Skip to content

fix(background): publish task status files atomically so bg wait cannot see a torn file - #1357

Closed
ianalitis wants to merge 7 commits into
1jehuang:masterfrom
ianalitis:pr/background-status-atomic-writes
Closed

ianalitis wants to merge 7 commits into
1jehuang:masterfrom
ianalitis:pr/background-status-atomic-writes

Conversation

@ianalitis

@ianalitis ianalitis commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1350.

Problem

BackgroundTaskManager::status reads <task-id>.status.json and treats an unreadable file as "task missing", so wait returns None while the task is still running. Tasks rewrite that same file on progress and completion with a plain truncating write, so a reader can observe an empty file in the window between truncate and write.

Reproduced at the library level: one manager rewrites the status file 400 times while another reads it 400 times and asserts the task is still tracked. Before this change it failed 8 of 8 runs.

As a suite flake it made background::tests::adopted_output_is_readable_while_running_and_preserves_final_result fail 3 of 15 full jcode-base --lib runs at the default thread count, and a temporary diagnostic in read_status_file printed exactly one failure per failing run:

DIAG read_status_file parse len=0 path=.../035325k0o4.status.json
  err=EOF while parsing a value at line 1 column 0 head=""

Change

Publish status updates through a uniquely named sibling plus a rename, so a reader sees either the previous complete file or the new complete one:

fn write_status_file_atomic(path: &std::path::Path, contents: &str) -> std::io::Result<()> {
    static WRITE_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let sequence = WRITE_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let temp = path.with_extension(format!("tmp-{}-{sequence}", std::process::id()));
    std::fs::write(&temp, contents)?;
    std::fs::rename(&temp, path)
}

The spawn, adopt, completion, cancel, and reconciliation writes all route through it.

Edge cases: a failed publish can leave one uniquely named temp file behind, and both the reconcile sweep and bg cleanup key off the .json extension, so such a file is inert. Rename-over-existing works on Windows because Rust opens files with FILE_SHARE_DELETE.

Rework: interrupted initial publication

The first revision awaited the initial publication (acquire the status_updates gate, then a spawn_blocking rename) before tokio::spawn created the wrapper that owns the supplied handle or closure. Dropping the caller inside that await does not cancel the blocking write, so a Running document could land with no live task to finish it, and an adopted handle's output and completion were never recorded. That is the gap reported as a P1 review finding on this PR.

The initial publication is now synchronous (status_file::publish_initial_status) on the caller's thread, before the wrapper is spawned, so no .await can sit between the document becoming visible and registration. It does not take the status gate, because it must not join another task's slow write; that is safe while the task is unregistered and no other writer exists for its path. Progress and terminal writes keep the gate and the atomic rename.

Two tests in background::status_write_tests cover the window:

  • aborting_the_adopting_caller_still_records_the_adopted_work
  • aborting_the_spawning_caller_still_runs_the_spawned_work

Each holds the status gate (standing in for a slow concurrent write) plus the live map, asserts the caller parks with the document already visible and the work already owned, then drops the caller future and requires the adopted output, the spawned output, and the terminal Completed document. Restoring the awaited publication makes both fail at the first assertion (no status document was published).

Test

  • background::tests::status_reads_never_observe_a_partially_written_status_file runs the concurrent read/write loop.
  • background::status_write_tests::aborting_* cover the interrupted-publication windows.

Verification

cargo test -p jcode-base --lib -- background::status_write_tests::   # 13 passed
cargo test -p jcode-base --lib -- background::tests::                # 21 passed
cargo test -p jcode-tui --lib -- persisted_background_task           # passed
cargo fmt --all --check
cargo clippy -p jcode-base --all-targets -- -D warnings
scripts/check_guardrails.sh                                          # every gate green

(The warning-budget gate is the one exception on my local host, where rust-objcopy in toolchain 1.98.1 aborts on a missing libLLVM.dylib; it reports no warning from this change.)

A/B control in the same worktree: reverting only background.rs to origin/master while keeping the new test makes it fail in 0.01s (0 passed; 1 failed), and restoring the helper makes background::tests pass 21 of 21.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High impact] Safe to merge based on the reviewed changes. The previous task-tracking issue is addressed, and no blocking findings remain.

Summary

Status files now publish through a sibling temporary file and rename, so readers cannot see an empty or partly written update.

  • Status readers see complete task records during updates.
  • New tasks publish their first status before yielding.
  • Detached cancellation leaves room for updates during its grace period.

Reviews (7) · Last reviewed commit: "test(background): cover the aborted-call..." · Reviewed by Greptile

Comment thread crates/jcode-base/src/background.rs Resolved
@greptile-apps

This comment has been minimized.

Comment thread crates/jcode-base/src/background.rs Resolved
@ianalitis

Copy link
Copy Markdown
Contributor Author

The finding was right for the commit it reviewed, and I reproduced it: with 13612fd2f's write path (no await in the loop body, so no suspension point) and the atomic rename replaced by an in-place write, this test passes 8/8 without ever reading during a write.

dc4651417 is the commit that addresses it. Publication now runs on spawn_blocking, so each write suspends, and the same truncating-write control against the current head fails 8/8 on the default current-thread runtime with a concurrent status write made the task look missing. That was measured on a tree whose write_status_file, write_status_file_locked, publish_status_file and write_status_file_atomic are byte-identical to this branch's head, compared function by function.

The deterministic synchronization this asks for is in this PR already: background/status_write_tests.rs::staged_atomic_publication_exposes_only_complete_old_then_new_json installs a pre-rename hook, holds a publication after it has staged its temp file, reads the live path (old complete JSON) and the staged file (new complete JSON) while it is held, then resumes. It cannot pass vacuously either: with the same truncating-plus-inline control it fails closed in 3s with status write did not reach the pre-rename hook: timed out waiting on channel. It is one of six passing tests in that module.

I did not add synchronization to this loop test as well. A strengthened version exists on my integration line (multi-thread flavor, a writes > 1 overlap assertion, and a fails-closed check for an empty file), and under the old inline shape it is not deterministic either: 2/5 runs failed, 3/5 passed. It would be a third overlapping guard without making the property deterministic. Happy to port it if you would rather have the belt and braces.

@ianalitis

Copy link
Copy Markdown
Contributor Author

Friendly ping: the review finding is addressed at the current head (see my reply above), the branch is still mergeable against master, and the linked issue (#1350) still reproduces on 691c6f526. Happy to rebase or adjust if you'd like a different approach.

@ianalitis

Copy link
Copy Markdown
Contributor Author

@greptile review

`BackgroundTaskManager::status` reads `<task-id>.status.json` and treats an
unreadable file as "task missing", so `wait` returns `None` for a task that is
still running. Tasks rewrite that same file on progress and completion with a
plain truncating write, so a reader can observe an empty file in the window
between truncate and write.

Reproduced at the library level: one manager rewrites the status file 400 times
while another reads it 400 times and asserts the task is still tracked. Before
this change it failed 8 of 8 runs. As a suite flake it made
`background::tests::adopted_output_is_readable_while_running_and_preserves_final_result`
fail 3 of 15 full `jcode-base --lib` runs at the default thread count, and a
temporary diagnostic in `read_status_file` printed exactly one
`parse len=0 ... EOF while parsing a value` per failing run.

Publish updates through a uniquely named sibling plus a rename, so a reader sees
either the previous complete file or the new complete one. The spawn, adopt,
completion, cancel, and reconciliation writes all route through the helper.

A failed publish can leave one uniquely named temp file behind; the reconcile
sweep and `bg cleanup` both key off the `.json` extension, so such a file is
inert. Rename-over-existing works on Windows because Rust opens files with
`FILE_SHARE_DELETE`.

Verified: `background::tests` 21 passed with the change, including the new
regression; the same regression fails in 0.01s against the truncating write
(A/B control run in the same worktree).
…odules

`background.rs` is ratcheted at 1673 LOC and the atomic status write plus the
graceful-cancel path pushed it to 1885. Move both into sibling modules with no
behavior change:

- `background/status_file.rs` owns `write_status_file_atomic` and
  `publish_status_file`.
- `background/cancel_grace.rs` owns the TERM-to-KILL grace logic;
  `BackgroundTaskManager::cancel_with_grace` now delegates to it.

Verified with `cargo test -p jcode-base --lib -- background` (30 tests) and
`scripts/check_guardrails.sh --skip-slow` (code-size ratchet passes).
@ianalitis
ianalitis force-pushed the pr/background-status-atomic-writes branch from ee9c3d8 to e708daf Compare October 11, 2026 20:42
Comment thread crates/jcode-base/src/background.rs Resolved
Rework of the P1 raised on #1357 (closes #1350): the initial `Running`
document was published through an awaited write *before* the task was
registered. The caller is an agent turn that a server reload can abort at any
await, so an abort landing inside that write left a `Running` document that no
live task would ever finish, losing the adopted or spawned work's output and
completion.

Publish the initial document synchronously, on the caller's thread, and before
the wrapper that owns the task handle is spawned, so no await separates the
visible document from its owner:

- `status_file::publish_initial_status` writes atomically, never awaits, and
  skips the manager-wide gate: the task id is freshly generated, so no other
  writer can reach that path yet, and the initial document carries no progress
  history. Every later update still runs off-worker behind the gate.
- `spawn_with_notify`, `adopt_with_options`, and `register_detached_task` use
  it; the now test-only `write_status_file` wrapper is marked `#[cfg(test)]`.

Tests in `crates/jcode-base/src/background/status_write_tests.rs`:

- `initial_publication_ignores_a_held_status_gate` holds the gate and asserts
  the document is still visible.
- `spawning_background_work_publishes_its_status_document_before_yielding` and
  `adopting_a_running_tool_publishes_its_status_document_before_yielding` poll
  the call site once and assert the document already exists.
- `registering_a_detached_task_publishes_its_status_document_before_yielding`
  registers under a held gate, asserting `Poll::Ready` plus the `detached` and
  `pid` fields.

Verified: `cargo test -p jcode-base --lib -- background` (34 tests) and
`scripts/check_guardrails.sh`, whose only failure is the pre-existing local
warning-budget gate from a broken toolchain `rust-objcopy`.
Greptile's P1 (comment 4243186337) measured the abort as "the caller stops
while the `Running` document is already visible". Two tests now pin that
window for both registration paths, and both fail against the awaited
publication they replace.

`aborting_the_adopting_caller_still_records_the_adopted_work` and
`aborting_the_spawning_caller_still_runs_the_spawned_work` hold the status
gate (another task's slow write) and the live map, then drop the caller
future once it is parked. The caller is only ever parked after the document
exists and after the wrapper that owns the work exists, so the adopted
output, the spawned output, and the terminal `Completed` document still land
even though the aborted caller never returned a task id. Under the awaited
publication both tests fail at the first assertion: the caller parks inside
the write, no document is published, and the work is never registered.

The existing held-gate tests still own the discriminating assertion for the
detached path, where registration is synchronous.
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
The status index already replaces status files atomically. Register spawn and adopt workers before awaiting publication so a disconnected caller cannot leave an unowned Running status.

Upstream: 1jehuang#1357

Co-authored-by: Iraklis Analitis <[email protected]>
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Upstream-PR: 1jehuang#1357
Upstream-PR-Commit: 1jehuang#1357 0da5e81
Upstream-PR: 1jehuang#1362
Upstream-PR-Commit: 1jehuang#1362 5962058
Upstream-PR: 1jehuang#1486
Upstream-PR-Commit: 1jehuang#1486 fadc624
Upstream-PR: 1jehuang#1733
Upstream-PR-Commit: 1jehuang#1733 01f3415
Upstream-PR: 1jehuang#1750
Upstream-PR-Commit: 1jehuang#1750 1ac0c82
Upstream-PR: 1jehuang#1822
Upstream-PR-Commit: 1jehuang#1822 73f85fc
Upstream-PR: 1jehuang#1912
Upstream-PR-Commit: 1jehuang#1912 36d7682
Upstream-PR: 1jehuang#1978
Upstream-PR-Commit: 1jehuang#1978 0f55643
Upstream-PR: 1jehuang#2007
Upstream-PR-Commit: 1jehuang#2007 638f87c
Upstream-PR: 1jehuang#2213
Upstream-PR-Commit: 1jehuang#2213 c5e1487
Upstream-PR: 1jehuang#2234
Upstream-PR-Commit: 1jehuang#2234 0d4d5d4
Upstream-PR: 1jehuang#2266
Upstream-PR-Commit: 1jehuang#2266 217ddc2
Upstream-PR: 1jehuang#2267
Upstream-PR-Commit: 1jehuang#2267 e98c40b
@ianalitis ianalitis closed this by deleting the head repository Nov 26, 2026
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.

bg wait can report a running task as missing while its status file is rewritten

1 participant