From 8fbddb82dca995f9c878bac7f7ccd030a6b7c8c1 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Tue, 24 Nov 2026 16:59:57 -0500 Subject: [PATCH] feat(tenancy): sweep and purge primary objects per org RunObjectGC is the multi-mode blob sweep: per (org_id, digest), under the blob session lock, rows commit before the object delete. The purge now deletes the org's object prefix and marks the tombstone purged only after that succeeds. Startup stays refused; binding comes with enablement. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 + DESIGN.md | 6 +- .../specs/2026-11-23-tenancy-design.md | 14 ++ internal/app/replica_schedules.go | 6 +- internal/blobstore/AGENTS.md | 5 +- internal/blobstore/object_runtime_test.go | 222 ++++++++++++++++++ internal/storage/charged_test.go | 2 +- internal/storage/object_gc.go | 109 +++++++++ internal/storage/purge.go | 20 +- internal/storage/purge_test.go | 28 ++- 10 files changed, 401 insertions(+), 15 deletions(-) create mode 100644 internal/blobstore/object_runtime_test.go create mode 100644 internal/storage/object_gc.go diff --git a/AGENTS.md b/AGENTS.md index 6a1c016f..2fe43fd9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -286,6 +286,10 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che A new table with a foreign key to a purged table must join it (`TestPurgeOrderCoversEveryCascade` reads the backend's foreign keys). Verify `TestPurgeLeavesNoRowOfTheOrg` (no value of the deleted org left in any table, the other org untouched) and `TestPurgeKilledBetweenBatchesFinishesNextRun`. + The purge takes the org's object-prefix delete (`storage.PurgeObjects`); without one, or if it + 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. - 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 a5bd149a..79e2b7dc 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -951,8 +951,10 @@ fingerprinted. The elected schedule adapter owns minute lifecycle/reminder/backu configured GC cadence and per-tick pool reporting. Proxy drain withdraws readiness and cancels work before five seconds of convergence, five seconds of HTTP drain and ten of worker drain. -These adapters are preparation for phase 6, not startup enablement. Real primary-object GC and -PostgreSQL backup/restore adapters are still prerequisites. Restore preserves permanent store +These adapters are preparation for phase 6, not startup enablement. `storage.RunObjectGC` is the +primary-object GC (per org and digest, under the blob session lock, rows before object) and the +purge deletes the org's object prefix before it marks the tombstone purged; startup binds them +later. PostgreSQL backup/restore adapters are still prerequisites. Restore preserves permanent store identity and clears ephemeral probe pointers so retired probe GC cannot strand a restored DB. Tests cover key/path isolation, identity races/private-store refusal/crash recovery, environment key/fingerprint boundaries, schedule ownership/cadence, drain and alternating-replica upload diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 166e078d..be8b50ec 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1605,6 +1605,20 @@ do not select a Notes ledger/protocol. Keep this and native-PG recovery open que explicit remaining gates, alongside store controls/age/provider proof and lifecycle E2E. +### PR 5b-3 as built: object GC and org purge (startup still refused) + +`storage.RunObjectGC` is the multi-mode blob sweep. Candidates and the in-lock re-check are per +`(org_id, digest)` with org-qualified references, at most 100 a pass, serving orgs only. Each +blob takes `BlobLockName(org, digest)`, deletes its rows in a short transaction on that +connection, commits, then deletes every version of the object. A failed delete leaves an +object with no row. `PurgeOrg` takes a `PurgeObjects` step and refuses without one; it deletes +the `orgs//` prefix after the rows and marks the tombstone purged only on success. +Tests use the real shared client over the local TLS fixture on PostgreSQL. Each property fails +under mutation: org-blind candidates, no re-check, object delete before commit, purge without +the prefix step. The schedule adapter carries the purge step; startup binding, the late-PUT +fence and the orphan sweep are separate. + + ### 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/internal/app/replica_schedules.go b/internal/app/replica_schedules.go index b5f3d3c7..5fd64d72 100644 --- a/internal/app/replica_schedules.go +++ b/internal/app/replica_schedules.go @@ -18,7 +18,8 @@ import ( ) // replicaSchedules is the application adapter, not another scheduler. The eventual multi -// startup supplies its object-GC and PostgreSQL-backup operations only after those exist. +// startup binds gc to storage.RunObjectGC and purge to the org's blobstore.Objects.Purge, and +// supplies PostgreSQL backup once it exists. // Until then config.Load refuses multi; the single-mode loops stay unchanged. type replicaSchedules struct { db *sql.DB @@ -28,6 +29,7 @@ type replicaSchedules struct { push *webpush.Sender gcInterval time.Duration gc func(context.Context, time.Time) error + purge storage.PurgeObjects backup func(context.Context, time.Time) error log *logging.Logger minute, gcAt time.Time @@ -50,7 +52,7 @@ func (s *replicaSchedules) tick(owned context.Context, now time.Time) { s.minute = now.Add(time.Minute) // count attempts, including failures run("org_poll", func() error { return s.orgs.Poll(owned) }) run("erased_poll", func() error { return httpapi.PollErased(owned, s.db, s.directory) }) - run("org_purge", func() error { return storage.PurgeDeletedOrgs(owned, s.db) }) + run("org_purge", func() error { return storage.PurgeDeletedOrgs(owned, s.db, s.purge) }) run("member_erase", func() error { return storage.EraseMembers(owned, s.db) }) run("shared_state", func() error { return storage.SweepSharedState(owned, s.db) }) run("reminders", func() error { return s.push.Fire(owned, s.db, now) }) diff --git a/internal/blobstore/AGENTS.md b/internal/blobstore/AGENTS.md index 41a9aba5..0a8ac174 100644 --- a/internal/blobstore/AGENTS.md +++ b/internal/blobstore/AGENTS.md @@ -9,7 +9,8 @@ Own opaque blob streams, single-volume compatibility and the tenancy blob seam. - `Backend`/`Temporary` are the product's storage seam; they do not expose filesystem handles. - `Objects` owns the prepared per-org permanent ciphertext and numbered upload-part I/O through the exported shared S3 client. It is not yet the complete `Backend`/`Temporary` - runtime adapter: exclusive control creation, age metadata, GC and route wiring remain gated. + runtime adapter: exclusive control creation, age metadata and route wiring remain gated. + `storage.RunObjectGC` and the purge's prefix step call it from the elected worker. - `Store`/`Temp` retain the single-tenant volume implementation and paths. - Key helpers own validation of org/blob/part path components. - `VerifySharedIdentity` owns N15 control-file identity/probe decisions; the real object adapter @@ -51,6 +52,8 @@ Own opaque blob streams, single-volume compatibility and the tenancy blob seam. ## Verification - `go test -race -count=1 ./internal/blobstore` +- `TestObjectGC*`/`TestPurgeDeletesOnlyTheDeletedOrgsPrefix` drive storage's GC and purge through + the real shared client on PostgreSQL. - `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/object_runtime_test.go b/internal/blobstore/object_runtime_test.go new file mode 100644 index 00000000..2c4c20d2 --- /dev/null +++ b/internal/blobstore/object_runtime_test.go @@ -0,0 +1,222 @@ +package blobstore_test + +import ( + "bytes" + "context" + "database/sql" + "testing" + "time" + + shareds3 "github.com/Busnes-app/ky-primitives/s3" + "github.com/Busnes-app/kynotes-server/internal/blobstore" + "github.com/Busnes-app/kynotes-server/internal/ids" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// runtimeDatabase is a multi-mode PostgreSQL install serving org_a and org_b in region eu, +// each with one user, notebook and page. +func runtimeDatabase(t *testing.T) *sql.DB { + t.Helper() + db := identityDatabase(t) + for _, q := range []string{ + `INSERT INTO server_settings(key,value,updated_at) VALUES('region','eu','t'),('staff_org_id','org_staff','t')`, + `INSERT INTO orgs(id,status,home_region) VALUES('org_a','active','eu'),('org_b','active','eu')`, + `INSERT INTO users(id,username,auth_secret_hash,login_salt,login_iterations,created_at,updated_at,org_id) VALUES('usr_a','a','x','x',1,'t','t','org_a'),('usr_b','b','x','x',1,'t','t','org_b')`, + `INSERT INTO containers(id,kind,owner_user_id,created_at,updated_at,org_id) VALUES('cnt_a','workbook','usr_a','t','t','org_a'),('cnt_b','workbook','usr_b','t','t','org_b')`, + `INSERT INTO objects(id,container_id,kind,change_seq,created_at,updated_at) VALUES('obj_a','cnt_a','note',1,'t','t'),('obj_b','cnt_b','note',1,'t','t')`, + } { + if _, err := db.Exec(q); err != nil { + t.Fatalf("%.60s: %v", q, err) + } + } + return db +} + +// putBlob stores body for org as an unreferenced blob marked two hours ago. +func putBlob(t *testing.T, db *sql.DB, client *shareds3.Client, org string, body []byte, now time.Time) string { + t.Helper() + digest := objectDigest(body) + if err := objectStore(t, client, org, t.TempDir()).Put(t.Context(), digest, bytes.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO blobs(org_id,digest,size_bytes,created_at,unreferenced_since) VALUES(?,?,?,'t',?)`, org, digest, len(body), now.Add(-2*time.Hour).Format(time.RFC3339)); err != nil { + t.Fatal(err) + } + return digest +} + +func stores(t *testing.T, client *shareds3.Client) storage.ObjectStores { + dir := t.TempDir() + return func(org string) (*blobstore.Objects, error) { return blobstore.NewObjects(client, org, dir, 64) } +} + +func objectExists(t *testing.T, client *shareds3.Client, org, digest string) bool { + t.Helper() + _, ok, err := objectStore(t, client, org, t.TempDir()).Stat(t.Context(), digest) + if err != nil { + t.Fatal(err) + } + return ok +} + +func blobRow(t *testing.T, db *sql.DB, org, digest string) bool { + t.Helper() + var n int + if err := db.QueryRow(`SELECT count(*) FROM blobs WHERE org_id=? AND digest=?`, org, digest).Scan(&n); err != nil { + t.Fatal(err) + } + return n == 1 +} + +// The same ciphertext in two orgs is two objects: GC of one org's unreferenced copy keeps the +// other org's referenced copy, its row and its object. +func TestObjectGCSweepsOnlyTheUnreferencedOrgsCopy(t *testing.T) { + db := runtimeDatabase(t) + _, client := newObjectFixture(t) + now := time.Now() + body := []byte("same ciphertext") + d := putBlob(t, db, client, "org_a", body, now) + putBlob(t, db, client, "org_b", body, now) + if _, err := db.Exec(`INSERT INTO object_versions(object_id,version,blob_digest,ciphertext_bytes,key_generation,change_seq,created_at,org_id) VALUES('obj_b',1,?,1,1,1,'t','org_b')`, d); err != nil { + t.Fatal(err) + } + n, err := storage.RunObjectGC(t.Context(), db, stores(t, client), now, time.Hour) + if err != nil || n != 1 { + t.Fatalf("deleted=%d err=%v", n, err) + } + if blobRow(t, db, "org_a", d) || objectExists(t, client, "org_a", d) { + t.Fatal("org_a's unreferenced blob survived") + } + if !blobRow(t, db, "org_b", d) || !objectExists(t, client, "org_b", d) { + t.Fatal("org_b's referenced blob was swept with org_a's") + } + var mark string + if err := db.QueryRow(`SELECT unreferenced_since FROM blobs WHERE org_id='org_b' AND digest=?`, d).Scan(&mark); err != nil || mark != "" { + t.Fatalf("referenced blob kept its mark %q %v", mark, err) + } +} + +// A save holding the blob's session lock commits its claim before GC's re-check, so GC keeps it. +func TestObjectGCWaitsForTheBlobLockAndRechecks(t *testing.T) { + db := runtimeDatabase(t) + _, client := newObjectFixture(t) + now := time.Now() + d := putBlob(t, db, client, "org_a", []byte("claimed during gc"), now) + lease, _, err := storage.SessionLock(t.Context(), db, storage.BlobLockName("org_a", d), true) + if err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + n, err := storage.RunObjectGC(t.Context(), db, stores(t, client), now, time.Hour) + if err == nil && n != 0 { + err = context.Canceled + } + done <- err + }() + select { + case err := <-done: + lease.Release() + t.Fatal("GC ran without the blob lock", err) + case <-time.After(300 * time.Millisecond): + } + if _, err := lease.Exec(`INSERT INTO object_versions(object_id,version,blob_digest,ciphertext_bytes,key_generation,change_seq,created_at,org_id) VALUES('obj_a',1,?,1,1,1,'t','org_a')`, d); err != nil { + t.Fatal(err) + } + lease.Release() + if err := <-done; err != nil { + t.Fatal("GC swept a claimed blob or failed:", err) + } + if !blobRow(t, db, "org_a", d) || !objectExists(t, client, "org_a", d) { + t.Fatal("claimed blob lost") + } +} + +// Rows commit before the object delete; a failed delete leaves an object with no row (storage +// only), never a row with no object. +func TestObjectGCDeleteFailureLeavesNoRowPointingAtAMissingObject(t *testing.T) { + db := runtimeDatabase(t) + fixture, client := newObjectFixture(t) + now := time.Now() + d := putBlob(t, db, client, "org_a", []byte("delete fails"), now) + fixture.mu.Lock() + fixture.failures["DELETE"] = 503 + fixture.mu.Unlock() + if _, err := storage.RunObjectGC(t.Context(), db, stores(t, client), now, time.Hour); err == nil { + t.Fatal("a failed object delete reported success") + } + fixture.mu.Lock() + delete(fixture.failures, "DELETE") + fixture.mu.Unlock() + if blobRow(t, db, "org_a", d) || !objectExists(t, client, "org_a", d) { + t.Fatal("want the row gone and the object left") + } +} + +func TestObjectGCWaitsWhileTheOrgIsStoppedAndRefusesSingleMode(t *testing.T) { + db := runtimeDatabase(t) + _, client := newObjectFixture(t) + now := time.Now() + d := putBlob(t, db, client, "org_a", []byte("suspended"), now) + if _, err := db.Exec(`UPDATE orgs SET status='suspended' WHERE id='org_a'`); err != nil { + t.Fatal(err) + } + if n, err := storage.RunObjectGC(t.Context(), db, stores(t, client), now, time.Hour); err != nil || n != 0 { + t.Fatalf("a suspended org's blob was swept: %d %v", n, err) + } + if !blobRow(t, db, "org_a", d) || !objectExists(t, client, "org_a", d) { + t.Fatal("suspended org's blob lost") + } + if _, err := db.Exec(`UPDATE server_settings SET value='single' WHERE key='tenancy_mode'`); err != nil { + t.Fatal(err) + } + if _, err := storage.RunObjectGC(t.Context(), db, stores(t, client), now, time.Hour); err == nil { + t.Fatal("object GC ran in single mode") + } +} + +// A deleted org's purge erases its whole prefix (blobs and upload parts) and nothing of another +// org's, even for identical ciphertext. +func TestPurgeDeletesOnlyTheDeletedOrgsPrefix(t *testing.T) { + db := runtimeDatabase(t) + fixture, client := newObjectFixture(t) + now := time.Now() + body := []byte("purged ciphertext") + d := putBlob(t, db, client, "org_b", body, now) + putBlob(t, db, client, "org_a", body, now) + upload, err := ids.Mint("ups") + if err != nil { + t.Fatal(err) + } + if err := objectStore(t, client, "org_b", t.TempDir()).PutPart(t.Context(), upload, 0, bytes.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + 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) + if err != nil { + return err + } + return s.Purge(ctx) + } + 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) + } + } + 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") + } + 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) + } +} diff --git a/internal/storage/charged_test.go b/internal/storage/charged_test.go index fc5a717a..2eaff18a 100644 --- a/internal/storage/charged_test.go +++ b/internal/storage/charged_test.go @@ -49,7 +49,7 @@ 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, "org_b"); err != nil { + if err := PurgeOrg(context.Background(), s.db, noObjects, "org_b"); err != nil { t.Fatal(err) } var n int diff --git a/internal/storage/object_gc.go b/internal/storage/object_gc.go new file mode 100644 index 00000000..f0d9526b --- /dev/null +++ b/internal/storage/object_gc.go @@ -0,0 +1,109 @@ +package storage + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/Busnes-app/kynotes-server/internal/blobstore" +) + +// ObjectStores resolves one org's primary-object store. Only the elected multi-mode worker +// calls it, with org IDs read from blob rows. +type ObjectStores func(org string) (*blobstore.Objects, error) + +// objectGCBatch caps one pass (spec, Blobs in S3-compatible storage: Delete). +const objectGCBatch = 100 + +// orgUnreferenced is unreferenced for one org's blob b: in multi mode a digest is per org (N8). +const orgUnreferenced = `NOT EXISTS(SELECT 1 FROM object_versions v WHERE v.org_id=b.org_id AND v.blob_digest=b.digest) AND NOT EXISTS(SELECT 1 FROM conflicts c WHERE c.org_id=b.org_id AND c.blob_digest=b.digest AND c.resolved_at='') AND NOT EXISTS(SELECT 1 FROM attachments a WHERE a.org_id=b.org_id AND (a.blob_digest=b.digest OR a.preview_digest=b.digest) AND (a.deleted_at='' OR EXISTS(SELECT 1 FROM attachment_refs r WHERE r.attachment_id=a.id)))` + +// BlobLockName is the org-and-digest session lock (N3) every save, claim and delete of one +// object takes around its I/O and short write transaction. +func BlobLockName(org, digest string) string { return "blob/" + org + "/" + digest } + +// RunObjectGC is RunGC's blob sweep for multi mode, where blobs live in object storage keyed +// by org. Each blob is re-checked and its rows deleted under its session lock, committed, and +// only then is the object deleted, still under the lock. A delete that fails after the commit +// leaves an object with no row; that costs storage only. +func RunObjectGC(ctx context.Context, db *sql.DB, stores ObjectStores, now time.Time, retention time.Duration) (int, error) { + tenancy, err := TenancyOfContext(ctx, db) + if err != nil { + return 0, err + } + if !tenancy.Multi() || !IsPostgres(db) { + return 0, errors.New("object gc: multi mode on PostgreSQL only") + } + cut := now.Add(-retention).UTC().Format(time.RFC3339) + rows, err := db.QueryContext(ctx, `SELECT org_id,digest FROM blobs b WHERE unreferenced_since!='' AND unreferenced_since