Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
6 changes: 4 additions & 2 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions docs/superpowers/specs/2026-11-23-tenancy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<org_id>/` 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
Expand Down
6 changes: 4 additions & 2 deletions internal/app/replica_schedules.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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) })
Expand Down
5 changes: 4 additions & 1 deletion internal/blobstore/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
222 changes: 222 additions & 0 deletions internal/blobstore/object_runtime_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
2 changes: 1 addition & 1 deletion internal/storage/charged_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading