Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
__pycache__/
*.pyc
*promo*
# ledger write lock (am._ledger_lock creates it next to the ledger, never deletes it)
*.jsonl.lock
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

---

## [Unreleased]

### Fixed
- **Concurrent appenders no longer fork the chain.** `record()` and `witness_peer()`
(the two writers, both through `_seal`) now reads the head seal and writes
its line under an exclusive OS lock on a sidecar `<ledger>.lock` file. Before, two
processes could read the same head and both append after it, and `verify_chain()`
reported the honest second line as a deletion/insertion. The lock file stays next to
the ledger; the lock is advisory, so writers that bypass this package are not covered.
Seal format unchanged. Covered by `tests/test_concurrent_append.py`.

## [0.5.0] — 2026-11-23

### Added
Expand Down
84 changes: 72 additions & 12 deletions actmirror/am.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
Zero dependencies (stdlib only). Deterministic. Same DNA as measure-mirror.
"""
from __future__ import annotations
import hashlib, json, os, sys, time
import contextlib, hashlib, json, os, sys, time
from dataclasses import dataclass


Expand Down Expand Up @@ -133,18 +133,78 @@ def _seal_of(raw: bytes):
return entry["seal"] if isinstance(entry, dict) and "seal" in entry else None


# How long an appender waits for another writer before giving up. An append holds the
# lock for one tail read + one line write, so reaching this means a writer is stuck.
_LOCK_TIMEOUT_S = 60.0


@contextlib.contextmanager
def _ledger_lock(ledger_path: str, timeout: float = _LOCK_TIMEOUT_S):
"""Hold an exclusive OS lock on ``<ledger>.lock`` for one read-head-then-append.

Without it two processes can read the SAME head seal and both append after it: the
chain forks and verify_chain() reports the honest second line as a deletion/insertion.
Reproduced 2026-11-24 with 4 processes x 50 record() calls on one ledger. Same lock
as measure-mirror's ``_ledger_lock`` (kept as a copy: both packages are stdlib-only
and independent).

A sidecar file, because Windows byte-range locks are mandatory and would make
concurrent READERS of the ledger fail. Never deleted; released by the OS if the
holder dies. Advisory: writers that bypass this module are not covered.
"""
fd = os.open(ledger_path + ".lock", os.O_CREAT | os.O_RDWR, 0o644)
deadline = time.monotonic() + timeout
try:
if os.name == "nt":
import msvcrt
while True:
os.lseek(fd, 0, os.SEEK_SET)
try:
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
break
except OSError:
if time.monotonic() >= deadline:
raise TimeoutError(
f"ledger {ledger_path!r} is locked by another writer") from None
time.sleep(0.005)
else:
import fcntl
while True:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(
f"ledger {ledger_path!r} is locked by another writer") from None
time.sleep(0.005)
try:
yield
finally:
if os.name == "nt":
import msvcrt
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)


def _seal(ledger_path: str, entry: dict, sign_key: str | None = None) -> dict:
entry["prev_seal"] = _get_last_seal(ledger_path)
# `seal` and `sig` are attestation fields, excluded from the content hash.
body = {k: v for k, v in entry.items() if k not in ("seal", "sig")}
entry["seal"] = hashlib.sha256(
json.dumps(body, sort_keys=True, ensure_ascii=False).encode()
).hexdigest()
if sign_key is not None:
from . import identity
entry["sig"] = identity.sign(sign_key, entry["seal"])
with open(ledger_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
with _ledger_lock(ledger_path):
entry["prev_seal"] = _get_last_seal(ledger_path)
# `seal` and `sig` are attestation fields, excluded from the content hash.
body = {k: v for k, v in entry.items() if k not in ("seal", "sig")}
entry["seal"] = hashlib.sha256(
json.dumps(body, sort_keys=True, ensure_ascii=False).encode()
).hexdigest()
if sign_key is not None:
from . import identity
entry["sig"] = identity.sign(sign_key, entry["seal"])
with open(ledger_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
return entry


Expand Down
59 changes: 59 additions & 0 deletions tests/test_concurrent_append.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Concurrent appenders must not fork the chain.

record() reads the head seal and then writes a line pointing at it. Before the ledger
lock, two processes could read the same head and both append after it, and
verify_chain() reported the honest second line as a deletion/insertion (reproduced
2026-11-24 with 4 processes x 50 record() calls). Real processes, not threads: the race
is between cron jobs / sibling agents sharing one ledger.
"""
import json
import os
import subprocess
import sys
import textwrap

from actmirror import am

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

WRITER = textwrap.dedent("""
import sys
from actmirror import am
path, wid, n = sys.argv[1], sys.argv[2], int(sys.argv[3])
for j in range(n):
am.record(path, agent=f"a{wid}", action="test", target=f"t{j}")
""")


def test_concurrent_appenders_keep_one_chain(tmp_path):
path = str(tmp_path / "actions.jsonl")
env = dict(os.environ)
env["PYTHONPATH"] = ROOT + os.pathsep + env.get("PYTHONPATH", "")
procs = [subprocess.Popen([sys.executable, "-c", WRITER, path, str(w), "30"],
env=env, stderr=subprocess.PIPE, text=True)
for w in range(4)]
for p in procs:
_, err = p.communicate(timeout=120)
assert p.returncode == 0, err

assert [f.level for f in am.verify_chain(path)] == ["OK"]
with open(path, encoding="utf-8") as f:
lines = [json.loads(l) for l in f if l.strip()]
assert len(lines) == 4 * 30
assert len({e["prev_seal"] for e in lines}) == len(lines)


def test_lock_is_released_after_a_failed_append(tmp_path):
path = str(tmp_path / "actions.jsonl")

class Unserializable:
pass

try:
am.record(path, agent="x", action="y", payload={"bad": Unserializable()})
except TypeError:
pass
with am._ledger_lock(path, timeout=1.0): # would time out if the lock leaked
pass
am.record(path, agent="x", action="ok")
assert [f.level for f in am.verify_chain(path)] == ["OK"]
Loading