Skip to content

test(relay): deterministic step-5 simulation with invariants 1-8 - #27040

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

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

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​340 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​340
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1254 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1254

ELI5

Before any cell runs step 5 for real, this test plays out thousands of desktops, five directors and thirty cells, with things breaking on purpose, and checks that no cell ever goes over its limit and no desktop ends up owned by two cells.

What Changed

reserve-placement-simulation.ts is a seeded discrete-event model that drives the real CellReserveBook and ReservePlacer (from the parent PR). Sockets, Postgres and desktops are modelled. Scenarios, 3 seeds each:

  • Mixed fleet, 25 min: 24 US + 6 Asia cells, a third in database mode and one on a pre-step-5 image; one director still on the database-only revision; poll lag 0 / 0.2 / 1 / 4 / 10 s; duplicate assigns; half-open controls; two cell restarts; two director restarts; 7 s database stalls every 610 s.
  • Near full: 17 US cells at 97 %.
  • Drain onto an empty cell: the c27 shape (free seats 2,805 / 841 / 777 / 667 / 26) at the 1,200 s and 300 s paces.

Invariants checked: (1) seats + bookings never over the hard cap, after every event; (2) ok bookings in any window ≤ burst + rate × window, per incarnation; (3) no host holds two live seats past poll lag + grace; (4) no demotion ever lands on the desktop's live control, and no host loses every seat; (5) the ledger epoch never falls, and after a reconcile each seat's row is that seat; (6) ≤ 3 reserve calls per request; (7) a database mint is above every epoch the map knew; (8) near full, extra calls ≤ 10 % and exhausted requests ≤ 1 %; (9) once a reserve cell's dead-man has tripped (while Postgres still says reserve), today's database path takes it within 20 s by the row the cell writes itself (raw mode, current process, under 45 s old). This must hold whether the directors' feed polls come back after 150 s or never come back; fault pgReserveBlocksDatabase ignores the row and must trip it. A tripped cell reports reserve while it re-registers (modelled delay), but placing directors read its raw mode and book nothing there. Fault noRawFeedMode sends it 118 bookings that it refuses.

Each invariant except 6 also has a fault run that breaks its rule (book past the cap, a 200-token burst with greedy directors, no demotion, a director that keeps the oldest seat, an unguarded ledger, no epoch floor) and must trip it, so a pass is not vacuous.

Why

The design (§9) gates every production flip on this simulation. Driving the production modules rather than a separate model means a bug in either decision-maker shows up here.

Three design gaps the simulation found, fixed in the parent PR and here:

  1. Demotion by epoch alone hit live controls. A director that is a few seconds behind can name a seat whose host has since rejoined the same cell at the same epoch. The demote request now names the seat by joinedAt too.
  2. A host that flaps across three cells kept an old seat alive. "Wait until every seat is older than the grace period" never fires while a newer seat keeps arriving. A seat is now demoted once it has been outranked for the grace period.
  3. An unused database-path answer left the row pointing at the wrong cell. When two directors answer the same desktop, one through a booking and one through today's database path at an equal or higher epoch, the desktop uses one answer, and the guarded ledger write can never correct the row. The model's reconcile corrects such a row with a compare-and-set only when the map can see the named cell and the host is not seated there. This is the one write that may lower an epoch; the ledger-writer PR carries the same rule.

Linked Issue

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

Visual Proof

N/A: test only.

Testing

  • vitest run src/reserve-placement-simulation.test.ts: 24 tests, ~25 s locally.

Row-ahead repair (invariant 8), measured

Run: 25 min, 5 directors (one old), 6,600 hosts, 10% duplicate assigns, seed 11. Re-measured after observePoll was removed.

Row-ahead demotions First re-seats behind or level with the row Demotions per host (max / p99)
WRONG_CELL row read (shipped in #27048) 514 13 (2.5%) 2 / 2
Without the row read 568 46 (8.1%) 3 / 2

A director whose map has not yet seen the leave can re-place level with the row; the next reconcile repairs it. The hard invariant is at most 2 demotions behind one divergence (the same row); fault mintAtFloor (placement never rises above the row) breaks it ("demoted 3 times behind its row"). Re-seats that miss are reported, not violations.

Feed outage that never ends: the first fresh placement lands 63 s in, when the first cell trips (60-120 s per cell); before that, a region where every cell is reserve has no new placement.

Cold start: a restarted director's per-cell estimates start empty and refill at its share of the cell's intake, so it books nothing on a cell for 1 / (intakePerSec / directors) s and paces the rest; the startup gate holds hosts that may be on an unheard cell for up to 30 s.

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

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

Adds a seeded discrete-event simulation that exercises CellReserveBook and ReservePlacer. The simulation models placement, cell and director events, database behavior, and invariant checks. New tests cover configured fleet scenarios, recovery paths, and injected faults.





Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 529f5

This change adds a deterministic test simulation for reserve placement and does not change production behavior. The remaining suggestions would improve test diagnostics and confidence in reproducibility, but they do not block merging.

Pre-merge checks | Passed 3 | Failed 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 22.73% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check Warning The description explains the simulation, scenarios, invariants, rationale, and testing. However, it omits required template sections such as AI Disclosure, Review, Agent skill upstream boundary, Notes… Add all required template sections and complete them. Provide the required linked issue instead of N/A, complete the checklist and review details, document AI disclosure or state the applicable internal-contributor exception, and address th…
✅ Passed checks (3 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 change as a deterministic Step 5 simulation with invariants 1–8. It is concise and directly related to the main changes.

Full details: Description check

Explanation

The description explains the simulation, scenarios, invariants, rationale, and testing. However, it omits required template sections such as AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist, and it marks Linked Issue as N/A despite the template requiring an actual issue link.

Resolution

Add all required template sections and complete them. Provide the required linked issue instead of N/A, complete the checklist and review details, document AI disclosure or state the applicable internal-contributor exception, and address the Notes requirements.


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

🧹 Nitpick comments (1)
cloud/apps/relay/src/reserve-placement-simulation.ts (1)

18-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test that one seed gives one result.

The suite relies on seededRandom and on the claim that the simulation is "deterministic". No test checks that two runs with the same seed give the same SimulationReport. Hidden nondeterminism can make seeded failures impossible to reproduce. Examples are a stray Math.random, Date.now in a dependency, or the order of async continuations. Add a short-duration test that runs one config twice and compares the reports with toEqual. The short duration keeps the extra runtime small. Also check that seededRandom(seed) gives the same sequence from two separate instances.

♻️ Proposed test
it('is deterministic for a seed', async () => {
  const config = { ...mixed({}), durationMs: 2 * 60_000 }
  const first = await runReservePlacementSimulation(config)
  const second = await runReservePlacementSimulation(config)
  expect(second).toEqual(first)
  const a = seededRandom(11)
  const b = seededRandom(11)
  expect(Array.from({ length: 100 }, a)).toEqual(Array.from({ length: 100 }, b))
})

Based on learnings: "For any seeded pseudo-random number generator (PRNG) implementation, require a determinism test verifying that initializing with the same seed produces an identical output sequence across separate instances/runs."

Source: Learnings


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0f86b362-f915-4c7d-9b51-67219a4a16fa
📥 Commits

Reviewing files that changed from the base of the PR and between 33a1ddf and 529f5a4.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/reserve-placement-simulation.test.ts
  • cloud/apps/relay/src/reserve-placement-simulation.ts

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

Comment on lines +506 to +508
const violate = (invariant: number, detail: string): void => {
if (violations.length < 50) violations.push({ invariant, at: clock.now, detail })
}

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

Cap violations per invariant, not across all invariants.

The comment at Line 15-16 says one run "reports every class it hit". violate stops recording after 50 violations of any kind. After that, a different invariant that fires later is dropped without notice.

This has two effects:

  • The fault tests check toContain(invariant). If an early run of another invariant fills the cap, the target invariant is lost and the test fails, even though the check worked.
  • Clean-run failures show only the first 50 entries. A second, independent invariant class can be hidden.

Keep a separate counter for each invariant number.

🐛 Proposed fix
--- "a/cloud/apps/relay/src/reserve-placement-simulation.ts"
+++ "b/cloud/apps/relay/src/reserve-placement-simulation.ts"
@@ -502,10 +502,13 @@
 ): Promise<SimulationReport> {
   const random = seededRandom(config.seed)
   const clock = new Clock()
   const violations: SimulationViolation[] = []
+  const violationCounts = new Map<number, number>()
   const violate = (invariant: number, detail: string): void => {
-    if (violations.length < 50) violations.push({ invariant, at: clock.now, detail })
+    const count = violationCounts.get(invariant) ?? 0
+    violationCounts.set(invariant, count + 1)
+    if (count < 20) violations.push({ invariant, at: clock.now, detail })
   }
   const faults = config.faults ?? {}
   const database = new SimDatabase(violate, faults)
   const cells = config.cells.map(

@Jinwoo-H
Jinwoo-H merged commit 3c6c24f 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