Skip to main content
Test health matters more than test volume: skip/xfail markers, a chronically red multi-job CI, and correctness that is never encoded as a gate let the bugs that matter (write-side merge corruption is the classic one) slip through even a large suite. This suite optimizes for: few layers, a real database, no skipped tests, and the eval harness as the correctness gate for memory semantics.

The pyramid (4 layers + evals)

1. Unit — packages/schema, packages/core pure logic

Pure functions only: schema validation, supersession resolution, commitment FSM transitions, retrieval fusion scoring. No DB, no mocks of the DB — if a test wants to mock packages/db, it’s an integration test in disguise; move it down a layer.

2. Integration — the workhorse layer

  • Runs against real Postgres + pgvector — never a mock, never SQLite. Locally: the same docker-compose.yml Postgres as self-host (test database). CI: each selected integration (...) shard gets its own disposable pgvector/pgvector:pg18 service container, aggregated by test, with the heavy DB package split into db-structure, db-search, db-auth, and db-memory slices. This path requires no hosted-database credentials and works for fork PRs.
  • Two isolation strategies, used deliberately (packages/db/test/integration/helpers.ts):
    • Savepoint pattern — withTestTransaction() for tests that own their SQL: rolled back, fast, parallel-safe.
    • Truncate-based cleanup — resetDomainTables() for suites exercising the real withTenant() path: withTenant commits on its own pool, so cross-connection visibility makes savepoints inapplicable there. Honest trade: those suites serialize on cleanup. Because these global TRUNCATEs are not isolated across packages on a shared database (--fileParallelism=false only serializes within a package), the root test:integration script pins turbo --concurrency=1 for local/single-database runs. CI keeps package-internal serialization and gives each selected shard its own Postgres service container. DB sub-shards therefore cannot collide with one another.
  • RLS tests run as the runtime role, not the owner role (owner bypasses RLS — a green isolation test as superuser proves nothing). The test harness provisions roles via the same scripts/provision-roles.sql as production.
  • Real concurrency is constructed, never timed (packages/db/test/integration/concurrency.ts): a test transaction takes the conflicting lock and parks before commit (holdOpen), the production call starts on its own pooled runtime-role connection and provably blocks on that lock (waitForLockWait polls pg_locks, scoped to the test database and to the holder’s pid, with a bounded timeout), and only then is the holder released and committed state asserted. No sleep picks a winner. session-contention.int.test.ts pins the session-locking claims (one epoch bump per resurrection, attach vs close, the single-open count at commit, attach vs erasure lock order, heartbeat vs erasure) this way.
  • Mandatory suites that exist from the start (packages/db/test/integration/):
    • Tenant isolation: user A writes, user B queries — across every query path including edges, facts, commitments, proposals. Mirrors the eval slice but as fast deterministic tests.
    • withTenant discipline: concurrent pooled connections cannot leak app.user_id.
    • Append-only enforcement: UPDATE/DELETE on memory_events/audit_log fails at the grant level; no DELETE anywhere in the memory domain.
    • Migration round-trip: fresh DB → all migrations → structure parity (tables, policies+NULLIF, FSM trigger, HNSW index, SECURITY DEFINER resolvers).
    • HNSW parity: pgvector vs the eval gate’s exact cosine on the real golden-set embeddings — the bridge between the eval gate’s upper bound and what production serves. Two-regime (see Data model & RLS): natural plan asserted index-driven (selective tenants get btree+exact — correct), plus a forced-HNSW arm (enable_sort=off, hnsw.iterative_scan) with EXPLAIN-asserted index use; both ≥ 0.95 overlap.
The provenance chain slice (packages/core/test/integration/provenance-chain.int.test.ts) uses eval/fixtures/provenance-synthetic.json to mirror product writes across two tenants. It requires exact chain recall and precision (1.0), zero foreign ids, and truncation for a 28-version chain. Expected labels map to stored identities without reading producer links or provenance output. An explicit caller-predicate probe works independently of RLS. Mutation checks remove that predicate or a producer link and must fail. This slice runs in integration (core), including fixture-only changes, and blocks through test; it does not add a database dependency to eval-gate.

3. Contract — MCP and REST surfaces

  • Spin up the Express app in-process through the SDK v2 dual-era handler; drive both legacy and 2026-07-28 clients through the official MCP client SDK (not hand-rolled JSON-RPC) so version negotiation, transport, auth bridging, and structured-output semantics are actually exercised.
  • Every tool: happy path + auth-missing + cross-tenant + output-schema validation (the response must parse against the tool’s declared outputSchema — enforced as plain tests, not a bespoke CI job).
  • REST mirrors: generated OpenAPI is diffed in CI; a contract change shows up in the PR.

4. E2E — minimal by design

The managed dashboard lives in 3ngram-platform. Browser QA drives the changed surface and records its evidence in the PR. Neither repository currently has a Playwright workflow; do not treat a staging merge as proof of a browser pass.

Consequence-loop coverage (#322)

These synthetic scenarios run in the existing suites and CI shards. They need no paid model calls or separate end-to-end framework. Paths below are relative to each package’s test/ directory; integration files end in .int.test.ts. Integration shards are path-gated by .github/workflows/ci.yml. The closer’s deterministic tests prove ID containment and write guards. Whether a model falsely classifies a briefed commitment as completed remains model-quality work under #166/#224; these tests do not claim to prove that judgment correct.

LLM policy in tests

  • Automated layers 1–3 never call a real model. packages/llm ships a FakeGateway (deterministic embeddings via seeded hash → vector; canned completions per operation key; canned decide() answers per operation, with a fixed low default probability so a test that forgets one fails closed). Tests assert on our logic, not model behavior. Browser QA against a shared deployment uses that environment’s configured gateway; isolated QA can inject the fake.
  • Model behavior is the eval harness’s job — that’s the separation: tests prove the machine is wired right; evals prove the memory is good. A PR can’t compensate for a golden-set regression with passing unit tests, and vice versa.
  • Recorded-fixture mode (capture a real gateway response once, replay) is allowed for extraction-shaped logic, stored under __fixtures__/, refreshed deliberately — never auto-recorded in CI.

Test health policy

  1. No skipped tests on main. it.skip/todo fails the lint step. A test that can’t pass is either fixed in the PR or deleted with a linked issue — a pile of dormant markers is how a suite rots.
  2. No flake tolerance: a test that fails intermittently is quarantined by deletion + issue, not retry-until-green. CI has no retry-on-failure config.
  3. Coverage is observed, not gated. Vitest coverage reported on PRs for review judgment; no threshold ratchet (thresholds breed assertion-free tests). The mandatory-suite list above is the real floor.
  4. Speed budgets are enforced: unit <30s, integration <3min, contract <2min, total ci.yml <10min wall. A PR that blows the budget fixes it or splits the suite — slow CI is how the job sprawl started.
  5. Tests-with-the-change: every behavior PR carries its tests; there is no “test backfill” epic, ever.

Local developer loop

One command per layer, same package entry points CI uses. The local root integration command is serial on one database; CI invokes package scripts and DB file groups against separate disposable Postgres service containers for safe parallelism.