From 91007f70c3af2284527130347c259150d2d1b468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mirko=20K=C3=A4mpf?= Date: Thu, 3 Dec 2026 22:55:09 +0100 Subject: [PATCH] test(smoke): distribution smoke plan COMP-kafgraph-01..14 as a suite (KG-01) test/smoke/PLAN.md is an unchanged copy of the plan at distribution tag pre-consolidation-2026-11-30 (sao/tests/smoke/components/kafgraph/PLAN.md); the distribution removed it and components/kafgraph from main on 2026-11-30. test/smoke is its own module: one test per case, HTTP via net/http, Bolt via neo4j-go-driver/v5 as the plan prescribes. Without a target it builds and starts KafGraph locally. Cases not passing yet are skipped with the roadmap entries that make them pass; a test fails if such an entry is missing, done or deferred. KAFGRAPH_SMOKE_STRICT=1 runs all. make test-smoke runs it, and CI runs it on every push and pull request. Today 14 passes. The official driver cannot complete the Bolt handshake: KafGraph accepts only the exact version 0x00000404, the driver offers ranges. With a range-aware handshake 03 and 11 pass; 05 lacks summary counters and 06 gets maps instead of nodes. ROADMAP.md proposes KG-15 for this; KG-07, KG-09 and KG-13 depend on it. The goal names the correct location of the plan. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 + Makefile | 4 + SPEC/ROADMAP.md | 16 +- test/smoke/PLAN.md | 43 +++++ test/smoke/README.md | 50 +++++ test/smoke/go.mod | 12 ++ test/smoke/go.sum | 6 + test/smoke/harness_test.go | 350 ++++++++++++++++++++++++++++++++++ test/smoke/proc_linux_test.go | 27 +++ test/smoke/proc_other_test.go | 24 +++ test/smoke/smoke_test.go | 330 ++++++++++++++++++++++++++++++++ 11 files changed, 863 insertions(+), 5 deletions(-) create mode 100644 test/smoke/PLAN.md create mode 100644 test/smoke/README.md create mode 100644 test/smoke/go.mod create mode 100644 test/smoke/go.sum create mode 100644 test/smoke/harness_test.go create mode 100644 test/smoke/proc_linux_test.go create mode 100644 test/smoke/proc_other_test.go create mode 100644 test/smoke/smoke_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f777a0..41ce6ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,9 @@ jobs: - uses: actions/setup-go@v7 with: go-version: "1.26.11" + cache-dependency-path: | + go.sum + test/smoke/go.sum - name: Check formatting run: make fmt-check @@ -37,6 +40,9 @@ jobs: - name: Check coverage run: make cover-check + - name: Run smoke contract (distribution plan COMP-kafgraph-01..14) + run: make test-smoke + - name: Check license headers run: bash hack/license-header.sh diff --git a/Makefile b/Makefile index f7c940f..876ce1f 100644 --- a/Makefile +++ b/Makefile @@ -90,6 +90,10 @@ test-unit: ## Run unit tests only (exclude e2e and integration) test-e2e: ## Run E2E tests (in-process, uses temp BadgerDB) CGO_ENABLED=1 $(GO) test $(GOFLAGS) -tags=e2e -v ./test/e2e/... +.PHONY: test-smoke +test-smoke: ## Run the distribution smoke plan (test/smoke, COMP-kafgraph-01..14) + cd test/smoke && $(GO) vet ./... && $(GO) test -count=1 -v ./... + .PHONY: test-integration test-integration: ## Run integration tests (requires docker-compose) CGO_ENABLED=1 $(GO) test $(GOFLAGS) -tags=integration -v -timeout 300s ./test/integration/... diff --git a/SPEC/ROADMAP.md b/SPEC/ROADMAP.md index d11e590..5cf482c 100644 --- a/SPEC/ROADMAP.md +++ b/SPEC/ROADMAP.md @@ -15,11 +15,16 @@ The phase history up to Phase 8 is in [PLAN.md](PLAN.md). ## Release v1.1.0: ready for the distribution Goal: KafGraph passes the distribution's component smoke plan for KafGraph -(`tests/smoke/components/kafgraph/PLAN.md` in the distribution repository, -cases COMP-kafgraph-01 to -14) and meets the distribution's release-gate +(cases COMP-kafgraph-01 to -14) and meets the distribution's release-gate contract: one CI workflow on `main` that covers every artefact (Go, Helm chart, compose files, multi-arch image). +The smoke plan is `sao/tests/smoke/components/kafgraph/PLAN.md` at tag +`pre-consolidation-2026-11-30` of the distribution repository. On 2026-11-30 +the distribution removed `sao/` and `components/kafgraph` from `main` (v1.0.1 +keep list). The plan is copied unchanged to +[test/smoke/PLAN.md](../test/smoke/PLAN.md); `make test-smoke` runs it. + | ID | Item | Status | Depends on | Done when | |----|------|--------|------------|-----------| | KG-00 | Roadmap and factory config (`SPEC/ROADMAP.md`, `.swfactory.yaml`) | done (#46) | – | merged to `main` | @@ -29,14 +34,15 @@ chart, compose files, multi-arch image). | KG-04 | `docker.yml` publishes only after green CI for the tagged commit, as a multi-arch image | open | KG-03 | a tag on a red commit publishes nothing; a published tag is a manifest list with amd64 and arm64 | | KG-05 | Branch protection on `main`: pull request and green CI required (repository admin) | open | KG-03 | protection active | | KG-06 | `GET /health` and `GET /ready`; readiness reports ingest status and lag (COMP-kafgraph-01, -02) | open | KG-01 | cases 01 and 02 pass | -| KG-07 | `CALL dbms.components()` returns the component KafGraph with its semver (COMP-kafgraph-04) | open | KG-01 | case 04 passes | +| KG-07 | `CALL dbms.components()` returns the component KafGraph with its semver (COMP-kafgraph-04) | open | KG-01, KG-15 | case 04 passes | | KG-08 | Graph metrics on `/metrics`, including `kafgraph_nodes_total` (COMP-kafgraph-13) | open | KG-01 | case 13 passes | -| KG-09 | Erasure endpoint `DELETE /api/v1/entities/{id}`: 204, a follow-up query returns 0 rows (COMP-kafgraph-12) | open | KG-01 | case 12 passes | +| KG-09 | Erasure endpoint `DELETE /api/v1/entities/{id}`: 204, a follow-up query returns 0 rows (COMP-kafgraph-12) | open | KG-01, KG-15 | case 12 passes | | KG-10 | Reflection API v1: `GET /api/v1/reflections`, `POST /api/v1/reflections/run` (202 with `job_id`), `GET /api/v1/reflections/jobs/{id}` (COMP-kafgraph-08 to -10) | open | KG-01 | cases 08 to 10 pass | | KG-11 | Ingest of topic `ops.agent.decisions` into `Decision` nodes with `trace_id` (COMP-kafgraph-07) | open | KG-01 | case 07 passes | | KG-12 | TLS for HTTP and Bolt, configurable, off by default; Helm values for it | open | KG-03 | E2E test over TLS passes; `helm lint` green with TLS values | -| KG-13 | `CHANGELOG.md`, docs in sync, tag `v1.1.0` and GitHub Release. A human sets the tag: it publishes to ghcr.io | open | KG-01, KG-04, KG-05, KG-06, KG-07, KG-08, KG-09, KG-10, KG-11, KG-12 | release exists; all 14 smoke cases pass without skips | +| KG-13 | `CHANGELOG.md`, docs in sync, tag `v1.1.0` and GitHub Release. A human sets the tag: it publishes to ghcr.io | open | KG-01, KG-04, KG-05, KG-06, KG-07, KG-08, KG-09, KG-10, KG-11, KG-12, KG-15 | release exists; all 14 smoke cases pass without skips | | KG-14 | Handover to the distribution (work happens in the distribution repo): subtree-sync to `v1.1.0`, PROVENANCE, DEVIATIONS, CI workflow name in `components.yaml`, distribution smoke test implements the plan, consumers checked | open | KG-13 | distribution release candidate with KafGraph `v1.1.0`, smoke passed | +| KG-15 | Bolt works with the official Neo4j driver (`neo4j-go-driver/v5`): the handshake accepts a version range that contains 4.4, the PULL summary carries `stats` counters, nodes are returned as Bolt node structures (COMP-kafgraph-03, -05, -06, -11) | open | KG-01 | cases 03, 05, 06 and 11 pass | ## Later diff --git a/test/smoke/PLAN.md b/test/smoke/PLAN.md new file mode 100644 index 0000000..b624f91 --- /dev/null +++ b/test/smoke/PLAN.md @@ -0,0 +1,43 @@ +# Component Smoke Test Plan — KafGraph + +**Image:** `ghcr.io/scalytics/kafgraph:latest` +**Swagger / OpenAPI:** `http://localhost:7474/openapi.json` (REST facade). Native Bolt v4 on `:7687` — tested via `github.com/neo4j/neo4j-go-driver/v5`. Browser UI at `http://localhost:7474/`. + +## Foundational tests (run against bp-001 Ops Foundation) + +| ID | Test | Method | Endpoint / Action | Assertion | +|----|------|--------|-------------------|-----------| +| COMP-kafgraph-01 | HTTP liveness | GET | `http://localhost:7474/health` | 200, `{"status":"ok"}` | +| COMP-kafgraph-02 | HTTP readiness | GET | `http://localhost:7474/ready` | 200, reports Kafka consumer lag | +| COMP-kafgraph-03 | Bolt handshake | Bolt | driver connect `bolt://localhost:7687` | session established within 5s | +| COMP-kafgraph-04 | version | Bolt | `CALL dbms.components()` | response contains `KafGraph` component, semver | +| COMP-kafgraph-05 | write decision node | Bolt | `CREATE (:Decision {trace_id:'smoke-', immutable:true})` | 1 node created | +| COMP-kafgraph-06 | read decision node | Bolt | `MATCH (d:Decision {trace_id:'smoke-'}) RETURN d` | 1 row, `immutable=true` | +| COMP-kafgraph-07 | audit trail append | Kafka | produce to `ops.agent.decisions`, then query KafGraph after 10s | node with matching `trace_id` appears | +| COMP-kafgraph-08 | reflection endpoint | GET | `http://localhost:7474/api/v1/reflections` | 200, array with cycle types daily/weekly/monthly | +| COMP-kafgraph-09 | trigger reflection | POST | `http://localhost:7474/api/v1/reflections/run` body `{"cycle":"daily"}` | 202, returns `job_id` | +| COMP-kafgraph-10 | reflection result | GET | `http://localhost:7474/api/v1/reflections/jobs/` | 200, terminal `status` within 60s | +| COMP-kafgraph-11 | schema lineage query | Bolt | `MATCH (s:Schema)-[:EVOLVED_FROM]->(p:Schema) RETURN count(*)` | >= 0, query executes without error | +| COMP-kafgraph-12 | GDPR erasure | DELETE | `http://localhost:7474/api/v1/entities/` | 204, follow-up query returns 0 rows | +| COMP-kafgraph-13 | prometheus metrics | GET | `http://localhost:7474/metrics` | 200, contains `kafgraph_nodes_total` | +| COMP-kafgraph-14 | browser UI | GET | `http://localhost:7474/` | 200, HTML contains knowledge-graph shell | + +## Claims covered + +| Claim | Source datasheet | Proven by test IDs | +|-------|-----------------|--------------------| +| "Knowledge graph + reflection + audit trail" | bp-001 | COMP-kafgraph-05, COMP-kafgraph-07, COMP-kafgraph-08 | +| "KafGraph ready for audit" | bp-001 | COMP-kafgraph-07 | +| "Full Audit Trail — Every transformation, every agent decision, every schema version" | bp-002 | COMP-kafgraph-07, COMP-kafgraph-11 | +| "Immutable audit trail, schema lineage, GDPR-ready erasure" | bp-002 | COMP-kafgraph-05, COMP-kafgraph-11, COMP-kafgraph-12 | +| "Knowledge graph, reflection engine, audit queries" | bp-003 | COMP-kafgraph-03, COMP-kafgraph-08, COMP-kafgraph-09 | +| "Daily/weekly/monthly reflection cycles" | bp-003 | COMP-kafgraph-08, COMP-kafgraph-09, COMP-kafgraph-10 | +| "Immutable audit trail. Replay any decision. Prove source provenance." | bp-003 | COMP-kafgraph-06, COMP-kafgraph-07 | + +## Implementation notes + +- Test framework: Go + testify + `neo4j-go-driver/v5` (Bolt) + `net/http` (REST) +- Requires: bp-001 deployed; KafGraph pointed at pre-provisioned `ops.agent.decisions` +- Immutability assertion relies on KafGraph server-side constraint rejecting UPDATE on `Decision.immutable=true`; test attempts update and expects server error +- Cleanup: `MATCH (n {trace_id:'smoke-'}) DETACH DELETE n` for nodes created with the smoke trace prefix +- Reflection run uses `cycle=daily` with a small sample window configured via Helm test-mode values diff --git a/test/smoke/README.md b/test/smoke/README.md new file mode 100644 index 0000000..9819ba7 --- /dev/null +++ b/test/smoke/README.md @@ -0,0 +1,50 @@ +# Smoke contract (distribution plan COMP-kafgraph-01 to -14) + +This suite runs the component smoke plan of the distribution against a running +KafGraph: HTTP with `net/http`, Bolt with the official Neo4j Go driver +(`neo4j-go-driver/v5`), as the plan prescribes. Roadmap entry: KG-01 in +[SPEC/ROADMAP.md](../../SPEC/ROADMAP.md). + +## Source of the plan + +[PLAN.md](PLAN.md) is an unchanged copy of +`sao/tests/smoke/components/kafgraph/PLAN.md` at tag +`pre-consolidation-2026-11-30` (commit `1f6fe6e67`) of +`scalytics/LASCARIS-distribution`, git blob +`b624f914ae2ad1372e18f3079a912b958417e0ba`. Check it with +`git hash-object test/smoke/PLAN.md`. The distribution removed `sao/` from +`main` on 2026-11-30 (`a46cca945`). The plan changes only together with the +distribution. + +## Run + +```bash +make test-smoke +``` + +Without a target, the suite builds `./cmd/kafgraph` from this repository with +the version stamp of `make build` (`git describe --tags`) and starts it on free +local ports with a temporary data directory. If a run fails, the end of the +server log is printed. + +| Variable | Meaning | +|---|---| +| `KAFGRAPH_SMOKE_HTTP_URL`, `KAFGRAPH_SMOKE_BOLT_URL` | test a running KafGraph instead, e.g. `http://localhost:7474` and `bolt://localhost:7687`; set both or neither | +| `KAFGRAPH_SMOKE_KAFKA_BROKERS` | brokers for case 07 | +| `KAFGRAPH_SMOKE_STRICT=1` | run every case, including pending ones (KG-13: all 14 pass without skips) | +| `KAFGRAPH_SMOKE_KEEP=1` | keep the data directory and log of the local instance | + +## Pending cases + +A case KafGraph does not pass yet is skipped with the roadmap entries that +make it pass (`pending` in [harness_test.go](harness_test.go)). Each entry +removes itself there once it is done; a case runs when its list is empty. +Cases that query over Bolt also wait on KG-15. `TestPendingCasesNameOpenRoadmapEntries` +fails if a pending case names an entry that is missing, done or deferred. + +`pending` reflects this checkout, not the version of an external target. To +measure a deployed KafGraph against the whole plan, set +`KAFGRAPH_SMOKE_STRICT=1`. Case 07 also needs a Kafka broker. + +The suite is its own Go module, so the Bolt driver is not a dependency of the +KafGraph binary. diff --git a/test/smoke/go.mod b/test/smoke/go.mod new file mode 100644 index 0000000..9fd61f9 --- /dev/null +++ b/test/smoke/go.mod @@ -0,0 +1,12 @@ +module github.com/scalytics/kafgraph/test/smoke + +go 1.26.0 + +toolchain go1.26.11 + +require ( + github.com/neo4j/neo4j-go-driver/v5 v5.28.6 + github.com/stretchr/testify v1.12.1 +) + +require go.yaml.in/yaml/v3 v3.0.5 // indirect diff --git a/test/smoke/go.sum b/test/smoke/go.sum new file mode 100644 index 0000000..014e129 --- /dev/null +++ b/test/smoke/go.sum @@ -0,0 +1,6 @@ +github.com/neo4j/neo4j-go-driver/v5 v5.28.6 h1:U6lQTe6EBzyMy7tAjpMZj/5vNK9+MPhCtBlfmGGffXo= +github.com/neo4j/neo4j-go-driver/v5 v5.28.6/go.mod h1:Vff8OwT7QpLm7L2yYr85XNWe9Rbqlbeb9asNXJTHO4k= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= diff --git a/test/smoke/harness_test.go b/test/smoke/harness_test.go new file mode 100644 index 0000000..36974ed --- /dev/null +++ b/test/smoke/harness_test.go @@ -0,0 +1,350 @@ +// Copyright 2026 Scalytics, Inc. +// Copyright 2026 Mirko Kämpf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package smoke runs the distribution's component smoke plan for KafGraph +// (PLAN.md, cases COMP-kafgraph-01 to -14) against a running KafGraph, over +// HTTP and over Bolt with the official Neo4j Go driver. +// +// Target: KAFGRAPH_SMOKE_HTTP_URL and KAFGRAPH_SMOKE_BOLT_URL. Without them, +// TestMain builds ./cmd/kafgraph of this repository like `make build` and +// starts it on free local ports with a temporary data directory. +// +// A case KafGraph does not pass yet is skipped with the roadmap entries that +// make it pass (see pending). KAFGRAPH_SMOKE_STRICT=1 runs every case. +package smoke + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/neo4j/neo4j-go-driver/v5/neo4j" + "github.com/stretchr/testify/require" +) + +// pending maps a case number of PLAN.md to the entries in SPEC/ROADMAP.md +// that make the case pass. An entry removes itself here once it is done; the +// case runs when its list is empty. Cases that query over Bolt also wait on +// KG-15, because the official driver cannot connect before it. +var pending = map[int][]string{ + 1: {"KG-06"}, + 2: {"KG-06"}, + 3: {"KG-15"}, + 4: {"KG-07", "KG-15"}, + 5: {"KG-15"}, + 6: {"KG-15"}, + 7: {"KG-11"}, + 8: {"KG-10"}, + 9: {"KG-10"}, + 10: {"KG-10"}, + 11: {"KG-15"}, + 12: {"KG-09", "KG-15"}, + 13: {"KG-08"}, +} + +type target struct { + httpURL string + boltURL string + kafka string + strict bool +} + +var ( + tgt target + runID = "smoke-" + strconv.FormatInt(time.Now().UnixNano(), 10) + httpClient = &http.Client{Timeout: 10 * time.Second} + // created is set before a case writes nodes with trace_id runID. + created bool +) + +func TestMain(m *testing.M) { + os.Exit(run(m)) +} + +func run(m *testing.M) int { + tgt = target{ + httpURL: strings.TrimRight(os.Getenv("KAFGRAPH_SMOKE_HTTP_URL"), "/"), + boltURL: os.Getenv("KAFGRAPH_SMOKE_BOLT_URL"), + kafka: os.Getenv("KAFGRAPH_SMOKE_KAFKA_BROKERS"), + strict: os.Getenv("KAFGRAPH_SMOKE_STRICT") == "1", + } + var local *instance + switch { + case tgt.httpURL != "" && tgt.boltURL != "": + case tgt.httpURL == "" && tgt.boltURL == "": + var err error + local, err = startLocal() + if err != nil { + fmt.Fprintln(os.Stderr, "smoke:", err) + return 1 + } + default: + fmt.Fprintln(os.Stderr, "smoke: set both KAFGRAPH_SMOKE_HTTP_URL and KAFGRAPH_SMOKE_BOLT_URL, or neither") + return 2 + } + fmt.Fprintf(os.Stderr, "smoke: target http=%s bolt=%s run=%s strict=%t\n", tgt.httpURL, tgt.boltURL, runID, tgt.strict) + code := m.Run() + cleanup() + if local != nil { + local.stop(code != 0) + } + return code +} + +// instance is a KafGraph started by this suite. +type instance struct { + cmd *exec.Cmd + exited chan error + tmp string + logPath string + logFile *os.File +} + +// startLocal builds KafGraph from this repository with the version stamp of +// `make build` and starts it on free local ports. +func startLocal() (*instance, error) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + return nil, err + } + tmp, err := os.MkdirTemp("", "kafgraph-smoke-") + if err != nil { + return nil, err + } + fail := func(err error) (*instance, error) { + _ = os.RemoveAll(tmp) + return nil, err + } + + version := "dev" + if out, err := exec.Command("git", "-C", root, "describe", "--tags", "--always", "--dirty").Output(); err == nil { + version = strings.TrimSpace(string(out)) + } + bin := filepath.Join(tmp, "kafgraph") + build := exec.Command("go", "build", + "-ldflags", "-X github.com/scalytics/kafgraph/internal/config.Version="+version, + "-o", bin, "./cmd/kafgraph") + build.Dir = root + build.Stdout, build.Stderr = os.Stderr, os.Stderr + if err := build.Run(); err != nil { + return fail(fmt.Errorf("build kafgraph: %w", err)) + } + + ports, err := freePorts(2) + if err != nil { + return fail(err) + } + httpPort, boltPort := ports[0], ports[1] + in := &instance{tmp: tmp, logPath: filepath.Join(tmp, "kafgraph.log"), exited: make(chan error, 1)} + if in.logFile, err = os.Create(in.logPath); err != nil { + return fail(err) + } + in.cmd = exec.Command(bin) + in.cmd.Dir = root // compliance rules are read from ./rules + in.cmd.Env = append(os.Environ(), + "KAFGRAPH_HOST=127.0.0.1", + "KAFGRAPH_PORT="+strconv.Itoa(httpPort), + "KAFGRAPH_BOLT_PORT="+strconv.Itoa(boltPort), + "KAFGRAPH_DATA_DIR="+filepath.Join(tmp, "data"), + ) + in.cmd.Stdout, in.cmd.Stderr = in.logFile, in.logFile + dieWithParent(in.cmd) + if err := in.cmd.Start(); err != nil { + _ = in.logFile.Close() + return fail(fmt.Errorf("start kafgraph: %w", err)) + } + go func() { in.exited <- in.cmd.Wait() }() + + tgt.httpURL = fmt.Sprintf("http://127.0.0.1:%d", httpPort) + tgt.boltURL = fmt.Sprintf("bolt://127.0.0.1:%d", boltPort) + deadline := time.Now().Add(60 * time.Second) + for _, port := range ports { + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + for { + select { + case err := <-in.exited: + in.exited <- err + in.stop(true) + return nil, fmt.Errorf("kafgraph exited during startup: %v", err) + default: + } + conn, err := net.DialTimeout("tcp", addr, time.Second) + if err == nil { + _ = conn.Close() + break + } + if time.Now().After(deadline) { + in.stop(true) + return nil, fmt.Errorf("kafgraph did not listen on %s within 60s", addr) + } + time.Sleep(200 * time.Millisecond) + } + } + return in, nil +} + +// stop ends KafGraph and removes its data. With dump, it first prints the +// end of the server log, so a failed run in CI keeps its diagnostics. +func (in *instance) stop(dump bool) { + _ = in.cmd.Process.Signal(os.Interrupt) + select { + case <-in.exited: + case <-time.After(10 * time.Second): + _ = in.cmd.Process.Kill() + <-in.exited + } + _ = in.logFile.Close() + if dump { + if b, err := os.ReadFile(in.logPath); err == nil { + const tail = 8 << 10 + if len(b) > tail { + b = b[len(b)-tail:] + } + fmt.Fprintf(os.Stderr, "smoke: end of kafgraph log:\n%s\n", b) + } + } + if os.Getenv("KAFGRAPH_SMOKE_KEEP") == "" { + _ = os.RemoveAll(in.tmp) + } else { + fmt.Fprintln(os.Stderr, "smoke: kept", in.tmp) + } +} + +// freePorts returns n distinct free local ports. All listeners stay open +// until every port is chosen, so no port is handed out twice. +func freePorts(n int) ([]int, error) { + ports := make([]int, 0, n) + for i := 0; i < n; i++ { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return nil, err + } + defer func() { _ = l.Close() }() + ports = append(ports, l.Addr().(*net.TCPAddr).Port) + } + return ports, nil +} + +// smokeCase starts case n of PLAN.md. It skips a pending case with its +// roadmap entries, unless KAFGRAPH_SMOKE_STRICT=1. +func smokeCase(t *testing.T, n int) { + t.Helper() + if ids := pending[n]; len(ids) > 0 && !tgt.strict { + t.Skipf("COMP-kafgraph-%02d pending: %s (SPEC/ROADMAP.md)", n, strings.Join(ids, ", ")) + } +} + +// ─── HTTP ──────────────────────────────────────────────────────────────────── + +type httpResult struct { + status int + contentType string + body []byte +} + +func call(t *testing.T, method, path string, body any) httpResult { + t.Helper() + var rd io.Reader + if body != nil { + b, err := json.Marshal(body) + require.NoError(t, err) + rd = bytes.NewReader(b) + } + req, err := http.NewRequest(method, tgt.httpURL+path, rd) + require.NoError(t, err) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := httpClient.Do(req) + require.NoError(t, err, "%s %s", method, path) + defer func() { _ = resp.Body.Close() }() + b, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return httpResult{status: resp.StatusCode, contentType: resp.Header.Get("Content-Type"), body: b} +} + +// ─── Bolt ──────────────────────────────────────────────────────────────────── + +type cypherResult struct { + records []*neo4j.Record + summary neo4j.ResultSummary +} + +func newDriver(t *testing.T) neo4j.DriverWithContext { + t.Helper() + d, err := neo4j.NewDriverWithContext(tgt.boltURL, neo4j.NoAuth()) + require.NoError(t, err) + t.Cleanup(func() { _ = d.Close(context.Background()) }) + return d +} + +// cypher runs one auto-commit query (RUN + PULL) and returns all records and +// the summary. +func cypher(ctx context.Context, d neo4j.DriverWithContext, query string) (cypherResult, error) { + s := d.NewSession(ctx, neo4j.SessionConfig{}) + defer func() { _ = s.Close(ctx) }() + res, err := s.Run(ctx, query, nil) + if err != nil { + return cypherResult{}, err + } + recs, err := res.Collect(ctx) + if err != nil { + return cypherResult{}, err + } + sum, err := res.Consume(ctx) + if err != nil { + return cypherResult{}, err + } + return cypherResult{records: recs, summary: sum}, nil +} + +func mustCypher(t *testing.T, query string) cypherResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + r, err := cypher(ctx, newDriver(t), query) + require.NoError(t, err, "cypher: %s", query) + return r +} + +// cleanup removes what the run created, with the query of PLAN.md. +func cleanup() { + if !created { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + d, err := neo4j.NewDriverWithContext(tgt.boltURL, neo4j.NoAuth()) + if err != nil { + fmt.Fprintln(os.Stderr, "smoke: cleanup:", err) + return + } + defer func() { _ = d.Close(ctx) }() + q := fmt.Sprintf("MATCH (n {trace_id:'%s'}) DETACH DELETE n", runID) + if _, err := cypher(ctx, d, q); err != nil { + fmt.Fprintf(os.Stderr, "smoke: cleanup %q: %v\n", q, err) + } +} diff --git a/test/smoke/proc_linux_test.go b/test/smoke/proc_linux_test.go new file mode 100644 index 0000000..f116bb8 --- /dev/null +++ b/test/smoke/proc_linux_test.go @@ -0,0 +1,27 @@ +// Copyright 2026 Scalytics, Inc. +// Copyright 2026 Mirko Kämpf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package smoke + +import ( + "os/exec" + "syscall" +) + +// dieWithParent makes the kernel stop KafGraph when the test binary dies +// without running its teardown (panic, -timeout). +func dieWithParent(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGTERM} +} diff --git a/test/smoke/proc_other_test.go b/test/smoke/proc_other_test.go new file mode 100644 index 0000000..cfe398a --- /dev/null +++ b/test/smoke/proc_other_test.go @@ -0,0 +1,24 @@ +// Copyright 2026 Scalytics, Inc. +// Copyright 2026 Mirko Kämpf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !linux + +package smoke + +import "os/exec" + +// dieWithParent is a no-op outside Linux: there the teardown in +// TestMain is the only stop. +func dieWithParent(*exec.Cmd) {} diff --git a/test/smoke/smoke_test.go b/test/smoke/smoke_test.go new file mode 100644 index 0000000..17c1128 --- /dev/null +++ b/test/smoke/smoke_test.go @@ -0,0 +1,330 @@ +// Copyright 2026 Scalytics, Inc. +// Copyright 2026 Mirko Kämpf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package smoke + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "net/http" + "os" + "regexp" + "strings" + "testing" + "time" + + "github.com/neo4j/neo4j-go-driver/v5/neo4j" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// One test per case of PLAN.md; the comment quotes its assertion. + +// COMP-kafgraph-01: GET /health → 200, {"status":"ok"}. +func TestCOMP_kafgraph_01(t *testing.T) { + smokeCase(t, 1) + r := call(t, http.MethodGet, "/health", nil) + require.Equal(t, http.StatusOK, r.status, string(r.body)) + var body map[string]any + require.NoError(t, json.Unmarshal(r.body, &body), string(r.body)) + assert.Equal(t, "ok", body["status"]) +} + +// COMP-kafgraph-02: GET /ready → 200, reports Kafka consumer lag. +func TestCOMP_kafgraph_02(t *testing.T) { + smokeCase(t, 2) + r := call(t, http.MethodGet, "/ready", nil) + require.Equal(t, http.StatusOK, r.status, string(r.body)) + var body any + require.NoError(t, json.Unmarshal(r.body, &body), string(r.body)) + assert.True(t, hasLag(body), "no consumer lag in %s", r.body) +} + +// COMP-kafgraph-03: driver connect bolt://… → session established within 5s. +func TestCOMP_kafgraph_03(t *testing.T) { + smokeCase(t, 3) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, newDriver(t).VerifyConnectivity(ctx)) +} + +// COMP-kafgraph-04: CALL dbms.components() → contains component KafGraph, semver. +func TestCOMP_kafgraph_04(t *testing.T) { + smokeCase(t, 4) + r := mustCypher(t, "CALL dbms.components()") + semver := regexp.MustCompile(`^v?\d+\.\d+\.\d+`) + found := false + for _, rec := range r.records { + vals := flatten(rec.Values) + if contains(vals, func(s string) bool { return s == "KafGraph" }) && + contains(vals, semver.MatchString) { + found = true + } + } + assert.True(t, found, "no record with KafGraph and a semver: %v", recordValues(r.records)) +} + +// decisionCreated is set by case 05; case 06 reads the node 05 wrote. +var decisionCreated bool + +func createDecision(t *testing.T) cypherResult { + t.Helper() + created, decisionCreated = true, true // before the query: a write may land even if the reply fails + return mustCypher(t, fmt.Sprintf("CREATE (:Decision {trace_id:'%s', immutable:true})", runID)) +} + +// COMP-kafgraph-05: CREATE (:Decision {trace_id:'smoke-', immutable:true}) → 1 node created. +func TestCOMP_kafgraph_05(t *testing.T) { + smokeCase(t, 5) + r := createDecision(t) + assert.Equal(t, 1, r.summary.Counters().NodesCreated(), "nodes created") +} + +// COMP-kafgraph-06: MATCH (d:Decision {trace_id:'smoke-'}) RETURN d → 1 row, immutable=true. +func TestCOMP_kafgraph_06(t *testing.T) { + smokeCase(t, 6) + if !decisionCreated { + createDecision(t) + } + r := mustCypher(t, fmt.Sprintf("MATCH (d:Decision {trace_id:'%s'}) RETURN d", runID)) + require.Len(t, r.records, 1) + v, ok := r.records[0].Get("d") + require.True(t, ok, "column d") + node, ok := v.(neo4j.Node) + require.True(t, ok, "d is %T, not a node", v) + assert.Equal(t, true, node.Props["immutable"]) +} + +// COMP-kafgraph-07: produce to ops.agent.decisions, query after 10s → node with matching trace_id. +func TestCOMP_kafgraph_07(t *testing.T) { + smokeCase(t, 7) + if tgt.kafka == "" { + t.Fatal("needs a Kafka broker in KAFGRAPH_SMOKE_KAFKA_BROKERS") + } + // KG-11 defines the record format of ops.agent.decisions and adds the + // producer here. + t.Fatal("not implemented: KG-11") +} + +// COMP-kafgraph-08: GET /api/v1/reflections → 200, array with cycle types daily/weekly/monthly. +func TestCOMP_kafgraph_08(t *testing.T) { + smokeCase(t, 8) + r := call(t, http.MethodGet, "/api/v1/reflections", nil) + require.Equal(t, http.StatusOK, r.status, string(r.body)) + var arr []any + require.NoError(t, json.Unmarshal(r.body, &arr), "not a JSON array: %s", r.body) + vals := flatten(arr) + for _, cycle := range []string{"daily", "weekly", "monthly"} { + assert.True(t, contains(vals, func(s string) bool { return s == cycle }), "no cycle %q in %s", cycle, r.body) + } +} + +// jobID is set by case 09; case 10 reads that job. +var jobID string + +func runReflection(t *testing.T) { + t.Helper() + r := call(t, http.MethodPost, "/api/v1/reflections/run", map[string]string{"cycle": "daily"}) + require.Equal(t, http.StatusAccepted, r.status, string(r.body)) + var body map[string]any + require.NoError(t, json.Unmarshal(r.body, &body), string(r.body)) + id, _ := body["job_id"].(string) + require.NotEmpty(t, id, "job_id in %s", r.body) + jobID = id +} + +// COMP-kafgraph-09: POST /api/v1/reflections/run {"cycle":"daily"} → 202, returns job_id. +func TestCOMP_kafgraph_09(t *testing.T) { + smokeCase(t, 9) + runReflection(t) +} + +// COMP-kafgraph-10: GET /api/v1/reflections/jobs/ → 200, terminal status within 60s. +func TestCOMP_kafgraph_10(t *testing.T) { + smokeCase(t, 10) + if jobID == "" { + runReflection(t) + } + terminal := map[string]bool{ + "completed": true, "succeeded": true, "success": true, "done": true, + "failed": true, "error": true, "cancelled": true, "canceled": true, + } + deadline := time.Now().Add(60 * time.Second) + for { + r := call(t, http.MethodGet, "/api/v1/reflections/jobs/"+jobID, nil) + require.Equal(t, http.StatusOK, r.status, string(r.body)) + var body map[string]any + require.NoError(t, json.Unmarshal(r.body, &body), string(r.body)) + status, _ := body["status"].(string) + if terminal[strings.ToLower(status)] { + return + } + if time.Now().After(deadline) { + t.Fatalf("job %s not terminal after 60s: %s", jobID, r.body) + } + time.Sleep(time.Second) + } +} + +// COMP-kafgraph-11: MATCH (s:Schema)-[:EVOLVED_FROM]->(p:Schema) RETURN count(*) → >= 0, no error. +func TestCOMP_kafgraph_11(t *testing.T) { + smokeCase(t, 11) + r := mustCypher(t, "MATCH (s:Schema)-[:EVOLVED_FROM]->(p:Schema) RETURN count(*)") + require.Len(t, r.records, 1) + require.Len(t, r.records[0].Values, 1) + n, ok := r.records[0].Values[0].(int64) + require.True(t, ok, "count(*) is %T", r.records[0].Values[0]) + assert.GreaterOrEqual(t, n, int64(0)) +} + +// COMP-kafgraph-12: DELETE /api/v1/entities/ → 204, follow-up query returns 0 rows. +func TestCOMP_kafgraph_12(t *testing.T) { + smokeCase(t, 12) + // Setup over KafGraph's node API: one node carrying the run's trace_id. + created = true + c := call(t, http.MethodPost, "/api/v1/nodes", map[string]any{ + "label": "SmokeErasure", + "properties": map[string]any{"trace_id": runID}, + }) + require.Equal(t, http.StatusCreated, c.status, string(c.body)) + var node map[string]any + require.NoError(t, json.Unmarshal(c.body, &node), string(c.body)) + id, _ := node["id"].(string) + require.NotEmpty(t, id, "id in %s", c.body) + + r := call(t, http.MethodDelete, "/api/v1/entities/"+id, nil) + require.Equal(t, http.StatusNoContent, r.status, string(r.body)) + q := mustCypher(t, fmt.Sprintf("MATCH (n:SmokeErasure {trace_id:'%s'}) RETURN n", runID)) + assert.Empty(t, q.records) +} + +// COMP-kafgraph-13: GET /metrics → 200, contains kafgraph_nodes_total. +func TestCOMP_kafgraph_13(t *testing.T) { + smokeCase(t, 13) + r := call(t, http.MethodGet, "/metrics", nil) + require.Equal(t, http.StatusOK, r.status) + assert.True(t, strings.Contains(string(r.body), "kafgraph_nodes_total"), + "no kafgraph_nodes_total in /metrics (%d bytes)", len(r.body)) +} + +// COMP-kafgraph-14: GET / → 200, HTML contains knowledge-graph shell. +// The shell is the embedded UI, recognised by its title. +func TestCOMP_kafgraph_14(t *testing.T) { + smokeCase(t, 14) + r := call(t, http.MethodGet, "/", nil) + require.Equal(t, http.StatusOK, r.status) + assert.Contains(t, r.contentType, "text/html") + assert.Contains(t, string(r.body), "KafGraph") +} + +// Every pending case names entries of SPEC/ROADMAP.md that are neither done +// nor deferred: a done entry still listed for a case is a stale skip. Outside +// this repository (a copy of the suite) there is no roadmap to check. +func TestPendingCasesNameOpenRoadmapEntries(t *testing.T) { + raw, err := os.ReadFile("../../SPEC/ROADMAP.md") + if errors.Is(err, fs.ErrNotExist) { + t.Skip("no ../../SPEC/ROADMAP.md: suite runs outside the KafGraph repository") + } + require.NoError(t, err) + status := map[string]string{} + row := regexp.MustCompile(`^\|\s*(KG-\d+)\s*\|[^|]*\|\s*([^|]*?)\s*\|`) + for _, line := range strings.Split(string(raw), "\n") { + if m := row.FindStringSubmatch(line); m != nil { + status[m[1]] = m[2] + } + } + for n, ids := range pending { + assert.True(t, n >= 1 && n <= 14, "case %d is not in PLAN.md", n) + for _, id := range ids { + s, ok := status[id] + if !assert.True(t, ok, "case %02d: %s is not in SPEC/ROADMAP.md", n, id) { + continue + } + assert.False(t, strings.HasPrefix(s, "done") || strings.HasPrefix(s, "deferred"), + "case %02d is pending on %s, which is %q", n, id, s) + } + } +} + +// ─── helpers ───────────────────────────────────────────────────────────────── + +// flatten returns the strings in v, descending into lists and maps. +func flatten(v any) []string { + var out []string + var walk func(any) + walk = func(x any) { + switch y := x.(type) { + case string: + out = append(out, y) + case []any: + for _, e := range y { + walk(e) + } + case map[string]any: + for _, e := range y { + walk(e) + } + } + } + walk(v) + return out +} + +func contains(vals []string, match func(string) bool) bool { + for _, s := range vals { + if match(s) { + return true + } + } + return false +} + +// hasLag reports whether a JSON value carries a consumer lag, at any depth: a +// key "lag" or ending in "_lag"/"Lag" whose value is a number or an object. +func hasLag(v any) bool { + switch y := v.(type) { + case map[string]any: + for k, e := range y { + isLag := strings.EqualFold(k, "lag") || strings.HasSuffix(strings.ToLower(k), "_lag") || strings.HasSuffix(k, "Lag") + switch e.(type) { + case float64, map[string]any: + if isLag { + return true + } + } + if hasLag(e) { + return true + } + } + case []any: + for _, e := range y { + if hasLag(e) { + return true + } + } + } + return false +} + +func recordValues(recs []*neo4j.Record) [][]any { + out := make([][]any, 0, len(recs)) + for _, r := range recs { + out = append(out, r.Values) + } + return out +}