Skip to content

fix(relay): retain confirm results for a week and audit events for 90 days - #25353

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay-step0-credential-retention
Oct 5, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay-step0-credential-retention

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​130 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​126
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​41 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​35

Stacked on #25352 (it uses the HeapWindowReaper added there). Review that first. This PR's own diff is the top commit.

ELI5

The relay keeps two kinds of records forever:

  • a receipt for every phone "resume confirm" (5.8 GB);
  • an audit log line for every credential event (3.6 GB).

The receipts only matter for a few seconds, if the same request is retried on the same connection. The audit log is for support questions. This keeps receipts for a week and audit lines for 90 days, and deletes older ones slowly.

What Changed

The director's existing credential cleanup (every ~30 s) now also reaps two tables:

reapBatch now deletes with ctid = ANY(ARRAY(...)) on Postgres instead of ctid IN (...), for all of its tables. With IN, the planner can choose a hash join over a sequential scan of the whole table; local Postgres showed exactly that plan for the audit batch. An array of TIDs is always a TID scan. SQLite keeps rowid IN (...).

Nothing changes for users:

  • A retried resume confirm inside a week still gets its stored answer.
  • No relay code reads audit events.

Why

What depends on relay_confirm_results. Exactly one read: confirmResume looks up (user, host, reqId). It returns the stored result only when the basis_conn_id matches, and otherwise throws confirmation_tuple_mismatch.

  • A basis is one phone relay connection. Desktop sends confirmResume(currentBasis, reqId) (desktop-relay-service.ts).
  • A replay is only meaningful as a retry on the same live connection. A basis is created with a 30 s deadline.
  • 7 days matches the existing terminal-invite retention ("long enough to answer a support question about a pairing that failed").
  • One behaviour change, after 7 days only: a confirm that reuses an old reqId on a new basis now runs as a fresh confirm instead of failing with a tuple mismatch. It still needs an active basis and a valid credential decision.

What depends on relay_audit_events.

  • No relay code, script, workflow or doc reads it. The only relay_audit_events reference outside tests is the INSERT in credential-store.ts.
  • The 90-day window is the conservative default from the brief. No code or doc sets a retention.

Production evidence (read-only session, 2026-10-04/05):

  • relay_confirm_results:
    • 8.26M rows, 4.4 GB heap plus 1.3 GB primary key, ~100–120k new a day, n_tup_del = 0.
    • ~90% are older than 7 days, oldest 2026-07-14.
    • No index on committed_at. Production EXPLAIN of a LIMIT delete picks a Seq Scan from page 0, hence the TID-window reaper. Production EXPLAIN of the TID-window statement shows Tid Range Scan plus Tid Scan.
  • relay_audit_events:
    • 8.39M rows, ~113k new a day.
    • By sample: 97% resume-confirmed, ~2% invite-created, ~1% credential-installed, <1% device-revoked.
    • The oldest row is 2026-07-14, so this deletes nothing until 2026-10-12. After that the table holds ~90 days, ~10M rows at today's rate.
    • Production EXPLAIN of the ordered batch uses Index Scan using relay_audit_events_at, even with 6.3M matching rows.

Pacing. At ~9 director ticks a minute, 250 rows a tick is ~3M rows a day. The 7.4M-row confirm-result backlog drains over 2–3 days. Audit deletes are about one day's worth of inserts per day.

For Jinwoo: audit retention decision needed

  • 90 days was chosen as a conservative placeholder. Nothing in code or docs sets a retention.
  • 90 days barely shrinks the table (steady state ~10M rows). That is because 97% of rows are resume-confirmed, one per phone resume.
  • If support only needs pairing and revocation history long-term, a shorter window for resume-confirmed alone (for example 14–30 days) would cut the table ~3–6x.
  • Note: the phase-0 measurement used relay_audit_events as a daily-active-host proxy. Any retention ends that history at the window.

Linked Issue

N/A. Relay redesign step 0 (internal).

Visual Proof

N/A. Database maintenance only; there is no UI or client-visible change.

Testing

  • Automated tests added/updated
  • credential-store-cleanup.test.ts (SQLite):
    • Confirm results and audit events are reaped only at or past their window.
    • A stored confirm result inside retention still replays after cleanup.
  • credential-cleanup-sweep-postgres.test.ts (local Postgres 16, port 55440):
    • With 20k past-retention rows, the ordered audit batch plans on relay_audit_events_at, not a Seq Scan.
    • cleanup() reaps old confirm results and audit events and keeps recent ones.
    • The basis reaper plan test now uses the new statement shape.
  • From cloud/apps/relay: pnpm typecheck passes, and the full relay suite with Postgres passes.

Review

Notes

  • Disk space. Freed space is reused after autovacuum. Files do not shrink without VACUUM FULL or pg_repack.
  • Backwards compatible. No schema change, and mixed director versions are fine.
  • Security: audit history older than 90 days becomes unavailable (see the decision above).

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one test-coverage note.

Reviewed changes

  • Confirm-result retention (7 days): RelayCredentialStore now reaps relay_confirm_results on committed_at through the HeapWindowReaper added in the base branch, with a {16 pages/stmt, 128 pages/tick, 250 rows/tick, 250ms} budget.
  • Audit-event retention (90 days): reapBatch gained an optional ORDER BY and now reaps relay_audit_events by at, walking the relay_audit_events_at index.
  • reapBatch delete shape: Postgres deletes switched from ctid IN (subquery) to ctid = ANY(ARRAY(subquery)) for all four tables; SQLite keeps rowid IN (...).
  • Tests: SQLite retention-boundary and in-retention replay tests; a Postgres audit plan test; a Postgres end-to-end reap test.

I verified the two load-bearing claims: relay_confirm_results has exactly one reader (confirmResume, tuple-mismatch on a different basis), and a resume basis deadline is 30s (resumeConfirmationDeadlineMs), so a 7-day window is far beyond any live retry. No production code reads relay_audit_events, and no schema/index is added, so the database.ts catalog rule holds. pnpm typecheck and the SQLite suite pass locally.

ℹ️ Nitpicks

  • The two EXPLAIN plan tests (credential-cleanup-sweep-postgres.test.ts:177 and :300) hand-copy the statement reapBatch builds, so they would still pass if reapBatch reverted to the IN (...) shape this PR is fixing — no test fails on that regression. Capturing the SQL passed to database.query during store.cleanup() and EXPLAINing that would tie the guard to the production statement.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

… days

relay_confirm_results (8.3M rows, 5.8 GB) and relay_audit_events (8.4M
rows, 3.6 GB) were never deleted. The director's credential cleanup now
reaps both after its existing passes:

- Confirm results older than 7 days. The only reader replays a stored
  result for a retry of the same request on the same connection basis; a
  different basis is already refused as a tuple mismatch. committed_at has
  no index, so this uses the TID-window reaper from the reservation prune,
  capped at 250 rows a tick (the 7.4M-row backlog drains over 2-3 days).
- Audit events older than 90 days, ordered by `at` so the batch walks
  relay_audit_events_at. Nothing in the relay reads them back. The oldest
  row is from 2026-07-14, so this deletes nothing until 2026-10-12.

reapBatch now deletes by `ctid = ANY(ARRAY(...))` on Postgres: with
`ctid IN (...)` the planner can choose a hash join over a sequential scan
of the whole table.
@Jinwoo-H
Jinwoo-H force-pushed the relay-step0-credential-retention branch from 108ee52 to c003436 Compare October 5, 2026 02:38
@Jinwoo-H
Jinwoo-H changed the base branch from relay-step0-reservation-prune to main October 5, 2026 02:38
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The credential store now reaps confirmation results after seven days and audit events after 90 days. Audit-event deletion orders batches by timestamp. Batch deletion uses SQLite row IDs or PostgreSQL tuple IDs. Tests cover retention boundaries, confirmation-result availability, and PostgreSQL query plans.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to c0034

Cleanup may do some unnecessary database work when no results have expired, but that work is bounded. No material issue remains that should prevent merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to c0034

The retention changes preserve the inspected credential-confirmation checks and use restartable cleanup. No introduced authorization bypass was identified. Risk remains low rather than minimal because audit-history deletion is irreversible and external retention requirements have not been established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Retention operates across identities in the shared relay tables because deletion predicates filter by age, not tenant. Its direct exposure is removal of eligible confirmation and audit history throughout that database, using existing maintenance authority rather than newly granted client privileges.

Security Findings and Attack Paths

  • inferred — The inspected receipt-expiry path does not establish an authorization bypass: reuse of a deleted request ID requires fresh confirmation checks, and an expired or inactive basis is rejected. Reuse on a new valid basis is no longer blocked by the deleted receipt, but still requires matching identity, ownership, and an acceptable credential decision. This conclusion is limited to the inspected paths.

Trust Boundaries and Controls

  • observed — The control-command handler parses the request and supplies the session identity and owning generation. Fresh confirmation checks basis ownership, credential kind, active status, deadline, device identity, and credential state before committing. Cleanup SQL identifiers and predicates come from fixed internal call sites; cutoff values are parameterized.

Resilience and Maintainability Implications

  • observed — PostgreSQL confirmation reaping skips locked rows and revisits heap windows on later passes. Restart resets the in-memory cursor to a randomized starting page. Background cleanup failures are caught without cancelling the interval, allowing subsequent sweeps to retry independently completed work.

Hardening Proposals

  • proposed — Before enabling irreversible audit deletion, establish whether incident-response or external retention obligations require an archive beyond 90 days. If they do, ensure archival completion precedes deletion. This is a proposal, not an observed missing production control.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: retaining confirmation results for seven days and audit events for 90 days.
Description check ✅ Passed The description explains the change, rationale, retention behavior, testing, visual-proof status, and compatibility considerations. It also notes the internal linked-issue exception. Some optional che…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
cloud/apps/relay/src/credential-store.ts (1)

705-705: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Stop the empty-page scan after a full pass with no deletions.

If the PostgreSQL table has one page and no expired rows, HeapWindowReaper.reap can issue up to 128 identical one-page DELETE statements per cleanup tick. The 30–36 second schedule makes this bounded periodic overhead, so this is an optional optimization rather than a high-impact issue. Stop after a complete page cycle with no deletions, and preserve nextPage so a later invocation retries rows skipped by SKIP LOCKED. Keep the existing budgets.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 08c773d1-0fb6-4b6c-b677-a4129d3ef1c0
📥 Commits

Reviewing files that changed from the base of the PR and between e9daf9b and c003436.

📒 Files selected for processing (3)
  • cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
  • cloud/apps/relay/src/credential-store-cleanup.test.ts
  • cloud/apps/relay/src/credential-store.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@Jinwoo-H
Jinwoo-H merged commit e884681 into main Oct 5, 2026
32 of 51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant