Skip to content

fix(relay): skip the dead-cell sweep's host scan when no cell qualifies - #25350

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-step0-evacuate-precheck
Oct 5, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-step0-evacuate-precheck

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​154 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​154
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​43 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​42

ELI5

Every 30 seconds each relay director asks the database "are there hosts stuck on a dead cell that I should move?". The answer is almost always "no", but working that out cost over half a second each time, because the question was asked host by host. Now the director first asks the cheap question, "is there any dead cell I could move hosts off?", and only asks the expensive one when the answer is yes.

What Changed

  • evacuateDeadCells runs a cell-level pre-check before its host query. The pre-check evaluates the parts of the existing predicate that depend only on the cell: liveness, admission, the connection-limits row, and the committed fence. It reads only the small cell tables (~33 rows each).
  • If no cell qualifies, the sweep returns 0 without running the host query. If some cells qualify, the host query runs unchanged, plus AND assignment.cell_id IN (...) for those cells.
  • The pre-check is a strict superset of the cells the host query could act on. It drops only the per-host pin checks. So the set of hosts that get moved is the same as before.

Nothing changes for users. Hosts on a dead cell that can be evacuated are still moved by the same sweep tick.

Why

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

  • pg_stat_statements: this statement has 85,459 calls at a 551 ms mean, 47,102 s in total, about 12% of relay database time (phase-0 measurement: 12.5%, 574 ms).
  • EXPLAIN (plain, read-only session): ORDER BY user_id, relay_host_id LIMIT 100 lets the planner walk the whole relay_assignments primary key. No row ever matches, so it reaches the end every call.
  • Why nothing matches: the only dead cells are c1, c2, c3, c6, c11 and c12. All six are existing-only (enabled = 0) with no committed fence, so no host on them qualifies. 2,706 assignments still point at c1/c2/c3/c6.
  • The new pre-check, run with EXPLAIN ANALYZE on the same read-only session (a plain SELECT), takes 3.1 ms and returns 0 rows.

Alternatives considered:

  • An index on relay_assignments(cell_id). It needs an out-of-band CREATE INDEX CONCURRENTLY (see the RULE beside SCHEMA), and it adds write cost to a table with ~390M updates a week. It still would not stop the per-row subplans from running.
  • Rewriting the host predicate. That carries more risk than a superset pre-check, which leaves the host predicate exactly as it was.

Linked Issue

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

Visual Proof

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

Testing

  • Automated tests added/updated
  • New dead-cell-evacuation-precheck.test.ts, run on SQLite and on local Postgres 16 (port 55440):
    • With only an unfenced existing-only dead cell, the host query is never issued and the host stays put.
    • A dead, uncapped, admitting cell still evacuates its host, and the host query does run.
  • Confirmed the skip test fails on origin/main's implementation.
  • Existing evacuation tests pass unchanged: the fence/attestation cases, post-drain pins, the busy-row skip, and capped-cell starvation.
  • From cloud/apps/relay: pnpm typecheck passes, and the full relay suite with Postgres passes (111 files, 992 tests).

Review

Superset argument: a host row qualifies only if (a) its cell is dead, and (b) either branch 1 holds (enabled = 1, no limits row, no active pin) or branch 2 holds (enabled = 0, limits row or active pin, valid committed fence). The pre-check keeps (a), and keeps (b) without the pin/limits disjunction of branch 2 and the pin clause of branch 1. So every cell with a qualifying host is in the pre-check result.

Notes

  • Security, cross-platform, SSH, mobile: not affected (director-only SQL).
  • Backwards compatible. No schema or wire change. It is safe with mixed director versions, because the sweep is idempotent and each director decides on its own.

evacuateDeadCells ran one query that joined every assignment to its cell's
liveness and fence state, ordered by primary key with LIMIT 100. In
production no row ever matched (the only dead cells are stale existing-only
cells without a committed fence), so the planner walked the whole
relay_assignments primary key every call: 551 ms mean over 85k calls,
~12% of relay database time.

A cell-level pre-check now evaluates the predicate's cell-only half over
the ~33-row cell tables (3 ms in production). It is a superset of the cells
the host query can act on, so the sweep returns early when it is empty and
otherwise restricts the host query to those cells. The host predicate is
unchanged.
@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.

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a983c0a4-cae2-4953-adc7-a803858abeeb
📥 Commits

Reviewing files that changed from the base of the PR and between 51fe6f3 and 681604d.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/dead-cell-evacuation-precheck.test.ts

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


📝 Walkthrough

Walkthrough

Dead-cell evacuation now selects eligible candidate cells before querying assignments. It returns zero without an assignment query when no candidates exist. When candidates exist, the assignment query is limited to those cell IDs. New tests cover the no-query case and assignment evacuation on SQLite and optional PostgreSQL.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 68160

The change skips the host scan when no cells qualify while preserving the evacuation path for eligible cells. No actionable merge-blocking risk is established; normal checks remain appropriate.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 68160

The existing fencing and assignment controls remain in place, with no demonstrated security bypass. A cell becoming eligible between the two reads can wait for a later sweep. Concurrent-transition coverage and the acceptable recovery delay remain unspecified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The maintenance operation addresses assignments across users in the shared relay database, with a default batch limit of 100. The new filter narrows candidate cells without adding a caller or authority; assignment operations remain keyed by user and host identity.

Trust Boundaries and Controls

  • observed — Candidate IDs originate from database rows and enter the host query through bound placeholders. Completed, unaborted, current-incarnation, heartbeat-relative and unexpired fence checks remain enforced in the original host predicate and existing assignment fence helper.

Resilience and Maintainability Implications

  • observed — The existing assignment transaction updates epochs, reservations and leases together and emits decision events only after commit. Database implementations roll back failed transactions. Expected per-host failures are isolated, and the background wrapper catches other sweep failures without stopping subsequent cleanup ticks.
🚥 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 4 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely states the main change: skipping the dead-cell host scan when no cell qualifies.
Description check ✅ Passed The description covers the change, rationale, testing, visual-proof status, and review notes. It marks the linked issue as not applicable for this internal change. Some template items are omitted or i…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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.

@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 new issues found.

Reviewed changes

  • Dead-cell sweep pre-check: evacuateDeadCells now calls the new private deadCellEvacuationCandidates(cutoff) first and returns 0 without issuing the host query when no cell qualifies; when candidates exist, the host query runs unchanged plus AND assignment.cell_id IN (...).
  • New test: dead-cell-evacuation-precheck.test.ts pins that an unfenced existing-only dead cell skips the host query and leaves the host in place, and that a dead uncapped admitting cell still evacuates, on SQLite and (when configured) Postgres.

The candidate query is the cell-level half of the host predicate minus the per-host pin/limits disjunctions, so it is a strict superset of the cells the host query can act on; the set of moved hosts is unchanged. The skip is guarded by the cellIds.length === 0 early return, and the param order [1, cutoff, now, now, ...cellIds, limit] matches the placeholder order. I independently traced the three-valued logic, the 1:1 LEFT JOINs (all cell tables keyed by cell_id), and the relay_cells inner-join domain against the host query, and separately had it verified — no counterexample.

Two benign observations, neither actionable: the pre-check and host query are separate statements with separately sampled now, so a cell that becomes actionable between them is caught on the next tick (errs safe); and the IN (...) parameter count grows with fleet size (the empty case is guarded, and the fleet is ~33 cells).

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

@Jinwoo-H
Jinwoo-H merged commit b9b0f29 into main Oct 5, 2026
24 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