Files
pad/internal/store/items_preimage_test.go
T
xarmian 3c93472613 perf(store): run the store suite in parallel (TASK-2900 deliverable 3) (#1263)
The SQLite leg was CPU-bound and serial: 154.9s of CPU inside 185.6s of wall on
an eight-core box, which is 0.84 cores. Unlike the Postgres leg there was no
setup cost to reclaim — the unattributed gap between package wall-clock and the
sum of its tests measured MINUS 1.4s, so per-binary overhead was already nil —
and no fat test to find beyond one 48s outlier. The only lever left was the
seven idle cores.

t.Parallel() on 844 of 906 tests. Every test in this package builds its own
isolated store (a SQLite file copy, or since 6f8b6eb9 a Postgres clone), so it
shares no database with any other.

Medians on a quiet box, three SQLite repeats and two Postgres:

  SQLite wall     185.6s -> 111.0s   -40%
  Postgres wall   224.4s -> 121.2s   -46%   (495.8s -> 121.2s, -76%, since 6f8b6eb9)
  -race wall     2006.3s -> 1365.0s  -32%

THE COST, stated rather than folded into the win: SQLite CPU rose 154.9s ->
159.9s, +3.2%. That is contention overhead, it is real, and it is paid by
whoever else is on the box — this change moves WALL, it does not remove work.
A pre-registered prediction that CPU would stay within ~1% is falsified by that
number, though only just.

THAT FIGURE IS ITSELF A CORRECTION. An earlier draft of this message reported
the CPU cost as +10.4%, from ONE run taken while another seat was working the
box. Three repeats on a quiet box put the median at +3.2% — the published
number overstated the cost by more than three times. The direction survived the
correction and the magnitude did not, which is the case for repeating a figure
you intend to publish as a cost just as carefully as one you intend to publish
as a win.

Postgres binary CPU is flat to slightly down (63.9s -> 63.1s), which fits the
mechanism rather than contradicting it: that leg was 82% waiting, so parallelism
fills idle time instead of competing for cycles.

VARIANCE, since it changed shape: the parallel SQLite leg's repeat spread is
5.9% (106.7 / 111.0 / 113.2) against 0.7% for the serial leg it replaces.
Parallel runs are genuinely less reproducible than serial ones — scheduling
decides which tests share a core — so a future before/after on this package
needs more than one run per side to say anything, which the serial suite did
not.

The -race figure was measured because it was a RISK, not for completeness. CI's
Go job runs `go test -race -timeout=45m ./...` and already takes ~42 minutes;
the race detector serialises heavily, so parallelism could plausibly have made
that leg slower and pushed CI toward its own timeout. It does not: 2006s ->
1365s on the same box, measured against the template-only tree.

EXCLUSIONS — 62 tests, each for a mechanism rather than caution:

  19  files measuring ALLOCATIONS (runtime.ReadMemStats). Those counters are
      process-global, so a concurrent test's allocations land in the
      measurement. Excluded by FILE, since the hazard is the process.
   7  migration_guard_test.go, every test of which mutates the EXPORTED
      globals store.AllowSchemaAhead or store.BinaryVersion and restores in a
      t.Cleanup. AllowSchemaAhead=true under parallelism disarms the
      schema-ahead guard for every concurrently-running test — which is the
      property two of those very tests exist to assert.
  23  tests measuring ELAPSED TIME. Wall-clock under contention is not the
      wall-clock the assertion was written against.
   1  test mutating a PACKAGE-LEVEL GLOBAL (see below).
   3  the template mechanism tests, which assert on package-level counters.
  16  already had t.Parallel().

Excluding a test is a real remedy here rather than a hope, and the reason is a
Go semantic worth naming: a top-level test that calls t.Parallel() is HELD and
resumed only after the sequential pass finishes. Every excluded test therefore
still runs alone in a quiet process, which is exactly the property its timing or
allocation assertion depends on.

TWO EXCLUSIONS WERE MISSED BY MY OWN SWEEP, and the shape is the same both
times — an instrument whose question was narrower than the claim resting on it.

FIRST (found before shipping, by grepping the package's own `var` lines):


I recorded that this package has "no per-test global setters", having grepped
t.Setenv, os.Setenv and Set*ForTesting — all genuinely zero. The counts were
true and the conclusion was false. That sweep asked whether a test changes the
ENVIRONMENT; the claim it was carrying was whether a test changes anything
GLOBAL, which is wider.

TestUpdateDocument_CascadeExhaustionRollsBackTheWholeRename assigns the
package-level cascadeRewriteAttempts and restores it in a defer. Under
t.Parallel that window stays open while every other cascade test runs. The
mutating test would not flake; the tests AROUND it would, intermittently, which
is the worst shape to debug. Found by a different question — grep the package's
own non-test `var` declarations, then grep the tests for each name.

SECOND (found by codex, P1, NOT by me): that grep was `^var [a-z]`. It finds
UNEXPORTED package vars and silently skips exported ones, so it never saw
store.AllowSchemaAhead or store.BinaryVersion — both mutated by every test in
migration_guard_test.go. The instrument asked "which unexported globals exist"
while the claim it carried was "which globals exist". The fix that caught the
first miss was itself too narrow to catch the second, which is the argument for
enforcing the invariant in code rather than trusting the sweep that produced it.

Both exclusions are now enforced by guards rather than by the exclusion list:
TestCascadeExhaustionStaysSerial (function-scoped) and
TestMigrationGuardTestsStaySerial (file-scoped). Both fail closed on a missing
file or renamed function, strip line comments so an explanatory comment naming
t.Parallel() can neither satisfy nor trip them, carry a positive control that
the scan can SEE a real t.Parallel() elsewhere, and are mutation-controlled in
both directions.

VERIFICATION — 10 runs, zero failures, zero data races:

  SQLite parallel    x4   exit 0
  Postgres parallel  x3   exit 0
  -race -timeout=45m x1   exit 0, zero DATA RACE reports
  baseline -race     x1   exit 0 (the counterfactual above)

A false alarm not filed as a finding: the first -race run exited 1 with zero
`--- FAIL` lines and zero data races — the shape that reads as a pass to
anything counting FAIL lines. The log said `panic: test timed out after 10m0s`.
That was the invocation, not the code: `-timeout` was omitted so Go's default
applied, and ci.yml already carries a comment explaining that the explicit
-timeout exists because the default is too low.

KNOWN BOUND, not a solved problem: the test container's max_connections is 100,
each store sets MaxOpenConns(25), and -parallel defaults to GOMAXPROCS. On an
eight-core box the worst case permits 200. Three Postgres runs showed no
53300 "too many clients", but the arithmetic still allows it on a larger box or
a heavier test, and that belongs here as a bound rather than as an absence of
observed failures.

Claude-Session: https://claude.ai/code/session_01HeChkgZVYb3NTgTcckF5KR
2026-09-06 16:59:31 -04:00

204 lines
8.1 KiB
Go

package store
import (
"encoding/json"
"reflect"
"testing"
"github.com/PerpetualSoftware/pad/internal/models"
)
// assertSameFields compares two `fields` blobs by VALUE, not by bytes.
// The column is TEXT on SQLite — which hands back exactly what was written —
// and JSONB on Postgres, which re-serialises it (`{"status": "done"}` with a
// space). A byte comparison therefore passes on one dialect and fails on the
// other while saying nothing about the property under test, which is WHICH
// snapshot the blob came from. Found by the Postgres leg after the SQLite
// suite was green (BUG-2776).
func assertSameFields(t *testing.T, label, got, want, why string) {
t.Helper()
var g, w any
if err := json.Unmarshal([]byte(got), &g); err != nil {
t.Fatalf("%s is not JSON: %q (%v)", label, got, err)
}
if err := json.Unmarshal([]byte(want), &w); err != nil {
t.Fatalf("want value is not JSON: %q (%v)", want, err)
}
if !reflect.DeepEqual(g, w) {
if why != "" {
t.Errorf("%s = %s, want %s — %s", label, got, want, why)
} else {
t.Errorf("%s = %s, want %s", label, got, want)
}
}
}
// BUG-2776. UpdateItemWithParentLink hands back the pre-write view it read
// under its own locks, so a caller can describe what THIS call changed rather
// than what changed since the caller last looked.
//
// These are the store half of the contract; the handler half (a concurrent
// writer's change must not reach this request's change list) lives in
// internal/server. Wiring is a claim, so both halves are tested — a pre-image
// that is correct but never consumed fixes nothing (CONVE-19).
func TestUpdateItem_PreUpdateIsTheLockedPreWriteView(t *testing.T) {
t.Parallel()
s := testStore(t)
ws := createTestWorkspace(t, s, "PreImage")
coll := createTestCollection(t, s, ws.ID, "Tasks")
item := createTestItem(t, s, ws.ID, coll.ID, "Subject", "")
first := `{"status":"open"}`
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &first}, nil, nil); err != nil {
t.Fatalf("seed update: %v", err)
}
// A second writer commits BEFORE our call — the sequential stand-in for
// the concurrent case: what matters is that the pre-image is read at call
// time under the write lock, not carried in by the caller.
second := `{"status":"done"}`
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &second}, nil, nil); err != nil {
t.Fatalf("rival update: %v", err)
}
third := `{"status":"done","priority":"high"}`
updated, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &third}, nil, nil)
if err != nil {
t.Fatalf("update: %v", err)
}
if updated.PreUpdate == nil {
t.Fatal("PreUpdate is nil on a successful update; every caller diffing against it would silently fall back to its own stale read")
}
assertSameFields(t, "PreUpdate.Fields", updated.PreUpdate.Fields, second,
"the pre-image must be the row as the WRITE LOCK saw it, not an earlier snapshot")
assertSameFields(t, "post-write fields", updated.Fields, third, "")
}
// TestUpdateItem_PreUpdateCarriesJoinedDisplayNames pins the part a narrower
// pre-image would have broken: the handler's change list compares the assigned
// user's NAME and the role's slug/name, not their ids. A pre-image read
// without the users/agent_roles joins would leave those empty and invent
// "assigned: → Someone" on every update — a louder version of the bug this
// field exists to fix.
func TestUpdateItem_PreUpdateCarriesJoinedDisplayNames(t *testing.T) {
t.Parallel()
s := testStore(t)
ws := createTestWorkspace(t, s, "PreImageJoins")
coll := createTestCollection(t, s, ws.ID, "Tasks")
item := createTestItem(t, s, ws.ID, coll.ID, "Subject", "")
role, err := s.CreateAgentRole(ws.ID, models.AgentRoleCreate{Name: "Implementer", Icon: "🔨"})
if err != nil {
t.Fatalf("create role: %v", err)
}
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{AgentRoleID: &role.ID}, nil, nil); err != nil {
t.Fatalf("assign role: %v", err)
}
title := "Subject renamed"
updated, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Title: &title}, nil, nil)
if err != nil {
t.Fatalf("rename: %v", err)
}
if updated.PreUpdate == nil {
t.Fatal("PreUpdate is nil")
}
if updated.PreUpdate.AgentRoleName != role.Name || updated.PreUpdate.AgentRoleSlug != role.Slug {
t.Errorf("PreUpdate role = %q/%q, want %q/%q — the pre-image lost the joined display fields the change list compares",
updated.PreUpdate.AgentRoleName, updated.PreUpdate.AgentRoleSlug, role.Name, role.Slug)
}
if updated.PreUpdate.Title != "Subject" {
t.Errorf("PreUpdate.Title = %q, want the pre-rename title", updated.PreUpdate.Title)
}
}
// TestUpdateItem_PreUpdateComesFromTheLockedReRead is what makes the locked
// re-read load-bearing rather than incidental. A rival commits inside the
// window between this call's PRE-LOCK read and its transaction; the pre-image
// must reflect the rival's committed value, because that is the row this
// transaction is about to write over.
//
// Without this test a mutation that takes the pre-image from the pre-lock
// snapshot SURVIVES the rest of the suite: every other test's rival write
// lands before the store call begins, so both reads see the same thing and
// the two implementations are indistinguishable. That is why the seam exists.
func TestUpdateItem_PreUpdateComesFromTheLockedReRead(t *testing.T) {
t.Parallel()
s := testStore(t)
ws := createTestWorkspace(t, s, "PreImageLock")
coll := createTestCollection(t, s, ws.ID, "Tasks")
item := createTestItem(t, s, ws.ID, coll.ID, "Subject", "")
seed := `{"status":"open"}`
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &seed}, nil, nil); err != nil {
t.Fatalf("seed: %v", err)
}
rival := `{"status":"done"}`
fired := 0
var hook func(string)
hook = func(string) {
if fired > 0 {
return
}
fired++
s.afterItemPreLockRead = nil
defer func() { s.afterItemPreLockRead = hook }()
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &rival}, nil, nil); err != nil {
t.Errorf("rival update: %v", err)
}
}
s.afterItemPreLockRead = hook
mine := `{"status":"done","priority":"high"}`
updated, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Fields: &mine}, nil, nil)
if err != nil {
t.Fatalf("update: %v", err)
}
s.afterItemPreLockRead = nil
if fired != 1 {
t.Fatalf("seam fired %d times, want 1 — the pre-lock window was not exercised", fired)
}
if updated.PreUpdate == nil {
t.Fatal("PreUpdate is nil")
}
assertSameFields(t, "PreUpdate.Fields", updated.PreUpdate.Fields, rival,
"the pre-image was taken before the lock, so it predates a write this transaction is about to overwrite")
}
// TestUpdateItem_PreUpdateCarriesTheAssignedUser is the users-join half of the
// display-name contract. Without it, an implementation that dropped the users
// join while keeping the agent_roles one passes every other test here (codex
// round 3) — and would make the handler report "assigned: → Dave" on any
// update to an already-assigned item.
func TestUpdateItem_PreUpdateCarriesTheAssignedUser(t *testing.T) {
t.Parallel()
s := testStore(t)
ws := createTestWorkspace(t, s, "PreImageAssignee")
coll := createTestCollection(t, s, ws.ID, "Tasks")
item := createTestItem(t, s, ws.ID, coll.ID, "Subject", "")
user := createTestUser(t, s, "assignee@test.com", "Assignee", "hunter2hunter2")
if err := s.AddWorkspaceMember(ws.ID, user.ID, "editor"); err != nil {
t.Fatalf("add member: %v", err)
}
if _, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{AssignedUserID: &user.ID}, nil, nil); err != nil {
t.Fatalf("assign: %v", err)
}
title := "Subject renamed"
updated, err := s.UpdateItemWithParentLink(item.ID, models.ItemUpdate{Title: &title}, nil, nil)
if err != nil {
t.Fatalf("rename: %v", err)
}
if updated.PreUpdate == nil {
t.Fatal("PreUpdate is nil")
}
if updated.PreUpdate.AssignedUserName != user.Name {
t.Errorf("PreUpdate.AssignedUserName = %q, want %q — a pre-image without the users join makes every update on an assigned item report a spurious assignment change",
updated.PreUpdate.AssignedUserName, user.Name)
}
}