Repository navigation
feat(relay): time successful client accepts and control round trips - #19232
Conversation
A 6s accept on a cross-region cell was invisible: only the abandoned path was timed. Record per-stage durations across acceptClient and acceptHostData (assignment/credential/activity/attach), emit one completed log line per accept, and aggregate p50/p95/max into the runtime metrics event. Sample control ping round trips from the pong echo so a host sitting on a distant cell is visible fleet-wide and per host, rate-limited to one log line an hour per session.
Omit the accept and RTT percentiles from windows with no samples: accepts are sparse, so a zero point every 30s would pin the p50 at 0 and collapse the p95. The *Delta counts still publish, and say when the omission is expected. Control-renewal output is unchanged. Add a `basis` stage for the splice lease and connection-basis writes that run between the host data leg and relay-hello, and start `attach` where the activity stage ended, so the stages now tile the whole accept and their sum equals totalMs. Clamp every stage at zero against a backwards clock step. Carry role/cellId/region on both new log lines, flatten the stage p95 field names so the log-metric extractors stay top-level, and record that only the RTT median reads as distance: the desktop echoes the pong on its main thread, so the p95 and max track desktop stalls.
📝 WalkthroughWalkthroughThe relay now records client-accept durations for assignment, credential, activity, attach, and basis stages. It validates and samples control-channel RTT values per host. Runtime observability aggregates these samples into conditional percentile fields. Tests cover timing, RTT validation, logging intervals, flush behavior, and data scrubbing. Terraform defines the corresponding relay metrics and millisecond units. Merge Risk: 🟡 Moderate · up to The new relay latency metrics should not merge until control RTT buffering is bounded, since an authenticated host could increase relay memory and CPU usage. The credential leak-guard exemption should also be narrowed to preserve observability privacy coverage. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the purpose, key changes, limitations, and verification, but it omits several required template sections. It has no linked issue, ELI5 section, visual-proof statement, checklist responses, agent-skill boundary response, or review details. Resolution Complete the required template sections. Add a Full details: Docstring CoverageExplanation 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 7 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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: a0856a71-fc67-4ae4-8cca-c2217137728a
📒 Files selected for processing (5)
cloud/apps/relay/src/host-session-client-accept.test.tscloud/apps/relay/src/host-session-registry.tscloud/apps/relay/src/relay-observability.test.tscloud/apps/relay/src/relay-observability.tscloud/infra/terraform/relay-observability.tf
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| // An accept stage is named `credential`, so the leak guard has to see past the | ||
| // bucket name to the values it exists to police. | ||
| function scrubStageNames(entries: Array<Record<string, unknown>>): string { | ||
| return JSON.stringify(entries).replaceAll('"credential":', '"stage":') |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Restrict the leak-guard exemption to the stage bucket.
replaceAll also renames an accidental raw "credential" field outside the accept-stage map. The leak guard would then pass. Rename only clientAcceptsAbandonedByStageDelta.credential in a cloned entry.
| } | ||
|
|
||
| recordControlRtt(rttMs: number): void { | ||
| this.deltas.controlRttSamplesMs.push(rttMs) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 43315
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- relay observability symbols ---'
ast-grep outline cloud/apps/relay/src/relay-observability.ts
printf '%s\n' '--- observability implementation ---'
sed -n '1,80p;270,430p' cloud/apps/relay/src/relay-observability.ts
printf '%s\n' '--- RTT definitions and callers ---'
rg -n -C 12 'CONTROL_RTT|recordControlRtt|parsed\.t|pong|ping' cloud/apps/relay/src/host-session-registry.tsRepository: stablyai/orca
Length of output: 20299
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- percentile and delta definitions ---'
sed -n '88,185p' cloud/apps/relay/src/relay-observability.ts
printf '%s\n' '--- control session setup and heartbeat ---'
sed -n '930,1045p;1125,1180p' cloud/apps/relay/src/host-session-registry.tsRepository: stablyai/orca
Length of output: 10590
Denial of Service (CWE-400): Uncontrolled Resource Consumption
Reachability: External · Exploitability: Moderate
Bound RTT samples before appending them.
An authenticated host can send unlimited pong frames with a recent valid timestamp. The registry forwards each sample before it caps the per-session window. flush() copies and sorts the process-wide array for percentile metrics. One host can cause heap growth and excessive CPU use during a flush interval.
Cap or reservoir-sample controlRttSamplesMs. Alternatively, accept at most one RTT sample for each emitted ping.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor test-hygiene suggestion inline.
Reviewed changes
- Client-accept timing — the successful accept path now records per-stage latency (
assignment/credential/activity/attach/basis) that tiles the accept end to end, emitted asorca_relay_client_accept_completedand aggregated into new runtime-metric percentiles. - Control round-trip timing — pong RTTs are sampled into a per-host rolling window and logged as
orca_relay_host_control_rtt(median, hourly), plus a fleet p50/p95/max in runtime metrics; implausible pongs are dropped from RTT but still feed the silence watchdog. - Observability aggregation —
latencySummary()folds the three inlined percentile calls (control-renewal output byte-identical) and sparse windows omit percentile fields rather than publishing zeros. - Terraform — 13 additive log-based metrics with correct
msvs count unit mapping.
The stage tiling (sum == totalMs before the documented nonNegativeMs clamp), the RTT measurement (reusing the desktop's existing t echo, so no relay/desktop clock-skew or wire change), and the sparse-window-zero handling all check out, and the new tests assert exact values rather than loose bounds.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
|
||
| // An accept stage is named `credential`, so the leak guard has to see past the | ||
| // bucket name to the values it exists to police. | ||
| function scrubStageNames(entries: Array<Record<string, unknown>>): string { |
There was a problem hiding this comment.
scrubStageNames is currently a no-op in both tests it guards. The case-sensitive /credential/ regex never matches the metric field clientAcceptCredentialMsP95 (capital C), and the lowercase credential key it scrubs only surfaces via clientAcceptsAbandonedByStageDelta — which is {} in both tests because neither records an abandoned accept. Consider removing the helper (and the comment, which overstates the risk), or adding a recordClientAcceptAbandoned('credential', …) case so the guard is actually exercised.
…19268) * fix(relay): bound control RTT samples per ping and per flush window An authenticated host chose how many round-trip samples a cell recorded: every pong carrying a recent plausible `t` was forwarded to the process-wide window, which grew unbounded until the 30s flush copied and sorted it for percentiles. Time a pong only when it echoes the `t` of the ping still outstanding on that session, so a flood yields at most one sample per ping the cell actually sent. A pong that lost the race to the next ping is dropped for timing but still counts as proof of life for the silence watchdog. Bound the process-wide window with a 1024-sample reservoir (Algorithm R) so the percentiles stay unbiased, keep `controlRttSamplesDelta` meaning round trips observed, and publish `controlRttSamplesDroppedDelta` for the ones the reservoir did not keep. Replace the leak guard's blanket `"credential":` string rewrite with an exact, path-scoped rename of the two schema keys that spell a policed word, and make the guard case-insensitive now that nothing legitimate trips it. Follow-up to #19232. * test(relay): prove the RTT reservoir samples the whole window
…tablyai#19232) * feat(relay): time successful client accepts and control round trips A 6s accept on a cross-region cell was invisible: only the abandoned path was timed. Record per-stage durations across acceptClient and acceptHostData (assignment/credential/activity/attach), emit one completed log line per accept, and aggregate p50/p95/max into the runtime metrics event. Sample control ping round trips from the pong echo so a host sitting on a distant cell is visible fleet-wide and per host, rate-limited to one log line an hour per session. * fix(relay): review round 1 on accept and control-RTT timing Omit the accept and RTT percentiles from windows with no samples: accepts are sparse, so a zero point every 30s would pin the p50 at 0 and collapse the p95. The *Delta counts still publish, and say when the omission is expected. Control-renewal output is unchanged. Add a `basis` stage for the splice lease and connection-basis writes that run between the host data leg and relay-hello, and start `attach` where the activity stage ended, so the stages now tile the whole accept and their sum equals totalMs. Clamp every stage at zero against a backwards clock step. Carry role/cellId/region on both new log lines, flatten the stage p95 field names so the log-metric extractors stay top-level, and record that only the RTT median reads as distance: the desktop echoes the pong on its main thread, so the p95 and max track desktop stalls.
…tablyai#19268) * fix(relay): bound control RTT samples per ping and per flush window An authenticated host chose how many round-trip samples a cell recorded: every pong carrying a recent plausible `t` was forwarded to the process-wide window, which grew unbounded until the 30s flush copied and sorted it for percentiles. Time a pong only when it echoes the `t` of the ping still outstanding on that session, so a flood yields at most one sample per ping the cell actually sent. A pong that lost the race to the next ping is dropped for timing but still counts as proof of life for the silence watchdog. Bound the process-wide window with a 1024-sample reservoir (Algorithm R) so the percentiles stay unbiased, keep `controlRttSamplesDelta` meaning round trips observed, and publish `controlRttSamplesDroppedDelta` for the ones the reservoir did not keep. Replace the leak guard's blanket `"credential":` string rewrite with an exact, path-scoped rename of the two schema keys that spell a policed word, and make the guard case-insensitive now that nothing legitimate trips it. Follow-up to stablyai#19232. * test(relay): prove the RTT reservoir samples the whole window
…tablyai#19232) * feat(relay): time successful client accepts and control round trips A 6s accept on a cross-region cell was invisible: only the abandoned path was timed. Record per-stage durations across acceptClient and acceptHostData (assignment/credential/activity/attach), emit one completed log line per accept, and aggregate p50/p95/max into the runtime metrics event. Sample control ping round trips from the pong echo so a host sitting on a distant cell is visible fleet-wide and per host, rate-limited to one log line an hour per session. * fix(relay): review round 1 on accept and control-RTT timing Omit the accept and RTT percentiles from windows with no samples: accepts are sparse, so a zero point every 30s would pin the p50 at 0 and collapse the p95. The *Delta counts still publish, and say when the omission is expected. Control-renewal output is unchanged. Add a `basis` stage for the splice lease and connection-basis writes that run between the host data leg and relay-hello, and start `attach` where the activity stage ended, so the stages now tile the whole accept and their sum equals totalMs. Clamp every stage at zero against a backwards clock step. Carry role/cellId/region on both new log lines, flatten the stage p95 field names so the log-metric extractors stay top-level, and record that only the RTT median reads as distance: the desktop echoes the pong on its main thread, so the p95 and max track desktop stalls.

Why
A phone connect through a cell in a region far from the relay database takes ~10 s instead of ~0.6 s, and nothing in the relay metrics showed it: only the abandoned accept path was timed, and control-socket ping RTT was never recorded. This adds the two signals that make a mis-homed host visible without a manual log query.
What
orca_relay_client_accept_completed: one log line per successful accept withstageMs.{assignment,credential,activity,attach,basis}(the stages tile the accept exactly,sum == totalMsasserted),totalMs,credentialKind, host digest,role/cellId/region.orca_relay_host_control_rtt: rolling median of the last 8 control-socket pong RTTs per host session, logged at the 4th sample then at most hourly; survives control rebind.orca_relay_runtime_metrics(metricVersion unchanged):clientAcceptCompletedDelta,controlRttSamplesDeltaalways;clientAcceptTotalMsP50/P95/Max, per-stageclientAccept<Stage>MsP95,controlRttMsP50/P95/Maxonly when the window has samples, so sparse windows do not publish zeros into the distributions.relay-observability.tf(flat extractors). Not applied.latencySummary()replaces three inlined percentile calls; control-renewal output is byte-identical.Notes
{type:'pong', t}since the original transport; the cell reads onlyt, ignores missing/negative, drops >120 s.conn-openaccept failures (phone close, attach deadline) are still not timed; follow-up.Verification
cloud/apps/relay:pnpm typecheck,pnpm test(54 files, 513 tests) after rebase on main.cloud:pnpm lint;terraform fmt -check; terraform script node tests (45).Not for merge until the owner gives the go.