From 4c32469a58a441c0395d17f0f2872b8e52e76483 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 15:53:39 -0700 Subject: [PATCH 1/4] Store commits: write the files they stage under the store lock; reads take no optional lock A commit under the store lock read a store file as another process replaced it outside that lock. git: "short read while indexing rules/last-project.json" (CI run 46195092165), then "rules/user.md" from rules organize. The undo snapshot and organize's two store files are now written inside store.commit, under the lock. sisi's own unlocked `git status` also held index.lock against those commits ("Unable to create index.lock: File exists"): git calls take no optional lock. The first line of git's stderr stays in the message. --- sisi/retro.py | 2 +- sisi/rules.py | 21 +++++++++---------- sisi/store.py | 18 ++++++++++++---- tests/test_core.py | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 16 deletions(-) diff --git a/sisi/retro.py b/sisi/retro.py index 723e690..b274a0d 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -142,7 +142,7 @@ def record(s, cwd, opt, sid=None): log = store.data("retro.jsonl") store.append(log, json.dumps(entry, sort_keys=True)) if not store.commit("retro recorded", log): - print("sisi: retro saved, but store git commit failed.") + print("sisi: retro saved, but store git commit failed (%s)." % store.GIT_ERROR) s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused", "fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began"): diff --git a/sisi/rules.py b/sisi/rules.py index f1ac7c4..e16782c 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -179,13 +179,15 @@ def scope_lines(scope, cwd=None, migrate=True): return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old))) -def _commit(msg, *paths, snap=None): +def _commit(msg, *paths, snap=None, put=None): + """Commit `paths` to the store. `put` ({path: text}) and the undo snapshot `snap` are written inside the store lock, with the commit.""" if snap: p = store.data("rules", "last-project.json") - store.write(p, json.dumps(dict(zip(("path", "before", "after"), snap)))) - paths = (p,) + paths - if not store.commit(msg, *paths): - raise OSError("store git commit failed") + paths, put = (p,) + paths, {**(put or {}), p: json.dumps(dict(zip(("path", "before", "after"), snap)))} + # written inside the store lock, never under a project's or the user's: another process's `git add` read these + # files as they were replaced ("short read while indexing") + if not store.commit(msg, *paths, put=put): + raise OSError("store git commit failed (%s)" % store.GIT_ERROR) def add(text, scope, source, cwd=None, log=None, means=""): @@ -390,21 +392,18 @@ def organize_record(answer_file, cwd): except OSError as e: return "could not write %s (%s)" % (pp, e) after is not None and note(pp) - wrote_u = False + utext = "".join(l + "\n" for l in got[USER]) try: - store.write(up, "".join(l + "\n" for l in got[USER])) - wrote_u = True seen = _organized() seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))}) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) marks = store.data("rules", "organized.json") - store.write(marks, json.dumps(seen)) dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") for r, pn, why in recs: store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True)) - _commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after)) + _commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after), put={up: utext, marks: json.dumps(seen)}) except OSError as e: - wrote_u and build_rulebook() + (wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook() if not wrote and not wrote_u: return "could not write %s (%s)" % (up, e) print("the organized rules are in %s; they could not be recorded for undo: %s" % (pp if wrote else up, e)) diff --git a/sisi/store.py b/sisi/store.py index 682b2a1..4813a38 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -96,20 +96,30 @@ def append(path, line, once=False): (not once or len(raw) <= 64000 and b"\0" not in raw and line[:-1] not in raw.splitlines()) and f.write(line) +GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error + + def git(args, cwd, timeout=15): # A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is. + # No optional locks: a plain `git status` holds index.lock while it runs, and a commit started then fails on it. + global GIT_ERROR env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")} + env["GIT_OPTIONAL_LOCKS"] = "0" try: r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env) - return r.returncode, r.stdout - except (OSError, subprocess.SubprocessError): + except (OSError, subprocess.SubprocessError) as e: + GIT_ERROR = str(e) return 1, "" + GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else "" + return r.returncode, r.stdout -def commit(message, *paths): - """One commit in the person's store holding only these paths, so the change can be undone on its own.""" +def commit(message, *paths, put=None): + """One commit in the person's store holding only these paths, so the change can be undone on its own. + `put` ({path: text}) is written first, under the same lock: `git add` in another process never reads a file as it is replaced.""" with lock("store"): os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA) + [write(p, text) for p, text in (put or {}).items()] rel = [os.path.relpath(p, DATA) for p in paths] return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and (git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or diff --git a/tests/test_core.py b/tests/test_core.py index 6c95717..86f7c55 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1231,6 +1231,57 @@ class Core(unittest.TestCase): self.assertIn("First concurrent project rule", after_revert) self.assertNotIn("Second concurrent project rule", after_revert) + def test_undo_snapshot_is_written_inside_the_store_lock(self): + # rules/last-project.json is one file for every project, each written under its own project's lock. Another + # project replaced it between `git add` taking its size and reading it: "short read while indexing" (run 46195092165). + from sisi import rules, store + self.sisi("learn", "--project", "First rule makes the snapshot") + snap, real_lock, seen = os.path.join(self.data, "rules", "last-project.json"), store.lock, [] + before = self.read(snap) + + def locked(key, wait=True): + key == "store" and seen.append(self.read(snap)) + return real_lock(key, wait=wait) + + with mock.patch.object(store, "lock", locked): + res, _ = self.in_process(rules.add, "Rule written while the store lock is asked for", rules.PROJECT, "owner", self.proj) + self.assertEqual(res[1], "") + self.assertEqual(seen, [before]) # still the old snapshot when the lock is asked for: it is written under the lock + self.assertIn("Rule written while the store lock is asked for", self.read(snap)) + committed = subprocess.run(["git", "show", "HEAD:rules/last-project.json"], cwd=self.data, capture_output=True, text=True, check=True).stdout + self.assertEqual(json.loads(committed)["after"], self.read(os.path.join(self.proj, ".sisi", "rules.md"))) + + def test_a_git_read_leaves_the_index_alone(self): + # A plain `git status` holds index.lock while it runs and rewrites the index when its stat info is stale; a + # commit that starts then fails with "Unable to create index.lock: File exists". A read of sisi's takes no lock. + from sisi import store + self.sisi("learn", "--project", "Tracked file whose stat info goes stale") + tracked, index, later = os.path.join(self.data, "rules", "last-project.json"), os.path.join(self.data, ".git", "index"), time.time() + 10 + os.utime(tracked, (later, later)) # same content, other mtime: plain git would write the refreshed index back + before = os.stat(index).st_ino + self.assertEqual(store.git(["status", "--porcelain"], self.data)[0], 0) + self.assertEqual(os.stat(index).st_ino, before) + + def test_organized_store_files_are_written_inside_the_store_lock(self): + # organize replaced rules/user.md under a project's lock; a user rule's concurrent `git add` read it as it + # shrank: "short read while indexing rules/user.md". + from sisi import rules, store + self.sisi("learn", "User rule before organizing") + user, real_lock, seen = os.path.join(self.data, "rules", "user.md"), store.lock, [] + before = self.read(user) + + def locked(key, wait=True): + key == "store" and seen.append(self.read(user)) + return real_lock(key, wait=wait) + + answer = self.write(os.path.join(self.tmp, "answer.md"), "## user\n- Organized user rule [retro 2026-11-24]\n## project\n- Organized project rule [retro 2026-11-24]\n") + self.in_process(rules.organize_brief, self.proj) + with mock.patch.object(store, "lock", locked): + why, out = self.in_process(rules.organize_record, answer, self.proj) + self.assertIsNone(why, out) + self.assertEqual(seen, [before]) # still the old list when the lock is asked for: it is replaced under the lock + self.assertEqual(self.read(user), "- Organized user rule [retro 2026-11-24]\n") + def test_folders_outside_git_are_each_their_own_project(self): notes, other, thing = (self.mkdir(self.tmp, *p) for p in (("notes",), ("code", "other"), ("code", "thing"))) self.assertEqual(self.sisi("learn", "--project", "A rule written at the home folder", cwd=self.tmp)[0], 0) From 6477f22933724808506b4fa0b9fd957bd2cf25a6 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 15:55:47 -0700 Subject: [PATCH 2/4] Tests: in-process helper uses the temp home; guard fails any test that writes the person's own rules file The new organize test rebuilt the rulebook in-process with the real home folder and re-pointed ~/.claude/CLAUDE.md at a deleted temp store. Co-Authored-By: Claude Fable 5.2 --- tests/test_core.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_core.py b/tests/test_core.py index 86f7c55..2ec3f4c 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -43,10 +43,16 @@ def tree(): return out.hexdigest() +REAL_HOME = os.path.expanduser("~") + + class Core(unittest.TestCase): def setUp(self): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = open(book).read() if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(open(book).read() if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) self.tmp = tempfile.mkdtemp(prefix="sisi-test-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data") @@ -1303,8 +1309,10 @@ class Core(unittest.TestCase): out, here = io.StringIO(), os.getcwd() os.chdir(self.tmp) try: + # the temp home too: a rulebook rebuild re-points every agent tool's rules file under the home folder with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \ - mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), contextlib.redirect_stdout(out): + mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \ + mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out): return fn(*args), out.getvalue() finally: os.chdir(here) From 6292f5c45e3aa88d29d1fb2505555701cecf6f27 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 16:09:59 -0700 Subject: [PATCH 3/4] Store commit fix: fit the size budget (put paths are committed without being named twice) Co-Authored-By: Claude Fable 5.2 --- sisi/rules.py | 11 +++-------- sisi/store.py | 16 ++++++---------- tests/test_core.py | 4 ++-- 3 files changed, 11 insertions(+), 20 deletions(-) diff --git a/sisi/rules.py b/sisi/rules.py index e16782c..3bda6ee 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -180,12 +180,8 @@ def scope_lines(scope, cwd=None, migrate=True): def _commit(msg, *paths, snap=None, put=None): - """Commit `paths` to the store. `put` ({path: text}) and the undo snapshot `snap` are written inside the store lock, with the commit.""" - if snap: - p = store.data("rules", "last-project.json") - paths, put = (p,) + paths, {**(put or {}), p: json.dumps(dict(zip(("path", "before", "after"), snap)))} - # written inside the store lock, never under a project's or the user's: another process's `git add` read these - # files as they were replaced ("short read while indexing") + # `put` and the undo snapshot are written inside the store lock: another process's `git add` read them mid-replace ("short read") + put = dict(put or {}, **({store.data("rules", "last-project.json"): json.dumps(dict(zip(("path", "before", "after"), snap)))} if snap else {})) if not store.commit(msg, *paths, put=put): raise OSError("store git commit failed (%s)" % store.GIT_ERROR) @@ -397,11 +393,10 @@ def organize_record(answer_file, cwd): seen = _organized() seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))}) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) - marks = store.data("rules", "organized.json") dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") for r, pn, why in recs: store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True)) - _commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after), put={up: utext, marks: json.dumps(seen)}) + _commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, store.data("rules", "organized.json"): json.dumps(seen)}) except OSError as e: (wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook() if not wrote and not wrote_u: diff --git a/sisi/store.py b/sisi/store.py index 4813a38..78aff25 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -20,6 +20,7 @@ def _where(own, xdg, fallback): DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share")) STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state")) LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi") +GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, @@ -96,31 +97,26 @@ def append(path, line, once=False): (not once or len(raw) <= 64000 and b"\0" not in raw and line[:-1] not in raw.splitlines()) and f.write(line) -GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error - - def git(args, cwd, timeout=15): # A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is. - # No optional locks: a plain `git status` holds index.lock while it runs, and a commit started then fails on it. global GIT_ERROR env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")} - env["GIT_OPTIONAL_LOCKS"] = "0" + env["GIT_OPTIONAL_LOCKS"] = "0" # a plain `git status` holds index.lock while it runs, and a commit started then fails on it try: r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env) except (OSError, subprocess.SubprocessError) as e: - GIT_ERROR = str(e) - return 1, "" + r = subprocess.CompletedProcess(args, 1, "", str(e)) GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else "" return r.returncode, r.stdout def commit(message, *paths, put=None): - """One commit in the person's store holding only these paths, so the change can be undone on its own. - `put` ({path: text}) is written first, under the same lock: `git add` in another process never reads a file as it is replaced.""" + """One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text}) + is written under the lock and committed too: another process's `git add` never reads a file as it is replaced.""" with lock("store"): os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA) [write(p, text) for p, text in (put or {}).items()] - rel = [os.path.relpath(p, DATA) for p in paths] + rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))] return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and (git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0)) diff --git a/tests/test_core.py b/tests/test_core.py index 2ec3f4c..4d2fc9b 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -51,8 +51,8 @@ class Core(unittest.TestCase): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") - mine = open(book).read() if os.path.exists(book) else None - self.addCleanup(lambda: self.assertEqual(open(book).read() if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) self.tmp = tempfile.mkdtemp(prefix="sisi-test-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data") From 62e494de8ef90f3cda9e69257bc908886bfd7351 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 16:39:10 -0700 Subject: [PATCH 4/4] Tests: no background git upkeep in test projects The setup commit started a detached git gc that pruned the tripwires test's fake .git/worktrees folders later under load (7 of 16 runs failed with four loops at once; 0 of 40 after). Co-Authored-By: Claude Fable 5.2 --- tests/test_core.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_core.py b/tests/test_core.py index 4d2fc9b..0487296 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -75,7 +75,9 @@ class Core(unittest.TestCase): def project(self, name): path = os.path.join(self.tmp, name) os.makedirs(path) - for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]): + # no background upkeep: the commit starts a detached `git gc`, which prunes a test's fake .git/worktrees folders later, under load + for args in (["init", "-q"], ["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"], + ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]): subprocess.run(["git"] + args, cwd=path, check=True, capture_output=True) return path