Repository navigation
feat(relay): count failed cell-inventory lock acquisitions - #21067
Conversation
The cell inventory lock is taken NOWAIT, so contention errors with 55P03 and retries instead of waiting. CellInventoryHoldSamples.record only runs after a successful acquisition, so the hold metrics were structurally blind to the dominant failure mode: production showed ~65 failed fleet-wide acquisitions per minute while cellInventoryHoldMsMax read a benign 53ms mean. Count failures next to the holds and publish them as cellInventoryLockUnavailable in orca_relay_runtime_metrics. Drained on both the commit and the rollback path, since a 55P03 rolls its transaction back.
There was a problem hiding this comment.
ℹ️ Minor suggestions only — the counter and its wiring are correct; the notes below are about test coverage and how to read the new metric.
Reviewed changes
cellInventoryLockUnavailablecounter (cell-inventory-hold-samples.ts) — adds the field toCellInventoryHoldCounts/emptyCellInventoryHoldCounts(), a monotonicrecordUnavailable(count = 1)guarded byNumber.isFinite && > 0, resets it inconsumeCounts(), and returns it from the empty-reservoir early path inreadCounts()so a window with failures and no holds is not read as all-zero.- PostgreSQL wiring (
database.ts) —PostgresTransactiongetslockUnavailable+consumeLockUnavailable(); a55P03underfailIfUnavailable && measureHoldMsincrements it inPostgresTransaction.queryLocked, andPostgresDatabase.queryLockedincrements the pool-levelholdsdirectly.PostgresDatabase.transactiondrains the transaction counter on both the COMMIT return and the ROLLBACK catch, so a failed NOWAIT grab is not dropped by the rollback. - Tests (
cell-inventory-hold-samples.test.ts) — four cases over the samples class only.
I confirmed the additive wiring reaches production: index.ts passes the raw PostgresDatabase to consumeRelayCellInventoryHold(database), and relay-observability.flush spreads ...counts into orca_relay_runtime_metrics; the observeRelayDatabase wrapper delegates to the same underlying object, each transaction attempt owns a fresh PostgresTransaction and drains on both exit paths, and only the nowait mode sets failIfUnavailable, so bounded-timeout 55P03s are correctly not counted.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change adds separate Priority: ⬇️ Low Merge Risk: 🔵 Low · up to Some bounded lock-contention attempts can be missing from the new metric and related alerts. Locking behavior is unchanged, so merge risk is low, but the counter guard should be corrected. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the problem, evidence, change, scope, and verification, but it does not follow the required template. It omits the required ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, AI Disclosure, Review, boundary, Notes, and Checklist sections. The Linked Issue field is also empty. Resolution Update the description to include all required template sections. Add a valid issue reference after “Fixes #”, provide the required visual-proof statement such as “N/A” with a reason, document testing and platform coverage, complete the applicable checkboxes, and address AI Disclosure, Review, Agent skill upstream boundary, Notes, ELI5, What Changed, and Why. Full details: Docstring CoverageExplanation Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 4 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
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: 906cf4ad-e115-469f-be24-5028976e347b
📒 Files selected for processing (3)
cloud/apps/relay/src/cell-inventory-hold-samples.test.tscloud/apps/relay/src/cell-inventory-hold-samples.tscloud/apps/relay/src/database.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
Review caught that the first counter only incremented under failIfUnavailable, which is the sweep mode. Background sweeps take the inventory NOWAIT and re-derive a skipped candidate next tick, so those deferrals are by design and already reported as orca_relay_sweep_cell_inventory_busy. The request path uses a bounded lock_timeout instead, whose expiry raises the same 55P03 without NOWAIT and was not counted at all -- so the metric measured only the benign population and missed the user-visible one. Split them: cellInventoryLockUnavailable for NOWAIT deferrals, cellInventoryLockTimeouts for expired bounded waits. Production over 30 minutes shows why the distinction matters -- roughly 1,200 fleet-wide sweep deferrals against roughly 10/min request-path timeouts. Adds transaction-path coverage for both drains, which were previously unpinned. Timeouts count per attempt, not per request, since 55P03 is retryable.
There was a problem hiding this comment.
ℹ️ No critical issues — the new counter, its wiring, and the transaction-path tests are correct; one lane-wording note inline.
Reviewed changes
cellInventoryLockTimeoutscounter (cell-inventory-hold-samples.ts) — splits the bounded request-path wait lane out ofcellInventoryLockUnavailable;recordLockTimeout(count = 1)shares theNumber.isFinite && > 0guard, resets inconsumeCounts(), and rides the sharedfailuresobject on the empty-reservoir early return.- PostgreSQL wiring (
database.ts) —PostgresTransaction.lockTimeouts+consumeLockTimeouts(), incremented only whenbounded && measureHoldMs && 55P03, and drained byPostgresDatabase.transactionon both the COMMIT return and the ROLLBACK catch. - Transaction-path tests (
cell-inventory-lock-contention.test.ts) — the rollback-path drains are now pinned: a NOWAIT deferral (cellInventoryLockUnavailable === 1,cellInventoryLockTimeouts === 0) and an expired bounded wait (cellInventoryLockTimeouts === 3, one perPOSTGRES_TRANSACTION_ATTEMPTS). This closes the untested-wiring gap from the prior review.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
google_logging_metric.relay_snapshot only creates metrics for fields listed in relay_runtime_metrics, and the cellInventoryHold* fields were never added when the hold telemetry landed. They have been log-only since, so nothing could alert on the lock and the contention stayed invisible in exactly the way the telemetry was meant to prevent. Maps the three hold fields and both new failure counters. Also corrects the field comment: the split is by wait policy, not by caller. assignOnce takes the inventory fail-fast on its first placement attempt, so request-reachable sites land in cellInventoryLockUnavailable too; that lane reads as contention pressure, and the expired bounded wait is the stall lane.
There was a problem hiding this comment.
ℹ️ No critical issues — one unit-metadata nit inline.
Reviewed changes
- Published the cell-inventory metrics to Cloud Monitoring (
relay-observability.tf) — registerscell_inventory_hold_ms_max,cell_inventory_hold_ms_p95,cell_inventory_holds,cell_inventory_lock_unavailable, andcell_inventory_lock_timeoutsinrelay_runtime_metrics, whichgoogle_logging_metric.relay_snapshotfans out into log-based metrics. The threecellInventoryHold*fields were already emitted but never mapped, so the hold telemetry had been log-only since it landed. - Corrected the lane comment (
cell-inventory-hold-samples.ts) — theCellInventoryHoldCountsfield comment now states the split is by wait policy rather than caller, and documents that the fail-fast lane covers request-path first attempts as well as by-design sweep deferrals.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| cell_inventory_hold_ms_max = { field = "cellInventoryHoldMsMax", description = "Longest cell-inventory lock hold in the interval." } | ||
| cell_inventory_hold_ms_p95 = { field = "cellInventoryHoldMsP95", description = "Cell-inventory lock hold p95 in the interval; the bound is tuned against this." } |
There was a problem hiding this comment.
These two are millisecond durations, but they are missing from the unit list in the metric_descriptor block (line 316), where their neighbours db_wait_ms_max and the other *_ms_* keys map to "ms". As written they will be published with unit 1; add both keys to that contains([...]) ? "ms" list while the descriptors are new.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Count bounded lockCellRows timeouts independently of hold sampling. · database.ts:848-855
cloud/apps/relay/src/database.ts:848-855
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winCount bounded
lockCellRowstimeouts independently of hold sampling.lockCellRowsretainslockTimeoutMsfor request-mode waits but removesmeasureHoldMs. Therefore, its reachable55P03failures satisfyboundedbut fail theoptions.measureHoldMsguard inqueryLocked, socellInventoryLockTimeoutsis not incremented. The metric contract defines this field as expired bounded waits in the user-visible lane, which includes these per-cell-row attempts. Removeoptions.measureHoldMsfrom the bounded-timeout classification guard, while keeping it for fail-fastlockUnavailableaccounting.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: fa8c434c-e175-4fc3-bae3-7d502381a30e
📒 Files selected for processing (2)
cloud/apps/relay/src/cell-inventory-hold-samples.tscloud/infra/terraform/relay-observability.tf
🚧 Files skipped from review as they are similar to previous changes (1)
- cloud/apps/relay/src/cell-inventory-hold-samples.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
Snapshot of the uncommitted working tree so nothing is lost when the worktree is removed. Superseded by main: the region-correction feature landed via #20105, #20712, #20749, and the pool-canary gate it was blocking on was retired after the contention was traced to the fleet-wide cell-inventory lock (#21067).
…21067) * feat(relay): count failed cell-inventory lock acquisitions The cell inventory lock is taken NOWAIT, so contention errors with 55P03 and retries instead of waiting. CellInventoryHoldSamples.record only runs after a successful acquisition, so the hold metrics were structurally blind to the dominant failure mode: production showed ~65 failed fleet-wide acquisitions per minute while cellInventoryHoldMsMax read a benign 53ms mean. Count failures next to the holds and publish them as cellInventoryLockUnavailable in orca_relay_runtime_metrics. Drained on both the commit and the rollback path, since a 55P03 rolls its transaction back. * fix(relay): separate request-path lock timeouts from sweep deferrals Review caught that the first counter only incremented under failIfUnavailable, which is the sweep mode. Background sweeps take the inventory NOWAIT and re-derive a skipped candidate next tick, so those deferrals are by design and already reported as orca_relay_sweep_cell_inventory_busy. The request path uses a bounded lock_timeout instead, whose expiry raises the same 55P03 without NOWAIT and was not counted at all -- so the metric measured only the benign population and missed the user-visible one. Split them: cellInventoryLockUnavailable for NOWAIT deferrals, cellInventoryLockTimeouts for expired bounded waits. Production over 30 minutes shows why the distinction matters -- roughly 1,200 fleet-wide sweep deferrals against roughly 10/min request-path timeouts. Adds transaction-path coverage for both drains, which were previously unpinned. Timeouts count per attempt, not per request, since 55P03 is retryable. * fix(relay): publish the cell-inventory lock metrics to Cloud Monitoring google_logging_metric.relay_snapshot only creates metrics for fields listed in relay_runtime_metrics, and the cellInventoryHold* fields were never added when the hold telemetry landed. They have been log-only since, so nothing could alert on the lock and the contention stayed invisible in exactly the way the telemetry was meant to prevent. Maps the three hold fields and both new failure counters. Also corrects the field comment: the split is by wait policy, not by caller. assignOnce takes the inventory fail-fast on its first placement attempt, so request-reachable sites land in cellInventoryLockUnavailable too; that lane reads as contention pressure, and the expired bounded wait is the stall lane.

Problem
The relay's cell inventory lock is taken NOWAIT:
So contention never becomes a wait — it errors with
55P03and retries.CellInventoryHoldSamples.record(holdMs)is only reachable after a successful acquisition (database.ts, post-COMMIT), which meanscellInventoryHoldMsMax/P95/cellInventoryHoldsare structurally blind to the dominant failure mode.The metric added to measure this contention cannot see it.
Evidence
Production
onorca-cloud:orca-cloud-auth-db, measured 2026-09-16 (read-only):ORDER BY cell_id ASCWHERE cell_id = $1relay_assignmentsOver the same window the hold metrics looked healthy — mean-of-maxima 53.5 ms. Reading only the hold metric produces a false "contention is resolved" verdict, which is what happened.
Change
Adds
cellInventoryLockUnavailablebeside the hold samples, published inorca_relay_runtime_metrics. Counted rather than sampled, since a failed acquisition has no duration.Drained on both the commit and the rollback path — a 55P03 rolls its transaction back, so counting only on success would drop every one.
Scope
Observability only. No change to locking behaviour, no production mutation. This makes the contention measurable so the follow-up — reducing how many of the 22
lockCellInventorycall sites need the fleet-wide lock — can be verified rather than guessed.Verification
tsc --noEmitcleangit diff --checkcleancloud/**by repo config; the relay package's ownlintistsc --noEmit, which passed