Skip to content

feat(relay): count failed cell-inventory lock acquisitions - #21067

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay-cell-inventory-lock
Sep 16, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay-cell-inventory-lock

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​100 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​100
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​69 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66

Problem

The relay's cell inventory lock is taken NOWAIT:

SELECT * FROM relay_cells ORDER BY cell_id ASC FOR UPDATE NOWAIT

So contention never becomes a wait — it errors with 55P03 and retries. CellInventoryHoldSamples.record(holdMs) is only reachable after a successful acquisition (database.ts, post-COMMIT), which means cellInventoryHoldMsMax / P95 / cellInventoryHolds are 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):

Statement Failed acquisitions / 30 min
fleet-wide ORDER BY cell_id ASC 1,956 (~65/min)
per-cell WHERE cell_id = $1 383
relay_assignments 23

Over 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 cellInventoryLockUnavailable beside the hold samples, published in orca_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 lockCellInventory call sites need the fleet-wide lock — can be verified rather than guessed.

Verification

  • tsc --noEmit clean
  • Full relay suite: 622 passed / 104 skipped
  • 4 new regression tests, including a window with failures and zero holds
  • git diff --check clean
  • Note: root oxlint ignores cloud/** by repo config; the relay package's own lint is tsc --noEmit, which passed

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.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 16, 2026 18:06

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

ℹ️ 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

  • cellInventoryLockUnavailable counter (cell-inventory-hold-samples.ts) — adds the field to CellInventoryHoldCounts / emptyCellInventoryHoldCounts(), a monotonic recordUnavailable(count = 1) guarded by Number.isFinite && > 0, resets it in consumeCounts(), and returns it from the empty-reservoir early path in readCounts() so a window with failures and no holds is not read as all-zero.
  • PostgreSQL wiring (database.ts) — PostgresTransaction gets lockUnavailable + consumeLockUnavailable(); a 55P03 under failIfUnavailable && measureHoldMs increments it in PostgresTransaction.queryLocked, and PostgresDatabase.queryLocked increments the pool-level holds directly. PostgresDatabase.transaction drains 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread cloud/apps/relay/src/database.ts Resolved
Comment thread cloud/apps/relay/src/database.ts Resolved
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds separate cellInventoryLockUnavailable and cellInventoryLockTimeouts counters to hold counts. CellInventoryHoldSamples validates, accumulates, reports, and resets both counters. PostgresTransaction counts measured bounded PostgreSQL 55P03 timeouts. PostgresDatabase records timeout counts after commit or rollback while preserving unavailable-lock accounting. Terraform adds runtime metrics, and tests cover both contention paths.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 4d382

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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… 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 app…
Docstring Coverage ⚠️ Warning 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 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: counting failed cell-inventory lock acquisitions.
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.
Full details: Description check

Explanation

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 Coverage

Explanation

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

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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: 906cf4ad-e115-469f-be24-5028976e347b

📥 Commits

Reviewing files that changed from the base of the PR and between 383c543 and 1f3d3cd.

📒 Files selected for processing (3)
  • cloud/apps/relay/src/cell-inventory-hold-samples.test.ts
  • cloud/apps/relay/src/cell-inventory-hold-samples.ts
  • cloud/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.

@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 critical issues — the new counter, its wiring, and the transaction-path tests are correct; one lane-wording note inline.

Reviewed changes

  • cellInventoryLockTimeouts counter (cell-inventory-hold-samples.ts) — splits the bounded request-path wait lane out of cellInventoryLockUnavailable; recordLockTimeout(count = 1) shares the Number.isFinite && > 0 guard, resets in consumeCounts(), and rides the shared failures object on the empty-reservoir early return.
  • PostgreSQL wiring (database.ts) — PostgresTransaction.lockTimeouts + consumeLockTimeouts(), incremented only when bounded && measureHoldMs && 55P03, and drained by PostgresDatabase.transaction on 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 per POSTGRES_TRANSACTION_ATTEMPTS). This closes the untested-wiring gap from the prior review.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@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 critical issues — one unit-metadata nit inline.

Reviewed changes

  • Published the cell-inventory metrics to Cloud Monitoring (relay-observability.tf) — registers cell_inventory_hold_ms_max, cell_inventory_hold_ms_p95, cell_inventory_holds, cell_inventory_lock_unavailable, and cell_inventory_lock_timeouts in relay_runtime_metrics, which google_logging_metric.relay_snapshot fans out into log-based metrics. The three cellInventoryHold* 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) — the CellInventoryHoldCounts field 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +96 to +97
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." }

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.

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.

@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 · Count bounded lockCellRows timeouts independently of hold sampling. · database.ts:848-855

cloud/apps/relay/src/database.ts:848-855
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Count bounded lockCellRows timeouts independently of hold sampling. lockCellRows retains lockTimeoutMs for request-mode waits but removes measureHoldMs. Therefore, its reachable 55P03 failures satisfy bounded but fail the options.measureHoldMs guard in queryLocked, so cellInventoryLockTimeouts is not incremented. The metric contract defines this field as expired bounded waits in the user-visible lane, which includes these per-cell-row attempts. Remove options.measureHoldMs from the bounded-timeout classification guard, while keeping it for fail-fast lockUnavailable accounting.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fa8c434c-e175-4fc3-bae3-7d502381a30e

📥 Commits

Reviewing files that changed from the base of the PR and between a2bc78e and 4d38266.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/cell-inventory-hold-samples.ts
  • cloud/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.

@Jinwoo-H
Jinwoo-H merged commit 71e308e into main Sep 16, 2026
25 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 16, 2026
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).
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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.
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