Skip to content

feat(relay): time successful client accepts and control round trips - #19232

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay/accept-and-control-rtt-timing
Sep 7, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay/accept-and-control-rtt-timing

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​246 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​242
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​235 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​217

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 with stageMs.{assignment,credential,activity,attach,basis} (the stages tile the accept exactly, sum == totalMs asserted), 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, controlRttSamplesDelta always; clientAcceptTotalMsP50/P95/Max, per-stage clientAccept<Stage>MsP95, controlRttMsP50/P95/Max only when the window has samples, so sparse windows do not publish zeros into the distributions.
  • Terraform: 13 additive log-based metrics in relay-observability.tf (flat extractors). Not applied.
  • latencySummary() replaces three inlined percentile calls; control-renewal output is byte-identical.

Notes

  • Wire: no change. The desktop has echoed {type:'pong', t} since the original transport; the cell reads only t, ignores missing/negative, drops >120 s.
  • Control RTT p95/max include desktop main-thread scheduling; only the per-host median and fleet p50 read as distance (Terraform descriptions say so).
  • Post-conn-open accept 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).
  • Independent adversarial review, two rounds; round 2 approved.

Not for merge until the owner gives the go.

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

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 65899

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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, checkli… Complete the required template sections. Add a Fixes #... issue reference, an ELI5 summary, N/A with a reason under Visual Proof, explicit Testing checklist responses, AI Disclosure information when applicable, Review details, the Agent…
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 7 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 identifies both primary changes: successful client-accept timing and control round-trip measurement.
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 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 Fixes #... issue reference, an ELI5 summary, N/A with a reason under Visual Proof, explicit Testing checklist responses, AI Disclosure information when applicable, Review details, the Agent skill upstream boundary response, Notes, and the Checklist responses.

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 7 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: a0856a71-fc67-4ae4-8cca-c2217137728a

📥 Commits

Reviewing files that changed from the base of the PR and between a62cfed and 658998d.

📒 Files selected for processing (5)
  • cloud/apps/relay/src/host-session-client-accept.test.ts
  • cloud/apps/relay/src/host-session-registry.ts
  • cloud/apps/relay/src/relay-observability.test.ts
  • cloud/apps/relay/src/relay-observability.ts
  • cloud/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":')

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.

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

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.

🔒 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.ts

Repository: 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.ts

Repository: 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.

@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 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 as orca_relay_client_accept_completed and 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 ms vs 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.

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

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.

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.

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