Skip to content

fix(daemon): give leased artifacts and diagnostics records only to their lease id - #4945

Merged
thymikee merged 18 commits into
0.22from
fix/0.22-leased-output-ownership
Nov 23, 2026
Merged

thymikee merged 18 commits into
0.22from
fix/0.22-leased-output-ownership

Conversation

@thymikee

@thymikee thymikee commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Bind downloadable captures and diagnostics to their producing lease through retention (#4912). Screenshots, xctrace results, remote recordings, and remote traces use daemon-owned paths. Downloads validate the opened file descriptor. Stale cleanup preserves replacements.

Recording stop and teardown preserve the producing lease and recover a missing tenant from the session. Direct HTTP keeps the supplied recording filename. Delivered scripts use the admitted lease. Public-network perf reports use the retained capture. Local reports check retained source ownership by path and file identity. Simpleperf reads the device-side capture. Reports belong to the requester. Perf stop falls back to the session lease tenant. Unleased recording teardown uses the session lease tenant. Apple runner output follows the trace lifetime for active unleased caller-owned traces.

Diagnostics use daemon-generated record IDs. A current record takes precedence over a verified legacy file with the same name. Verified unleased recordings in session storage can replay. Legacy exports on reusable remote temp paths are refused.

Breaking for callers that omit the producing lease ID and for clients older than 0.21.28.

Before / after

  • GET /artifacts/<id> without the producing lease returns 401 instead of 200.
  • Reusing a screenshot destination leaves the earlier download bound to its own frame.
  • record stop refuses ambiguous remote exports.

Validation

At 10dfbfa6c9, 526 focused tests, 1,002 wire and eager-closure tests, wire compatibility, typecheck, lint, Fallow, and package verification passed.

Closes #4912

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.10 MB 5.11 MB +9.5 kB
Package (unpacked) 5.10 MB 5.11 MB +9.5 kB
Package (download) 1.55 MB 1.55 MB +3.2 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 21.1 ms 21.0 ms -0.1 ms
CLI --help 37.8 ms 41.6 ms +3.8 ms

@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: 2 new findings on dbcd132. The verdict and the full list are in the summary comment.

@thymikee
thymikee force-pushed the fix/0.22-leased-output-ownership branch from dbcd132 to 8d56500 Compare November 22, 2026 08:42
@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 8d56500. The verdict and the full list are in the summary comment.

@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 400ff5d. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Commit 400ff5d has five problems with leased artifacts and diagnostics. Each one lets a record or capture reach the wrong lease, or locks out the right one. They need fixes before merge.

A second independent pass found that reusing a capture path lets older artifact IDs serve a new lease's bytes. A direct static-token daemon that accepts host output paths can register a screenshot of an unleased session, then write a leased screenshot to the same path while the first ID is pending (artifact-tracking.ts:232, screenshot adapter, request-finalization.ts:161). Registration keeps the earlier entry, so both entries point at that path. GET /artifacts and the artifacts RPC still list the tenant-only ID, and GET /artifacts/<id> opens the new leased bytes through it. If the earlier entry was leased, the same-path check returns its ID instead, so the old lease reads the new capture and the producing lease cannot. Should each downloadable capture be published to a distinct daemon-owned file before it is tracked, with an ID reused only for the same published output and owner?

A second independent pass found that diagnostics written before an upgrade stay readable by the whole tenant (request-diagnostics-http.ts:194). With the same state directory, a leased request record written by the base keeps its original path and has no owners file. The head resolves that path without a live session (daemon-runtime.ts:656). It reads the missing sidecar as an empty owner list and streams the record to a caller with the shared token and tenant but no lease ID. A base debug close that kept its lease also wrote the raw lease ID into that record. The rule: a record that is explicitly unleased and a legacy record of unknown ownership must be told apart. Legacy records should be served only after trustworthy lease provenance is recovered and credentials are redacted, and ambiguous ones should stay off the remote route.

A second independent pass found that sequential reuse of a request ID makes existing diagnostics unreadable (request-diagnostics-http.ts:162). HTTP keeps caller-supplied tracking IDs and frees them on completion (http-server.ts:532), and the record name comes from that ID and the session (request-execution-scope.ts:271). Two completed requests with different lease IDs can therefore share one record, and the second can be a request the router refused, since the router writes diagnostics before lease admission. Both digests are appended (diagnostics.ts:395), and every digest must match the same credential. The base returned the record to its tenant. At head even the first request's legitimate owner gets 401, and an earlier unleased record at that address loses tenant-only readability. The rule: each independent request gets a server-unique diagnostics locator that carries its own ownership, while the client tracking ID stays for request tracking only.

A second independent pass found that legacy recording manifests can republish a leased export without its producing lease (record-runtime.ts:504). The base manifest recorded the remote-output flag and tenant but no lease verifier. When a stop-recovery request reaches the head handler for such a manifest, the missing verifier bypasses ownership and the completed export is returned (record-runtime.ts:539). A same-tenant request for an unheld named session with no tenant isolation can reach this path without a lease (request-admission.ts:116). Finalization then registers the export with no verifier (request-finalization.ts:107). The rule: the remote stop-recovery path republishes a completed recording only when its provenance is known. Explicitly unleased manifests keep recovery, and legacy exports of unknown ownership stay out of remote delivery.

A second independent pass found that the producing caller cannot replay its retained recording through record stop after teardown (record-runtime.ts:505). ADR 0024 documents that replay. Sending the original lease ID with its scope is refused in normal lease admission before the recording handler (request-admission.ts:132, lease-registry.ts:675). A request under no lease or a replacement lease reaches recovery and is refused at the manifest. The base could return the completed export on the same named session without a live lease. The rule: a replay that only returns a completed export verifies the presented ID against the manifest owner and needs no active lease. Live recovery stays under normal admission, and the manifest owner carries into artifact registration.

Not blocking, and each can be taken or left: the lease-ownership code (leaseVerifier, requestHoldsOutputLease, leasedOutputRefusal, claimRequestDiagnosticsRecord) sits in artifact-tracking.ts although diagnostics, recording and the router import it, while lease ID canonicalization already lives beside lease-context.ts; the SHA-256 digest comparison at artifact-tracking.ts:52 could use the existing timingSafeStringEqual; the doc and PR text say the daemon log names the lease ID, but request-scoped lines written before the request record are fingerprinted, so the sentence should cover only daemon-scope events or those writes should be marked operator-only; the test "record stop after a daemon restart serves the export only under the lease that started it" retires a session in memory and never reaches the ok:true branch after a real restart, so it could be renamed to the refusal it proves; the sentence "each caller reads only its own records" in remote-device-lease-contracts.md:93 holds only for callers that sent a lease ID; and http-server-proxy-leased-output.test.ts:200 does not send the artifacts RPC with an ended lease ID, so one assertion after endLeasedSession would cover the documented CLI route.

Could the ownership code be simpler and better owned with the same behavior? One lease-output module next to lease-context.ts could export the verifier (via canonicalLeaseId), a constant-time holds(), the refusal and the diagnostics claim. The HTTP authorizer could return {tenantId, leaseId} so both REST routes share one reader. The router could set one request-lease value read for artifacts, manifests and diagnostics owner. TenantOwnedEntry could take an optional leaseVerifier, so requireTenantOwnedEntry enforces both rules for artifacts. Production size (+266/-56) is under the 700-line threshold, and no deletion was found that would shrink it.

The three open inline threads from earlier review do not apply, so they can be resolved. Shared path cleanup: two IDs for one path share one refcounted cleanup, and leased-entry precedence is the documented rule. Lease-exempt commands: none of the lease-exempt commands returns downloadable artifacts. In-scope steps: they keep the outer request ID and append to the record the outer request already owns, and other steps get a fresh scope and claim. No lower-priority threads still apply.

CI is still running: Smoke Tests (android, ios, macos) and one other check are in progress, and the smoke jobs run every request through the new diagnostics claim, so the diff overlaps their route. Body rules has two cancelled runs superseded by a rerun in progress, with no code overlap. No conflicts are known. Not verified here: the test suite, the seeded mutations and check:affected were not run, and regression validity was judged by reading the base code path. Not verified here: the 0.21.28 client cut-off against release history, whether local macos-app leased sessions use the artifacts command or GET /artifacts without sending the lease ID (their listing would then be empty), and the daemon side of an artifacts RPC with an ended lease ID, which is traced in code only.

Before merge, the five problems above need fixes, and the checks that are still running need to finish green.

@thymikee
thymikee force-pushed the fix/0.22-leased-output-ownership branch from 400ff5d to ac4f9b2 Compare November 22, 2026 09:48
@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4945 (comment). Head is now ac4f9b2, rebased on 0.22.

The five problems

  1. Capture path reuse. An artifact record is bound to the output it registered (device, inode, size, mtime). An id is reused only for the same output and the same owner. A later capture at that path gets its own id, and the earlier id expires on list and on download. I did not copy each capture to a daemon-owned file: the tracker runs synchronously in response finalization, so recordings and directory artifacts would be copied on the request path, and record stop replay needs the original path. One gap stays: the output is checked at stat, not on the open descriptor, so a rewrite between the check and the open is not caught.
  2. Request id reuse. The daemon names each diagnostics record with a random id that carries its owner (<32 hex>-<SHA-256 of the lease id> or -unleased). The caller's request id names no record. A record has one owner or none, so the owners file and "match every line" are gone.
  3. Legacy records. A record name that the daemon did not choose has no known owner. The route answers 404 for it.
  4. Legacy manifests. The manifest names its lease, or that it has none. record stop does not return a remote export whose manifest names neither.
  5. Replay after teardown. A completed export replays to a request that sends the manifest's lease id. record stop with no session passes admission when the lease it names has ended. A recording that still runs needs an admitted lease. The manifest owner goes into artifact registration.

Taken from the optional list: timingSafeStringEqual for the digest compare; the daemon-log sentence now covers only daemon-scope events; the contract doc sentence is limited to callers that sent a lease id; the recovery test is renamed and now reaches the ok: true branch; the proxy test sends the artifacts RPC with the ended lease id.

Not taken: a separate lease-output module. A new module in the daemon's eager import closure fails the closure budget, so the code stays in artifact-tracking.ts.

Side effect: files under requests/ are no longer named by the request id. A failed command prints the path, and each line carries the request id. Help and docs are updated.

Tests: seven seeded mutations each fail a test. pnpm check:affected --base origin/0.22 --run passes.

@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: 2 new findings on ac4f9b2. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Several findings from the earlier review (#4945 (comment)) are fixed at 639973d: the lease-blind artifact lookup, the owners file, the owners.every() check and the sensitive lease id registration are gone. CI is green, with 16 checks and none failing. There are no conflicts. The code still has the problems below.

Two user-doc sentences now name the diagnostics file by the request id, but the daemon names it by the record id (request-execution-scope.ts#L276, session-artifact-paths.ts#L50-L57). sessions.md#L49 tells the reader to look in requests/<request-id>.ndjson, and debugging-profiling.md#L149 names the same file for the remote download. The next line, #L150, says the "Log: unavailable" line carries the request id, but remote-request-diagnostics.ts#L84 prints the record id. A reader who follows these steps looks for a file that does not exist. Every user-doc and help mention of a request record file or its locator should name the record id. Searching request-id>.ndjson and "request id" near "Log: unavailable" over website/, skills/ and src/commands/schema lists the sites; docs/evidence is exempt.

A second independent pass found that an earlier screenshot ID can serve a later lease's bytes (artifact-tracking.ts#L339). A direct static-token daemon without an auth hook accepts explicit screenshot destinations. An unleased screenshot registered through clientArtifactPaths passes the identity check at #L432-L440. If a leased request publishes a same-size replacement to that path while the GET moves from stat to stream open, the unleased ID returns the leased bytes. Two captures can also overlap before registration (screenshot-runtime.ts#L218-L234). The rule: each downloadable result is bound at capture publication to a distinct daemon-owned file that stays stable through download and cleanup.

A second independent pass found the same problem for xctrace directories (artifact-tracking.ts#L285). A stop under another lease can target an existing published directory (session-perf-runtime.ts#L296-L299). The rename falls back to a recursive copy into it (perf-xctrace.ts#L171-L175), so the inode stays the same and the earlier ID still passes the check. Its GET then packages the new contents. The rule: an ID is bound at publication to a distinct daemon-owned directory or a sealed archive, so later writes to the caller-visible directory cannot change what the ID serves.

A second independent pass found that looking up a stale artifact can delete a newer caller-owned screenshot (artifact-tracking.ts#L396). Register an unleased screenshot at an explicit path, then write a replacement to the same path without clientArtifactPaths. The replacement is not registered (request-finalization.ts#L158-L181). A GET /artifacts, the artifacts RPC, or a GET of the stale ID detects the mismatch and cleans up the only entry, which unlinks the current file (#L615-L617). The base left that file in place. Retiring a stale entry should never unlink a replacement; cleanup should touch only the output the retired entry owned.

A second independent pass found that an old leased diagnostics record can pass as a new unleased one (request-diagnostics-http.ts#L143). The base accepted caller-chosen tracking IDs as filenames, so a legacy leased record can have a name that matches the new unleased format. After an upgrade with the same state directory, the head treats that name as explicitly unleased (artifact-tracking.ts#L100-L103) and streams the record to an authorized reader without its lease ID. The rule: new records resolve only in a daemon-owned namespace separate from legacy files, or carry persisted provenance that the legacy writer could not have supplied.

A second independent pass found the opposite upgrade gap in the same file (request-diagnostics-http.ts#L145). An unleased failure record written before the upgrade was fetchable through its locator on the base. At the head the same request gets 404, because the filename has no owner suffix. Legacy records with trusted evidence of unleased production should stay readable, through migration or a provenance-aware read. Records with ambiguous ownership should stay closed.

A second independent pass found that a routed batch step can append leased diagnostics to an unleased record (artifact-tracking.ts#L84). Send a batch without a lease to a fresh named session, and give its open step an active lease. Step flags are kept (batch.ts#L268-L278), and the step inherits the batch record ID (diagnostics.ts#L88-L102). The claim returns early, so the step writes into the batch's unleased file. The rule: a child reuses its parent's record only when their effective lease owners match; otherwise it claims its own record.

A second independent pass found that completed direct-HTTP recordings from the base can be republished without their lease (record-runtime.ts#L515). On the base, a leased recording with a client destination and no daemon path used the downloadable remote temp path, and its manifest had neither remoteCaptureOutput nor a lease verifier. With the export still present and no live session, a same-tenant request without a lease reaches record stop recovery. The guard allows the unknown owner, the temp-path check in record-runtime-response.ts#L12-L20 marks the export downloadable, and finalization registers it with no verifier. The unknown-owner refusal should cover both forms of daemon-owned remote recording, and provenance should be verified before either completed export is returned or registered.

A second independent pass found that an unleased recording can take the session's later lease at publication (request-finalization.ts#L102). Start an unleased remote recording in a named session, then open the same session and device under an active lease. Open keeps the recording and attaches the lease (session-open-state.ts#L52-L62). On record stop, the explicit unleased marker becomes undefined (record-runtime.ts#L511-L512), so finalization uses the stop request's lease. Close and release do the same through leased-recording-retention.ts#L28-L41. The explicit-unleased owner should survive response finalization, teardown should register with the recording's stored owner, and the request's lease should apply only when the producer made no ownership decision.

A second independent pass found a replay gap for recordings that finished before the upgrade (record-runtime.ts#L515). The base manifest stored remoteCaptureOutput and no lease verifier, and a repeated record stop replayed the export. At the head the same request gets LEASE_OUTPUT_MISMATCH, although no lease produced the file. Replay should work for legacy manifests with trustworthy evidence that the recording was unleased, and unknown remote ownership should stay closed.

Not blocking, and these can be taken or left: when an identity mismatch cleans up a registered output, the entry should be dropped without unlinking the path, or the source removed only if it still matches entry.output (artifact-tracking.ts#L396, which the base expiry timer already does by path); and a nested routed step should reuse the parent's record ID only when the step's sent lease matches the parent's owner (artifact-tracking.ts#L84). Both fit a follow-up issue.

None of the open inline threads from other reviewers still applies. These can be resolved: the lease-blind reverse lookup is gone because the lookup now matches tenant, verifier and output (#4945 (comment)); the record owner now comes from the lease id the request sent (#4945 (comment)); the owners file was deleted (#4945 (comment)); owners.every() was deleted (#4945 (comment)); the sent lease id is now registered as sensitive in 93c51bb (#4945 (comment)); and the unknown-owner case now answers 404 before the lease check (#4945 (comment)).

Not verified here: tests, seeded mutations and check:affected were not run. Regression validity was judged by reading the earlier test commit against the new tests. A batch step carrying a lease id different from its parent's was judged from the fill-unset rule only. The timing window between a capture write and its registration was judged from code, with no live attempt. Parts outside this delta were not re-traced.

Before merge, fix the request-id wording in sessions.md:49 and debugging-profiling.md:149-150 so every record file mention names the record id. Then address the diagnostics, artifact and recording findings above, and re-run CI.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed the six findings in 40f030f3d8.

  • Docs and help use the record ID. Screenshot and xctrace downloads serve their own daemon-owned paths. Stale artifact cleanup checks the registered output before unlinking.
  • New diagnostics use a separate directory. A routed child with a different lease gets its own record. The host can restore a legacy unleased record after verifying its provenance and checking for credentials.
  • Direct-HTTP recording replay refuses ambiguous remote exports. Stop and teardown preserve the recorded owner, including explicit unleased ownership. The lease contract documents how to restore a verified legacy unleased export.

The final head passed 280 focused tests, 950 eager-closure tests, 52 wire tests, the released wire compatibility check, typecheck, lint, and Fallow. The full affected rerun was queued behind the shared validation lock at push.

Review findings

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The smoke-test failures from the earlier review are fixed, but 9a83b71 still lets unleased output leak or be misowned in three places, and a second independent pass found six more. There are no conflicts. The only check not passing is Body rules, which was cancelled rather than failed and looks unrelated to the diff. Before merge, the three findings below need fixes, and the later ones need an answer.

Every remote screenshot against a direct static-token daemon leaves a PNG in the host's /tmp. The client sends a generated remote-temp outPath, and that path is kept when there is no auth hook or network marker. screenshot-runtime.ts:256 writes the capture to a private file, which is the only registered artifact, and then publishes a second full copy to outPath. Download or expiry removes only the private file, so long-running daemons grow without bound. On base the outPath file was the registered artifact and the download deleted it. The rule: a file the daemon writes for a downloadable result is either the registered artifact or is not written. Skip the publish when isRemoteTempArtifactPath(outPath, 'screenshot', '.png') is true, as macos-app-lease.ts:205 does, keep the caller-visible copy only for a real daemon-side destination, and assert that the remote-temp outPath does not exist after the download. The second pass reached the same result. Not verified here: that nothing else sweeps these files from /tmp.

The recording producer marker now owns the whole response. In request-finalization.ts:117, producer === null registers every artifact in the response with no verifier. Take an unleased recording in a session with remote script publication armed and stop it under a valid lease. The stop records an action, and remoteScriptVersionDelivery appends a savedScript revision to the same response. That revision is registered with no verifier, so a same-tenant caller without the lease can list and download it. The rule: a producer marker governs only what that producer made, here the recording export, its chunks and its telemetry. A daemon-delivered artifact takes the verifier of the admitted lease of the request that wrote it. Use the admitted-lease verifier when daemonDeliveredArtifact(artifact) is set, or carry the owner per artifact. Not verified here: the re-open path that leads to this state was not traced end to end.

Unleased recording exports lose the base tenant fallback. At request-finalization.ts:105, an unleased producer with no stored tenant registers the export with an undefined tenant, and artifact-tracking.ts:577 serves such an entry to every reader. On base, the stop request's tenant was used. A recording that a tenant-labelled stop finalizes is now downloadable for every tenant and for callers with none. leased-recording-retention.ts:34 dropped its fallback to lease.tenantId the same way. The rule: the explicit unleased producer decides only the lease verifier, and tenant resolution stays as on base. Use producerTenant ?? req.meta?.tenantId in every case, and fall back to lease.tenantId in retention.

A second independent pass found that request-diagnostics-http.ts:146 cannot serve verified legacy records with reserved-format names. Base accepts caller request IDs that match the new generated format. An operator who moves a verified record to requests-unleased under its original name, as the lease-contracts doc says, cannot restore access when the ID ends in the unleased marker or a 64-hex verifier. The first looks only in request-records and returns 404, and the second can return a lease refusal before any file is checked. Honor the verifier of an existing current record, and otherwise look for the exact name in the host-verified legacy directory regardless of its format.

A second independent pass found that record-runtime.ts:464 can register replacement bytes under the original owner. Two sessions on different devices can share an explicit remote-temp recording destination over direct static-token HTTP. Complete an unleased recording, then a leased one to the same destination. Android copies the new export over the path, and a repeat stop of the unleased session validates only the original manifest and that the path exists. It then registers the replacement under an unleased ID. Give direct-HTTP downloadable recordings a daemon-owned per-capture export path before the video, chunks and telemetry are written, and require verified byte provenance for older exports on reusable paths.

A second independent pass found that artifact-tracking.ts:344 validates a pathname before it opens the file. The identity check at lines 435-446 can pass while the original export is present, then another session's leased recording can replace the output before the stream opens. The handler can send the replacement's bytes under the original artifact ID. For replaceable producer paths, serve a daemon-owned per-capture copy. For file downloads, validate the identity of the opened file and stream from that same handle.

A second independent pass found that trace-runtime.ts:85 can publish leased diagnostics to an unleased reader. On a static-token daemon, an unleased named session can run a public-network command under a valid scoped lease without attaching it to the session. A trace started under that lease collects leased events, and a same-tenant stop without a lease registers the trace with no verifier. Starting the trace unleased also lets a later leased request append before an unleased stop. Keep the trace's producer owner from start through registration, refuse a stop under the wrong lease, and attach diagnostics only when the request and trace owners match.

A second independent pass found that session-perf-runtime.ts:331 assigns a perf capture to whoever stops it. Start a native perf capture under a valid scoped lease in an unleased named session. Start persists the path and tenant with no producer verifier, so a same-tenant request can stop it without the lease, and the artifact takes that stop request's owner in request-finalization.ts:100-117. The route is shared by xctrace, Perfetto and simpleperf, and the inverse case registers an unleased capture under a later stop lease. Persist the producer verifier or explicit unleased owner with the capture, check it before stopping, and pass it to artifact registration.

A second independent pass found that session-perf-runtime.ts:174 lets a report read a leased profile without the lease. Start and stop a CPU profile under the same scoped lease in an unleased named session. The profile stays in session.lastPerfProfile without its owner, and a same-tenant report request with no lease reads it and registers the report with no verifier. Carry the capture's owner into the retained profile, require the producing lease for the report source, and preserve that owner on the resulting artifact.

Would it be simpler to let trackDownloadableArtifact take ownership of the bytes at registration? It could hard-link the produced file or directory into an artifact-store directory under the daemon state dir, or copy it when linking is impossible, and serve and delete only that copy. Producers would keep writing to their normal outPath. That removes the screenshot private path and publish copy, publishXctraceDownload and the readOutputIdentity checks on download and cleanup, so the screenshot leak cannot occur. The parallel string|null|undefined helpers could become one OutputOwner value, {lease: verifier} | 'unleased', where absent means unknown and closed. Stamped per artifact at production and read by finalization, recording retention and the diagnostics route, it would stop a response-wide marker from reassigning a delivered artifact or dropping the tenant fallback. Does that fit what this PR needs?

Not blocking: the plugin-host managed-process test fix in plugin-host.test.ts:69 (try/finally and expect.poll for the hilog line) is not in the commit message, which describes only the smoke probes, so it can be mentioned there or split out, or left as is.

Of the other open threads, none are high-priority and all six no longer apply, so they can be resolved. Same-path registration: the tracker matches tenant, verifier and output, so a leased registration of the same path gets its own id by design. Record owner: it comes from the lease id the request sent, not the session lease (artifact-tracking.ts:76). Owners file: the file is gone, and nested steps reuse the parent record only on an owner match. owners.every(): it is deleted, and a record has one owner encoded in its id. Sensitive lease id: the trimmed canonical id is registered as a sensitive value. Unminted ids: an id the daemon did not mint is read only from requests-unleased, and an absent file returns 404.

Not verified here: no tests, seeded mutations or check:affected were run. Every finding comes from reading the code against base and the earlier head.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed the findings in 34b6b2c1d5.

  • A remote screenshot writes only its registered file. A delivered script keeps the admitted lease alongside an unleased recording. Response finalization and teardown keep the tenant fallback.
  • Verified legacy diagnostics keep their original locator, including reserved-format names. An existing current record takes precedence and enforces its verifier.
  • Downloadable direct-HTTP recordings get a daemon-owned path at start. Replay refuses legacy exports on reusable temp paths. Verified unleased exports in session storage can still replay. File downloads check the opened descriptor and stream from that descriptor.
  • Trace stop and request diagnostics attachment check the trace producer. Downloadable traces use request-scoped diagnostics. Persistent runner streams stay on caller-owned trace paths.
  • Perf stop and report carry the producer through the retained profile and resulting artifact. A request that lacks the producing lease cannot stop or report on a leased capture.

I kept publication in the producers because a registration-time copy runs after the producer can lose control of a reusable path. A hard link also shares the source inode. Finalization selects the admitted owner for delivered artifacts and the stored producer for capture output.

Unit-core, focused tests, eager closure, wire compatibility, typecheck, lint, Fallow, and package verification passed. The affected run was still queued at push after 15 minutes of cumulative lock wait.

Review findings

@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: 2 new findings on 34b6b2c. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At f307a48, the two earlier trace-stop and perf-report findings from the 9a83b71 review are fixed, but four defects remain. All 17 checks pass at this commit. Not verified here: any behavior by running it, because no tests, mutations or check:affected were run, and every result below comes from reading f307a48 against 9a83b71, 34b6b2c and base e8adbb8.

A second independent pass found that an ID-only stop loses the session tenant for an unleased recording (record-runtime.ts:498). On a static-token daemon, start a downloadable recording in an unleased named session with no tenant label, then reopen that session under tenant A's lease. The reopen keeps the recording (session-open-state.ts:52-62). A stop with only the lease id now stores no tenant, and request-finalization.ts:103 falls back to the absent request tenant. The base used session.lease.tenantId. Callers with no tenant, or another tenant, now see the video, chunks and telemetry in inventory and can fetch them by ID. When the manifest has no tenant, the stop should take it from the stored tenant, then the session lease tenant, then the request, and the recording should keep its unleased verifier. This assumes admission does not copy the session lease tenant into req.meta.tenantId for a request that sends only the lease id. Not verified here: every writer of that field.

A second independent pass found that direct HTTP recordings change an explicitly extensionless client filename (record-runtime.ts:386). Against a static-token direct HTTP daemon without a network marker, start an unleased Android recording with the client destination clip. The client sends a .mp4 host placeholder but keeps the client destination without an extension (daemon-artifacts.ts:372-384,426-432). The base kept that destination as supplied. The head appends .mp4, so the start reply echoes clip.mp4, and a stop without a new destination writes clip.mp4 (record-runtime-response.ts:41,140-146). The unique daemon export path and its platform extension should stay. The supplied client destination should stay as supplied on the direct HTTP explicit-placeholder branch, and extension completion should remain on the branches that applied it on base.

A second independent pass found that unleased downloadable traces lose replay timing events and Apple runner output (trace-runtime.ts:58). In an unleased session reached through a public-network HTTP request, start a downloadable trace and run an .ad replay against that session. The base set session.trace.outPath, so replay appended replay_action_start and replay_action_stop with result timing. The head sets only remoteCaptureOutputPath, so the fallback at session-replay-runtime-plan.ts:153 is undefined and session-replay-trace.ts:9 drops these events. Apple runner launch and build chunks that start during the trace are also lost (request-generic-dispatch.ts:102, runner-launched-session.ts:114-117). The owner-checked trace destination should reach replay's event writer, and runner output attributable to a matching request should reach the trace. Runner writes should stay bound to the trace lifetime and the producing request, so the published file stays stable and output from other owners stays out.

A second independent pass found that a retained leased profile blocks an xctrace report on an unrelated explicit source (session-perf-runtime.ts:178). In a named Apple session without a bound lease, start and stop xctrace under a scoped lease so lastPerfProfile belongs to that lease. A local SDK caller then asks for a report with an explicit tracePath that names its own unleased capture. The base uses the explicit source. The head refuses with LEASE_OUTPUT_MISMATCH before it selects the source. The SDK exposes this input (perf/index.ts:46,133-143), and the Apple backend reads it without consuming the handoff (platform-runtime-perf-host.ts:40-48). The report source should be selected first, and ownership should be checked only where the retained handoff or its path is used. A distinct caller-owned xctrace source should work without consuming the retained profile or its template.

Not blocking, and these can be taken or left: a remote trace now has no outPath, so runner and backend streams no longer reach it, and the PR body could say it carries only request diagnostics; record stop and perf stop (record-runtime.ts:500, session-perf-runtime.ts:308) could resolve a missing manifest tenant from the stored tenant, then the session lease tenant, then the request, as leased-recording-retention.ts:34 does; and ADR 0024 line 290 should say a daemon-owned export (remoteCaptureOutput) is registered and legacy remote-temp exports are refused, to match remote-device-lease-contracts.md.

Could one assertRequestMayUseOutput(req, owner: string | null | undefined) live in artifact-tracking.ts next to requestHoldsOutputLease? Trace stop, perf stop and report (replacing assertPerfOutputOwner), and the running-recording branch of assertRequestMayStopRecording could all use it, and the perf manifest owner could be read through the same reader as recordings, so remoteCaptureLease has one encoding. That would remove the duplicate predicate and the second encoding with no behavior change.

No high-priority threads from other reviewers still apply, and no lower-priority threads still apply. These eight threads do not apply and can be resolved. The tracker reuses an id only for the same tenant, verifier and output identity, so a leased registration gets its own id by design (#4945 (comment)). The record owner comes from the lease id the request sent, not from the session lease (#4945 (comment)). The owners file is gone, and the owner is encoded in the record id (#4945 (comment)). owners.every() is deleted, and a record has one owner (#4945 (comment)). The trimmed and the canonical lease id are both registered as sensitive values (#4945 (comment)). An unminted name is read only from the unleased requests, and a missing file returns 404 (#4945 (comment)). Trace stop under a lease is fixed at f307a48 (#4945 (comment)). The perf report now uses the requester's lease and tenant, fixed at f307a48 (#4945 (comment)).

Before merge, the four findings above need fixes, and the checks need to pass again on the new head. Live validation should reach each route named above and show the tenant, filename, trace events and report source it describes.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed the four findings in the review at f307a48 in a141e047f2.

  • Recording stop uses the manifest tenant, then the session lease tenant, then the request tenant. The recording keeps its explicit unleased owner.
  • Direct HTTP keeps the supplied client filename, including an extensionless name, and exports to a unique daemon path with the platform extension.
  • Replay timing and Apple runner output use the owner-checked request trace. Runner output stops when the trace or its producing request ends.
  • A distinct explicit xctrace source reports without consuming the retained profile or its template. The retained source and aliases still require the producing lease.

All six regression cases failed with the relevant fixes disabled. The amended head passed 322 focused tests, wire compatibility, 1,002 wire and eager-import tests, typecheck, lint, and Fallow. The packed-core checks passed before the final test-only amendment, and clean-install snapshot-bridge verification passed. The final affected run is queued behind the shared validation lock.

@apex-sentinel-staging

This comment has been minimized.

@thymikee
thymikee force-pushed the fix/0.22-leased-output-ownership branch from a141e04 to b2e982f Compare November 22, 2026 16:37
@thymikee

Copy link
Copy Markdown
Member Author

Rebased on 0.22 at bdf5096f77, including #4942 and #4953, and pushed b2e982f02a. The rebase keeps upstream lease admission and session routing, uses the contracts package’s lease ID normalizer, and updates the fixtures for the typed session lease. All 439 focused tests, 1,000 wire and eager-closure tests, the wire compatibility gate, typecheck, lint, and Fallow passed. The full affected run and hosted CI are pending.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee
thymikee force-pushed the fix/0.22-leased-output-ownership branch from 26c0d1d to 8c6fcd5 Compare November 22, 2026 19:49
@thymikee

Copy link
Copy Markdown
Member Author

Rebased #4945 on 0.22 after #4944 and #4846. The current head is 8c6fcd5e36 on base 9c40d427fa. The conflict resolution preserves #4944’s lease admission and journaling, #4846’s provider-catalog fallback, and #4945’s leased output ownership and replay. Typecheck, lint, Fallow, wire compatibility, package verification, 526 focused tests, and 1,002 wire and eager-closure tests passed at this head.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Of the earlier findings (#4945 (comment)), the Simpleperf one is fixed at 8c6fcd5, but one regression in the xctrace report path is still open.

An independent explicit xctrace source drops the saved handoff whenever the handoff has a lease verifier (session-perf-runtime.ts:191). This includes a handoff owned by the caller's own admitted lease. A second independent pass found the same path. To reproduce, stop an xctrace CPU capture with Time Profiler on a leased local session. Then run perf cpu profile report --kind xctrace under the same lease with a different readable tracePath and no --template. The saved handoff is dropped, so the template and profile at :223-224 are undefined. Base 9c40d42 passed the saved template. The report JSON (perf-xctrace.ts:549) and the response lose the template for the lease owner reading its own capture. Unleased callers keep it. The lease rule does not need this drop, because assertPerfOutputOwner (:432-435) accepts this handoff for this caller. The rule to enforce: an independent explicit source discards the saved handoff only when assertPerfOutputOwner would refuse that handoff for this caller. The simplest way is to share one predicate between the two sites. The test at http-server-perf-report.test.ts:273-301 currently asserts template: undefined and profile: undefined for the same-lease case. It should expect Time Profiler and the saved profile instead.

The inline thread on Simpleperf lease checks (#4945 (comment)) no longer applies at 8c6fcd5. An explicit Simpleperf tracePath now runs the lease check, daemon-owned Simpleperf stops are retained, and the test.each at :170 covers it. It can be resolved.

Body rules was cancelled. It lints the PR body and runs no code route, and the diff does not touch it. It needs a re-run before merge. One other check is still running. No conflicts are known.

Not verified here: any test, mutation or check:affected run, since all conclusions come from reading 8c6fcd5 against ce3c247 and base 9c40d42. Not verified here: a device run showing the xctrace report differs only in the echoed template field. Only the logical patch changes from the rebase were reviewed line by line, not the upstream 0.22 commits.

Before merge, the saved handoff must be kept for a same-lease caller at :191 with the test updated as above, and Body rules must pass.

@thymikee

Copy link
Copy Markdown
Member Author

Follow-up to the review on 8c6fcd5. 10dfbfa6c9 shares the lease predicate between handoff selection and ownership assertion. An independent xctrace source keeps the saved profile and Time Profiler template when the caller owns the handoff. The HTTP regression test failed before the fix and passed after it.

The 526 focused tests, 1,002 wire and eager-closure tests, wire compatibility, typecheck, lint, Fallow, and package verification passed. The full local affected run stopped on a timeout in the unchanged daemon fixture launch guard, which passed in isolation with its original timeout. I requested the Body rules rerun and validated the updated PR body locally.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 10dfbfa

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

No open findings.

Not in the reviewers' prompt (1 file)
  • test/wire-compat/ledger.json: left out as an asset or for its size; reviewers could still search it

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

💬 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

The code at 10dfbfa looks good. It fixes the finding from the earlier review (#4945 (comment)), and no new problems were found in the changes since 8c6fcd5. The Simpleperf explicit trace path lease check was already fixed at 8c6fcd5 and the new commit does not touch it, so that thread can be resolved: #4945 (comment).

Only the Body rules check is not passing. It was cancelled, it only lints the PR body, and it runs no code from this change. It needs a re-run before merge. No conflicts are known.

Not verified here: tests, mutations and check:affected were not run, so this conclusion comes from reading the diff against 8c6fcd5 and base 9c40d42. Not verified here: a device run of perf cpu profile report --kind xctrace on a leased session. The change restores the base inputs to perfProfileReport, so no device run is needed.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee
thymikee merged commit 555c62b into 0.22 Nov 23, 2026
16 of 17 checks passed
@thymikee
thymikee deleted the fix/0.22-leased-output-ownership branch November 23, 2026 07:19
thymikee added a commit that referenced this pull request Nov 23, 2026
… rules out

#4945 tests attached a lease to an open session. A session lifetime now keeps
its lease from creation, so trace writability no longer checks for a gained
lease, and tests of an unleased producer on a later-leased session go away.
thymikee added a commit that referenced this pull request Nov 23, 2026
* refactor(daemon): bind session authority to one lifetime

* chore(gates): ratchet raw session store reads

* fix(daemon): verify reopen lease claims and retry pinned cleanup

* fix(daemon): fence replay and snapshot cancellation by lifetime

* refactor(daemon): drop lease-change paths that a fixed lifetime lease rules out

#4945 tests attached a lease to an open session. A session lifetime now keeps
its lease from creation, so trace writability no longer checks for a gained
lease, and tests of an unleased producer on a later-leased session go away.

* docs(help): keep the remote first screen within 30 lines

* fix(daemon): refuse ended session authority as a canceled request

Name a missing merge base in the raw-read ratchet instead of a git stack.
thymikee added a commit that referenced this pull request Nov 23, 2026
…eir lease id (#4945)

* fix(daemon): give leased artifacts and diagnostics records only to their lease id

Output of a request that acted under a lease keeps that lease as its owner.
Artifact inventory and download (HTTP and the artifacts RPC) and the request
diagnostics route give it only to a request that sends the lease id, for as
long as the daemon keeps the output, also after the lease ends. The proxy
forwards the lease header, REST errors carry details.field, and the CLI sends
the ended proxy lease id on artifacts.

Closes #4912

* fix(daemon): keep lease ids out of diagnostics records and bind recordings to their lease

A request diagnostics record gets its owners before its first byte: the lease
id that the request sends and the lease of the session at its address. They are
kept beside the record as SHA-256 verifiers and never served. Diagnostics name
a lease by a fingerprint, except in the host-only daemon log. A recording
manifest keeps the verifier of the lease that started it, and record stop
checks it. The request_lease line and its parser are gone.

* fix(daemon): make the lease id a request sent the only owner of its diagnostics record

The lease of the session at the request's address is no longer an owner. A
request without the session lease id never acts on a leased session, and a
record never holds a raw lease id, so each caller reads only its own records.
The record claim moves to the request router; request-execution-scope.ts is
unchanged from the base.

* fix(daemon): bind each output to its own record and its lease

- An artifact id serves only the output that it registered. Another capture
  written to the same path gets its own id, and the earlier id expires.
- The daemon names each request diagnostics record. The name carries the owner,
  so a record has one owner or none, and the owners file is gone. The caller's
  request id names no record. A record that an earlier release named is not served.
- A recording manifest names its lease, or that it has none. A completed export
  replays to a request that sends that lease id, with no active lease, and stays
  with that lease when it is registered. A remote export of unknown ownership is
  not replayed.

* fix(daemon): redact any sent lease id from its record and answer unknown records 404 in one place

* fix(daemon): type the legacy diagnostics headers and refresh the route's wire acknowledgment

* test(wire-compat): record the diagnostics route digest in the declaration map

* fix(daemon): isolate published captures and preserve producer ownership

* test: follow the daemon-reported diagnostics path in packed smoke probes

* fix(daemon): retain capture provenance through artifact delivery

* fix(daemon): preserve trace stop and assign perf reports to requesters

* fix(daemon): preserve capture destinations and scope trace writers

* fix(daemon): use canonical lease types for retained outputs

* fix(daemon): authorize perf report sources and downloads

* fix(daemon): preserve retained capture ownership and trace lifetime

* fix(daemon): preserve perf report and diagnostics admission semantics

* fix(daemon): enforce retained source ownership for Simpleperf reports

* fix(daemon): preserve xctrace handoff for its lease owner
hannojg pushed a commit to hannojg/agent-device that referenced this pull request Nov 23, 2026
…eir lease id (callstack#4945)

* fix(daemon): give leased artifacts and diagnostics records only to their lease id

Output of a request that acted under a lease keeps that lease as its owner.
Artifact inventory and download (HTTP and the artifacts RPC) and the request
diagnostics route give it only to a request that sends the lease id, for as
long as the daemon keeps the output, also after the lease ends. The proxy
forwards the lease header, REST errors carry details.field, and the CLI sends
the ended proxy lease id on artifacts.

Closes callstack#4912

* fix(daemon): keep lease ids out of diagnostics records and bind recordings to their lease

A request diagnostics record gets its owners before its first byte: the lease
id that the request sends and the lease of the session at its address. They are
kept beside the record as SHA-256 verifiers and never served. Diagnostics name
a lease by a fingerprint, except in the host-only daemon log. A recording
manifest keeps the verifier of the lease that started it, and record stop
checks it. The request_lease line and its parser are gone.

* fix(daemon): make the lease id a request sent the only owner of its diagnostics record

The lease of the session at the request's address is no longer an owner. A
request without the session lease id never acts on a leased session, and a
record never holds a raw lease id, so each caller reads only its own records.
The record claim moves to the request router; request-execution-scope.ts is
unchanged from the base.

* fix(daemon): bind each output to its own record and its lease

- An artifact id serves only the output that it registered. Another capture
  written to the same path gets its own id, and the earlier id expires.
- The daemon names each request diagnostics record. The name carries the owner,
  so a record has one owner or none, and the owners file is gone. The caller's
  request id names no record. A record that an earlier release named is not served.
- A recording manifest names its lease, or that it has none. A completed export
  replays to a request that sends that lease id, with no active lease, and stays
  with that lease when it is registered. A remote export of unknown ownership is
  not replayed.

* fix(daemon): redact any sent lease id from its record and answer unknown records 404 in one place

* fix(daemon): type the legacy diagnostics headers and refresh the route's wire acknowledgment

* test(wire-compat): record the diagnostics route digest in the declaration map

* fix(daemon): isolate published captures and preserve producer ownership

* test: follow the daemon-reported diagnostics path in packed smoke probes

* fix(daemon): retain capture provenance through artifact delivery

* fix(daemon): preserve trace stop and assign perf reports to requesters

* fix(daemon): preserve capture destinations and scope trace writers

* fix(daemon): use canonical lease types for retained outputs

* fix(daemon): authorize perf report sources and downloads

* fix(daemon): preserve retained capture ownership and trace lifetime

* fix(daemon): preserve perf report and diagnostics admission semantics

* fix(daemon): enforce retained source ownership for Simpleperf reports

* fix(daemon): preserve xctrace handoff for its lease owner
thymikee added a commit that referenced this pull request Nov 24, 2026
…eir lease id (#4945)

* fix(daemon): give leased artifacts and diagnostics records only to their lease id

Output of a request that acted under a lease keeps that lease as its owner.
Artifact inventory and download (HTTP and the artifacts RPC) and the request
diagnostics route give it only to a request that sends the lease id, for as
long as the daemon keeps the output, also after the lease ends. The proxy
forwards the lease header, REST errors carry details.field, and the CLI sends
the ended proxy lease id on artifacts.

Closes #4912

* fix(daemon): keep lease ids out of diagnostics records and bind recordings to their lease

A request diagnostics record gets its owners before its first byte: the lease
id that the request sends and the lease of the session at its address. They are
kept beside the record as SHA-256 verifiers and never served. Diagnostics name
a lease by a fingerprint, except in the host-only daemon log. A recording
manifest keeps the verifier of the lease that started it, and record stop
checks it. The request_lease line and its parser are gone.

* fix(daemon): make the lease id a request sent the only owner of its diagnostics record

The lease of the session at the request's address is no longer an owner. A
request without the session lease id never acts on a leased session, and a
record never holds a raw lease id, so each caller reads only its own records.
The record claim moves to the request router; request-execution-scope.ts is
unchanged from the base.

* fix(daemon): bind each output to its own record and its lease

- An artifact id serves only the output that it registered. Another capture
  written to the same path gets its own id, and the earlier id expires.
- The daemon names each request diagnostics record. The name carries the owner,
  so a record has one owner or none, and the owners file is gone. The caller's
  request id names no record. A record that an earlier release named is not served.
- A recording manifest names its lease, or that it has none. A completed export
  replays to a request that sends that lease id, with no active lease, and stays
  with that lease when it is registered. A remote export of unknown ownership is
  not replayed.

* fix(daemon): redact any sent lease id from its record and answer unknown records 404 in one place

* fix(daemon): type the legacy diagnostics headers and refresh the route's wire acknowledgment

* test(wire-compat): record the diagnostics route digest in the declaration map

* fix(daemon): isolate published captures and preserve producer ownership

* test: follow the daemon-reported diagnostics path in packed smoke probes

* fix(daemon): retain capture provenance through artifact delivery

* fix(daemon): preserve trace stop and assign perf reports to requesters

* fix(daemon): preserve capture destinations and scope trace writers

* fix(daemon): use canonical lease types for retained outputs

* fix(daemon): authorize perf report sources and downloads

* fix(daemon): preserve retained capture ownership and trace lifetime

* fix(daemon): preserve perf report and diagnostics admission semantics

* fix(daemon): enforce retained source ownership for Simpleperf reports

* fix(daemon): preserve xctrace handoff for its lease owner
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