Skip to content

fix(relay): database sweeps and ops reads skip reserve-mode cells (step-5 census, inert) - #27046

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-step5-census
Oct 10, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-step5-census

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​801 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​798
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​500 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​483

ELI5

In step 5 a switched-on cell stops writing per-desktop records to the database right away; it keeps them in memory and the database catches up later. Anything that reads those records to decide "this desktop is gone" or "this cell is empty" would then be wrong, and could move desktops or roll a full cell. This PR makes every such path skip or refuse a switched-on cell. While no cell is switched on, nothing changes.

What Changed

RelayAssignmentStore takes reserveModeCells: the cells whose applied admitMode (from each cell's seat feed) is reserve, or null while a starting director has not yet heard from every live cell (capped at 30 s, after which a silent cell is treated as off so sweeps cannot stall).

Path Reserve-mode cell
activity-lease expiry, counter expiry skipped; neither runs while the set is unknown
dead-cell evacuation skipped (an unreachable cell is unverifiable, never gone); none while unknown
idle regional rehome never a source or a target; none while unknown
sticky mayNormallyReassign an idle host on it is not treated as gone; also while unknown
database placement (leastLoadedCell) never picked, unless the cell's own relay_cell_admit_effective row says db (below)
drain prepare, evacuation start/capacity/status, dormant rebalance, cell-status refused with cell_in_reserve_mode (a switched-on cell must be flipped back before a roll)

assignment-reserve-mode-census.test.ts classifies every public store method (connect path, skips, refuses, follows a refused start, cell-level). It reads the class with the TypeScript AST, so a new method fails CI until someone decides how it treats a switched-on cell.

Why

The design calls this the top risk (§6.3, §11 point 2): a missed sweep that evacuates a switched-on cell's hosts makes duplicate owners and moves desktops. Keying on the cell's applied switch, as reported in its own feed, means a director only skips a cell that really is switched on, and the startup cap keeps a dead feed from freezing cleanup.

Beyond the design's list: cellDeploymentStatus, cellEvacuationCapacity/Status and startEvacuation are also refused. Rollout tooling reads them, and for a switched-on cell they would report stale counts.

Mixed versions: a director on an older revision does not know about the switch, so before deploying an older director revision every cell must be flipped back first.

A cell that tripped its dead-man. A reserve cell that no placing director has reached for 60-120 s flips itself back to database admission, but Postgres still records it as reserve (only the flag workflow writes that). If every director lost touch at once, today's path had no cell left for a new desktop. Each cell now writes its raw mode (switch file plus dead-man, without the flip-back wait) to a new table, relay_cell_admit_effective, on every change and every 15 s. The write is best-effort through the cell's own pool: it is skipped while requests wait for a connection, and never made before the cell's first flag read. Database placement takes a reserve cell only while that row says db, names the process relay_cell_runtime knows, and is under 45 s old. A cell on an older image writes no row and is never taken. The sweeps above still read only relay_cell_admit_modes. We chose the cell's own row over a director's feed because the likeliest reason every director goes quiet (token minting, the cell's token check, a network partition) is the same thing that would stop the feed.

The seat feed also gains an optional admitModeRaw. Placing directors treat a tripped cell as a database cell at once, so they stop booking into it and pacing desktops for it while it re-registers. Older directors ignore the field.

Reads outside transactions. The reserve set, including the admit-effective rows, is read before each transaction begins, and inside one it is answered from that read. A timed-out read inside a transaction (57014) used to abort it, and the next statement failed with 25P02.

Linked Issue

N/A (internal relay redesign, step 5).

Visual Proof

N/A: server-side, no UI.

Testing

  • assignment-reserve-mode-census.test.ts: the AST ratchet (it caught a missed method while being written); expiry sweeps skip a reserve cell and run none while the set is unknown; an idle host stays sticky on a reserve cell where today's path re-places it, also while unknown; fresh database placements never land on a reserve cell; drain, evacuation and status reads refuse it.
  • shadow-seat-directory.test.ts: the set is null until every live cell answered or the 30 s grace passes, and keeps a cell's last applied switch through lost contact.
  • assignment-reserve-mode-postgres.test.ts (PostgreSQL): a reserve cell is taken only while its own row says db. A cell with no row, a row from another process, and a row older than 45 s are each refused, and each refusal case fails when its check is removed. Placement also succeeds while the admit-mode table is locked under a 300 ms statement timeout (a real 57014). A host on a reserve cell that still heartbeats while not ready is not moved.
  • cell-reserve-rollback.blackbox.test.ts: a cell writes reserve, then db the moment its dead-man trips, under its current process. A cell that has not yet read its flag object writes nothing.
  • cell-admit-effective-writer.test.ts: writes on a change and every 15 s, one at a time; skips while the pool has waiters; a failure is logged at most once a minute and retried.
  • reserve-assignment.test.ts: a tripped cell that is still re-registering gets no booking.
  • The full relay suite passes locally.

Stacked on #27043, so the census lists the two store methods #27043 adds (activateControlDeferringCell, commitCellReservationDelta).

Now stacked on #27048 (the chain's next link), still carrying the census entries for #27043's methods.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The relay adds database-backed configured and effective cell admission modes. Cell servers report effective mode, and seat feeds expose raw mode for placement decisions. A director-only endpoint reads or updates configured mode. RelayAssignmentStore uses reserve-mode state to govern assignment placement, evacuation, drain, rehome, and cleanup paths. Tests cover these behaviors, mode-report refresh, unknown state, and database-backed assignment scenarios.





Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 1a3a1

Reserve-mode handling still has several open gaps. Placement, drains, evacuations, and rehomes can act on cells that are, or may be, in reserve mode when the mode is unknown or has just changed. The evacuation-status endpoint also returns a server error instead of a reserve-mode refusal. These gaps should be resolved or explicitly accepted before merge.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 18 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 identifies the main change: relay database sweeps and operations reads skip reserve-mode cells. The step and census qualifiers provide relevant context without making the title misle…
Description check Passed The description is complete and matches the repository template. It explains the user impact, implementation, rationale, linked stacked issues, testing, visual-proof status, compatibility consideratio…

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR









  • Autofix · 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.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b40ab43d-05f0-439e-9838-8b1a95918075
📥 Commits

Reviewing files that changed from the base of the PR and between 3dd332e and d9acbb7.

📒 Files selected for processing (5)
  • cloud/apps/relay/src/assignment-reserve-mode-census.test.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/relay-server.ts
  • cloud/apps/relay/src/shadow-seat-directory.test.ts
  • cloud/apps/relay/src/shadow-seat-directory.ts

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

if (mayNormallyReassign(activity(existing), now)) return null
// A reserve-mode cell's hosts hold no activity here, so idle is not evidence they left.
if (
!this.mayBeReserveCell(text(existing, 'cell_id')) &&

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Keep the reserve-mode pin through the other reassignment checks. This guard blocks normal idle reassignment, but assignStickyOnce can still return null at assignmentStrandedOnUnservedCell. For example, an existing-only reserve-mode cell with a recent grant and no live database leases satisfies that stranded check because its host activity is held in memory. Placement can then change the host’s assignment epoch. Apply the reserve-mode guard to the stranded and roll-isolation decisions that also discard the pin.

Comment on lines +3902 to +3905
return selection.candidates.filter(
(candidate) =>
!reserveCells.has(candidate.sourceCellId) && !reserveCells.has(candidate.targetCellId)
)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Recheck reserve membership at rehome commit. This filter protects candidate selection only. If either cell switches to reserve mode after selection, commitIdleRegionalRehome can still call startRegionalRehomeCandidate and move the database assignment. Recheck both cells in the commit path before it writes the move, and defer the commit when membership is unknown.

Comment thread cloud/apps/relay/src/relay-server.ts Outdated
const assignments = new RelayAssignmentStore(observedDatabase, options.now, {
requireLiveCells: config.role === 'director',
// Without the poller this director cannot see a cell's switch, so none is treated as on.
reserveModeCells: () => shadowSeatDirectory?.reserveModeCells() ?? NO_RESERVE_MODE_CELLS,

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve unknown reserve-mode membership through every decision. During startup grace, the directory returns null because an unreported cell may be in reserve mode. The callback and two store decisions instead treat that state as an empty set. This permits placement and cell operations against potentially stale database state.

  • cloud/apps/relay/src/relay-server.ts#L152-L152: return the directory’s null; use the empty set only when no poller exists.
  • cloud/apps/relay/src/assignment-store.ts#L645-L645: defer reserve-sensitive cell operations while membership is null.
  • cloud/apps/relay/src/assignment-store.ts#L7882-L7882: defer database placement while membership is null.
📍 Affects 2 files
  • cloud/apps/relay/src/relay-server.ts#L152-L152 (this comment)
  • cloud/apps/relay/src/assignment-store.ts#L645-L645
  • cloud/apps/relay/src/assignment-store.ts#L7882-L7882

@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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6857bb8a-2331-4da0-9005-0c79c4c56421
📥 Commits

Reviewing files that changed from the base of the PR and between d9acbb7 and b5b5ac3.

📒 Files selected for processing (5)
  • cloud/apps/relay/src/admin-token-verifier.test.ts
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/assignment-reserve-mode-census.test.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/database.ts

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

Comment on lines +2438 to +2439
// Rolling a switched-on cell needs a flip back first (design default 4).
await this.refuseReserveCell(input.cellId)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- diff paths ---'
git diff --name-only 7450f40662b539492294782cad803d8b5e8ca49d b5b5ac34b7432541d60a0b74db251198abc955ba -- cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- relevant symbols ---'
rg -n -F --glob 'cloud/apps/relay/src/assignment-store.ts' -e 'refuseReserveCell' -e 'setCellAdmitMode' -e 'startActiveCellEvacuations' -e 'startEvacuation' -e 'queryLocked' -e 'relay_cell_admit_modes' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- changed region ---'
git diff --unified=80 7450f40662b539492294782cad803d8b5e8ca49d b5b5ac34b7432541d60a0b74db251198abc955ba -- cloud/apps/relay/src/assignment-store.ts | sed -n '1,1200p'

Repository: stablyai/orca

Length of output: 42474


🏁 Script executed:

set -eu
printf '%s\n' '--- relevant source excerpts ---'
sed -n '2260,2515p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- all matching method references ---'
rg -n -F --glob 'cloud/apps/relay/src/**/*.ts' -e 'startActiveCellEvacuations(' -e 'startEvacuation(' -e 'refuseReserveCell(' -e 'setCellAdmitMode(' -e 'reserveModeCells(' cloud/apps/relay/src
printf '%s\n' '--- database transaction and locking definitions ---'
rg -n -F --glob 'cloud/apps/relay/src/**/*.ts' -e 'queryLocked' -e 'transaction(' -e 'relay_cell_admit_modes' cloud/apps/relay/src | sed -n '1,500p'

Repository: stablyai/orca

Length of output: 41206


🏁 Script executed:

git diff --unified=40 7450f40662b539492294782cad803d8b5e8ca49d b5b5ac34b7432541d60a0b74db251198abc955ba -- cloud/apps/relay/src/assignment-store.ts

Repository: stablyai/orca

Length of output: 42717


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
p = Path("cloud/apps/relay/src/assignment-store.ts")
lines = p.read_text().splitlines()
terms = ("refuseReserveCell", "setCellAdmitMode", "startActiveCellEvacuations", "startEvacuation", "queryLocked", "relay_cell_admit_modes")
for i, line in enumerate(lines):
    if any(term in line for term in terms):
        lo, hi = max(0, i-12), min(len(lines), i+45)
        print(f"--- lines {lo+1}-{hi} ---")
        for n in range(lo, hi):
            print(f"{n+1}: {lines[n]}")
PY

Repository: stablyai/orca

Length of output: 45667


🏁 Script executed:

set -eu
printf '%s\n' '--- evacuation methods ---'
sed -n '3328,3380p' cloud/apps/relay/src/assignment-store.ts
sed -n '4538,4620p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- admit-mode schema and lock implementation ---'
sed -n '350,375p' cloud/apps/relay/src/database.ts
sed -n '800,845p' cloud/apps/relay/src/database.ts
sed -n '1175,1215p' cloud/apps/relay/src/database.ts

Repository: stablyai/orca

Length of output: 9300


🏁 Script executed:

set -eu
printf '%s\n' '--- database classes and lock SQL ---'
rg -n -F --glob 'cloud/apps/relay/src/database.ts' -e 'function lockedStatement' -e 'class SqliteTransaction' -e 'class SqliteDatabase' -e 'class PostgresTransaction' -e 'async queryLocked' -e 'async transaction' cloud/apps/relay/src/database.ts
sed -n '780,860p' cloud/apps/relay/src/database.ts
sed -n '960,1045p' cloud/apps/relay/src/database.ts
sed -n '1160,1235p' cloud/apps/relay/src/database.ts
printf '%s\n' '--- admit-mode initialization ---'
rg -n -F --glob 'cloud/apps/relay/src/assignment-store.ts' -e 'relay_cell_admit_modes' -e 'ensureCellAdmission' cloud/apps/relay/src/assignment-store.ts

Repository: stablyai/orca

Length of output: 9876


Serialize admit-mode changes with operation transactions.

reserveModeCells() can return a cached db result for 5 seconds. prepareCellDrainAttempt() checks that result before its transaction. startEvacuation() checks the same cache inside its transaction. A reserve flip can commit before the drain or evacuation write, so both operations can succeed.

Use an uncached, locked admit-mode read inside each operation transaction. setCellAdmitMode() must acquire the same lock before checking for open work. The lock must cover cells with no admit-mode row because the schema treats a missing row as db.

Suggested fix
+  private async lockedCellAdmitMode(
+    cellId: string,
+    transaction: RelayDatabase,
+    now: number
+  ): Promise<'db' | 'reserve'> {
+    await transaction.query(
+      `INSERT INTO relay_cell_admit_modes (cell_id, admit_mode, updated_at)
+       VALUES (?, 'db', ?)
+       ON CONFLICT (cell_id) DO NOTHING`,
+      [cellId, now]
+    )
+    const row = (
+      await transaction.queryLocked(
+        `SELECT admit_mode FROM relay_cell_admit_modes WHERE cell_id = ?`,
+        [cellId]
+      )
+    )[0]
+    return row && text(row, 'admit_mode') === 'reserve' ? 'reserve' : 'db'
+  }
+
+  private async refuseReserveCellInTransaction(
+    cellId: string,
+    transaction: RelayDatabase,
+    now: number
+  ): Promise<void> {
+    if ((await this.lockedCellAdmitMode(cellId, transaction, now)) === 'reserve') {
+      throw new RelayCellInReserveModeError(cellId)
+    }
+  }
+
   async setCellAdmitMode(cellId: string, admitMode: 'db' | 'reserve'): Promise<void> {
     const now = this.now()
     await this.database.transaction(async (transaction) => {
+      await this.lockedCellAdmitMode(cellId, transaction, now)
       if (admitMode === 'reserve') {

Move the prepareCellDrainAttempt() check into its transaction and replace the checks inside startEvacuation() with refuseReserveCellInTransaction(..., transaction, now). Keep the outer startActiveCellEvacuations() checks only as early rejection; the locked checks in each startEvacuation() transaction must remain authoritative.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Do not treat an unknown reserve-mode set as empty. · assignment-store.ts:8011

cloud/apps/relay/src/assignment-store.ts:8011
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not treat an unknown reserve-mode set as empty.

If the first admit-mode query fails, reserveModeCells() returns null and reserveModeRead is unset. This fallback then admits every cell to placement, including a reserve-mode cell. Defer placement when there is no known set, or use a source that can establish which cells are eligible.

🟡 Minor · Map reserve-mode refusal on the evacuation-status route. · app.ts:1570-1572

cloud/apps/relay/src/app.ts:1570-1572
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Map reserve-mode refusal on the evacuation-status route.

If either cell is in reserve mode, cellEvacuationStatus() now throws RelayCellInReserveModeError. This handler rethrows that error instead of returning cell_in_reserve_mode, so the status request becomes a server error. Use rejectAdminOperation(context, error, 409) here, as the other guarded admin routes do.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: afbaea6e-ef2c-4ca2-a033-444c83654f65
📥 Commits

Reviewing files that changed from the base of the PR and between b5b5ac3 and 963b819.

📒 Files selected for processing (3)
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/assignment-reserve-mode-postgres.test.ts
  • cloud/apps/relay/src/assignment-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 changed the base branch from main to relay-step5-rollback October 10, 2026 02:18
@Jinwoo-H
Jinwoo-H changed the base branch from relay-step5-rollback to relay-step5-ledger October 10, 2026 02:39
…ep-5 census, inert)

Rebased onto main as one commit after its parent squash-merged.
@Jinwoo-H
Jinwoo-H changed the base branch from relay-step5-ledger to main October 10, 2026 23:12

@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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5ce78a39-1dde-44a8-b1a6-f15342f3f962
📥 Commits

Reviewing files that changed from the base of the PR and between 5748e19 and 1a3a1a6.

📒 Files selected for processing (16)
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/assignment-reserve-mode-census.test.ts
  • cloud/apps/relay/src/assignment-reserve-mode-postgres.test.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/cell-admit-effective-writer.test.ts
  • cloud/apps/relay/src/cell-admit-effective-writer.ts
  • cloud/apps/relay/src/cell-reserve-rollback.blackbox.test.ts
  • cloud/apps/relay/src/cell-seat-feed-route.ts
  • cloud/apps/relay/src/database.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/relay-server.ts
  • cloud/apps/relay/src/reserve-assignment.test.ts
  • cloud/apps/relay/src/reserve-assignment.ts
  • cloud/apps/relay/src/shadow-seat-directory.test.ts
  • cloud/apps/relay/src/shadow-seat-directory.ts
  • cloud/apps/relay/src/test-fixtures/reserve-mode-cell.ts

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

Comment on lines +816 to +819
async setCellAdmitMode(cellId: string, admitMode: 'db' | 'reserve'): Promise<void> {
const now = this.now()
await this.database.transaction(async (transaction) => {
if (admitMode === 'reserve') {

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject an unknown cellId in setCellAdmitMode.

setCellAdmitMode inserts a relay_cell_admit_modes row for any cellId. /v1/admin/cell-admit-mode does not validate the ID either. If an operator mistypes the ID, the call succeeds and returns admitMode: 'reserve' for a cell that does not exist. The real cell stays in database mode, so the sweeps keep acting on it after its switch file says reserve. Check relay_cells inside the transaction.

Proposed fix
     await this.database.transaction(async (transaction) => {
+      const known = await transaction.query(`SELECT cell_id FROM relay_cells WHERE cell_id = ?`, [cellId])
+      if (known.length === 0) throw new Error('cell_not_found')
       if (admitMode === 'reserve') {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async setCellAdmitMode(cellId: string, admitMode: 'db' | 'reserve'): Promise<void> {
const now = this.now()
await this.database.transaction(async (transaction) => {
if (admitMode === 'reserve') {
async setCellAdmitMode(cellId: string, admitMode: 'db' | 'reserve'): Promise<void> {
const now = this.now()
await this.database.transaction(async (transaction) => {
const known = await transaction.query(`SELECT cell_id FROM relay_cells WHERE cell_id = ?`, [cellId])
if (known.length === 0) throw new Error('cell_not_found')
if (admitMode === 'reserve') {

Comment on lines +3593 to +3594
await this.refuseReserveCell(sourceCellId)
await this.refuseReserveCell(targetCellId)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Map reserve-mode refusals on /v1/admin/evacuation-status to 409/503.

cellEvacuationStatus() now throws RelayCellInReserveModeError. The route in cloud/apps/relay/src/app.ts (lines 1656-1666) does not use rejectAdminOperation. It rethrows every non-transient error. A reserve-mode cell therefore returns a 500 instead of a 409. An unknown reserve-mode set (cellId === null) also returns a 500 instead of the retryable 503 that the other admin routes return. Rollout tooling retries only on 503, so an unreadable admit-mode table aborts that tooling.

Proposed fix in app.ts
     } catch (error) {
-      if (!isRelayDatabaseTransientError(error)) throw error
-      return context.json({ error: 'database_temporarily_unavailable' }, 503)
+      if (error instanceof RelayCellInReserveModeError || isRelayDatabaseTransientError(error)) {
+        return rejectAdminOperation(context, error, 409)
+      }
+      throw error
     }

@Jinwoo-H
Jinwoo-H merged commit a188831 into main Oct 10, 2026
27 of 44 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