Skip to content

fix(output): retain admitted scope through uploads and publication - #5344

Open
thymikee wants to merge 9 commits into
0.22from
candidate/output-upload-scope-022
Open

thymikee wants to merge 9 commits into
0.22from
candidate/output-upload-scope-022

Conversation

@thymikee

@thymikee thymikee commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

A daemon-produced artifact belongs to the tenant and lease of the request that produced it. A tenant-owned artifact, upload or materialized path serves only its own tenant. Remote callers choose the tenant and lease they send, so those values no longer decide who owns another request's output. Staged uploads are capped per tenant.

Before / after

  • Download of another request's output: 0.22 assigned the owner at finalize from the requesting tenant. Now trackDownloadableArtifact requires the producer's ArtifactOwner; a mismatch returns TENANT_OUTPUT_MISMATCH.
  • Untenanted entry: 0.22 served any tenant. Now exact tenant match only.
  • 33rd unconsumed upload for a tenant: 0.22 accepted it. Now UPLOAD_LIMIT_REACHED. trace stop, perf stop and perf report check tenant and lease.

Validation

Head daf62a2e3e. Production vs origin/0.22: +272/-193.

  • Unit-core on changed files plus 134 related daemon/proxy files: pass. Wire-compat: 52 passed.
  • Revert proof: with production restored from 0.22, 14 tests fail, including every new test.
  • Hosted CI owns lint, typecheck, Coverage and integration. artifact-tracking.ts is at the 1000-line cap.
  • Uploads carry the request tenant, so a tenanted CLI install works on a hookless daemon. Live tenanted proxy runs (install; trace and perf capture) in the PR comments.
  • Typed preflight, ticket PUT, finalize and legacy upload refusals reach the CLI with reason and hint, with no legacy fallback.
  • Risk: uploads bind to tenant, not lease.

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.29 MB 5.29 MB +833 B
Package (unpacked) 5.29 MB 5.29 MB +833 B
Package (download) 1.62 MB 1.62 MB +327 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 15.3 ms 15.6 ms +0.2 ms
CLI --help 26.0 ms 26.4 ms +0.4 ms

@blacksmith-sh

This comment has been minimized.

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

@apex-sentinel-staging

This comment has been minimized.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Review of 6bfaf24: the change needs fixes and one live validation before merge. CI shows 18 checks, 0 not passing, at this commit. The earlier failures in lease-artifacts.test.ts were at an older head, and that file is part of this diff. There are no conflicts.

This change is device-facing under the repo rules. Every admitted request now gets admittedArtifactScope, producers throw without it, and install from an uploaded artifact now goes through upload admission, capacity and owner matching (lease-lifecycle.ts:96). The PR body says no builds or devices ran, and the HTTP tests use fake runtimes. commitPerfFile also refuses when the platform's returned path differs from the reservation path (session-perf-runtime.ts:460), and only a real backend shows whether that holds. Nothing shows the production route working end to end. Before merge, please run one live session through agent-device proxy and connect proxy with a leased session on an Android emulator, using a built CLI at this head. Record the SHA, commands and outputs for: (1) install of a local .apk succeeds; (2) screenshot --out and perf memory snapshot --kind android-hprof --out <local> both download files locally; (3) trace start, then trace stop --out <local>, downloads the file; (4) after close, artifacts --json on the same connection lists the retained entries; (5) from a second connection with a different lease, artifacts --json lists none of them and downloading one of the first artifact IDs fails with LEASE_OUTPUT_MISMATCH.

A second independent pass found that ending a lease leaves its staging capacity charged. A tenant stages an upload or gets a resumable ticket under lease A, then ends A before using it. The lease registry drops the lease (lease-registry.ts:347), but neither staging registry gets the end event. The reservations stay charged until their idle timers fire (resumable-upload.ts:304, uploaded-artifact-tracking.ts:47). A successor lease can get UPLOAD_CAPACITY_EXCEEDED while every occupied slot belongs to an ended lease. A transfer already in progress sees the ended lease only at a commit gate (upload-authority.ts:94, upload-http.ts:136). At the shared lease-end boundary, invalidate that lease's tickets and pending uploads and abort its active transfers. Join started filesystem work before removal, and release the reservations when removal succeeds.

A second independent pass found a leak in install-from-source cleanup (session-app-source-deployment.ts:143). A staged archive is consumed and materializes. If removing the materializer's extraction directory then fails (install-source-archive.ts:136), the first await in the finally throws and skips resolvedSource.cleanup(). Taking the upload already disarmed its expiry timer (uploaded-artifact-tracking.ts:65), so the staging directory and its reservation can stay for the daemon's lifetime. Put resolvedSource.cleanup() in an inner finally around materialized.cleanup().

A second independent pass found that performance reports can read a retained profile from a different owner (session-perf-runtime.ts:215). On a hookless daemon, tenant A stops an unleased CPU capture in a shared named session. Tenant B can then request a report with its own active lease. The saved source carries only a lease verifier, the null verifier passes canReadPerfOutput at line 541, and the report is registered for B at lines 236 and 448. The report-requester fixture exercises this successful download under the second tenant and lease (http-server-remote-output.test.ts:463, :671 and :945). After close, the explicit host-path xctrace report route has the same gap for a retained unleased source, because its registry ignores tenant and skips null verifiers (artifact-tracking.ts:491 and :509). Store the full capture owner in the session handoff and the retained source registry. Check it before building a report from a session handoff or from an explicit source that resolves to tracked output.

A second independent pass found that performance stop returns another scope's capture metadata (session-perf-runtime.ts:384). On a hookless daemon, a declared tenant starts a public-network capture in a shared unleased session. A request under a different declared tenant or admitted lease can stop it, because the guard passes a null verifier and never compares the stored tenant. The stop response includes the producer's output path and artifact ID at lines 415–422. Compare the stopping request's admitted owner with the stored capture owner before finishing or returning the capture.

A second independent pass found the same gap for trace (trace-runtime.ts:86). A declared tenant starts a daemon-owned trace without a lease in a shared named session on a hookless daemon. A caller in a different tenant or lease scope can stop it. The stop guard compares only a non-null lease verifier, so it commits the original reservation and returns its artifact ID and daemon path (lines 97–114). Keep the admitted tenant and lease on the live trace, and require the matching owner before stop commits or returns the reservation.

A second independent pass found that script publication discloses identifiers to a different closing tenant (session-script-output.ts:162). On a hookless daemon, a declared tenant arms a remote script in an unleased shared session. A request from a different declared tenant can close that session and receive its publication ID and final artifact ID, because the close reply never compares its admitted owner with close.owner. A normal recorded action can also return the other tenant's publication metadata through lines 90–115. Download enforces the registered owner, but both responses disclose identifiers before that check. Pass the admitted request owner to both script response paths, and attach publication IDs, versions and delivery failures only for the matching producer scope.

A second independent pass found that remote app staging rejects supported Unicode session names (upload-client.ts:351). An unleased remote session with a valid name such as QA 東京 can be named through JSON RPC (request-session-intake.ts:17, session-paths.ts:16). At the base, install staged the app without putting that name in an HTTP header. This head sends the raw session as a header on preflight and legacy upload, and both fetch and Node's HTTP fallback reject it (ERR_INVALID_CHAR). So that session can no longer install a local package remotely. Use a reversible ASCII wire encoding for the session header, and decode it before resolving the upload session.

A second independent pass found that the upload client discards typed lease refusals after preflight (upload-client.ts:604). The client gets a valid ticket, then its lease ends before the PUT or finalize. The daemon answers with a typed lease refusal (upload-authority.ts:88 and :116). Direct PUT and finalize drop the response reason at lines 569 and 604. The fallback then turns the refusal into a generic COMMAND_FAILED with the raw body in its message at line 335. Decode scoped REST failures the same way for direct, finalize and legacy responses. Keep the refusal code and reason, and stop the fallback on a definitive scope refusal.

Not blocking, and each can be taken or left: (a) assertArtifactOwner reports every owner mismatch as "Artifact belongs to a device lease. Send its lease id.", including tenant mismatches and an unleased upload used by a leased install, so pass the resource kind in, keep the earlier different-tenant refusal, and hint to stage again under the consuming lease (tenant-owned-entry.ts:69); (b) three registries repeat get, expired-error and assertArtifactOwner inline (uploaded-artifact-tracking.ts:64, resumable-upload.ts:437-441, materialized-path-registry.ts:123-125), so one requireOwnedEntry(map, id, owner, kind) could serve all four registries; (c) principal has no reader in packages/daemon/src, so delete it from admittedArtifactScope, DaemonRequestInternal and UploadAuthority until one exists (daemon-request.ts:55); (d) admittedOutputLeaseVerifier and screenshotProducerTenant still derive identity next to the new admittedArtifactScope.owner, so make FileOutputProducer = ArtifactOwner & { lifetimeId } and delete the old derivations (screenshot-runtime.ts:224); (e) the requestHoldsOutputLease and matchesTenantOwnedEntry comments still describe the old null-owner rule (artifact-tracking.ts:77); (f) with no x-agent-device-session header, admitUploadAuthority resolves default, which a leased default session now refuses, so treat a headerless upload as sessionless (upload-authority.ts:49); (g) the sentence on hookless declared tenants should say "For leased staging", because unleased staging trusts the declared tenant without a lease (remote-proxy.md:417); (h) commitPerfFile and commitPerfArtifact throw leasedOutputRefusal for internal invariant violations, so throw a plain Error at both sites (session-perf-runtime.ts:460); (i) ArtifactOwner, FileOutputDelivery and FileOutputReservation moved into the public @agent-device/contracts/artifact-adapter entry, but only packages/daemon uses them, so a daemon-local leaf module could hold them (artifact-adapter.ts:101).

For a follow-up issue, not for this PR: RESUMABLE_UPLOAD_LEASE_MISMATCH is declared and documented but no code path throws it, because the owner check already reports LEASE_OUTPUT_MISMATCH (error-reasons.md:1235).

Could the ownership logic collapse to one path? Keep the deletion of finalization registration, which is the core win. Then make admittedArtifactOwner(req) the only producer identity, with screenshot, trace and perf calling reserveFileOutput(type, name, req, lifetimeId). Replace requireTenantOwnedEntry and the inline copies with one requireOwnedEntry, with distinct tenant and lease refusals. Drop principal and the unused reason, and keep ArtifactOwner daemon-local. That removes duplicate derivations without changing behavior. The CLI artifactQuery resolution (artifactQueryFlags in command-connection.ts, about 30 lines with a 7-condition inheritance rule) is the other complexity hot spot. Does it need to ship with the daemon ownership change, or could it be a separate change?

Of the open inline threads, the one on the uncapped retry in staged-upload-cleanup.ts does not apply: the reservation must stay held until the bytes are gone, so please resolve it (thread). The threads on provider-session scope matching (thread) and on capacity errors staying server faults (thread) are fixed at this head, so please resolve them too.

Not verified here: any test run, so test validity is judged from the diff only, and whether session-script-output.test.ts or lease-artifacts.test.ts would fail on the base, because the modules they import moved. Also not verified here: that the hosted attachment lease is registered in LeaseRegistry under the id assertCurrent() returns, which admitUploadAuthority relies on (no hosted upload test is in the diff); that a first-party client can send a lease without tenant or run on an unleased non-isolated session, the one shape where the stricter requestHoldsOutputLease could break a download that worked at the base; the moved provider run-scope assertions and the deleted request-finalization.test.ts, beyond confirming the code they covered is gone; and the Apple perfProfileReport and iOS memory paths against the equal-path rule in commitPerfFile. The Android perfMemorySnapshot path does return the given outPath.

@thymikee
thymikee force-pushed the candidate/output-upload-scope-022 branch from 6bfaf24 to f6a93bb Compare December 3, 2026 07:44
@apex-sentinel-staging

This comment has been minimized.

@blacksmith-sh

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

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

@blacksmith-sh

This comment has been minimized.

@thymikee
thymikee marked this pull request as ready for review December 3, 2026 10:11

@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 40 files

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

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

Comment thread website/docs/docs/remote-proxy.md Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

2b0d987 fixes some of the earlier findings (#5344 (comment)), but it introduces a regression on the documented remote route, and the script publication disclosure from the earlier review is still open. The shared 32-upload limit is now documented, and cleanupInstallSources now runs both cleanups and rethrows the first error. The checks show 18 passing and only "Body rules" cancelled, which reads PR body text that no changed file exercises, so CI looks unrelated. There are no conflicts. The next step before merge is the tenant regression below.

On a daemon with no auth hook (for example behind agent-device proxy in clientToken mode), a tenanted CLI connection (connect proxy --tenant t1) uploads without a tenant. The upload client sends only auth and lease headers on preflight, ticket PUT, finalize and legacy POST (upload-client.ts, #L303-L310, #L470-L477), so the upload is staged with no tenant. The install request then carries meta.tenantId = t1, and the exact-match check refuses it with UNAUTHORIZED / TENANT_OUTPUT_MISMATCH. install ./app.apk, reinstall and install-from-source with a local path worked on 0.22 and now fail under this setup. The test 'another tenant cannot consume an upload that has no tenant' (artifact-tracking.test.ts:712) encodes this broken shape. The rule is that an upload is staged under the same tenant the consuming command sends. That means the upload client sends buildDaemonHttpTenantHeaders(req.meta?.tenantId ?? req.flags?.tenant) on all four upload requests, with the tenant passed through UploadArtifactOptions from both uploadArtifact call sites in packages/remote/src/daemon-artifacts.ts. Please add one test that goes from a tenanted CLI request through upload to install against a hookless daemon. A proxy with authenticate or a hook-attested daemon is unaffected.

This PR changes device-facing routes (capture stop and report guards for trace, perf and recording, plus the upload-to-install tenant rule), and the only evidence is unit and HTTP tests with fake runtimes. Those tests cannot catch the tenant disagreement above. The live run asked for at 6bfaf24 is still missing and is required before merge. After the fix, run a built CLI at the new head against an Android emulator with agent-device proxy (no authenticate) and connect proxy --tenant t1 on a leased session. Record the SHA, the commands and their output for: (1) install ./app.apk succeeds; (2) trace start, then trace stop --out <local>, downloads the file; (3) perf memory snapshot --kind android-hprof --out <local> downloads the file; (4) from a second connection with --tenant t2, artifacts --json lists none of t1's entries, and downloading a t1 artifact ID fails with TENANT_OUTPUT_MISMATCH.

A second independent pass found the following. On a hookless daemon, tenant T starts an upload under lease A, and lease B for T can then repeat the preflight, send a chunk, or finalize the same ticket. The HTTP routes pass only the tenant to staging (upload-http.ts:149-158, #L179-L185, #L202-L217, #L234-L242), and the preflight key has no lease (#L448-L457). A finished upload can also be installed or reinstalled through B, because session-app-deployment.ts:77-81 and install-source-resolution.ts:44-54 look it up by tenant alone. Uploads can cross leases within one tenant. The rule is to admit the presented lease at upload ingress and carry the admitted tenant and lease verifier through the preflight key, PUT, finalize, staged artifact registration and both install consumers, returning a typed lease refusal before touching a foreign entry.

A second independent pass found that lease end unbinds lease A without invalidating its uploads. Staged entries keep counting for the tenant until their five-minute timers run (artifact-tracking.ts:951-979), so a successor lease can hit UPLOAD_LIMIT_REACHED. Unfinished tickets stay until idle expiry (resumable-upload.ts:291-323), and a transfer already running can finish and publish after A ends, since its commit is gated only by HTTP ingress (upload-http.ts:108-124, #L234-L244, #L259-L275). At the shared lease-end boundary, invalidate the lease's tickets and staged entries and abort its active transfers. Join started filesystem work, and release reservations after the staged files are removed.

A second independent pass found that one tenant can hold more than 32 distinct preflight tickets with uploads partly staged. Each new ticket creates a directory and payload (resumable-upload.ts:261, #L265-L287), and the legacy POST receives its body before the count is checked (upload.ts:52-75, upload-http.ts:149-159, #L259-L279). The count applies only when a finished file reaches trackUploadedArtifact, so concurrent staging is unbounded apart from per-file limits and idle expiry. The rule is to reserve bounded staging capacity before any ticket or legacy directory is created, carry the same reservation through finalize, and release it on consumption or after joined cleanup.

A second independent pass found that tenant T can release retained install paths that were admitted under lease A, from no lease or from lease B, by supplying the materialization ID. The retain path passes only req.meta.tenantId (session-app-source-deployment.ts:238-244), the release RPC ignores the session lease (session-operations.ts:326-342), and the registry removes the paths after a tenant-only check (#L121-L127, #L155-L158). The scope checked at 6bfaf24 was removed in the follow-up delta. Store the producer's tenant and lease verifier when retaining, carry the lease credential through the release RPC, and compare it before removal, including for entries that outlive the session.

A second independent pass found that on a hookless daemon, tenant A can arm remote script recording in an unleased, explicitly named shared session, and a distinct declared tenant can then record an action there and receive A's publication ID and revision, or A's publication ID in a delivery failure (session-script-publication-capability.ts:254-283, #L291, #L295-L314). The same caller can close the session and get A's publication ID even when no final version is written (session-close.ts:389-403, #L345-L354). Finalization registers the file under A but still puts the artifact ID and publication metadata in the other caller's reply (request-finalization.ts:165-179). This was the earlier blocking finding at 6bfaf24 and it is not fixed. The rule is that the admitted reader owner is passed to both script-delivery paths and checked against the stored producer owner before any publication ID, version artifact, revision or failure is added to a reply.

A second independent pass found that when a tenant stops a daemon-owned trace without a lease and closes the session, a caller in the same tenant presenting a different lease can list the trace or fetch it by ID. Both routes forward the lease header (downloadable-artifact-http.ts:107-110, #L180-L197), but the null-owner path accepts any presented lease (#L111-L119, #L697-L713, #L851-L857). This conflicts with the new rule in remote-proxy.md:109-114 that a capture downloads only in the same tenant and lease scope. For downloadable artifacts, require an absent reader lease when the saved producer is unleased, and keep the verifier comparison for leased producers so the original lease credential still works after close.

A second independent pass found that the upload client drops typed refusals. When a tenant is at the staged upload limit, the daemon emits UPLOAD_LIMIT_REACHED at finalize (artifact-tracking.ts:959-966, upload-http.ts:234-244, #L267-L278), but the client drops the reason, falls back to sending the file again, and wraps the legacy rejection in a generic COMMAND_FAILED with the raw body (upload-client.ts:105-133, #L176-L185, #L280-L288, #L495-L499). A hosted-attachment lease refusal between a good preflight and the PUT or finalize is discarded the same way (http-authorization.ts:279-291, hosted-attachment-admission.ts:34-46, upload-client.ts:453-457). The rule is that REST error bodies on preflight, direct PUT, finalize and legacy upload decode into typed errors, and definitive scope and capacity refusals end the upload without a fallback.

Not blocking, and these can be taken or left: the script publication fix is to pass the admitted request owner into remoteScriptVersionDelivery and remoteCloseScriptDelivery and attach the publication fields only when it equals delivery.owner; and the CLI user never sees the UPLOAD_LIMIT_REACHED reason or hint because requestUploadControl reads the body only on success (upload-client.ts:370, #L499-L504), so capacity refusals should be terminal with their code, reason and hint.

For a follow-up issue, not for this PR: the staged-upload cap counts only finished uploads (artifact-tracking.ts:951-967), while open tickets and legacy bodies are uncounted, so every staged upload directory a tenant holds should count against one per-tenant limit before bytes are accepted, without counting a finalized ticket twice.

The open inline thread on the capture lease-before-tenant wording (#5344 (comment)) still applies, as wording only. Of the lower-priority threads, none still apply. These can be resolved: #5344 (comment) (an unadmitted caller-chosen lease proves nothing, so unleased recording is correct), #5344 (comment) (a tenantless open followed by a tenanted download is not a real flow), #5344 (comment) (the docs now state the shared limit of 32), #5344 (comment) (one refusal for ownerless and foreign entries is intended), and #5344 (comment) (cleanup now runs both steps and rethrows the first error).

Evidence limits: no tests were run, so test validity, including the 14-test revert proof and whether any test exercises the hookless tenanted upload-to-install route, is judged from the diff only. The tenant regression was traced through client and daemon source, not reproduced live. Not verified here: whether connect proxy always persists a tenant, only that leased sessions need one. Not verified here: recovered recordings or perf captures whose envelope metadata predates this PR (no remoteCaptureTenantId) now register with an undefined tenant, which a tenanted reader cannot download. The logical patch was reviewed from the 2b0d987 diff (40 files) against merge-base f3520a5.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Answers to #5344 (comment), head fca536ce5b:

  • A (tenanted upload regression): fixed in fca536c. The upload client sends the tenant header with the lease header on preflight, same-origin PUT, finalize and legacy POST. Both uploadArtifact call sites pass leaseScopeFromRequest(req).tenantId. Test: the lease-header test in upload-client.test.ts now asserts lease and tenant on every route. A daemon-package test cannot import the remote client without a new package edge, so the live run below covers the end-to-end route.
  • B1 (lease admission at upload ingress): not changed. Lease-scoped uploads are a separate invariant: the PR body states that uploads bind to tenant, not lease. The fix needs the lease through the preflight key, PUT, finalize, registration and both install consumers.
  • B2 (invalidate uploads at lease end): not changed. Uploads do not record a lease, so lease end has nothing to match. This follows B1.
  • B3 (reserve staging before directory creation): not changed. The review itself lists the same staging-count rule as a follow-up issue.
  • C1 (lease check on materialized-path release): not changed. This PR does not change the retention registry, and 0.22 had no lease check on release either.
  • C2 (reader owner for script delivery): not changed. On a hookless daemon the tenant is self-declared, so the other caller can send tenant A itself. On an attested daemon, tenant sessions are partitioned. The reply shape is the same as on 0.22.
  • C3 (absent reader lease for unleased producers): not changed. Unleased output has no lease rule (ADR 0007). A reader can omit the header, so the check protects nothing.
  • C4 (typed REST errors in the upload client): fixed in fca536c. A typed refusal from finalize or legacy POST is an AppError with code, reason and hint. A finalize refusal, such as UPLOAD_LIMIT_REACHED, ends the upload with no legacy fallback. Test: upload-client-redirect.test.ts.
  • D (live evidence): the local run is below. Trace and perf captures were not run, because they need an app session on a shared emulator.
Live run at fca536c (local daemon + agent-device proxy, no authenticate)
$ pnpm build
✔ Build complete in 7201ms
$ node bin/agent-device.mjs proxy --port 4399 --daemon-auth-token <token> --state-dir <private dir>
✓ Proxy listening at http://127.0.0.1:4399

$ export AGENT_DEVICE_SESSION=live-t1
$ agent-device connect proxy --daemon-base-url http://127.0.0.1:4399/agent-device --tenant t1
Status: Proxy configuration saved. Access is checked by the first remote command.

$ printf 'not-a-real-apk' > app.apk
$ agent-device install ./app.apk --platform android --serial emulator-5556 --json
"code": "COMMAND_FAILED",
"message": "failed to install /var/folders/.../agent-device-artifact-upload-MDM1pO/app.apk: Failure [INSTALL_PARSE_FAILED_NOT_APK: ...",
"diagnosticsRecord": { "session": "t1:live-t1", ... },
"details": { "cmd": "adb", "args": ["-s", "emulator-5556", "install", "-r", ".../agent-device-artifact-upload-MDM1pO/app.apk"], "adbFailure": "install_failed" }

The tenanted upload was staged for t1, and the t1 install consumed it: the daemon passed the staged file to adb install. The APK is deliberately invalid, so the emulator did not change. The old head was not run live. By code trace, at 2b0d987 the same install stops at the upload lookup with TENANT_OUTPUT_MISMATCH before any device step.

@blacksmith-sh

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Commit 7af202e fixes the tenant regression from the earlier review (#5344 (comment)), and typed refusals now reach the caller in the finalize step. Three findings remain. CI is pending: 17 of 18 checks pass, and the one not passing is a review check still in progress that runs no test route. The wire-compat and upload mutation jobs that failed at fca536c now pass, because 7af202e re-records the upload-client digests in the ledger.

The PR changes device-facing capture routes. Trace stop (trace-runtime.ts:79), perf stop and report, and recording stop now take the output owner from the starting request and check tenant and lease. The client downloads these outputs with lease and tenant headers. The only live run (fca536c, same production code as 7af202e) covers upload to install. The earlier tenant regression was a client and daemon scope disagreement that fake-runtime tests missed. The same disagreement on capture ownership would break trace stop --out or perf ... --out for a tenanted, leased caller. Please run a built CLI at 7af202e on any available emulator, with agent-device proxy (no authenticate) and connect proxy --tenant t1 on a leased session. Record the SHA, the commands and their output for: (1) trace start, then trace stop --out <local>, with the file downloaded; (2) perf memory snapshot --kind android-hprof --out <local> (or perf start and perf stop --out), with the file downloaded; (3) from a second connection with --tenant t2, artifacts --json lists none of t1's entries, and downloading one t1 artifact ID returns UNAUTHORIZED with reason TENANT_OUTPUT_MISMATCH. This run is required before merge. The install route is already covered.

A second independent pass found that a remote install can reach a hosted attachment with a lease ID the attachment no longer accepts (upload-client.ts:355). Admission refuses it with LEASE_SESSION_MISMATCH and the daemon returns a typed REST refusal. But requestUploadPreflight returns undefined for every failed status. The initial call at line 98 and the renewed preflight at line 219 then choose the legacy POST and send the artifact stream again. The caller only sees the later result. Please decode the failed response in requestUploadPreflight and throw definitive scope or capacity refusals at once. Keep the fallback for unsupported preflight and recoverable failures.

The same pass found that a valid same-origin ticket can still be refused on PUT, either by lease admission or by the tenant check at resumable-upload.ts:155 (upload-client.ts:472). The daemon sends a typed REST body, and upload-stream.ts returns it, but uploadDirectArtifact replaces it with a generic COMMAND_FAILED. The catches at upload-client.ts:185-192 and :235-238 then allow the legacy POST, so the PUT refusal is lost and a second upload starts. Please decode the daemon REST body in the same-origin non-success PUT branch and pass a definitive scope or capacity refusal through the existing UploadRefusal path.

Of the earlier inline threads, the thread on capture ownership wording still applies as wording only and does not block. The thread on the shared upload limit and the thread on install source cleanup are fixed at this head. These threads do not apply and can be resolved: #5344 (comment) (an unadmitted lease ID proves nothing, so recording the output as unleased is correct), #5344 (comment) (the opener owns the script version and the same connection downloads it) and #5344 (comment) (the refusal wording avoids revealing which entries exist).

Not verified here: no tests were run, the two new tests were judged from the diff (both would fail at 2b0d987), and the live install run at fca536c was read, not reproduced. No conflicts. Once the capture run is posted and the two refusal paths are fixed, the PR can be re-checked for merge.

Register every downloadable artifact with a required producer owner
(tenant and lease). Capture output from an earlier request carries that
producer; finalize no longer mixes in the requesting tenant or lease.
Tenant-owned entries serve only their own tenant, so an untenanted
upload or artifact is not readable by another tenant. Trace stop, perf
stop, and perf report check the full capture owner. Cap staged uploads
per tenant with UPLOAD_LIMIT_REACHED, and always run install-source
cleanup after materialized cleanup.
A failed preflight with a typed REST refusal reason, and a refused same-origin ticket PUT, now throw UploadRefusal instead of falling back to the legacy POST. An unsupported preflight route (404, 405, 501) and untyped failures keep the fallback.
@thymikee
thymikee force-pushed the candidate/output-upload-scope-022 branch from 7af202e to daf62a2 Compare December 3, 2026 12:24
@thymikee

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Head daf62a2e3e (rebased onto current origin/0.22, plus one fix commit).

Code findings

  • Preflight refusal (upload-client.ts requestUploadPreflight): a failed preflight with a typed REST reason now throws UploadRefusal through the existing readUploadRefusal decoder. 404, 405 and 501 and untyped failures still take the legacy POST. Fixed in daf62a2.
  • Same-origin ticket PUT refusal (uploadDirectArtifact): a non-2xx PUT on the daemon origin decodes the REST body through readUploadRefusal and throws UploadRefusal, so the existing catches do not fall back. A foreign-origin ticket keeps the generic failure. Fixed in daf62a2.
  • Test: upload-client-redirect.test.ts now runs the typed refusal case at preflight, PUT and finalize, and checks that no request follows the refused one. Ledger digests and rationales re-recorded for both declarations. check:daemon-wire-compat passes, and wire-compat plus wire-mutations pass 52 tests.

Live capture run

Built CLI at daf62a2e3e (pnpm build, node bin/agent-device.mjs). Android emulator emulator-5554 (Pixel 7, Android 16), app com.android.settings. Each command also had --platform android --serial emulator-5554 --state-dir <client dir> --session <s>.

$ AGENT_DEVICE_RETAIN_ARTIFACTS=1 agent-device proxy --port 4377 --state-dir <daemon dir>
✓ Proxy listening at http://127.0.0.1:4377

# t1 (session s1)
$ agent-device connect proxy --daemon-base-url http://127.0.0.1:4377/agent-device --tenant t1 --run-id r1
$ agent-device open com.android.settings
Opened: com.android.settings          # leaseId 4581ffdb62c3284f8e1c9bdbd99433ba saved in the connection
$ agent-device trace start
$ agent-device trace stop out/t1-trace2.log --json
"trace": "stopped", artifactId 70c69567-…, localPath out/t1-trace2.log   # 593 bytes downloaded
$ agent-device perf trace start --kind perfetto
Perf start: perfetto trace state=running
$ agent-device perf trace stop --kind perfetto --out out/t1.perfetto-trace --json
"state": "stopped", sizeBytes 41351, artifactId fe6f4e6c-…, localPath out/t1.perfetto-trace   # 41351 bytes downloaded
$ agent-device artifacts --json
3 entries: 6afe1281-… (trace-log), 70c69567-… (trace-log), fe6f4e6c-… (performance)

# t2 (separate client state, session s2)
$ agent-device connect proxy --daemon-base-url http://127.0.0.1:4377/agent-device --tenant t2 --run-id r2
$ agent-device artifacts --json
"artifacts": [], "message": "No daemon artifacts available."

# t2 downloads t1 artifact IDs (Node fetch, bearer token + x-agent-device-tenant: t2)
GET /agent-device/artifacts/70c69567-… tenant=t2 -> 401
{"ok":false,"error":"Artifact belongs to a different tenant","code":"UNAUTHORIZED","reason":"TENANT_OUTPUT_MISMATCH",...}
GET /agent-device/artifacts/70c69567-… tenant=t2 lease=<t1 lease> -> 401 TENANT_OUTPUT_MISMATCH
GET /agent-device/artifacts/fe6f4e6c-… tenant=t2 -> 401 TENANT_OUTPUT_MISMATCH
GET /agent-device/artifacts/fe6f4e6c-… tenant=t2 lease=<t1 lease> -> 401 TENANT_OUTPUT_MISMATCH
# control
GET /agent-device/artifacts/70c69567-… tenant=t1 lease=<t1 lease> -> 200 (593 bytes)

$ agent-device close; agent-device disconnect   # both clients; proxy and its daemon stopped

Notes:

  • AGENT_DEVICE_RETAIN_ARTIFACTS=1 keeps t1's downloaded artifacts in inventory, so the t2 check hits real entries. An earlier run without it (same head) also downloaded trace stop output for t1.
  • The trace CLI takes the output as a positional path (trace stop <path>); it has no --out.
  • Not run: perf memory snapshot --kind android-hprof. Settings is not debuggable (SecurityException: Process not debuggable), so the Perfetto perf trace start/stop --out pair covers the perf download.
  • scroll failed because the Android helper apk is not built in this checkout (unrelated). That is why the first trace log is empty.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of daf62a2

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

No open findings.

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

💬 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

thymikee commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Both refusal problems from the earlier review are fixed at daf62a2, and the live capture run is now posted. Two new problems remain in the upload fallback, so this is not ready yet.

A second independent pass found that a recoverable preflight error now ends the upload. A daemon auth hook can hit a transient dependency error during preflight and throw a typed COMMAND_FAILED reason. It reaches the client as an HTTP 500 REST body (http-authorization.ts, upload-http.ts, http-errors.ts). A proxy transfer timeout uses the same shape (daemon-proxy.ts). At 0.22 and 7af202e these fell back to POST /upload. At this head any string reason at that status makes preflight throw UploadRefusal, at both the first call and the renewed preflight. The rule: preflight refusal is terminal only for definitive authorization, scope or capacity reasons, and every other response reason keeps the legacy route. The set of reasons that stay terminal should come from one list that the daemon and client both use.

A second independent pass also found that an expired resumable ticket now aborts a recoverable install. The tenant is still authorized, but the ticket expires before the PUT arrives. For example, a client suspended between preflight and PUT for more than the five-minute idle TTL, inside its ten-minute budget. The daemon drops the entry (resumable-upload.ts) and answers the PUT with RESOURCE_EXPIRED as HTTP 404 (tenant-owned-entry.ts). Legacy POST needs no ticket (upload-http.ts). At this head the PUT catches rethrow UploadRefusal on the first and the retried PUT, and artifact preparation fails before the install RPC. Ticket-only failures such as UPLOAD_STATE_CORRUPT (resumable-upload-transfer.ts) change the same way. The rule: only definitive authorization, scope and capacity failures are terminal, and RESOURCE_EXPIRED and other recoverable ticket failures keep the existing fallback. A test that expires the ticket between preflight and PUT, then expects the install to finish through the legacy route, would prove it.

The open inline threads need no further change from the author. These do not apply at this head: wording only, as judged before; an unadmitted lease id proves nothing, so unleased is correct; the opener owns the script version and the same connection downloads it; one refusal for ownerless and foreign entries hides which entries exist; the remote-proxy.md upload limit is fixed at this head; cleanupInstallSources was verified at 7af202e and is unchanged. No lower-priority threads still apply.

No conflicts. The only check not passing is Body rules, which was cancelled; it lints the PR description and runs no test route, so it is likely unrelated, and the other 19 checks pass. Re-run Body rules after the fixes.

Not verified here: local test runs, because CI owns validation. The live capture run was read from the author comment and not reproduced. Hosted gateways that front preflight with their own typed REST bodies were not inspected, and would now end the upload instead of taking the legacy POST.

This branch has not been deployed

No deployments
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