mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-10-26 14:30:13 +00:00
3c93472613
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 since6f8b6eb9a 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%, since6f8b6eb9) -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
300 lines
11 KiB
Go
300 lines
11 KiB
Go
package store
|
|
|
|
// BUG-2614 — the orphan GC's reference scan and the writer-side reference
|
|
// stamp both ignored the legacy v1 documents surface, so an attachment
|
|
// referenced ONLY from a document body was reclaimable while genuinely
|
|
// referenced. BUG-2615 — the bundle import's attachment remap rewrote item
|
|
// content and fields but not comment bodies, so imported comments kept the
|
|
// source workspace's ids.
|
|
//
|
|
// Both defects have the same shape: a content surface that carries
|
|
// `pad-attachment:` references was missing from a walk that is supposed to
|
|
// cover every such surface.
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/PerpetualSoftware/pad/internal/models"
|
|
)
|
|
|
|
func (f *gcClaimFixture) createDocument(t *testing.T, content string) *models.Document {
|
|
t.Helper()
|
|
doc, err := f.s.CreateDocument(f.wsID, models.DocumentCreate{
|
|
Title: "Ref carrier",
|
|
Content: content,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("CreateDocument: %v", err)
|
|
}
|
|
if doc == nil {
|
|
t.Fatal("CreateDocument returned nil")
|
|
}
|
|
return doc
|
|
}
|
|
|
|
// The headline: an attachment referenced only from a document body must read
|
|
// as referenced. Before the fix the scan covered items and comments only, so
|
|
// this returned false and the GC was free to reclaim a live reference.
|
|
func TestAttachmentReferenced_SeesDocumentContent(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
|
|
// Control first: nothing references it yet, on any surface.
|
|
referenced, err := f.s.AttachmentReferenced(f.wsID, a.ID)
|
|
if err != nil {
|
|
t.Fatalf("AttachmentReferenced (pre): %v", err)
|
|
}
|
|
if referenced {
|
|
t.Fatal("attachment read as referenced before anything referenced it — " +
|
|
"the assertion below would be vacuous")
|
|
}
|
|
|
|
f.createDocument(t, "before  after")
|
|
|
|
referenced, err = f.s.AttachmentReferenced(f.wsID, a.ID)
|
|
if err != nil {
|
|
t.Fatalf("AttachmentReferenced (post): %v", err)
|
|
}
|
|
if !referenced {
|
|
t.Error("attachment referenced from a document body read as UNreferenced — " +
|
|
"the orphan GC would reclaim it while the reference is live")
|
|
}
|
|
}
|
|
|
|
// A soft-deleted document must NOT hold a reference, mirroring items. Without
|
|
// this the scan would pin blobs behind deleted content forever.
|
|
func TestAttachmentReferenced_IgnoresDeletedDocument(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
doc := f.createDocument(t, "")
|
|
|
|
// Armed: live document, reference visible. Without this leg a broken
|
|
// scan that never sees documents at all would satisfy the assertion below.
|
|
referenced, err := f.s.AttachmentReferenced(f.wsID, a.ID)
|
|
if err != nil {
|
|
t.Fatalf("AttachmentReferenced (live): %v", err)
|
|
}
|
|
if !referenced {
|
|
t.Fatal("fixture never armed: live document's reference was not seen")
|
|
}
|
|
|
|
if err := f.s.DeleteDocument(doc.ID); err != nil {
|
|
t.Fatalf("DeleteDocument: %v", err)
|
|
}
|
|
|
|
referenced, err = f.s.AttachmentReferenced(f.wsID, a.ID)
|
|
if err != nil {
|
|
t.Fatalf("AttachmentReferenced (deleted): %v", err)
|
|
}
|
|
if referenced {
|
|
t.Error("a soft-deleted document still held the attachment reference; " +
|
|
"items are scanned live-only and documents must match")
|
|
}
|
|
}
|
|
|
|
// A document in ANOTHER workspace must not hold the reference — the scan is
|
|
// workspace-scoped, and a pasted foreign id must not pin someone else's rows.
|
|
func TestAttachmentReferenced_DocumentScanIsWorkspaceScoped(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
|
|
other, err := f.s.CreateWorkspace(models.WorkspaceCreate{Name: "Other WS"})
|
|
if err != nil {
|
|
t.Fatalf("CreateWorkspace: %v", err)
|
|
}
|
|
if _, err := f.s.CreateDocument(other.ID, models.DocumentCreate{
|
|
Title: "Foreign carrier",
|
|
Content: "",
|
|
}); err != nil {
|
|
t.Fatalf("CreateDocument (other ws): %v", err)
|
|
}
|
|
|
|
referenced, err := f.s.AttachmentReferenced(f.wsID, a.ID)
|
|
if err != nil {
|
|
t.Fatalf("AttachmentReferenced: %v", err)
|
|
}
|
|
if referenced {
|
|
t.Error("a document in another workspace held the reference — the scan " +
|
|
"must stay workspace-scoped")
|
|
}
|
|
}
|
|
|
|
// The write half. The scan protects references that exist when the sweep runs;
|
|
// the stamp is what covers a reference landing DURING a sweep, and it only
|
|
// works if the document writers call it. Both write paths are covered because
|
|
// they were differently shaped: UpdateDocument already had a transaction,
|
|
// CreateDocument had none and needed one.
|
|
func TestDocumentWrites_StampAttachmentRefs(t *testing.T) {
|
|
t.Parallel()
|
|
t.Run("create stamps", func(t *testing.T) {
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
|
|
if stamp := f.lastReferencedAt(t, a.ID); stamp != nil {
|
|
t.Fatalf("attachment already stamped before any write: %v", *stamp)
|
|
}
|
|
|
|
f.createDocument(t, "")
|
|
|
|
if stamp := f.lastReferencedAt(t, a.ID); stamp == nil {
|
|
t.Error("CreateDocument did not stamp the reference it wrote — a claim " +
|
|
"racing the insert cannot observe it")
|
|
}
|
|
})
|
|
|
|
t.Run("update stamps", func(t *testing.T) {
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
|
|
// Create with NO reference, so the stamp under test can only come
|
|
// from the update.
|
|
doc := f.createDocument(t, "nothing here yet")
|
|
if stamp := f.lastReferencedAt(t, a.ID); stamp != nil {
|
|
t.Fatalf("stamped by a document that never referenced it: %v", *stamp)
|
|
}
|
|
|
|
body := ""
|
|
if _, err := f.s.UpdateDocument(doc.ID, models.DocumentUpdate{Content: &body}); err != nil {
|
|
t.Fatalf("UpdateDocument: %v", err)
|
|
}
|
|
|
|
if stamp := f.lastReferencedAt(t, a.ID); stamp == nil {
|
|
t.Error("UpdateDocument did not stamp the reference it wrote")
|
|
}
|
|
})
|
|
|
|
t.Run("a metadata-only update stamps nothing", func(t *testing.T) {
|
|
f := newGCClaimFixture(t)
|
|
a := f.seedNeverAttached(t)
|
|
doc := f.createDocument(t, "")
|
|
|
|
// Clear the create-time stamp so the assertion is about THIS update.
|
|
if _, err := f.s.db.Exec(f.s.q(
|
|
`UPDATE attachments SET last_referenced_at = NULL WHERE id = ?`), a.ID); err != nil {
|
|
t.Fatalf("clear stamp: %v", err)
|
|
}
|
|
|
|
title := "Renamed, content untouched"
|
|
if _, err := f.s.UpdateDocument(doc.ID, models.DocumentUpdate{Title: &title}); err != nil {
|
|
t.Fatalf("UpdateDocument: %v", err)
|
|
}
|
|
|
|
if stamp := f.lastReferencedAt(t, a.ID); stamp != nil {
|
|
t.Errorf("a metadata-only update refreshed the reference stamp (%v) — it "+
|
|
"neither adds nor keeps a reference and must not vouch for one", *stamp)
|
|
}
|
|
})
|
|
}
|
|
|
|
// BUG-2615. The remap is what makes an imported bundle's references point at
|
|
// the destination's cloned attachment rows. It walked items only, so a
|
|
// reference living in a COMMENT kept the source workspace's id: broken in the
|
|
// destination, and the clone it should have pointed at ends up referenced by
|
|
// nothing.
|
|
func TestRemapAttachmentReferences_RewritesCommentBodies(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
oldID, newID := "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"
|
|
|
|
item, err := f.s.CreateItem(f.wsID, f.collID, models.ItemCreate{Title: "Carrier"})
|
|
if err != nil {
|
|
t.Fatalf("CreateItem: %v", err)
|
|
}
|
|
comment, err := f.s.CreateComment(f.wsID, item.ID, "", models.CommentCreate{
|
|
Author: "alice",
|
|
Body: "see  above",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("CreateComment: %v", err)
|
|
}
|
|
|
|
if err := f.s.RemapAttachmentReferencesInWorkspace(f.wsID, map[string]string{oldID: newID}); err != nil {
|
|
t.Fatalf("RemapAttachmentReferencesInWorkspace: %v", err)
|
|
}
|
|
|
|
var body string
|
|
if err := f.s.db.QueryRow(f.s.q(`SELECT body FROM comments WHERE id = ?`), comment.ID).Scan(&body); err != nil {
|
|
t.Fatalf("read comment body: %v", err)
|
|
}
|
|
if want := "pad-attachment:" + newID; !contains(body, want) {
|
|
t.Errorf("comment body was not remapped: %q — an imported comment keeps the "+
|
|
"SOURCE workspace's id, which resolves to nothing here", body)
|
|
}
|
|
if stale := "pad-attachment:" + oldID; contains(body, stale) {
|
|
t.Errorf("comment body still carries the source id: %q", body)
|
|
}
|
|
}
|
|
|
|
// The remap must leave the destination's stamps correct, not just its text.
|
|
// The import stamps each comment body at insert, but the body still holds the
|
|
// SOURCE ids then — so the clone the rewrite now points at carries no stamp
|
|
// unless the remap adds one, which is exactly the never-attached shape the GC
|
|
// claims.
|
|
func TestRemapAttachmentReferences_StampsTheRewrittenTarget(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
target := f.seedNeverAttached(t)
|
|
oldID := "33333333-3333-4333-8333-333333333333"
|
|
|
|
item, err := f.s.CreateItem(f.wsID, f.collID, models.ItemCreate{Title: "Carrier"})
|
|
if err != nil {
|
|
t.Fatalf("CreateItem: %v", err)
|
|
}
|
|
if _, err := f.s.CreateComment(f.wsID, item.ID, "", models.CommentCreate{
|
|
Author: "alice",
|
|
Body: "",
|
|
}); err != nil {
|
|
t.Fatalf("CreateComment: %v", err)
|
|
}
|
|
// The comment referenced the SOURCE id, so nothing stamped the clone.
|
|
if stamp := f.lastReferencedAt(t, target.ID); stamp != nil {
|
|
t.Fatalf("fixture never armed: clone was already stamped (%v)", *stamp)
|
|
}
|
|
|
|
if err := f.s.RemapAttachmentReferencesInWorkspace(f.wsID, map[string]string{oldID: target.ID}); err != nil {
|
|
t.Fatalf("RemapAttachmentReferencesInWorkspace: %v", err)
|
|
}
|
|
|
|
if stamp := f.lastReferencedAt(t, target.ID); stamp == nil {
|
|
t.Error("the remap rewrote a reference onto the clone without stamping it — " +
|
|
"a GC sweep between the import and the next write reclaims it")
|
|
}
|
|
}
|
|
|
|
// A clone that nothing ends up referencing must NOT be stamped. Stamping the
|
|
// whole id map would vouch for rows no text points at, keeping genuinely
|
|
// unreferenced clones alive for an extra GC window.
|
|
func TestRemapAttachmentReferences_DoesNotStampUnreferencedClones(t *testing.T) {
|
|
t.Parallel()
|
|
f := newGCClaimFixture(t)
|
|
unreferenced := f.seedNeverAttached(t)
|
|
|
|
if err := f.s.RemapAttachmentReferencesInWorkspace(f.wsID, map[string]string{
|
|
"44444444-4444-4444-8444-444444444444": unreferenced.ID,
|
|
}); err != nil {
|
|
t.Fatalf("RemapAttachmentReferencesInWorkspace: %v", err)
|
|
}
|
|
|
|
if stamp := f.lastReferencedAt(t, unreferenced.ID); stamp != nil {
|
|
t.Errorf("stamped a clone that no content references (%v)", *stamp)
|
|
}
|
|
}
|
|
|
|
// strings.Contains by another name would be simpler; kept local only because
|
|
// the package already imports strings for other purposes and a helper name
|
|
// collision is cheaper to avoid than to debug.
|
|
func contains(haystack, needle string) bool {
|
|
return len(needle) > 0 && len(haystack) >= len(needle) &&
|
|
func() bool {
|
|
for i := 0; i+len(needle) <= len(haystack); i++ {
|
|
if haystack[i:i+len(needle)] == needle {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}()
|
|
}
|