Skip to content

perf(remote): let lease admission check a reused lease instead of a heartbeat - #5151

Merged
thymikee merged 9 commits into
mainfrom
t3/skip-redundant-lease-heartbeat
Nov 28, 2026
Merged

thymikee merged 9 commits into
mainfrom
t3/skip-redundant-lease-heartbeat

Conversation

@thymikee

@thymikee thymikee commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Admission already renews a lease, so the CLI skips the heartbeat on a reused one when that request's /health reports lease-admission with every instance ID (a proxy's only through its upstream). An undispatched inactive-lease refusal, or the client's own unsent refusal, reruns once. Device commands go from 3 requests to 2.

The heartbeat stays for macos-app and runtime-backed leases, admission-exempt commands, installs, batch/replay/test, fill --text-stdin, --save-script, Metro preparation, non-canonical lease IDs, another daemon or owner scope than the saved connection, and by-spec opens naming a spec, selector, or no stored device. Marked requests never take /rpc/checked; one request per step there is a follow-up.

Daemon: device work on a dead lease is refused before teardown. close and lease commands still end the session; for a removed lease they start its lease end without waiting. The CLI daemon transport moved modules (line limit).

Security

No resend on timeouts, 5xx, scope mismatch, a daemon-claimed unsupported capability, or missing no disclosure. Refusals after teardown claim no verdict. Fill redaction restores only typed dispatched and lease reason.

Validation

Head 53800bd on b69cf45: 233 lease, changed, wire-compat and eager-closure test files (3069 tests), lint, typecheck, layering and Fallow pass (6082299 ran 828 files). Review fixes have tests failing without them; Metro open after lease expiry heartbeats, allocates, sets up the bridge, then opens on one lease. Not run on a device; CI pending.

Hot-path timing from an earlier head (50 ms each way, emulator, n=10):

command      base req  p50/p90     head req  p50/p90
open repeat  3         2064/2375   2         1986/2306
snapshot -i  3          878/930    2          710/1018
press        3          580/647    2          577/623
fill         3          950/995    2          925/1610
screenshot   4          826/948    3          670/845
round trips/call ~312 -> ~208 ms; 10-step loop 30 -> 21 requests

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.67 MB 6.67 MB +6.2 kB
Package (unpacked) 6.67 MB 6.67 MB +6.2 kB
Package (download) 2.04 MB 2.04 MB +1.8 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 22.9 ms 25.5 ms +2.6 ms
CLI --help 48.3 ms 49.6 ms +1.2 ms

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 18 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread packages/daemon-client/src/index.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

…eartbeat

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on a2120d3. The verdict and the full list are in the summary comment.

thymikee and others added 2 commits November 27, 2026 14:25
An admission-checked request reads lease-admission from /health, so it goes
health-first on /rpc even on a checked connection. Lease-free commands there
still send one checked request.

Fill redaction restores details.dispatched and details.reason only when they
are daemon vocabulary. The CLI loads the lease-admission dispatch on demand.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Keeps cli.ts and daemon-client-transport.ts under the line limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@thymikee
thymikee force-pushed the t3/skip-redundant-lease-heartbeat branch from a2120d3 to 3708303 Compare November 27, 2026 13:28
@thymikee

Copy link
Copy Markdown
Member Author

Pushed 3708303, rebased on current main (the earlier four commits are squashed into 4953438).

  • An admission-checked command no longer takes /rpc/checked: on a checked connection it sends /health → /rpc with no heartbeat. Lease-free commands there still send one checked request. One request per step over the checked route is left for a follow-up.
  • Fill redaction restores details.dispatched / details.reason only when they are daemon vocabulary.
  • The CLI loads the lease-admission dispatch and its daemon transport on demand (eager-closure budget and line limit).

Local tests, lint, format, typecheck and layering pass; CI is pending.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 3708303. The verdict and the full list are in the summary comment.

Refusing before teardown now applies only to a request that would do device
work under the expired lease. A close or an admission-exempt command ends the
session at once, and a close also ends one whose lease the registry no longer
holds. Its refusal states no dispatch disclosure, since teardown may have run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

… input

- A request naming its session's expired lease in another spelling is refused
  before teardown, not after it.
- A lease command also ends a session whose lease the registry removed, while no
  other request holds that session.
- A rerun after a lease refusal reuses the fill --text-stdin value. batch,
  replay and test keep the heartbeat, since they read scripts while building
  the request.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on eed7a80. The verdict and the full list are in the summary comment.

A close or lease command that found a busy session skipped the teardown and
nothing queued it. It now starts the daemon's lease end, which runs once no
other request holds the session. A close waits for it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 39a7e8a, the code needs changes before merge. The main problem is that some remote work can now run under a stored lease that no heartbeat checked. This can break the Expo and React Native flow where open runs after a pause.

Could an expired lease reach Metro setup here? Take a Metro proxy profile (metroProxyBaseUrl or metroPublicBaseUrl) with an expired stored lease, no prepared runtime and no explicit Metro overrides, then run open on the stored device. connection-lease-admission.ts:62 does not look at runtime preparation, so the heartbeat is skipped. Then connection-runtime.ts:123 prepares the runtime and connection-metro-runtime.ts:46 registers the companion tunnel under the dead lease, before the retry path starts. If the bridge rejects the lease, the command fails and nothing reruns. If the bridge accepts it, the runtime is saved, the rerun skips preparation, and the tunnel stays on the dead lease while the app runs on the new one. The base always gives the bridge a live lease. The rule: no lease-scoped remote work may run before the command RPC under a lease that no heartbeat checked. leaseCheckedByAdmission should return undefined when this invocation will prepare a Metro runtime. Please export the predicate that preparation already applies (shouldPrepareRuntimeForCommand && hasDeferredMetroConfig && shouldPrepareRuntime) and pass forceRuntimePrepare and the selected runtime into the check.

connection-lease-admission.ts:89 returns state.leaseId as stored, and a connection without a saved record takes it from flags.leaseId as typed (connection-runtime.ts:245). Suppose that value is uppercase hex and the daemon session holds the same lease under the lowercase ID. The registry finds the lease, but request-admission.ts:219 compares the raw strings and returns LEASE_SESSION_MISMATCH, with no rerun. The base succeeds because the heartbeat returns the canonical ID. This needs a noncanonical ID from outside. Please lowercase and trim a hex lease ID with the same rule as normalizeLeaseId, or keep the heartbeat when the ID is not canonical. A second compare on the daemon side is not needed.

A second independent pass found a related path at connection-runtime.ts:123. connection-lease-transaction.ts:248 uses the stored lease instead of a heartbeat, so deferred Metro setup runs with an unchecked lease. If preparation succeeds and admission then rejects that lease, the first attempt has already saved the runtime. The retry may reuse those bridge hints with the new lease, because connection-metro-runtime.ts:85 checks the platform. Could the same fix as in the first point cover this? Keep the heartbeat whenever the existing preparation predicate will run, including with explicit Metro overrides, and decide this before the lease is acquired or reused.

A second independent pass found that a stale record may now hide a replaced lease. A record still names lease A, and another client with the same scope has replaced it with B and opened the same session. The base heartbeats A, gets LEASE_NOT_FOUND, and recovers B. request-admission.ts:125 compares A with B first and returns LEASE_SESSION_MISMATCH, so connection-lease-admission.ts:148 does not recover. When the request lease differs from the session lease, please check that the named lease is active first. Return the typed inactive refusal for an absent lease, and keep the mismatch for a live one.

A second independent pass found that the bypass may run without a daemon instance fence. If a proxy or health adapter reports lease-admission without the upstream instanceId, index.ts:132 still accepts it. The next RPC may then reach a different daemon, which can run the command if it holds the same lease ID and scope. For remote daemons, please require complete instance evidence with the capability, on both the first and the refreshed health answer. When a required ID is missing, use the existing heartbeat fallback.

A second independent pass found that command overrides may change which lease is admitted. A record from daemon A names lease L, daemon B has its own L under another run, and the command passes --daemon-base-url for B and B's --run-id. connection-lease-admission.ts:77 allows the bypass, so B admits its own lease. The base sends the stored run in the heartbeat and refuses the scope mismatch. Please skip the heartbeat only when the command's endpoint and lease owner scope match the saved connection, so that the command checks the same scope as the heartbeat.

A second independent pass found that a daemon answer may cause a second dispatch. connection-lease-admission.ts:152 treats the reason lease_admission_unsupported alone as proof that nothing was sent. An RPC error from a gateway can carry that reason with dispatched: unknown after the command was forwarded, and the CLI then heartbeats and resends. Only a typed refusal made by the local capability guard before send should trigger the fallback. A daemon error with the same reason should fail normally.

A second independent pass found a possible deadlock. Two sessions on different devices share one lease, each has a queued close, and the lease is removed meanwhile. Each close takes its own session and device locks, then at lease-lifecycle.ts:113 waits for the whole lease to end. request-execution-scope.ts:880 needs every session's lock, so each close may wait on the other. Any wait for a whole-lease end must happen outside request execution locks. A close that already holds its session locks should end only that session and leave the others to the lease-end owner.

A second independent pass found that a dispatched: no refusal may follow real teardown. A device command names missing lease A while the session holds a different expired lease B. lease-lifecycle.ts:122 only guards requests that name B, so cleanup can close the app (request-execution-scope.ts:669) before A is checked. The command then returns LEASE_NOT_FOUND marked as not dispatched, and the CLI may resubmit it. Please check that the request lease is live before request-driven expiry teardown, or report the actual teardown in the dispatch disclosure.

A second independent pass found that fill --text-stdin may fail later than before. On the base, a lease scope error returns before the pipe is read. Now cli-runner.ts:46 reads stdin to EOF first, so an open pipe delays the error until the producer closes it. Could this path keep the heartbeat, or run an equivalent scope check, before it reads stdin?

Not blocking: these can be taken or left: give one owner the list of commands that upload before their RPC, since connection-lease-admission.ts:43 repeats daemon-artifacts.ts:48 and isInstallLikeCommand; use one typed predicate that requires a no dispatch disclosure for both refusal kinds at connection-lease-admission.ts:148; and either state in the Summary that, after the registry removes a lease, close now waits for the lease to end and other admission-exempt commands that resolve the session start that end (lease-lifecycle.ts:112), or move that branch to a follow-up.

The earlier review threads are fixed at this commit and can be resolved: the separate capability probe is gone; the local dispatch helper is deleted; the claim about stored capabilities has no symbol left; the no-resend table now asserts the details; only typed disclosure and lease reason values skip redaction; close can tear down an expired lease; and removed-lease teardown now queues on session locks.

All checks pass at this commit. An earlier cancelled "Body rules" run checks only the PR description, and its re-run passed.

Not verified here: no tests were run, and the claims that the new tests fail on the base or the previous head were checked by reading only. It was not checked whether the external Metro bridge accepts or rejects an expired lease, though either result differs from the base. The live timing in the PR description predates the rebase and four later commits. It was accepted only for the hot path, which those commits did not change; the changed refusal, teardown and rerun route is covered by cli-lease-admission-proxy.test.ts, not on a device. Not every command handler was checked for commands that send several requests with a lease-exempt one first, where no rerun would happen.

Before merge, the heartbeat must stay when the command prepares a lease-scoped Metro runtime, and a noncanonical lease ID must be made canonical or keep the heartbeat. The other points above also need a fix or an answer. Validation should show that open with a Metro proxy profile after lease expiry sends a heartbeat or allocation before bridge setup, and registers the tunnel under the same live lease that the app runs on.

…t does

CLI: the heartbeat stays for Metro preparation, fill --text-stdin, a stored
lease id that is not canonical, and a command whose daemon or owner scope is not
the saved connection's. Only the client's own pre-send guard falls back for a
daemon without lease-admission, and that capability needs every instance ID.

Daemon: an ended lease named against another session lease is the inactive
refusal. Device work under a lease that is not live is refused before teardown,
a refusal after a teardown claims no dispatch verdict, and no request waits for
a whole-lease end under its execution locks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member Author

Re the review, addressed in 6082299:

  1. Metro: the heartbeat stays whenever preparation's own predicate (willPrepareRuntime) will run, decided before the lease is reused. A CLI test shows heartbeat, allocate, bridge setup, then open, all on the live lease.
  2. Lease ID: a stored ID that is not canonical keeps the heartbeat; the normalization rule now lives in contracts.
  3. Admission order: an ended lease named against another session lease is LEASE_NOT_FOUND; a live one stays a mismatch.
  4. Instance IDs: lease-admission counts only when /health names the daemon's and any proxy's instance, on the first and refreshed answer.
  5. Scope: the heartbeat stays unless daemon URL, tenant, run, backend and device key match a saved record. Records without a daemon URL keep it.
  6. Unsupported fallback: only the client's own LeaseAdmissionUnsupportedError triggers it.
  7. Lock order: a close holding its session ends only that session; the lease end is started outside the request's locks and never awaited.
  8. Teardown disclosure: device work naming a non-live lease is refused before teardown, and any refusal after a teardown omits dispatched.
  9. stdin: fill --text-stdin keeps the heartbeat, so the read-once plumbing is gone.

Non-blocking: uploads now use requestUploadsArtifacts, both refusal kinds are typed with dispatched: no, and the Summary states the removed-lease behavior. Still not checked: handlers that send a lease-exempt request before a device request, and nothing ran on a device.

The capability refusal table has no outside reader since the CLI matches the
refusal class. Binding the lease end outside a request's locks moves to the
execution-lock module.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At b58d303, one problem still needs a code change: a proxy can enable lease admission without identifying its upstream daemon. The other nine points from the earlier review are fixed.

A second independent pass found that the missing-upstream-ID point is still open in one case. On the first health check, or on the refresh after an instance mismatch, a proxy or health adapter can report service agent-device-proxy, its own instance ID and a top-level lease-admission, with no upstream. remoteDaemonCapabilities then treats the proxy as the daemon and accepts the capability. Both callers (first check, refresh) leave remoteUpstreamInstanceId unset, so the next RPC carries only the proxy fence and can reach a different upstream with no instance check. The rule: when the health service identifies a proxy, lease-admission counts only from an upstream link that has its own instance ID. Please apply this in the shared helper, which covers both health paths, and otherwise filter the capability out so the heartbeat runs. A test with that health answer, on both paths, should show a heartbeat before the command RPC.

These earlier threads no longer apply and can be resolved: the separate capability probe is gone, and capability comes from the command's own /health; the local dispatch helper is deleted in favor of the shared thrownBeforeDispatch; the stored capabilities symbol is gone, and the capability is read per request; the never-resent table still asserts the reason and dispatch value per row; the redaction exception stays limited to the typed dispatch and lease reason values; expired-lease close can tear the lease down, because close is not device work; and removed-lease teardown still runs under each session's locks, now queued outside the request's locks.

The cancelled "Body rules" check is likely unrelated to the code, since it validates only the PR description. The other 22 checks pass.

Not verified here: no tests were run. It was judged only by reading that the new Metro ordering, two-closes deadlock and admission-order tests would fail on 39a7e8a. The AsyncResource.bind escape was checked for top-level requests only. For a nested batch or replay step, the scope may be built inside the parent's lock context; the outcome looks the same because the close step ends its own session, but this was not traced end to end. There was no device or live Metro bridge run; the Metro fix returns that case to the base heartbeat path, and the CLI test mocks prepareMetroRuntime. The hot-path timing in the PR description predates the last two commits, which only add guards that fall back to the heartbeat. Command handlers that send a lease-exempt request before a device request, where no rerun would happen, were not checked; the PR author also lists this as unchecked.

Before merge, the proxy case needs the fix and its test, and "Body rules" needs a re-run.

…upstream

A health answer from agent-device-proxy with no upstream named only the
proxy's instance, so nothing held the next request to the daemon that checks
the lease. Such an answer now takes the heartbeat.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member Author

Re the follow-up, fixed in 53800bd: remoteDaemonCapabilities no longer counts lease-admission from a link that calls itself agent-device-proxy. A proxy answer therefore counts only through an upstream that names its own instance; with no upstream, or none with an ID, the capability is filtered and the heartbeat runs. Both health paths use that helper.

A CLI test against a proxy answer with no upstream covers both: the first check sends heartbeat then snapshot; after an instance mismatch the refused first send is followed by heartbeat, then snapshot. It fails without the fix, as does a daemon-client refusal case. The earlier review threads are already resolved.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 53800bd

Since the review of b58d303: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (f0b3cb684685).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee

Copy link
Copy Markdown
Member Author

At 53800bd, the remaining problem from the earlier review is fixed, and no code change is still needed. remoteDaemonCapabilities now counts a proxy's lease-admission only from its upstream link, so a proxy answer with no upstream gets the heartbeat before the command on both the first health check and the instance-mismatch refresh.

The cancelled "Body rules" check is likely unrelated to the code, since it validates only the PR description. The other 22 checks pass, including the jobs that run the changed daemon-client and CLI tests.

Not verified here: no tests were run locally, and it was judged only by tracing the b58d303 helper that the two new CLI cases and the new unit case would catch the old behavior. A non-proxy health adapter that omits service and reports a top-level lease-admission with only its own instance ID is still treated as the daemon, which is outside the proxy rule and remains accepted.

Before merge, "Body rules" needs a re-run.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 27, 2026
@thymikee
thymikee merged commit 982cdc1 into main Nov 28, 2026
22 of 23 checks passed
@thymikee
thymikee deleted the t3/skip-redundant-lease-heartbeat branch November 28, 2026 06:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant