diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..7a681735 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +* text=auto eol=lf +*.png binary +*.jpg binary +*.gif binary +*.ico binary +*.webp binary diff --git a/docs/studio/behaviour/storage.md b/docs/studio/behaviour/storage.md index dc1fd1e4..265bae12 100644 --- a/docs/studio/behaviour/storage.md +++ b/docs/studio/behaviour/storage.md @@ -20,6 +20,8 @@ The data folder was `~/Library/Application Support/dev.falinks.studio/` before p The hooks are async, so Claude Code never waits for them, and they append whether the app runs or not. Two events that fire within a few milliseconds can land in either order. +`events.lock` beside the log is the log's lock (#811). Every writer of `events.jsonl` holds `events.lock` while it writes: the hook, the answer hook, and the app's own lines (`StudioRename`, `StudioDelete`, `StudioPromptName`, a `SessionEnd` with reason `process_gone`). It takes the lock before it opens the log, and writes its lines in one write, so two writers never interleave their lines. A prune swaps the new log in only while holding it, so a writer always opens the log the last prune left. Readers take no lock, and nothing locks `events.jsonl` itself. A hook waits up to 5 seconds for the lock (a Codex or Cursor line 1 second) and otherwise drops its event to `drops.txt` beside the log; the app and a prune wait up to 60 seconds. The lock file is made on first use, so a data folder from before it needs no step, and its bytes mean nothing: it is never written, read, truncated, replaced or deleted. + The log holds tool inputs and results: commands and their output, errors, exit codes, the text an edit replaced and its hunks, and a written file's content. It leaves out two fields no reader takes (danielrispler/plotkeeper#132): an Edit's or Write's `originalFile`, the whole file before the change, and a Read's file `content`. It keeps a session's events for 30 days after its last one. At each start, before the replay, the app moves the events of older sessions to `events-archive.jsonl` beside it, and drops the two fields from the lines it keeps; a prune moves lines, so it also removes `studio-state.json`, the state a replay made, which the next start saves again and later starts resume from, replaying only the log's tail. Each session in it keeps its `project`, its project folder (spec #659): the root of the first folder it got, set once and never changed by later events. It has a default, so a previous build reads the file and skips it as an unknown key; a session saved before it existed takes it from its saved folder when the file is read, a task's worktree's main checkout, so it keeps the project it showed. The app never reads the archive, and never deletes it; their turns stay in the card store. diff --git a/docs/studio/development.md b/docs/studio/development.md index 90b59b61..2bf14648 100644 --- a/docs/studio/development.md +++ b/docs/studio/development.md @@ -33,7 +33,7 @@ - `core/tests/blocked_commands.rs`: blocked commands replayed through the core: the command's fields, block order, a subagent's block, needs you until the session moves on (the agent's next call, Daniel's next prompt, a subagent's end, not the turn's end), which blocks count as waiting, and an older log's Allow, Decline, decision and retry. - `hook/tests/named_roots.rs`: the hook binary in a scratch `HOME` and a temporary repository with a second worktree: the roots a Bash call names and touches, the deepest root on a path boundary, a worktree an earlier command made, a removed worktree's folder (by path or as the event's folder) touching nothing, a new folder in a listed one touching it, a known root not listed again, and a worktree made mid-turn starting from its creation commit; - `hook/tests/harness_trees.rs`: the hook binary in a scratch `HOME` and a temporary repository fed wave 1's trial lines of a Codex and a Cursor turn and a real OpenCode turn, each recording its worktree's start and end trees, which differ by the file it changed; OpenCode turns whose hooks run at once and out of order, their appends waiting on the log's lock together, each listing their own edit once the core replays the log; a Cursor turn writing in its second workspace root listing the file, a Cursor prompt starting every workspace root but touching only its folder's, a Cursor `Shell` call touching the folder its input names, a Cursor line logged in time while `git` hangs, and a Cursor prompt's trees given up past the budget leaving the worktree's start to the turn's next touch; -- `hook/tests/agents.rs`: the agent a hook entry names stored on the line, and another harness's payload dropped by the Claude entry and recorded once by its own; `hook/tests/names.rs`: every name a user sees says plotkeeper; `hook/tests/prune.rs`: the two heavy fields left out and the ended sessions' archive, each session's lines kept together by its agent's own id; +- `hook/tests/agents.rs`: the agent a hook entry names stored on the line, and another harness's payload dropped by the Claude entry and recorded once by its own; `hook/tests/names.rs`: every name a user sees says plotkeeper; `hook/tests/prune.rs`: the two heavy fields left out and the ended sessions' archive, each session's lines kept together by its agent's own id, and the log's lock, `events.lock` (a line waiting through a swap landing in the new log, a held lock leaving the log readable and an append waiting or giving up, whole lines from threads at once, the lock file made on first use, a prune's tail copy, and no file but the log code naming the log and opening a file to write); - `server/tests/runner.rs`: the background runner with a fake harness that is a real child process, a shell script run through the real launcher: a run's result, cost, exit and record, denials in a 0 exit, a failed run's prompt, a refused run (no harness, no `checks`), `checks` and `setup` read for each run, one run at a time per project, a run picked up after a restart, a dead run failed live and at a start, Cancel killing the group and removing the folder and refusing a process whose start time differs, Cancel of a run that ends at that moment, the pause on a login or limit failure and Resume, the time limit, the cores, an orphaned folder, a running run a start cannot read left alone, a queued run never started beside a running one, a refusal that removes nothing but a new run's folder, a finished run's stray children stopped, standard input closed and the command's removed variables, a pause told to every project, the page's two commands, and the `claude` command, sandbox block and allow list as built, never run; - `server/tests/back_a_law.rs`: Back a law end to end against a temporary repository with a bare `origin`, a fake agent run by the real launcher, a fake `srt` that runs its command as it is and a recorded `gh`: the clone of the default branch with no remote, a well-formed run proven and kept with Daniel's repository untouched byte for byte, each rejection (no test patch, a test patch outside its scope, a plant that edits the test or breaks the build, a red run that does not name the new test, a test that fails alone, a law left on trust), Discard, the prompt's text, a missing `srt` copying the prompt, a proof with no home folder or with a settings file that cannot be written rejected before `srt` starts, Dismiss refused while the proof runs, a proof plotkeeper stopped in rejected at the next start, Open draft PR from a temporary worktree (its branch, body and ratify record), a retry after `gh` failed past the push, Daniel's other worktrees left alone, an out-of-date patch, and the new-law variant (the writer's draft, the confirmed sentence alone in the prompt, its proof and PR); - `server/tests/micro_worlds.rs`: micro-worlds with the real launcher, a fake harness that writes the page and the fake dsh-visual (`tests/fake-dsh-visual/`): a flow's topic, a checked page stored and served with its policy first, a failing page never served, rewritten once and then falling back to the prompt to copy, no run without `microWorlds.dshVisual`, out of date and Rebuild, Dismiss refused while the host check runs, a check plotkeeper stopped in failing with why at the next start, and a folder of its own for each project; @@ -41,7 +41,7 @@ - `server/tests/map_draft.rs`: First map's drafting through the real launcher, a stub `claude` that answers canned JSON and a recorded `gh`, on `studio-test-support`'s repositories: the groups landing in order and each reviewer reading its group alone, a failed group (no JSON, a reviewer that cannot start, a purpose without a verdict, one answered twice) kept apart and retried alone, Redraft this part with its flag, Discard mid-batch and a Discard refused half way, a limit pausing the queues, a restart mid-batch, Accept's Write and its refusals and replace question, Open a draft PR from a temporary worktree, muted, and pressed again after it stopped short, and the pending PR followed merged, closed or open; `server/tests/map_check.rs`: `plotkeeper map check` printing what `system-map check` prints, with its exit codes, and `map scan`; - `server/tests/install.rs`: `plotkeeper install` and `uninstall` on a temporary home with stand-in `claude`, `agy`, `codex` and `copilot`: every file byte-identical after both, Claude Code's settings file never opened, each harness's hooks naming the data folder's `bin/`, Codex's and Cursor's hook files edited beside the user's own hooks, `~/.zshrc` with only its removed lines kept, and an uninstall that retries only its failed steps; `server/tests/hook_copies.rs`: the hook binaries' copies made, left when equal, replaced by rename when they differ, and kept when a binary is missing; `server/tests/api_key.rs`: the API keys saved, replaced and removed through a key store in memory, never reaching the page or the log; `understanding/tests/http_writer.rs`: the API-key writers against a local fake HTTP server, the request's shape and each error status's failure kind; - `hook/tests/answer.rs`: the answer hook's contract (Seam 4), including a blocked command's denial returned at once with no decision, a payload on stdin and the studio played by the test in a scratch `HOME`: an answer's `allow` with the questions and each label, a multi-select's joined; an approved plan's `allow` with its input and a rejected one's `deny`; a permission's `allow` or `deny`; each card answer logged as `StudioAnswer`, a terminal one not; for questions, plans and permissions alike, an immediate return with no decision when nobody watches, another session is watched, the studio's pid is dead or its heartbeat old; no decision at the timeout or for "Answer in the terminal"; a wrong nonce or an answer file others may write refused; -- the unit tests of the event log's path and of the turn the shell's `StudioInterrupted` line ends, its own and never a later one (`hook`), of what `scrub` keeps (`studio-core`), of the weekly rates' dates (`understanding`), of the shell's risk-note log lines, which keep no reply and no command, and of a worker's view joining its session's risk notes and asks and of the cards key changing with a second card of a judged command (`server/src/lib.rs`) and of the settings file's reads (`server/src/settings.rs`: the writer, `briefBackfill.hours` and its older name `catchUp.hours`, `prBriefs.model`, Opus unless it says another, `prBriefs.effort`, low unless it names another claude takes or `default`, and a background run's `backgroundRuns`, `checks` and `setup`, its project's own with no default) and of the settings' write: a comment and a trailing comma beside the edited key kept byte for byte, a value replaced, a missing parent inserted, reset removing the key, a text that does not parse or a file that changed refused and left as it was, a missing file created, the file replaced whole with nothing left beside it, and a symbolic link written through and kept. and of the PR briefs (`server/src/prs.rs`: which PRs are ready from the sessions' branches and the repository's open list, a failed lookup keeping what was known; `pr_briefs.rs`: the write once per head, stale on a new head, no lock held across a write, a failed head not retried, what waits for Daniel and what a chapter lights, and which ready PRs the start writes, at most 3, the newest head first within `briefBackfill.hours`; `part_catch_ups.rs`: which fogged part gets a part catch-up and which opens its one PR's chapter, completion clearing the part's fog and completing no brief, a stored catch-up read only for the fog list it covers, and, with a fake writer, a shown map writing at most 8 fogged Core parts' catch-ups oldest fog first and none of the others, a part that is not Core written on click, the catch-up's state carrying the stage as each call starts, a new fog entry rewriting it on the next show and an unchanged one never, and two shows in a row starting one write; `ratify.rs`: the decisions file read and written back whole, what has landed; `fog.rs`: reads and the fog a push after reading files; `history.rs`: a PR's files for the drawer). +- the unit tests of the event log's path and of the turn the shell's `StudioInterrupted` line ends, its own and never a later one (`hook`), of what `scrub` keeps (`studio-core`), of the weekly rates' dates (`understanding`), of the shell's risk-note log lines, which keep no reply and no command, and of a worker's view joining its session's risk notes and asks and of the cards key changing with a second card of a judged command and of the server's own lines waiting for the log's lock, then landing whole (`server/src/lib.rs`) and of the settings file's reads (`server/src/settings.rs`: the writer, `briefBackfill.hours` and its older name `catchUp.hours`, `prBriefs.model`, Opus unless it says another, `prBriefs.effort`, low unless it names another claude takes or `default`, and a background run's `backgroundRuns`, `checks` and `setup`, its project's own with no default) and of the settings' write: a comment and a trailing comma beside the edited key kept byte for byte, a value replaced, a missing parent inserted, reset removing the key, a text that does not parse or a file that changed refused and left as it was, a missing file created, the file replaced whole with nothing left beside it, and a symbolic link written through and kept. and of the PR briefs (`server/src/prs.rs`: which PRs are ready from the sessions' branches and the repository's open list, a failed lookup keeping what was known; `pr_briefs.rs`: the write once per head, stale on a new head, no lock held across a write, a failed head not retried, what waits for Daniel and what a chapter lights, and which ready PRs the start writes, at most 3, the newest head first within `briefBackfill.hours`; `part_catch_ups.rs`: which fogged part gets a part catch-up and which opens its one PR's chapter, completion clearing the part's fog and completing no brief, a stored catch-up read only for the fog list it covers, and, with a fake writer, a shown map writing at most 8 fogged Core parts' catch-ups oldest fog first and none of the others, a part that is not Core written on click, the catch-up's state carrying the stage as each call starts, a new fog entry rewriting it on the next show and an unchanged one never, and two shows in a row starting one write; `ratify.rs`: the decisions file read and written back whole, what has landed; `fog.rs`: reads and the fog a push after reading files; `history.rs`: a PR's files for the drawer). Each crate's integration tests are one test binary, `it`: its `Cargo.toml` sets `autotests = false`, and `tests/main.rs` declares each `tests/*.rs` file as a module, so a new test file needs a `mod` line there. Helpers the files share live in `tests/common.rs`; the git helpers that `hook`, `understanding` and `workbench` share (an isolated `git`, a one-commit repository, also in a folder the test names, a bare `origin`) and the `LauncherGuard` that `server`'s tests hold to stop the `plotkeeper-run` launchers a test leaves running live in the `studio-test-support` crate (`test-support/`), a dev-dependency that depends on no workspace crate. The fake writers of `understanding/tests` are `Scripted` in its `common.rs`. In `ui/tests/`, `dom.mjs` holds the fake document (`fakeDocument`) and the `invoke` stub (`tauri`). diff --git a/hook/src/answer.rs b/hook/src/answer.rs index 57c6a2bb..82fd8232 100644 --- a/hook/src/answer.rs +++ b/hook/src/answer.rs @@ -209,7 +209,7 @@ pub fn answered_line(payload: &Value, answer: &Value) -> Value { /// Appends a `StudioAnswer` line to the event log and says whether it got there; the decision stands /// even if it cannot be logged. pub fn log_answer(data: &Path, line: &Value) -> bool { - match crate::append(&data.join("events.jsonl"), line, crate::PATIENCE) { + match crate::append(&crate::event_log_in(data), line, crate::PATIENCE) { Ok(true) => true, Ok(false) => { eprintln!("plotkeeper-answer: log the answer: the log stayed locked"); diff --git a/hook/src/lib.rs b/hook/src/lib.rs index eedb17b3..2aa27393 100644 --- a/hook/src/lib.rs +++ b/hook/src/lib.rs @@ -90,7 +90,12 @@ pub const HOOK_BINARIES: [&str; 2] = ["plotkeeper-hook", "plotkeeper-answer"]; /// The log in the studio's data directory. The hook writes it; the app reads it. pub fn event_log(home: &Path) -> PathBuf { - data_dir(home).join(EVENT_LOG) + event_log_in(&data_dir(home)) +} + +/// The log in the data folder `data`. +pub fn event_log_in(data: &Path) -> PathBuf { + data.join(EVENT_LOG) } /// The event log's name in the data folder. @@ -105,7 +110,14 @@ pub fn drops_file(log: &Path) -> PathBuf { log.with_file_name("drops.txt") } -/// Appends `event` to the log at `log` as one line, with one write under an exclusive lock, so hooks +/// The event log's lock beside the log `log`, `events.lock`, which every writer of the log holds while it writes and a +/// prune holds while it puts a new log in the old one's place. Its bytes mean nothing: it is never written, read, +/// truncated, replaced or deleted, and no reader takes it, so the log itself is never locked. +pub fn lock_file(log: &Path) -> PathBuf { + log.with_file_name("events.lock") +} + +/// Appends `event` to the log at `log` as one line, with one write under the log's lock, so hooks /// that fire together never interleave their lines. Waits up to `patience` for the lock; returns /// `false`, having written nothing, when it never came. pub fn append(log: &Path, event: &serde_json::Value, patience: Duration) -> std::io::Result { @@ -119,27 +131,53 @@ pub fn append(log: &Path, event: &serde_json::Value, patience: Duration) -> std: Ok(true) } -/// The log at `log`, open to append under its exclusive lock, which it waits up to `patience` for; -/// `None` when the lock never came. A prune puts a new file in the log's place while it holds the -/// lock (danielrispler/plotkeeper#132), so a file replaced while this waited is let go for the new one. -pub fn locked(log: &Path, patience: Duration) -> std::io::Result> { - use std::{fs::TryLockError, os::unix::fs::MetadataExt}; +/// The log open to append, under the log's lock; dropping it closes the log and lets the lock go. +pub struct Locked { + log: fs::File, + _lock: fs::File, +} + +impl std::io::Write for Locked { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.log.write(bytes) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.log.flush() + } +} + +/// The log at `log`, open to append under the log's lock, which it waits up to `patience` for; +/// `None` when the lock never came. A prune puts a new file in the log's place only while it holds +/// the lock (danielrispler/plotkeeper#132), and the log is opened after the lock is taken, so it is +/// always the one the last prune left. +pub fn locked(log: &Path, patience: Duration) -> std::io::Result> { + let Some(lock) = hold(log, patience)? else { + return Ok(None); + }; + let log = fs::OpenOptions::new().create(true).append(true).open(log)?; + Ok(Some(Locked { log, _lock: lock })) +} + +/// The lock beside the log `log`, created if missing and locked exclusively, which it waits up to +/// `patience` for; `None` when it never came. +fn hold(log: &Path, patience: Duration) -> std::io::Result> { + use std::fs::TryLockError; let deadline = Instant::now() + patience; + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(lock_file(log))?; loop { - let file = fs::OpenOptions::new().create(true).append(true).open(log)?; - loop { - match file.try_lock() { - Ok(()) => break, - Err(TryLockError::WouldBlock) if Instant::now() < deadline => { - thread::sleep(Duration::from_millis(20)); - } - Err(TryLockError::WouldBlock) => return Ok(None), - Err(TryLockError::Error(e)) => return Err(e), + match lock.try_lock() { + Ok(()) => return Ok(Some(lock)), + Err(TryLockError::WouldBlock) if Instant::now() < deadline => { + thread::sleep(Duration::from_millis(20)); } - } - let ours = file.metadata().map(|m| (m.dev(), m.ino()))?; - if fs::metadata(log).is_ok_and(|m| (m.dev(), m.ino()) == ours) { - return Ok(Some(file)); + Err(TryLockError::WouldBlock) => return Ok(None), + Err(TryLockError::Error(e)) => return Err(e), } } } @@ -226,12 +264,11 @@ impl Stamp { /// before `now`, in Unix milliseconds, and lightens the lines it keeps (danielrispler/plotkeeper#132). /// A line of no session goes by its own time; a line with no time stays. A log whose first line is /// recent is left as it is, so most launches read one line. The new log takes the old one's place -/// under its lock, with the lines hooks appended meanwhile. +/// under the log's lock, with the lines hooks appended meanwhile. pub fn prune(log: &Path, now: u64) -> std::io::Result { use std::{ collections::HashMap, io::{self, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write}, - os::unix::fs::MetadataExt, }; let cutoff = now.saturating_sub(KEEP.as_millis() as u64); let file = match fs::File::open(log) { @@ -303,9 +340,10 @@ pub fn prune(log: &Path, now: u64) -> std::io::Result { archive.write_all(&archived)?; archive.sync_all()?; } - let held = locked(log, Duration::from_secs(60))?.ok_or(io::ErrorKind::TimedOut)?; - let read = file.metadata().map(|m| (m.dev(), m.ino()))?; - if held.metadata().map(|m| (m.dev(), m.ino()))? != read { + let held = hold(log, Duration::from_secs(60))?.ok_or(io::ErrorKind::TimedOut)?; + // Writers only append, so a log shorter than the bytes read was replaced, which only another prune + // could do. + if fs::metadata(log)?.len() < end { fs::remove_file(&next)?; return Err(io::Error::other("the log was replaced during the prune")); } diff --git a/hook/src/main.rs b/hook/src/main.rs index 4bec2ec0..2cca83fd 100644 --- a/hook/src/main.rs +++ b/hook/src/main.rs @@ -84,7 +84,7 @@ fn append() -> Result<(), Box> { } event.insert("studio_received_ms".into(), received_ms.into()); let home = env::home_dir().ok_or("no home directory")?; - let path = studio_hook::hook_data_dir(&home).join(studio_hook::EVENT_LOG); + let path = studio_hook::event_log_in(&studio_hook::hook_data_dir(&home)); let data = path.parent().ok_or("no data directory")?; fs::create_dir_all(data)?; // The line goes in the log even when the trees cannot be recorded. diff --git a/hook/tests/common.rs b/hook/tests/common.rs index ebf84b37..ab356194 100644 --- a/hook/tests/common.rs +++ b/hook/tests/common.rs @@ -1,4 +1,4 @@ -//! What the hook's tests share: a scratch `HOME`, and the hook binaries run on a payload. +//! What the hook's tests share: a scratch `HOME`, the hook binaries run on a payload, and the event log's lock held. use std::{ fs, io::Write, @@ -50,3 +50,10 @@ pub(crate) fn feed(mut cmd: Command, payload: &serde_json::Value) -> Child { .unwrap(); child } + +/// Holds the event log's lock as another writer would, with the log open to append, until dropped. +pub(crate) fn hold(log: &Path) -> studio_hook::Locked { + studio_hook::locked(log, std::time::Duration::from_secs(1)) + .unwrap() + .expect("the log's lock is free") +} diff --git a/hook/tests/deadline.rs b/hook/tests/deadline.rs index aa701379..d6ae6414 100644 --- a/hook/tests/deadline.rs +++ b/hook/tests/deadline.rs @@ -1,6 +1,6 @@ // Seam 4 (#43): the hook's deadline. The binary runs with a scratch `HOME`; the test holds the -// event log's lock, as a stuck hook would. -use crate::common::{feed, hook as hook_command, scratch as scratch_home}; +// event log's lock, `events.lock`, as a stuck hook would. +use crate::common::{feed, hold, hook as hook_command, scratch as scratch_home}; use std::{ fs, path::{Path, PathBuf}, @@ -30,18 +30,19 @@ fn event() -> serde_json::Value { serde_json::json!({ "session_id": "s-1", "hook_event_name": "PostToolUse", "cwd": "/" }) } +// @law: log-writers-hold-the-log-lock #[test] fn a_held_lock_gives_a_drops_line_and_no_log_line_once_its_patience_runs_out() { let home = scratch("held"); let log = studio_hook::event_log(&home); - let held = fs::File::create(&log).unwrap(); - held.lock().unwrap(); + let held = hold(&log); let took = hook(&home, 200, event()); + drop(held); assert!(took >= Duration::from_millis(200), "took {took:?}"); assert!(took < Duration::from_secs(3), "took {took:?}"); - assert_eq!(fs::read_to_string(&log).unwrap(), ""); + assert_eq!(fs::read_to_string(&log).unwrap_or_default(), ""); let drops = fs::read_to_string(studio_hook::drops_file(&log)).unwrap(); let fields: Vec<&str> = drops.trim_end().split(' ').collect(); assert_eq!(drops.lines().count(), 1); diff --git a/hook/tests/harness_trees.rs b/hook/tests/harness_trees.rs index 974e8bc7..560a66f9 100644 --- a/hook/tests/harness_trees.rs +++ b/hook/tests/harness_trees.rs @@ -4,7 +4,7 @@ // the lines of a real OpenCode turn that wrote `hello.txt` (#717; the first turn of // `core/tests/fixtures/opencode/run.jsonl`, in `/Users/me/work/hello`). Each harness's turn records // the start and end trees of the worktree it worked in, as Claude Code's does. -use crate::common::{feed, hook}; +use crate::common::{feed, hold, hook}; use serde_json::Value; use std::{fs, path::Path, time::Duration}; use studio_test_support::git; @@ -323,8 +323,7 @@ fn a_cursor_prompts_late_trees_leave_the_worktrees_start_to_its_next_touch() { // Another hook holds the log's lock meanwhile. let log = studio_hook::event_log(&home); fs::create_dir_all(log.parent().unwrap()).unwrap(); - let held = fs::File::create(&log).unwrap(); - held.lock().unwrap(); + let held = hold(&log); let mut cmd = hook(&home); cmd.args(["--agent", "cursor"]) .env("PATH", path) @@ -392,7 +391,7 @@ fn opencode_turns_whose_hooks_run_at_once_out_of_order_each_list_their_own_edit( let log = studio_hook::event_log(&home); fs::create_dir_all(log.parent().unwrap()).unwrap(); let run = |lines: Vec| { - let held = studio_hook::locked(&log, Duration::from_secs(1)).unwrap(); + let held = hold(&log); let children: Vec<_> = (lines.iter().rev()) .map(|payload| { let mut cmd = hook(&home); diff --git a/hook/tests/prune.rs b/hook/tests/prune.rs index c7dfb69b..f9f6e934 100644 --- a/hook/tests/prune.rs +++ b/hook/tests/prune.rs @@ -1,6 +1,8 @@ // The event log's growth (danielrispler/plotkeeper#132): the hook leaves out the two heavy fields, -// and a prune moves the sessions that ended more than 30 days ago to the archive. -use crate::common::{feed, hook, scratch as scratch_home}; +// and a prune moves the sessions that ended more than 30 days ago to the archive. And the log's lock +// (#805): appends and a prune against a held `events.lock`, and the law's scan that every writer of +// the log goes through the hook crate's log code. +use crate::common::{feed, hold, hook, scratch as scratch_home}; use serde_json::{Value, json}; use std::{ fs, @@ -169,15 +171,15 @@ fn no_log_prunes_nothing() { assert!(!log.exists()); } -/// A prune replaces the log's file while it holds the lock. A hook that opened the old file and waits -/// for the lock must write to the new one, or its line is lost. +/// A prune replaces the log's file while it holds the lock. A hook that waits for the lock must write +/// to the new one, or its line is lost. +// @law: log-writers-hold-the-log-lock #[test] fn a_line_waiting_for_the_lock_lands_in_the_log_that_replaced_it() { let home = scratch("replaced"); let log = studio_hook::event_log(&home); fs::write(&log, "").unwrap(); - let held = fs::File::open(&log).unwrap(); - held.lock().unwrap(); + let held = hold(&log); let waiting = { let log = log.clone(); thread::spawn(move || studio_hook::append(&log, &at("s-1", NOW), Duration::from_secs(5))) @@ -277,3 +279,200 @@ fn a_prune_keeps_a_copilot_sessions_camel_case_lines_together() { assert_eq!(lines(&log), [old, recent]); } + +/// No reader meets the log's lock: while another writer holds it, the log opens and reads whole, and an append waits for +/// it. An append whose patience outlasts the hold lands once the lock is let go; one whose patience runs out first gives +/// `false` and writes nothing. +// @law: log-writers-hold-the-log-lock +#[test] +fn an_append_against_a_held_lock_lands_once_it_is_let_go_or_writes_nothing_when_its_patience_runs_out() + { + for (name, patience, lands) in [ + ("longer", Duration::from_secs(5), true), + ("shorter", Duration::from_millis(100), false), + ] { + let home = scratch(&format!("held-{name}")); + let log = studio_hook::event_log(&home); + write(&log, &[at("s-0", NOW)]); + let held = hold(&log); + let waiting = { + let log = log.clone(); + thread::spawn(move || studio_hook::append(&log, &at("s-1", NOW), patience)) + }; + thread::sleep(Duration::from_millis(200)); + + assert_eq!(lines(&log), [at("s-0", NOW)], "{name}"); + let appended = if lands { + assert!(!waiting.is_finished(), "{name}"); + drop(held); + waiting.join() + } else { + let appended = waiting.join(); + drop(held); + appended + }; + assert_eq!(appended.unwrap().unwrap(), lands, "{name}"); + let expected: &[Value] = if lands { + &[at("s-0", NOW), at("s-1", NOW)] + } else { + &[at("s-0", NOW)] + }; + assert_eq!(lines(&log), expected, "{name}"); + } +} + +/// A data folder from before the log had a lock file of its own gets one on the first append, and its log keeps its +/// lines. +// @law: log-writers-hold-the-log-lock +#[test] +fn a_data_folder_with_no_lock_file_gets_one_on_the_first_append_and_keeps_its_lines() { + let home = scratch("no-lock"); + let log = studio_hook::event_log(&home); + write(&log, &[at("s-0", NOW)]); + let lock = studio_hook::lock_file(&log); + assert!(!lock.exists()); + + assert!(studio_hook::append(&log, &at("s-1", NOW), Duration::from_secs(1)).unwrap()); + + assert!(lock.is_file()); + assert_eq!(lines(&log), [at("s-0", NOW), at("s-1", NOW)]); +} + +/// Many appends at once, from threads, give whole lines, none interleaved, in a log that ends with a newline. +// @law: log-writers-hold-the-log-lock +#[test] +fn appends_from_many_threads_at_once_give_whole_lines() { + let home = scratch("threads"); + let log = studio_hook::event_log(&home); + let line = |thread: usize, n: usize| json!({ "session_id": format!("s-{thread}-{n}"), "studio_received_ms": NOW, "pad": "x".repeat(20_000) }); + let threads: Vec<_> = (0..8) + .map(|thread| { + let log = log.clone(); + thread::spawn(move || { + for n in 0..20 { + let event = line(thread, n); + assert!(studio_hook::append(&log, &event, Duration::from_secs(30)).unwrap()); + } + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + + let text = fs::read_to_string(&log).unwrap(); + assert!(text.ends_with('\n')); + let mut logged = lines(&log); + logged.sort_by_key(|l| l["session_id"].as_str().unwrap().to_owned()); + let mut expected: Vec<_> = (0..8) + .flat_map(|t| (0..20).map(move |n| line(t, n))) + .collect(); + expected.sort_by_key(|l| l["session_id"].as_str().unwrap().to_owned()); + assert_eq!(logged, expected); +} + +/// A prune reads the log, then waits for the lock to swap the new log in; lines appended between its read and its swap +/// are copied to the new log's tail. +// @law: log-writers-hold-the-log-lock +#[test] +fn a_prunes_tail_copy_keeps_the_lines_appended_between_its_read_and_its_swap() { + let home = scratch("tail"); + let log = studio_hook::event_log(&home); + let (old, recent, late) = ( + at("old", NOW - 40 * DAY), + at("recent", NOW - DAY), + at("late", NOW), + ); + write(&log, &[old.clone(), recent.clone()]); + let mut held = hold(&log); + let pruning = { + let log = log.clone(); + thread::spawn(move || prune(&log, NOW)) + }; + thread::sleep(Duration::from_millis(300)); + assert!( + !pruning.is_finished(), + "the prune swapped the log without its lock" + ); + // A hook that got the lock before the prune writes its line. + std::io::Write::write_all(&mut held, format!("{late}\n").as_bytes()).unwrap(); + drop(held); + + let pruned = pruning.join().unwrap().unwrap(); + + assert_eq!(pruned.archived, 1); + assert_eq!(lines(&log), [recent, late]); + assert_eq!(lines(&archive_file(&log)), [old]); +} + +/// Every writer of the log goes through the hook crate's log code, which takes the lock: outside it, `archive/` and the +/// tests' own helpers, no source file names the event log and opens a file to write. +// @law: log-writers-hold-the-log-lock +#[test] +fn no_file_but_the_log_code_names_the_log_and_opens_a_file_to_write() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + let listed = std::process::Command::new("git") + .args(["ls-files", "-z", "--", "*.rs"]) + .current_dir(root) + .output() + .unwrap(); + assert!(listed.status.success()); + let listed = String::from_utf8(listed.stdout).unwrap(); + let ours = listed.split('\0').filter(|file| { + let helper = file.starts_with("test-support/") + || file.contains("/tests/") + || file.ends_with("tests.rs"); + !file.is_empty() && !helper && !file.starts_with("archive/") && *file != "hook/src/lib.rs" + }); + let names = ["events.jsonl", "EVENT_LOG", "event_log(", "event_log_in("]; + let opens = ["OpenOptions", "File::create", "fs::write"]; + let mut found = Vec::new(); + for file in ours { + let text = fs::read_to_string(root.join(file)).unwrap(); + // Statement by statement: a path bound to a variable in one statement and opened in the next escapes. + let writes = without_test_modules(&text).split(';').any(|statement| { + let has = |words: &[&str]| words.iter().any(|w| statement.contains(w)); + has(&names) && has(&opens) + }); + if writes { + found.push(file); + } + } + assert!( + found.is_empty(), + "names the log and opens a file to write: {found:#?}" + ); +} + +/// `text` without its inline test modules, each `#[cfg(test)]` then `mod {` up to its matching `}`. A file's test +/// module is a test helper, and one in a file of its own is left out by its path; a `#[cfg(test)] mod tests;` +/// declaration or a test-only item cuts nothing. +fn without_test_modules(text: &str) -> String { + const TEST: &str = "#[cfg(test)]"; + let (mut kept, mut rest) = (String::new(), text); + while let Some(at) = rest.find(TEST) { + let item = rest[at + TEST.len()..].trim_start(); + let inline = item.strip_prefix("mod ").is_some_and(|module| { + let name = module.trim_start_matches(|c: char| c.is_alphanumeric() || c == '_'); + name.trim_start().starts_with('{') + }); + let open = rest[at..].find('{').map(|i| at + i); + let Some(open) = open.filter(|_| inline) else { + kept.push_str(&rest[..at + TEST.len()]); + rest = &rest[at + TEST.len()..]; + continue; + }; + kept.push_str(&rest[..at]); + let mut depth = 0; + let close = rest[open..].find(|c| { + depth += match c { + '{' => 1, + '}' => -1, + _ => 0, + }; + depth == 0 + }); + rest = close.map_or("", |i| &rest[open + i + 1..]); + } + kept + rest +} diff --git a/server/src/lib.rs b/server/src/lib.rs index 3359a0fa..36c8ea0d 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -582,7 +582,7 @@ pub fn append(lines: &[serde_json::Value]) -> Result<(), String> { append_to(&studio_hook::event_log(&home), lines) } -/// Appends `lines` to the event log `log`, under its lock. +/// Appends `lines` to the event log `log`, under the log's lock, `events.lock`. pub fn append_to(log: &Path, lines: &[serde_json::Value]) -> Result<(), String> { let locked = studio_hook::locked(log, Duration::from_secs(60)); let mut log = locked diff --git a/server/src/tests.rs b/server/src/tests.rs index aa12a60c..2d66cdc2 100644 --- a/server/src/tests.rs +++ b/server/src/tests.rs @@ -120,6 +120,32 @@ fn a_session_whose_agent_process_is_gone_gets_a_synthetic_end_and_ends() { assert!(super::process_ends(&studio, alive).is_empty()); } +/// The server's own lines wait for the log's lock, `events.lock`, as a hook's do, then land whole. +// @law: log-writers-hold-the-log-lock +#[test] +fn the_servers_lines_wait_for_the_logs_lock_then_land_whole() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("events.jsonl"); + let held = studio_hook::locked(&log, std::time::Duration::from_secs(1)) + .unwrap() + .unwrap(); + let lines = [ + serde_json::json!({ "session_id": "s1", "hook_event_name": "StudioRename", "studio_name": "a" }), + serde_json::json!({ "session_id": "s1", "hook_event_name": "StudioPromptName", "studio_name": "b" }), + ]; + let appending = { + let (log, lines) = (log.clone(), lines.clone()); + std::thread::spawn(move || super::append_to(&log, &lines)) + }; + std::thread::sleep(std::time::Duration::from_millis(200)); + + assert!(!appending.is_finished(), "wrote without the log's lock"); + drop(held); + appending.join().unwrap().unwrap(); + let text = std::fs::read_to_string(&log).unwrap(); + assert_eq!(text, format!("{}\n{}\n", lines[0], lines[1])); +} + #[test] fn an_event_reaches_what_the_shell_set_and_is_dropped_before() { let events = super::Events::default(); diff --git a/system-map.json b/system-map.json index dc1a99e1..1f3426b9 100644 --- a/system-map.json +++ b/system-map.json @@ -196,7 +196,7 @@ "ignored": [ ".agents/", ".claude/", ".github/", ".gitignore", "AGENTS.md", "CHANGELOG.md", "CLAUDE.md", "Cargo.lock", "Cargo.toml", "LICENSE", "README.md", "package-lock.json", "package.json", "rust-toolchain.toml", "tsconfig.json", "biome.json", "knip.jsonc", - "skills-lock.json", + "skills-lock.json", ".gitattributes", "docs/", "scripts/agents/", "scripts/check/", "scripts/review/", "scripts/snap/", "scripts/system-map/", "scripts/wire/", "archive/", "wayfinder/", "test-support/" ], @@ -215,6 +215,8 @@ "text": "Install and uninstall reach Cline only through `cline plugin` and never open a file in Cline's config folder, which holds its API keys." }, { "id": "hook-never-makes-agent-wait", "on": "hook", "backing": "trust", "text": "The hook never makes the agent wait, except for your answer." }, + { "id": "log-writers-hold-the-log-lock", "on": "hook", "backing": "check", + "text": "Every line written to the event log is written whole, under `events.lock`; a prune replaces the log only while holding it, and no reader takes it." }, { "id": "projects-leave-only-by-remove", "on": "server", "backing": "check", "text": "A saved project stays after its sessions end or are deleted, and leaves only through Remove project." }, { "id": "core-reads-only-transcripts", "on": "core", "backing": "trust",