package store import ( "testing" "time" ) // d73Seed gives a box rows in the three box-keyed tables that had no delete, and its household rows in the three // household-keyed ones — plus the hub's own alarm marks that name the box. func d73Seed(t *testing.T, s *Store, hostID, customerID string) { t.Helper() exec := func(q string, a ...any) { t.Helper() if _, err := s.db.Exec(q, a...); err != nil { t.Fatalf("seed %q: %v", q, err) } } exec(`INSERT INTO os_host_settings (host_id, ring, enabled) VALUES (?, 0, 1)`, hostID) exec(`INSERT INTO os_reports (host_id, layer, outcome, report_json) VALUES (?, 'host', 'nothing', '{}')`, hostID) exec(`INSERT INTO os_reports (host_id, layer, outcome, report_json) VALUES (?, 'kernel', 'applied', '{}')`, hostID) exec(`INSERT INTO os_kernel_notices (host_id, kver, sent_at) VALUES (?, '7.0.14-22-pve', datetime('now'))`, hostID) exec(`INSERT INTO offsite_keys (customer_id, fingerprint) VALUES (?, 'SHA256:x')`, customerID) exec(`INSERT INTO offsite_windows (customer_id, closes_by) VALUES (?, datetime('now'))`, customerID) exec(`INSERT INTO offsite_abandon_requests (customer_id, path, due_at) VALUES (?, '.orphaned-1', datetime('now'))`, customerID) exec(`INSERT INTO operator_actions (customer_id, host_id, action, requested_at) VALUES (?, ?, 'rerun_backup', datetime('now'))`, customerID, hostID) for _, k := range []string{"box_clock:" + hostID + ":ahead", "pve_trust:" + hostID + ":ca_copy_does_not_verify", "guest_power:" + hostID + ":9201", "signed_job_wait:" + hostID + ":job1", "wg_stale:" + hostID} { if err := s.SetOSAlarmRaised(k, time.Now()); err != nil { t.Fatal(err) } } } func d73Count(t *testing.T, s *Store, q string, args ...any) int { t.Helper() var n int if err := s.db.QueryRow(q, args...).Scan(&n); err != nil { t.Fatalf("count %q: %v", q, err) } return n } func d73Counts(t *testing.T, s *Store, hostID, customerID string) map[string]int { t.Helper() return map[string]int{ "os_host_settings": d73Count(t, s, `SELECT COUNT(*) FROM os_host_settings WHERE host_id = ?`, hostID), "os_reports": d73Count(t, s, `SELECT COUNT(*) FROM os_reports WHERE host_id = ?`, hostID), "os_kernel_notices": d73Count(t, s, `SELECT COUNT(*) FROM os_kernel_notices WHERE host_id = ?`, hostID), "alarm marks": d73Count(t, s, `SELECT COUNT(*) FROM hub_settings WHERE key LIKE 'os_alarm:%' AND instr(key, ?) > 0`, hostID), "offsite_keys": d73Count(t, s, `SELECT COUNT(*) FROM offsite_keys WHERE customer_id = ?`, customerID), "offsite_windows": d73Count(t, s, `SELECT COUNT(*) FROM offsite_windows WHERE customer_id = ?`, customerID), "offsite_abandon_requests": d73Count(t, s, `SELECT COUNT(*) FROM offsite_abandon_requests WHERE customer_id = ?`, customerID), "operator_actions": d73Count(t, s, `SELECT COUNT(*) FROM operator_actions WHERE customer_id = ?`, customerID), } } var d73BoxTables = []string{"os_host_settings", "os_reports", "os_kernel_notices", "alarm marks"} var d73HouseholdTables = []string{"offsite_keys", "offsite_windows", "offsite_abandon_requests"} // D73 (`09` §3 decision 293, R-1376): deleting a BOX deletes its rows in the three box-keyed tables that had no // delete statement, and the hub's alarm marks that name it. The household's rows stay (the household is still // there), the other box is untouched — also one whose id only STARTS with this box's id — and the delete journal has // its row. COMPANION RED-PROOFS (observed, audits/night-build-2026-11-14/B/redproof-hub-d73.txt). func TestD73_DeleteHostRemovesTheBoxesRows(t *testing.T) { s := newTestStore(t) for _, h := range []struct{ host, cust string }{{"box-a1", "cust-a"}, {"box-a1b", "cust-b"}, {"x-box-a1", "cust-c"}} { if err := s.UpsertHost(&Host{HostID: h.host, CustomerID: h.cust, APIKey: "k-" + h.host}); err != nil { t.Fatal(err) } d73Seed(t, s, h.host, h.cust) } before := d73Counts(t, s, "box-a1", "cust-a") for table, n := range before { if n == 0 { t.Fatalf("fixture gap: %s has no row", table) } } otherB, otherC := d73Counts(t, s, "box-a1b", "cust-b"), d73Counts(t, s, "x-box-a1", "cust-c") if err := s.DeleteHost("box-a1", true); err != nil { t.Fatal(err) } after := d73Counts(t, s, "box-a1", "cust-a") // "alarm marks" counts by a substring, so the two look-alike boxes' marks (box-a1b, x-box-a1) are in it: those // must be all that is left. lookAlikes := 2 * 5 for _, table := range d73BoxTables { want := 0 if table == "alarm marks" { want = lookAlikes } if after[table] != want { t.Errorf("%s: %d row(s) left for the deleted box (want %d)", table, after[table], want) } } for _, table := range append(d73HouseholdTables, "operator_actions") { if after[table] != before[table] { t.Errorf("%s: %d → %d — a box delete must leave the HOUSEHOLD's rows (the household still exists)", table, before[table], after[table]) } } for name, pair := range map[string][2]map[string]int{"box-a1b": {otherB, d73Counts(t, s, "box-a1b", "cust-b")}, "x-box-a1": {otherC, d73Counts(t, s, "x-box-a1", "cust-c")}} { for _, table := range []string{"os_host_settings", "os_reports", "os_kernel_notices", "offsite_keys", "operator_actions"} { if pair[0][table] != pair[1][table] { t.Errorf("another box (%s) lost rows in %s: %d → %d", name, table, pair[0][table], pair[1][table]) } } if n := d73Count(t, s, `SELECT COUNT(*) FROM hub_settings WHERE key LIKE 'os_alarm:%' AND (instr(key, ':'||?||':') > 0 OR key LIKE '%:'||?)`, name, name); n != 5 { t.Errorf("another box (%s) has %d alarm mark(s) left, want its 5", name, n) } } if n := d73Count(t, s, `SELECT COUNT(*) FROM host_deletions WHERE host_id = 'box-a1'`); n != 1 { t.Errorf("the delete journal has %d row(s) for the box, want 1 — the journal STAYS", n) } } // Deleting a HOUSEHOLD (the purge leg) deletes its rows in the three household-keyed tables, counts them in the // preview's residue, and leaves the two journals alone. The operator's action log is an audit record: it stays at the // purge and goes with the audit rows one year after the deletion. func TestD73_PurgeRemovesTheHouseholdsRows_JournalStays(t *testing.T) { s := newTestStore(t) for _, c := range []string{"cust-a", "cust-b"} { if err := s.SaveCustomerConfig(&CustomerConfig{CustomerID: c, APIKey: "k-" + c, RetrievalPassword: "p"}); err != nil { t.Fatal(err) } d73Seed(t, s, "box-"+c, c) } id, err := s.StartCustomerReset("cust-a", false) if err != nil { t.Fatal(err) } _ = s.UpdateResetLeg(id, "customer_delete", "ok") _ = s.FinishCustomerReset(id) if _, err := s.db.Exec(`INSERT INTO host_deletions (host_id, customer_id, escrow_acked) VALUES ('box-cust-a', 'cust-a', 0)`); err != nil { t.Fatal(err) } for _, cust := range []string{"cust-a", "cust-b", "cust-a2"} { if err := s.SetOSAlarmRaised("end_date:web_cert:"+cust+":x.example.hu:soon", time.Now()); err != nil { t.Fatal(err) } } res, err := s.CustomerResidue("cust-a") if err != nil || res.OffsiteKeys != 1 || res.OffsiteWindows != 1 || res.OffsiteAbandonRequests != 1 || res.Total() < 3 { t.Fatalf("the preview's residue does not count the three tables: %+v (%v)", res, err) } if err := s.PurgeCustomerResidue("cust-a"); err != nil { t.Fatal(err) } after, other := d73Counts(t, s, "box-cust-a", "cust-a"), d73Counts(t, s, "box-cust-b", "cust-b") for _, table := range d73HouseholdTables { if after[table] != 0 { t.Errorf("%s: %d row(s) outlived the household", table, after[table]) } if other[table] != 1 { t.Errorf("%s: the OTHER household has %d row(s), want 1", table, other[table]) } } if after["operator_actions"] != 1 { t.Errorf("operator_actions: %d — the action log is an audit record and stays at the purge", after["operator_actions"]) } for _, j := range []string{"customer_resets", "host_deletions"} { if n := d73Count(t, s, `SELECT COUNT(*) FROM `+j+` WHERE customer_id = 'cust-a'`); n != 1 { t.Errorf("journal %s: %d row(s), want 1 — the delete journal stays (the ruling's one exception)", j, n) } } // the hub's own alarm marks that name the HOUSEHOLD went too (review 2026-11-14) — and only that household's, // also when another household's id starts the same way for cust, want := range map[string]int{"cust-a": 0, "cust-b": 1, "cust-a2": 1} { if n := len(s.OSAlarmKeys("end_date:web_cert:" + cust + ":")); n != want { t.Errorf("web-certificate marks of %s: %d, want %d", cust, n, want) } } // the action log goes with the audit rows: not at 100 days, gone after a year now := time.Now().UTC() if _, _, err := s.PruneDeletedCustomerAudit(now.Add(100*24*time.Hour), DeletedCustomerAuditKeep); err != nil { t.Fatal(err) } if n := d73Counts(t, s, "box-cust-a", "cust-a")["operator_actions"]; n != 1 { t.Errorf("operator_actions after 100 days: %d, want 1", n) } if _, _, err := s.PruneDeletedCustomerAudit(now.Add(400*24*time.Hour), DeletedCustomerAuditKeep); err != nil { t.Fatal(err) } if n := d73Counts(t, s, "box-cust-a", "cust-a")["operator_actions"]; n != 0 { t.Errorf("operator_actions a year after the deletion: %d, want 0", n) } if n := d73Counts(t, s, "box-cust-b", "cust-b")["operator_actions"]; n != 1 { t.Errorf("the OTHER household's action log: %d, want 1", n) } // the journal rows stay; since D86 (`05` §14.3) the deleted household's rows hold no id after the year for _, j := range []string{"customer_resets", "host_deletions"} { if n := d73Count(t, s, `SELECT COUNT(*) FROM `+j+` WHERE customer_id = ''`); n != 1 { t.Errorf("journal %s after the one-year prune: %d row(s) with no id, want 1 (the row stays, the id goes)", j, n) } } } // The daily sweep is for what was left BEFORE: rows of a box or household that no longer exists. A live box, a live // household, and a household in the middle of its delete (its boxes are gone, its config is still there) lose nothing. func TestD73_PurgeOrphanRows_OnlyTheGone(t *testing.T) { s := newTestStore(t) // live: a household with a box _ = s.SaveCustomerConfig(&CustomerConfig{CustomerID: "live", APIKey: "k1", RetrievalPassword: "p"}) _ = s.UpsertHost(&Host{HostID: "live-box", CustomerID: "live", APIKey: "hk1"}) d73Seed(t, s, "live-box", "live") // mid-delete: the config is there, the box is already gone (so its box rows ARE orphans, its household rows are not) _ = s.SaveCustomerConfig(&CustomerConfig{CustomerID: "mid", APIKey: "k2", RetrievalPassword: "p"}) d73Seed(t, s, "mid-box", "mid") // a ghost with a box: the config row is gone, a box row is left → the household still „exists” _ = s.UpsertHost(&Host{HostID: "ghost-box", CustomerID: "ghost", APIKey: "hk3"}) d73Seed(t, s, "ghost-box", "ghost") // gone: neither config nor box (Peti's box, the test boxes of 2026-11) d73Seed(t, s, "gone-box", "gone") got, err := s.PurgeOrphanRows() if err != nil { t.Fatal(err) } want := map[string]map[string]int{ "live": {"os_host_settings": 1, "os_reports": 2, "os_kernel_notices": 1, "offsite_keys": 1, "offsite_windows": 1, "offsite_abandon_requests": 1, "operator_actions": 1}, "mid": {"os_host_settings": 0, "os_reports": 0, "os_kernel_notices": 0, "offsite_keys": 1, "offsite_windows": 1, "offsite_abandon_requests": 1, "operator_actions": 1}, "ghost": {"os_host_settings": 1, "os_reports": 2, "os_kernel_notices": 1, "offsite_keys": 1, "offsite_windows": 1, "offsite_abandon_requests": 1, "operator_actions": 1}, "gone": {"os_host_settings": 0, "os_reports": 0, "os_kernel_notices": 0, "offsite_keys": 0, "offsite_windows": 0, "offsite_abandon_requests": 0, "operator_actions": 1}, } for cust, tables := range want { c := d73Counts(t, s, cust+"-box", cust) for table, n := range tables { if c[table] != n { t.Errorf("%s / %s: %d row(s), want %d", cust, table, c[table], n) } } } if got.Total() != 11 || got["os_reports"] != 4 || got["offsite_keys"] != 1 { t.Errorf("the sweep reported %v (total %d), want 11 rows: 8 box rows of mid and gone, 3 household rows of gone", got, got.Total()) } again, _ := s.PurgeOrphanRows() if again.Total() != 0 { t.Errorf("a second sweep removed %v — it must find nothing", again) } } // Review of 2026-11-14: a cleared alarm mark must leave NO row. It used to leave an empty one for ever, and several // marks carry a name a box sends (a guest number, a job id, a certificate name) — empty rows without limit. func TestOSAlarm_AClearedMarkLeavesNoRow(t *testing.T) { s := newTestStore(t) if err := s.SetOSAlarmRaised("probe:x", time.Now()); err != nil { t.Fatal(err) } if s.OSAlarmRaised("probe:x").IsZero() || d73Count(t, s, `SELECT COUNT(*) FROM hub_settings WHERE key = 'os_alarm:probe:x'`) != 1 { t.Fatal("setup: the mark was not set") } if err := s.SetOSAlarmRaised("probe:x", time.Time{}); err != nil { t.Fatal(err) } if n := d73Count(t, s, `SELECT COUNT(*) FROM hub_settings WHERE key = 'os_alarm:probe:x'`); n != 0 { t.Fatalf("a cleared mark left %d row(s)", n) } if !s.OSAlarmRaised("probe:x").IsZero() { t.Fatal("a cleared mark still reads as raised") } if err := s.SetOSAlarmRaised("probe:never-set", time.Time{}); err != nil { t.Fatalf("clearing a mark that was never set: %v", err) } }