Merge: store files are written under the store lock with their commit; tests cannot write the person's rules file
ci / test (push) Waiting to run

Fixes the CI failure in run 46195092165 (short read while indexing rules/last-project.json).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-28 16:39:10 -07:00
commit 6e73cca4a1
4 files changed
+84 -23

No files matched your search

+1 -1
View File
@@ -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"):
+8 -14
View File
@@ -179,13 +179,11 @@ 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):
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")
def _commit(msg, *paths, snap=None, put=None):
# `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)
def add(text, scope, source, cwd=None, log=None, means=""):
@@ -390,21 +388,17 @@ 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", *([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 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))
+12 -6
View File
@@ -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,
@@ -98,19 +99,24 @@ def append(path, line, once=False):
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.
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" # 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)
return r.returncode, r.stdout
except (OSError, subprocess.SubprocessError):
return 1, ""
except (OSError, subprocess.SubprocessError) as e:
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):
"""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 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)
rel = [os.path.relpath(p, DATA) for p in paths]
[write(p, text) for p, text in (put or {}).items()]
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))
+63 -2
View File
@@ -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 = 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")
@@ -69,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
@@ -1231,6 +1239,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)
@@ -1252,8 +1311,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)