Files
felhom.eu/hub/internal/store/deleted_customer_audit_test.go
T

247 lines
13 KiB
Go

package store
import (
"strings"
"testing"
"time"
)
// R-901: a deleted customer's events and notification_log rows go 1 year after the deletion — and nothing else goes.
// RED-PROOF: return early from PruneDeletedCustomerAudit (the pre-R-901 state: nothing prunes notification_log) →
// the c-old rows survive → this FAILS on the first assertion.
func TestR901_DeletedCustomerAuditGoesAfterOneYear(t *testing.T) {
s := newTestStore(t)
now := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
ts := func(d time.Duration) string { return now.Add(-d).Format("2006-01-02 15:04:05") }
day := 24 * time.Hour
journal := func(cid, legs string, completedAgo time.Duration) {
if _, err := s.db.Exec(`INSERT INTO customer_resets (customer_id, started_at, completed_at, legs_json) VALUES (?, ?, ?, ?)`,
cid, ts(completedAgo+time.Minute), ts(completedAgo), legs); err != nil {
t.Fatal(err)
}
}
row := func(cid string, ago time.Duration) {
if _, err := s.db.Exec(`INSERT INTO events (customer_id, event_type, severity, message, created_at) VALUES (?, 'x', 'info', 'm', ?)`, cid, ts(ago)); err != nil {
t.Fatal(err)
}
if _, err := s.db.Exec(`INSERT INTO notification_log (customer_id, event_type, severity, message, status, created_at) VALUES (?, 'x', 'info', 'm', 'sent', ?)`, cid, ts(ago)); err != nil {
t.Fatal(err)
}
}
deleted := `{"hosts":"ok","residue":"ok","customer_delete":"ok"}`
journal("c-old", deleted, 400*day) // deleted 400 days ago → its audit rows go
journal("c-recent", deleted, 100*day) // deleted 100 days ago → kept
journal("c-reset", `{"hetzner":"ok","pbs":"ok","db_purge":"ok"}`, 400*day) // a RESET, not a deletion → kept
row("c-old", 500*day)
row("c-old", 401*day)
row("c-old", 10*day) // the id re-used AFTER the deletion → kept
row("c-recent", 200*day)
row("c-reset", 500*day)
row("c-live", 900*day) // never deleted → kept (events' own 90-day prune is not this function's business)
ev, nl, err := s.PruneDeletedCustomerAudit(now, DeletedCustomerAuditKeep)
if err != nil {
t.Fatal(err)
}
if ev != 2 || nl != 2 {
t.Fatalf("deleted events=%d notification_log=%d, want 2 and 2 (c-old's two rows before its deletion)", ev, nl)
}
count := func(table, cid string) int {
var n int
if err := s.db.QueryRow(`SELECT COUNT(*) FROM `+table+` WHERE customer_id = ?`, cid).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
for _, c := range []struct {
cid string
want int
}{{"c-old", 1}, {"c-recent", 1}, {"c-reset", 1}, {"c-live", 1}} {
for _, tb := range []string{"events", "notification_log"} {
if got := count(tb, c.cid); got != c.want {
t.Errorf("%s rows for %s = %d, want %d", tb, c.cid, got, c.want)
}
}
}
// The journal row (provenance) stays — since D86 without its id: three rows before, three after, one with no id.
var j, noID int
_ = s.db.QueryRow(`SELECT COUNT(*) FROM customer_resets`).Scan(&j)
_ = s.db.QueryRow(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = ''`).Scan(&noID)
if j != 3 || noID != 1 {
t.Fatalf("the deletion journal rows must stay (3) and c-old's must hold no id (1), got %d and %d", j, noID)
}
// Idempotent.
if ev, nl, _ := s.PruneDeletedCustomerAudit(now, DeletedCustomerAuditKeep); ev+nl != 0 {
t.Fatalf("a second run deleted %d+%d rows, want 0", ev, nl)
}
}
// d86Box is a hub store with deleted and living households, for the D86 tests (`05` §14.3's test list).
type d86Box struct {
t *testing.T
s *Store
now time.Time
}
func newD86Box(t *testing.T) *d86Box {
return &d86Box{t: t, s: newTestStore(t), now: time.Date(2027, 11, 15, 12, 0, 0, 0, time.UTC)}
}
func (b *d86Box) ts(ago time.Duration) string { return b.now.Add(-ago).Format("2006-01-02 15:04:05") }
func (b *d86Box) exec(q string, a ...any) {
b.t.Helper()
if _, err := b.s.db.Exec(q, a...); err != nil {
b.t.Fatal(err)
}
}
// deleted makes a household whose delete cascade completed `ago` ago: one box delete just before, the delete journal
// row, and one audit row of each kind.
func (b *d86Box) deleted(cid, host string, ago time.Duration, legs string) {
b.exec(`INSERT INTO host_deletions (host_id, customer_id, deleted_at) VALUES (?, ?, ?)`, host, cid, b.ts(ago+time.Minute))
b.exec(`INSERT INTO customer_resets (customer_id, started_at, completed_at, legs_json) VALUES (?, ?, ?, ?)`, cid, b.ts(ago+2*time.Minute), b.ts(ago), legs)
b.exec(`INSERT INTO events (customer_id, event_type, severity, message, created_at) VALUES (?, 'x', 'info', 'm', ?)`, cid, b.ts(ago+time.Hour))
}
func (b *d86Box) n(q string, a ...any) int {
b.t.Helper()
var n int
if err := b.s.db.QueryRow(q, a...).Scan(&n); err != nil {
b.t.Fatal(err)
}
return n
}
// idAnywhere counts the journal rows that still hold the text `id` in ANY column (searched as text, so a look-alike
// id is told apart only by the caller's choice of text).
func (b *d86Box) idAnywhere(id string) int {
return b.n(`SELECT (SELECT COUNT(*) FROM customer_resets WHERE customer_id = ?1 OR instr(legs_json, ?1) > 0) +
(SELECT COUNT(*) FROM host_deletions WHERE customer_id = ?1 OR host_id = ?1 OR instr(host_id, ?1 || '-') = 1)`, id)
}
const d86Legs = `{"hosts":"ok","residue":"ok","customer_delete":"ok"}`
// D86, the consequence: a year after a household was deleted, no journal row holds its id or its box's id — and the
// rows are still there, with their times and step states. A look-alike id, a household deleted 364 days ago and a
// household that still exists keep everything.
func TestD86_AfterTheYearTheJournalHoldsNoIDAndKeepsItsRows(t *testing.T) {
b := newD86Box(t)
day := 24 * time.Hour
b.deleted("peti", "peti-4f2a1c", 366*day, d86Legs)
b.deleted("peti-2", "peti-2-9be001", 366*day, `{"hosts":"ok","residue":"ok","customer_delete":"failed"}`) // a look-alike whose delete never ENDED
b.deleted("anna", "anna-77aa01", 364*day, d86Legs) // one day short of the year
b.exec(`INSERT INTO host_deletions (host_id, customer_id, deleted_at) VALUES ('living-1-aa', 'living', ?)`, b.ts(500*day)) // a household that still exists, one old box delete
b.exec(`INSERT INTO customer_resets (customer_id, started_at, completed_at, legs_json) VALUES ('living', ?, ?, '{"hetzner":"ok","pbs":"ok","db_purge":"ok"}')`, b.ts(500*day), b.ts(500*day))
rowsBefore := b.n(`SELECT (SELECT COUNT(*) FROM customer_resets) + (SELECT COUNT(*) FROM host_deletions)`)
timesBefore := b.n(`SELECT COUNT(*) FROM customer_resets WHERE completed_at = ?`, b.ts(366*day))
if _, _, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err != nil {
t.Fatal(err)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = 'peti'`) + b.n(`SELECT COUNT(*) FROM host_deletions WHERE customer_id = 'peti' OR host_id = 'peti-4f2a1c'`); got != 0 {
t.Fatalf("a year after the deletion %d journal row(s) still hold the household's id or its box's id", got)
}
if got := b.n(`SELECT (SELECT COUNT(*) FROM customer_resets) + (SELECT COUNT(*) FROM host_deletions)`); got != rowsBefore {
t.Fatalf("the journal lost rows: %d before, %d after — the id goes, the row stays", rowsBefore, got)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE completed_at = ?`, b.ts(366*day)); got != timesBefore {
t.Fatalf("the journal lost its times: %d rows with the completion time before, %d after", timesBefore, got)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = '' AND legs_json = ?`, `{"customer_delete":"ok","hosts":"ok","residue":"ok"}`); got != 1 {
t.Fatalf("the step states of the deleted household's row are not kept as they were: %d", got)
}
for id, want := range map[string]int{"peti-2": 2, "anna": 2, "living": 2} {
if got := b.idAnywhere(id); got != want {
t.Errorf("%s: %d journal row(s) hold the id after the run, want %d (nothing of it may change)", id, got, want)
}
}
// the audit rows went in the same step (the log is never gone with the id still there, or the other way round)
if b.n(`SELECT COUNT(*) FROM events WHERE customer_id = 'peti'`) != 0 || b.n(`SELECT COUNT(*) FROM events WHERE customer_id = 'anna'`) != 1 {
t.Fatal("the audit rows and the journal ids did not go together")
}
// a second run changes nothing and does not read the row with no id as a household
if ev, nl, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err != nil || ev+nl != 0 {
t.Fatalf("second run: %d+%d rows, err %v", ev, nl, err)
}
}
// An id used AGAIN for a new household: the new life's journal rows are read by live code (the escrow carry, a later
// delete's purge) and must keep their ids when the OLD life's year ends.
func TestD86_AnIDUsedAgainKeepsTheJournalOfItsNewLife(t *testing.T) {
b := newD86Box(t)
day := 24 * time.Hour
b.deleted("tester4", "tester4-46836f", 400*day, d86Legs)
// the new life: the same id, a box deleted last week, a RESET last month
b.exec(`INSERT INTO host_deletions (host_id, customer_id, deleted_at, escrow_acked) VALUES ('tester4-2f0c25', 'tester4', ?, 1)`, b.ts(7*day))
b.exec(`INSERT INTO customer_resets (customer_id, started_at, completed_at, legs_json) VALUES ('tester4', ?, ?, '{"hetzner":"ok","pbs":"ok","db_purge":"ok"}')`, b.ts(30*day), b.ts(30*day))
if _, _, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err != nil {
t.Fatal(err)
}
if got := b.n(`SELECT COUNT(*) FROM host_deletions WHERE customer_id = 'tester4' AND host_id = 'tester4-2f0c25'`); got != 1 {
t.Fatalf("the NEW life's box delete lost its id (%d) — the escrow carry of the living household reads it", got)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = 'tester4'`); got != 1 {
t.Fatalf("the NEW life's RESET row: %d with the id, want 1", got)
}
if got := b.n(`SELECT COUNT(*) FROM host_deletions WHERE host_id = 'tester4-46836f'`) + b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = '' `); got != 1 {
t.Fatalf("the OLD life: want its box id gone and exactly one journal row with no id, got %d", got)
}
}
// A household with the id that an emptied row holds cannot exist — and a household NAMED like a marker word must not be
// read as a deleted one. With a word in place of the empty string, the daily run would delete this household's log.
func TestD86_TheEmptiedRowIsNeverReadAsAHousehold(t *testing.T) {
b := newD86Box(t)
day := 24 * time.Hour
b.deleted("old", "old-aaaa01", 400*day, d86Legs)
if _, _, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err != nil {
t.Fatal(err)
}
for _, word := range []string{"removed", "deleted", "gone", ""} {
b.exec(`INSERT INTO events (customer_id, event_type, severity, message, created_at) VALUES (?, 'x', 'info', 'm', ?)`, word, b.ts(500*day))
}
if ev, _, err := b.s.PruneDeletedCustomerAudit(b.now.Add(day), DeletedCustomerAuditKeep); err != nil || ev != 0 {
t.Fatalf("the next day's run deleted %d event row(s) of a household it took the emptied journal row for (err %v)", ev, err)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id IN ('removed', 'deleted', 'gone')`); got != 0 {
t.Fatalf("the journal holds a WORD in place of the id (%d row(s)) — a household can be given that word as its id", got)
}
}
// The step field holds state words only. If a later writer ever puts a name there, the year-end still leaves none.
func TestD86_TheStepFieldKeepsOnlyPlainWords(t *testing.T) {
b := newD86Box(t)
b.deleted("kata", "kata-123456", 400*24*time.Hour, `{"hosts":"ok","hetzner":"sub-account kata.kovacs@example.com removed","customer_delete":"ok","Kata Kovacs":"ok"}`)
if _, _, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err != nil {
t.Fatal(err)
}
var legs string
if err := b.s.db.QueryRow(`SELECT legs_json FROM customer_resets WHERE customer_id = ''`).Scan(&legs); err != nil {
t.Fatal(err)
}
if legs != `{"customer_delete":"ok","hetzner":"other","hosts":"ok","other":"ok"}` {
t.Fatalf("legs_json after the year = %s", legs)
}
}
// All or nothing: when the journal step fails, the audit rows of that household are still there (no day on which the
// log is gone and the id is not).
func TestD86_TheLogAndTheIDGoInOneTransaction(t *testing.T) {
b := newD86Box(t)
b.deleted("mari", "mari-abcdef", 400*24*time.Hour, d86Legs)
b.exec(`CREATE TRIGGER d86_fail BEFORE UPDATE ON host_deletions BEGIN SELECT RAISE(ABORT, 'staged failure'); END`)
// the error must be the STAGED one from the journal step — any other error (a lock) would mean the step was never
// reached, and the test would prove nothing
if _, _, err := b.s.PruneDeletedCustomerAudit(b.now, DeletedCustomerAuditKeep); err == nil || !strings.Contains(err.Error(), "staged failure") {
t.Fatalf("the staged failure of the journal step was not returned: %v", err)
}
if got := b.n(`SELECT COUNT(*) FROM events WHERE customer_id = 'mari'`); got != 1 {
t.Fatalf("the audit rows went (%d left) although the journal step failed", got)
}
if got := b.n(`SELECT COUNT(*) FROM customer_resets WHERE customer_id = 'mari'`); got != 1 {
t.Fatalf("the journal row lost its id although the step failed: %d", got)
}
}