diff --git a/pm-stack/external-comms/record-external-send b/pm-stack/external-comms/record-external-send index fec2b2bde3..a1feb35034 100755 --- a/pm-stack/external-comms/record-external-send +++ b/pm-stack/external-comms/record-external-send @@ -22,7 +22,14 @@ events.ts): DATABASE-FIRST WITH SPILL TO OUTBOX. each record is inserted with ignore-duplicates on its stable id (so a retry after an ambiguous failure is safe), landed lines are removed, failures stay with - _attempts/_last_error bookkeeping. Runs under the + _attempts/_last_error bookkeeping. A line that cannot + be parsed (or is not a JSON object) is NEVER dropped: + it is appended verbatim to quarantine.jsonl in the + state dir (raw line + timestamp + reason, fsync'd + before the outbox rewrite that removes it), counted + in pusher-health.json and the stdout summary, and a + run that quarantined a line is not a clean drain (it + does not set last_drain_ok_at). Runs under the systemd user timer external-comms-pusher.timer (every minute) and always rewrites pusher-health.json — the visible surface a stewardship @@ -53,6 +60,7 @@ STATE_DIR = os.environ.get( os.path.expanduser("~/.local/state/external-comms")) OUTBOX = os.path.join(STATE_DIR, "outbox.jsonl") HEALTH = os.path.join(STATE_DIR, "pusher-health.json") +QUARANTINE = os.path.join(STATE_DIR, "quarantine.jsonl") LOCK = os.path.join(STATE_DIR, "pusher.lock") TABLE = "external_comms" TIMEOUT = 8 # seconds; a send-time caller must never hang on the ledger @@ -137,7 +145,7 @@ def spill(rec): os.fsync(f.fileno()) -def write_health(**fields): +def write_health(_remove=(), **fields): os.makedirs(STATE_DIR, exist_ok=True) health = {} if os.path.exists(HEALTH): @@ -147,6 +155,8 @@ def write_health(**fields): except Exception: health = {} health.update(fields) + for k in _remove: + health.pop(k, None) health["updated_at"] = now_iso() tmp = HEALTH + ".tmp" with open(tmp, "w") as f: @@ -155,6 +165,34 @@ def write_health(**fields): return health +def quarantine_line(raw, run_at, reason): + """Durably append one malformed outbox line to quarantine.jsonl. + + Stores the exact raw line (minus its line terminator), the time and + the reason. fsync'd: callers must only drop the line from the outbox + after this returns. Raises on failure.""" + os.makedirs(STATE_DIR, exist_ok=True) + entry = {"_quarantined_at": run_at, "_reason": reason, + "_raw": raw.rstrip("\n")} + # Roll a failed append back to its starting offset: a partial + # (unterminated) prefix left in quarantine.jsonl would merge with + # the next successful entry into one invalid JSON line, making + # that record unrecoverable even though it counted as quarantined. + offset = os.path.getsize(QUARANTINE) if os.path.exists(QUARANTINE) else 0 + try: + with open(QUARANTINE, "a") as f: + f.write(json.dumps(entry) + "\n") + f.flush() + os.fsync(f.fileno()) + except Exception: + try: + with open(QUARANTINE, "r+") as f: + f.truncate(offset) + except Exception: + pass + raise + + def do_record(rec): """Returns 'db' or 'outbox'. Raises only if both paths fail.""" try: @@ -181,13 +219,17 @@ def do_push(): return 0 run_at = now_iso() pending, landed, last_error = [], 0, None - total_landed = 0 + pending_raw = [] # malformed lines whose quarantine write failed + quarantined, last_quarantine_reason = 0, None + total_landed, total_quarantined = 0, 0 if os.path.exists(HEALTH): try: with open(HEALTH) as f: - total_landed = json.load(f).get("total_landed", 0) + prev_health = json.load(f) + total_landed = prev_health.get("total_landed", 0) + total_quarantined = prev_health.get("total_quarantined", 0) except Exception: - total_landed = 0 + total_landed, total_quarantined = 0, 0 lines = [] if os.path.exists(OUTBOX): with open(OUTBOX) as f: @@ -198,10 +240,27 @@ def do_push(): except Exception as e: base, key, last_error = None, None, f"db config: {e}" for ln in lines: + rec, malformed = None, None try: rec = json.loads(ln) - except Exception: - continue # unparseable line: drop, it can never land + if not isinstance(rec, dict): + malformed = "not a JSON object" + except Exception as e: + malformed = f"json-decode: {e}" + if malformed is not None: + # NEVER SILENT: quarantine the exact line durably + # BEFORE the rewrite below removes it from the outbox. + # If the quarantine write itself fails, keep the raw + # line in the outbox for the next run instead. + try: + quarantine_line(ln, run_at, malformed) + quarantined += 1 + last_quarantine_reason = malformed + except Exception as qe: + pending_raw.append(ln if ln.endswith("\n") + else ln + "\n") + last_error = f"quarantine failed: {qe}"[:300] + continue if base is None: rec["_attempts"] = rec.get("_attempts", 0) + 1 rec["_last_error"] = str(last_error) @@ -221,16 +280,31 @@ def do_push(): with open(tmp, "w") as f: for rec in pending: f.write(json.dumps(rec) + "\n") + for ln in pending_raw: + f.write(ln) os.replace(tmp, OUTBOX) total_landed += landed - health = write_health( + total_quarantined += quarantined + pending_total = len(pending) + len(pending_raw) + health_fields = dict( last_run_at=run_at, - pending_count=len(pending), + pending_count=pending_total, last_error=last_error, total_landed=total_landed, - **({"last_drain_ok_at": run_at} if not pending else {})) + last_run_quarantined=quarantined, + total_quarantined=total_quarantined) + if quarantined: + health_fields["last_quarantine_at"] = run_at + health_fields["last_quarantine_reason"] = last_quarantine_reason + health_fields["last_lossy_drain_at"] = run_at + clean_drain = not pending_total and not quarantined + health = write_health( + _remove=("last_drain_ok_at",) if quarantined else (), + **health_fields, + **({"last_drain_ok_at": run_at} if clean_drain else {})) print(json.dumps({"pusher": "ran", "landed": landed, - "pending": len(pending), + "pending": pending_total, + "quarantined": quarantined, "last_error": last_error})) return 0 diff --git a/pm-stack/external-comms/test_push_quarantine.py b/pm-stack/external-comms/test_push_quarantine.py new file mode 100644 index 0000000000..6c1ea67a9e --- /dev/null +++ b/pm-stack/external-comms/test_push_quarantine.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Pinning tests for issue #6154: the external-comms pusher must never +silently drop a malformed outbox line. + +Each case runs the real `record-external-send push` as a subprocess +with an isolated EXTERNAL_COMMS_STATE_DIR and a loopback-refused +Supabase URL (127.0.0.1:9), so valid records stay pending with retry +bookkeeping and no database is needed. + +Run: python3 -m unittest test_push_quarantine -v (from this dir) +""" +import json +import os +import random +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPT = os.path.join(HERE, "record-external-send") +TORN = '{"id":"torn-record","identity":"drew","channel":"emai' +VALID = {"id": "valid-record", "identity": "drew", "channel": "email", + "destination": "x@example.com", "kind": "bug-report", + "approval_basis": "per-item", "summary": "control record", + "sent_at": "2026-11-05T00:00:00+00:00", "_attempts": 0} + + +class PushCase(unittest.TestCase): + def run_push(self, lines): + state = tempfile.mkdtemp(prefix="extcomms-test-") + with open(os.path.join(state, "outbox.jsonl"), "w") as f: + for ln in lines: + f.write(ln + "\n") + env = dict(os.environ, + EXTERNAL_COMMS_STATE_DIR=state, + EXTERNAL_COMMS_SUPABASE_URL="http://127.0.0.1:9", + EXTERNAL_COMMS_SERVICE_KEY="dummy-test-key") + out = subprocess.run([sys.executable, SCRIPT, "push"], env=env, + capture_output=True, text=True, timeout=60) + self.assertEqual(out.returncode, 0, out.stderr) + health = {} + hpath = os.path.join(state, "pusher-health.json") + if os.path.exists(hpath): + with open(hpath) as f: + health = json.load(f) + quarantine = [] + qpath = os.path.join(state, "quarantine.jsonl") + if os.path.exists(qpath): + with open(qpath) as f: + quarantine = [json.loads(ln) for ln in f if ln.strip()] + with open(os.path.join(state, "outbox.jsonl")) as f: + outbox = [ln for ln in f if ln.strip()] + return json.loads(out.stdout.strip()), health, quarantine, outbox + + def test_torn_only_is_quarantined_and_not_a_clean_drain(self): + summary, health, quarantine, outbox = self.run_push([TORN]) + self.assertEqual(summary["quarantined"], 1) + self.assertEqual(summary["pending"], 0) + self.assertEqual(outbox, []) + # the exact torn line is recoverable from the state dir + self.assertEqual(len(quarantine), 1) + self.assertEqual(quarantine[0]["_raw"], TORN) + self.assertTrue(quarantine[0]["_reason"].startswith("json-decode:")) + self.assertTrue(quarantine[0]["_quarantined_at"]) + # health accounts for the loss; no clean-drain claim + self.assertEqual(health["last_run_quarantined"], 1) + self.assertEqual(health["total_quarantined"], 1) + self.assertEqual(health["last_quarantine_reason"], + quarantine[0]["_reason"]) + self.assertNotIn("last_drain_ok_at", health) + self.assertEqual(health["last_lossy_drain_at"], + health["last_run_at"]) + + def test_mixed_valid_and_torn(self): + summary, health, quarantine, outbox = self.run_push( + [json.dumps(VALID), TORN]) + self.assertEqual(summary["quarantined"], 1) + self.assertEqual(summary["pending"], 1) + # valid control stays pending with retry bookkeeping + self.assertEqual(len(outbox), 1) + kept = json.loads(outbox[0]) + self.assertEqual(kept["id"], "valid-record") + self.assertEqual(kept["_attempts"], 1) + self.assertIn("_last_error", kept) + # torn line quarantined verbatim + self.assertEqual([q["_raw"] for q in quarantine], [TORN]) + self.assertEqual(health["total_quarantined"], 1) + + def test_valid_only_control_has_no_quarantine(self): + summary, health, quarantine, outbox = self.run_push( + [json.dumps(VALID)]) + self.assertEqual(summary["quarantined"], 0) + self.assertEqual(quarantine, []) + self.assertEqual(health["last_run_quarantined"], 0) + self.assertEqual(health["total_quarantined"], 0) + self.assertEqual(len(outbox), 1) + + def test_non_object_json_line_is_quarantined(self): + summary, health, quarantine, outbox = self.run_push(["[1, 2]"]) + self.assertEqual(summary["quarantined"], 1) + self.assertEqual(quarantine[0]["_raw"], "[1, 2]") + self.assertEqual(quarantine[0]["_reason"], "not a JSON object") + self.assertEqual(outbox, []) + + +class GeneratedConservationCase(unittest.TestCase): + """Property-style coverage (repo testing doctrine): the oracle is + the conservation invariant — every nonblank outbox line ends the + run either pending in the outbox (valid records, DB refused) or + preserved verbatim in quarantine (malformed / non-object lines); + nothing is lost and nothing is double-counted.""" + + def test_generated_mixed_batches_preserve_every_line(self): + rng = random.Random(6154) + case = PushCase() + case.setUp = lambda: None + lines, want_quarantined, want_valid_ids = [], [], [] + for i in range(120): + kind = rng.randrange(4) + if kind == 0: + rec = dict(VALID, id=f"gen-{i}") + lines.append(json.dumps(rec)) + want_valid_ids.append(f"gen-{i}") + elif kind == 1: + full = json.dumps(dict(VALID, id=f"gen-{i}")) + cut = rng.randrange(1, len(full)) + lines.append(full[:cut]) # proper prefix: never valid + want_quarantined.append(full[:cut]) + elif kind == 2: + val = rng.choice([[1, 2], 42, "str", None, True]) + lines.append(json.dumps(val)) + want_quarantined.append(json.dumps(val)) + else: + junk = "x" + "".join(rng.choice("abcdefghij") + for _ in range(rng.randrange(1, 30))) + lines.append(junk) + want_quarantined.append(junk) + rng.shuffle(lines) + summary, health, quarantine, outbox = case.run_push(lines) + self.assertEqual(summary["quarantined"], len(want_quarantined)) + self.assertEqual(summary["pending"], len(want_valid_ids)) + self.assertEqual(summary["quarantined"] + summary["pending"], + len(lines)) + self.assertEqual(sorted(q["_raw"] for q in quarantine), + sorted(want_quarantined)) + kept = [json.loads(ln) for ln in outbox] + self.assertEqual(sorted(r["id"] for r in kept), + sorted(want_valid_ids)) + self.assertTrue(all(r["_attempts"] == 1 for r in kept)) + self.assertEqual(health["total_quarantined"], + len(want_quarantined)) + + +class QuarantineRollbackCase(unittest.TestCase): + """A quarantine append that fails mid-write (disk full) must roll + back to its starting offset, so the next successful entry is a + clean JSONL line rather than a merge with an unterminated prefix.""" + + def test_failed_append_rolls_back_to_starting_offset(self): + import importlib.machinery + import importlib.util + state = tempfile.mkdtemp(prefix="extcomms-rollback-") + os.environ["EXTERNAL_COMMS_STATE_DIR"] = state + loader = importlib.machinery.SourceFileLoader("rec_ext_send", + SCRIPT) + spec = importlib.util.spec_from_loader("rec_ext_send", loader) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + mod.quarantine_line('{"good"', "2026-11-05T00:00:00+00:00", + "json-decode: seed") + with open(mod.QUARANTINE) as f: + before = f.read() + real_fsync = os.fsync + + def boom(fd): + raise OSError("disk full (simulated)") + + os.fsync = boom + try: + with self.assertRaises(OSError): + mod.quarantine_line(TORN, "2026-11-05T00:01:00+00:00", + "json-decode: torn") + finally: + os.fsync = real_fsync + with open(mod.QUARANTINE) as f: + self.assertEqual(f.read(), before) + mod.quarantine_line(TORN, "2026-11-05T00:02:00+00:00", + "json-decode: torn") + with open(mod.QUARANTINE) as f: + entries = [json.loads(ln) for ln in f if ln.strip()] + self.assertEqual(entries[-1]["_raw"], TORN) + + +if __name__ == "__main__": + unittest.main()