Skip to content

Preserve cumulative Pi usage across executions with native session restoration - #16983

Merged
JaidenRatti merged 3 commits into
masterfrom
factory/pi-cumulative-usage-resume
Nov 30, 2026
Merged

JaidenRatti merged 3 commits into
masterfrom
factory/pi-cumulative-usage-resume

Conversation

@JaidenRatti

@JaidenRatti JaidenRatti commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Follow-up to #16821 and Kevin's accounting concern: Pi currently starts a fresh native session for a continued execution, so its latest usage snapshot replaces earlier spend instead of including it. The goal is to make successful continuations retain cumulative per-model/token-type counters, allowing the Factory web app to subtract the previous harness_metadata snapshot and apply public model prices to the delta. For example, 100 prior input tokens plus 40 new tokens must publish 140, not 40. This is important for accurate cost estimation!

Slight Open Question: mismatched cwds.

This revision rewrites the restored session header's cwd to the current run's working directory instead of failing on a mismatch (open to bringing the strict check back if the reviewer prefers) a la Codex. I initially rejected mismatched working directories a la how Claude Code works (i.e. the working directory changes across executions within the same conversation), but was running into issues locally.

  • Why the strict check broke locally: The oz-agent-worker direct backend creates a fresh temp workspace per execution (<workspace_root>/<task_id>-<execution_id>-...), so every follow-up execution runs in a different cwd and failed setup before Pi could start.
  • Why this can happen in prod: A run's harness_working_dir changes whenever its workspace root changes (including self-hosted direct-backend workers without a shared target_dir) or when the number of eager repo checkouts changes between executions.

Scope of the removed check: Only rehydrate_pi_transcript stops requiring the saved cwd to equal the current execution's cwd. The pre-existing cwd matching in transcript discovery (session_header, used by map lookup and directory scanning) stays intact. A relocated restore rewrites only the first-line header's cwd; it preserves the native UUID, other header fields and historical JSONL body, with the existing trailing-newline repair. Same-cwd restores retain their original bytes. The ACP map points to the current private transcript path and cwd.

Strict restore-time equality can be added back if we intentionally require a fixed workspace path, but it would reject legitimate relocations and prevent those continuations from starting. Historical absolute paths inside messages/tool results are not rewritten.

How

  • Restore the complete saved Pi JSONL into the run's private session directory, preserving prior usage records and native identity.
  • Register a new ACP session ID in pi-acp's session map, preserving unrelated entries, then use the existing capability-negotiated reopen flow (session/load for pi-acp). Shared replay suppression prevents duplicated UI history.
  • Reject invalid headers, mismatched working directories and malformed/unsupported maps; write each file atomically and repair a missing trailing newline.

This does not add pricing, a separate accounting ledger, or historical backfill. Missing transcripts, adapters without reopen support, or rejected reopen requests still take the existing fresh-session fallback; cumulative accounting is not guaranteed for those fallback executions. Previously overwritten usage cannot be reconstructed by this change.

Linked Issue

Original request/discussion: #16821. Created as a separate PR as requested; #16843, its branch, and QUALITY-2403 remain unchanged and are not superseded or closed.

Testing

  • 37 focused tests passed on the cwd-relocation revision: cargo nextest run -p warp --lib --no-default-features -E 'test(ai::agent_sdk::driver::harness::pi_transcript::tests) | test(ai::agent_sdk::driver::harness::acp::resume::tests) | test(ai::agent_sdk::driver::harness::acp::cli_transcript::tests)'. Includes cumulative per-model input/output/cache buckets after relocated restore+append, header/body and native-ID preservation, new-cwd discovery/old-cwd rejection, same-cwd byte preservation, map preservation, newline repair, invalid headers/maps and write failure.
  • Relocation regression proof: the new test fails against the prior production code with Invalid Pi session header or mismatched working directory; the revised code passes. The original eligibility regression also failed with the Pi Unsupported gate reinstated (Err(Unsupported) versus Ok(Pi)).
  • cargo clippy -p warp --lib --tests --no-default-features -- -D warnings passed on the cwd-relocation revision; ./script/format applied last.
  • Before the cwd-relocation revision, a credential-free Linux check using production restore/extractor code, real pi-acp@0.0.34, and @earendil-works/pi-coding-agent@1.6.0: session/load replayed the saved native answer; appending synthetic usage through native SessionManager preserved native identity and yielded 100→140 input, 10→14 output. No live provider turn, server publication, or desktop UI test. Changed-cwd adapter execution has not been exercised.
  • Compatibility observation: pairing pi-acp 0.0.34 with legacy Pi 0.73.1 stalled on the adapter's unsupported get_available_thinking_levels RPC; the successful check above uses a compatible runtime.
  • Windows verification could not start: environment Git clone failed with Access is denied (os error 5) before agent/test execution, including one retry. No Windows runtime result is claimed.

Agent Mode

  • Warp Agent Mode - This PR was created via Warp's AI Agent Mode

CHANGELOG-NONE

Rehydrate the complete native JSONL in the run's private Pi directory and register its pi-acp mapping before reopening the session. This keeps prior per-model usage in later snapshots so consumers can compute execution cost deltas instead of replacing earlier spend with a fresh session's counters.
@cla-bot cla-bot Bot added the cla-signed label Nov 24, 2026
@warp-agent-staging

Copy link
Copy Markdown
Contributor

This PR was generated with Warp, requested by @JaidenRatti.

Comment @warp-staging-factory on this PR to send it follow-up work.

View run View on Slack

@warp-agent-staging warp-agent-staging Bot added the factory:eng-factory-slim Label associated to the "eng-factory-slim" factory label Nov 24, 2026
@warp-agent-staging
warp-agent-staging Bot marked this pull request as ready for review November 24, 2026 23:23

@warp-agent-staging warp-agent-staging 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.

Overview

Restores Pi's native history before ACP reopening so successful continuations retain cumulative usage. Reviewed design, correctness, security, standards, complexity, naming, comments and test value; no material findings.

Verdict

Checks: Linux build/tests pass (36 focused tests), Clippy pass; real adapter load/native SDK append pass. Full CI is running after ready-for-review; the earlier draft-only aggregate failed because params were deliberately skipped. Windows helper setup failed before execution; visual proof n/a.

Found: 0 critical, 0 important, 0 suggestions, 0 nits. Approve the reviewed code; merge remains gated on CI and the human decision.

View in factory

Rebase the restored session header to the current execution cwd while preserving native identity and historical JSONL records. Keep cwd matching in transcript discovery and cover cumulative usage after relocation.

Co-authored-by: JaidenRatti <jaiden.ratti@warp.dev>

@warp-agent-staging warp-agent-staging 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.

Overview

Allows Pi restoration after workspace relocation by rebasing only the saved header cwd, preserving native identity and historical usage while retaining existing discovery safeguards. Re-read the complete published diff and all feedback surfaces against design, correctness, security, standards, complexity, naming, comments and test value; no material findings.

Verdict

Checks: Linux build/tests pass (37 focused tests; relocation regression failed before the fix), Clippy pass, formatter applied last; CI running across Linux/macOS/Windows, visual proof n/a. Changed-cwd adapter execution and live-provider/server publication remain unverified.

Found: 0 critical, 0 important, 0 suggestions, 0 nits. Approve this head; merge remains a human decision after required CI.

View in factory

Compare filesystem identity rather than OS-specific path spelling. The map stores a canonical path while directory fallback retains the temporary root spelling on macOS and Windows.

@warp-agent-staging warp-agent-staging 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.

Overview

The CI repair canonicalizes the discovered transcript path before comparison, preserving failure on missing/wrong discovery and old-cwd rejection. Re-read the full diff and feedback; design, correctness, security, standards, complexity, naming, comments and test value have no material findings.

Verdict

Checks: build/tests pass (37 focused tests with symlinked TMPDIR), Clippy pass, final formatter applied; new cross-platform CI pending, visual proof n/a. Prior macOS/Windows failures both identified this exact path-spelling assertion.

Found: 0 critical, 0 important, 0 suggestions, 0 nits. Approve reviewed code; required CI and human merge decision remain outstanding.

View in factory

@kevinyang372 kevinyang372 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Awesome work! This looks good to me

One thing we should do once this is on staging is to test this across different runner configs (e.g. windows, mac, linux, etc) to make sure there is no unexpected behavior when a session is restored. Mind owning that?

@warp-local-for-testing-only

Copy link
Copy Markdown

@kevinyang372, your GitHub account is not connected to Warp. Connect your GitHub account, then retry github-pr-review-submitted from eng-factory-slim.

@warp-agent-staging

Copy link
Copy Markdown
Contributor

@kevinyang372 I’ll check what’s needed to own the staging verification across Windows, macOS, and Linux, including runner access and any live-usage approval needed. No cross-runner staging test has been run yet.

View in factory

@warp-agent-staging

Copy link
Copy Markdown
Contributor

@kevinyang372 Yes, I can own the staging verification follow-up across Windows, macOS, and Linux: resume across separate executions, preserve session/context and cumulative usage without double counting, and cover changed workspace paths. I’ll report each runner’s results and gaps. Once deployed, I’ll need the build SHA, runner/workspace access, and approval with a spend limit for real provider turns; staging verification has not run yet.

PR #16983 now has green CI. Factory self-review was accepted, with current-head bot approval on 150209f3e66a181b5304137551073e094b29720f, plus your approval. No code changes were needed for this review. Shall we proceed with a human merge decision, or hold for anything else? I won’t merge it myself.

View in factory

@JaidenRatti
JaidenRatti merged commit c89fa40 into master Nov 30, 2026
79 of 96 checks passed
@JaidenRatti
JaidenRatti deleted the factory/pi-cumulative-usage-resume branch November 30, 2026 19:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla-signed factory:eng-factory-slim Label associated to the "eng-factory-slim" factory

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants