Skip to content

feat(relay): report lane service times, 503 causes, per-site hold p99 and a director-vs-cell lock-wait split - #25645

Merged
Jinwoo-H merged 4 commits into
mainfrom
relay-step1-observability
Oct 5, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
relay-step1-observability

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

ELI5

We are about to decide whether drains, reconnect herds and the relay database lock are the bottleneck. Today the director cannot answer those questions: it does not report how long each admission lane holds a slot, it lumps scheduled "come back in N seconds" drain answers together with real failures, and nothing can tell a director's database lock wait from a cell's. This adds those numbers to the existing 30-second runtime metrics line.

What Changed

All new fields ride the existing orca_relay_runtime_metrics line; no new metrics line.

  • Lane service times. drainReturnServiceMsP50/P95 reports the raw sample the drain-return lane already fed its pacing estimate (drain-return-admission.ts), unclamped. stickyServiceMsP50/P99 is how long a sticky slot is held, verification read included. Both are omitted when the lane served nothing, like the accept percentiles.
  • 503s by cause. Every /v1/assign 503 records a cause (sticky-lane, placement-lane, drain-return-deferred, relay_capacity_exhausted, relay_assignment_row_busy, database, …) in assign503sByCauseDelta. assignNonDrain503sDelta is the total excluding scheduled drain-return deferrals.
  • Per-site lock hold p99. CellInventoryHoldSamples now reports inventoryHoldMsP99, rehomeTargetRowHoldMsP99 and isolatedReplacementHoldMsP99. The drain-return path's regional row lock (lockIsolatedReplacementCells) was not sampled at all; it now records under its own isolated-replacement site.
  • Director-vs-cell lock-wait split. Every 5 s each director samples pg_stat_activity for relay backends in a Lock wait (single-flight).
    • Each waiter is keyed by its role, the first relay table its statement names (relay_cells / relay_assignments / other), and the role of the root of its wait chain. Roles come from application_name (orca-relay/<role>/<cell>).
    • The root matters because in a row-lock convoy every later waiter is blocked by the first waiter's tuple lock, not by the transaction holding the row. A recursive CTE walks pg_blocking_pids, calling it once per waiter.
    • Emitted as dbLockWaitersByKeyDelta with dbLockWaitSamplesDelta, plus flat dbCellRowLockWaiters{Director,Cell}Delta.
  • Reservation drift. Reconciliation logs orca_relay_reservation_drift {cellId, reservedRequests, leaseUnits} for each cell whose counter it corrects, after COMMIT.
  • Terraform (relay-observability.tf): 12 new entries in the relay_snapshot log-metric map and one relay_incident counter (reservation_drift). Not applied.
  • Short paragraph in docs/orca-relay-operations.md.

Why

These are the inputs the next steps are gated on (drain-pace ladder, the conditional drain-return lock change, the step-2 one-round-trip commit):

  • Drain-lane capacity = concurrency / service time, so the gate needs the service time.
  • A gate on all 503s trips on every fast drain, because a drain deliberately answers 503 + Retry-After to hosts it will serve later.
  • Whether drain returns wait on their own regional rows or on the inventory lock needs a separate p99 per lock.
  • Directors and cells connect as the same database user through a Unix socket, so pg_stat_statements and Query Insights (user / client address) cannot split them. I checked this read-only in production: every relay backend shows client address local and user orca_relay, with application_name the only role marker.

Alternatives considered for the lock-wait split:

  • Query Insights tags (sqlcommenter) need an instance-level setting on the shared auth instance, which lives outside this repo.
  • Separate database users per role need new credentials and a cell roll.
  • Measuring wait inside each process cannot separate lock wait from the Asia round trip, and cells would only report it after their next roll.

The director-side sample works with a director-only deploy and reads shared state without locking any relay row. It calls pg_blocking_pids once per waiting backend. The reviewer timed it at 0.37 ms with 20 waiters and 97 backends. The cost is 1 query/s fleet-wide (5 directors at 5 s).

Linked Issue

N/A (internal relay observability)

Visual Proof

N/A: server-side metrics and logs, no UI.

Testing

  • pnpm lint (tsc, all cloud packages), pnpm test at cloud/ on a fresh local Postgres 16: relay 114 files / 1013 tests, all other workspaces, and both node --test sets (189 + 681) pass. terraform fmt -check passes.

  • New tests: per-site p99; drain-return service samples reported once and unclamped; 503 cause split and non-drain total; lane service fields omitted when empty; lock-waiter sums; app-level causes for a drain deferral, a sticky rejection and a capacity-exhausted placement; sticky slot timing including the drained host's verification hold; the drain return's regional lock recorded under its own site; drift logged once and only after commit; a real-Postgres test where 3 directors queue behind a cell-held relay_cells row and the sample reports all 3 as director:relay_cells:cell. With the first-blocker query this test reports 2 of them as held by a director.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Review

Operational notes for whoever ships this:

  • cloud/infra/terraform/relay-observability.tf is in the evidence-code set (relay-evidence-code-provenance.mjs). Merging it invalidates any in-flight or sealed monitor dry-run, so merge between rolls and run a fresh monitor afterwards.

  • The log metrics need a targeted apply. A root plan rolls the fleet. The targets:

    • google_logging_metric.relay_snapshot["<key>"] for inventory_hold_ms_p99, rehome_target_row_hold_ms_p99, isolated_replacement_hold_ms_p99, isolated_replacement_holds, drain_return_service_ms_p50, drain_return_service_ms_p95, sticky_service_ms_p50, sticky_service_ms_p99, assign_non_drain_503s, db_lock_wait_samples, db_cell_row_lock_waiters_director, db_cell_row_lock_waiters_cell;
    • google_logging_metric.relay_incident["reservation_drift"].

    These are additions only; existing metric instances are untouched. The fields are in the logs from the deploy on, with or without the apply.

  • Expected alert change (documented, not suppressed). Drain-return regional holds now feed the shared cellInventoryHoldMsMax / P95 and cellInventoryHoldMaxSite, as every other site already does.

    • The non-paging policy "director cell table lock held over 1 second" can now fire on a ≥ 1 s drain-return hold during a roll. cellInventoryHoldMaxSite: isolated-replacement names it, and it needs no action.
    • The director's cellInventoryLockUnavailable / cellInventoryLockTimeouts also now include that lock. Compare them across this deploy only with the site subtracted. The DECISION item-1 gate should read orca_relay_cloud_sql_lock_timeouts, which is unaffected.
    • The paging cell policy is unchanged, because drain returns run only on directors.
    • Documented in docs/relay-incident-monitor.md under "Relay lock contention alert policies".
    • I chose documenting over excluding the site: excluding it would need special cases in both the hold samples and the Postgres counters.
  • The inventory log line ([orca-relay] regional rehome inventory …), which the enable workflow parses, is untouched.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No wire, schema, lock-order or placement-decision change. Cells pick up the drift log and hold-site fields with their next image; everything else is director-side. Rebased on main after #25638 merged, so the drift log reports the post-lock units. Sessions from the combined role (staging's single-service mode, where the sampler also runs) are labelled combined, not other; they were never misread as director or cell.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… and lock-wait split

Adds the step-1 observability: drain-return and sticky slot service times,
every /v1/assign 503 by cause with a non-drain total, a p99 per lock hold
site (drain-return regional rows get their own site), a director-side
pg_stat_activity sample that splits lock waiters by director vs cell, and
a log line for each reserved_requests drift reconciliation corrects.
Log-based metrics for the new fields are declared in Terraform, not applied.
@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.

📝 Walkthrough

Walkthrough

Reservation reconciliation now logs corrected reservation counts after its transaction. Cell-lock measurements distinguish the isolated-replacement site and report per-site p99 values. Assignment handling records sticky and drain-return service times and classifies unavailable outcomes. Assignment-maintenance roles sample PostgreSQL lock waiters. Runtime metrics, Terraform mappings, tests, and operations documentation cover these observations.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to d0e67

Lock-wait telemetry cannot distinguish combined-role sessions from other sessions, making diagnosis less precise. This is bounded and does not block merging, but the role mapping should be corrected.

🚥 Pre-merge checks | ✅ 2 | ❌ 2 | ❓ 1

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The drift log and its test relate to #25638. The lane service-time metrics, 503 cause metrics, general database lock-wait sampling, Terraform metric declarations, and related operations documentation … Separate the unrelated observability work into a separately scoped change or provide an active linked issue that covers those objectives.
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 15 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive #25638 requires reading lease units after locking the cell rows and adding a PostgreSQL concurrency test for placement during reconciliation. The PR diff changes reconciliation to log corrected counte… A focused view of the reviewed-head reconciliation query order and the PostgreSQL reconciliation-versus-placement test is needed to determine whether #25638 is satisfied.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the PR’s main observability changes, including lane service times, 503 causes, per-site hold p99 metrics, and lock-wait attribution. It is specific, though longer than pre…
Description check ✅ Passed The description covers the required explanation, changes, rationale, testing, visual-proof status, review notes, and checklist. It marks the linked issue as not applicable for internal work and identi…
Full details: Linked Issues check

Explanation

#25638 requires reading lease units after locking the cell rows and adding a PostgreSQL concurrency test for placement during reconciliation. The PR diff changes reconciliation to log corrected counters after commit, but it does not show a change to the lease-read order or a new test for that race. I could not establish whether the required behavior and test already exist at the reviewed head.

Full details: Out of Scope Changes check

Explanation

The drift log and its test relate to #25638. The lane service-time metrics, 503 cause metrics, general database lock-wait sampling, Terraform metric declarations, and related operations documentation do not implement or test #25638's reconciliation counter requirement. The PR description identifies these as a separate observability effort, but no active linked issue for that scope is provided.

Full details: Docstring Coverage

Explanation

Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 15 files. (1 skipped: 1 unsupported.)

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

@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: f0a84d51-97cf-4844-9737-bafe49ec88d7
📥 Commits

Reviewing files that changed from the base of the PR and between 98171a8 and c62ece3.

📒 Files selected for processing (17)
  • cloud/apps/relay/src/app.ts
  • cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts
  • cloud/apps/relay/src/assignment-store.test.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/cell-inventory-hold-samples.test.ts
  • cloud/apps/relay/src/cell-inventory-hold-samples.ts
  • cloud/apps/relay/src/drain-return-admission.test.ts
  • cloud/apps/relay/src/drain-return-admission.ts
  • cloud/apps/relay/src/index.ts
  • cloud/apps/relay/src/postgres-lock-wait-sample-postgres.test.ts
  • cloud/apps/relay/src/postgres-lock-wait-sample.ts
  • cloud/apps/relay/src/public-assignment-drain-return-lane.test.ts
  • cloud/apps/relay/src/relay-observability.test.ts
  • cloud/apps/relay/src/relay-observability.ts
  • cloud/apps/relay/src/relay-server.ts
  • cloud/docs/orca-relay-operations.md
  • cloud/infra/terraform/relay-observability.tf

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

Comment on lines 7488 to +7511
@@ -7495,8 +7497,18 @@ export class RelayAssignmentStore {
`UPDATE relay_cells SET reserved_requests = ?, updated_at = ? WHERE cell_id = ?`,
[expected, now, cellId]
)
corrected.push({
cellId,
reservedRequests: integer(row, 'reserved_requests'),
leaseUnits: expected
})
}
return corrected
})
// Logged after COMMIT so a retried transaction reports each correction once.
for (const sample of drift) {
console.warn(JSON.stringify({ event: 'orca_relay_reservation_drift', ...sample }))
}

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 '7370,7520p' cloud/apps/relay/src/assignment-store.ts
git diff 2a68ea94967caf926aa60ebbd2bb32797bebb146 c62ece3a77883d7eb45712c77e0a65fe5dc5cf51 -- cloud/apps/relay/src/assignment-store.ts

Repository: stablyai/orca

Length of output: 9846


🏁 Script executed:

printf '%s\n' '--- full PR changed paths ---'
git diff --name-status 2a68ea94967caf926aa60ebbd2bb32797bebb146 c62ece3a77883d7eb45712c77e0a65fe5dc5cf51
printf '%s\n' '--- base reconciliation block ---'
git show 2a68ea94967caf926aa60ebbd2bb32797bebb146:cloud/apps/relay/src/assignment-store.ts | sed -n '7368,7510p'
printf '%s\n' '--- relevant references/tests ---'
rg -n -i 'reconcileReservationAccounting|reservation accounting|reserved_requests|concurrent.*(placement|reconcil)|reconcil.*concurr|lockCellRows|lease units|leaseUnits' cloud/apps/relay --glob '*.{ts,sql,md}' || test "$?" -eq 1
printf '%s\n' '--- transaction/locking definitions ---'
rg -n 'queryLocked|class .*Transaction|transaction\(' cloud/apps/relay/src --glob '*.{ts}' | head -120

Repository: stablyai/orca

Length of output: 41997


🏁 Script executed:

printf '%s\n' '--- reconciliation callers ---'
sed -n '2340,2450p' cloud/apps/relay/src/assignment-store.ts
sed -n '3240,3305p' cloud/apps/relay/src/assignment-store.ts
sed -n '3390,3450p' cloud/apps/relay/src/assignment-store.ts
sed -n '5070,5140p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- placement / lease insertion and reservation update ---'
sed -n '760,845p' cloud/apps/relay/src/assignment-store.ts
sed -n '1200,1290p' cloud/apps/relay/src/assignment-store.ts
sed -n '6230,6305p' cloud/apps/relay/src/assignment-store.ts
sed -n '8450,8510p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- reconciliation tests and relevant PR test diffs ---'
sed -n '620,815p' cloud/apps/relay/src/postgres-transaction-recovery.test.ts
git diff 2a68ea94967caf926aa60ebbd2bb32797bebb146 c62ece3a77883d7eb45712c77e0a65fe5dc5cf51 -- cloud/apps/relay/src/assignment-store.test.ts cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts cloud/apps/relay/src/postgres-transaction-recovery.test.ts
printf '%s\n' '--- database lock/query implementation ---'
rg -n 'queryLocked|READ COMMITTED|REPEATABLE READ|isolation|FOR UPDATE|beginTransaction|BEGIN' cloud/apps/relay/src/database.ts cloud/apps/relay/src/*database* cloud/apps/relay/src --glob '*.{ts}' | head -180

Repository: stablyai/orca

Length of output: 42108


🏁 Script executed:

printf '%s\n' '--- activity acquisition declarations and callers ---'
rg -n 'async acquireActivity|acquireActivity\(|INSERT INTO relay_assignment_activity_leases|lockAssignmentActivities|assignStickyOnce|async assign\\(' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- placement/activity implementation candidates ---'
sed -n '500,760p' cloud/apps/relay/src/assignment-store.ts
sed -n '3600,3900p' cloud/apps/relay/src/assignment-store.ts
sed -n '4350,4445p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- exact reconciliation concurrency test ---'
rg -n -C 12 'assignment-first lock order|while activity waits|reconcil' cloud/apps/relay/src/postgres-transaction-recovery.test.ts
printf '%s\n' '--- postgres queryLocked and transaction methods ---'
sed -n '1000,1095p' cloud/apps/relay/src/database.ts
printf '%s\n' '--- assignment lock-order contract ---'
sed -n '350,425p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- changed concurrency tests in PR ---'
git diff 2a68ea94967caf926aa60ebbd2bb32797bebb146 c62ece3a77883d7eb45712c77e0a65fe5dc5cf51 -- cloud/apps/relay/src/assignment-store.test.ts cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts cloud/apps/relay/src/cell-inventory-hold-samples.test.ts cloud/apps/relay/src/postgres-lock-wait-sample-postgres.test.ts | rg -n -C 8 'reconcil|concurr|activity waits|assignment-first|leaseUnits|cell row|placement'

Repository: stablyai/orca

Length of output: 42362


🏁 Script executed:

printf '%s\n' '--- assignOnce implementation ---'
rg -n 'private async assignOnce|async assignOnce|INSERT INTO relay_assignment_activity_leases|control-pending:' cloud/apps/relay/src/assignment-store.ts | head -80
sed -n '870,1275p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- assignmentRow and lockAssignmentActivities helpers ---'
rg -n 'private async assignmentRow|private assignmentRow|assignmentRow\\(|lockAssignmentActivities\\(' cloud/apps/relay/src/assignment-store.ts | tail -45
sed -n '8570,8675p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- exact PostgreSQL reconciliation lock-order test candidates ---'
rg -n 'assignment-first|activity waits|reconcil.*activity|activity.*reconcil' cloud/apps/relay/src/postgres-transaction-recovery.test.ts cloud/apps/relay/src/assignment-store.test.ts || test "$?" -eq 1
sed -n '630,810p' cloud/apps/relay/src/postgres-transaction-recovery.test.ts
printf '%s\n' '--- PostgreSQL transaction isolation configuration ---'
rg -n 'default_transaction_isolation|SET TRANSACTION|isolation level|BEGIN ISOLATION|READ COMMITTED' cloud/apps/relay/src cloud/infra --glob '*.{ts,sql,tf,md}' || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 31757


🏁 Script executed:

printf '%s\n' '--- new-assignment final write sequence ---'
sed -n '1230,1375p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- pending-control lease writer ---'
rg -n -F 'private async insertPendingControlLease' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- cell reservation locking helpers ---'
sed -n '8455,8505p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- reconciliation current head exact order ---'
sed -n '7373,7515p' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- PR diff for reconciliation only ---'
git diff --unified=3 2a68ea94967caf926aa60ebbd2bb32797bebb146 c62ece3a77883d7eb45712c77e0a65fe5dc5cf51 -- cloud/apps/relay/src/assignment-store.ts | sed -n '/reconcileReservationAccounting/,/private async lockCellInventory/p' | head -100

Repository: stablyai/orca

Length of output: 14439


🏁 Script executed:

sed -n '8105,8155p' cloud/apps/relay/src/assignment-store.ts
nl -ba cloud/apps/relay/src/assignment-store.ts | sed -n '7415,7510p'
nl -ba cloud/apps/relay/src/assignment-store.ts | sed -n '994,1048p;1260,1330p'
nl -ba cloud/apps/relay/src/postgres-transaction-recovery.test.ts | sed -n '719,797p'

Repository: stablyai/orca

Length of output: 16933


Refresh cell lease units after locking the cells.

If a new assign() holds the target cell row while reconciliation reads leases, its assignment and pending-control lease are not in that result. Reconciliation can then wait for the cell lock and overwrite reserved_requests using the earlier snapshot, omitting the committed placement. The new drift sample can also report stale leaseUnits. Keep the locked lease read for assignment counters, but re-read the source and target cell lease units after lockCellRows with a non-locking query.

Suggested fix
       const cells = await this.lockCellRows(
         transaction,
         [sourceCellId, targetCellId],
         'pool-default'
       )
+      const reservationLeases = await transaction.query(
+        `SELECT cell_id, request_units FROM relay_assignment_activity_leases
+         WHERE cell_id IN (?, ?)`,
+        [sourceCellId, targetCellId]
+      )
       const assignmentKeys = new Set(
         assignments.map((row) =>
           assignmentKey(text(row, 'user_id'), text(row, 'relay_host_id'))
@@
         const kind = activityKind(lease)
         current.counts[kind]++
         current.leaseExpiresAt = Math.max(current.leaseExpiresAt, integer(lease, 'expires_at'))
         assignmentCounts.set(key, current)
-        cellUnits.set(cellId, (cellUnits.get(cellId) ?? 0) + integer(lease, 'request_units'))
+      }
+      for (const lease of reservationLeases) {
+        const cellId = text(lease, 'cell_id')
+        cellUnits.set(cellId, (cellUnits.get(cellId) ?? 0) + integer(lease, 'request_units'))
       }
 
       for (const row of assignments) {

…irector hold alert change

Every waiter after the first in a row-lock convoy is blocked by the first
waiter, so the sample now walks pg_blocking_pids to the root, reading it once
per waiter. The sampler is single-flight. Drain-return regional holds feeding
the non-paging director hold policy is documented as expected.
Jinwoo-H added a commit that referenced this pull request Oct 5, 2026
…minutes, and seal the canary's pace verdict

Review of #25639 replayed the shadow gate: it read 10-01 c29 as unverified (the
log read stopped at 20k entries), false-blocked 10-02 c22, and was blind on four
cells whose 24 h/48 h baseline held an incident.

- Director 503s now come from Cloud Run's request_count, aligned per minute by
  Cloud Monitoring, so volume cannot truncate the count.
- The background is the median of the 10 same-day minutes before the drain;
  the 24 h/48 h baselines are gone.
- Scheduled 503s come out: drain-return deferrals and sticky/placement answers
  to a host's own early retry (host-rate-limited, host-in-flight), each split
  across the minutes its 30 s sample covers.
- The rung budget counts only sustained breaches: two straight minutes over
  max(1.5x, +20) warn, over max(2x, +40) would-block.
- The report carries a paceVerdict over the three pace checks. seal_canary
  downloads the canary cell's report and seals that verdict; a batch below the
  default pace needs PASS, from a report on the same cell that drained at that
  pace.
- Docs: the step-down rule reads paceVerdict, 30 s waits for the lane service
  time (#25645), and the staging step is dropped since staging drains unpaced.

Replayed read-only: 10-01 c29 would-block (9 minutes over 41.5/min); all nine
10-02 cells and 10-01 c25 paceVerdict PASS.

@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

The new commits since the prior review (c62ece3) rework the lock-wait sampler and document the director hold-alert change:

  • Root-holder attribution. postgres-lock-wait-sample.ts now walks pg_blocking_pids with a recursive CTE to the root of each wait chain, so every waiter in a row-lock convoy is attributed to the transaction actually holding the row rather than the waiter directly in front of it. pg_blocking_pids is read once per waiter through a MATERIALIZED CTE, and the chain is depth-capped so a cycle cannot run away.
  • Single-flight sampling. index.ts guards the 5 s lock-wait sampler with a module-level flag so a slow database cannot stack samples on the pool, and clears it in finally; runRelayBackgroundOperation swallows failures, so the flag always resets.
  • Real-Postgres convoy test. The Postgres test now queues three directors behind a cell-held relay_cells row and asserts all three report holderRole: 'cell' — the first-blocker query reported two of them as director-held, so the test fails without the fix.
  • Docs and Terraform. The operations and incident-monitor docs describe the root-holder semantics and the expected director hold-alert change; the Terraform reorders reservation_drift alongside the other incident metrics.

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

@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 (1)

🟡 Minor · Keep combined distinct in lock-wait samples. · postgres-lock-wait-sample.ts:40-48

cloud/apps/relay/src/postgres-lock-wait-sample.ts:40-48
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep combined distinct in lock-wait samples.

The default combined role enables the sampler, and the SQL selects its sessions. relayRole maps that valid role to other, so dbLockWaitersByKeyDelta cannot distinguish combined waiters or holders from operator sessions or finished holders. Add combined to RELAY_ROLES. The per-key dimension will then retain it; the director- and cell-only scalar fields remain unchanged.

Suggested fix
-const RELAY_ROLES = new Set(['director', 'cell'])
+const RELAY_ROLES = new Set(['director', 'cell', 'combined'])

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cdd42d5c-a8ba-4dbf-b7f4-2e25a4761473
📥 Commits

Reviewing files that changed from the base of the PR and between 5c32e68 and d0e676b.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/postgres-lock-wait-sample.ts
  • cloud/docs/orca-relay-operations.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • cloud/apps/relay/src/postgres-lock-wait-sample.ts
  • cloud/docs/orca-relay-operations.md

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

Jinwoo-H added a commit that referenced this pull request Oct 5, 2026
…in-aware 503 gates (#25639)

* feat(relay): drain pace window as a reviewed same-cap input, with drain-aware 503 gates

The same-cap roll drained every cell over a fixed 300 s window, so a US roll
re-placed hosts at ~2/s and spent ~10 minutes draining and waiting for quiet.
The window is now a dispatch input from a closed set (300000, 60000, 30000),
defaulting to today's 300000.

- Below the default is refused for anything but US general cells; Asia drains
  are bound by their targets' accept rate, and migration-only cells hold no hosts.
- A non-default window must be named in the confirmation, the canary authority
  records it (v2), and a batch may run at its canary's window or slower only.
- Each cell job re-checks the window, scales the restart-safe timeout with it
  (15-min lease + window, unchanged at the default), and records what the cell
  applied and when it settled.
- The report-only shadow gate takes the director's drain-return deferrals out
  of the 503 count (window and baselines), adds the rung's 5-min non-drain 503
  budget and a Retry-After check, and reports the measured re-placement rate.
- relay-workflows.md documents the pace ladder and what each rung records.

* fix(relay): judge paced drains on counted 503s against the pre-drain minutes, and seal the canary's pace verdict

Review of #25639 replayed the shadow gate: it read 10-01 c29 as unverified (the
log read stopped at 20k entries), false-blocked 10-02 c22, and was blind on four
cells whose 24 h/48 h baseline held an incident.

- Director 503s now come from Cloud Run's request_count, aligned per minute by
  Cloud Monitoring, so volume cannot truncate the count.
- The background is the median of the 10 same-day minutes before the drain;
  the 24 h/48 h baselines are gone.
- Scheduled 503s come out: drain-return deferrals and sticky/placement answers
  to a host's own early retry (host-rate-limited, host-in-flight), each split
  across the minutes its 30 s sample covers.
- The rung budget counts only sustained breaches: two straight minutes over
  max(1.5x, +20) warn, over max(2x, +40) would-block.
- The report carries a paceVerdict over the three pace checks. seal_canary
  downloads the canary cell's report and seals that verdict; a batch below the
  default pace needs PASS, from a report on the same cell that drained at that
  pace.
- Docs: the step-down rule reads paceVerdict, 30 s waits for the lane service
  time (#25645), and the staging step is dropped since staging drains unpaced.

Replayed read-only: 10-01 c29 would-block (9 minutes over 41.5/min); all nine
10-02 cells and 10-01 c25 paceVerdict PASS.

* fix(relay): a partial count already past a block line blocks, in the shadow gate's Cloud SQL and pool checks

A truncated FATAL count is a floor, and one runtime sample over the SQL-failure
line is a fact, so neither waits for a complete read. The waiter-run rule still
needs a complete run, since holes can join two runs into one.

* fix(relay): a canary pace PASS needs a real cohort and whole telemetry; one median-based 503 check

From the final review of #25639:
- canaryPaceVerdict seals PASS only from a report that drained at least 400
  hosts (about half a 10-02 US cell), so a near-empty canary cannot authorize
  a fast batch.
- A director-metrics sub-window with fewer samples than one instance emits
  is unverified, so an empty or short Logging answer is never a calm drain.
- seal_canary names the shadow artifact, report path and cell from the gate's
  normalized cell list, as cell_1 uploads it.
- director503 folds into nonDrain503Budget as a single-minute spike rule,
  max(10x median, 200), dropping the pre-drain peak statistic. All 30 replayed
  windows keep their verdicts.
@Jinwoo-H
Jinwoo-H merged commit 10bea3a into main Oct 5, 2026
42 of 46 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