Repository navigation
fix(relay): database sweeps and ops reads skip reserve-mode cells (step-5 census, inert) - #27046
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 Walkthrough
Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to 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 |
|
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
b40ab43d-05f0-439e-9838-8b1a95918075
📒 Files selected for processing (5)
cloud/apps/relay/src/assignment-reserve-mode-census.test.tscloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/relay-server.tscloud/apps/relay/src/shadow-seat-directory.test.tscloud/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')) && |
There was a problem hiding this comment.
🗄️ 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.
| return selection.candidates.filter( | ||
| (candidate) => | ||
| !reserveCells.has(candidate.sourceCellId) && !reserveCells.has(candidate.targetCellId) | ||
| ) |
There was a problem hiding this comment.
🗄️ 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.
| 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, |
There was a problem hiding this comment.
🗄️ 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’snull; 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 isnull.cloud/apps/relay/src/assignment-store.ts#L7882-L7882: defer database placement while membership isnull.
📍 Affects 2 files
cloud/apps/relay/src/relay-server.ts#L152-L152(this comment)cloud/apps/relay/src/assignment-store.ts#L645-L645cloud/apps/relay/src/assignment-store.ts#L7882-L7882
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
6857bb8a-2331-4da0-9005-0c79c4c56421
📒 Files selected for processing (5)
cloud/apps/relay/src/admin-token-verifier.test.tscloud/apps/relay/src/app.tscloud/apps/relay/src/assignment-reserve-mode-census.test.tscloud/apps/relay/src/assignment-store.tscloud/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.
| // Rolling a switched-on cell needs a flip back first (design default 4). | ||
| await this.refuseReserveCell(input.cellId) |
There was a problem hiding this comment.
🗄️ 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.tsRepository: 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]}")
PYRepository: 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.tsRepository: 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.tsRepository: 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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 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 liftDo not treat an unknown reserve-mode set as empty.
If the first admit-mode query fails,
reserveModeCells()returnsnullandreserveModeReadis 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 winMap reserve-mode refusal on the evacuation-status route.
If either cell is in reserve mode,
cellEvacuationStatus()now throwsRelayCellInReserveModeError. This handler rethrows that error instead of returningcell_in_reserve_mode, so the status request becomes a server error. UserejectAdminOperation(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
📒 Files selected for processing (3)
cloud/apps/relay/src/app.tscloud/apps/relay/src/assignment-reserve-mode-postgres.test.tscloud/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.
da6c37b to
680e462
Compare
…ep-5 census, inert) Rebased onto main as one commit after its parent squash-merged.
7620a51 to
1a3a1a6
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
5ce78a39-1dde-44a8-b1a6-f15342f3f962
📒 Files selected for processing (16)
cloud/apps/relay/src/app.tscloud/apps/relay/src/assignment-reserve-mode-census.test.tscloud/apps/relay/src/assignment-reserve-mode-postgres.test.tscloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/cell-admit-effective-writer.test.tscloud/apps/relay/src/cell-admit-effective-writer.tscloud/apps/relay/src/cell-reserve-rollback.blackbox.test.tscloud/apps/relay/src/cell-seat-feed-route.tscloud/apps/relay/src/database.test.tscloud/apps/relay/src/database.tscloud/apps/relay/src/relay-server.tscloud/apps/relay/src/reserve-assignment.test.tscloud/apps/relay/src/reserve-assignment.tscloud/apps/relay/src/shadow-seat-directory.test.tscloud/apps/relay/src/shadow-seat-directory.tscloud/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.
| async setCellAdmitMode(cellId: string, admitMode: 'db' | 'reserve'): Promise<void> { | ||
| const now = this.now() | ||
| await this.database.transaction(async (transaction) => { | ||
| if (admitMode === 'reserve') { |
There was a problem hiding this comment.
🎯 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.
| 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') { |
| await this.refuseReserveCell(sourceCellId) | ||
| await this.refuseReserveCell(targetCellId) |
There was a problem hiding this comment.
🎯 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
}
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
RelayAssignmentStoretakesreserveModeCells: the cells whose appliedadmitMode(from each cell's seat feed) isreserve, 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).mayNormallyReassignleastLoadedCell)relay_cell_admit_effectiverow says db (below)cell-statuscell_in_reserve_mode(a switched-on cell must be flipped back before a roll)assignment-reserve-mode-census.test.tsclassifies 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/StatusandstartEvacuationare 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 processrelay_cell_runtimeknows, and is under 45 s old. A cell on an older image writes no row and is never taken. The sweeps above still read onlyrelay_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.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.