Skip to content

fix(core): refuse a second writer on a session file with an advisory lock - #488

Merged
ajianaz merged 2 commits into
developfrom
fix/session-writer-lock
Nov 3, 2026
Merged

ajianaz merged 2 commits into
developfrom
fix/session-writer-lock

Conversation

@ajianaz

@ajianaz ajianaz commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

What (description of the change)

A writable JsonlStorage now takes an exclusive advisory lock on a sidecar file <id>.jsonl.lock for the lifetime of the handle. A second process opening the same session for writing is refused with session is open for writing by pid N. Details:

  • The lock lives on a sidecar that is never renamed, so it survives compact() (which renames a new file over the live path and would drop a lock held on the old inode).
  • It is taken before the torn-tail repair in open_with, so a refused open never truncates a line another process is still appending.
  • open_read_only stays lock-free (status, sessions keep working while a writer holds the lock).
  • Belt and braces: before each append one fstat compares the file length with the last known good length and returns StorageError::StaleHandle instead of appending to a file that changed under the handle.
  • The OS releases the lock on crash or SIGKILL, so the existing crash-resume paths are unchanged.
  • docs/architecture.md section 9 now says the CAS only protects against double-drive inside one process. CHANGELOG entry under [Unreleased].

Why (the problem you're solving)

Closes #475. The only write guard was the in-memory expected_seq CAS, so two processes could append to the same session file. Live repro from the issue: chat --resume A, resume from B, then A writes again gives duplicated seq 11-15 and an unreadable session (corrupt session file: line 11: seq 11 not strictly increasing).

Testing (how you verified this works)

  • RED: the new core tests did not compile before the change (StorageError::Locked / StaleHandle did not exist). For the CLI end-to-end test I reverted storage.rs to the origin/develop version and ran it: second_process_is_refused_and_the_file_stays_valid FAILED at assert!(!o.status.success()) (the second writer was accepted), then restored the fix.
  • New tests: crates/tole-core/tests/writer_lock.rs (5: second process refused with the holder pid and file untouched, open_read_only works, reopen after SIGKILL, lock still held after compact(), refused open does not truncate a torn tail and repair runs once the lock is free, stale handle refuses to append) and crates/tole-cli/tests/writer_lock_e2e.rs (1: the issue repro with the real binary and a mock provider; status and sessions succeed meanwhile, no duplicate seq, session resumes after A exits).
  • cargo fmt --all -- --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test --workspace, cargo test -p tole-core --no-default-features and cargo build -p tole-cli --no-default-features: all pass (run on a clean target dir).
  • Five existing tests assumed several live writable handles on one session, which the lock now correctly refuses, so they were adjusted: the mission.rs unit test, perf_threshold.rs, acp_handshake.rs, acp_config_options.rs (drop the first handle before the second opens) and acp_session_cancel.rs (match only .jsonl files, since the .lock sidecar contains the session id).
  • Not verified: the Android/iOS cross-compile (relies on File::try_lock, stable since 1.89; the CI cross-compile jobs are the check), and a test for the issue's serve/ACP/MCP acceptance item (CLI resume against a daemon-held session); the two-process tests cover the shared lock path.
  • Local cora review --diff-file was unavailable at the time (the LLM backend returned empty responses, including for a diff that passed earlier), so there is no local verdict; the CI Cora Review job is the check.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

🔍 Cora AI Code Review

✅ No issues found. Code looks good!


Review powered by cora-code · BYOK · MIT

@ajianaz
ajianaz force-pushed the fix/session-writer-lock branch from 014dcd9 to 21187eb Compare November 3, 2026 03:40
@ajianaz
ajianaz merged commit adc9dac into develop Nov 3, 2026
16 checks passed
@ajianaz
ajianaz deleted the fix/session-writer-lock branch November 3, 2026 03:50
ajianaz added a commit that referenced this pull request Nov 3, 2026
…l step (#495)

## What (description of the change)
A model step now costs exactly 2 `fdatasync` calls (read-only and Write
tools alike; final answer 1) instead of ~4.8. `Commit` gains
`defer_sync()`: the line is written and flushed but its `sync_data` is
skipped, and the next durable commit's `fdatasync` persists it too
(fdatasync covers every earlier byte of the file). The turn loop defers
the usage row, the `Planning → ToolCall` hop, `wrote_this_turn` and the
tool settlement (`settle_ok_deferred`, crate-private); every one of them
is always followed by a durable commit before an effect runs, the next
provider call starts, or the turn returns. The intent commit (`begin`),
`finish`, the final answer and every error/settle-error path stay
durable. `settle_ok` public form is unchanged. `docs/architecture.md`
documents the sync contract. New measurement harness
`crates/tole-core/tests/fsync_budget.rs` counts actual `sync_data` calls
through a `#[doc(hidden)] JsonlStorage::sync_count()` and re-opens the
file read-only to prove disk matches memory after a turn. CHANGELOG
under [Unreleased].

## Why (the problem you're solving)
Closes #483. The issue measured ~4.8 fsync per model step (strace,
aarch64) because the turn loop issues ~5 commits per tool step (usage,
ToolCall hop, intent, settlement, finish) and each synced. The design
decision here is Option 1's intent without changing the on-disk format:
merging transitions into one commit would need a format change, so the
syncs are deferred instead — one line per commit, same bytes, fewer
waits.

## Testing (how you verified this works)
- RED harness first: on develop the harness measures **4.82** syncs per
read-only model step (5.73 with a Write tool) — matching the issue's
strace number without strace.
- GREEN: **2.00 / 2.00** (final answer 1); disk-vs-memory check passes
(read-only reopen shows the same entries, state and usage rows).
- All durability invariants hold unchanged: crash-resume golden, SIGKILL
E2E, torn-tail repair, poison-on-failed-append, compact() clearing, and
the #488 writer-lock tests all pass inside `cargo test --workspace
--no-fail-fast` (933 passed / 0 failed).
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets
-- -D warnings`, `cargo test -p tole-core --no-default-features` (362
passed / 0 failed), `cargo build -p tole-cli --no-default-features`: all
pass. cora pre-commit gave a real verdict: "No issues found".
- Power-loss behaviour is reasoned and documented (a lost in-flight
step's deferred lines leave the same pending-intent states a crash
inside the effect window already produces; SIGKILL loses nothing) — not
tested with real power cuts. Wall-clock is not re-benchmarked (sync
counts only; the issue's 25-step wall figure came from a different
host). Real-provider commit mix may differ slightly from the mock (4.82
was with usage reported).

Co-authored-by: ajianaz <[email protected]>
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.

storage: no cross-process writer exclusion — a second writer corrupts the session file (live repro)

1 participant