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)