Skip to content

feat(relay): the director that booked a join writes its row about a second later (off) - #27048

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

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

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​270 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​268
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​394 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​387

ELI5

A switched-on cell lets a booked desktop in without the database. The database still needs a record of where each desktop is (phones look it up until step 6), so the director that booked the desktop writes that record about a second later, and keeps trying through a database stall.

What Changed

  • ReserveLedgerWriter: when the seat feed shows a join with reservedBy equal to this director's id, the director queues the host's (cell, epoch). Every 250 ms it writes up to 500 queued rows in one multi-row upsert of relay_assignments, guarded by WHERE assignment_epoch < excluded.assignment_epoch. A demotion winner is written with <=, the only path that can replace an equal epoch (every director names the same winner). It touches no relay_cells row and no activity lease.
  • A row whose cell changes drops its counters. The leases behind them keep their own cell id, so they settle on the old cell as today; units no lease backs stay counted on the old cell until its next drain reconcile. That only makes the old cell look fuller.
  • On a write failure the queue is kept and retried with backoff (250 ms to 5 s). Past 200k entries the oldest are dropped and counted. A per-minute orca_relay_reserve_ledger_summary line reports written, pending, dropped and failures.
  • Reconcile, every 10 min plus up to 60 s of jitter: the map's seats on switched-on cells (older than 30 s) are upserted under the same guard.
  • Correction (design gap found by the simulation, test(relay): deterministic step-5 simulation with invariants 1-8 #27040). If two directors answer the same desktop, one by booking and one through today's database path at an equal or higher epoch, and the desktop uses the booking, then no guarded write can ever fix the row, and phones are sent to the wrong cell. The reconcile corrects such a row by compare-and-set, only when the row names a polled, live cell that does not seat the host. This is the one write that may lower an epoch.

Only with ORCA_RELAY_RESERVE_PLACEMENT=on, and only for joins this director booked, so nothing is written while every cell is off.

Why

Design §6.2, default 2 (≤ 1 s). Nothing on a switched-on cell's connect path reads the row; phones (/v1/resolve) and a flip back (#27043) do.

Linked Issue

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

Visual Proof

N/A: server-side, no UI.

Testing

  • reserve-ledger-writer.test.ts (SQLite): only a higher epoch replaces a row; only a demotion winner replaces an equal one; a moved row drops its counters and a same-cell row keeps them; a stall keeps the queue and backs off; the bound drops the oldest; reconcile upserts settled seats, skips young ones and corrects an orphaned row; a row naming a cell that may still seat the host is left alone.
  • The full relay suite passes locally.

…econd later (off)

Rebased onto main as one commit after its parent squash-merged.
@Jinwoo-H
Jinwoo-H changed the base branch from relay-no-feed-cells to main October 10, 2026 22:55
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The relay now writes reserve-mode assignments to a ledger and periodically reconciles ledger rows with shadow seats. Reserve assignment tracks expiring row epoch floors, uses bounded row reads for wrong-cell leaves, and rejects sticky reconnects at or below the floor. The relay server starts this workflow for eligible directors and enqueues qualifying booked joins.

Estimated code review effort





Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 680e4

These failures require unusual queue pressure or a director configuration without rehome support. The change is mergeable with owner awareness, though both issues should be fixed.

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 6 functions across 8 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: the director that books a join writes the reserve ledger row shortly afterward. The “(off)” qualifier indicates the feature is disabled by default.
Description check Passed The description includes the main required sections, explains the user-facing behavior, implementation, rationale, testing, and visual-proof status. It omits the Review, Agent skill upstream boundary,…

  • 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: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0ca1adda-5e04-4c20-9352-631ca232efea
📥 Commits

Reviewing files that changed from the base of the PR and between 3f7943c and 680e462.

📒 Files selected for processing (8)
  • cloud/apps/relay/src/floating-promise-census.test.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/reserve-ledger-writer-postgres.test.ts
  • cloud/apps/relay/src/reserve-ledger-writer.test.ts
  • cloud/apps/relay/src/reserve-ledger-writer.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; 9 remain after this review.

Comment on lines +193 to +197
// Only a director that books writes rows, and only for the joins it booked.
const reserveLedger =
config.role === 'director' && shadowSeatPoller && config.reservePlacement === 'on'
? new ReserveLedgerWriter(observedDatabase, { now: options.now })
: undefined

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

A director without rehomeAudience creates the writer, but it cannot demote seats.

reserveLedger is created without a rehomeAudience check. reservePlacement does require rehomeAudience. If rehomeAudience is missing, reservePlacement is undefined. The demote callback then does nothing except log a warning, and reconcileReserveLedger still counts the seat as demoted. Such a director also books nothing, so the writer has no purpose there. Add the same condition: create the writer only when reservePlacement?.placementMode === 'on'.

Comment on lines +69 to +99
this.queue.splice(0, excess)
this.dropped += excess
}
}

pending(): number {
return this.queue.length
}

// Single-flight; resolves once the queued rows are written or the attempt failed.
async flush(): Promise<void> {
if (this.flushing || this.queue.length === 0 || this.now() < this.retryAt) {
this.logSummary()
return
}
this.flushing = true
const batch = this.queue.slice(0, RESERVE_LEDGER_BATCH)
try {
await this.write(batch)
this.queue.splice(0, batch.length)
this.written += batch.length
this.failures = 0
this.retryAt = 0
} catch {
this.failures += 1
this.retryAt = this.now() + Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (this.failures - 1))
} finally {
this.flushing = false
this.logSummary()
}
}

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 | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '27,105p' cloud/apps/relay/src/reserve-ledger-writer.ts
sed -n '60,80p' cloud/apps/relay/src/reserve-ledger-writer.test.ts

Repository: stablyai/orca

Length of output: 3355


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- writer ---'
nl -ba cloud/apps/relay/src/reserve-ledger-writer.ts | sed -n '1,180p'
printf '%s\n' '--- writer references ---'
rg -n -F --glob '*.ts' -- 'new ReserveLedgerWriter' cloud/apps/relay/src || true
rg -n -F --glob '*.ts' -- '.enqueue(' cloud/apps/relay/src | rg 'writer|ledger|reserve' || true
printf '%s\n' '--- queue/flush tests ---'
rg -n -F --glob 'reserve-ledger-writer.test.ts' -- 'flush|enqueue|queueMax|pending|in flight|Promise' cloud/apps/relay/src || true
nl -ba cloud/apps/relay/src/reserve-ledger-writer.test.ts | sed -n '1,150p'

Repository: stablyai/orca

Length of output: 16612


🏁 Script executed:

nl -ba cloud/apps/relay/src/relay-server.ts | sed -n '175,260p'
rg -n -F --glob 'relay-server.ts' -- 'reserveLedger.start' 'reserveLedger.flush' 'ORCA_RELAY_RESERVE_PLACEMENT' cloud/apps/relay/src || true

Repository: stablyai/orca

Length of output: 4582


Remove only the entries that the successful write actually used.

flush() snapshots a batch, awaits write(batch), then removes batch.length entries from the current queue. If enqueue() overflows during that await, it can already remove the batch’s oldest entries. The later count-based splice() can then remove newer entries that were never written.

Use stable queue-entry identities and remove only the snapshot entries still present after the write.

Suggested fix
+type QueuedLedgerEntry = { id: symbol; entry: LedgerEntry }
+
 export class ReserveLedgerWriter {
-  private queue: LedgerEntry[] = []
+  private queue: QueuedLedgerEntry[] = []
...
   enqueue(entry: LedgerEntry): void {
-    this.queue.push(entry)
+    this.queue.push({ id: Symbol(), entry })
...
-    const batch = this.queue.slice(0, RESERVE_LEDGER_BATCH)
+    const batch = this.queue.slice(0, RESERVE_LEDGER_BATCH)
     try {
-      await this.write(batch)
-      this.queue.splice(0, batch.length)
+      await this.write(batch.map(({ entry }) => entry))
+      for (const queued of batch) {
+        const index = this.queue.findIndex(({ id }) => id === queued.id)
+        if (index >= 0) this.queue.splice(index, 1)
+      }

@Jinwoo-H
Jinwoo-H merged commit fda01fa into main Oct 10, 2026
36 of 56 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