From 72567edc28e39c0228180034f6967892d096d3b5 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Tue, 24 Nov 2026 18:51:14 -0500 Subject: [PATCH 1/3] feat(tenancy): fence late object PUTs out of erasure A PUT admitted before an org's deletion can still be stored after the purge erased its prefix. Every object PUT is now bounded from entry, and the purge marks the org purged only after a prefix delete at least LatePutWindow past its database-time fence. An age-gated orphan sweep, run by object GC under the blob and upload locks, removes late PUTs after GC or erasure. The shared client pin moves to the #78 merge for provider modification times. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 + DESIGN.md | 6 +- IMPLEMENTATION_PLAN.md | 14 +- docs/ASSURANCE-CASE.md | 8 +- .../specs/2026-11-23-tenancy-design.md | 34 +++- go.mod | 2 +- go.sum | 12 +- internal/blobstore/AGENTS.md | 12 +- internal/blobstore/export_test.go | 10 + internal/blobstore/object_parts.go | 2 + internal/blobstore/object_runtime_test.go | 180 ++++++++++++++++-- internal/blobstore/objects.go | 59 +++++- internal/blobstore/objects_test.go | 25 ++- internal/storage/charged_test.go | 7 +- internal/storage/object_gc.go | 89 ++++++++- internal/storage/purge.go | 58 +++++- internal/storage/purge_test.go | 25 +++ 17 files changed, 496 insertions(+), 52 deletions(-) create mode 100644 internal/blobstore/export_test.go diff --git a/AGENTS.md b/AGENTS.md index 2fe43fd9..05ce34e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -290,6 +290,11 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che fails, nothing is marked purged. Multi-mode blob GC is `storage.RunObjectGC`: candidates and the re-check are per `(org_id, digest)`, under `storage.BlobLockName`, rows commit before the object delete. Verify `TestObjectGC*` and `TestPurgeDeletesOnlyTheDeletedOrgsPrefix` on PostgreSQL. + Late-PUT fence: the purge's first run records `purge_fence:` (database time) with the + started audit; it deletes the prefix every run but marks purged only on a run at least + `blobstore.LatePutWindow` later. `SweepOrphanObjects` (inside `RunObjectGC`) deletes unclaimed + objects over an hour old by provider time, re-checked under their session lock. Verify + `TestLatePutAfterPurge*` and `TestOrphanSweep*`. - Member erasure uses `CleanupFor(db).AdvanceSeq` and `TombstoneComment`, one fresh sequence per retained comment so paginated sync delivers every deletion. Directory erasure runs only in multi mode; single mode refuses `user.erased`. Verify `TestMultiModeDirectoryKeepsAccountsInTheirOrg`. diff --git a/DESIGN.md b/DESIGN.md index 79e2b7dc..f2bfa695 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1028,8 +1028,10 @@ of replica fields and persisted settings. This entry point remains separate from and all startup paths; tests preserve the multi refusal and standalone golden. N3 session-lock ownership and context cancellation do not establish the fate of a previously -issued remote PUT after lock loss. Complete GC/purge/runtime integration requires a selected -and qualified delayed-writer erasure fence before deletion/readiness claims. The shared +issued remote PUT after lock loss. The selected fence is a time window: PUTs are bounded from +entry, a purge completes only after a prefix delete `LatePutWindow` past its fence, and an +age-gated orphan sweep removes late PUTs after GC or erasure. Provider qualification of the +window remains before readiness claims. The shared conditional API does not choose a product ledger/protocol. Store controls/age and selected provider proof, native-PG recovery transport and final assembly remain launch prerequisites. diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 02389117..57ba9acc 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2319,15 +2319,15 @@ regular credential files may end with one LF/CRLF; bounded reads, source/type fa client validation errors disclose setting names only. Construction makes no network request, local key/store or SQL write. No normal config loader or startup path invokes it. -The base shared client is pinned to merged #77 (`79823f9`); #78's exclusive-create, -ETag and age additions are merged as `b55ca6d` but are not consumed by this pin. Complete Backend/Temporary, +The shared client is pinned to the #78 merge (`b55ca6d`): exclusive create, ETags and +provider age are consumed; the orphan sweep reads the age. Complete Backend/Temporary, store-ID/probes, request/GC/purge integration and provider evidence remain unbuilt. -Before binding GC/purge/runtime, qualify the fate of an already-issued remote PUT after the -writer loses its PG session lock or context. Lock loss/cancellation alone cannot prove that -remote write finished before erasure. The selected Notes resolution and delayed-write test -must be recorded here before erasure-readiness claims; consuming wire-only conditional APIs -does not select Messages' ledger/protocol. Preserve access fences while this is unresolved. +Selected late-PUT resolution (spec "Late-PUT erasure fence as built"): a time fence, not a +ledger. Every object PUT is bounded from entry; the purge marks an org purged only after a +prefix delete at least `LatePutWindow` after its fence; an age-gated orphan sweep removes a +late PUT after GC or erasure. The window holds only if the provider honors SigV4 request age +and commits no PUT after it; that is provider qualification, still open. Native encrypted PG base-backup/WAL tool/transport, destination/retention and restore/drill remain spec open question 3. Startup remains refused; existing single-mode behavior stays. diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index a3a317f6..64af002a 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -207,9 +207,11 @@ client gate clearance, exclusive controls, provider age and native recovery rema Primary-object client preparation has a separate environment/_FILE credential boundary. `TestReplicaObject*` covers bounded values/files, source ambiguity, nonregular/missing paths, multiline/empty refusal and secret-safe errors/formatting. Construction writes no shared -settings or local store and does not enable startup. Actual delayed PUT completion after a -lost PG lock remains unqualified; neither a canceled context nor the published wire API is -erasure proof. Runtime/GC/purge/provider and native-PG recovery gates remain explicit. +settings or local store and does not enable startup. A late PUT after a lost PG lock is fenced +by time: `TestLatePutAfterPurgeIsErasedBeforeTheOrgIsMarkedPurged` lands a timed-out PUT after +the prefix delete and fails if the purge completes inside the window; +`TestOrphanSweepDeletesOnlyOldUnclaimedObjects` covers GC/erasure orphans. The provider's +honoring of the window is unqualified. Runtime/GC/purge/provider and native-PG recovery gates remain explicit. Host maintenance uses the exact existing PG schema and recorded staff org/region, with no migration or local-key fallback. Tests require atomic account/audit creation, real password diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index be8b50ec..0e7f24b3 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1598,7 +1598,7 @@ network or database I/O and is not called by ordinary startup or maintenance loa Tests cover direct/file/mixed sources, ambiguity/empty/size/multiline/path/type refusal, secret-safe errors/formatting, shared-field separation and unchanged startup refusals. -Base #77 is merged and pinned to79823f9; #78 is merged asb55ca6d but is not consumed. Before +Base #77 was pinned at 79823f9; the late-PUT fence moved the pin to the #78 merge b55ca6d. Before complete GC/purge/runtime binding, Notes must select and qualify delayed remote-PUT fate after PG-lock loss; cancellation alone is no completion proof. Shared conditional operations do not select a Notes ledger/protocol. Keep this and native-PG recovery open question3 as @@ -1619,6 +1619,38 @@ the prefix step. The schedule adapter carries the purge step; startup binding, t fence and the orphan sweep are separate. +### Late-PUT erasure fence as built (startup still refused) + +The problem: a writer admitted before an org's deletion (or holding a blob lock it then +loses) can have a PUT the provider stores after the purge deleted the prefix, or after GC +deleted the blob. Lock loss and cancellation prove nothing about that remote write. + +The selected resolution is a time fence, with no new ledger: + +- `Objects.Put`/`PutPart` bound the whole call by a 5-minute deadline from entry. Callers + admit the org under the session lock just before the call, with bytes already received. +- `LatePutWindow` is 20 minutes: the deadline plus SigV4's 15-minute request-age limit, which + a provider applies when it receives the request. +- The purge's first run inserts `purge_fence:` in database time with the + `platform.org_purge_started` audit, in one transaction (the audit is now written once). Every + run deletes the rows and the prefix. Only a run that read the fence at least the window old + before its prefix delete marks the tombstone purged and removes the fence. +- `SweepOrphanObjects` runs at the end of `RunObjectGC`. For each serving org it lists the + prefix with provider times and deletes, under the blob or upload session lock, any blob with + no row and any upload with no pending session, once over an hour old. Zero (unknown) age + never deletes; at most 100 a pass. +- The shared client pin moved to the #78 merge (`b55ca6d`) for `LastModified`. + +Tests: a PUT blocked at the provider times out at the client; the purge runs; the provider +then stores the PUT. The purge must not be marked inside the window, and the run after it must +leave no key. Removing the window check fails it; removing the deadline hangs it to its limit. +The orphan sweep keeps young, unknown-age, claimed, pending-upload and stopped-org objects. +Mutations of the age check, the claim re-check and the pending-upload check each fail it. + +Unproven: that a selected provider honors request age and commits no PUT past the window +(provider qualification), and clock skew between provider and database beyond a few minutes. + + ### Phase 6 host maintenance as built (startup still refused) Multi-mode `user add --admin` uses bounded stdin derived credentials and an exact existing PG diff --git a/go.mod b/go.mod index 3e4e4d6f..30ee5142 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.26.9 toolchain go1.27.4 require ( - github.com/Busnes-app/ky-primitives v0.10.2-0.20261124001445-79823f9af6b7 + github.com/Busnes-app/ky-primitives v0.10.2-0.20261124003741-b55ca6d3313c github.com/Busnes-app/ky-primitives/offsite v0.3.0 github.com/cloudflare/circl v1.6.5 github.com/jackc/pgx/v5 v5.13.0 diff --git a/go.sum b/go.sum index b22eed96..22e4ae2b 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,5 @@ -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123013446-90b0e58aa724 h1:LGkxdH5emHN9FviYtr5QgYB5qqc3EiF/YzpAmCwxcYU= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123013446-90b0e58aa724/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123144426-9185e49e0370 h1:iA96g0TPifRPXjZygpDBghFjLOx1AoSxejhjst0Ft6s= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123144426-9185e49e0370/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123230226-12e1963e8dc8 h1:blG5fPxQFJ4k/K/PCaC5abe1hF/cWYjUJ0RsmGELCKw= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123230226-12e1963e8dc8/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123231137-3242eb82f4b9 h1:F1P9sjVAF4rVl2lbVOaMmF2Z8BI0zVci+96Frn7HdYg= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261123231137-3242eb82f4b9/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261124001445-79823f9af6b7 h1:fko4xQHrAHJxDR7Ni1tBqj4PAOZVataOpyi+uIC4O6g= -github.com/Busnes-app/ky-primitives v0.10.2-0.20261124001445-79823f9af6b7/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= +github.com/Busnes-app/ky-primitives v0.10.2-0.20261124003741-b55ca6d3313c h1:uVDDt5rGQoNUSRvVeTGGBKl/S8C2ygmF65n0d/xf+jo= +github.com/Busnes-app/ky-primitives v0.10.2-0.20261124003741-b55ca6d3313c/go.mod h1:xYUuDP23Ey2tnBVVIbrOz0qjGsZ0bBBpSraG0qWm1O8= github.com/Busnes-app/ky-primitives/offsite v0.3.0 h1:E0ycngO0BHAooTDRvDagmrJlkZlTeRqBNX5pLwQMlg0= github.com/Busnes-app/ky-primitives/offsite v0.3.0/go.mod h1:UYfgJk5VJ/Z4Dff5wvSPeOn4dwS1qLGDeNPTTkEguKI= github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc= diff --git a/internal/blobstore/AGENTS.md b/internal/blobstore/AGENTS.md index 0a8ac174..09b301e7 100644 --- a/internal/blobstore/AGENTS.md +++ b/internal/blobstore/AGENTS.md @@ -38,8 +38,13 @@ Own opaque blob streams, single-volume compatibility and the tenancy blob seam. content cache or storage fallback. Identical writes reuse verified bytes; parts remain live until explicit post-commit/cancel/expiry cleanup. Tail removal validates every index first. - Delete/Purge are explicit unreferenced-key/org erasure, including physical versions/markers. - No scheduled pruning or orphan deletion is enabled. Unknown-object cleanup needs provider age - proof; store-ID creation still requires the shared client's create-exclusive operation. + No scheduled version pruning. `Stored` feeds storage's orphan sweep, which deletes only with + provider age proof (zero `LastModified` never deletes); store-ID creation still requires the + shared client's create-exclusive operation. +- Late-PUT fence: `Put`/`PutPart` bound the whole call by `putDeadline` from entry. Callers + pass already-received bytes and admit the org under the session lock just before the call. + `LatePutWindow` (deadline plus SigV4's 15-minute request age) is how long the purge waits + after its fence; widening the deadline means widening the window. - New shared-client dependencies must point to its reviewed upstream implementation, with no copied signing/transport or invented client contract. Provider qualification is separate from the local TLS S3 wire fixture. @@ -53,7 +58,8 @@ Own opaque blob streams, single-volume compatibility and the tenancy blob seam. - `go test -race -count=1 ./internal/blobstore` - `TestObjectGC*`/`TestPurgeDeletesOnlyTheDeletedOrgsPrefix` drive storage's GC and purge through - the real shared client on PostgreSQL. + the real shared client on PostgreSQL. `TestLatePutAfterPurgeIsErasedBeforeTheOrgIsMarkedPurged` + and `TestOrphanSweepDeletesOnlyOldUnclaimedObjects` prove the late-PUT fence. - `TestObjects*`/`TestObjectParts*` use the actual shared client and a local verified TLS fixture. - PostgreSQL CI runs `TestReplicaStoreIdentity*` against isolated schemas. - The full HTTPAPI suite and `TestSingleTenantUpgradeGolden` pin existing behavior. diff --git a/internal/blobstore/export_test.go b/internal/blobstore/export_test.go new file mode 100644 index 00000000..1195c456 --- /dev/null +++ b/internal/blobstore/export_test.go @@ -0,0 +1,10 @@ +package blobstore + +import "time" + +// SetPutDeadline shortens the put deadline for one test. +func SetPutDeadline(d time.Duration) (restore func()) { + old := putDeadline + putDeadline = d + return func() { putDeadline = old } +} diff --git a/internal/blobstore/object_parts.go b/internal/blobstore/object_parts.go index aadd3543..3ebcb0ec 100644 --- a/internal/blobstore/object_parts.go +++ b/internal/blobstore/object_parts.go @@ -17,6 +17,8 @@ import ( // upload session lock and owns DB counter admission. An identical retry reuses bytes; a // rolled-back counter explicitly drops its uncommitted tail before accepting another body. func (s *Objects) PutPart(ctx context.Context, id string, index int64, body io.Reader, size int64) error { + ctx, cancel := context.WithTimeout(ctx, putDeadline) + defer cancel() key, err := UploadPartKey(s.org, id, index) if err != nil { return err diff --git a/internal/blobstore/object_runtime_test.go b/internal/blobstore/object_runtime_test.go index 2c4c20d2..71838a82 100644 --- a/internal/blobstore/object_runtime_test.go +++ b/internal/blobstore/object_runtime_test.go @@ -4,6 +4,8 @@ import ( "bytes" "context" "database/sql" + "errors" + "strings" "testing" "time" @@ -194,29 +196,181 @@ func TestPurgeDeletesOnlyTheDeletedOrgsPrefix(t *testing.T) { if _, err := db.Exec(`UPDATE orgs SET status='deleted' WHERE id='org_b'`); err != nil { t.Fatal(err) } - resolve := stores(t, client) - purge := func(ctx context.Context, org string) error { - s, err := resolve(org) + purge := purgeWith(stores(t, client)) + for range 2 { // the second run is past the late-PUT window + if err := storage.PurgeDeletedOrgs(t.Context(), db, purge); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`UPDATE server_settings SET value='0' WHERE key='purge_fence:org_b'`); err != nil { + t.Fatal(err) + } + } + if keys := orgKeys(fixture, "org_b"); len(keys) != 0 { + t.Errorf("%v survived the purge", keys) + } + if !objectExists(t, client, "org_a", d) || !blobRow(t, db, "org_a", d) { + t.Fatal("the purge of org_b removed org_a's copy") + } + if purgedAt(t, db, "org_b") == "" { + t.Fatal("org_b not marked purged") + } +} + +func purgeWith(stores storage.ObjectStores) storage.PurgeObjects { + return func(ctx context.Context, org string) error { + s, err := stores(org) if err != nil { return err } return s.Purge(ctx) } +} + +func orgKeys(f *objectFixture, org string) []string { + f.mu.Lock() + defer f.mu.Unlock() + var keys []string + for key := range f.objects { + if strings.HasPrefix(key, "orgs/"+org+"/") { + keys = append(keys, key) + } + } + return keys +} + +func purgedAt(t *testing.T, db *sql.DB, org string) string { + t.Helper() + var at string + if err := db.QueryRow(`SELECT purged_at FROM orgs WHERE id=?`, org).Scan(&at); err != nil { + t.Fatal(err) + } + return at +} + +// A PUT admitted before the org was deleted times out at the client, then the provider stores +// it after the purge deleted the prefix. The purge must not mark the org purged until a prefix +// delete after the late-PUT window has erased it. +func TestLatePutAfterPurgeIsErasedBeforeTheOrgIsMarkedPurged(t *testing.T) { + db := runtimeDatabase(t) + fixture, client := newObjectFixture(t) + putBlob(t, db, client, "org_b", []byte("stored before the delete"), time.Now()) + fixture.started, fixture.release, fixture.landed = make(chan struct{}), make(chan struct{}), make(chan struct{}) + defer blobstore.SetPutDeadline(200 * time.Millisecond)() + late := []byte("admitted before the delete, stored after the purge") + put := make(chan error, 1) + go func() { + put <- objectStore(t, client, "org_b", t.TempDir()).Put(t.Context(), objectDigest(late), bytes.NewReader(late), int64(len(late))) + }() + <-fixture.started + select { + case err := <-put: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatal("want the put deadline, got", err) + } + case <-time.After(10 * time.Second): + close(fixture.release) + t.Fatal("an admitted PUT outlived its deadline") + } + if _, err := db.Exec(`UPDATE orgs SET status='deleted' WHERE id='org_b'`); err != nil { + t.Fatal(err) + } + purge := purgeWith(stores(t, client)) if err := storage.PurgeDeletedOrgs(t.Context(), db, purge); err != nil { t.Fatal(err) } - fixture.mu.Lock() - for key := range fixture.objects { - if bytes.HasPrefix([]byte(key), []byte("orgs/org_b/")) { - t.Errorf("%s survived the purge", key) + if at := purgedAt(t, db, "org_b"); at != "" { + close(fixture.release) + t.Fatal("org marked purged inside the late-PUT window") + } + close(fixture.release) + <-fixture.landed + if keys := orgKeys(fixture, "org_b"); len(keys) != 1 { + t.Fatalf("the late PUT should have landed: %v", keys) + } + if _, err := db.Exec(`UPDATE server_settings SET value='0' WHERE key='purge_fence:org_b'`); err != nil { + t.Fatal(err) + } + if err := storage.PurgeDeletedOrgs(t.Context(), db, purge); err != nil { + t.Fatal(err) + } + if keys := orgKeys(fixture, "org_b"); len(keys) != 0 || purgedAt(t, db, "org_b") == "" { + t.Fatalf("after the window: keys=%v purged_at=%q", keys, purgedAt(t, db, "org_b")) + } +} + +// The orphan sweep deletes an object no row claims only when the provider says it is over an +// hour old, and only for a serving org: a late PUT after GC or an erasure, or an abandoned +// upload's parts. Claimed, young, unknown-age and stopped orgs' objects stay. +func TestOrphanSweepDeletesOnlyOldUnclaimedObjects(t *testing.T) { + db := runtimeDatabase(t) + fixture, client := newObjectFixture(t) + old, young := time.Now().Add(-2*time.Hour), time.Now().Add(-10*time.Minute) + put := func(org, body string, at time.Time) string { + d := objectDigest([]byte(body)) + if err := objectStore(t, client, org, t.TempDir()).Put(t.Context(), d, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + key, _ := blobstore.BlobKey(org, d) + fixture.mu.Lock() + if !at.IsZero() { + fixture.modified[key] = at } + fixture.mu.Unlock() + return d } - fixture.mu.Unlock() - if !objectExists(t, client, "org_a", d) || !blobRow(t, db, "org_a", d) { - t.Fatal("the purge of org_b removed org_a's copy") + orphan := put("org_a", "late put after gc", old) + recent := put("org_a", "put ten minutes ago", young) + unknown := put("org_a", "no provider age", time.Time{}) + claimed := put("org_a", "claimed", old) + stopped := put("org_b", "suspended org", old) + if _, err := db.Exec(`INSERT INTO blobs(org_id,digest,size_bytes,created_at) VALUES('org_a',?,7,'t')`, claimed); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`UPDATE orgs SET status='suspended' WHERE id='org_b'`); err != nil { + t.Fatal(err) } - var purgedAt string - if err := db.QueryRow(`SELECT purged_at FROM orgs WHERE id='org_b'`).Scan(&purgedAt); err != nil || purgedAt == "" { - t.Fatalf("purged_at=%q %v", purgedAt, err) + part := func(pending bool) string { + id, err := ids.Mint("ups") + if err != nil { + t.Fatal(err) + } + if err := objectStore(t, client, "org_a", t.TempDir()).PutPart(t.Context(), id, 0, strings.NewReader("chunk"), 5); err != nil { + t.Fatal(err) + } + key, _ := blobstore.UploadPartKey("org_a", id, 0) + fixture.mu.Lock() + fixture.modified[key] = old + fixture.mu.Unlock() + if pending { + if _, err := db.Exec(`INSERT INTO upload_sessions(id,user_id,container_id,declared_bytes,chunk_bytes,created_at,updated_at,expires_at,org_id) VALUES(?,'usr_a','cnt_a',5,5,'t','t','t','org_a')`, id); err != nil { + t.Fatal(err) + } + } + return id + } + abandoned, live := part(false), part(true) + n, err := storage.SweepOrphanObjects(t.Context(), db, stores(t, client)) + if err != nil || n != 2 { + t.Fatalf("swept=%d err=%v", n, err) + } + if objectExists(t, client, "org_a", orphan) { + t.Error("an old unclaimed object survived") + } + for name, d := range map[string]string{"young": recent, "unknown age": unknown, "claimed": claimed} { + if !objectExists(t, client, "org_a", d) { + t.Errorf("the %s object was swept", name) + } + } + if !objectExists(t, client, "org_b", stopped) { + t.Error("a stopped org's object was swept") + } + for id, want := range map[string]bool{abandoned: false, live: true} { + key, _ := blobstore.UploadPartKey("org_a", id, 0) + fixture.mu.Lock() + _, ok := fixture.objects[key] + fixture.mu.Unlock() + if ok != want { + t.Errorf("upload %s part present=%v, want %v", id, ok, want) + } } } diff --git a/internal/blobstore/objects.go b/internal/blobstore/objects.go index e6c0f375..d9606449 100644 --- a/internal/blobstore/objects.go +++ b/internal/blobstore/objects.go @@ -7,7 +7,9 @@ import ( "errors" "io" "os" + "strconv" "strings" + "time" shareds3 "github.com/Busnes-app/ky-primitives/s3" ) @@ -22,6 +24,16 @@ type Objects struct { maxBytes int64 } +// putDeadline bounds every Put/PutPart call, from entry, so a write admitted before an erasure +// or purge cannot reach the provider after LatePutWindow. Callers pass already-received bytes +// and admit the org under the session lock immediately before the call. +var putDeadline = 5 * time.Minute + +// LatePutWindow is how long after its writers are fenced an org's prefix can still gain a +// late PUT: the put deadline plus SigV4's 15-minute request-age limit, which also covers a +// provider that commits after the client gave up. Unqualified on a real provider. +const LatePutWindow = 20 * time.Minute + func (Objects) String() string { return "blobstore.Objects" } func (Objects) GoString() string { return "blobstore.Objects" } @@ -38,6 +50,8 @@ func NewObjects(client *shareds3.Client, org, scratch string, maxBytes int64) (* // Put verifies a bounded private snapshot before any PUT. The caller's session lock makes // HEAD/verify/PUT safe for a content-addressed key; it does not replace exclusive control PUTs. func (s *Objects) Put(ctx context.Context, digest string, body io.Reader, size int64) error { + ctx, cancel := context.WithTimeout(ctx, putDeadline) + defer cancel() key, err := BlobKey(s.org, digest) if err != nil { return err @@ -157,8 +171,49 @@ func (s *Objects) ListDigests(ctx context.Context) ([]string, error) { return out, nil } +// Stored lists the org's blobs and uploads with the provider's modification time, the latest +// part's for an upload. A zero time is unknown age: the orphan sweep never deletes on it. +func (s *Objects) Stored(ctx context.Context) (blobs, uploads map[string]time.Time, err error) { + prefix, _ := OrgPrefix(s.org) + objects, err := s.listObjects(ctx, prefix) + if err != nil { + return nil, nil, err + } + blobs, uploads = map[string]time.Time{}, map[string]time.Time{} + for _, o := range objects { + rest := o.Key[len(prefix):] + if strings.HasPrefix(rest, "blobs/") { + digest := rest[strings.LastIndexByte(rest, '/')+1:] + if key, err := BlobKey(s.org, digest); err != nil || key != o.Key { + return nil, nil, ErrCorruptBlob + } + blobs[digest] = o.LastModified + continue + } + id, index, _ := strings.Cut(strings.TrimPrefix(rest, "uploads/"), "/") + n, err := strconv.ParseInt(index, 10, 64) + if key, keyErr := UploadPartKey(s.org, id, n); err != nil || keyErr != nil || key != o.Key { + return nil, nil, ErrCorruptBlob + } + switch t, seen := uploads[id]; { + case !seen, !t.IsZero() && (o.LastModified.IsZero() || o.LastModified.After(t)): + uploads[id] = o.LastModified // the newest part, or unknown if any part's age is + } + } + return blobs, uploads, nil +} + func (s *Objects) listKeys(ctx context.Context, prefix string) ([]string, error) { - var keys []string + objects, err := s.listObjects(ctx, prefix) + keys := make([]string, len(objects)) + for i, o := range objects { + keys[i] = o.Key + } + return keys, err +} + +func (s *Objects) listObjects(ctx context.Context, prefix string) ([]shareds3.Object, error) { + var keys []shareds3.Object seenKeys, seenTokens := map[string]bool{}, map[string]bool{} token := "" for { @@ -171,7 +226,7 @@ func (s *Objects) listKeys(ctx context.Context, prefix string) ([]string, error) return nil, ErrCorruptBlob } seenKeys[object.Key] = true - keys = append(keys, object.Key) + keys = append(keys, object) } if page.Next == "" { return keys, nil diff --git a/internal/blobstore/objects_test.go b/internal/blobstore/objects_test.go index 7d68a042..2157c439 100644 --- a/internal/blobstore/objects_test.go +++ b/internal/blobstore/objects_test.go @@ -36,14 +36,16 @@ type objectFixture struct { puts map[string]int failures map[string]int started, release chan struct{} + landed chan struct{} // closed once the first blocked PUT is stored once sync.Once gzipKey string getEncoding string + modified map[string]time.Time // provider age; absent is unknown } func newObjectFixture(t *testing.T) (*objectFixture, *shareds3.Client) { t.Helper() - f := &objectFixture{objects: map[string][]byte{}, puts: map[string]int{}, failures: map[string]int{}} + f := &objectFixture{objects: map[string][]byte{}, puts: map[string]int{}, failures: map[string]int{}, modified: map[string]time.Time{}} server := httptest.NewTLSServer(http.HandlerFunc(f.serve)) t.Cleanup(server.Close) client, err := shareds3.New(shareds3.Config{Endpoint: server.URL, Bucket: "bucket", Region: "local", AccessKey: "object-fixture-access", SecretKey: "object-fixture-secret", HTTP: server.Client()}) @@ -86,18 +88,25 @@ func (f *objectFixture) serve(w http.ResponseWriter, r *http.Request) { Size int64 VersionID string `xml:"VersionId,omitempty"` Latest bool `xml:"IsLatest,omitempty"` + Modified string `xml:"LastModified,omitempty"` + } + age := func(k string) string { + if at, ok := f.modified[k]; ok { + return at.UTC().Format(time.RFC3339) + } + return "" } entries := []entry{} next := "" if r.URL.Query().Has("versions") { for _, k := range keys { - entries = append(entries, entry{k, int64(len(f.objects[k])), "null", true}) + entries = append(entries, entry{k, int64(len(f.objects[k])), "null", true, age(k)}) } } else { token := r.URL.Query().Get("continuation-token") for _, k := range keys { if token == "" || k > token { - entries = append(entries, entry{Key: k, Size: int64(len(f.objects[k]))}) + entries = append(entries, entry{Key: k, Size: int64(len(f.objects[k])), Modified: age(k)}) } } if len(entries) > 1 { @@ -128,13 +137,17 @@ func (f *objectFixture) serve(w http.ResponseWriter, r *http.Request) { w.WriteHeader(500) return } + first := false if f.started != nil { - f.once.Do(func() { close(f.started) }) + f.once.Do(func() { close(f.started); first = true }) <-f.release } f.mu.Lock() f.objects[key] = body f.mu.Unlock() + if first && f.landed != nil { + close(f.landed) + } w.Header().Set("X-Amz-Version-Id", "null") w.WriteHeader(200) return @@ -149,6 +162,7 @@ func (f *objectFixture) serve(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodDelete { delete(f.objects, key) } + modified, aged := f.modified[key] f.mu.Unlock() if r.Method == http.MethodDelete { w.WriteHeader(204) @@ -161,6 +175,9 @@ func (f *objectFixture) serve(w http.ResponseWriter, r *http.Request) { if encoded { w.Header().Set("Content-Encoding", "gzip") } + if aged { + w.Header().Set("Last-Modified", modified.UTC().Format(http.TimeFormat)) + } w.Header().Set("Content-Length", strconv.Itoa(len(body))) w.Header().Set("X-Amz-Version-Id", "null") if r.Method == http.MethodGet { diff --git a/internal/storage/charged_test.go b/internal/storage/charged_test.go index 2eaff18a..b257a4d9 100644 --- a/internal/storage/charged_test.go +++ b/internal/storage/charged_test.go @@ -49,8 +49,11 @@ func TestOrgUsageMatchesUsedBytes(t *testing.T) { if _, err := s.db.Exec(`UPDATE orgs SET status='deleted' WHERE id='org_b'`); err != nil { t.Fatal(err) } - if err := PurgeOrg(context.Background(), s.db, noObjects, "org_b"); err != nil { - t.Fatal(err) + for range 2 { // the second run is past the late-PUT window + if err := PurgeOrg(context.Background(), s.db, noObjects, "org_b"); err != nil { + t.Fatal(err) + } + endPurgeWindow(t, s) } var n int if err := s.db.QueryRow(`SELECT count(*) FROM org_usage WHERE org_id='org_b'`).Scan(&n); err != nil || n != 0 { diff --git a/internal/storage/object_gc.go b/internal/storage/object_gc.go index f0d9526b..a61e5baf 100644 --- a/internal/storage/object_gc.go +++ b/internal/storage/object_gc.go @@ -69,7 +69,94 @@ func RunObjectGC(ctx context.Context, db *sql.DB, stores ObjectStores, now time. if _, err := db.ExecContext(ctx, `UPDATE blobs AS b SET unreferenced_since=? WHERE unreferenced_since='' AND `+orgUnreferenced, now.UTC().Format(time.RFC3339)); err != nil { return deleted, errors.Join(sweepErr, err) } - return deleted, sweepErr + orphans, err := SweepOrphanObjects(ctx, db, stores) + return deleted + orphans, errors.Join(sweepErr, err) +} + +// orphanAge is how old, by the provider's clock, an object no row claims must be before the +// sweep deletes it (spec: an hour). It exceeds LatePutWindow, so no admitted PUT is in flight. +const orphanAge = time.Hour + +// SweepOrphanObjects deletes serving orgs' objects that no row claims: a blob whose delete +// failed after its commit, or one a late PUT wrote after GC or an erasure deleted it, and the +// parts of an upload with no pending session. Each is re-checked under its session lock, so a +// writer that still holds the lock claims first. Unknown provider age never deletes. +func SweepOrphanObjects(ctx context.Context, db *sql.DB, stores ObjectStores) (int, error) { + var now int64 + if err := db.QueryRowContext(ctx, `SELECT floor(extract(epoch FROM clock_timestamp()))::bigint`).Scan(&now); err != nil { + return 0, err + } + cutoff := time.Unix(now, 0).Add(-orphanAge) + rows, err := db.QueryContext(ctx, `SELECT id FROM orgs o WHERE `+OrgServes("o.id")+` ORDER BY id`) + if err != nil { + return 0, err + } + var orgs []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return 0, err + } + orgs = append(orgs, id) + } + rows.Close() + if err := rows.Err(); err != nil { + return 0, err + } + deleted := 0 + for _, org := range orgs { + store, err := stores(org) + if err != nil { + return deleted, err + } + blobs, uploads, err := store.Stored(ctx) + if err != nil { + return deleted, err + } + type orphan struct { + lock, claimed string + id string + drop func(context.Context, string) error + } + var due []orphan + for digest, at := range blobs { + if !at.IsZero() && at.Before(cutoff) { + due = append(due, orphan{BlobLockName(org, digest), `SELECT count(*) FROM blobs WHERE org_id=? AND digest=?`, digest, store.Delete}) + } + } + for id, at := range uploads { + if !at.IsZero() && at.Before(cutoff) { + due = append(due, orphan{"upload/" + id, `SELECT count(*) FROM upload_sessions WHERE org_id=? AND id=? AND status='pending'`, id, store.DeleteParts}) + } + } + for _, o := range due { + if deleted >= objectGCBatch { + return deleted, nil + } + ok, err := dropOrphan(ctx, db, org, o.lock, o.claimed, o.id, o.drop) + if err != nil { + return deleted, err + } + if ok { + deleted++ + } + } + } + return deleted, nil +} + +func dropOrphan(ctx context.Context, db *sql.DB, org, lock, claimed, id string, drop func(context.Context, string) error) (bool, error) { + lease, _, err := SessionLock(ctx, db, lock, true) + if err != nil { + return false, err + } + defer lease.Release() + var n int + if err := lease.QueryRow(claimed, org, id).Scan(&n); err != nil || n != 0 { + return false, err + } + return true, drop(lease.Context, id) } func sweepObject(ctx context.Context, db *sql.DB, stores ObjectStores, org, digest, cut string) (bool, error) { diff --git a/internal/storage/purge.go b/internal/storage/purge.go index 81aa06f9..7223d407 100644 --- a/internal/storage/purge.go +++ b/internal/storage/purge.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "time" + + "github.com/Busnes-app/kynotes-server/internal/blobstore" ) // purgeBatch is the most rows one purge transaction deletes, so no batch holds the writer @@ -99,8 +101,9 @@ func PurgeDeletedOrgs(ctx context.Context, db *sql.DB, objects PurgeObjects) err // PurgeOrg deletes every row of one deleted org in short batches behind a fail-closed audit row, // then marks its tombstone purged (spec, Lifecycle, Deleted). It is idempotent: a purge killed -// between batches finishes on its next run. After the rows, the org's object prefix goes; the -// tombstone is marked purged only once that delete succeeded. +// between batches finishes on its next run. After the rows, the org's object prefix goes, on +// every run. The tombstone is marked purged only by a run whose prefix delete started at least +// LatePutWindow after the purge fenced the org's writers, so a late PUT cannot outlive it. func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) error { if objects == nil { return errors.New("purge: no object store") // multi mode has no blobs anywhere else @@ -112,7 +115,8 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) if status != "deleted" || org == DefaultOrgID { return fmt.Errorf("purge: org is %s", status) } - if err := RecordAuditOutcome(db, "", "platform.org_purge_started", "", org, "success", "", "org-purge"); err != nil { + fenced, err := purgeFence(ctx, db, org) + if err != nil { return err // nothing is deleted without the record that the purge began } progress := "purge_rows:" + org + ":" @@ -122,9 +126,13 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) return fmt.Errorf("purge %s: %w", step.table, err) } } + waited := fenced >= int64(blobstore.LatePutWindow/time.Second) if err := objects(ctx, org); err != nil { return fmt.Errorf("purge objects: %w", err) } + if !waited { + return nil // a PUT admitted before the fence may still land; a later run deletes it + } tx, err := db.BeginTx(ctx, nil) if err != nil { return err @@ -152,6 +160,9 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) return err } } + if _, err = tx.ExecContext(ctx, `DELETE FROM server_settings WHERE key=?`, purgeFenceKey+org); err != nil { + return err + } if _, err = tx.ExecContext(ctx, `UPDATE orgs SET purged_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339), org); err != nil { return err } @@ -161,6 +172,47 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) return tx.Commit() } +const purgeFenceKey = "purge_fence:" + +// purgeFence returns the seconds, in database time, since the org's purge began. The first run +// records that time with the platform.org_purge_started audit, in one transaction. The org is +// deleted before then, so every writer admitted later is refused. +func purgeFence(ctx context.Context, db *sql.DB, org string) (int64, error) { + clock := `SELECT CAST(strftime('%s','now') AS INTEGER)` + if IsPostgres(db) { + clock = `SELECT floor(extract(epoch FROM clock_timestamp()))::bigint` + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + var now int64 + if err := tx.QueryRowContext(ctx, clock).Scan(&now); err != nil { + return 0, err + } + res, err := tx.ExecContext(ctx, `INSERT INTO server_settings(key,value,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO NOTHING`, purgeFenceKey+org, strconv.FormatInt(now, 10), time.Now().UTC().Format(time.RFC3339)) + if err != nil { + return 0, err + } + if n, err := res.RowsAffected(); err != nil { + return 0, err + } else if n == 1 { + if err := RecordAuditOutcomeTx(tx, "", "platform.org_purge_started", "", org, "success", "", "org-purge"); err != nil { + return 0, err + } + } + var since string + if err := tx.QueryRowContext(ctx, `SELECT value FROM server_settings WHERE key=?`, purgeFenceKey+org).Scan(&since); err != nil { + return 0, err + } + start, err := strconv.ParseInt(since, 10, 64) + if err != nil { + return 0, err + } + return now - start, tx.Commit() +} + // purgeTable deletes the step's rows in batches. When progress names a server_settings row, each // batch adds its count there in its own transaction. func purgeTable(ctx context.Context, db *sql.DB, step purgeStep, org, progress string) (int64, error) { diff --git a/internal/storage/purge_test.go b/internal/storage/purge_test.go index aa2ef12a..f7309c2f 100644 --- a/internal/storage/purge_test.go +++ b/internal/storage/purge_test.go @@ -151,7 +151,31 @@ func TestPurgeLeavesNoRowOfTheOrg(t *testing.T) { if err := PurgeDeletedOrgs(context.Background(), s.db, noObjects); err != nil { t.Fatal(err) } + var purgedAt string + var users, started int + if err := s.db.QueryRow(`SELECT purged_at,(SELECT count(*) FROM users WHERE org_id='org_b'),(SELECT count(*) FROM audit_events WHERE event='platform.org_purge_started' AND object_id='org_b') FROM orgs WHERE id='org_b'`).Scan(&purgedAt, &users, &started); err != nil || purgedAt != "" || users != 0 || started != 1 { + t.Fatalf("inside the late-PUT window: purged_at=%q users=%d started=%d %v", purgedAt, users, started, err) + } + if err := PurgeDeletedOrgs(context.Background(), s.db, noObjects); err != nil { + t.Fatal(err) + } + endPurgeWindow(t, s) + if err := PurgeDeletedOrgs(context.Background(), s.db, noObjects); err != nil { + t.Fatal(err) + } assertPurged(t, s, bIDs, before) + var fences int + if err := s.db.QueryRow(`SELECT (SELECT count(*) FROM server_settings WHERE key LIKE 'purge_fence:%'),(SELECT count(*) FROM audit_events WHERE event='platform.org_purge_started' AND object_id='org_b')`).Scan(&fences, &started); err != nil || fences != 0 || started != 1 { + t.Fatalf("fence rows=%d started audits=%d %v", fences, started, err) + } +} + +// endPurgeWindow moves every purge fence back past the late-PUT window. +func endPurgeWindow(t *testing.T, s *Store) { + t.Helper() + if _, err := s.db.Exec(`UPDATE server_settings SET value='0' WHERE key LIKE 'purge_fence:%'`); err != nil { + t.Fatal(err) + } } // A purge killed between batches finishes on its next run. @@ -175,6 +199,7 @@ func TestPurgeKilledBetweenBatchesFinishesNextRun(t *testing.T) { t.Fatalf("a killed purge marked the org purged: %q %v", purgedAt, err) } purgeBatchHook = func(string) error { return nil } + endPurgeWindow(t, s) if err := PurgeDeletedOrgs(context.Background(), s.db, noObjects); err != nil { t.Fatal(err) } From 72f3a6476b87a5cbd3894e25206e7e34b25f9bb9 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Tue, 24 Nov 2026 18:53:33 -0500 Subject: [PATCH 2/3] docs: state how the deadline mutation fails Co-Authored-By: Claude Opus 5.5 --- docs/superpowers/specs/2026-11-23-tenancy-design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 0e7f24b3..74910404 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1643,7 +1643,7 @@ The selected resolution is a time fence, with no new ledger: Tests: a PUT blocked at the provider times out at the client; the purge runs; the provider then stores the PUT. The purge must not be marked inside the window, and the run after it must -leave no key. Removing the window check fails it; removing the deadline hangs it to its limit. +leave no key. Removing the window check fails it; removing the deadline fails its 10-second guard. The orphan sweep keeps young, unknown-age, claimed, pending-upload and stopped-org objects. Mutations of the age check, the claim re-check and the pending-upload check each fail it. From ed3735bf6457d2abc49a0984028109d127a91eff Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Tue, 24 Nov 2026 22:21:36 -0500 Subject: [PATCH 3/3] fix(tenancy): re-admit each orphan deletion and purge step from current org state The orphan sweep decided from an org query read before the listing, so an org stopped meanwhile could lose objects. Each deletion now re-reads that the org serves, with the claim, in a short transaction under its session lock. The purge re-reads the status before the prefix delete and requires deleted when it marks the tombstone. The purge batch hook now runs after each commit. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- .../specs/2026-11-23-tenancy-design.md | 13 +++++-- internal/blobstore/object_runtime_test.go | 37 +++++++++++++++++++ internal/blobstore/objects_test.go | 7 ++++ internal/storage/object_gc.go | 22 +++++++++-- internal/storage/purge.go | 22 ++++++++--- internal/storage/purge_test.go | 37 +++++++++++++++++++ 7 files changed, 128 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 05ce34e0..8cb3abfb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -293,7 +293,8 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che Late-PUT fence: the purge's first run records `purge_fence:` (database time) with the started audit; it deletes the prefix every run but marks purged only on a run at least `blobstore.LatePutWindow` later. `SweepOrphanObjects` (inside `RunObjectGC`) deletes unclaimed - objects over an hour old by provider time, re-checked under their session lock. Verify + objects over an hour old by provider time; each deletion re-reads the claim and that the org + serves, under its session lock. The purge re-reads `deleted` before the prefix and at the mark. Verify `TestLatePutAfterPurge*` and `TestOrphanSweep*`. - Member erasure uses `CleanupFor(db).AdvanceSeq` and `TombstoneComment`, one fresh sequence per retained comment so paginated sync delivers every deletion. Directory erasure runs only in multi diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 74910404..e833ae37 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1634,10 +1634,14 @@ The selected resolution is a time fence, with no new ledger: - The purge's first run inserts `purge_fence:` in database time with the `platform.org_purge_started` audit, in one transaction (the audit is now written once). Every run deletes the rows and the prefix. Only a run that read the fence at least the window old - before its prefix delete marks the tombstone purged and removes the fence. + before its prefix delete marks the tombstone purged and removes the fence. The status is + re-read before the prefix delete, and the mark requires `status='deleted'` in its own + transaction. - `SweepOrphanObjects` runs at the end of `RunObjectGC`. For each serving org it lists the - prefix with provider times and deletes, under the blob or upload session lock, any blob with - no row and any upload with no pending session, once over an hour old. Zero (unknown) age + prefix with provider times and deletes any blob with no row and any upload with no pending + session, once over an hour old. Each deletion is admitted under the blob or upload session + lock, in a short transaction that re-reads both the claim and whether the org still serves. + An org stopped during the listing keeps its objects. Zero (unknown) age never deletes; at most 100 a pass. - The shared client pin moved to the #78 merge (`b55ca6d`) for `LastModified`. @@ -1646,6 +1650,9 @@ then stores the PUT. The purge must not be marked inside the window, and the run leave no key. Removing the window check fails it; removing the deadline fails its 10-second guard. The orphan sweep keeps young, unknown-age, claimed, pending-upload and stopped-org objects. Mutations of the age check, the claim re-check and the pending-upload check each fail it. +`TestOrphanSweepKeepsObjectsOfAnOrgStoppedDuringTheListing` suspends the org from inside the +provider listing; it fails without the in-lock serving re-check. +`TestPurgeRereadsTheStatusBeforeThePrefixAndTheMark` fails without either status re-read. Unproven: that a selected provider honors request age and commits no PUT past the window (provider qualification), and clock skew between provider and database beyond a few minutes. diff --git a/internal/blobstore/object_runtime_test.go b/internal/blobstore/object_runtime_test.go index 71838a82..610ed841 100644 --- a/internal/blobstore/object_runtime_test.go +++ b/internal/blobstore/object_runtime_test.go @@ -374,3 +374,40 @@ func TestOrphanSweepDeletesOnlyOldUnclaimedObjects(t *testing.T) { } } } + +// An org stopped while the sweep lists its prefix keeps its orphans: each deletion re-admits +// the org under the session lock, not from the earlier org query. +func TestOrphanSweepKeepsObjectsOfAnOrgStoppedDuringTheListing(t *testing.T) { + db := runtimeDatabase(t) + fixture, client := newObjectFixture(t) + old := time.Now().Add(-2 * time.Hour) + body := "orphan of an org about to stop" + d := objectDigest([]byte(body)) + store := objectStore(t, client, "org_a", t.TempDir()) + if err := store.Put(t.Context(), d, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + upload, err := ids.Mint("ups") + if err != nil { + t.Fatal(err) + } + if err := store.PutPart(t.Context(), upload, 0, strings.NewReader("chunk"), 5); err != nil { + t.Fatal(err) + } + blobKey, _ := blobstore.BlobKey("org_a", d) + partKey, _ := blobstore.UploadPartKey("org_a", upload, 0) + fixture.mu.Lock() + fixture.modified[blobKey], fixture.modified[partKey] = old, old + fixture.onList = func() { + if _, err := db.Exec(`UPDATE orgs SET status='suspended' WHERE id='org_a'`); err != nil { + t.Error(err) + } + } + fixture.mu.Unlock() + if n, err := storage.SweepOrphanObjects(t.Context(), db, stores(t, client)); err != nil || n != 0 { + t.Fatalf("swept=%d err=%v", n, err) + } + if keys := orgKeys(fixture, "org_a"); len(keys) != 2 { + t.Fatalf("a stopped org lost objects: %v", keys) + } +} diff --git a/internal/blobstore/objects_test.go b/internal/blobstore/objects_test.go index 2157c439..15d1077a 100644 --- a/internal/blobstore/objects_test.go +++ b/internal/blobstore/objects_test.go @@ -41,6 +41,7 @@ type objectFixture struct { gzipKey string getEncoding string modified map[string]time.Time // provider age; absent is unknown + onList func() // runs during each listing, outside the lock } func newObjectFixture(t *testing.T) (*objectFixture, *shareds3.Client) { @@ -75,6 +76,12 @@ func (f *objectFixture) serve(w http.ResponseWriter, r *http.Request) { return } if r.Method == http.MethodGet && key == "" { + f.mu.Lock() + onList := f.onList + f.mu.Unlock() + if onList != nil { + onList() + } f.mu.Lock() keys := []string{} for k := range f.objects { diff --git a/internal/storage/object_gc.go b/internal/storage/object_gc.go index a61e5baf..b4b3dba4 100644 --- a/internal/storage/object_gc.go +++ b/internal/storage/object_gc.go @@ -79,8 +79,9 @@ const orphanAge = time.Hour // SweepOrphanObjects deletes serving orgs' objects that no row claims: a blob whose delete // failed after its commit, or one a late PUT wrote after GC or an erasure deleted it, and the -// parts of an upload with no pending session. Each is re-checked under its session lock, so a -// writer that still holds the lock claims first. Unknown provider age never deletes. +// parts of an upload with no pending session. Each deletion is admitted under its session lock +// (the org still serves, no claim), so a writer that holds the lock claims first and an org +// stopped after the listing keeps its objects. Unknown provider age never deletes. func SweepOrphanObjects(ctx context.Context, db *sql.DB, stores ObjectStores) (int, error) { var now int64 if err := db.QueryRowContext(ctx, `SELECT floor(extract(epoch FROM clock_timestamp()))::bigint`).Scan(&now); err != nil { @@ -152,8 +153,21 @@ func dropOrphan(ctx context.Context, db *sql.DB, org, lock, claimed, id string, return false, err } defer lease.Release() - var n int - if err := lease.QueryRow(claimed, org, id).Scan(&n); err != nil || n != 0 { + // Admit under the lock, in a short transaction (N3) that serialises with the org poll's + // status write: the org still serves and nothing claims the object. No I/O holds N3. + tx, err := lease.Begin() + if err != nil { + return false, err + } + defer tx.Rollback() + var serving, n int + if err := tx.QueryRow(`SELECT count(*) FROM orgs o WHERE o.id=? AND `+OrgServes("o.id"), org).Scan(&serving); err != nil || serving == 0 { + return false, err + } + if err := tx.QueryRow(claimed, org, id).Scan(&n); err != nil || n != 0 { + return false, err + } + if err := tx.Commit(); err != nil { return false, err } return true, drop(lease.Context, id) diff --git a/internal/storage/purge.go b/internal/storage/purge.go index 7223d407..6414b533 100644 --- a/internal/storage/purge.go +++ b/internal/storage/purge.go @@ -127,6 +127,14 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) } } waited := fenced >= int64(blobstore.LatePutWindow/time.Second) + // The batches take time and a run can wait out the window: re-read the status before the + // prefix goes, and again when marking it purged. + if err := db.QueryRowContext(ctx, `SELECT status FROM orgs WHERE id=?`, org).Scan(&status); err != nil { + return err + } + if status != "deleted" { + return fmt.Errorf("purge: org is %s", status) + } if err := objects(ctx, org); err != nil { return fmt.Errorf("purge objects: %w", err) } @@ -163,9 +171,13 @@ func PurgeOrg(ctx context.Context, db *sql.DB, objects PurgeObjects, org string) if _, err = tx.ExecContext(ctx, `DELETE FROM server_settings WHERE key=?`, purgeFenceKey+org); err != nil { return err } - if _, err = tx.ExecContext(ctx, `UPDATE orgs SET purged_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339), org); err != nil { + res, err := tx.ExecContext(ctx, `UPDATE orgs SET purged_at=? WHERE id=? AND status='deleted'`, time.Now().UTC().Format(time.RFC3339), org) + if err != nil { return err } + if n, err := res.RowsAffected(); err != nil || n != 1 { + return errors.Join(err, errors.New("purge: org is no longer deleted")) + } if err = RecordAuditOutcomeTx(tx, "", "platform.org_deleted", "", org, "success", strings.Join(counts, ","), "org-purge"); err != nil { return err } @@ -239,9 +251,6 @@ func purgeTable(ctx context.Context, db *sql.DB, step purgeStep, org, progress s _, err = tx.ExecContext(ctx, `INSERT INTO server_settings(key,value,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value=CAST(CAST(server_settings.value AS BIGINT)+? AS TEXT)`, progress, strconv.FormatInt(n, 10), time.Now().UTC().Format(time.RFC3339), n) } } - if err == nil { - err = purgeBatchHook(step.table) - } if err == nil { err = tx.Commit() } @@ -250,13 +259,16 @@ func purgeTable(ctx context.Context, db *sql.DB, step purgeStep, org, progress s return total, err } total += n + if err := purgeBatchHook(step.table); err != nil { + return total, err + } if n < int64(purgeBatch) { return total, nil } } } -// purgeBatchHook lets a test kill a purge between batches. +// purgeBatchHook runs after each committed batch, so a test can kill a purge between batches. var purgeBatchHook = func(string) error { return nil } const ( diff --git a/internal/storage/purge_test.go b/internal/storage/purge_test.go index f7309c2f..fd3e41e2 100644 --- a/internal/storage/purge_test.go +++ b/internal/storage/purge_test.go @@ -354,3 +354,40 @@ func TestPurgeRefusesWithoutObjectsAndKeepsTheOrgUnpurged(t *testing.T) { t.Fatalf("org marked purged with its objects left: %q %v", purgedAt, err) } } + +// An org no longer deleted when the batches end keeps its objects, and one that changes during +// the prefix delete is not marked purged: both decisions re-read the status. +func TestPurgeRereadsTheStatusBeforeThePrefixAndTheMark(t *testing.T) { + s, _, _ := purgeFixture(t) + endPurgeWindow(t, s) + restore := func() { + if _, err := s.db.Exec(`UPDATE orgs SET status='active' WHERE id='org_b'`); err != nil { + t.Error(err) + } + } + purgeBatchHook = func(table string) error { + if table == "users" { + restore() + } + return nil + } + t.Cleanup(func() { purgeBatchHook = func(string) error { return nil } }) + called := false + objects := func(context.Context, string) error { called = true; return nil } + if err := PurgeOrg(context.Background(), s.db, objects, "org_b"); err == nil || called { + t.Fatalf("prefix deleted for an org no longer deleted: err=%v called=%v", err, called) + } + purgeBatchHook = func(string) error { return nil } + if _, err := s.db.Exec(`UPDATE orgs SET status='deleted' WHERE id='org_b'`); err != nil { + t.Fatal(err) + } + endPurgeWindow(t, s) + flip := func(context.Context, string) error { restore(); return nil } + if err := PurgeOrg(context.Background(), s.db, flip, "org_b"); err == nil { + t.Fatal("an org restored during the prefix delete was marked purged") + } + var purgedAt string + if err := s.db.QueryRow(`SELECT purged_at FROM orgs WHERE id='org_b'`).Scan(&purgedAt); err != nil || purgedAt != "" { + t.Fatalf("purged_at=%q %v", purgedAt, err) + } +}