Skip to content

The agent that grows with you

refactor(cron): keep the suppressed disposition, drop the delivery-manifest ledger rework

kshitijk4poor55b254a2c704
diff --git a/cron/bot_chat_delivery.py b/cron/bot_chat_delivery.py
index f061f7a3371..97ee0888194 100644
--- a/cron/bot_chat_delivery.py
+++ b/cron/bot_chat_delivery.py
@@ -79,14 +79,9 @@ def drain(root: Path | None = None) -> None:
root = root if root is not None else _root()
with retirement.work() as admitted:
- if not admitted:
- return
- if root.is_dir():
+ if admitted and root.is_dir():
with _FileLock(root / ".drain.lock"):
_drain(root)
- # Receipt replay is work too: it stays behind the same admission as the drain.
- from cron.executions import reconcile_delivery_projections
- reconcile_delivery_projections()
def _drain(root: Path) -> None:
@@ -102,6 +97,8 @@ def _drain(root: Path) -> None:
if record["status"] != "queued":
continue
home = Path(record["home"])
+ # A failure notice queued before the target profile opted out is settled as
+ # suppressed at drain time; the policy is the owner's, read from its own config.
from gateway.warning_notifications import warning_notifications_enabled
from hermes_cli.config_effective import load_user_config_effective
if (record.get("for_failure")
@@ -141,8 +138,6 @@ def drain_in_background() -> None:
home = get_hermes_home().resolve()
root = home / "cron" / "bot_chat_pending"
if not root.is_dir():
- from cron.executions import reconcile_delivery_projections
- reconcile_delivery_projections()
return
from hermes_cli.backend_retirement import retirement
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.py
index f78d65537ea..a55e1a36d24 100644
--- a/cron/delivery_queue.py
+++ b/cron/delivery_queue.py
@@ -329,8 +329,6 @@ def drain(
with _lock:
_ACTIVE_DELIVERIES.discard(row["execution_id"])
processed += 1
- from cron.executions import reconcile_delivery_projections
- reconcile_delivery_projections()
return processed
diff --git a/cron/executions.py b/cron/executions.py
index 8de6c3bd149..35dd8b5b607 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -8,8 +8,6 @@ immutable.
from __future__ import annotations
import os
-import json
-import logging
import sqlite3
import threading
import time
@@ -82,158 +80,12 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
"CREATE INDEX IF NOT EXISTS idx_executions_status_claimed "
"ON executions(status, claimed_at DESC, id DESC)"
)
- add_column_if_missing(conn, "executions", "delivery_manifest", "delivery_manifest TEXT")
- add_column_if_missing(conn, "executions", "incident_id", "incident_id TEXT")
- add_column_if_missing(conn, "executions", "incident_generation", "incident_generation INTEGER")
- add_column_if_missing(conn, "executions", "delivery_projection_settled", "delivery_projection_settled INTEGER NOT NULL DEFAULT 0")
- # Durable intent written BEFORE any deferred (Bot Chat) send: while set, the row's manifest is
- # incomplete and no reader may project/settle/prune from it. Cleared by the manifest write itself.
- add_column_if_missing(conn, "executions", "delivery_manifest_pending", "delivery_manifest_pending INTEGER NOT NULL DEFAULT 0")
add_column_if_missing(conn, "executions", "delivery_outcome", "delivery_outcome TEXT")
add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_executions_occurrence "
"ON executions(job_id, scheduled_instant) WHERE status='completed'"
)
- conn.execute("CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
- # Column existence is NOT the migration authority (DDL commits on its own). The fence row
- # below is: until it exists, readers hold pre-flag rows conservatively and every
- # initialization retries adoption.
- _try_adopt_legacy_intent(conn)
-
-
-_ADOPTION_KEY = "manifest_intent_adopted"
-_adoption_complete: set = set() # ledger paths whose fence row was observed (monotonic: it never disappears)
-
-
-def _ledger_key() -> str:
- return str(EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db"))
-
-
-def _legacy_intent_adopted(conn: Optional[sqlite3.Connection] = None) -> bool:
- """True once the one-time adoption of pre-flag journaled intent has durably completed."""
- key = _ledger_key()
- if key in _adoption_complete:
- return True
- if conn is None:
- with _transaction() as own:
- return _legacy_intent_adopted(own)
- row = conn.execute("SELECT 1 FROM schema_meta WHERE key=?", (_ADOPTION_KEY,)).fetchone()
- if row is not None:
- _adoption_complete.add(key)
- return row is not None
-
-
-def _journal_inventory_strict() -> Dict[str, dict]:
- """Journal inventory that RAISES on any unreadable directory or entry.
-
- Adoption must distinguish a genuinely empty journal from one it could not read: an
- incomplete inventory is not proof that no outstanding intent exists.
- """
- root = _journal_root()
- if not root.exists():
- return {}
- out: Dict[str, dict] = {}
- for path in sorted(root.iterdir()): # raises PermissionError on an unreadable directory
- if path.suffix != ".json":
- continue
- record = json.loads(path.read_text(encoding="utf-8")) # raises on an unreadable entry
- if record.get("execution_id") and record.get("manifest"):
- out[record["execution_id"]] = record["manifest"]
- return out
-
-
-def _try_adopt_legacy_intent(conn: sqlite3.Connection) -> bool:
- """One-time, retryable, atomic adoption of pre-flag outstanding journals.
-
- In ONE write transaction: every row whose real manifest is still only journaled gets
- ``delivery_manifest_pending=1``, then the fence row is written. Any failure (unreadable
- journal, rejected write) rolls back everything, logs, and leaves the fence absent so the
- next initialization retries and readers keep holding legacy rows conservatively.
- """
- if _legacy_intent_adopted(conn):
- return True
- if conn.in_transaction:
- # A caller (e.g. incident upsert) owns an open transaction; adoption must not nest a
- # BEGIN inside it nor piggyback on its commit. Defer to the next ordinary ledger open.
- logging.getLogger(__name__).debug("Cron ledger: legacy intent adoption deferred (caller transaction open)")
- return False
- try:
- inventory = _journal_inventory_strict()
- conn.execute("BEGIN IMMEDIATE")
- try:
- if conn.execute("SELECT 1 FROM schema_meta WHERE key=?", (_ADOPTION_KEY,)).fetchone():
- conn.execute("ROLLBACK") # a concurrent initializer won the race
- _adoption_complete.add(_ledger_key())
- return True
- for execution_id in inventory:
- conn.execute(
- "UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND "
- "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
- (execution_id,))
- conn.execute("INSERT INTO schema_meta(key, value) VALUES (?, ?)", (_ADOPTION_KEY, _hermes_now().isoformat()))
- conn.execute("COMMIT")
- except BaseException:
- conn.execute("ROLLBACK")
- raise
- except Exception:
- logging.getLogger(__name__).error(
- "Cron ledger: legacy delivery-intent adoption incomplete; pre-flag rows are held until it succeeds",
- exc_info=True)
- return False
- _adoption_complete.add(_ledger_key())
- return True
-
-
-def _placeholder_only(record: Optional[dict]) -> bool:
- manifest = record.get("delivery_manifest") if record else None
- return bool(manifest) and "bot" not in json.loads(manifest)
-
-
-def _journal_entry_state(execution_id: str) -> Optional[bool]:
- """True: this row has a journal entry. False: verified absent. None: could not tell."""
- path = _journal_root() / f"{execution_id}.json"
- try:
- return path.is_file()
- except OSError:
- return None
-
-
-def _held_by_incomplete_adoption(record: Optional[dict], conn: Optional[sqlite3.Connection] = None) -> bool:
- """Conservative fence while adoption is incomplete: a row carrying only the external
- placeholder may still have an outstanding journaled child we cannot see."""
- if not record or _legacy_intent_adopted(conn):
- return False
- return _placeholder_only(record)
-
-
-def _late_legacy_intent(record: Optional[dict], conn: Optional[sqlite3.Connection] = None) -> bool:
- """Old-writer accounting at terminalization (K2c).
-
- A pre-flag process that outlives adoption publishes its child manifest only to the
- journal. A placeholder-only row with pending=0 is therefore complete ONLY if its own
- journal entry is verifiably absent. When present, the intent is adopted here (in the
- caller's transaction when given) so every later reader sees the flag; when unknowable,
- the row is held. Rows that already carry "bot" are past this window and never probed.
- """
- if not record or record.get("delivery_manifest_pending") or not _placeholder_only(record):
- return False
- state = _journal_entry_state(record["id"])
- if state is False:
- return False
- if state is True and conn is not None:
- # Write-time recheck: `record` is a snapshot taken before the stat. A replay that landed
- # the complete manifest in between must not be re-armed with a flag nothing can clear.
- cur = conn.execute(
- "UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND delivery_manifest_pending=0 "
- "AND delivery_manifest IS NOT NULL AND instr(delivery_manifest, '\"bot\"')=0",
- (record["id"],))
- if cur.rowcount == 0:
- # The row moved on (complete manifest landed, or already flagged): defer to the
- # authoritative row state rather than the stale snapshot.
- current = _fetch(conn, record["id"])
- return bool(current and (current.get("delivery_manifest_pending") or _placeholder_only(current)))
- return True
@contextmanager
@@ -283,16 +135,10 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
def _prune_unlocked(conn: sqlite3.Connection) -> None:
- # While legacy-intent adoption is incomplete, rows carrying only a placeholder manifest may
- # still anchor an unseen journaled child: never prune them.
- hold = "" if _legacy_intent_adopted(conn) else " AND (delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')>0)"
conn.execute(
- f"""DELETE FROM executions WHERE id IN (
+ """DELETE FROM executions WHERE id IN (
SELECT id FROM executions
WHERE status IN ('completed','failed','unknown')
- AND (delivery_outcome IS NULL OR delivery_outcome != 'queued')
- AND (delivery_manifest IS NULL OR delivery_projection_settled=1)
- AND delivery_manifest_pending=0{hold}
ORDER BY finished_at DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
)""",
(max(0, int(MAX_TERMINAL_EXECUTIONS)),),
@@ -406,312 +252,23 @@ def finish_execution(
now = _hermes_now().isoformat()
status = "completed" if success else "failed"
detail = None if success else (str(error) if error else "unknown failure")
- # A worker may observe a terminal receipt during its wait. Use the same durable
- # classification as restart reconciliation, in particular unknown != failed.
- caller_outcome = delivery_outcome
with _transaction() as conn:
- cur = None
- for _attempt in range(2):
- # Derive the terminal delivery decision from the AUTHORITATIVE row contents and
- # write it with a CAS on the exact manifest it was derived from. A concurrent
- # replay that lands the complete manifest between derivation and write fails the
- # CAS; the second pass derives again from what is there now. The row is ours
- # (process/pid), so this never double-terminalizes.
- row = _fetch(conn, execution_id)
- derived_from = row.get("delivery_manifest") if row else None
- delivery_outcome = caller_outcome
- if row and (row.get("delivery_manifest_pending") or _held_by_incomplete_adoption(row, conn)
- or _late_legacy_intent(row, conn)):
- # Deferred children were sent but their manifest is not in the ledger yet: the
- # caller's classification (and any placeholder) is incomplete by construction.
- delivery_outcome = "queued"
- elif row and derived_from:
- projection = _delivery_projection(row)
- if projection is not None:
- delivery_outcome = projection[0]
- elif manifest_pending(row):
- delivery_outcome = "queued"
- cur = conn.execute(
- """UPDATE executions
- SET status=?, finished_at=?, error=?, handoff_pending=0,
- handoff_started_at=NULL, delivery_outcome=?
- WHERE id=? AND status IN ('claimed','running')
- AND process_id=? AND pid=? AND delivery_manifest IS ?""",
- (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid(), derived_from),
- )
- if cur.rowcount == 1:
- break
- if cur is None or cur.rowcount != 1:
+ cur = conn.execute(
+ """UPDATE executions
+ SET status=?, finished_at=?, error=?, handoff_pending=0,
+ handoff_started_at=NULL, delivery_outcome=?
+ WHERE id=? AND status IN ('claimed','running')
+ AND process_id=? AND pid=?""",
+ (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid()),
+ )
+ if cur.rowcount != 1:
return None
_prune_unlocked(conn)
record = _fetch(conn, execution_id)
_emit_execution_state(record, delivery_outcome=delivery_outcome)
- if record and record.get("delivery_manifest"):
- reconcile_delivery_projections()
return record
-def bind_delivery_incident(execution_id: Optional[str], incident_id: str) -> None:
- """Persist the producer's actual incident association, never infer it from errors."""
- if execution_id:
- with _transaction() as conn:
- from cron.incidents import _initialize_schema as init_incidents
- init_incidents(conn)
- _bind_delivery_incident_unlocked(conn, execution_id, incident_id)
-
-
-def _bind_delivery_incident_unlocked(conn, execution_id: str, incident_id: str) -> None:
- """Called in the producer's incident upsert transaction; no later generation lookup."""
- conn.execute("UPDATE executions SET incident_id=?, incident_generation="
- "(SELECT generation FROM cron_incidents WHERE id=?) "
- "WHERE id=? AND incident_id IS NULL "
- "AND status IN ('claimed','running') AND process_id=? AND pid=?",
- (incident_id, incident_id, execution_id, _PROCESS_ID, os.getpid()))
-
-
-def record_delivery_manifest(execution_id: Optional[str], manifest: dict) -> None:
- """Retain receipt identities and sibling disposition separately from the run result.
-
- The worker may first bind the external handoff; its gateway replaces that placeholder
- with the resolved target receipts. No payload or raw output is copied here.
- """
- if not execution_id:
- return
- with _transaction() as conn:
- _store_manifest(conn, execution_id, manifest)
-
-
-def _store_manifest(conn, execution_id: str, manifest: dict) -> None:
- """CAS the manifest onto a row that has none (or only the external placeholder).
-
- Clearing ``delivery_manifest_pending`` is part of the SAME statement: a storage fault that
- rejects the manifest leaves the intent flag set, so no reader can misread the placeholder.
- """
- row = _fetch(conn, execution_id)
- existing = row.get("delivery_manifest") if row else None
- if existing and "bot" not in json.loads(existing):
- # Any placeholder-only manifest (canonical or not) is incomplete by the same predicate
- # every reader uses; the complete manifest replaces it and keeps its external marker.
- manifest = {**manifest, "external": True}
- conn.execute("UPDATE executions SET delivery_manifest=?, delivery_manifest_pending=0 WHERE id=? AND "
- "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
- (json.dumps(manifest, sort_keys=True), execution_id))
-
-
-def mark_delivery_manifest_pending(execution_id: Optional[str]) -> None:
- """Record, BEFORE any deferred send, that this run will own child receipts.
-
- Raises when the ledger cannot take the write: nothing has been sent yet, so the caller
- may truthfully report a pre-send failure instead of sending without durable intent.
- """
- if not execution_id:
- return
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (execution_id,))
-
-
-def manifest_pending(record: Optional[dict]) -> bool:
- """True while the row's deferred-child manifest is not yet in the ledger."""
- if not record or not record.get("delivery_manifest_pending"):
- return False
- manifest = record.get("delivery_manifest")
- return not (manifest and "bot" in json.loads(manifest))
-
-
-def _journal_root() -> Path:
- return (EXECUTIONS_FILE.parent if EXECUTIONS_FILE else get_hermes_home().resolve() / "cron") / "manifest_journal"
-
-
-def journal_manifest(execution_id: str, manifest: dict) -> bool:
- """Best-effort durable copy of a manifest the ledger could not store (post-send fault).
-
- The row's ``delivery_manifest_pending`` flag is the authoritative invariant; this journal
- only lets the reconciler recover the manifest once the ledger accepts writes again.
- Never raises: a second storage failure is logged, and the row simply stays pending.
- """
- try:
- # The row flag is the authoritative fence; re-assert it here (idempotent) so a journal
- # entry never exists for a row that readers would treat as complete.
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (execution_id,))
- except Exception:
- logging.getLogger(__name__).debug("Could not re-assert manifest intent for %s", execution_id, exc_info=True)
- try:
- from utils import atomic_json_write
- root = _journal_root()
- root.mkdir(parents=True, exist_ok=True, mode=0o700)
- atomic_json_write(root / f"{execution_id}.json", {"execution_id": execution_id, "manifest": manifest},
- fsync_dir=True, mode=0o600)
- return True
- except Exception:
- logging.getLogger(__name__).exception(
- "Cron delivery manifest for %s could not be journaled; row stays pending", execution_id)
- return False
-
-
-def journaled_manifests() -> Dict[str, dict]:
- root = _journal_root()
- if not root.is_dir():
- return {}
- out: Dict[str, dict] = {}
- for path in root.glob("*.json"):
- try:
- record = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError, UnicodeDecodeError):
- logging.getLogger(__name__).error("Unreadable cron manifest journal entry %s", path)
- continue
- if record.get("execution_id") and record.get("manifest"):
- out[record["execution_id"]] = record["manifest"]
- return out
-
-
-def _recover_unrecorded_manifests() -> Dict[str, dict]:
- """Replay journaled manifests into the ledger; return what is STILL outstanding.
-
- Idempotent through the same CAS as the primary write (which also clears the row's pending
- flag). An entry is removed only once the ledger row actually carries the children.
- Callers must NOT use the return value as an authority: the row flag is authoritative.
- """
- outstanding: Dict[str, dict] = {}
- for execution_id, manifest in journaled_manifests().items():
- try:
- # A journal entry IS outstanding intent (legacy rows predating the flag, or a mark
- # whose re-assert failed). Assert it in its OWN committed transaction first: if the
- # replay below is rejected by storage, the fence must survive the rollback.
- with _transaction() as conn:
- row = _fetch(conn, execution_id)
- if row is None:
- outstanding[execution_id] = manifest
- continue
- conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND "
- "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
- (execution_id,))
- # A terminal classification derived from a placeholder-only manifest was, by
- # construction, computed without the children this journal now supplies (a
- # pre-flag writer publishing late). Reopen exactly that row, in the same
- # transaction as the intent, so the real manifest is projected once it lands.
- conn.execute("UPDATE executions SET delivery_outcome='queued', delivery_projection_settled=0 "
- "WHERE id=? AND delivery_manifest_pending=1 AND delivery_outcome IN ('delivered','failed') "
- "AND (delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
- (execution_id,))
- with _transaction() as conn:
- _store_manifest(conn, execution_id, manifest)
- row = _fetch(conn, execution_id)
- stored = json.loads(row["delivery_manifest"]) if row and row.get("delivery_manifest") else {}
- if stored.get("bot") == manifest.get("bot"):
- (_journal_root() / f"{execution_id}.json").unlink(missing_ok=True)
- else:
- outstanding[execution_id] = manifest
- except Exception:
- logging.getLogger(__name__).exception("Could not replay journaled cron manifest %s", execution_id)
- outstanding[execution_id] = manifest
- return outstanding
-
-
-def _delivery_projection(record: dict) -> Optional[tuple[str, dict]]:
- from cron import delivery_queue, bot_chat_delivery
- from tools.bot_live_delivery import read_delivery_result
-
- if manifest_pending(record) or _held_by_incomplete_adoption(record) or _late_legacy_intent(record):
- return None # children were sent; their manifest is not in the ledger yet
- manifest = json.loads(record["delivery_manifest"])
- external_outcome = None
- external_error = None
- if manifest.get("external"):
- receipt = delivery_queue.get_status(record["id"])
- if not receipt or receipt["status"] in ("pending", "delivering"):
- return None
- outcome = receipt["status"]
- external_outcome, external_error = outcome, receipt.get("error")
- if not manifest.get("bot"):
- return outcome, {"last_delivery_queued": None, "last_delivery_unverified": None,
- "last_delivery_error": receipt.get("error")}
-
- queued = {}
- states = []
- for target, ref in manifest.get("bot", {}).items():
- receipt = read_delivery_result(Path(ref["home"]), ref["delivery_id"])
- if receipt is None:
- receipt = bot_chat_delivery.read_pending(ref["delivery_id"])
- status = (receipt or ref)["status"]
- if status in ("queued", "claimed", "transferred"):
- queued[target] = {**ref, "status": status}
- states.append(status)
- error = manifest.get("error") or external_error
- unverified = manifest.get("unverified")
- if queued:
- outcome = "queued"
- elif external_outcome == "unknown" or "ambiguous" in states or "unknown" in states or unverified:
- outcome = "unknown"
- elif external_outcome == "failed" or "failed" in states or error:
- outcome = "failed"
- elif manifest.get("delivered") or "settled" in states:
- outcome = "delivered"
- else:
- outcome = "suppressed"
- if outcome in ("failed", "unknown") and not error:
- error = "Deferred delivery completion unverified; do not resend"
- return outcome, {"last_delivery_queued": queued or None,
- "last_delivery_unverified": unverified or None,
- "last_delivery_error": error}
-
-
-def reconcile_delivery_projections() -> None:
- """Replay durable receipts, never sends. Safe after either store write or restart.
-
- Only delivery_outcome can change after run completion. The queued CAS and manifest
- comparison fence racing reconcilers; execution status/error/timestamps are untouched.
- Retaining manifests also repairs a crash between the ledger and jobs/incident writes.
- """
- import logging
- from cron.jobs import update_delivery_projection
- from cron.incidents import _initialize_schema as init_incidents
-
- try:
- _recover_unrecorded_manifests()
- except Exception:
- logging.getLogger(__name__).exception("Could not replay journaled cron delivery manifests")
- with _transaction() as conn:
- records = [dict(row) for row in conn.execute(
- "SELECT * FROM executions WHERE delivery_manifest IS NOT NULL "
- "AND status IN ('completed','failed','unknown')").fetchall()]
- for record in records:
- try:
- # A pending row (children sent, manifest not yet in the ledger) projects to None
- # inside _delivery_projection; the CAS below re-checks the flag at write time so a
- # reader that loaded the row before the flag flipped cannot settle it either.
- projection = _delivery_projection(record)
- if projection is None:
- continue
- outcome, values = projection
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_outcome=? WHERE id=? "
- "AND delivery_outcome='queued' AND delivery_manifest=? "
- "AND delivery_manifest_pending=0",
- (outcome, record["id"], record["delivery_manifest"]))
- current = _fetch(conn, record["id"])
- if not current or current["delivery_outcome"] != outcome:
- continue
- if outcome == "delivered" and record.get("incident_id"):
- init_incidents(conn)
- # Late completion cannot resurrect resolved/acked incidents.
- conn.execute("UPDATE cron_incidents SET state='alerted' WHERE id=? "
- "AND state='detected' AND generation=?",
- (record["incident_id"], record.get("incident_generation")))
- update_delivery_projection(record["job_id"], record["id"], values)
- if outcome != "queued":
- # Pin the receipt association until BOTH durable projections have
- # completed. A crash above leaves it replayable even under retention.
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_projection_settled=1 "
- "WHERE id=? AND delivery_outcome=? AND delivery_manifest=? "
- "AND delivery_manifest_pending=0",
- (record["id"], outcome, record["delivery_manifest"]))
- except Exception:
- logging.getLogger(__name__).exception(
- "Could not reconcile cron delivery %s; durable receipt retained", record["id"])
-
-
def recover_interrupted_executions() -> int:
"""Mark provably abandoned attempts unknown without scheduling retries."""
now = _hermes_now().isoformat()
@@ -740,17 +297,13 @@ def recover_interrupted_executions() -> int:
cur = conn.execute(
"""UPDATE executions
SET status='unknown', finished_at=?, error=?,
- handoff_pending=0, handoff_started_at=NULL,
- delivery_outcome=CASE WHEN delivery_manifest_pending=1 OR (? AND delivery_manifest IS NOT NULL
- AND instr(delivery_manifest, '"bot"')=0)
- THEN 'queued' ELSE delivery_outcome END
+ handoff_pending=0, handoff_started_at=NULL
WHERE id=? AND status=? AND process_id=? AND pid=?
AND handoff_pending=?
AND handoff_started_at IS ?""",
(now,
"Scheduler restarted after this execution's owner exited before a durable "
"terminal state; whether side effects ran is unknown.",
- 0 if _legacy_intent_adopted(conn) else 1,
row["id"], row["status"], row["process_id"], row["pid"],
row["handoff_pending"], row["handoff_started_at"]),
)
diff --git a/cron/incidents.py b/cron/incidents.py
index 65c494fc124..623012f1394 100644
--- a/cron/incidents.py
+++ b/cron/incidents.py
@@ -81,18 +81,6 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
output_file TEXT
)"""
)
- from hermes_cli.sqlite_util import add_column_if_missing
- add_column_if_missing(conn, "cron_incidents", "generation", "generation INTEGER NOT NULL DEFAULT 1")
- # Enforce recurrence at storage level: old daemons may still update state
- # without knowing about generations. Avoid double increment for an
- # intermediate writer which already advanced generation in its UPDATE.
- conn.execute("""CREATE TRIGGER IF NOT EXISTS cron_incident_recurrence_generation
- AFTER UPDATE OF state ON cron_incidents
- WHEN OLD.state='resolved' AND NEW.state='detected'
- AND NEW.generation=OLD.generation
- BEGIN
- UPDATE cron_incidents SET generation=OLD.generation+1 WHERE id=NEW.id;
- END""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_cron_incidents_job "
"ON cron_incidents(job_id)"
@@ -155,7 +143,7 @@ def _classify_failure_type(error: str) -> str:
def upsert_incident(
job_id: str, error: str, *, job_name: Optional[str] = None, failure_type: Optional[str] = None,
- output_file: Optional[str] = None, execution_id: Optional[str] = None,
+ output_file: Optional[str] = None,
) -> tuple[str, bool]:
"""Record (or refresh) the incident for ``job_id`` + ``error``; returns ``(incident_id,
is_new)``. An existing row for the signature refreshes
@@ -184,9 +172,6 @@ def upsert_incident(
WHERE id=?""",
(now, stored_error, output_file, incident_id),
)
- if execution_id:
- _executions._initialize_schema(conn)
- _executions._bind_delivery_incident_unlocked(conn, execution_id, incident_id)
return incident_id, reopen
conn.execute(
"""INSERT INTO cron_incidents
@@ -196,29 +181,9 @@ def upsert_incident(
(incident_id, job_id, sig, failure_type, now, now,
stored_error, output_file),
)
- if execution_id:
- _executions._initialize_schema(conn)
- _executions._bind_delivery_incident_unlocked(conn, execution_id, incident_id)
return incident_id, True
-def mark_alerted_for_execution(incident_id: str, execution_id: str) -> bool:
- """Mark ``alerted`` only if the incident is still on the occurrence this execution bound.
-
- A run whose failure ping went out for occurrence N must not mark occurrence N+1 (the job
- recovered and reopened with the same signature meanwhile). Returns whether it changed.
- """
- with _transaction() as conn:
- _executions._initialize_schema(conn)
- cur = conn.execute(
- """UPDATE cron_incidents SET state='alerted'
- WHERE id=? AND state='detected'
- AND generation=(SELECT incident_generation FROM executions WHERE id=? AND incident_id=?)""",
- (incident_id, execution_id, incident_id),
- )
- return cur.rowcount == 1
-
-
def set_incident_state(incident_id: str, state: str) -> bool:
"""Transition an incident's lifecycle state; return whether it changed. ``closed`` is terminal
for that signature (re-open happens by a changed error minting a NEW incident). Unknown states
diff --git a/cron/jobs.py b/cron/jobs.py
index f8f95d59263..98e26aa0b24 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2030,44 +2030,6 @@ def _fill_missing_next_run(updated: Dict[str, Any]) -> None:
updated["next_run_at"] = next_run
-def bind_delivery_execution(job_id: str, execution_id: str) -> None:
- """Fence asynchronous job projections at run start, under the store lock."""
- from cron.executions import latest_execution
-
- def apply(records, _i, job):
- latest = latest_execution(job_id)
- if latest and latest["id"] == execution_id:
- job["delivery_execution_id"] = execution_id
- save_jobs(records)
- _with_job(job_id, apply)
-
-
-def update_delivery_projection(job_id: str, execution_id: str, values: dict) -> bool:
- """CAS delivery-only fields; an older drain cannot clobber a newer run."""
- allowed = {"last_delivery_queued", "last_delivery_unverified", "last_delivery_error"}
- if not set(values) <= allowed:
- raise ValueError("Not a delivery projection")
-
- def apply(records, _i, job):
- if job.get("delivery_execution_id") != execution_id:
- return False
- # The new execution can have been claimed before it binds its projection.
- from cron.executions import latest_execution
- latest = latest_execution(job_id)
- if not latest or latest["id"] != execution_id:
- return False
- # Projection freshness: a 'queued' projection computed by a slower reconciler must
- # not resurrect job pending after the SAME execution settled terminally in the ledger.
- if values.get("last_delivery_queued") and latest.get("delivery_outcome") not in (None, "queued"):
- return False
- job.update(values)
- if job.get("last_status") == "delivery_queued" and not job.get("last_delivery_queued"):
- job["last_status"] = "delivery_failed" if job.get("last_delivery_error") else "ok"
- save_jobs(records)
- return True
- return bool(_with_job(job_id, apply))
-
-
def update_job(job_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Update a job by ID, refreshing derived schedule fields when needed."""
# ``id`` is a path component under OUTPUT_DIR — changing it would leak path-escape values.
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 070fa56b1cd..9bffddc0725 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -295,8 +295,7 @@ def _upsert_incident_for_failure(
from cron.incidents import get_incident, upsert_incident
incident_id, _is_new = upsert_incident(
- job["id"], str(error or ""), job_name=job.get("name"), output_file=output_file,
- execution_id=job.get("execution_id"))
+ job["id"], str(error or ""), job_name=job.get("name"), output_file=output_file)
incident = get_incident(incident_id)
acked = bool(incident and incident.get("state") == "closed")
return acked, incident_id
@@ -318,21 +317,14 @@ def _resolve_incidents_for_recovered_job(job: dict) -> None:
logger.debug("Incident store unavailable for job %s (delivery unaffected): %s", job["id"], exc)
-def _mark_incident_alerted(incident_id: Optional[str], execution_id: Optional[str] = None) -> None:
- """Best-effort: mark incident ``alerted`` (no-op for closed; never resurrects an acked one).
-
- Fenced to the occurrence THIS execution bound: a native alert whose run belongs to an
- older occurrence (the incident recovered and reopened meanwhile) must not mark the new one.
- """
+def _mark_incident_alerted(incident_id: Optional[str]) -> None:
+ """Best-effort: mark incident ``alerted`` (no-op for closed; never resurrects an acked one)."""
if not incident_id:
return
try:
- from cron.incidents import mark_alerted_for_execution, set_incident_state
+ from cron.incidents import set_incident_state
- if execution_id:
- mark_alerted_for_execution(incident_id, execution_id)
- else:
- set_incident_state(incident_id, "alerted")
+ set_incident_state(incident_id, "alerted")
except Exception as exc:
logger.debug("Failed marking incident %s alerted: %s", incident_id, exc)
@@ -2482,8 +2474,6 @@ def run_one_job(
job["execution_id"] = execution["id"]
execution_id = str(job["execution_id"])
- from cron.jobs import bind_delivery_execution
- bind_delivery_execution(job["id"], execution_id)
external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id
if not external_owner:
try:
@@ -2560,10 +2550,10 @@ def _classify_delivery_outcome(
normalized_deliver: str, incident_acked: bool, success: bool,
delivery_queued=None, notification_suppressed: bool = False,
) -> str:
- if should_deliver and delivery_queued:
- return "queued"
if delivery_error:
return "failed"
+ if should_deliver and delivery_queued:
+ return "queued"
if notification_suppressed:
return "suppressed"
if should_deliver and unresolved_origin:
@@ -2800,8 +2790,8 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
"""mark_job_run (owner-fenced) + execution ledger row for a run that reached delivery."""
job = d.job
if not d.should_deliver and job.get("last_delivery_queued"):
- from cron.jobs import update_delivery_projection
- update_delivery_projection(job["id"], execution_id, {"last_delivery_queued": None})
+ from cron.jobs import update_job
+ update_job(job["id"], {"last_delivery_queued": None})
job["last_delivery_queued"] = None
mark_kwargs: dict = {"delivery_error": d.delivery_error}
if not d.success and job.pop("_model_unreachable", False):
@@ -2835,7 +2825,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
)
if delivery_outcome in ("delivered", "not_configured") and not d.success:
# Failure ping left the process (or had a configured target): mark the incident alerted.
- _mark_incident_alerted(d.failure_incident_id, execution_id)
+ _mark_incident_alerted(d.failure_incident_id)
finish_execution(
execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)
return True
@@ -2875,7 +2865,7 @@ def _deliver_crash_failure(
delivery_queued=job.get("last_delivery_queued"),
notification_suppressed=bool(job.get("_notification_all_targets_suppressed")))
if delivery_outcome in ("delivered", "not_configured"):
- _mark_incident_alerted(failure_incident_id, job.get("execution_id"))
+ _mark_incident_alerted(failure_incident_id)
return delivery_error, delivery_outcome
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 945cc3b1c88..6bcf2ed1d18 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -663,18 +663,6 @@ def _get_bot_chat_delivery_timeout() -> int:
return 600
-def _mark_manifest_intent(job: dict) -> None:
- """Durable intent before ANY send of a run that has deferred (Bot Chat) targets.
-
- Raises: nothing has been sent yet, so the caller reports a truthful pre-send failure and
- sends nothing. Every exit after a successful mark settles a manifest (_settle_manifest).
- """
- if job.get("execution_id") and not job.get("_manifest_intent_marked"):
- from cron.executions import mark_delivery_manifest_pending
- mark_delivery_manifest_pending(str(job["execution_id"]))
- job["_manifest_intent_marked"] = True
-
-
_BOT_CHAT_STDERR_TAIL = 500
# stdout is the model's answer; only a short tail is persisted (jobs.json / ledger).
_BOT_CHAT_STDOUT_TAIL = 200
@@ -709,14 +697,15 @@ def _format_failure_streams(result) -> str:
return redact_sensitive_text(" | ".join(parts), force=True, redact_url_credentials=True)
-
def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optional[dict] = None,
for_failure: bool = False) -> Optional[str]:
"""Hand output to the live Bot Chat owner, or use the legacy unowned CLI lane.
None means completed; a queued/claimed receipt returns an explicit unverified status
string so existing Optional[str] callers cannot misreport admission as delivery.
- ``profile`` is ``""`` for the job's own profile.
+ ``profile`` is ``""`` for the job's own profile. A ``for_failure`` notice whose target
+ profile hides warning notifications is recorded as ``suppressed`` (a durable
+ disposition, never a send) and flagged on the job.
"""
import hashlib
import json
@@ -744,7 +733,8 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
for_failure = for_failure or bool((deferred or {}).get("for_failure"))
from gateway.warning_notifications import warning_notifications_enabled
from hermes_cli.config_effective import load_user_config_effective
- suppress_notification = for_failure and not warning_notifications_enabled("tui", load_user_config_effective(home / "config.yaml"))
+ suppress_notification = for_failure and not warning_notifications_enabled(
+ "tui", load_user_config_effective(home / "config.yaml"))
if deferred is not None and not (home / "state.db").is_file():
return f"bot-chat delivery target no longer exists: {home}; do not resend"
# run_one_job/claim_fire attach the durable execution id before delivery. The
@@ -767,8 +757,8 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
from tools.bot_live_delivery import find_canonical_owner
pending = read_pending(key)
- # Validate existing identity and settle only never-started requests under
- # the producer lock. Suppression is a durable disposition, not a send.
+ # Suppression is a durable disposition, not a send: record it under the producer
+ # lock even when a live owner exists, so the deferred lane never replays it.
if (pending is not None or suppress_notification
or (find_canonical_live_owner(home) is None and find_canonical_owner(home))):
pending = defer(key, dict(job), content, profile, home,
@@ -777,7 +767,7 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
status = pending["status"]
target = f"bot-chat:{profile_label}"
job.setdefault("_bot_chat_delivery_receipts", {})[target] = {
- "status": status, "delivery_id": key, "home": str(home)}
+ "status": status, "delivery_id": key}
if status == "suppressed":
job["_notification_all_targets_suppressed"] = True
return None if status in ("settled", "suppressed") else f"{target} {status} (receipt {key}): completion unverified; do not resend"
@@ -793,7 +783,7 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
status = receipt["status"]
target = f"bot-chat:{profile_label}"
receipts = job.setdefault("_bot_chat_delivery_receipts", {})
- receipts[target] = {"status": status, "delivery_id": key, "home": str(home)}
+ receipts[target] = {"status": status, "delivery_id": key}
logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
job_id, profile_label, key, status)
if status == "settled":
@@ -1176,11 +1166,8 @@ def _record_delivery_verification(job: dict, unverified_targets: list) -> None:
return
job.update(values)
try:
- from cron.jobs import update_delivery_projection, update_job
- if job.get("execution_id"):
- update_delivery_projection(job["id"], job["execution_id"], values)
- else:
- update_job(job["id"], values)
+ from cron.jobs import update_job
+ update_job(job["id"], values)
except Exception as exc: # pragma: no cover - defensive
logger.debug("Job '%s': could not record delivery verification: %s", job.get("id"), exc)
@@ -1792,8 +1779,6 @@ def _deliver_result(
job.pop("_bot_chat_delivery_receipts", None)
job.pop("_notification_suppressed_targets", None)
job.pop("_notification_all_targets_suppressed", None)
- job.pop("_manifest_intent_marked", None)
- job.pop("_policy_drop_errors", None)
targets = _resolve_delivery_targets(job, for_failure=for_failure)
if not targets:
_record_delivery_verification(job, [])
@@ -1810,25 +1795,15 @@ def _deliver_result(
and any(target["platform"] != BOT_CHAT_PLATFORM for target in targets)):
from cron.delivery_queue import enqueue_and_wait
- from cron.executions import record_delivery_manifest
- record_delivery_manifest(job.get("execution_id"), {"external": True})
_record_delivery_verification(job, [])
error = enqueue_and_wait(external_execution, job, content, for_failure=for_failure)
from cron.delivery_queue import get_status
delivery_status = get_status(external_execution)
if delivery_status and delivery_status["status"] == "suppressed":
job["_notification_all_targets_suppressed"] = True
- from cron.executions import get_execution, _delivery_projection, manifest_pending
- execution = get_execution(external_execution)
- projection = _delivery_projection(execution) if execution and execution.get("delivery_manifest") else None
- job["last_delivery_queued"] = (
- {"gateway": {"status": "queued", "delivery_id": external_execution}}
- if (delivery_status and delivery_status["status"] in ("pending", "delivering"))
- or manifest_pending(execution) # gateway sent children; their manifest is not recorded yet
- else projection[1]["last_delivery_queued"] if projection else None)
- from cron.jobs import update_delivery_projection
- update_delivery_projection(job["id"], external_execution,
- {"last_delivery_queued": job["last_delivery_queued"]})
+ from cron.jobs import get_job
+ refreshed = get_job(job["id"]) or {}
+ job["last_delivery_queued"] = refreshed.get("last_delivery_queued")
return error
from gateway.config import load_gateway_config
@@ -1872,7 +1847,6 @@ def _deliver_result(
"policy (missing file, denied prefix, or strict-mode miss); "
"see gateway.strict / media_delivery_allow_dirs in config.yaml"
] if _policy_dropped > 0 else []
- job["_policy_drop_errors"] = policy_drop_errors
# Resolve the mirror gate ONCE (default off): successful deliveries are appended to the target
# chat's session transcript. Mirror the CLEAN, unwrapped output (not the header/footer).
@@ -1893,38 +1867,9 @@ def _deliver_result(
return msg
delivery_errors = []
- unverified_targets: list = []
- if any(t["platform"] == BOT_CHAT_PLATFORM for t in targets) and job.get("execution_id"):
- # Durable intent BEFORE any send in this run: until the manifest lands, no reader may
- # treat this run's placeholder/absence of a manifest as terminal. Nothing has been sent,
- # so a ledger fault here is a truthful pre-send failure and nothing is sent at all.
- try:
- _mark_manifest_intent(job)
- except Exception as exc:
- msg = f"delivery ledger unavailable before send: {exc}"
- logger.error("Job '%s': %s", job["id"], msg)
- return msg
- try:
- _deliver_targets(job, targets, content, cleaned_delivery_content, media_files, adapters, loop,
- config, user_cfg, notify_delivery, mirror_enabled, mirror_text,
- for_failure, delivery_errors, unverified_targets)
- except BaseException as exc:
- # Any exit after the mark MUST settle the manifest (possibly with no children), else the
- # row is pending forever. The exception itself is retained in the manifest error, and a
- # second failure inside settlement never masks it (the row simply stays pending).
- try:
- _settle_manifest(job, targets, delivery_errors + [f"{type(exc).__name__}: {exc}"], unverified_targets)
- except BaseException as settle_exc: # noqa: BLE001 - deliberate: preserve the original
- logger.error("Job '%s': manifest settlement interrupted (%r); row stays pending",
- job.get("id"), settle_exc)
- raise
- return _settle_manifest(job, targets, delivery_errors, unverified_targets)
-
-
-def _deliver_targets(job, targets, content, cleaned_delivery_content, media_files, adapters, loop,
- config, user_cfg, notify_delivery, mirror_enabled, mirror_text,
- for_failure, delivery_errors, unverified_targets) -> None:
for target in targets:
+ # A failure notice for a platform that hides warning notifications is a suppressed
+ # disposition, not a send; requested (non-failure) results are never gated.
from gateway.warning_notifications import warning_notifications_enabled
if (for_failure and target["platform"] != BOT_CHAT_PLATFORM
and not warning_notifications_enabled(target["platform"], user_cfg)):
@@ -1932,8 +1877,7 @@ def _deliver_targets(job, targets, content, cleaned_delivery_content, media_file
continue
# Bot Chat owns admission; never concurrently resume a live owner's transcript.
if target["platform"] == BOT_CHAT_PLATFORM:
- bot_chat_error = _deliver_to_bot_chat(job, content, target["chat_id"],
- **({"for_failure": True} if for_failure else {}))
+ bot_chat_error = _deliver_to_bot_chat(job, content, target["chat_id"], for_failure=for_failure)
if job.pop("_notification_all_targets_suppressed", False):
job.setdefault("_notification_suppressed_targets", []).append(dict(target))
if bot_chat_error:
@@ -1961,58 +1905,13 @@ def _deliver_targets(job, targets, content, cleaned_delivery_content, media_file
_deliver_standalone(
t, cleaned_delivery_content, media_files, target_errors, delivery_errors)
- # Filter-time drops apply to every target; report them once.
+ # Filter-time drops apply to every target; report them once. A run whose every target was
+ # suppressed sent nothing, so there is no drop to report.
if len(job.get("_notification_suppressed_targets", [])) == len(targets):
job["_notification_all_targets_suppressed"] = True
- if not job.get("_notification_all_targets_suppressed"):
- delivery_errors.extend(job.get("_policy_drop_errors", []))
-
-
-def _settle_manifest(job: dict, targets: list, delivery_errors: list, unverified_targets: list) -> Optional[str]:
- """Record this run's child manifest (possibly empty) and return the legacy error string.
-
- Called on EVERY exit of the delivery loop once intent may have been marked: a run that
- marked intent but ends with no receipt settles through the same durable, replayable
- manifest path as one with children, so it never stays pending forever.
- """
+ else:
+ delivery_errors.extend(policy_drop_errors)
_record_delivery_verification(job, unverified_targets)
- from cron.executions import record_delivery_manifest
- bot_receipts = job.get("_bot_chat_delivery_receipts", {})
- native_count = sum(t["platform"] != BOT_CHAT_PLATFORM for t in targets)
- native_suppressed = sum(t["platform"] != BOT_CHAT_PLATFORM for t in job.get("_notification_suppressed_targets", []))
- # Only deferred receipts need mutable terminal projections. Direct native
- # sends retain legacy delivered-plus-unverified behavior when default-off.
- if bot_receipts:
- manifest = {
- "bot": bot_receipts,
- "delivered": native_count > native_suppressed or (not bot_receipts and not job.get("_notification_all_targets_suppressed")),
- "error": "; ".join(delivery_errors) if delivery_errors else None,
- "unverified": unverified_targets,
- }
- try:
- record_delivery_manifest(job.get("execution_id"), manifest)
- except Exception:
- # Post-send bookkeeping: the sends above already happened and the receipts are
- # durable. The row's pending flag (set before the first send) keeps it queued and
- # unprunable; the journal is a best-effort copy for the reconciler. Never report a
- # transport failure, which would discard the pending sibling or invite a resend.
- logger.exception("Job '%s': delivery manifest not recorded; row stays pending", job.get("id"))
- if job.get("execution_id"):
- from cron.executions import journal_manifest
- journal_manifest(str(job["execution_id"]), manifest) # never raises
- elif job.get("_manifest_intent_marked") and job.get("execution_id"):
- # Intent was marked but no child receipt exists (rejected pre-admission, filtered, or an
- # exception on the way). Settle through the same durable, replayable manifest path so
- # the row leaves pending with its errors retained; transient ledger faults replay later.
- manifest = {"bot": {}, "delivered": native_count > native_suppressed,
- "error": "; ".join(delivery_errors) if delivery_errors else None,
- "unverified": unverified_targets}
- try:
- record_delivery_manifest(job.get("execution_id"), manifest)
- except Exception:
- logger.exception("Job '%s': no-receipt manifest not recorded; row stays pending", job.get("id"))
- from cron.executions import journal_manifest
- journal_manifest(str(job["execution_id"]), manifest) # never raises
return "; ".join(delivery_errors) if delivery_errors else None
diff --git a/tests/cron/_r4_reconcile_child.py b/tests/cron/_r4_reconcile_child.py
deleted file mode 100644
index 26b917e1ddf..00000000000
--- a/tests/cron/_r4_reconcile_child.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from cron.executions import reconcile_delivery_projections
-for _ in range(3):
- reconcile_delivery_projections()
-print('reconciled')
diff --git a/tests/cron/_r4_restart.py b/tests/cron/_r4_restart.py
deleted file mode 100644
index 516ef463a7f..00000000000
--- a/tests/cron/_r4_restart.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Fresh-process bookkeeping only; never sends."""
-import sys
-from cron import executions
-if int(sys.argv[1]):
- original=executions._store_manifest
- def failed(conn,eid,manifest):
- if 'bot' in manifest:raise OSError('injected persistent SQLite manifest write failure after restart')
- return original(conn,eid,manifest)
- executions._store_manifest=failed
-for _ in range(int(sys.argv[2])):executions.reconcile_delivery_projections()
-print('RECONCILED')
diff --git a/tests/cron/_r5_nested_driver.py b/tests/cron/_r5_nested_driver.py
deleted file mode 100644
index eb7961b7f69..00000000000
--- a/tests/cron/_r5_nested_driver.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""Called by actual outer job script; inner executes through manual-run API."""
-import json, os, sys
-from pathlib import Path
-REPO=str(next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists()))
-sys.path.insert(0,REPO)
-os.environ['PYTHONPATH']=REPO
-from cron import jobs, executions
-assert Path(executions.__file__).is_relative_to(REPO), executions.__file__
-from tools.cronjob_tools import _execute_job_now
-home=Path(os.environ['HERMES_HOME'])
-inner=jobs.create_job(prompt=None,schedule='every 1h',script='fail.sh',no_agent=True,deliver='bot-chat')
-with executions._transaction() as conn:
- conn.execute('''CREATE TRIGGER nested_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions
- WHEN NEW.delivery_manifest LIKE '%"bot"%' BEGIN SELECT RAISE(ABORT,'nested manifest fault'); END''')
-result=_execute_job_now(inner)
-(home/'inner-proof.json').write_text(json.dumps({'outer_env':os.environ.get('_HERMES_CRON_EXTERNAL_WORKER'),'inner':executions.latest_execution(inner['id']),'result':result}))
diff --git a/tests/cron/_r5_prior_executions.py b/tests/cron/_r5_prior_executions.py
deleted file mode 100644
index 62e7f7f8f1f..00000000000
--- a/tests/cron/_r5_prior_executions.py
+++ /dev/null
@@ -1,598 +0,0 @@
-"""Profile-local durable audit ledger for cron execution attempts.
-
-The ledger records what is known about each attempt; it is not a retry queue. Interrupted attempts
-become ``unknown`` only after their exact owner process is proved gone. Terminal states are
-immutable.
-"""
-
-from __future__ import annotations
-
-import os
-import json
-import logging
-import sqlite3
-import threading
-import time
-import uuid
-from contextlib import contextmanager
-from pathlib import Path
-from typing import Any, Dict, Iterator, List, Optional
-
-from hermes_constants import get_hermes_home
-from hermes_time import now as _hermes_now
-
-# Optional test override. Production resolves the path at transaction time so dashboard operations
-# that temporarily enter another profile cannot leak that profile's records into the import-time
-# home.
-EXECUTIONS_FILE: Optional[Path] = None
-MAX_TERMINAL_EXECUTIONS = 1000
-HANDOFF_ADOPTION_GRACE_SECONDS = 30.0
-_TERMINAL_STATES = ("completed", "failed", "unknown")
-_lock = threading.RLock()
-_PROCESS_ID = uuid.uuid4().hex
-
-
-# --- executions ledger --------------------------------------------------------------------------
-
-def _connect() -> sqlite3.Connection:
- # Late imports: a scheduler daemon that outlives an on-disk upgrade already has the OLD
- # ``hermes_cli.sqlite_util`` / ``cron.jobs`` cached, so new names must be resolved at call time,
- # not at import time (the guarantee cron/ledger.py used to carry, see e24c8499).
- from cron.jobs import _ensure_cron_dir
- from hermes_cli.sqlite_util import open_db
-
- path = EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db")
- _ensure_cron_dir(path.parent)
- return open_db(path, db_label="cron/executions.db", synchronous_full=True, initialize=_initialize_schema)
-
-
-def _initialize_schema(conn: sqlite3.Connection) -> None:
- from hermes_cli.sqlite_util import add_column_if_missing
-
- conn.execute(
- """CREATE TABLE IF NOT EXISTS executions (
- id TEXT PRIMARY KEY,
- job_id TEXT NOT NULL,
- source TEXT NOT NULL,
- process_id TEXT NOT NULL,
- pid INTEGER NOT NULL,
- process_started_at INTEGER,
- status TEXT NOT NULL CHECK(status IN
- ('claimed','running','completed','failed','unknown')),
- handoff_pending INTEGER NOT NULL DEFAULT 0,
- handoff_started_at REAL,
- claimed_at TEXT NOT NULL,
- started_at TEXT,
- finished_at TEXT,
- error TEXT
- )"""
- )
- add_column_if_missing(
- conn, "executions", "handoff_pending",
- "handoff_pending INTEGER NOT NULL DEFAULT 0",
- )
- add_column_if_missing(
- conn, "executions", "handoff_started_at", "handoff_started_at REAL"
- )
- conn.execute(
- "CREATE INDEX IF NOT EXISTS idx_executions_job_claimed "
- "ON executions(job_id, claimed_at DESC, id DESC)"
- )
- conn.execute(
- "CREATE INDEX IF NOT EXISTS idx_executions_status_claimed "
- "ON executions(status, claimed_at DESC, id DESC)"
- )
- add_column_if_missing(conn, "executions", "delivery_manifest", "delivery_manifest TEXT")
- add_column_if_missing(conn, "executions", "incident_id", "incident_id TEXT")
- add_column_if_missing(conn, "executions", "incident_generation", "incident_generation INTEGER")
- add_column_if_missing(conn, "executions", "delivery_projection_settled", "delivery_projection_settled INTEGER NOT NULL DEFAULT 0")
- add_column_if_missing(conn, "executions", "delivery_outcome", "delivery_outcome TEXT")
- add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT")
- conn.execute(
- "CREATE INDEX IF NOT EXISTS idx_executions_occurrence "
- "ON executions(job_id, scheduled_instant) WHERE status='completed'"
- )
-
-
-@contextmanager
-def _transaction() -> Iterator[sqlite3.Connection]:
- from hermes_cli.sqlite_util import transaction
-
- with _lock, transaction(_connect()) as conn:
- yield conn
-
-
-def _fetch(conn: sqlite3.Connection, execution_id: str) -> Optional[Dict[str, Any]]:
- row = conn.execute("SELECT * FROM executions WHERE id=?", (execution_id,)).fetchone()
- return dict(row) if row is not None else None
-
-
-def _emit_execution_state(
- record: Optional[Dict[str, Any]], *, delivery_outcome: Optional[str] = None
-) -> None:
- """Project durable state to monitoring without affecting ledger behavior."""
- try:
- from agent.monitoring.cron_health import emit_execution_state
-
- emit_execution_state(record, delivery_outcome=delivery_outcome)
- except Exception:
- pass
-
-
-def _process_start_time(pid: int) -> Optional[int]:
- try:
- from gateway.status import get_process_start_time
- return get_process_start_time(pid)
- except Exception:
- return None
-
-
-def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
- try:
- from gateway.status import _pid_exists
- if not _pid_exists(pid):
- return False
- except Exception:
- return True # fail safe: inability to prove death must not rewrite state
- if started_at is None:
- return pid == os.getpid()
- current = _process_start_time(pid)
- return current is not None and current == started_at
-
-
-def _prune_unlocked(conn: sqlite3.Connection) -> None:
- conn.execute(
- """DELETE FROM executions WHERE id IN (
- SELECT id FROM executions
- WHERE status IN ('completed','failed','unknown')
- AND (delivery_outcome IS NULL OR delivery_outcome != 'queued')
- AND (delivery_manifest IS NULL OR delivery_projection_settled=1)
- ORDER BY finished_at DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
- )""",
- (max(0, int(MAX_TERMINAL_EXECUTIONS)),),
- )
-
-
-def create_execution(
- job_id: str, *, source: str, scheduled_instant: Optional[str] = None,
-) -> Dict[str, Any]:
- """Persist a claimed attempt before executor/provider dispatch."""
- from cron.occurrences import scheduled_instant as canonical_instant
-
- now = _hermes_now().isoformat()
- execution_id = uuid.uuid4().hex
- pid = os.getpid()
- with _transaction() as conn:
- conn.execute(
- """INSERT INTO executions
- (id, job_id, source, process_id, pid, process_started_at,
- status, claimed_at, scheduled_instant)
- VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?)""",
- (execution_id, str(job_id), str(source), _PROCESS_ID, pid,
- _process_start_time(pid), now, canonical_instant(scheduled_instant)),
- )
- record = _fetch(conn, execution_id)
- _emit_execution_state(record)
- return record # type: ignore[return-value]
-
-
-def set_execution_occurrence(execution_id: str, instant: Optional[str]) -> None:
- """Bind the store-claimed snapshot before a provider hands it to a worker."""
- from cron.occurrences import scheduled_instant
-
- with _transaction() as conn:
- cur = conn.execute(
- "UPDATE executions SET scheduled_instant=? WHERE id=? AND status='claimed' "
- "AND handoff_pending=0 AND process_id=? AND pid=?",
- (scheduled_instant(instant), execution_id, _PROCESS_ID, os.getpid()),
- )
- if cur.rowcount != 1:
- raise RuntimeError("Cron occurrence could not be bound before dispatch")
-
-
-def mark_execution_handoff_pending(execution_id: str) -> Optional[Dict[str, Any]]:
- """Fence restart recovery while an external worker is adopting a claim."""
- with _transaction() as conn:
- cur = conn.execute(
- """UPDATE executions
- SET handoff_pending=1, handoff_started_at=?
- WHERE id=? AND status='claimed'
- AND process_id=? AND pid=?""",
- (time.time(), execution_id, _PROCESS_ID, os.getpid()),
- )
- if cur.rowcount != 1:
- return None
- record = _fetch(conn, execution_id)
- _emit_execution_state(record)
- return record
-
-
-def adopt_claimed_execution(execution_id: str) -> Optional[Dict[str, Any]]:
- """Atomically transfer and start an attempt in its worker process.
-
- The dispatching gateway creates the row before spawning a restart-safe
- worker. Adoption is the single ``claimed`` → ``running`` gate: only the
- winner may acknowledge ownership or run side effects.
- """
- pid = os.getpid()
- process_started_at = _process_start_time(pid)
- now = _hermes_now().isoformat()
- with _transaction() as conn:
- cur = conn.execute(
- """UPDATE executions
- SET process_id=?, pid=?, process_started_at=?,
- status='running', started_at=?, handoff_pending=0,
- handoff_started_at=NULL
- WHERE id=? AND status='claimed' AND handoff_pending=1""",
- (_PROCESS_ID, pid, process_started_at, now, execution_id),
- )
- if cur.rowcount != 1:
- return None
- record = _fetch(conn, execution_id)
- _emit_execution_state(record)
- return record
-
-
-def mark_execution_running(execution_id: str) -> Optional[Dict[str, Any]]:
- """Transition one claimed attempt to running exactly once."""
- now = _hermes_now().isoformat()
- with _transaction() as conn:
- cur = conn.execute(
- """UPDATE executions
- SET status='running', started_at=?, handoff_pending=0,
- handoff_started_at=NULL
- WHERE id=? AND status='claimed' AND handoff_pending=0
- AND process_id=? AND pid=?""",
- (now, execution_id, _PROCESS_ID, os.getpid()),
- )
- if cur.rowcount != 1:
- return None
- record = _fetch(conn, execution_id)
- _emit_execution_state(record)
- return record
-
-
-def finish_execution(
- execution_id: str, *, success: bool, error: Optional[str] = None,
- delivery_outcome: Optional[str] = None,
-) -> Optional[Dict[str, Any]]:
- """Write a terminal result once; terminal attempts cannot be rewritten."""
- now = _hermes_now().isoformat()
- status = "completed" if success else "failed"
- detail = None if success else (str(error) if error else "unknown failure")
- # A worker may observe a terminal receipt during its wait. Use the same durable
- # classification as restart reconciliation, in particular unknown != failed.
- with _transaction() as conn:
- pending = _fetch(conn, execution_id)
- if pending and pending.get("delivery_manifest"):
- projection = _delivery_projection(pending)
- if projection is not None:
- delivery_outcome = projection[0]
- cur = conn.execute(
- """UPDATE executions
- SET status=?, finished_at=?, error=?, handoff_pending=0,
- handoff_started_at=NULL, delivery_outcome=?
- WHERE id=? AND status IN ('claimed','running')
- AND process_id=? AND pid=?""",
- (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid()),
- )
- if cur.rowcount != 1:
- return None
- _prune_unlocked(conn)
- record = _fetch(conn, execution_id)
- _emit_execution_state(record, delivery_outcome=delivery_outcome)
- if record and record.get("delivery_manifest"):
- reconcile_delivery_projections()
- return record
-
-
-def bind_delivery_incident(execution_id: Optional[str], incident_id: str) -> None:
- """Persist the producer's actual incident association, never infer it from errors."""
- if execution_id:
- with _transaction() as conn:
- from cron.incidents import _initialize_schema as init_incidents
- init_incidents(conn)
- _bind_delivery_incident_unlocked(conn, execution_id, incident_id)
-
-
-def _bind_delivery_incident_unlocked(conn, execution_id: str, incident_id: str) -> None:
- """Called in the producer's incident upsert transaction; no later generation lookup."""
- conn.execute("UPDATE executions SET incident_id=?, incident_generation="
- "(SELECT generation FROM cron_incidents WHERE id=?) "
- "WHERE id=? AND incident_id IS NULL "
- "AND status IN ('claimed','running') AND process_id=? AND pid=?",
- (incident_id, incident_id, execution_id, _PROCESS_ID, os.getpid()))
-
-
-def record_delivery_manifest(execution_id: Optional[str], manifest: dict) -> None:
- """Retain receipt identities and sibling disposition separately from the run result.
-
- The worker may first bind the external handoff; its gateway replaces that placeholder
- with the resolved target receipts. No payload or raw output is copied here.
- """
- if not execution_id:
- return
- with _transaction() as conn:
- _store_manifest(conn, execution_id, manifest)
-
-
-def _store_manifest(conn, execution_id: str, manifest: dict) -> None:
- """CAS the manifest onto a row that has none (or only the external placeholder)."""
- placeholder = json.dumps({"external": True}, sort_keys=True)
- row = _fetch(conn, execution_id)
- if row and row.get("delivery_manifest") == placeholder:
- manifest = {**manifest, "external": True}
- conn.execute("UPDATE executions SET delivery_manifest=? WHERE id=? AND "
- "(delivery_manifest IS NULL OR delivery_manifest=?)",
- (json.dumps(manifest, sort_keys=True), execution_id, placeholder))
-
-
-def _journal_root() -> Path:
- return (EXECUTIONS_FILE.parent if EXECUTIONS_FILE else get_hermes_home().resolve() / "cron") / "manifest_journal"
-
-
-def journal_manifest(execution_id: str, manifest: dict) -> None:
- """Durably record a delivery manifest the ledger could not store (post-send fault).
-
- Source-owned: independent of which receipt store (deferred file or live-owner mailbox)
- holds the children, and never mutated by receipt consumers. Replayed by
- :func:`_recover_unrecorded_manifests`; deleted only after the ledger holds it.
- """
- from utils import atomic_json_write
- root = _journal_root()
- root.mkdir(parents=True, exist_ok=True, mode=0o700)
- atomic_json_write(root / f"{execution_id}.json", {"execution_id": execution_id, "manifest": manifest},
- fsync_dir=True, mode=0o600)
-
-
-def journaled_manifests() -> Dict[str, dict]:
- root = _journal_root()
- if not root.is_dir():
- return {}
- out: Dict[str, dict] = {}
- for path in root.glob("*.json"):
- try:
- record = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError, UnicodeDecodeError):
- logging.getLogger(__name__).error("Unreadable cron manifest journal entry %s", path)
- continue
- if record.get("execution_id") and record.get("manifest"):
- out[record["execution_id"]] = record["manifest"]
- return out
-
-
-def _recover_unrecorded_manifests() -> Dict[str, dict]:
- """Replay journaled manifests into the ledger; return what is STILL outstanding.
-
- Idempotent through the same CAS as the primary write. An entry is removed only once
- the ledger row actually carries a manifest with the children; while outstanding, the
- row's placeholder manifest must not be projected or pruned (see callers).
- """
- outstanding: Dict[str, dict] = {}
- for execution_id, manifest in journaled_manifests().items():
- try:
- with _transaction() as conn:
- row = _fetch(conn, execution_id)
- if row is None:
- outstanding[execution_id] = manifest
- continue
- _store_manifest(conn, execution_id, manifest)
- row = _fetch(conn, execution_id)
- stored = json.loads(row["delivery_manifest"]) if row and row.get("delivery_manifest") else {}
- if stored.get("bot") == manifest.get("bot"):
- (_journal_root() / f"{execution_id}.json").unlink(missing_ok=True)
- else:
- outstanding[execution_id] = manifest
- except Exception:
- logging.getLogger(__name__).exception("Could not replay journaled cron manifest %s", execution_id)
- outstanding[execution_id] = manifest
- return outstanding
-
-
-def _delivery_projection(record: dict) -> Optional[tuple[str, dict]]:
- from cron import delivery_queue, bot_chat_delivery
- from tools.bot_live_delivery import read_delivery_result
-
- manifest = json.loads(record["delivery_manifest"])
- external_outcome = None
- external_error = None
- if manifest.get("external"):
- receipt = delivery_queue.get_status(record["id"])
- if not receipt or receipt["status"] in ("pending", "delivering"):
- return None
- outcome = receipt["status"]
- external_outcome, external_error = outcome, receipt.get("error")
- if not manifest.get("bot"):
- return outcome, {"last_delivery_queued": None, "last_delivery_unverified": None,
- "last_delivery_error": receipt.get("error")}
-
- queued = {}
- states = []
- for target, ref in manifest.get("bot", {}).items():
- receipt = read_delivery_result(Path(ref["home"]), ref["delivery_id"])
- if receipt is None:
- receipt = bot_chat_delivery.read_pending(ref["delivery_id"])
- status = (receipt or ref)["status"]
- if status in ("queued", "claimed", "transferred"):
- queued[target] = {**ref, "status": status}
- states.append(status)
- error = manifest.get("error") or external_error
- unverified = manifest.get("unverified")
- if queued:
- outcome = "queued"
- elif external_outcome == "unknown" or "ambiguous" in states or "unknown" in states or unverified:
- outcome = "unknown"
- elif external_outcome == "failed" or "failed" in states or error:
- outcome = "failed"
- elif manifest.get("delivered") or "settled" in states:
- outcome = "delivered"
- else:
- outcome = "suppressed"
- if outcome in ("failed", "unknown") and not error:
- error = "Deferred delivery completion unverified; do not resend"
- return outcome, {"last_delivery_queued": queued or None,
- "last_delivery_unverified": unverified or None,
- "last_delivery_error": error}
-
-
-def reconcile_delivery_projections() -> None:
- """Replay durable receipts, never sends. Safe after either store write or restart.
-
- Only delivery_outcome can change after run completion. The queued CAS and manifest
- comparison fence racing reconcilers; execution status/error/timestamps are untouched.
- Retaining manifests also repairs a crash between the ledger and jobs/incident writes.
- """
- import logging
- from cron.jobs import update_delivery_projection
- from cron.incidents import _initialize_schema as init_incidents
-
- try:
- outstanding = _recover_unrecorded_manifests()
- except Exception:
- logging.getLogger(__name__).exception("Could not replay journaled cron delivery manifests")
- outstanding = journaled_manifests()
- with _transaction() as conn:
- records = [dict(row) for row in conn.execute(
- "SELECT * FROM executions WHERE delivery_manifest IS NOT NULL "
- "AND status IN ('completed','failed','unknown')").fetchall()]
- for record in records:
- if record["id"] in outstanding:
- # The ledger holds at most the external placeholder for this run while its real
- # manifest (with pending children) is journaled: an incomplete manifest must not be
- # projected as a terminal disposition. Stay queued until the replay succeeds.
- continue
- try:
- projection = _delivery_projection(record)
- if projection is None:
- continue
- outcome, values = projection
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_outcome=? WHERE id=? "
- "AND delivery_outcome='queued' AND delivery_manifest=?",
- (outcome, record["id"], record["delivery_manifest"]))
- current = _fetch(conn, record["id"])
- if not current or current["delivery_outcome"] != outcome:
- continue
- if outcome == "delivered" and record.get("incident_id"):
- init_incidents(conn)
- # Late completion cannot resurrect resolved/acked incidents.
- conn.execute("UPDATE cron_incidents SET state='alerted' WHERE id=? "
- "AND state='detected' AND generation=?",
- (record["incident_id"], record.get("incident_generation")))
- update_delivery_projection(record["job_id"], record["id"], values)
- if outcome != "queued":
- # Pin the receipt association until BOTH durable projections have
- # completed. A crash above leaves it replayable even under retention.
- with _transaction() as conn:
- conn.execute("UPDATE executions SET delivery_projection_settled=1 "
- "WHERE id=? AND delivery_outcome=? AND delivery_manifest=?",
- (record["id"], outcome, record["delivery_manifest"]))
- except Exception:
- logging.getLogger(__name__).exception(
- "Could not reconcile cron delivery %s; durable receipt retained", record["id"])
-
-
-def recover_interrupted_executions() -> int:
- """Mark provably abandoned attempts unknown without scheduling retries."""
- now = _hermes_now().isoformat()
- changed = 0
- recovered: List[Dict[str, Any]] = []
- with _transaction() as conn:
- rows = conn.execute(
- """SELECT id, status, process_id, pid, process_started_at,
- handoff_pending, handoff_started_at
- FROM executions
- WHERE status IN ('claimed','running')"""
- ).fetchall()
- for row in rows:
- if row["process_id"] == _PROCESS_ID:
- continue
- if _owner_is_live(int(row["pid"]), row["process_started_at"]):
- continue
- handoff_started_at = row["handoff_started_at"]
- if (
- row["handoff_pending"]
- and handoff_started_at is not None
- and time.time() - float(handoff_started_at)
- < HANDOFF_ADOPTION_GRACE_SECONDS
- ):
- continue
- cur = conn.execute(
- """UPDATE executions
- SET status='unknown', finished_at=?, error=?,
- handoff_pending=0, handoff_started_at=NULL
- WHERE id=? AND status=? AND process_id=? AND pid=?
- AND handoff_pending=?
- AND handoff_started_at IS ?""",
- (now,
- "Scheduler restarted after this execution's owner exited before a durable "
- "terminal state; whether side effects ran is unknown.",
- row["id"], row["status"], row["process_id"], row["pid"],
- row["handoff_pending"], row["handoff_started_at"]),
- )
- changed += cur.rowcount
- if cur.rowcount:
- record = _fetch(conn, row["id"])
- if record is not None:
- recovered.append(record)
- if changed:
- _prune_unlocked(conn)
- for record in recovered:
- _emit_execution_state(record)
- return changed
-
-
-def list_executions(
- *, job_id: Optional[str] = None, limit: int = 50, before_claimed_at: Optional[str] = None,
-) -> List[Dict[str, Any]]:
- """Return indexed, newest-first execution history with cursor pagination."""
- clauses: List[str] = []
- params: List[Any] = []
- if job_id is not None:
- clauses.append("job_id=?")
- params.append(str(job_id))
- if before_claimed_at is not None:
- clauses.append("claimed_at < ?")
- params.append(str(before_claimed_at))
- where = " WHERE " + " AND ".join(clauses) if clauses else ""
- params.append(max(1, min(int(limit), 500)))
- with _transaction() as conn:
- rows = conn.execute(
- "SELECT * FROM executions" + where
- + " ORDER BY claimed_at DESC, id DESC LIMIT ?",
- params,
- ).fetchall()
- return [dict(row) for row in rows]
-
-
-def get_execution(execution_id: str) -> Optional[Dict[str, Any]]:
- """Return one exact execution attempt, or ``None`` when it is absent."""
- with _transaction() as conn:
- row = conn.execute(
- "SELECT * FROM executions WHERE id=?",
- (str(execution_id),),
- ).fetchone()
- return dict(row) if row is not None else None
-
-
-def latest_execution(job_id: str) -> Optional[Dict[str, Any]]:
- rows = list_executions(job_id=job_id, limit=1)
- return rows[0] if rows else None
-
-
-def latest_executions(job_ids: List[str]) -> Dict[str, Dict[str, Any]]:
- """Load latest execution for many jobs in one indexed query."""
- clean = [str(job_id) for job_id in dict.fromkeys(job_ids) if job_id]
- if not clean:
- return {}
- placeholders = ",".join("?" for _ in clean)
- with _transaction() as conn:
- rows = conn.execute(
- f"""SELECT e.* FROM executions e
- WHERE e.job_id IN ({placeholders})
- AND e.id=(SELECT e2.id FROM executions e2
- WHERE e2.job_id=e.job_id
- ORDER BY e2.claimed_at DESC, e2.id DESC LIMIT 1)""",
- clean,
- ).fetchall()
- return {row["job_id"]: dict(row) for row in rows}
diff --git a/tests/cron/_r7_exit_child.py b/tests/cron/_r7_exit_child.py
deleted file mode 100644
index b47aee7efe6..00000000000
--- a/tests/cron/_r7_exit_child.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Intentionally exit immediately for real dead-owner probes."""
diff --git a/tests/cron/_r7_initializer_worker.py b/tests/cron/_r7_initializer_worker.py
deleted file mode 100644
index 502731b0a68..00000000000
--- a/tests/cron/_r7_initializer_worker.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""Independent initializer process, synchronization only at inventory boundary."""
-import json, os, sys, time
-from pathlib import Path
-from cron import executions as ex
-home, barrier, name = map(Path, sys.argv[1:])
-ex.EXECUTIONS_FILE=home/'cron'/'executions.db'
-real_inventory=ex._journal_inventory_strict
-real_adopt=ex._try_adopt_legacy_intent
-trace=[]; entry=[]
-def inventory():
- result=real_inventory()
- (barrier/(str(name)+'.ready')).write_text('ready')
- deadline=time.monotonic()+20
- while not (barrier/'go').exists():
- if time.monotonic()>deadline: raise TimeoutError('barrier')
- time.sleep(.01)
- return result
-def adopt(conn):
- entry.append({'in_transaction':conn.in_transaction,'isolation_level':conn.isolation_level,'journal_mode':conn.execute('PRAGMA journal_mode').fetchone()[0]})
- conn.set_trace_callback(trace.append)
- return real_adopt(conn)
-ex._journal_inventory_strict=inventory
-ex._try_adopt_legacy_intent=adopt
-rows=ex.list_executions()
-print(json.dumps({'name':str(name),'entry':entry,'trace':trace,'pending':[r['delivery_manifest_pending'] for r in rows],'adopted':ex._legacy_intent_adopted()}))
diff --git a/tests/cron/_r7_old_writer.py b/tests/cron/_r7_old_writer.py
deleted file mode 100644
index 5d2e75bc142..00000000000
--- a/tests/cron/_r7_old_writer.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Load exact R4 fixture before upgrade; publish only on parent signal."""
-import json, sys, time
-from pathlib import Path
-from tests.cron.test_r5_salt_legacy_and_races import prior, receipt
-from cron import delivery_queue as dq
-home=Path(sys.argv[1]);eid=sys.argv[2];barrier=Path(sys.argv[3])
-old=prior();old.EXECUTIONS_FILE=home/'cron'/'executions.db'
-dq.DELIVERY_DB=home/'cron'/'deliveries.db'
-assert old.get_execution(eid)['delivery_manifest']=='{"external": true}'
-assert dq.claim_next()['execution_id']==eid
-(barrier/'ready').write_text('loaded old module')
-deadline=time.monotonic()+20
-while not (barrier/'go').exists():
- if time.monotonic()>deadline: raise TimeoutError('writer release')
- time.sleep(.01)
-manifest=receipt(home,eid)
-old.journal_manifest(eid,manifest)
-assert dq._finish(eid,error=None)
-print(json.dumps({'manifest':manifest,'external':dq.get_status(eid)}))
diff --git a/tests/cron/_r7_restart_read.py b/tests/cron/_r7_restart_read.py
deleted file mode 100644
index 0513cc9132a..00000000000
--- a/tests/cron/_r7_restart_read.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import json, sys
-from pathlib import Path
-from cron import executions as ex, delivery_queue as dq, jobs
-home=Path(sys.argv[1]);eid=sys.argv[2]
-ex.EXECUTIONS_FILE=home/'cron'/'executions.db';dq.DELIVERY_DB=home/'cron'/'deliveries.db'
-ex.reconcile_delivery_projections()
-print(json.dumps({'execution':ex.get_execution(eid),'job':jobs.get_job('child-job'),'journal':ex.journaled_manifests()}))
diff --git a/tests/cron/_r8_child.py b/tests/cron/_r8_child.py
deleted file mode 100644
index 9aa1e5cb602..00000000000
--- a/tests/cron/_r8_child.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Evidence subprocess: real old journal writer / current replay / fresh read."""
-import json, os, sys, time
-from pathlib import Path
-from cron import executions as ex, delivery_queue as dq
-from tests.cron.test_r5_salt_legacy_and_races import prior, receipt, snap
-home=Path(sys.argv[2]); eid=sys.argv[3]
-ex.EXECUTIONS_FILE=home/'cron'/'executions.db'
-dq.DELIVERY_DB=home/'cron'/'deliveries.db'
-mode=sys.argv[1]
-if mode=='replay':
- ex._recover_unrecorded_manifests()
- print(json.dumps(snap(eid)))
-elif mode=='read':
- ex.reconcile_delivery_projections()
- print(json.dumps(snap(eid)))
-elif mode=='writer':
- barrier=Path(sys.argv[4]); old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- assert old.get_execution(eid)
- assert dq.claim_next()['execution_id']==eid
- (barrier/'ready').write_text('old module loaded, external claimed')
- deadline=time.monotonic()+25
- while not (barrier/'publish').exists():
- assert time.monotonic()<deadline
- time.sleep(.005)
- manifest=receipt(home,eid)
- old.journal_manifest(eid,manifest)
- assert (old._journal_root()/f'{eid}.json').is_file()
- (barrier/'published').write_text(json.dumps(manifest))
- while not (barrier/'complete').exists():
- assert time.monotonic()<deadline
- time.sleep(.005)
- assert dq._finish(eid,error=None)
- print(json.dumps({'manifest':manifest,'external':dq.get_status(eid)}))
-else: raise ValueError(mode)
diff --git a/tests/cron/test_cron_live_bot_delivery.py b/tests/cron/test_cron_live_bot_delivery.py
index 4889a267c6a..70fbd6ccc78 100644
--- a/tests/cron/test_cron_live_bot_delivery.py
+++ b/tests/cron/test_cron_live_bot_delivery.py
@@ -42,7 +42,7 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypat
def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):
- from cron import jobs, executions
+ from cron import jobs
from gateway import config
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -53,23 +53,18 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):
monkeypatch.setattr(delivery._sched, "load_config", lambda: {})
monkeypatch.setattr(config, "load_gateway_config", lambda: None)
monkeypatch.setattr(delivery.subprocess, "run", Mock(side_effect=AssertionError("CLI")))
- job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="bot-chat")
- execution = executions.create_execution(job["id"], source="test")
- job["execution_id"] = execution["id"]
- jobs.bind_delivery_execution(job["id"], execution["id"])
+ updates = []
+ monkeypatch.setattr(jobs, "update_job", lambda key, values: updates.append(values))
+ job = dict(id="digest", execution_id="run", deliver="bot-chat")
error = delivery._deliver_result(job, "payload")
assert error is None
- queued = jobs.get_job(job["id"])["last_delivery_queued"]
+ queued = updates[-1]["last_delivery_queued"]
assert queued and next(iter(queued.values()))["status"] == "queued"
assert delivery._sched._classify_delivery_outcome(
delivery_error=error, delivery_queued=queued, should_deliver=True, unresolved_origin=False,
normalized_deliver="bot-chat", incident_acked=False, success=True) == "queued"
- executions.finish_execution(execution["id"], success=True, delivery_outcome="queued")
record = mailbox.claim_pending_delivery(tmp_path, owner)
assert record is not None
mailbox.complete_delivery(tmp_path, record["delivery_id"], status="settled", reply="done")
- from cron.bot_chat_delivery import drain
- drain() # housekeeping, not another delivery attempt, refreshes the durable projection
- assert jobs.get_job(job["id"])["last_delivery_queued"] is None
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
assert delivery._deliver_result(job, "payload") is None
+ assert updates[-1]["last_delivery_queued"] is None
diff --git a/tests/cron/test_deferred_warning_projection.py b/tests/cron/test_deferred_warning_projection.py
deleted file mode 100644
index 93424637835..00000000000
--- a/tests/cron/test_deferred_warning_projection.py
+++ /dev/null
@@ -1,219 +0,0 @@
-"""Queue admission is not delivery; late suppression updates exact projections."""
-import json
-
-import pytest
-from cron import executions, incidents, jobs, scheduler, delivery_queue
-from gateway.config import GatewayConfig, Platform, PlatformConfig
-
-
[email protected]("setting", [None, False, True])
[email protected]("exit_code", [0, 7])
-def test_external_timeout_then_drain_reconciles_exact_failed_execution(tmp_path, monkeypatch, setting, exit_code):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
- cfg = {"cron": {"wrap_response": False, "preflight": False}}
- if setting is not None:
- cfg["display"] = {"suppress_warning_notifications": setting}
- (tmp_path / "config.yaml").write_text(json.dumps(cfg))
- config = GatewayConfig()
- config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
- monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
- sent = []
- async def send(platform, pconfig, chat_id, text, **kwargs):
- sent.append(text)
- return {"success": True, "message_id": "recorded-send"}
- monkeypatch.setattr("tools.send_message_tool._send_to_platform", send)
- scripts = tmp_path / "scripts"
- scripts.mkdir()
- (scripts / "failure.sh").write_text("#!/bin/sh\nprintf 'retained stdout\\n'\nprintf 'diagnostic stderr\\n' >&2\nexit 7\n")
- script = scripts / "failure.sh"
- script.write_text(script.read_text().replace("exit 7", f"exit {exit_code}"))
- job = jobs.create_job(prompt=None, schedule="every 1h", script="failure.sh", no_agent=True, deliver="telegram:fixture")
- execution = executions.create_execution(job["id"], source="test-external")
- job["execution_id"] = execution["id"]
- monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])
- wait = delivery_queue.enqueue_and_wait
- monkeypatch.setattr(delivery_queue, "enqueue_and_wait",
- lambda execution_id, job, content, for_failure=False: wait(execution_id, job, content, for_failure=for_failure, timeout=0))
- scheduler.run_one_job(job)
- before = executions.get_execution(execution["id"])
- assert delivery_queue.get_status(execution["id"])["status"] == "pending"
- assert not sent
- assert before["status"] == ("failed" if exit_code else "completed")
- assert before["delivery_outcome"] == "queued"
- if exit_code:
- incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])
- assert incident["state"] == "detected"
- assert scheduler.drain_delivery_queue({}, None) == 1
- assert scheduler.drain_delivery_queue({}, None) == 0
- after = executions.get_execution(execution["id"])
- muted = setting is True and exit_code != 0
- expected = "suppressed" if muted else "delivered"
- assert delivery_queue.get_status(execution["id"])["status"] == expected
- assert after["delivery_outcome"] == expected
- assert after["status"] == before["status"]
- assert after["error"] == before["error"]
- assert len(sent) == (0 if muted else 1)
- if exit_code:
- incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])
- assert incident["state"] == ("detected" if muted else "alerted")
- outputs = list((tmp_path / "cron" / "output" / job["id"]).glob("*.md"))
- assert outputs and "retained stdout" in outputs[0].read_text()
- assert not jobs.get_job(job["id"]).get("last_delivery_queued")
-
-
-
[email protected]("sibling", ["none", "delivered", "ambiguous"])
-def test_bot_chat_late_suppression_reconciles_after_reopen(tmp_path, monkeypatch, sibling):
- from cron import bot_chat_delivery
- from hermes_state import SessionDB
- from hermes_cli.active_sessions import try_acquire_active_session
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
- (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}\n")
- db = SessionDB(db_path=tmp_path / "state.db")
- db.create_session(session_id="bot", source="cli")
- db.set_session_title("bot", "Bot Chat")
- lease, refusal = try_acquire_active_session(session_id="bot", surface="cli", config={}, registry_home=tmp_path)
- assert refusal is None
- try:
- monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (False, "raw evidence", "", "failure evidence"))
- job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="bot-chat")
- scheduler.run_one_job(job)
- before = executions.latest_execution(job["id"])
- assert before["delivery_outcome"] == "queued"
- key = next(iter(jobs.get_job(job["id"])["last_delivery_queued"].values()))["delivery_id"]
- if sibling != "none":
- # A sibling's durable disposition must survive this target's suppression.
- with executions._transaction() as conn:
- manifest = json.loads(conn.execute("SELECT delivery_manifest FROM executions WHERE id=?", (before["id"],)).fetchone()[0])
- manifest["delivered"] = sibling == "delivered"
- manifest["unverified"] = ["ambiguous sibling"] if sibling == "ambiguous" else []
- conn.execute("UPDATE executions SET delivery_manifest=? WHERE id=?", (json.dumps(manifest), before["id"]))
- (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}\n")
- bot_chat_delivery.drain()
- bot_chat_delivery.drain()
- assert bot_chat_delivery.read_pending(key)["status"] == "suppressed"
- after = executions.get_execution(before["id"])
- assert after["delivery_outcome"] == {"none": "suppressed", "delivered": "delivered", "ambiguous": "unknown"}[sibling]
- assert after["error"] == before["error"]
- assert after["finished_at"] == before["finished_at"]
- assert not jobs.get_job(job["id"]).get("last_delivery_queued")
- finally:
- lease.release()
- db.close()
-
-
-def _queued_execution(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
- execution = executions.create_execution(job["id"], source="test")
- job["execution_id"] = execution["id"]
- jobs.bind_delivery_execution(job["id"], execution["id"])
- incident_id, _ = incidents.upsert_incident(job["id"], "raw failure")
- executions.bind_delivery_incident(execution["id"], incident_id)
- executions.record_delivery_manifest(execution["id"], {"external": True})
- delivery_queue.enqueue(execution["id"], job, "diagnostic", for_failure=True)
- jobs.update_delivery_projection(job["id"], execution["id"], {"last_delivery_queued": {"gateway": {"status": "queued"}}})
- executions.finish_execution(execution["id"], success=False, error="raw failure", delivery_outcome="queued")
- return job, execution, incident_id
-
-
[email protected]("terminal", ["delivered", "suppressed", "failed", "unknown"])
[email protected]("newer", [False, True])
-def test_restart_repairs_exact_execution_without_replay(tmp_path, monkeypatch, terminal, newer):
- import os
- import subprocess
- import sys
- job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
- before = executions.get_execution(execution["id"])
- if newer:
- latest = executions.create_execution(job["id"], source="newer")
- jobs.bind_delivery_execution(job["id"], latest["id"])
- jobs.update_delivery_projection(job["id"], latest["id"], {
- "last_delivery_queued": {"newer-target": {"status": "queued"}},
- "last_delivery_unverified": ["newer-ambiguity"], "last_delivery_error": "newer-error"})
- saved = jobs.get_job(job["id"])
- # Kill-window simulation: persist terminal receipt, omit projection callback.
- monkeypatch.setattr(executions, "reconcile_delivery_projections", lambda: None)
- if terminal == "unknown":
- delivery_queue.claim_next()
- delivery_queue._terminalize_wait_timeout(execution["id"])
- else:
- def send(queued_job, *args):
- queued_job["_notification_all_targets_suppressed"] = terminal == "suppressed"
- return "wire failure" if terminal == "failed" else None
- assert delivery_queue.drain(send) == 1
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "queued"
- # All connections reopened in a fresh interpreter. A terminal receipt never sends.
- code = "from cron.delivery_queue import drain; assert drain(lambda *a: (_ for _ in ()).throw(AssertionError('REPLAY'))) == 0"
- subprocess.run([sys.executable, "-c", code], env=os.environ.copy(), check=True)
- after = executions.get_execution(execution["id"])
- assert after["delivery_outcome"] == terminal
- assert {k: after[k] for k in ("status", "error", "finished_at")} == {k: before[k] for k in ("status", "error", "finished_at")}
- assert incidents.get_incident(incident_id)["state"] == ("alerted" if terminal == "delivered" else "detected")
- if newer:
- assert jobs.get_job(job["id"]) == saved
- else:
- assert not jobs.get_job(job["id"])["last_delivery_queued"]
-
-
-def test_external_claimed_timeout_reports_unknown_immediately(tmp_path, monkeypatch):
- from cron import scheduler_delivery
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (False, "raw", "", "failed script"))
- job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
- execution = executions.create_execution(job["id"], source="test")
- job["execution_id"] = execution["id"]
- monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])
- wait = delivery_queue.enqueue_and_wait
- def claim_then_wait(key, job, content, *, for_failure=False):
- delivery_queue.enqueue(key, job, content, for_failure=for_failure)
- assert delivery_queue.claim_next()
- return wait(key, job, content, for_failure=for_failure, timeout=0)
- monkeypatch.setattr(delivery_queue, "enqueue_and_wait", claim_then_wait)
- scheduler.run_one_job(job)
- assert delivery_queue.get_status(execution["id"])["status"] == "unknown"
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "unknown"
-
-
-def test_late_gateway_result_cannot_override_unknown_send(tmp_path, monkeypatch):
- job, execution, _ = _queued_execution(tmp_path, monkeypatch)
- assert delivery_queue.claim_next()
- delivery_queue._terminalize_wait_timeout(execution["id"])
- # The late sender finishes target bookkeeping after the worker fenced the claim.
- executions.record_delivery_manifest(execution["id"], {"bot": {}, "delivered": True})
- assert not delivery_queue._finish(execution["id"], error=None)
- delivery_queue.drain(lambda *a: pytest.fail("must not replay"))
- assert delivery_queue.get_status(execution["id"])["status"] == "unknown"
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "unknown"
-
-
-
-def test_direct_unverified_native_send_retains_legacy_outcome(tmp_path, monkeypatch):
- import asyncio
- from concurrent.futures import Future
- from types import SimpleNamespace
- from unittest.mock import MagicMock
- from gateway.platforms.base import SendResult
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}")
- monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (True, "raw", "requested result", None))
- config = GatewayConfig()
- config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
- monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
- async def send(*args, **kwargs):
- return SendResult(success=True)
- router = SimpleNamespace(_deliver_to_platform=send)
- monkeypatch.setattr("gateway.delivery.DeliveryRouter", lambda *a, **k: router)
- def run_coro(coro, loop):
- future = Future()
- future.set_result(asyncio.run(coro))
- return future
- monkeypatch.setattr("asyncio.run_coroutine_threadsafe", run_coro)
- job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
- loop = MagicMock()
- loop.is_running.return_value = True
- scheduler.run_one_job(job, adapters={Platform.TELEGRAM: MagicMock()}, loop=loop)
- assert executions.latest_execution(job["id"])["delivery_outcome"] == "delivered"
- assert jobs.get_job(job["id"])["last_delivery_unverified"]
diff --git a/tests/cron/test_delivery_incident_generation.py b/tests/cron/test_delivery_incident_generation.py
deleted file mode 100644
index 02bc81988aa..00000000000
--- a/tests/cron/test_delivery_incident_generation.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""A receipt belongs to one incident occurrence, not every reuse of its ID."""
-import pytest
-from cron import executions, incidents, delivery_queue
-from tests.cron.test_deferred_warning_projection import _queued_execution
-
-
[email protected]("finish_before_recovery", [False, True])
-def test_old_receipt_cannot_alert_reopened_incident(tmp_path, monkeypatch, finish_before_recovery):
- job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
- if finish_before_recovery:
- delivery_queue.drain(lambda *a: None)
- assert incidents.get_incident(incident_id)["state"] == "alerted"
- assert incidents.close_incidents_for_recovered_job(job["id"]) == 1
- reopened, is_new = incidents.upsert_incident(job["id"], "raw failure")
- assert reopened == incident_id and is_new
- if not finish_before_recovery:
- delivery_queue.drain(lambda *a: None)
- executions.reconcile_delivery_projections()
- executions.reconcile_delivery_projections()
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
- assert incidents.get_incident(incident_id)["state"] == "detected"
-
-
-def test_receipt_for_current_reopened_occurrence_can_alert(tmp_path, monkeypatch):
- job, old, incident_id = _queued_execution(tmp_path, monkeypatch)
- incidents.close_incidents_for_recovered_job(job["id"])
- incidents.upsert_incident(job["id"], "raw failure")
- current = executions.create_execution(job["id"], source="new failure")
- executions.bind_delivery_incident(current["id"], incident_id)
- executions.record_delivery_manifest(current["id"], {"external": True})
- delivery_queue.enqueue(current["id"], dict(job, execution_id=current["id"]), "diagnostic", for_failure=True)
- executions.finish_execution(current["id"], success=False, error="raw failure", delivery_outcome="queued")
- delivery_queue.drain(lambda *a: None)
- assert incidents.get_incident(incident_id)["state"] == "alerted"
-
-
-def test_upgrade_does_not_invent_old_receipts_incident_generation(tmp_path, monkeypatch):
- import sqlite3
- job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
- before = executions.get_execution(execution["id"])
- # Exact pre-generation schema shape, with a pending receipt already persisted.
- with sqlite3.connect(tmp_path / "cron" / "executions.db") as conn:
- conn.execute("ALTER TABLE executions DROP COLUMN incident_generation")
- conn.execute("DROP TRIGGER IF EXISTS cron_incident_recurrence_generation")
- conn.execute("ALTER TABLE cron_incidents DROP COLUMN generation")
- delivery_queue.drain(lambda *a: None)
- after = executions.get_execution(execution["id"])
- assert after["delivery_outcome"] == "delivered"
- assert after["incident_generation"] is None
- assert after["error"] == before["error"]
- assert incidents.get_incident(incident_id)["state"] == "detected"
- assert incidents.get_incident(incident_id)["generation"] == 1
-
-
-def test_concurrent_reconcilers_cannot_alert_reopened_occurrence(tmp_path, monkeypatch):
- import os
- import subprocess
- import sys
- job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
- delivery_queue.drain(lambda *a: None)
- incidents.close_incidents_for_recovered_job(job["id"])
- incidents.upsert_incident(job["id"], "raw failure")
- code = "from cron.executions import reconcile_delivery_projections; reconcile_delivery_projections()"
- children = [subprocess.Popen([sys.executable, "-c", code], env=os.environ.copy()) for _ in range(4)]
- for child in children:
- assert child.wait(timeout=30) == 0
- assert incidents.get_incident(incident_id)["state"] == "detected"
- assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
diff --git a/tests/cron/test_incident_binding_atomicity.py b/tests/cron/test_incident_binding_atomicity.py
deleted file mode 100644
index e07f4b54c15..00000000000
--- a/tests/cron/test_incident_binding_atomicity.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""An execution owns the occurrence created in its incident transaction."""
-import os
-import subprocess
-import sys
-
-import pytest
-
-from cron import executions, incidents, scheduler
-from tests.cron.test_mixed_delivery_retention import setup
-
-
-def test_reopen_after_upsert_return_cannot_rebind_old_execution(setup, monkeypatch):
- home, cfg, run, sent = setup
- original = incidents.upsert_incident
- def interleave(*args, **kwargs):
- result = original(*args, **kwargs)
- iid = result[0]
- script = home / "reopen.py"
- script.write_text('from cron import incidents\nimport sys\ni=incidents.get_incident(sys.argv[1])\nassert incidents.close_incidents_for_recovered_job(i["job_id"])==1\nincidents.upsert_incident(i["job_id"],i["error"])\n')
- subprocess.run([sys.executable, str(script), iid], env={**os.environ, "PYTHONPATH": os.getcwd()}, check=True, timeout=20)
- return result
- monkeypatch.setattr(incidents, "upsert_incident", interleave)
- job, before = run(True, deliver="telegram:test")
- assert before["incident_generation"] == 1
- assert scheduler.drain_delivery_queue({}, None) == 1
- incident = incidents.get_incident(before["incident_id"])
- assert incident["generation"] == 2
- assert incident["state"] == "detected"
- assert len(sent) == 1
-
-
-def test_pre_generation_writer_cannot_reuse_occurrence(setup):
- home, cfg, run, sent = setup
- job, before = run(True, deliver="telegram:test")
- assert scheduler.drain_delivery_queue({}, None) == 1
- iid = before["incident_id"]
- assert incidents.get_incident(iid)["state"] == "alerted"
- incidents.close_incidents_for_recovered_job(job["id"])
- # Exact old writer, not a replacement approximation of its SQL.
- source = subprocess.check_output(['git', 'show', 'd738176e09d65a58252d5c4f2110e95f43570602:cron/incidents.py'], text=True)
- (home / "old_incidents.py").write_text(source)
- script = home / "old_writer.py"
- script.write_text('import old_incidents as old\nimport sys\ni=old.get_incident(sys.argv[1])\nassert old.upsert_incident(i["job_id"],i["error"])[1]\n')
- subprocess.run([sys.executable, str(script), iid], env={**os.environ, "PYTHONPATH": os.getcwd()}, check=True, timeout=20)
- executions.reconcile_delivery_projections()
- assert incidents.get_incident(iid)["generation"] == 2
- assert incidents.get_incident(iid)["state"] == "detected"
-
-
-def test_incident_and_execution_bind_roll_back_together(setup, monkeypatch):
- home, cfg, run, sent = setup
- execution = executions.create_execution("bind-rollback", source="fixture")
- def fail(*args):
- raise OSError("fixture bind failure")
- with monkeypatch.context() as scoped:
- scoped.setattr(executions, "_bind_delivery_incident_unlocked", fail)
- with pytest.raises(OSError, match="fixture bind failure"):
- incidents.upsert_incident("bind-rollback", "fixture", execution_id=execution["id"])
- assert not [i for i in incidents.list_incidents() if i["job_id"] == "bind-rollback"]
- assert executions.get_execution(execution["id"])["incident_id"] is None
- iid, new = incidents.upsert_incident("bind-rollback", "fixture", execution_id=execution["id"])
- assert new
- assert executions.get_execution(execution["id"])["incident_id"] == iid
- assert executions.get_execution(execution["id"])["incident_generation"] == 1
diff --git a/tests/cron/test_incident_native_alert_generation.py b/tests/cron/test_incident_native_alert_generation.py
deleted file mode 100644
index 46fcb386d28..00000000000
--- a/tests/cron/test_incident_native_alert_generation.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""Salt R3 S4: an immediate native alert for occurrence N must not mark a reopened occurrence N+1."""
-import json
-import os
-import subprocess
-import sys
-from cron import incidents, executions
-from tests.cron.test_mixed_delivery_retention import setup
-
-
-def test_direct_native_old_output_does_not_alert_reopened_occurrence(setup,monkeypatch):
- home,cfg,run,sent=setup
- original=incidents.upsert_incident
- hits=[]
- def after_commit(*args,**kw):
- result=original(*args,**kw)
- iid=result[0]
- hits.append(iid)
- subprocess.run([sys.executable,'-c', '''
-from cron import incidents
-import sys
-i=incidents.get_incident(sys.argv[1])
-assert incidents.close_incidents_for_recovered_job(i['job_id'])==1
-incidents.upsert_incident(i['job_id'],i['error'])
-''',iid],env={**os.environ,'PYTHONPATH':os.getcwd()},check=True,timeout=30)
- return result
- monkeypatch.setattr(incidents,'upsert_incident',after_commit)
- job,execution=run(False,deliver='telegram:test')
- assert len(hits)==1 and len(sent)==1
- i=incidents.get_incident(execution['incident_id'])
- assert execution['incident_generation']==1 and i['generation']==2
- print('DIRECT_SIBLING',json.dumps({'execution':execution,'incident':i,'wire_count':len(sent)}))
- assert i['state']=='detected'
diff --git a/tests/cron/test_late_legacy_intent_layers.py b/tests/cron/test_late_legacy_intent_layers.py
deleted file mode 100644
index 4df5c921ebd..00000000000
--- a/tests/cron/test_late_legacy_intent_layers.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""K2c layers isolated. Salt R7's late-writer schedules are recovered by any one of three layers
-(finish accounting, projection accounting, replay reopen); each cell here disables the others so
-a single missing layer fails."""
-import json, sqlite3
-from cron import executions as ex, jobs
-from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap
-from tests.cron.test_r6_salt_migration_authority import legacy_running
-
-
-def _adopted_with_no_journal(store):
- """Fence committed while the legacy row's journal did not exist yet (the K2c window)."""
- eid, manifest = legacy_running(store)
- (ex._journal_root() / f"{eid}.json").unlink()
- assert ex.get_execution(eid)["delivery_manifest_pending"] == 0 and ex._legacy_intent_adopted()
- old = prior(); old.EXECUTIONS_FILE = ex.EXECUTIONS_FILE
- return eid, manifest, old
-
-
-def test_finish_accounts_for_late_journal_without_replay(store, monkeypatch):
- eid, manifest, old = _adopted_with_no_journal(store)
- old.journal_manifest(eid, manifest) # pre-flag writer publishes late
- monkeypatch.setattr(ex, "_recover_unrecorded_manifests", lambda: {}) # no replay layer
- finished = ex.finish_execution(eid, success=True, delivery_outcome="queued")
- assert finished["delivery_outcome"] == "queued"
- assert finished["delivery_manifest_pending"] == 1 # intent adopted in finish's transaction
-
-
-def test_projection_accounts_for_late_journal_without_replay(store, monkeypatch):
- eid, manifest, old = _adopted_with_no_journal(store)
- # Row is terminal-queued with only the placeholder: its external queue child is still
- # pending when the OLD module finishes it (healthy legacy contract), then the old writer
- # publishes the journal. The reconciler must not settle the placeholder as delivered.
- from cron import delivery_queue as dq
- with dq._transaction() as conn:
- conn.execute("UPDATE deliveries SET status='pending', finished_at=NULL WHERE execution_id=?", (eid,))
- with old._transaction() as conn:
- conn.execute("UPDATE executions SET process_id=? WHERE id=?", (old._PROCESS_ID, eid))
- assert old.finish_execution(eid, success=True, delivery_outcome="queued")["delivery_outcome"] == "queued"
- old.journal_manifest(eid, manifest)
- with dq._transaction() as conn:
- conn.execute("UPDATE deliveries SET status='delivered', finished_at=? WHERE execution_id=?",
- (dq._hermes_now().isoformat(), eid))
- monkeypatch.setattr(ex, "_recover_unrecorded_manifests", lambda: {})
- ex.reconcile_delivery_projections()
- row = ex.get_execution(eid)
- assert row["delivery_outcome"] == "queued", "placeholder settled as delivered although its journal exists"
- assert row["delivery_projection_settled"] == 0
-
-
-def test_replay_reopens_row_terminalized_by_old_code(store):
- """The OLD module (no accounting layers) finished the row as delivered from the placeholder,
- then published its journal. Only the replay's reopen can correct the ledger."""
- eid, manifest, old = _adopted_with_no_journal(store)
- with old._transaction() as conn:
- conn.execute("UPDATE executions SET process_id=? WHERE id=?", (old._PROCESS_ID, eid))
- finished = old.finish_execution(eid, success=True, delivery_outcome="queued")
- assert finished["delivery_outcome"] == "delivered" # the pre-flag defect, reproduced
- old.journal_manifest(eid, manifest)
- ex.reconcile_delivery_projections()
- row = ex.get_execution(eid)
- assert row["delivery_outcome"] == "queued"
- assert '"bot"' in row["delivery_manifest"]
- assert jobs.get_job("child-job")["last_delivery_queued"]
-
-
-def test_unknowable_journal_state_holds_after_adoption(store):
- """Adoption complete, journal directory later unreadable: a placeholder-only row cannot be
- proven journal-free, so it is held rather than terminalized."""
- eid, manifest, old = _adopted_with_no_journal(store)
- root = ex._journal_root(); mode = root.stat().st_mode & 0o777
- root.chmod(0)
- try:
- finished = ex.finish_execution(eid, success=True, delivery_outcome="queued")
- finally:
- root.chmod(mode)
- assert finished["delivery_outcome"] == "queued"
- assert finished["delivery_manifest_pending"] == 0 # nothing adopted: state was unknown, not present
diff --git a/tests/cron/test_manifest_intent_fence.py b/tests/cron/test_manifest_intent_fence.py
deleted file mode 100644
index af7c3766b70..00000000000
--- a/tests/cron/test_manifest_intent_fence.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""Salt R4 closure: the pre-send intent flag is the authoritative fence on every reader.
-
-Each cell here kills one specific mutant that the ported J1-J4 probes do not:
-pre-send mark when the journal is also unwritable; prune predicate; reconcile CAS re-check.
-"""
-import json, threading
-from cron import executions, scheduler, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_journal_edges import reject_manifest, repaired, fast_gateway
-from tests.cron.test_r4_salt_recovery_probes import restart
-
-
-def test_presend_intent_alone_keeps_queued_when_ledger_and_journal_both_fault(setup, monkeypatch):
- """Ledger rejects the manifest AND the journal is entirely unavailable (its re-assert of the
- flag included): only the PRE-SEND flag can keep the run queued. Native sent once; no
- transport failure reported."""
- home, cfg, run, sent = setup
- reject_manifest()
- monkeypatch.setattr(executions, 'journal_manifest', lambda eid, manifest: False)
- root = home / 'cron' / 'manifest_journal'; root.mkdir(); root.chmod(0o500)
- try:
- job, row = run(False)
- finally:
- root.chmod(0o700)
- assert len(sent) == 1
- assert row['delivery_outcome'] == 'queued'
- assert row['delivery_manifest_pending'] == 1
- assert jobs.get_job(job['id']).get('last_delivery_queued')
- assert not jobs.get_job(job['id']).get('last_delivery_error')
- # Retention pressure with nothing else protecting the row.
- monkeypatch.setattr(executions, 'MAX_TERMINAL_EXECUTIONS', 0)
- with executions._transaction() as conn:
- executions._prune_unlocked(conn)
- assert executions.get_execution(row['id']) is not None
-
-
-def test_prune_predicate_honours_pending_even_when_outcome_is_not_queued(setup, monkeypatch):
- """Direct-DB corruption of the outcome must not make a pending row prunable."""
- home, cfg, run, sent = setup
- reject_manifest()
- job, row = run(False)
- with executions._transaction() as conn:
- conn.execute("UPDATE executions SET delivery_outcome='delivered' WHERE id=?", (row['id'],))
- monkeypatch.setattr(executions, 'MAX_TERMINAL_EXECUTIONS', 0)
- with executions._transaction() as conn:
- executions._prune_unlocked(conn)
- assert executions.get_execution(row['id']) is not None
-
-
-def test_reconcile_cas_rechecks_pending_at_write_time(setup, monkeypatch):
- """A reconciler that loaded the row BEFORE the pending flag flipped must not settle it."""
- home, cfg, run, sent = setup
- fast_gateway(monkeypatch)
- job, row = run(True) # healthy: external placeholder + real bot receipt, manifest recorded
- assert row['delivery_outcome'] == 'queued'
- # Stale reader: its projection was computed from a snapshot with pending=0 and returns
- # 'delivered' unconditionally (no projection-time recheck); intent flips underneath it
- # before the write. Only the CAS predicate can refuse the settle.
- def stale(record):
- with executions._transaction() as conn:
- conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (record['id'],))
- return ('delivered', {'last_delivery_queued': None, 'last_delivery_unverified': None, 'last_delivery_error': None})
- monkeypatch.setattr(executions, '_delivery_projection', stale)
- executions.reconcile_delivery_projections()
- after = executions.get_execution(row['id'])
- assert after['delivery_outcome'] == 'queued'
- assert after['delivery_projection_settled'] == 0
- assert jobs.get_job(job['id']).get('last_delivery_queued')
diff --git a/tests/cron/test_manifest_intent_upgrade.py b/tests/cron/test_manifest_intent_upgrade.py
deleted file mode 100644
index 4d9c734cce0..00000000000
--- a/tests/cron/test_manifest_intent_upgrade.py
+++ /dev/null
@@ -1,73 +0,0 @@
-"""K2 mechanisms isolated: migration adoption and replay re-assert each carry cases the other cannot."""
-import json, sqlite3
-from pathlib import Path
-import pytest
-from cron import executions as ex, jobs, delivery_queue as dq, bot_chat_delivery as bot
-from tests.cron.test_r5_salt_legacy_and_races import store, seed, receipt, set_receipt, snap
-
-
-def _reject_bot_manifest(conn):
- conn.execute("CREATE TRIGGER k2_reject BEFORE UPDATE OF delivery_manifest ON executions "
- "WHEN instr(NEW.delivery_manifest, '\"bot\"')>0 BEGIN SELECT RAISE(ABORT,'k2 manifest fault'); END")
-
-
-def test_replay_reasserts_intent_on_already_migrated_row(store):
- """Schema already has the column (pending=0 default) and a journal entry appears later
- (e.g. copied from a backup, or a mark whose re-assert failed). Migration adoption cannot
- run again; only the replay's own intent assertion fences the placeholder."""
- eid = seed(store) # current schema: pending column exists, value 0
- manifest = receipt(store, eid)
- ex.journal_manifest(eid, manifest) # journal written; simulate the flag being lost
- with ex._transaction() as conn:
- conn.execute("UPDATE executions SET delivery_manifest_pending=0 WHERE id=?", (eid,))
- _reject_bot_manifest(conn)
- ex.reconcile_delivery_projections()
- state = snap(eid)
- assert state['execution']['delivery_outcome'] == 'queued'
- assert state['execution']['delivery_manifest_pending'] == 1
- assert state['execution']['delivery_projection_settled'] == 0
-
-
-def test_migration_adopts_journal_before_any_reader_even_without_replay(store, monkeypatch):
- """Old schema + outstanding journal. A reader that touches the row BEFORE any reconcile
- (finish_execution of a late worker, or prune) must already see the intent: the migration
- step, not the replay, is what fences it."""
- from tests.cron.test_r5_salt_legacy_and_races import prior
- old = prior(); eid = seed(store, old); manifest = receipt(store, eid)
- old.journal_manifest(eid, manifest)
- with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
- assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
- # Make replay a no-op so only migration adoption can fence the row.
- monkeypatch.setattr(ex, '_recover_unrecorded_manifests', lambda: {})
- with ex._transaction() as conn: # triggers schema init (migration) on the current module
- pass
- row = ex.get_execution(eid)
- assert row['delivery_manifest_pending'] == 1
- monkeypatch.setattr(ex, 'MAX_TERMINAL_EXECUTIONS', 0)
- with ex._transaction() as conn:
- ex._prune_unlocked(conn)
- assert ex.get_execution(eid) is not None
- ex.reconcile_delivery_projections()
- assert ex.get_execution(eid)['delivery_outcome'] == 'queued'
-
-
-def test_finish_holds_placeholder_row_regardless_of_caller_outcome_while_adoption_incomplete(store, monkeypatch):
- """K2a finish path isolated: the caller says 'failed' (its own classification) for a legacy
- placeholder-only row while adoption is incomplete. finish must write queued, not trust the
- caller — the projection fence alone cannot do this because a None projection keeps the
- caller's value."""
- from tests.cron.test_r6_salt_migration_authority import legacy_running
- eid, manifest = legacy_running(store)
- root = store / 'cron' / 'manifest_journal'
- mode = root.stat().st_mode & 0o777
- root.chmod(0)
- try:
- ex.get_execution(eid) # initialization: adoption fails, fence row absent
- assert not ex._legacy_intent_adopted()
- finished = ex.finish_execution(eid, success=False, error='worker failure', delivery_outcome='failed')
- finally:
- root.chmod(mode)
- assert finished['delivery_outcome'] == 'queued'
- ex.reconcile_delivery_projections()
- after = ex.get_execution(eid)
- assert after['delivery_outcome'] == 'queued' and '"bot"' in after['delivery_manifest']
diff --git a/tests/cron/test_manifest_recording_recovery.py b/tests/cron/test_manifest_recording_recovery.py
deleted file mode 100644
index e841cc7a88d..00000000000
--- a/tests/cron/test_manifest_recording_recovery.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""A post-send ledger fault must never become transport failure or trigger resend."""
-import pytest
-from cron import executions, scheduler, delivery_queue, bot_chat_delivery, jobs
-from tests.cron.test_mixed_delivery_retention import setup
-
-
[email protected]("external", [False, True])
[email protected]("persistent_fault", [False, True])
-def test_manifest_fault_retains_child_and_real_send_outcome(setup, monkeypatch, external, persistent_fault):
- home, cfg, run, sent = setup
- original = executions.record_delivery_manifest
- failures = []
- def fail(eid, manifest):
- if "bot" in manifest:
- failures.append(eid)
- raise OSError("fixture ledger recorder unavailable")
- return original(eid, manifest)
- monkeypatch.setattr(executions, "record_delivery_manifest", fail)
- job, before = run(external)
- if external:
- scheduler.drain_delivery_queue({}, None)
- assert delivery_queue.get_status(before["id"])["status"] == "delivered"
- assert len(sent) == 1
- assert failures
- mid = executions.get_execution(before["id"])
- assert mid["delivery_outcome"] == "queued"
- assert jobs.get_job(job["id"])["last_delivery_queued"]
- if not persistent_fault:
- monkeypatch.setattr(executions, "record_delivery_manifest", original)
- cfg(True)
- bot_chat_delivery.drain()
- executions.reconcile_delivery_projections()
- after = executions.get_execution(before["id"])
- assert after["delivery_outcome"] == "delivered"
- assert after["error"] == before["error"]
- assert after["finished_at"] == before["finished_at"]
- assert not jobs.get_job(job["id"])["last_delivery_queued"]
- assert len(sent) == 1
- monkeypatch.setattr(executions, "record_delivery_manifest", original)
- executions.reconcile_delivery_projections()
- executions.reconcile_delivery_projections()
- assert len(sent) == 1
diff --git a/tests/cron/test_mixed_delivery_retention.py b/tests/cron/test_mixed_delivery_retention.py
deleted file mode 100644
index bc7dd266b16..00000000000
--- a/tests/cron/test_mixed_delivery_retention.py
+++ /dev/null
@@ -1,107 +0,0 @@
-"""Independent product-path falsification; vendor edges only are fake."""
-import json
-from pathlib import Path
-import pytest
-from cron import executions, incidents, jobs, scheduler, delivery_queue, bot_chat_delivery
-from gateway.config import GatewayConfig, Platform, PlatformConfig
-from hermes_state import SessionDB
-from hermes_cli.active_sessions import try_acquire_active_session
-
-def setup(tmp_path, monkeypatch):
- monkeypatch.setenv('HERMES_HOME',str(tmp_path))
- monkeypatch.setenv('HERMES_MANAGED_DIR',str(tmp_path/'managed'))
- def cfg(muted=False):
- (tmp_path/'config.yaml').write_text(json.dumps({'cron':{'wrap_response':False,'preflight':False},'display':{'suppress_warning_notifications':muted}}))
- cfg()
- config=GatewayConfig(); config.platforms[Platform.TELEGRAM]=PlatformConfig(enabled=True)
- monkeypatch.setattr('gateway.config.load_gateway_config',lambda:config)
- (tmp_path/'scripts').mkdir()
- (tmp_path/'scripts'/'fail.sh').write_text("#!/bin/sh\nprintf 'preserved shell stdout\\n'\nprintf 'preserved stderr\\n' >&2\nexit 7\n")
- db=SessionDB(db_path=tmp_path/'state.db'); db.create_session(session_id='bot',source='cli'); db.set_session_title('bot','Bot Chat')
- lease, refusal=try_acquire_active_session(session_id='bot',surface='cli',config={},registry_home=tmp_path)
- assert refusal is None
- sent=[]
- async def send(platform,pconfig,chat_id,text,**kwargs):
- sent.append(text)
- return {'success':True,'message_id':'recorded'}
- monkeypatch.setattr('tools.send_message_tool._send_to_platform',send)
- def run(external=False, deliver='bot-chat,telegram:test'):
- job=jobs.create_job(prompt=None,schedule='every 1h',script='fail.sh',no_agent=True,deliver=deliver)
- if external:
- ex=executions.create_execution(job['id'],source='test-external'); job['execution_id']=ex['id']
- monkeypatch.setenv('_HERMES_CRON_EXTERNAL_WORKER',ex['id'])
- wait=delivery_queue.enqueue_and_wait
- monkeypatch.setattr(delivery_queue,'enqueue_and_wait',lambda eid,j,c,for_failure=False: wait(eid,j,c,for_failure=for_failure,timeout=0))
- scheduler.run_one_job(job)
- return job, executions.latest_execution(job['id'])
- yield tmp_path,cfg,run,sent
- lease.release(); db.close()
-
[email protected]('external',[False,True])
[email protected]('native_fails',[False,True])
-def test_real_mixed_router_preserves_pending_and_terminal(setup,monkeypatch,external,native_fails):
- home,cfg,run,sent=setup
- if native_fails:
- async def fail(*a,**k): return {'success':False,'error':'native rejected'}
- monkeypatch.setattr('tools.send_message_tool._send_to_platform',fail)
- job,before=run(external)
- if external:
- assert before['delivery_outcome']=='queued'
- assert scheduler.drain_delivery_queue({},None)==1
- middle=executions.get_execution(before['id']); saved=jobs.get_job(job['id'])
- print('MIXED',external,native_fails,'MID',json.dumps({'execution':middle,'queued':saved.get('last_delivery_queued')},default=str))
- # The bot has NOT been attempted; native failure must not erase its pending state.
- assert middle['delivery_outcome']=='queued'
- assert saved.get('last_delivery_queued')
- cfg(True); bot_chat_delivery.drain(); bot_chat_delivery.drain()
- after=executions.get_execution(before['id'])
- assert after['delivery_outcome']==('failed' if native_fails else 'delivered')
- assert after['error']==before['error'] and after['finished_at']==before['finished_at']
- assert not jobs.get_job(job['id']).get('last_delivery_queued')
-
-
-def test_execution_retention_does_not_erase_pending_projection(setup,monkeypatch):
- home,cfg,run,sent=setup
- job,before=run(True,deliver='telegram:test')
- # Use the production retention implementation with a small deterministic limit.
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',1)
- newer=executions.create_execution('unrelated-job',source='retention-pressure')
- executions.finish_execution(newer['id'],success=True,delivery_outcome='not_configured')
- print('PRUNE',before['id'],executions.get_execution(before['id']))
- cfg(True); scheduler.drain_delivery_queue({},None)
- assert delivery_queue.get_status(before['id'])['status']=='suppressed'
- print('PRUNE JOB',json.dumps(jobs.get_job(job['id']),default=str))
- assert not jobs.get_job(job['id']).get('last_delivery_queued')
-
-
[email protected]("drop_settlement_column", [False, True])
-def test_projection_write_failure_pins_receipt_until_replay_then_prunes(setup, monkeypatch, drop_settlement_column):
- import sqlite3
- home, cfg, run, sent = setup
- job, before = run(True, deliver="telegram:test")
- if drop_settlement_column:
- with sqlite3.connect(home / "cron" / "executions.db") as conn:
- conn.execute("ALTER TABLE executions DROP COLUMN delivery_projection_settled")
- original = jobs.update_delivery_projection
- def fail(*args, **kwargs):
- raise OSError("fixture jobs projection write failure")
- monkeypatch.setattr(jobs, "update_delivery_projection", fail)
- cfg(True)
- scheduler.drain_delivery_queue({}, None)
- assert executions.get_execution(before["id"])["delivery_outcome"] == "suppressed"
- assert not executions.get_execution(before["id"])["delivery_projection_settled"]
- monkeypatch.setattr(executions, "MAX_TERMINAL_EXECUTIONS", 0)
- with executions._transaction() as conn:
- executions._prune_unlocked(conn)
- assert executions.get_execution(before["id"]) is not None
- assert jobs.get_job(job["id"])["last_delivery_queued"]
- monkeypatch.setattr(jobs, "update_delivery_projection", original)
- executions.reconcile_delivery_projections()
- assert not jobs.get_job(job["id"])["last_delivery_queued"]
- assert executions.get_execution(before["id"])["delivery_projection_settled"]
- with executions._transaction() as conn:
- executions._prune_unlocked(conn)
- assert executions.get_execution(before["id"]) is None
- assert not sent # never retry delivery to repair bookkeeping
-
diff --git a/tests/cron/test_r4_salt_composed_probes.py b/tests/cron/test_r4_salt_composed_probes.py
deleted file mode 100644
index 9fcfefd0f0e..00000000000
--- a/tests/cron/test_r4_salt_composed_probes.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""Salt R3 composed R4 probes (B2/B3), ported as regression cells."""
-import json, threading
-import pytest
-from cron import executions, scheduler, bot_chat_delivery, jobs
-from tools import bot_live_delivery as mailbox
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_recovery_probes import restart, fail_bot_store
-
-
-def test_real_scheduler_manifest_park_races_active_drain(setup,monkeypatch):
- home,cfg,run,sent=setup
- entered=threading.Event();release=threading.Event();threads=[];errors=[]
- # Consumer edge only, not a real model launch; receipt claim/completion is production.
- def consume(job,content,profile,*,deferred):
- entered.set();assert release.wait(10);return None
- from cron import scheduler_delivery
- original_delivery=scheduler_delivery._deliver_to_bot_chat
- def route(job,content,profile,**kwargs):
- if kwargs.get('deferred') is not None:return consume(job,content,profile,**kwargs)
- return original_delivery(job,content,profile,**kwargs)
- monkeypatch.setattr('cron.scheduler_delivery._deliver_to_bot_chat',route)
- orig_record=executions.record_delivery_manifest
- def fail(eid,manifest):
- if 'bot' not in manifest:return orig_record(eid,manifest)
- monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
- def drain():
- try:bot_chat_delivery.drain()
- except Exception as e:errors.append(e)
- t=threading.Thread(target=drain);threads.append(t);t.start()
- assert entered.wait(10)
- raise OSError('recorder unavailable while receipt consumer active')
- monkeypatch.setattr(executions,'record_delivery_manifest',fail)
- original_attach=executions.journal_manifest
- def attach(eid,manifest):
- original_attach(eid,manifest)
- assert executions.journaled_manifests()[eid]==manifest
- release.set()
- for t in threads:t.join(10)
- assert not errors and all(not t.is_alive() for t in threads)
- monkeypatch.setattr(executions,'journal_manifest',attach)
- job,before=run(False)
- monkeypatch.setattr(executions,'record_delivery_manifest',orig_record)
- records=bot_chat_delivery._records(bot_chat_delivery._root())
- restart(home)
- after=executions.get_execution(before['id'])
- print('COMPOSED_RACE',json.dumps({'receipt':records[0][1],'execution':after,'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
- assert after['delivery_outcome']=='delivered'
- assert not jobs.get_job(job['id']).get('last_delivery_queued')
-
-
-def test_external_store_fault_recovers_after_bot_failure_without_false_delivery(setup,monkeypatch):
- home,cfg,run,sent=setup
- original=fail_bot_store(monkeypatch)
- job,before=run(True);scheduler.drain_delivery_queue({},None)
- mid=executions.get_execution(before['id'])
- restart(home,fault=True)
- # Drive the pending receipt to an actual failed attempt through production drain.
- monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
- monkeypatch.setattr('cron.scheduler_delivery._deliver_to_bot_chat',lambda *a,**k:'consumer failed')
- bot_chat_delivery.drain()
- monkeypatch.setattr(executions,'_store_manifest',original)
- restart(home)
- after=executions.get_execution(before['id'])
- receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
- print('FAULT_RECOVERY',json.dumps({'mid':mid,'after':after,'receipt_status':receipt['status'],'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
- assert after['delivery_outcome']=='unknown'
-
-
-def test_pruned_row_cannot_be_reconstructed_from_parked_manifest(setup,monkeypatch):
- home,cfg,run,sent=setup
- original=fail_bot_store(monkeypatch)
- job,before=run(True);scheduler.drain_delivery_queue({},None)
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
- with executions._transaction() as conn:executions._prune_unlocked(conn)
- # Fixed contract: a journaled (outstanding-manifest) run is fenced from retention.
- assert executions.get_execution(before['id']) is not None
- monkeypatch.setattr(executions,'_store_manifest',original)
- cfg(True);bot_chat_delivery.drain();restart(home)
- receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
- print('PRUNED_REPLAY',json.dumps({'execution':executions.get_execution(before['id']),'receipt_status':receipt['status'],'journaled':before['id'] in executions.journaled_manifests(),'job':jobs.get_job(job['id'])}))
- assert executions.get_execution(before['id']) is not None
diff --git a/tests/cron/test_r4_salt_journal_composed.py b/tests/cron/test_r4_salt_journal_composed.py
deleted file mode 100644
index 2bdec611a52..00000000000
--- a/tests/cron/test_r4_salt_journal_composed.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Salt R4 J1/J3 composed probes, ported as regression cells."""
-import json, subprocess, sys, os
-import pytest
-from cron import executions, scheduler, scheduler_delivery, delivery_queue, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_journal_edges import reject_manifest, repaired, fast_gateway
-from tests.cron.test_r4_salt_recovery_probes import restart
-
-
-def test_finish_alone_overrides_correct_queued_input(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest();fast_gateway(monkeypatch)
- original=scheduler.finish_execution
- seen=[]
- def finish(eid,**kwargs):
- kwargs['delivery_outcome']='queued'
- result=original(eid,**kwargs)
- seen.append({'input':'queued','result':result})
- return result
- monkeypatch.setattr(scheduler,'finish_execution',finish)
- job,row=run(True)
- print('FINISH_ALONE',json.dumps({'calls':seen,'journal':executions.journaled_manifests(),'native_sends':len(sent)}))
- assert row['delivery_outcome']=='queued'
-
-
-def test_interrupted_scheduler_journal_row_pruned_by_next_completion(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest()
- original=executions.journal_manifest
- def journal_then_shutdown(eid,manifest):
- original(eid,manifest)
- assert scheduler.mark_running_jobs_interrupted('probe shutdown')
- monkeypatch.setattr(executions,'journal_manifest',journal_then_shutdown)
- job,row=run(False)
- assert row and row['delivery_outcome']=='queued' # fixed contract: pre-send intent keeps the interrupted run queued
- assert executions.journaled_manifests().get(row['id'])
- assert len(sent)==1
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',1)
- another=executions.create_execution('retention-pressure',source='direct')
- executions.finish_execution(another['id'],success=True,delivery_outcome='not_configured')
- snapshot={'before':row,'after_retention':executions.get_execution(row['id']),'journal':executions.journaled_manifests(),'job':jobs.get_job(job['id']),'native_sends':len(sent)}
- repaired();cfg(True);bot_chat_delivery.drain();restart(home)
- snapshot['after_restart']=executions.get_execution(row['id']);snapshot['receipt']=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
- print('COMPOSED_SHUTDOWN_PRUNE',json.dumps(snapshot))
- assert snapshot['after_retention'] is not None
-
-
-def test_normal_wait_repaired_manifest_still_pins_false_outcome(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest();fast_gateway(monkeypatch)
- job,row=run(True)
- # Pending Bot Chat truly fails; no fabricated terminal receipt.
- from tools import bot_live_delivery as mailbox
- monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
- monkeypatch.setattr(scheduler_delivery,'_deliver_to_bot_chat',lambda *a,**k:'consumer failure')
- bot_chat_delivery.drain()
- repaired();restart(home)
- after=executions.get_execution(row['id'])
- print('WAIT_BOT_FAILED',json.dumps({'before':row,'after':after,'job':jobs.get_job(job['id']),'receipt':bot_chat_delivery._records(bot_chat_delivery._root())[0][1],'sends':len(sent)}))
- assert after['delivery_outcome']=='unknown'
-
-
-def test_abandoned_direct_owner_recovery_prunes_outstanding_journal(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest()
- original=scheduler.finish_execution
- def lose_terminal_write(*a,**kwargs):
- raise OSError('terminal write unavailable until owner dies')
- monkeypatch.setattr(scheduler,'finish_execution',lose_terminal_write)
- job,row=run(False)
- assert row['status']=='running'
- assert executions.journaled_manifests().get(row['id'])
- # Real recovery decisions need a provably absent owner; set the durable pid to a dead pid.
- with executions._transaction() as conn:
- conn.execute('UPDATE executions SET process_id=?,pid=?,process_started_at=? WHERE id=?',('dead-test-owner',99999999,0,row['id']))
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
- assert executions.recover_interrupted_executions()==1
- print('ABANDONED_JOURNAL',json.dumps({'after':executions.get_execution(row['id']),'journal':executions.journaled_manifests(),'sends':len(sent)}))
- assert executions.get_execution(row['id']) is not None
diff --git a/tests/cron/test_r4_salt_journal_edges.py b/tests/cron/test_r4_salt_journal_edges.py
deleted file mode 100644
index 1a7f03c8846..00000000000
--- a/tests/cron/test_r4_salt_journal_edges.py
+++ /dev/null
@@ -1,125 +0,0 @@
-"""Salt R4 J1-J4 journal-boundary probes, ported as regression cells (real stores; scheduling/fault edges only)."""
-import json, os, subprocess, sys, threading
-from pathlib import Path
-import pytest
-from cron import executions, scheduler, scheduler_delivery, delivery_queue, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_recovery_probes import restart
-
-
-def reject_manifest():
- with executions._transaction() as conn:
- conn.execute('''CREATE TRIGGER salt_r4_reject BEFORE UPDATE OF delivery_manifest ON executions
- WHEN NEW.delivery_manifest LIKE '%"bot"%'
- BEGIN SELECT RAISE(ABORT, 'persistent ledger fault'); END''')
-
-
-def repaired():
- with executions._transaction() as conn:
- conn.execute('DROP TRIGGER salt_r4_reject')
-
-
-def fast_gateway(monkeypatch):
- wait=delivery_queue.enqueue_and_wait
- def synchronous(eid,job,content,*,for_failure=False,**kwargs):
- delivery_queue.enqueue(eid,job,content,for_failure=for_failure)
- scheduler.drain_delivery_queue({},None)
- return wait(eid,job,content,for_failure=for_failure,timeout=0)
- monkeypatch.setattr(delivery_queue,'enqueue_and_wait',synchronous)
-
-
-def test_worker_wait_with_outstanding_journal_keeps_queued(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest();fast_gateway(monkeypatch)
- job,row=run(True)
- snapshot={'execution':row,'saved_job':jobs.get_job(job['id']),'journal':executions.journaled_manifests(),'queue':delivery_queue.get_status(row['id']),'native_sends':len(sent)}
- print('WAIT_BEFORE_REPAIR',json.dumps(snapshot))
- repaired();cfg(True);bot_chat_delivery.drain();restart(home)
- print('WAIT_AFTER_REPAIR',json.dumps(executions.get_execution(row['id'])))
- assert row['delivery_outcome']=='queued'
- assert snapshot['saved_job']['last_delivery_queued']
-
-
-def test_finish_projection_cannot_override_queued_with_placeholder(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest()
- original=executions._delivery_projection
- observed=[]
- def recording(record):
- result=original(record)
- observed.append((record['id'],result))
- return result
- monkeypatch.setattr(executions,'_delivery_projection',recording)
- fast_gateway(monkeypatch)
- job,row=run(True)
- print('FINISH_PROJECTIONS',json.dumps({'observed':observed,'outcome':row['delivery_outcome'],'outstanding':list(executions.journaled_manifests())}))
- # This row is terminal but falsely delivered while a real Bot Chat receipt remains queued.
- assert not any(result and result[0]=='delivered' for eid,result in observed)
-
-
[email protected]('external',[False,True])
-def test_unwritable_journal_after_real_send_is_not_transport_failure(setup,monkeypatch,external):
- home,cfg,run,sent=setup
- reject_manifest()
- root=home/'cron'/'manifest_journal';root.mkdir();root.chmod(0o500)
- try:
- job,row=run(external)
- if external:scheduler.drain_delivery_queue({},None)
- snapshot={'execution':executions.get_execution(row['id']),'job':jobs.get_job(job['id']),'queue':delivery_queue.get_status(row['id']) if external else None,'native_sends':len(sent),'receipts':[r for p,r in bot_chat_delivery._records(bot_chat_delivery._root())]}
- print('UNWRITABLE_JOURNAL',json.dumps(snapshot))
- assert len(sent)==1
- if external:assert snapshot['queue']['status']!='failed'
- else:assert not snapshot['job'].get('last_delivery_error')
- finally:root.chmod(0o700)
-
-
-def test_retention_after_interrupted_direct_run_preserves_journal(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest()
- ex=executions.create_execution('interrupted',source='direct')
- executions.mark_execution_running(ex['id'])
- manifest={'bot':{'bot-chat:':{'home':str(home),'delivery_id':'receipt','status':'queued'}}}
- executions.journal_manifest(ex['id'],manifest)
- # _finish_interrupted_run calls finish_execution without delivery_outcome.
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
- scheduler._finish_interrupted_run({'id':'interrupted'},ex['id'],None)
- print('INTERRUPTED_RETENTION',json.dumps({'row':executions.get_execution(ex['id']),'journal':executions.journaled_manifests()}))
- assert executions.get_execution(ex['id']) is not None
-
-
-def test_journal_without_row_is_retained_not_resurrected(setup):
- home,cfg,run,sent=setup
- manifest={'bot':{'bot-chat:':{'home':str(home),'delivery_id':'missing','status':'queued'}}}
- executions.journal_manifest('never-created',manifest)
- restart(home,count=2)
- assert executions.get_execution('never-created') is None
- assert executions.journaled_manifests()['never-created']==manifest
- print('ORPHAN_RETAINED',json.dumps(executions.journaled_manifests()))
-
-
[email protected]('terminal',['settled','ambiguous','suppressed'])
-def test_two_reconcilers_terminal_receipt_replay(setup,monkeypatch,terminal):
- home,cfg,run,sent=setup
- reject_manifest();job,row=run(True);scheduler.drain_delivery_queue({},None)
- from tools import bot_live_delivery as mailbox
- monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
- if terminal=='suppressed':cfg(True)
- else:monkeypatch.setattr(scheduler_delivery,'_deliver_to_bot_chat',lambda *a,**k: None if terminal=='settled' else 'consumer failed')
- bot_chat_delivery.drain()
- records=bot_chat_delivery._records(bot_chat_delivery._root())
- assert records[0][1]['status']==terminal
- repaired()
- REPO=next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists())
- env={k:v for k,v in os.environ.items() if k in ('PATH','LANG','LC_ALL','PYTHONDONTWRITEBYTECODE')}
- env.update(HOME=str(home),HERMES_HOME=str(home),HERMES_MANAGED_DIR=str(home/'managed'),TMPDIR=str(home),PYTHONPATH=str(REPO))
- script=Path(__file__).parent/'_r4_reconcile_child.py'
- children=[subprocess.Popen([sys.executable,str(script)],env=env,cwd=str(next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists())),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) for _ in range(2)]
- for p in children:
- out,err=p.communicate(timeout=30);print('CONCURRENT_REPLAY',p.returncode,out,err);assert p.returncode==0
- after=executions.get_execution(row['id'])
- assert after['delivery_outcome']==('unknown' if terminal=='ambiguous' else 'delivered')
- assert after['delivery_projection_settled']==1
- assert not executions.journaled_manifests()
- assert not jobs.get_job(job['id']).get('last_delivery_queued')
- assert len(sent)==1
- print('CONCURRENT_FINAL',json.dumps(after))
diff --git a/tests/cron/test_r4_salt_journal_race.py b/tests/cron/test_r4_salt_journal_race.py
deleted file mode 100644
index 58741a3aa0c..00000000000
--- a/tests/cron/test_r4_salt_journal_race.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""Salt R4 J2: reconciler that started before journal creation must not settle the placeholder."""
-import json, threading
-from cron import executions, scheduler, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_journal_edges import reject_manifest, fast_gateway
-
-
-def test_reconciler_started_before_journal_creation_does_not_settle_placeholder(setup,monkeypatch):
- home,cfg,run,sent=setup
- reject_manifest()
- job,row=run(True)
- entered=threading.Event();release=threading.Event();errors=[]
- original=executions._recover_unrecorded_manifests
- def paused():
- outstanding=original()
- if threading.current_thread().name=='early-reconciler':
- assert not outstanding
- entered.set();assert release.wait(15)
- return outstanding
- monkeypatch.setattr(executions,'_recover_unrecorded_manifests',paused)
- def reconcile():
- try:executions.reconcile_delivery_projections()
- except BaseException as e:errors.append(str(e))
- thread=threading.Thread(target=reconcile,name='early-reconciler');thread.start()
- assert entered.wait(15)
- scheduler.drain_delivery_queue({},None)
- assert executions.journaled_manifests().get(row['id'])
- assert executions.get_execution(row['id'])['delivery_outcome']=='queued'
- release.set();thread.join(15)
- assert not thread.is_alive() and not errors
- after=executions.get_execution(row['id'])
- print('STALE_OUTSTANDING',json.dumps({'row':after,'journal':executions.journaled_manifests(),'job':jobs.get_job(job['id']),'native_sends':len(sent)}))
- assert after['delivery_outcome']=='queued'
- assert after['delivery_projection_settled']==0
-
-
-def test_fast_gateway_without_fault_keeps_bot_queued(setup,monkeypatch):
- home,cfg,run,sent=setup
- fast_gateway(monkeypatch)
- job,row=run(True)
- assert row['delivery_outcome']=='queued'
- assert jobs.get_job(job['id'])['last_delivery_queued']
- cfg(True);bot_chat_delivery.drain()
- assert executions.get_execution(row['id'])['delivery_outcome']=='delivered'
- assert len(sent)==1
- print('HEALTHY_FAST_WAIT',json.dumps(executions.get_execution(row['id'])))
diff --git a/tests/cron/test_r4_salt_recovery_probes.py b/tests/cron/test_r4_salt_recovery_probes.py
deleted file mode 100644
index 18aeca52c04..00000000000
--- a/tests/cron/test_r4_salt_recovery_probes.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""Salt R3 (B1-B3) recovery probes, ported verbatim as regression cells. Real stores/router; network and ledger edges injected."""
-import json, os, subprocess, sys, threading
-from pathlib import Path
-import pytest
-from cron import executions, scheduler, bot_chat_delivery, jobs, delivery_queue
-from tools import bot_live_delivery as mailbox
-from tests.cron.test_mixed_delivery_retention import setup
-
-ROOT=Path(__file__).resolve().parent
-
-def restart(home, *, fault=False, count=1):
- REPO=next(p for p in ROOT.parents if (p/'cron'/'executions.py').exists())
- env={k:v for k,v in os.environ.items() if k in ('PATH','LANG','LC_ALL','PYTHONDONTWRITEBYTECODE')}
- env['PYTHONPATH']=str(REPO)
- env.update(HOME=str(home), HERMES_HOME=str(home), HERMES_MANAGED_DIR=str(home/'managed'), TMPDIR=str(home))
- cmd=[sys.executable,str(ROOT/'_r4_restart.py'),str(int(fault)),str(count)]
- p=subprocess.run(cmd,env=env,cwd=str(REPO),capture_output=True,text=True,timeout=30)
- print('RESTART',p.returncode,p.stdout,p.stderr)
- assert p.returncode==0
- return p
-
-def fail_bot_store(monkeypatch):
- orig=executions._store_manifest
- def fail(conn,eid,manifest):
- if 'bot' in manifest: raise OSError('injected persistent SQLite manifest write failure')
- return orig(conn,eid,manifest)
- monkeypatch.setattr(executions,'_store_manifest',fail)
- return orig
-
[email protected]('external',[False,True])
-def test_live_mailbox_recorder_fault_recovers(setup,monkeypatch,external):
- from hermes_cli.active_sessions import try_acquire_active_session
- from hermes_state import SessionDB
- home,cfg,run,sent=setup
- db=SessionDB(db_path=home/'state.db');db.create_session(session_id='live-bot',source='tui');db.set_session_title('bot','old bot');db.set_session_title('live-bot','Bot Chat')
- lease,refusal=try_acquire_active_session(session_id='live-bot',surface='tui',config={},registry_home=home,metadata={'bot_live_delivery_consumer':True,'live_session_id':'salt-live'})
- assert refusal is None
- try:
- owner=mailbox.find_canonical_live_owner(home);assert owner
- orig=executions.record_delivery_manifest
- def fail(eid,manifest):
- if 'bot' in manifest: raise OSError('injected recorder fault')
- return orig(eid,manifest)
- monkeypatch.setattr(executions,'record_delivery_manifest',fail)
- job,before=run(external)
- if external: scheduler.drain_delivery_queue({},None)
- records=list((home/'runtime/bot_live_delivery').glob('*.json'));assert len(records)==1
- key=records[0].stem
- mid=executions.get_execution(before['id'])
- print('LIVE_MID',external,json.dumps(mid), 'pending',bot_chat_delivery.read_pending(key))
- assert len(sent)==1
- claimed=mailbox.claim_pending_delivery(home,owner);assert claimed
- mailbox.complete_delivery(home,key,status='settled',reply='done')
- monkeypatch.setattr(executions,'record_delivery_manifest',orig)
- restart(home)
- after=executions.get_execution(before['id']);saved=jobs.get_job(job['id'])
- print('LIVE_FINAL',external,json.dumps(after),'queued',saved.get('last_delivery_queued'))
- assert after['delivery_outcome']=='delivered'
- assert not saved.get('last_delivery_queued')
- assert after['delivery_manifest'] and 'bot' in json.loads(after['delivery_manifest'])
- finally: lease.release();db.close()
-
[email protected]('external',[False,True])
-def test_persistent_real_manifest_store_fault_across_restart(setup,monkeypatch,external):
- home,cfg,run,sent=setup
- orig=fail_bot_store(monkeypatch)
- job,before=run(external)
- if external: scheduler.drain_delivery_queue({},None)
- assert executions.journaled_manifests().get(before['id'])
- restart(home,fault=True,count=2)
- mid=executions.get_execution(before['id']);saved=jobs.get_job(job['id'])
- print('PERSISTENT_MID',external,json.dumps(mid),'queued',saved.get('last_delivery_queued'))
- assert mid['delivery_outcome']=='queued'
- assert saved.get('last_delivery_queued')
- monkeypatch.setattr(executions,'_store_manifest',orig)
- cfg(True);bot_chat_delivery.drain();restart(home)
- after=executions.get_execution(before['id'])
- assert after['delivery_outcome']=='delivered'
- assert not jobs.get_job(job['id']).get('last_delivery_queued')
- assert len(sent)==1
-
-
-
-
-def test_parked_manifest_execution_is_not_pruned_during_store_fault(setup,monkeypatch):
- home,cfg,run,sent=setup
- fail_bot_store(monkeypatch)
- job,before=run(True);scheduler.drain_delivery_queue({},None)
- assert executions.journaled_manifests().get(before['id'])
- monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
- with executions._transaction() as conn:executions._prune_unlocked(conn)
- print('PARKED_PRUNE',executions.get_execution(before['id']))
- assert executions.get_execution(before['id']) is not None
diff --git a/tests/cron/test_r4_salt_sqlite_probe.py b/tests/cron/test_r4_salt_sqlite_probe.py
deleted file mode 100644
index 85d2f71e7f8..00000000000
--- a/tests/cron/test_r4_salt_sqlite_probe.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""Salt R3 B2: actual SQLite write rejection persists across fresh reconcilers."""
-import json, sqlite3
-from cron import executions, scheduler, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_recovery_probes import restart
-
-
-def test_actual_sqlite_manifest_update_failure_keeps_pending_sibling(setup):
- home,cfg,run,sent=setup
- # Initialize real database; reject ONLY full-manifest updates, not placeholder/projection.
- with executions._transaction() as conn:
- conn.execute('''CREATE TRIGGER salt_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions
- WHEN NEW.delivery_manifest LIKE '%"bot"%'
- BEGIN SELECT RAISE(ABORT, 'salt persistent manifest storage fault'); END''')
- job,before=run(True);scheduler.drain_delivery_queue({},None)
- restart(home,count=2) # no Python fault hook: SQLite itself rejects replay after restart.
- mid=executions.get_execution(before['id'])
- receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
- print('SQLITE_FAULT',json.dumps({'execution':mid,'receipt_status':receipt['status'],'journaled':before['id'] in executions.journaled_manifests(),'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
- with sqlite3.connect(home/'cron/executions.db') as conn:conn.execute('DROP TRIGGER salt_reject_manifest')
- restart(home)
- recovered=executions.get_execution(before['id'])
- print('SQLITE_REPAIRED',json.dumps({'execution':recovered,'queued':jobs.get_job(job['id']).get('last_delivery_queued')}))
- assert mid['delivery_outcome']=='queued'
- assert recovered['delivery_outcome']=='queued'
diff --git a/tests/cron/test_r5_salt_intent_lifecycle.py b/tests/cron/test_r5_salt_intent_lifecycle.py
deleted file mode 100644
index 8f9f15ec8db..00000000000
--- a/tests/cron/test_r5_salt_intent_lifecycle.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""Salt R5 K1 intent-lifecycle probes, ported as regression cells (production stores/scheduler; fault edges only)."""
-import json, os, subprocess, sys
-from pathlib import Path
-import pytest
-from cron import executions, scheduler, scheduler_delivery, jobs, bot_chat_delivery
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r4_salt_recovery_probes import restart
-
-
-def snapshot(home, job, row, sent):
- return {'row':executions.get_execution(row['id']), 'job':jobs.get_job(job['id']),
- 'receipts':bot_chat_delivery._records(bot_chat_delivery._root()),
- 'journal':executions.journaled_manifests(),'native_sends':len(sent)}
-
-
-def test_all_suppressed_real_receipt_clears_intent(setup):
- home,cfg,run,sent=setup
- cfg(True)
- job,row=run(False,deliver='bot-chat')
- result=snapshot(home,job,row,sent)
- print('ALL_SUPPRESSED',json.dumps(result,default=str))
- assert row['delivery_manifest_pending']==0
- assert row['delivery_outcome']=='suppressed'
- assert not sent
-
-
-def test_rejected_before_receipt_clears_intent(setup,monkeypatch):
- home,cfg,run,sent=setup
- from tools import bot_live_delivery
- def fail(*a,**k): raise OSError('discovery unavailable before admission')
- monkeypatch.setattr(bot_live_delivery,'read_delivery_result',fail)
- job,row=run(False,deliver='bot-chat')
- print('PRE_RECEIPT_REJECT',json.dumps(snapshot(home,job,row,sent),default=str))
- assert row['delivery_manifest_pending']==0
- assert row['delivery_outcome']=='failed'
- assert not bot_chat_delivery._records(bot_chat_delivery._root())
-
-
-def test_presend_ledger_refusal_sends_nothing(setup,monkeypatch):
- home,cfg,run,sent=setup
- with executions._transaction() as conn:
- conn.execute("CREATE TRIGGER reject_intent BEFORE UPDATE OF delivery_manifest_pending ON executions WHEN NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'intent unavailable'); END")
- job,row=run(False)
- print('PRE_SEND_REFUSAL',json.dumps(snapshot(home,job,row,sent),default=str))
- assert not sent and not bot_chat_delivery._records(bot_chat_delivery._root())
- assert row['delivery_outcome']=='failed' and row['delivery_manifest_pending']==0
-
-
-def test_exception_before_first_send_does_not_pin_forever(setup,monkeypatch):
- home,cfg,run,sent=setup
- def fail(*a,**k): raise OSError('transport discovery failed before any send')
- monkeypatch.setattr(scheduler_delivery,'_resolve_target_transport',fail)
- job,row=run(False,deliver='telegram:test,bot-chat')
- restart(home,count=2)
- result=snapshot(home,job,row,sent)
- print('NO_RECEIPT_EXCEPTION',json.dumps(result,default=str))
- assert not sent and not result['receipts'] and not result['journal']
- assert result['row']['delivery_manifest_pending']==0, 'Known pre-send exception has no recovery source yet remains permanently pending'
-
-
-def test_transient_release_fault_recovers_no_receipt(setup,monkeypatch):
- home,cfg,run,sent=setup
- from tools import bot_live_delivery
- def fail(*a,**k): raise OSError('discovery unavailable before admission')
- monkeypatch.setattr(bot_live_delivery,'read_delivery_result',fail)
- with executions._transaction() as conn:
- conn.execute("CREATE TRIGGER reject_release BEFORE UPDATE OF delivery_manifest_pending ON executions WHEN NEW.delivery_manifest_pending=0 BEGIN SELECT RAISE(ABORT,'transient intent release fault'); END")
- job,row=run(False,deliver='bot-chat')
- with executions._transaction() as conn: conn.execute('DROP TRIGGER reject_release')
- restart(home,count=2)
- result=snapshot(home,job,row,sent)
- print('NO_RECEIPT_RELEASE_FAULT',json.dumps(result,default=str))
- assert not sent and not result['receipts'] and not result['journal']
- assert result['row']['delivery_manifest_pending']==0, 'Storage repaired but no deferred release exists; permanently queued'
-
-
-def test_nested_script_inner_intent_does_not_mark_outer(setup,monkeypatch):
- home,cfg,run,sent=setup
- driver=Path(__file__).with_name('_r5_nested_driver.py')
- (home/'scripts'/'outer.sh').write_text('#!/bin/sh\n'+sys.executable+' '+str(driver)+'\n')
- outer=jobs.create_job(prompt=None,schedule='every 1h',script='outer.sh',no_agent=True,deliver='local')
- row=executions.create_execution(outer['id'],source='external-outer')
- outer['execution_id']=row['id']
- monkeypatch.setenv('_HERMES_CRON_EXTERNAL_WORKER',row['id'])
- assert scheduler.run_one_job(outer)
- receipt=json.loads((home/'inner-proof.json').read_text())
- after=executions.get_execution(row['id'])
- print('NESTED_SCRIPT',json.dumps({'outer':after,'inner':receipt}))
- assert receipt['outer_env']==row['id']
- assert receipt['inner']['id'] != row['id']
- assert receipt['inner']['delivery_manifest_pending']==1
- assert after['delivery_manifest_pending']==0 and after['delivery_outcome']=='suppressed' # outer script emits no output
- assert receipt['inner']['delivery_outcome']=='queued'
diff --git a/tests/cron/test_r5_salt_legacy_and_races.py b/tests/cron/test_r5_salt_legacy_and_races.py
deleted file mode 100644
index 68a16322cc3..00000000000
--- a/tests/cron/test_r5_salt_legacy_and_races.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""Salt R5 K2/S5 probes (legacy upgrade + reconciler races), ported as regression cells."""
-import importlib.util, json, sqlite3, threading
-from pathlib import Path
-import pytest
-from cron import executions as ex, jobs, delivery_queue as dq, bot_chat_delivery as bot
-from utils import atomic_json_write
-ROOT=Path(__file__).resolve().parent
-SALT=Path('/home/deploy/work/nous368-full-audit/salt-r5-review')
-
-def store(tmp_path, monkeypatch):
- monkeypatch.setenv('HERMES_HOME',str(tmp_path))
- monkeypatch.setenv('HERMES_MANAGED_DIR',str(tmp_path/'managed'))
- monkeypatch.setattr(ex,'EXECUTIONS_FILE',tmp_path/'cron'/'executions.db')
- monkeypatch.setattr(dq,'DELIVERY_DB',tmp_path/'cron'/'deliveries.db')
- return tmp_path
-
-def prior():
- spec=importlib.util.spec_from_file_location('child_prior',ROOT/'_r5_prior_executions.py')
- mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod)
- return mod
-
-def seed(home, module=ex, placeholder=True):
- module.EXECUTIONS_FILE=home/'cron'/'executions.db'
- row=module.create_execution('child-job',source='evidence')
- eid=row['id']
- module.record_delivery_manifest(eid,{'external':True} if placeholder else {'bot':{}})
- module.finish_execution(eid,success=True,delivery_outcome='queued')
- # Actual durable jobs store, no scheduler/model/transport.
- jobs.save_jobs([{'id':'child-job','name':'child probe','prompt':'probe','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_status':'delivery_queued','last_delivery_queued':{'gateway':{'status':'queued'}}}])
- dq.enqueue(eid,{'id':'child-job'},'evidence')
- assert dq.claim_next()['execution_id']==eid
- assert dq._finish(eid,error=None)
- return eid
-
-def receipt(home,eid):
- key=eid+'b07'
- bot.defer(key,{'id':'child-job'},'evidence','',home)
- return {'bot':{'bot-chat:(own)':{'home':str(home),'delivery_id':key,'status':'queued'}},'delivered':True}
-
-def set_receipt(manifest,status):
- ref=next(iter(manifest['bot'].values()))
- row=bot.read_pending(ref['delivery_id']);row['status']=status
- atomic_json_write(bot._root()/(ref['delivery_id']+'.json'),row,fsync_dir=True,mode=0o600)
-
-def snap(eid):
- return {'execution':ex.get_execution(eid),'job':jobs.get_job('child-job'),'journal':ex.journaled_manifests()}
-
-def save(name,data):
- print(name,json.dumps(data))
-
[email protected]('version',['prior','head'])
-def test_legacy_failed_replay_must_not_project_placeholder(store,version):
- old=prior();eid=seed(store,old);manifest=receipt(store,eid)
- old.journal_manifest(eid,manifest)
- with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
- assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
- conn.execute("CREATE TRIGGER child_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions WHEN instr(NEW.delivery_manifest, '\"bot\"')>0 BEGIN SELECT RAISE(ABORT,'child persistent manifest fault'); END")
- target=old if version=='prior' else ex
- target.reconcile_delivery_projections()
- state=snap(eid)
- with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
- conn.execute('DROP TRIGGER child_reject_manifest')
- set_receipt(manifest,'ambiguous')
- target.reconcile_delivery_projections()
- repaired=snap(eid)
- save('legacy-'+version,{'after_failed_replay':state,'after_repair':repaired})
- assert state['execution']['delivery_outcome']=='queued'
- assert state['execution']['delivery_projection_settled']==0
- assert state['job']['last_delivery_queued']
-
[email protected]('kind',['no_manifest','external_only','healthy_replay'])
-def test_legacy_default_zero_parity_controls(store,kind):
- old=prior()
- if kind=='no_manifest':
- eid=old.create_execution('child-job',source='evidence')['id']
- old.finish_execution(eid,success=True,delivery_outcome='not_configured')
- before=old.get_execution(eid)
- ex.reconcile_delivery_projections();after=ex.get_execution(eid)
- assert after['delivery_outcome']==before['delivery_outcome']
- else:
- eid=seed(store,old)
- if kind=='healthy_replay':old.journal_manifest(eid,receipt(store,eid))
- ex.reconcile_delivery_projections();after=ex.get_execution(eid)
- assert after['delivery_outcome']==('queued' if kind=='healthy_replay' else 'delivered')
- assert after['delivery_manifest_pending']==0
- save('parity-'+kind,after)
-
-
-def test_two_reconcilers_repair_before_stale_projection_write(store,monkeypatch):
- eid=seed(store);manifest=receipt(store,eid)
- ex.mark_delivery_manifest_pending(eid)
- assert ex.journal_manifest(eid,manifest)
- reached=threading.Event();release=threading.Event();errors=[]
- original=ex._delivery_projection
- def barrier(record):
- result=original(record)
- if threading.current_thread().name=='child-stale':
- reached.set();assert release.wait(15)
- return result
- monkeypatch.setattr(ex,'_delivery_projection',barrier)
- def run():
- try:ex.reconcile_delivery_projections()
- except BaseException as err:errors.append(repr(err))
- t=threading.Thread(target=run,name='child-stale');t.start()
- assert reached.wait(15)
- repaired=ex.get_execution(eid)
- assert repaired['delivery_manifest_pending']==0
- set_receipt(manifest,'settled');ex.reconcile_delivery_projections()
- winner=snap(eid)
- release.set();t.join(15);assert not t.is_alive() and not errors
- after=snap(eid)
- save('race-before-ledger',{'winner':winner,'after':after})
- assert after['execution']['delivery_outcome']=='delivered'
- assert not after['job']['last_delivery_queued']
- assert not after['journal']
-
-
-def test_two_reconcilers_repair_and_settle_between_ledger_and_jobs(store,monkeypatch):
- eid=seed(store);manifest=receipt(store,eid)
- ex.mark_delivery_manifest_pending(eid);assert ex.journal_manifest(eid,manifest)
- reached=threading.Event();release=threading.Event();errors=[]
- original=jobs.update_delivery_projection
- def barrier(*args,**kwargs):
- if threading.current_thread().name=='child-stale':
- reached.set();assert release.wait(15)
- return original(*args,**kwargs)
- monkeypatch.setattr(jobs,'update_delivery_projection',barrier)
- def run():
- try:ex.reconcile_delivery_projections()
- except BaseException as err:errors.append(repr(err))
- t=threading.Thread(target=run,name='child-stale');t.start()
- assert reached.wait(15)
- assert ex.get_execution(eid)['delivery_manifest_pending']==0
- set_receipt(manifest,'settled');ex.reconcile_delivery_projections()
- winner=snap(eid)
- release.set();t.join(15);assert not t.is_alive() and not errors
- after=snap(eid)
- monkeypatch.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0)
- with ex._transaction() as conn:ex._prune_unlocked(conn)
- ex.reconcile_delivery_projections()
- pruned=snap(eid)
- save('race-after-ledger',{'winner':winner,'after':after,'after_prune':pruned})
- assert not after['job']['last_delivery_queued'], 'stale queued projection resurrected after winning terminal projection'
- assert not pruned['job']['last_delivery_queued']
diff --git a/tests/cron/test_r6_salt_controls.py b/tests/cron/test_r6_salt_controls.py
deleted file mode 100644
index af9ade16184..00000000000
--- a/tests/cron/test_r6_salt_controls.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""Salt R6 controls, ported: healthy adoption, freshness, settlement durability; Q1 secondary-exception contract now FIXED (original wins)."""
-import json
-import sqlite3
-import sys
-from pathlib import Path
-import pytest
-from tests.cron.test_r6_salt_migration_authority import legacy_running
-from tests.cron.test_r5_salt_legacy_and_races import store, seed
-from tests.cron.test_mixed_delivery_retention import setup
-from cron import executions as ex, jobs, scheduler_delivery as sd
-
-
-def test_healthy_adoption_precedes_late_finish(store):
- eid,manifest=legacy_running(store)
- row=ex.get_execution(eid)
- assert row['delivery_manifest_pending']==1
- row=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- assert row['delivery_outcome']=='queued'
- assert ex.get_execution(eid)['delivery_outcome']=='queued'
-
-
-def test_new_execution_after_unknown_accepts_queued(store):
- eid=seed(store)
- with ex._transaction() as conn:
- conn.execute("UPDATE executions SET delivery_outcome='unknown' WHERE id=?",(eid,))
- newer=ex.create_execution('child-job',source='r6-explicit-new-run')
- jobs.bind_delivery_execution('child-job',newer['id'])
- values={'last_delivery_queued':{'bot-chat:test':{'status':'queued'}}}
- assert jobs.update_delivery_projection('child-job',newer['id'],values)
- assert jobs.get_job('child-job')['last_delivery_queued']==values['last_delivery_queued']
-
-
-def test_original_exception_survives_all_ordinary_bookkeeping_faults(setup,monkeypatch):
- home,cfg,run,sent=setup
- job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='telegram:test,bot-chat')
- row=ex.create_execution(job['id'],source='r6');job['execution_id']=row['id']
- jobs.bind_delivery_execution(job['id'],row['id'])
- original=sd._deliver_targets
- error=RuntimeError('original post-admission fault')
- def fail_after(*a,**k):
- original(*a,**k)
- raise error
- monkeypatch.setattr(sd,'_deliver_targets',fail_after)
- def fail_jobs(*a,**k): raise OSError('jobs write refused')
- monkeypatch.setattr(jobs,'update_delivery_projection',fail_jobs)
- with ex._transaction() as conn:
- conn.execute("CREATE TRIGGER r6_settle_fault BEFORE UPDATE OF delivery_manifest ON executions BEGIN SELECT RAISE(ABORT,'manifest write refused'); END")
- root=ex._journal_root();root.mkdir();root.chmod(0)
- try:
- with pytest.raises(RuntimeError) as caught: sd._deliver_result(job,'r6 payload')
- assert caught.value is error
- assert len(sent)==1 and job['_bot_chat_delivery_receipts']
- assert ex.get_execution(row['id'])['delivery_manifest_pending']==1
- finally:
- root.chmod(0o700)
-
-
-def test_secondary_baseexception_does_not_mask_original(setup,monkeypatch):
- import asyncio
- home,cfg,run,sent=setup
- job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='bot-chat')
- row=ex.create_execution(job['id'],source='r6');job['execution_id']=row['id']
- original=OSError('original transport discovery failure')
- secondary=asyncio.CancelledError('second interruption during manifest persistence')
- def fail_targets(*a,**k): raise original
- def fail_record(*a,**k): raise secondary
- monkeypatch.setattr(sd,'_deliver_targets',fail_targets)
- monkeypatch.setattr(ex,'record_delivery_manifest',fail_record)
- with pytest.raises(OSError) as caught: sd._deliver_result(job,'r6 payload')
- assert caught.value is original
- assert ex.get_execution(row['id'])['delivery_manifest_pending']==1 # uncertainty preserved
-
-
-def test_column_presence_is_not_the_authority_fence_row_is(store):
- """DDL commits on its own; the schema_meta fence row is what readers trust."""
- eid,manifest=legacy_running(store)
- assert ex.get_execution(eid)['delivery_manifest_pending']==1
- with sqlite3.connect(ex.EXECUTIONS_FILE) as other:
- assert other.execute("SELECT 1 FROM schema_meta WHERE key=?",(ex._ADOPTION_KEY,)).fetchone()
- assert ex._legacy_intent_adopted()
diff --git a/tests/cron/test_r6_salt_migration_authority.py b/tests/cron/test_r6_salt_migration_authority.py
deleted file mode 100644
index 48091f293ad..00000000000
--- a/tests/cron/test_r6_salt_migration_authority.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""Salt R6 probes (partial-exception settle, empty-bot outcomes, jobs freshness, K2a/K2b migration authority), ported as regression cells."""
-import asyncio
-import json
-import os
-import sqlite3
-from pathlib import Path
-import pytest
-from cron import executions as ex, jobs, scheduler_delivery as sd, bot_chat_delivery as bot, delivery_queue as dq
-from tests.cron.test_mixed_delivery_retention import setup
-from tests.cron.test_r5_salt_legacy_and_races import store, prior, seed, receipt, snap
-
[email protected]('exception_type',[OSError, asyncio.CancelledError, KeyboardInterrupt])
[email protected]('persist_fault',[False,True])
-def test_partial_native_and_bot_then_exception(setup,monkeypatch,exception_type,persist_fault):
- home,cfg,run,sent=setup
- job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='telegram:test,bot-chat')
- row=ex.create_execution(job['id'],source='r6'); job['execution_id']=row['id']
- jobs.bind_delivery_execution(job['id'],row['id'])
- original=sd._deliver_targets
- error=exception_type('r6 post-admission exception')
- def fail_after(*args,**kwargs):
- original(*args,**kwargs)
- assert len(sent)==1 and job['_bot_chat_delivery_receipts']
- raise error
- monkeypatch.setattr(sd,'_deliver_targets',fail_after)
- if persist_fault:
- with ex._transaction() as conn:
- conn.execute("CREATE TRIGGER r6_fault BEFORE UPDATE OF delivery_manifest ON executions BEGIN SELECT RAISE(ABORT,'r6 ledger fault'); END")
- with pytest.raises(exception_type) as caught:
- sd._deliver_result(job,'r6 payload')
- assert caught.value is error
- state=ex.get_execution(row['id'])
- manifest=ex.journaled_manifests()[row['id']] if persist_fault else json.loads(state['delivery_manifest'])
- assert manifest['bot'] and manifest['delivered'] and 'r6 post-admission exception' in manifest['error']
- if persist_fault:
- with ex._transaction() as conn: conn.execute('DROP TRIGGER r6_fault')
- ex._recover_unrecorded_manifests()
- finished=ex.finish_execution(row['id'],success=False,error='original run failure',delivery_outcome='failed')
- assert finished['delivery_outcome']=='queued'
- assert jobs.get_job(job['id'])['last_delivery_queued']
- print('PARTIAL',exception_type.__name__,persist_fault,json.dumps(ex.get_execution(row['id'])))
-
[email protected]('error,expected',[(None,'delivered'),('bot discovery failed','failed')])
-def test_empty_bot_manifest_native_outcome(setup,monkeypatch,error,expected):
- home,cfg,run,sent=setup
- monkeypatch.setattr(sd,'_deliver_to_bot_chat',lambda *a,**k:error)
- job,row=run(False,deliver='telegram:test,bot-chat')
- assert len(sent)==1
- manifest=json.loads(row['delivery_manifest'])
- assert manifest['bot']=={} and manifest['delivered'] is True
- assert row['delivery_manifest_pending']==0 and row['delivery_outcome']==expected
- print('EMPTY_BOT',expected,json.dumps(row))
-
[email protected]('outcome,accepted',[(None,True),('queued',True),('delivered',False),('failed',False),('unknown',False),('suppressed',False),('not_configured',False)])
-def test_jobs_freshness_outcomes(store,outcome,accepted):
- eid=seed(store)
- with ex._transaction() as conn:
- conn.execute('UPDATE executions SET delivery_outcome=? WHERE id=?',(outcome,eid))
- values={'last_delivery_queued':{'bot-chat:test':{'status':'queued'}}}
- assert jobs.update_delivery_projection('child-job',eid,values) is accepted
- assert jobs.update_delivery_projection('child-job',eid,{'last_delivery_queued':None}) is True
- assert jobs.get_job('child-job')['last_delivery_queued'] is None
- print('FRESHNESS',outcome,accepted)
-
-
-def legacy_running(home):
- old=prior(); old.EXECUTIONS_FILE=home/'cron'/'executions.db'
- row=old.create_execution('child-job',source='r6-upgrade'); eid=row['id']
- # Model a surviving process importing upgraded code: retain its ownership.
- with old._transaction() as conn:
- conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
- old.record_delivery_manifest(eid,{'external':True})
- jobs.save_jobs([{'id':'child-job','name':'r6','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
- dq.enqueue(eid,{'id':'child-job'},'evidence'); assert dq.claim_next(); assert dq._finish(eid,error=None)
- manifest=receipt(home,eid); old.journal_manifest(eid,manifest)
- with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
- assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
- return eid,manifest
-
[email protected]('inaccessible',['directory','entry'])
-def test_unreadable_upgrade_must_not_terminalize_placeholder(store,inaccessible):
- eid,manifest=legacy_running(store)
- root=store/'cron'/'manifest_journal'
- target=root if inaccessible=='directory' else root/(eid+'.json')
- original_mode=target.stat().st_mode & 0o777
- target.chmod(0)
- try:
- # Real permission fault: no monkeypatch of journal enumeration or projection.
- after_init=ex.get_execution(eid)
- adopted_while_unreadable=ex._legacy_intent_adopted()
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- while_unreadable=ex.get_execution(eid)
- finally:
- target.chmod(original_mode)
- ex.reconcile_delivery_projections()
- repaired=ex.get_execution(eid)
- print('UNREADABLE_UPGRADE',inaccessible,json.dumps({'after_init':after_init,'finished':finished,'unreadable':while_unreadable,'restored':repaired,'job':jobs.get_job('child-job')}))
- # Contract (Salt R6 K2a): an unreadable inventory is NOT proof of no outstanding intent. The
- # mechanism here is the migration-completion fence row (absent until adoption succeeds), so
- # every reader holds placeholder-only rows conservatively; the flag itself lands on retry.
- assert not adopted_while_unreadable, 'unreadable adoption must not be recorded as complete'
- assert finished['delivery_outcome']=='queued', 'late finish projected the placeholder while adoption incomplete'
- assert while_unreadable['delivery_projection_settled']==0
- assert repaired['delivery_outcome']=='queued', 'readable journal restoration cannot repair falsely terminal ledger'
- assert '"bot"' in repaired['delivery_manifest'] and jobs.get_job('child-job')['last_delivery_queued']
- assert ex._legacy_intent_adopted(), 'adoption retried and completed once the journal became readable'
-
-
-def test_failed_adoption_must_retry_before_finish(store):
- eid,manifest=legacy_running(store)
- # Trigger can reference the to-be-added column, as a restored old-schema DB can.
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- conn.execute("CREATE TRIGGER r6_adoption_fault BEFORE UPDATE ON executions WHEN NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'r6 adoption fault'); END")
- # Adoption fails (rolled back, logged) but initialization degrades to a fenced state rather
- # than blocking every cron operation; the fence row is absent so readers hold the row.
- ex.get_execution(eid)
- assert not ex._legacy_intent_adopted()
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- columns=[r[1] for r in conn.execute('PRAGMA table_info(executions)')]
- raw=conn.execute('SELECT delivery_manifest_pending FROM executions WHERE id=?',(eid,)).fetchone()[0]
- conn.execute('DROP TRIGGER r6_adoption_fault')
- # The first retry is a legitimate late worker finish, not a reconciler.
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- after=ex.get_execution(eid)
- print('ADOPTION_RETRY',json.dumps({'pending_column_survives': 'delivery_manifest_pending' in columns,'raw_pending':raw,'finished':finished,'after':after,'job':jobs.get_job('child-job')}))
- assert after['delivery_outcome']=='queued', 'schema ALTER survived adoption rollback; next finish projects placeholder before replay'
- assert ex._legacy_intent_adopted(), 'adoption retried on the next initialization'
- assert '"bot"' in after['delivery_manifest'], 'replay landed the real manifest after adoption fenced the row'
diff --git a/tests/cron/test_r7_salt_edges.py b/tests/cron/test_r7_salt_edges.py
deleted file mode 100644
index 6805fee03b1..00000000000
--- a/tests/cron/test_r7_salt_edges.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""Salt R7 probes (late legacy journal K2c, concurrent initializers, interrupted CASE matrix), ported as regression cells."""
-import json, os, os, sqlite3, subprocess, sys, time
-from pathlib import Path
-import pytest
-from cron import executions as ex, jobs
-from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap
-from tests.cron.test_r6_salt_migration_authority import legacy_running
-from tests.cron.test_manifest_intent_upgrade import _reject_bot_manifest
-HERE=Path(__file__).resolve().parent
-REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
-def _env(**extra):
- env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
-
[email protected]('window',['after_commit','after_inventory'])
[email protected]('replay_first',[False,True])
-def test_late_old_journal_before_finish(store,monkeypatch,window,replay_first):
- eid,manifest=legacy_running(store)
- journal=ex._journal_root()/(eid+'.json'); journal.unlink()
- old=prior(); old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- if window=='after_inventory':
- original=ex._journal_inventory_strict
- def after_snapshot():
- result=original()
- old.journal_manifest(eid,manifest)
- return result
- monkeypatch.setattr(ex,'_journal_inventory_strict',after_snapshot)
- initial=ex.get_execution(eid)
- assert ex._legacy_intent_adopted() and initial['delivery_manifest_pending']==0
- if window=='after_commit': old.journal_manifest(eid,manifest)
- # No pending reset or production-projection stub. Actual old journal writer lacks preflag.
- if replay_first:
- with ex._transaction() as conn: _reject_bot_manifest(conn)
- ex._recover_unrecorded_manifests()
- assert ex.get_execution(eid)['delivery_manifest_pending']==1
- with ex._transaction() as conn: conn.execute('DROP TRIGGER k2_reject')
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- after=snap(eid)
- print('LATE_JOURNAL',json.dumps({'window':window,'replay_first':replay_first,'initial':initial,'finished':finished,'after':after}))
- assert after['execution']['delivery_outcome']=='queued', 'late old journal escaped adoption; replay cannot undo false terminal outcome'
- assert jobs.get_job('child-job')['last_delivery_queued']
-
[email protected]('iteration',range(3))
-def test_two_concurrent_old_schema_initializers(store,iteration):
- eid,manifest=legacy_running(store)
- barrier=store/'barrier'; barrier.mkdir()
- processes=[]
- try:
- for name in ('a','b'):
- env=_env(HERMES_HOME=str(store))
- p=subprocess.Popen([sys.executable,str(HERE/'_r7_initializer_worker.py'),str(store),str(barrier),name],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
- processes.append(p)
- deadline=time.monotonic()+20
- while not all((barrier/(name+'.ready')).exists() for name in ('a','b')):
- assert time.monotonic()<deadline, 'concurrent initialization never reached inventory boundary'
- assert all(p.poll() is None for p in processes), 'initializer exited early'
- time.sleep(.01)
- (barrier/'go').write_text('go')
- results=[]
- for p in processes:
- stdout,stderr=p.communicate(timeout=25)
- assert p.returncode==0,(stdout,stderr)
- result=json.loads(stdout.strip().splitlines()[-1]);results.append(result)
- assert result['adopted'] and result['pending']==[1]
- assert result['entry'][0]['in_transaction'] is False
- # Journal mode is runtime policy (hermes_state_wal gates WAL by SQLite build), not the
- # contract under test; the atomicity evidence below is what one adoption must satisfy.
- assert result['entry'][0]['journal_mode'] in ('wal','delete')
- assert sum('COMMIT' in r['trace'] for r in results)==1
- assert sum('ROLLBACK' in r['trace'] for r in results)==1
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- assert conn.execute('SELECT count(*) FROM schema_meta WHERE key=?',(ex._ADOPTION_KEY,)).fetchone()[0]==1
- assert conn.execute('SELECT delivery_manifest_pending FROM executions WHERE id=?',(eid,)).fetchone()[0]==1
- print('TWO_INITIALIZERS',iteration,json.dumps(results))
- finally:
- for p in processes:
- if p.poll() is None: p.kill();p.wait()
-
[email protected]('adoption_complete',[False,True])
[email protected]('manifest',[None,{'external':True},{'bot':{}}],ids=['null','placeholder','bot'])
[email protected]('flag',[0,1])
-def test_interrupted_case_matrix(store,monkeypatch,adoption_complete,manifest,flag):
- old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- eid=old.create_execution('matrix',source='r7')['id']
- if manifest is not None: old.record_delivery_manifest(eid,manifest)
- root=ex._journal_root();root.mkdir(exist_ok=True)
- if not adoption_complete: root.chmod(0)
- try:
- ex.get_execution(eid)
- assert ex._legacy_intent_adopted() is adoption_complete
- # Real exited process identity, not a monkeypatched liveness result.
- # pid selected from a Popen whose exit was waited, not guessed.
- p=subprocess.Popen([sys.executable,str(HERE/'_r7_exit_child.py')],env=_env());p.wait()
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- conn.execute("UPDATE executions SET process_id='gone-r7',pid=?,process_started_at=NULL,delivery_manifest_pending=?,delivery_outcome=NULL WHERE id=?",(p.pid,flag,eid))
- assert ex.recover_interrupted_executions()==1
- row=ex.get_execution(eid)
- expected='queued' if flag or (not adoption_complete and manifest is not None and 'bot' not in manifest) else None
- print('RECOVERY_CASE',json.dumps({'adopted':adoption_complete,'manifest':manifest,'flag':flag,'outcome':row['delivery_outcome']}))
- assert row['status']=='unknown' and row['delivery_outcome']==expected
- finally: root.chmod(0o700)
-
-
-def test_external_only_liveness_and_prune_connection(store,monkeypatch):
- old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- eid=old.create_execution('external-only',source='r7')['id']
- old.record_delivery_manifest(eid,{'external':True})
- with old._transaction() as conn: conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
- root=ex._journal_root();root.mkdir(exist_ok=True);root.chmod(0)
- try:
- row=ex.finish_execution(eid,success=False,delivery_outcome='failed')
- assert row['delivery_outcome']=='queued'
- assert ex._delivery_projection(row) is None
- with ex._transaction() as conn:
- conn.execute("UPDATE executions SET delivery_outcome='delivered',delivery_projection_settled=1 WHERE id=?",(eid,))
- statements=[];conn.set_trace_callback(statements.append)
- def no_new_connection(): raise AssertionError('nested connection opened by prune')
- with monkeypatch.context() as m:
- m.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0)
- m.setattr(ex,'_connect',no_new_connection)
- ex._prune_unlocked(conn)
- assert ex._fetch(conn,eid) is not None
- assert not any(s.startswith('BEGIN') for s in statements)
- print('PRUNE_CONNECTION',json.dumps(statements))
- assert not ex._legacy_intent_adopted()
- finally: root.chmod(0o700)
- assert ex._legacy_intent_adopted()
- with ex._transaction() as conn:
- with monkeypatch.context() as m:
- m.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0);ex._prune_unlocked(conn)
- assert ex.get_execution(eid) is None
-
-
-def test_multirow_adoption_rolls_back_all_and_retries(store):
- eid,manifest=legacy_running(store)
- old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- second=old.create_execution('second',source='r7')['id'];old.record_delivery_manifest(second,{'external':True});old.journal_manifest(second,receipt(store,second))
- last=max(eid,second)
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- conn.execute(f"CREATE TRIGGER r7_partial BEFORE UPDATE ON executions WHEN NEW.id='{last}' AND NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'second row fault'); END")
- ex.get_execution(eid)
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==0
- assert conn.execute('SELECT sum(delivery_manifest_pending) FROM executions').fetchone()[0]==0
- conn.execute('DROP TRIGGER r7_partial')
- ex.get_execution(eid)
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==1
- assert conn.execute('SELECT sum(delivery_manifest_pending) FROM executions').fetchone()[0]==2
- print('ATOMIC_ADOPTION','rollback all rows and fence, retry both rows')
diff --git a/tests/cron/test_r7_salt_late_process.py b/tests/cron/test_r7_salt_late_process.py
deleted file mode 100644
index 33f7de1527a..00000000000
--- a/tests/cron/test_r7_salt_late_process.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""Salt R7 K2c: real separate pre-flag writer publishing after adoption, ported as regression cell."""
-import json, os, os, sqlite3, subprocess, sys, time
-from pathlib import Path
-import pytest
-from cron import executions as ex, delivery_queue as dq, jobs
-from tests.cron.test_r5_salt_legacy_and_races import store, prior, snap
-HERE=Path(__file__).resolve().parent
-REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
-def _env(**extra):
- env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
-
[email protected]('replay_first',[False,True])
-def test_old_process_publishes_after_adoption(store,replay_first):
- old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- eid=old.create_execution('child-job',source='r7-late-process')['id']
- old.record_delivery_manifest(eid,{'external':True})
- with old._transaction() as conn: conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
- jobs.save_jobs([{'id':'child-job','name':'r7','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
- dq.enqueue(eid,{'id':'child-job'},'evidence')
- barrier=store/'writer';barrier.mkdir()
- p=subprocess.Popen([sys.executable,str(HERE/'_r7_old_writer.py'),str(store),eid,str(barrier)],env=_env(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
- try:
- deadline=time.monotonic()+20
- while not (barrier/'ready').exists():
- assert time.monotonic()<deadline and p.poll() is None
- time.sleep(.01)
- initial=ex.get_execution(eid)
- assert ex._legacy_intent_adopted() and initial['delivery_manifest_pending']==0
- assert dq.get_status(eid)['status']=='delivering'
- (barrier/'go').write_text('publish')
- stdout,stderr=p.communicate(timeout=20);assert p.returncode==0,(stdout,stderr)
- writer=json.loads(stdout.strip().splitlines()[-1])
- assert dq.get_status(eid)['status']=='delivered'
- assert ex.journaled_manifests()[eid]['bot']
- if replay_first: ex._recover_unrecorded_manifests()
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- after=snap(eid)
- # Another fresh reader performs restart reconciliation; no cached authority helps.
- p2=subprocess.run([sys.executable,str(HERE/'_r7_restart_read.py'),str(store),eid],env=_env(),capture_output=True,text=True,timeout=20)
- assert p2.returncode==0,(p2.stdout,p2.stderr)
- restarted=json.loads(p2.stdout.strip().splitlines()[-1])
- print('LATE_PROCESS',json.dumps({'replay_first':replay_first,'writer':writer,'finished':finished,'after':after,'restarted':restarted}))
- assert restarted['execution']['delivery_outcome']=='queued', 'replayed queued child cannot correct terminal delivered'
- finally:
- if p.poll() is None:p.kill();p.wait()
diff --git a/tests/cron/test_r7_salt_transaction_controls.py b/tests/cron/test_r7_salt_transaction_controls.py
deleted file mode 100644
index 36b234f91c4..00000000000
--- a/tests/cron/test_r7_salt_transaction_controls.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Salt R7 transaction/RLock/Q2 controls, ported as regression cells."""
-import json, sqlite3, subprocess, sys
-from pathlib import Path
-import os
-HERE=Path(__file__).resolve().parent
-REPO=next(p for p in HERE.parents if (p/"cron"/"executions.py").exists())
-def _env(**extra):
- env=dict(os.environ); env["PYTHONPATH"]=str(REPO); env.update(extra); return env
-from cron import executions as ex, incidents
-from tests.cron.test_r5_salt_legacy_and_races import store
-from tests.cron.test_r6_salt_migration_authority import legacy_running
-
-
-def test_incident_upsert_cold_adoption_preserves_outer_transaction(store,monkeypatch,caplog):
- eid,manifest=legacy_running(store)
- incident,is_new=incidents.upsert_incident('child-job','r7 script failure',execution_id=eid)
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- binding=conn.execute('SELECT incident_id,incident_generation FROM executions WHERE id=?',(eid,)).fetchone()
- assert binding[0]==incident and binding[1] is not None
- assert conn.execute('SELECT count(*) FROM cron_incidents WHERE id=?',(incident,)).fetchone()[0]==1
- assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==0
- # Q2 FIXED: adoption is deferred quietly when the caller owns the transaction (no nested BEGIN attempt).
- assert 'cannot start a transaction within a transaction' not in caplog.text
- row=ex.get_execution(eid)
- assert ex._legacy_intent_adopted() and row['delivery_manifest_pending']==1
- print('INCIDENT_OUTER_TRANSACTION',json.dumps({'binding':binding,'new':is_new,'adopted_on_next_open':True}))
-
-
-def test_pending_with_null_manifest_is_reachable_and_must_stay_queued(store):
- # Modern producer marks BEFORE it can store any manifest.
- row=ex.create_execution('null-pending',source='r7');eid=row['id']
- ex.mark_delivery_manifest_pending(eid)
- assert ex.get_execution(eid)['delivery_manifest'] is None
- p=subprocess.Popen([sys.executable,str(Path(__file__).with_name('_r7_exit_child.py'))],env=_env());p.wait()
- with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
- conn.execute("UPDATE executions SET process_id='exited-r7',pid=?,process_started_at=NULL WHERE id=?",(p.pid,eid))
- assert ex.recover_interrupted_executions()==1
- row=ex.get_execution(eid)
- print('NULL_PENDING',json.dumps(row))
- assert row['delivery_manifest'] is None and row['delivery_manifest_pending']==1
- assert row['delivery_outcome']=='queued' and row['status']=='unknown'
diff --git a/tests/cron/test_r8_salt_race_probes.py b/tests/cron/test_r8_salt_race_probes.py
deleted file mode 100644
index b4445c63c82..00000000000
--- a/tests/cron/test_r8_salt_race_probes.py
+++ /dev/null
@@ -1,174 +0,0 @@
-"""Salt R8 probes (after-stat writer barriers, K2d replay-between-stat-and-write, stat failure matrix, reopen predicate, CAS), ported as regression cells."""
-import errno, json, os, sqlite3, subprocess, sys, time
-from pathlib import Path
-import pytest
-from cron import executions as ex, delivery_queue as dq, jobs
-from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap, set_receipt
-from tests.cron.test_r6_salt_migration_authority import legacy_running
-HERE=Path(__file__).resolve().parent
-REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
-def _env(**extra):
- env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
-
-def child(mode,store,eid):
- p=subprocess.run([sys.executable,str(HERE/'_r8_child.py'),mode,str(store),eid],env=_env(),capture_output=True,text=True,timeout=25)
- assert p.returncode==0,(p.stdout,p.stderr)
- return json.loads(p.stdout.strip().splitlines()[-1])
-
-def adopted(store):
- eid,manifest=legacy_running(store)
- (ex._journal_root()/f'{eid}.json').unlink()
- assert ex.get_execution(eid)['delivery_manifest_pending']==0
- assert ex._legacy_intent_adopted()
- old=prior(); old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- return eid,manifest,old
-
-def wait(path,p):
- deadline=time.monotonic()+20
- while not path.exists():
- assert p.poll() is None and time.monotonic()<deadline
- time.sleep(.005)
-
[email protected]('publish_at',[1,2])
-def test_writer_after_absent_stat_before_external_completes(store,monkeypatch,publish_at):
- old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
- eid=old.create_execution('child-job',source='r8-barrier')['id']
- old.record_delivery_manifest(eid,{'external':True})
- with old._transaction() as conn:conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
- jobs.save_jobs([{'id':'child-job','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
- dq.enqueue(eid,{'id':'child-job'},'evidence')
- barrier=store/'barrier';barrier.mkdir()
- p=subprocess.Popen([sys.executable,str(HERE/'_r8_child.py'),'writer',str(store),eid,str(barrier)],env=_env(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
- try:
- wait(barrier/'ready',p)
- assert ex.get_execution(eid)['delivery_manifest_pending']==0
- original=ex._journal_entry_state;calls=[]
- def stat_then_publish(key):
- state=original(key); calls.append(state)
- if len(calls)==publish_at:
- assert state is False
- (barrier/'publish').write_text('go');wait(barrier/'published',p)
- assert dq.get_status(eid)['status']=='delivering'
- return state
- with monkeypatch.context() as m:
- m.setattr(ex,'_journal_entry_state',stat_then_publish)
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- assert finished['delivery_outcome']=='queued'
- (barrier/'complete').write_text('go')
- stdout,stderr=p.communicate(timeout=20);assert p.returncode==0,(stdout,stderr)
- restarted=child('read',store,eid)
- print('AFTER_STAT',json.dumps({'publish_at':publish_at,'stats':calls,'finished':finished,'restart':restarted}))
- assert restarted['execution']['delivery_outcome']=='queued'
- assert restarted['execution']['delivery_projection_settled']==0
- assert restarted['job']['last_delivery_queued']
- finally:
- if p.poll() is None:p.kill();p.wait()
-
-
[email protected]('schedule',['before_stat','during_stat'])
-def test_replay_between_stat_and_finish_intent_does_not_strand_complete_manifest(store,monkeypatch,schedule):
- eid,manifest,old=adopted(store)
- old.journal_manifest(eid,manifest)
- if schedule=='before_stat': child('replay',store,eid)
- original=ex._journal_entry_state; observed=[]; transaction_states=[]
- original_fetch=ex._fetch
- def traced_fetch(conn,key):
- transaction_states.append(conn.in_transaction)
- return original_fetch(conn,key)
- monkeypatch.setattr(ex,'_fetch',traced_fetch)
- def after_stat(key):
- result=original(key)
- if not observed:
- assert result is True
- replay=child('replay',store,eid)
- assert replay['execution']['delivery_manifest_pending']==0
- assert json.loads(replay['execution']['delivery_manifest'])['bot']
- observed.append(replay)
- return result
- with monkeypatch.context() as m:
- m.setattr(ex,'_journal_entry_state',after_stat)
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- before=snap(eid)
- # Actual queue claim/settle implementation; only owner discovery and final turn are doubles.
- from cron import bot_chat_delivery as bot, scheduler_delivery as sd
- from tools import bot_live_delivery as live
- sends=[]
- with monkeypatch.context() as m:
- m.setattr(live,'find_canonical_owner',lambda home:None)
- def delivered(*args,**kwargs):sends.append(kwargs['deferred']['id']);return None
- m.setattr(sd,'_deliver_to_bot_chat',delivered)
- bot._drain(bot._root())
- assert len(sends)==1
- assert bot.read_pending(next(iter(manifest['bot'].values()))['delivery_id'])['status']=='settled'
- restarted=child('read',store,eid)
- print('REPLAY_DURING_STAT',json.dumps({'schedule':schedule,'transaction_states':transaction_states,'replay':observed,'finished':finished,'before':before,'restart':restarted}))
- assert restarted['execution']['delivery_outcome']=='delivered', 'late adoption reasserted pending on a complete manifest and stranded settlement'
- assert restarted['execution']['delivery_manifest_pending']==0
- assert restarted['execution']['delivery_projection_settled']==1
-
[email protected]('shape',['directory_no_search','entry_no_read','missing_root','eio','bot_no_probe'])
-def test_stat_failure_matrix(store,monkeypatch,shape):
- eid,manifest,old=adopted(store)
- root=ex._journal_root(); path=root/f'{eid}.json'
- expected={'directory_no_search':None,'entry_no_read':True,'missing_root':False,'eio':None}
- old.journal_manifest(eid,manifest)
- try:
- if shape=='directory_no_search':root.chmod(0o600)
- elif shape=='entry_no_read':path.chmod(0)
- elif shape=='missing_root':path.unlink();root.rmdir()
- elif shape=='eio':
- original=Path.stat
- def fail(p,*a,**kw):
- if p==path:raise OSError(errno.EIO,'injected stat I/O error')
- return original(p,*a,**kw)
- monkeypatch.setattr(Path,'stat',fail)
- else:
- ex.record_delivery_manifest(eid,manifest)
- def forbidden(*a):raise AssertionError('bot-complete row probed journal')
- monkeypatch.setattr(ex,'_journal_entry_state',forbidden)
- assert ex._late_legacy_intent(ex.get_execution(eid)) is False
- return
- state=ex._journal_entry_state(eid)
- assert state is expected[shape]
- with monkeypatch.context() as m:
- m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- print('STAT_MATRIX',shape,json.dumps({'state':state,'finished':finished}))
- assert finished['delivery_outcome']==('delivered' if state is False else 'queued')
- assert finished['delivery_manifest_pending']==int(state is True)
- finally:
- if shape=='directory_no_search':root.chmod(0o700)
- if shape=='entry_no_read':path.chmod(0o600)
-
[email protected]('outcome',['suppressed','not_configured','unknown','delivered','failed'])
[email protected]('complete',[False,True])
-def test_reopen_predicate(store,outcome,complete):
- eid,manifest,old=adopted(store)
- if complete:ex.record_delivery_manifest(eid,{'bot':{},'delivered':True})
- with ex._transaction() as conn:
- conn.execute("UPDATE executions SET status='completed',delivery_outcome=?,delivery_projection_settled=1 WHERE id=?",(outcome,eid))
- old.journal_manifest(eid,manifest)
- ex._recover_unrecorded_manifests()
- row=ex.get_execution(eid)
- should_reopen=not complete and outcome in ('delivered','failed')
- print('REOPEN_PREDICATE',outcome,complete,json.dumps(row))
- assert row['delivery_outcome']==('queued' if should_reopen else outcome)
- assert row['delivery_projection_settled']==(0 if should_reopen else 1)
-
-
-def test_finish_adopted_flag_blocks_stale_reconciler_before_replay(store,monkeypatch):
- eid,manifest,old=adopted(store)
- stale=ex.get_execution(eid)
- projection=ex._delivery_projection(stale);assert projection[0]=='delivered'
- old.journal_manifest(eid,manifest)
- with monkeypatch.context() as m:
- m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- assert finished['delivery_manifest_pending']==1
- m.setattr(ex,'_delivery_projection',lambda record: projection)
- ex.reconcile_delivery_projections()
- row=ex.get_execution(eid)
- print('CAS_AFTER_FINISH',json.dumps(row))
- assert row['delivery_outcome']=='queued' and row['delivery_projection_settled']==0
- assert row['delivery_manifest_pending']==1
- assert jobs.get_job('child-job')['last_delivery_queued']
diff --git a/tests/cron/test_r9_salt_finish_truth.py b/tests/cron/test_r9_salt_finish_truth.py
deleted file mode 100644
index 5746f797c32..00000000000
--- a/tests/cron/test_r9_salt_finish_truth.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""Salt R9 probes (K2e finish truth after lost adoption, S7 non-canonical placeholder replay convergence), ported as regression cells."""
-import json, os, subprocess, sys
-from pathlib import Path
-import pytest
-from cron import executions as ex, jobs, bot_chat_delivery as bot
-from tests.cron.test_r5_salt_legacy_and_races import store, snap
-from tests.cron.test_r8_salt_race_probes import adopted, child
-
-def drain(monkeypatch, error=None):
- from cron import scheduler_delivery as sd
- from tools import bot_live_delivery as live
- calls=[]
- with monkeypatch.context() as m:
- m.setattr(live,'find_canonical_owner',lambda home:None)
- def send(*args,**kwargs):calls.append(kwargs['deferred']['id']);return error
- m.setattr(sd,'_deliver_to_bot_chat',send)
- bot._drain(bot._root())
- assert len(calls)==1
-
[email protected]('schedule',['before_stat','during_stat'])
[email protected]('error',[None,'independent downstream failure'])
-def test_complete_row_fallback_truth(store,monkeypatch,schedule,error):
- eid,manifest,old=adopted(store);old.journal_manifest(eid,manifest)
- if schedule=='before_stat':child('replay',store,eid)
- original=ex._journal_entry_state;seen=[]
- def barrier(key):
- state=original(key)
- if not seen:
- assert state is True
- seen.append(child('replay',store,eid))
- return state
- with monkeypatch.context() as m:
- m.setattr(ex,'_journal_entry_state',barrier)
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- before=snap(eid)
- assert before['execution']['delivery_manifest_pending']==0
- assert 'bot' in json.loads(before['execution']['delivery_manifest'])
- assert bot.read_pending(next(iter(manifest['bot'].values()))['delivery_id'])['status']=='queued'
- drain(monkeypatch,error)
- restarted=child('read',store,eid)
- expected='unknown' if error else 'delivered'
- print('FALLBACK_TRUTH',json.dumps(dict(schedule=schedule,error=error,finished=finished,before=before,restart=restarted,expected=expected)))
- checks={'queued_before_child':before['execution']['delivery_outcome']=='queued',
- 'truth_after_restart':restarted['execution']['delivery_outcome']==expected,
- 'projection_settled':restarted['execution']['delivery_projection_settled']==1}
- assert all(checks.values()), checks
-
[email protected]('replacement',[{'external':True},{'external':True,'delivered':False}])
-def test_replaced_placeholder_adoption_and_replay(store,monkeypatch,replacement):
- eid,manifest,old=adopted(store);old.journal_manifest(eid,manifest)
- original=ex._journal_entry_state;seen=[]
- def barrier(key):
- state=original(key)
- if not seen:
- ex.record_delivery_manifest(eid,replacement)
- seen.append(ex.get_execution(eid))
- return state
- with monkeypatch.context() as m:
- m.setattr(ex,'_journal_entry_state',barrier)
- m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
- finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
- assert finished['delivery_manifest_pending']==1
- drain(monkeypatch)
- restarts=[child('read',store,eid) for _ in range(2)]
- print('REPLACEMENT',json.dumps(dict(replacement=replacement,seen=seen,finished=finished,restarts=restarts)))
- assert restarts[-1]['execution']['delivery_outcome']=='delivered', 'shape accepted for adoption is rejected by manifest replacement CAS'
- assert restarts[-1]['execution']['delivery_manifest_pending']==0
- assert restarts[-1]['execution']['delivery_projection_settled']==1
-
[email protected]('existing',[{'external':True},{'external':True,'delivered':False}])
-def test_projection_only_replay_converges(store,monkeypatch,existing):
- eid,manifest,old=adopted(store)
- ex.record_delivery_manifest(eid,existing)
- old.journal_manifest(eid,manifest)
- row=ex.get_execution(eid)
- assert row['delivery_manifest_pending']==0
- assert ex._delivery_projection(row) is None
- assert ex.get_execution(eid)['delivery_manifest_pending']==0
- # Fixture terminal run, not a projection stub: projection is a read-only function.
- with ex._transaction() as conn:
- conn.execute("UPDATE executions SET status='completed', delivery_outcome='queued' WHERE id=?",(eid,))
- drain(monkeypatch)
- first=child('read',store,eid);second=child('read',store,eid)
- print('PROJECTION_REPLAY',json.dumps(dict(existing=existing,first=first,second=second)))
- assert second['execution']['delivery_manifest_pending']==0
- assert second['execution']['delivery_outcome']=='delivered'
- assert second['execution']['delivery_projection_settled']==1