Skip to content

perf(relay): batch control lease renewals per cell instead of one write transaction per host - #21303

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay-batch-control-renewals
Sep 17, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay-batch-control-renewals

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​805 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​799
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​588 $\color{#cf222e}{\Huge{\mathbf{−}}}$​129 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​459

ELI5

Every Orca desktop that is connected keeps its place on a relay server by writing a small "still here" note to the shared database every 30 seconds. With about 14,000 desktops connected, that is roughly 470 separate database writes per second, all touching the same few pages of the same two tables. The database spends more time coordinating those writers than doing the writes, and every few minutes it seizes up for 5 to 12 seconds.

Each relay server now collects the notes that came due in the last second and writes them all in one go. Same notes, same meaning, a fraction of the writers. If one desktop's row happens to be busy, the batch steps over it and tries again next time rather than making every other desktop wait.

What Changed

Before. Every few minutes, for 5 to 12 seconds, the database shared by relay and auth stopped answering. Phones failed to pair, desktops dropped their relay connection and reconnected, and the whole fleet felt it at once. The gap between episodes was set by how long recovery took, not by any clock, so it looked like a load problem with no single heavy query behind it.

After. The write rate that caused it is gone. A relay cell issues one renewal statement per second instead of one per host per 30 seconds.

Mechanism. A host session's heartbeat used to call renewControlActivity, which issued a single-row write transaction: lock that host's assignment row, check for an active migration, lock that host's control lease, push both expiry timestamps forward, report an outcome. At fleet scale that is about 470 concurrent single-row write transactions per second, each with its own transaction id, all updating the same handful of hot heap pages.

Sampling three onsets at 250 ms intervals showed what that costs. There was no heavyweight lock queue and no slow statement. Instead 60 to 144 backends sat in LWLock:BufferContent, with 24 of them in Timeout/SpinDelay (spinlock backoff), plus XidGen and WALInsert, all inside that one statement. Query Insights attributed 152 of 157 seconds of lightweight-lock wait in the onset minute to it. Contention on the buffer headers, not on the rows.

The heartbeat now enqueues the renewal instead of issuing it. Each cell flushes its queue every second, or as soon as 200 rows are waiting, through one statement that unnests the parameter arrays and applies the same logic row-wise. Concurrent writers drop from the host count to the cell count, and transaction ids drop with them, which also relieves most of the instance's transaction-id burn.

Per-session behaviour is unchanged. Each enqueue resolves on a renewal and rejects with the outcome as its message, exactly as the single-row call did, so the completed-attempt counter, the staleness guard, and every close path route as before. One metric is still recorded per row.

Read cost per host does not change. Measured against a 20,000-row assignments table on PostgreSQL 16:

Rows in one statement Buffer hits Hits per host Execution
1 30 30.0 —
12 306 25.5 0.6 ms
200 6,019 30.1 8.5 ms

The single-row statement reports 28.7 buffer hits per call in production, which the 1-row measurement above reproduces. So batching removes write transactions and transaction ids without adding page traffic per host.

Row locking

This is the part worth a reviewer's attention, and the design changed once production numbers for the single-row locks arrived.

Row locks are held until the statement commits, not until the row is written. That is true of a SELECT ... FOR UPDATE in a CTE and equally true of an UPDATE ... FROM unnest(...): in both forms the autocommit statement is the transaction, and every lock it has taken lives to the end of it. So the choice between those two forms does not change how long locks are held, and neither form stops the batch from waiting on a contended row while holding the rows it already has. What matters is whether the batch can wait at all.

So the assignment pass does not wait. It takes its locks with FOR UPDATE ... SKIP LOCKED and reports a passed-over host as assignment_lock_unavailable. The registry retries that host on its next tick and never closes the control for it, which is safe because the tick is 15 seconds away and the lease has 105 seconds on it. Hold time is then the statement's own execution time, measured with a competing holder in place:

Scenario 12 rows 50 rows 200 rows
No competing holder 3.1 ms 6.1 ms 11.5 ms
One host's assignment row held 1.7 ms 2.8 ms 9.4 ms

In the contended runs the batch renewed every host but the held one and reported assignment_lock_unavailable for that one. For comparison, on the same wedge a blocking single-row FOR UPDATE spent 1,007 ms and then failed with 55P03; a blocking batch would have spent the same and failed all 200 rows. A test pins this: with SKIP LOCKED removed, that case takes 2,029 ms and returns database_error instead.

An unlocked probe keeps a skip from being read as a missing assignment. assignment_not_found closes a desktop's control socket, so a skipped row must never produce it. A present_assignment CTE reads the row without locking, and the outcome for "present but not locked" is the retryable one. Removing that probe makes the contended host report assignment_not_found, which a test also pins.

Deadlock freedom. With no wait on the assignment pass, only the two later passes can block, and neither can. Every writer in the store locks a host's assignment row before that host's lease rows, and there are 21 callers of the assignment-row lock and 18 of the lease lock, all inside per-host transactions. A host whose assignment row is held was skipped, so the batch never reaches that host's lease and the lease pass cannot wait. markMigrationTargetRegistered is the one writer that locks a migration row without the assignment row first; it takes no further locks, so it can delay a mid-migration row by up to the pool's lock_timeout but cannot close a cycle. The migration pass is never executed in the steady state anyway, because the authorization OR short-circuits for a host on its own cell.

The lock order is still (user_id, relay_host_id), the primary key of relay_assignments, applied when building the parameter arrays and repeated as the statement's ORDER BY. EXPLAIN confirms LockRows sits above that Sort.

One correction to the production figures. The 845,553 ms maximum on the single-row assignment FOR UPDATE cannot have come from a serving connection. The serving pool sets lock_timeout to 1,000 ms and statement_timeout to 5,000 ms, and I confirmed against PostgreSQL 16 that the driver really applies them (SHOW lock_timeout returns 1s for a pool built the way openRelayDatabase builds it). A serving-path wait on that statement is therefore bounded at one second, as the 1,007 ms measurement above shows. That 14-minute sample is almost certainly a session outside the serving pool, such as an operator or script connection through cloud-sql-proxy, and it is worth confirming separately because a human session holding an assignment row is its own hazard.

Blast radius and observability

A batch statement that fails for any other reason falls back to the per-host statements it replaced, so a driver failure costs one host its renewal rather than all of them. A malformed request is rejected per row before the statement is built, for the same reason.

A flush logs one line only when it exceeds 250 ms or did not renew every row, with counts by outcome. Flush count, largest flush, and flush latency percentiles join the existing renewal fields in the runtime metrics event, with matching log-based metrics in relay-observability.tf. Applying that Terraform is a separate manual step and is not part of merging this PR; until it runs, the fields are in the logs but have no metric series. No per-row logs.

One existing metric changes meaning rather than name. controlRenewalLatencyMsP50/P95/Max used to be a host's own statement latency; for a batched row it is now the duration of the flush that carried it. The names are left alone so the history stays continuous, and the emit site carries a line saying the meaning changed at this commit. The new controlRenewalFlushLatencyMs* fields are the ones to read for statement cost from here on.

One row per host per statement

A statement updates a host's assignment row once. If one host contributed two control leases to the same batch, the assignment UPDATE would be offered its target row twice, apply one source row, and return one, so the second lease's row was told control_activity_not_found even though its lease had just been renewed. The registry treats that outcome as a reason to re-acquire the lease, so it was a silent, wrong answer on a path that acts on it.

Two changes, both kept:

  • The renewed verdict now reads renewed_lease, which has exactly one row per input row, instead of the assignment update that collapses per host. The assignment update is also grouped per host now, so it takes the later of the two expiries rather than an arbitrary one.
  • The queue partitions per (userId, relayHostId) rather than per activity, so a second control activity for one host opens the next flush instead of sharing this one.

The queue change alone would have hidden the statement bug rather than fixed it, since renewControlActivities is a public store API that has to be correct for the rows it accepts. A Postgres test puts two live control leases on one host through one batch and expects ["renewed", "renewed"]; reverting either half of the statement fix makes it report control_activity_not_found for the second.

Why

The measured cause is the number of concurrent write transactions, not the cost of any one of them. Batching is the only option that addresses that directly.

  • Lengthen the renewal interval. Cuts the rate proportionally but also cuts the safety margin: the 105 s lease exists so a host survives several failed renewals, and a longer interval spends that margin to buy a smaller improvement than batching gives.
  • A bigger database instance. More vCPUs give more spinlock contenders on the same buffer headers. Buffer-header contention does not reliably improve with core count, and the write rate would keep growing with the fleet.
  • Move relay to its own instance. Worth doing for isolation, and it would stop relay from taking auth down with it, but it does not fix relay's own collapse. It is also a migration, not a same-day fix.
  • Drop the index and set fillfactor so the lease update goes HOT. Already merged in perf(relay): stop indexing the column every control renewal writes #21286. It cut write-ahead-log volume, not concurrency, which is why the stalls continued.
  • UPDATE ... FROM unnest(...) with the authorization inlined, no explicit row locks. Considered and rejected. It does not shorten the lock hold, for the reason given above, and it does not avoid waiting on a contended row either. It also costs correctness: under READ COMMITTED a migration that completes between the plan's read of relay_assignment_migrations and the row lock would slip through, which is exactly what the FOR UPDATE OF migration in the current statement prevents, and it cannot produce the four distinct outcomes the registry routes on without extra passes. SKIP LOCKED on the locking form achieves what that option was meant to achieve, and more, since it removes the wait rather than shortening it.

PR #21286 and this change are complementary: that one made each write cheaper, this one makes there be far fewer of them.

Linked Issue

N/A. Found by production sampling on 2026-09-17, no tracking issue filed.

Visual Proof

N/A. No user-visible surface changes. The user-visible effect is the absence of the fleet-wide stalls described above, which is a server-side write pattern with no UI.

Testing

Ran from cloud/ against a fresh PostgreSQL 16 container, recreating the database before each run as the suite requires. Two consecutive full runs on fresh databases:

Test Files  88 passed (88)
      Tests  823 passed | 1 skipped (824)

pnpm typecheck and pnpm build pass across the workspace.

New coverage:

  • control-renewal-batch.test.ts - one call per window, per-row outcome routing, flush on the row ceiling, flush on the interval, concurrent flushes while one statement is stalled, driver failure reaching every caller, duplicate supersession, and the warn line's contents.
  • control-renewal-batch-store.test.ts - one statement for N rows asserted through a query spy, primary-key lock ordering with answers still in input order, a malformed row kept out of the statement, a contended row reported apart from a missing one, the per-host fallback after a batch failure, per-row metrics including the rethrowing one-row flush and the all-invalid batch, and the SQLite path.
  • control-renewal-postgres.test.ts - four hosts renewed in one autocommitted statement against a real database, three hosts each getting their own verdict from one batch, both of one host's control leases renewed in a single batch with the assignment row carrying the later expiry, and a host whose assignment row is held by a per-host transaction being passed over inside the pool's lock_timeout while the rest renew.
  • host-session-registry.test.ts - two due hosts sharing one call, with a session whose socket closes mid-flight left untouched while the live one advances.

Mutation-checked each mechanism: removing the sort, the per-row validation, the fallback, the batch window, the outcome routing, SKIP LOCKED, the unlocked presence probe, the per-input-row verdict source, the metric on the rethrow path, or the metric on the all-invalid path each fails the test that covers it.

terraform fmt -check -recursive and terraform validate pass on the observability change.

Platforms: server-side relay code with no platform-dependent behaviour. Verified on macOS against Linux containers; CI covers ubuntu.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Two behaviour changes a reviewer should weigh:

  1. A due renewal now reaches PostgreSQL up to one second after the heartbeat that scheduled it, where before it was issued synchronously. That is inside the 105 s lease and the 15 s retry cadence, so no host is at risk, but it surfaced in control-lease-recovery-postgres.test.ts, whose expect.poll used the default 1 s timeout and raced the flush. Those two polls now allow for the batch window.
  2. A renewal whose assignment row is locked now returns rather than waiting. Before, it queued for up to the pool's one-second lock_timeout and usually succeeded; now it is reported and retried 15 seconds later. This is deliberate and is what bounds the lock hold, and it also stops a renewal from pinning a pooled client for a second, which the existing queryLocked comment already calls out as a cost. It does mean the assignment_lock_unavailable counter is new and expected to be non-zero in normal operation whenever a phone is connecting on the same host.

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

  • Security. No change to what is authorized. The statement carries the same assignment, migration, and lease-ownership conditions per row, and identities still come from the token, never from a batch peer.
  • Backwards compatibility. No schema change, no wire change. renewControlActivity stays as a single-row wrapper, so existing callers and tests are unaffected, and a mixed-version fleet is fine because each cell batches only its own hosts.
  • Cross-platform. Server-side only; nothing platform-dependent.
  • Remote SSH and mobile. Unaffected. This is the relay's own control-lease bookkeeping, not anything a client sends or reads.
  • Performance. The point of the change, measured above. The one cost added is the batch window's sub-second delay, covered under Review.

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)

…te transaction per host

Every connected desktop renewed its own control lease with its own single-row
write transaction every 30s. At ~14,000 hosts that is ~470 write transactions
per second fleet-wide, each with its own transaction id, all updating the same
few heap pages of relay_assignments and relay_assignment_activity_leases.
Sampling three onsets at 250ms showed no lock queue and no slow statement:
60-144 backends piled into LWLock:BufferContent and Timeout/SpinDelay inside
that one statement, and Query Insights attributed 152 of 157 seconds of
lightweight-lock wait in the onset minute to it.

The heartbeat now enqueues a due renewal instead of issuing it. A cell flushes
its queue once per second, or as soon as 500 rows are waiting, through one
statement that unnests the parameter arrays and applies the same CTE row-wise.
Concurrent writers drop from the host count to the cell count, and transaction
ids with them. Measured against a 20,000-row table: 1 row 4.1ms, 12 rows
3.3ms, 100 rows 6.6ms, 500 rows 22.7ms.

Per-session semantics are unchanged. Each enqueue still resolves on a renewal
and rejects with the outcome as its message, so the completed-attempt counter,
the staleness guard, and every close path route exactly as before, and one
outcome per row is recorded against the flush latency.

Lock order is (user_id, relay_host_id), the primary key of relay_assignments,
applied in JavaScript and repeated as the statement's ORDER BY. EXPLAIN
confirms LockRows sits above that Sort, so a batch acquires its assignment rows
in one global order. Every writer in the store locks a host's assignment row
before its migration or lease rows and only ever touches one host, so a batch
can only wait on a row a single-host writer holds, never the reverse.

One statement also means one contended row could fail the whole batch, so a
failed batch degrades to the per-host statements it replaced rather than
costing every other host on the cell its renewal.
@pullfrog

pullfrog Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The relay now batches control-lease renewals. PostgreSQL uses one ordered batch statement. The assignment store records outcomes for invalid rows and failures. Heartbeats enqueue renewals through a timed, size-limited queue. The queue routes outcomes to callers and handles duplicate or deferred requests. Host session tests cover batching and lock contention. Runtime metrics now include flush counts, row counts, and latency values.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 8be8c

The new renewal metrics can mislead operational analysis during failed or fallback flushes. Correct the descriptions before relying on these dashboards for rollout monitoring.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 10 files. (1 skipped:… 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 and concisely describes the main change: batching relay control-lease renewals per cell instead of using one write transaction per host.
Description check ✅ Passed The description is detailed and covers the required explanation, changes, rationale, testing, visual proof, review risks, compatibility, and checklist items. The Linked Issue section states N/A even t…
Full details: Docstring Coverage

Explanation

Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 10 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

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: 8fdd0066-f8eb-4bc1-96d8-2691344f363c

📥 Commits

Reviewing files that changed from the base of the PR and between 4927439 and 588e742.

📒 Files selected for processing (10)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/control-lease-recovery-postgres.test.ts
  • cloud/apps/relay/src/control-renewal-batch-store.test.ts
  • cloud/apps/relay/src/control-renewal-batch.test.ts
  • cloud/apps/relay/src/control-renewal-batch.ts
  • cloud/apps/relay/src/control-renewal-postgres.test.ts
  • cloud/apps/relay/src/control-renewal-statement.ts
  • cloud/apps/relay/src/host-session-registry.test.ts
  • cloud/apps/relay/src/host-session-registry.ts
  • cloud/apps/relay/src/relay-observability.ts

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

this.timer = null
}
const batch = [...this.pending.values()]
this.pending = new Map()

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.

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '45,115p' cloud/apps/relay/src/control-renewal-batch.ts
sed -n '1360,1435p' cloud/apps/relay/src/host-session-registry.ts
sed -n '100,125p' cloud/apps/relay/src/control-renewal-batch.test.ts
sed -n '830,900p' cloud/apps/relay/src/host-session-registry.test.ts
rg -n 'renewal|renewControl|next.*renew|due' cloud/apps/relay/src/host-session-registry.ts | head -80

Repository: stablyai/orca

Length of output: 10826


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- control-renewal-batch definitions ---'
cat -n cloud/apps/relay/src/control-renewal-batch.ts | sed -n '1,150p'
printf '%s\n' '--- renewal callback and store bindings ---'
cat -n cloud/apps/relay/src/host-session-registry.ts | sed -n '285,325p'
rg -n -g '*.ts' 'renewControlActivities|renewControlActivity|activityRenewalCompletedAttempt|activityRenewalDueAt|CONTROL_ACTIVITY_LEASE_MS|CONTROL_ACTIVITY_RENEWAL_INTERVAL_MS' cloud/apps/relay/src cloud/packages
printf '%s\n' '--- database/schema definitions for control activity renewal ---'
rg -n -g '*.{ts,sql}' 'renewControlActivities|control_activity|expires_at|activity_cell_not_authoritative' cloud | head -160

Repository: stablyai/orca

Length of output: 37573


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 19206


🏁 Script executed:

#!/bin/bash
set -e
cat -n cloud/apps/relay/src/control-renewal-batch.ts | sed -n '1,150p'
cat -n cloud/apps/relay/src/host-session-registry.ts | sed -n '285,325p'
rg -n -g '*.ts' 'renewControlActivities|renewControlActivity|activityRenewalCompletedAttempt|activityRenewalDueAt|CONTROL_ACTIVITY_LEASE_MS|CONTROL_ACTIVITY_RENEWAL_INTERVAL_MS' cloud/apps/relay/src
rg -n -g '*.{ts,sql}' 'renewControlActivities|control_activity|expires_at|activity_cell_not_authoritative' cloud/apps/relay | head -160

Repository: stablyai/orca

Length of output: 38102


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- renewal store ---'
cat -n cloud/apps/relay/src/assignment-store.ts | sed -n '3470,3690p'
printf '%s\n' '--- renewal statement ---'
cat -n cloud/apps/relay/src/control-renewal-statement.ts | sed -n '1,190p'
printf '%s\n' '--- heartbeat constants and tests ---'
cat -n cloud/apps/relay/src/host-session-registry.ts | sed -n '55,110p'
cat -n cloud/apps/relay/src/host-session-registry.test.ts | sed -n '790,900p'

Repository: stablyai/orca

Length of output: 28804


🏁 Script executed:

#!/bin/bash
set -e
cat -n cloud/apps/relay/src/assignment-store.ts | sed -n '3470,3690p'
cat -n cloud/apps/relay/src/control-renewal-statement.ts | sed -n '1,190p'
cat -n cloud/apps/relay/src/host-session-registry.ts | sed -n '55,110p'
cat -n cloud/apps/relay/src/host-session-registry.test.ts | sed -n '790,900p'

Repository: stablyai/orca

Length of output: 28718


Serialize same-key renewals across flushes.

If a PostgreSQL renewal remains pending through the next heartbeat, HostSessionRegistry.heartbeat() can enqueue the same (userId, relayHostId, activityId) again. Its completion attempt and due time update only after the promise settles, and current() does not block a new enqueue. flush() then removes the key from pending while the first renew() is still active.

PostgreSQL row locks and GREATEST preserve the newest expiry, but they do not deduplicate the statements. The second statement can wait on the same rows and still add duplicate query and lock work, amplifying load during a stall.

Track active keys separately from pending. For an active key, retain only the newest expiry and queue at most one follow-up renewal after the active operation settles. Keep different keys eligible for concurrent flushes. Add a regression test that stalls one renewal across a heartbeat window and asserts that same-key store calls never overlap, while the newer expiry is eventually written.

…te transaction per host

Every connected desktop renewed its own control lease with its own single-row
write transaction every 30s. At ~14,000 hosts that is ~470 write transactions
per second fleet-wide, each with its own transaction id, all updating the same
few heap pages of relay_assignments and relay_assignment_activity_leases.
Sampling three onsets at 250ms showed no lock queue and no slow statement:
60-144 backends piled into LWLock:BufferContent and Timeout/SpinDelay inside
that one statement, and Query Insights attributed 152 of 157 seconds of
lightweight-lock wait in the onset minute to it.

The heartbeat now enqueues a due renewal instead of issuing it. A cell flushes
its queue every second, or as soon as 200 rows are waiting, through one
statement that unnests the parameter arrays and applies the same CTE row-wise.
Concurrent writers drop from the host count to the cell count, and transaction
ids with them. Per-host buffer traffic is unchanged: 30 hits for one row, 25.5
per host at 12 rows, 30.1 per host at 200, against the 28.7 the single-row
statement reports in production.

Per-session semantics are unchanged. Each enqueue still resolves on a renewal
and rejects with the outcome as its message, so the completed-attempt counter,
the staleness guard, and every close path route as before, and one outcome per
row is recorded against the flush latency.

Row locks live until the statement commits, so a batch that waited on a
contended row would hold every other row's lock for that whole wait. The
assignment pass therefore takes its locks with SKIP LOCKED and reports a
contended host as assignment_lock_unavailable, which the registry retries on the
next tick instead of closing the control. That keeps the hold to the statement's
own execution: 11.5ms for 200 rows against a 20,000-row table, and 9.4ms with a
host wedged in a per-host transaction, where a blocking FOR UPDATE spends the
pool's whole 1s lock_timeout and then fails every row in the flush.

An unlocked present_assignment probe separates a host with no assignment row
from one the skip passed over, so a skipped row can never be mistaken for a
missing assignment and close a live desktop.

With no wait on the assignment pass the lock order is only needed for the two
later passes, and it holds: every writer takes a host's assignment row before
that host's lease rows, and a host whose assignment row is held was skipped, so
the batch never reaches its lease. markMigrationTargetRegistered is the one
writer that locks a migration row first, and it takes no further locks.
…lease update

Review findings on the batched renewal.

Two control leases on one host in one batch made the second report
control_activity_not_found although both were renewed: the assignment UPDATE is
offered the same target row twice, applies one source row and returns one, so
the other row_index never came back. The verdict now reads renewed_lease, which
has a row per input row, and the assignment UPDATE groups per host so it also
stops taking an arbitrary one of the two expiries instead of the later one.

The queue now partitions per (userId, relayHostId) rather than per activity, so
a second control activity for one host opens the next flush instead of sharing
this one. Belt to the statement fix, not a substitute: the store API has to be
right for the rows it accepts.

renewControlActivities recorded no outcome for a one-row flush that threw, and
none at all when every row failed validation, where a mixed batch recorded its
invalid_* rows. Both now record in a finally, the way the single-row path's
finally always did, and the error-to-outcome mapping both paths share is one
function.

The four flush fields the runtime metrics event emits had no log-based metric,
so add them next to the existing controlRenewalLatencyMs* entries. Applying the
Terraform is a separate manual step.

controlRenewalLatencyMsP50/P95/Max now measure a batched row's flush duration
rather than its own statement latency. Left named as they are for history, with
a line at the emit site recording that the meaning changed here.
@Jinwoo-H
Jinwoo-H merged commit 91ade4b into main Sep 17, 2026
24 checks passed

@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: 3253ac54-ae09-496c-9aac-a3d09be18d7e

📥 Commits

Reviewing files that changed from the base of the PR and between 18d7358 and 8be8c5e.

📒 Files selected for processing (8)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/control-renewal-batch-store.test.ts
  • cloud/apps/relay/src/control-renewal-batch.test.ts
  • cloud/apps/relay/src/control-renewal-batch.ts
  • cloud/apps/relay/src/control-renewal-postgres.test.ts
  • cloud/apps/relay/src/control-renewal-statement.ts
  • cloud/apps/relay/src/relay-observability.ts
  • cloud/infra/terraform/relay-observability.tf
🚧 Files skipped from review as they are similar to previous changes (1)
  • cloud/apps/relay/src/relay-observability.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +63 to +66
control_renewal_flushes = { field = "controlRenewalFlushesDelta", description = "Batched control-renewal statements issued in the interval, one per cell per flush window." }
control_renewal_flush_rows_max = { field = "controlRenewalFlushRowsMax", description = "Largest number of hosts renewed by a single statement in the interval; the row ceiling is what bounds how long one flush holds its row locks." }
control_renewal_flush_ms_p95 = { field = "controlRenewalFlushLatencyMsP95", description = "Batched control-renewal statement duration p95 in the interval. Row locks live until the statement commits, so this is the lock hold." }
control_renewal_flush_ms_max = { field = "controlRenewalFlushLatencyMsMax", description = "Maximum batched control-renewal statement duration in the interval." }

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '45,160p' cloud/apps/relay/src/control-renewal-batch.ts
sed -n '270,300p' cloud/apps/relay/src/relay-observability.ts
sed -n '385,410p' cloud/apps/relay/src/relay-observability.ts
sed -n '450,485p' cloud/apps/relay/src/relay-observability.ts
sed -n '50,75p' cloud/infra/terraform/relay-observability.tf
sed -n '3490,3615p' cloud/apps/relay/src/assignment-store.ts

Repository: stablyai/orca

Length of output: 16667


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- batch file outline and top ---'
ast-grep outline cloud/apps/relay/src/control-renewal-batch.ts
sed -n '1,80p' cloud/apps/relay/src/control-renewal-batch.ts
printf '%s\n' '--- relevant symbols ---'
rg -n -C 4 'ControlRenewalFlush|recordControlRenewalFlush|new ControlRenewalBatch|pendingKey|ControlRenewalRequest|controlRenewalFlush' cloud/apps/relay/src cloud/infra/terraform/relay-observability.tf
printf '%s\n' '--- batch SQL definition ---'
rg -n -C 8 'CONTROL_RENEWAL_BATCH_SQL|controlRenewalBatchParams|orderedControlRenewalRows' cloud/apps/relay/src

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
ast-grep outline cloud/apps/relay/src/control-renewal-batch.ts
sed -n '1,80p' cloud/apps/relay/src/control-renewal-batch.ts
rg -n -C 4 'ControlRenewalFlush|recordControlRenewalFlush|new ControlRenewalBatch|pendingKey|ControlRenewalRequest|controlRenewalFlush' cloud/apps/relay/src cloud/infra/terraform/relay-observability.tf
rg -n -C 8 'CONTROL_RENEWAL_BATCH_SQL|controlRenewalBatchParams|orderedControlRenewalRows' cloud/apps/relay/src

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

sed -n '1,55p' cloud/apps/relay/src/control-renewal-batch.ts; rg -n -C 5 'function pendingKey|const pendingKey|type ControlRenewalRequest|interface ControlRenewalRequest|ControlRenewalFlush|recordControlRenewalFlush|observe:' cloud/apps/relay/src; rg -n -C 5 'new ControlRenewalBatch|ControlRenewalBatch\\(' cloud/apps/relay/src

Repository: stablyai/orca

Length of output: 19454


Describe these metrics as flush metrics.

ControlRenewalBatch.flush reports one observation for each non-empty flush, including failed and fallback flushes. Its row count is the number of queued host rows. The per-host fallback can process those rows with multiple statements, so the row metric does not always describe one statement. Its duration also includes fallback work and is not necessarily one statement duration or one lock hold. Admission defers a second activity for the same host, so duplicate hosts cannot occur in one flush.

Update the descriptions as follows:

Suggested descriptions
- description = "Batched control-renewal statements issued in the interval, one per cell per flush window."
+ description = "Control-renewal flushes recorded in the interval."
- description = "Largest number of hosts renewed by a single statement in the interval; the row ceiling is what bounds how long one flush holds its row locks."
+ description = "Largest number of control-renewal rows in a flush in the interval."
- description = "Batched control-renewal statement duration p95 in the interval. Row locks live until the statement commits, so this is the lock hold."
+ description = "Control-renewal flush duration p95 in the interval."
- description = "Maximum batched control-renewal statement duration in the interval."
+ description = "Maximum control-renewal flush duration in the interval."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
control_renewal_flushes = { field = "controlRenewalFlushesDelta", description = "Batched control-renewal statements issued in the interval, one per cell per flush window." }
control_renewal_flush_rows_max = { field = "controlRenewalFlushRowsMax", description = "Largest number of hosts renewed by a single statement in the interval; the row ceiling is what bounds how long one flush holds its row locks." }
control_renewal_flush_ms_p95 = { field = "controlRenewalFlushLatencyMsP95", description = "Batched control-renewal statement duration p95 in the interval. Row locks live until the statement commits, so this is the lock hold." }
control_renewal_flush_ms_max = { field = "controlRenewalFlushLatencyMsMax", description = "Maximum batched control-renewal statement duration in the interval." }
control_renewal_flushes = { field = "controlRenewalFlushesDelta", description = "Control-renewal flushes recorded in the interval." }
control_renewal_flush_rows_max = { field = "controlRenewalFlushRowsMax", description = "Largest number of control-renewal rows in a flush in the interval." }
control_renewal_flush_ms_p95 = { field = "controlRenewalFlushLatencyMsP95", description = "Control-renewal flush duration p95 in the interval." }
control_renewal_flush_ms_max = { field = "controlRenewalFlushLatencyMsMax", description = "Maximum control-renewal flush duration in the interval." }

ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…te transaction per host (stablyai#21303)

* perf(relay): batch control lease renewals per cell instead of one write transaction per host

Every connected desktop renewed its own control lease with its own single-row
write transaction every 30s. At ~14,000 hosts that is ~470 write transactions
per second fleet-wide, each with its own transaction id, all updating the same
few heap pages of relay_assignments and relay_assignment_activity_leases.
Sampling three onsets at 250ms showed no lock queue and no slow statement:
60-144 backends piled into LWLock:BufferContent and Timeout/SpinDelay inside
that one statement, and Query Insights attributed 152 of 157 seconds of
lightweight-lock wait in the onset minute to it.

The heartbeat now enqueues a due renewal instead of issuing it. A cell flushes
its queue once per second, or as soon as 500 rows are waiting, through one
statement that unnests the parameter arrays and applies the same CTE row-wise.
Concurrent writers drop from the host count to the cell count, and transaction
ids with them. Measured against a 20,000-row table: 1 row 4.1ms, 12 rows
3.3ms, 100 rows 6.6ms, 500 rows 22.7ms.

Per-session semantics are unchanged. Each enqueue still resolves on a renewal
and rejects with the outcome as its message, so the completed-attempt counter,
the staleness guard, and every close path route exactly as before, and one
outcome per row is recorded against the flush latency.

Lock order is (user_id, relay_host_id), the primary key of relay_assignments,
applied in JavaScript and repeated as the statement's ORDER BY. EXPLAIN
confirms LockRows sits above that Sort, so a batch acquires its assignment rows
in one global order. Every writer in the store locks a host's assignment row
before its migration or lease rows and only ever touches one host, so a batch
can only wait on a row a single-host writer holds, never the reverse.

One statement also means one contended row could fail the whole batch, so a
failed batch degrades to the per-host statements it replaced rather than
costing every other host on the cell its renewal.

* perf(relay): batch control lease renewals per cell instead of one write transaction per host

Every connected desktop renewed its own control lease with its own single-row
write transaction every 30s. At ~14,000 hosts that is ~470 write transactions
per second fleet-wide, each with its own transaction id, all updating the same
few heap pages of relay_assignments and relay_assignment_activity_leases.
Sampling three onsets at 250ms showed no lock queue and no slow statement:
60-144 backends piled into LWLock:BufferContent and Timeout/SpinDelay inside
that one statement, and Query Insights attributed 152 of 157 seconds of
lightweight-lock wait in the onset minute to it.

The heartbeat now enqueues a due renewal instead of issuing it. A cell flushes
its queue every second, or as soon as 200 rows are waiting, through one
statement that unnests the parameter arrays and applies the same CTE row-wise.
Concurrent writers drop from the host count to the cell count, and transaction
ids with them. Per-host buffer traffic is unchanged: 30 hits for one row, 25.5
per host at 12 rows, 30.1 per host at 200, against the 28.7 the single-row
statement reports in production.

Per-session semantics are unchanged. Each enqueue still resolves on a renewal
and rejects with the outcome as its message, so the completed-attempt counter,
the staleness guard, and every close path route as before, and one outcome per
row is recorded against the flush latency.

Row locks live until the statement commits, so a batch that waited on a
contended row would hold every other row's lock for that whole wait. The
assignment pass therefore takes its locks with SKIP LOCKED and reports a
contended host as assignment_lock_unavailable, which the registry retries on the
next tick instead of closing the control. That keeps the hold to the statement's
own execution: 11.5ms for 200 rows against a 20,000-row table, and 9.4ms with a
host wedged in a per-host transaction, where a blocking FOR UPDATE spends the
pool's whole 1s lock_timeout and then fails every row in the flush.

An unlocked present_assignment probe separates a host with no assignment row
from one the skip passed over, so a skipped row can never be mistaken for a
missing assignment and close a live desktop.

With no wait on the assignment pass the lock order is only needed for the two
later passes, and it holds: every writer takes a host's assignment row before
that host's lease rows, and a host whose assignment row is held was skipped, so
the batch never reaches its lease. markMigrationTargetRegistered is the one
writer that locks a migration row first, and it takes no further locks.

* fix(relay): answer every row of a control-renewal batch from its own lease update

Review findings on the batched renewal.

Two control leases on one host in one batch made the second report
control_activity_not_found although both were renewed: the assignment UPDATE is
offered the same target row twice, applies one source row and returns one, so
the other row_index never came back. The verdict now reads renewed_lease, which
has a row per input row, and the assignment UPDATE groups per host so it also
stops taking an arbitrary one of the two expiries instead of the later one.

The queue now partitions per (userId, relayHostId) rather than per activity, so
a second control activity for one host opens the next flush instead of sharing
this one. Belt to the statement fix, not a substitute: the store API has to be
right for the rows it accepts.

renewControlActivities recorded no outcome for a one-row flush that threw, and
none at all when every row failed validation, where a mixed batch recorded its
invalid_* rows. Both now record in a finally, the way the single-row path's
finally always did, and the error-to-outcome mapping both paths share is one
function.

The four flush fields the runtime metrics event emits had no log-based metric,
so add them next to the existing controlRenewalLatencyMs* entries. Applying the
Terraform is a separate manual step.

controlRenewalLatencyMsP50/P95/Max now measure a batched row's flush duration
rather than its own statement latency. Left named as they are for history, with
a line at the emit site recording that the meaning changed here.
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