The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: restore cron and session-store guards dropped by #120071
teknium13f2c86d627e5
diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.pyindex afc33e0d80a..7e7094c5fae 100644--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@ -157,6 +157,23 @@ def test_deliver_failure_reports_both_streams_labeled():assert "stdout: banner out" in err+def test_deliver_failure_banner_only_stdout_names_exit_code_not_banner():+ """The reported shape: empty stderr, stdout holding only the resume+ banner — the recorded error must say what happened (exit code, banner-only+ stdout) instead of echoing the banner as if it were a reason (#104056)."""+ banner = ('↻ Resumed session 20260905_121420_8084c7 "Bot Chat" (1 user message, 1 total messages)'+ '\n\nsession_id: 20260905_121420_8084c7')+ with mock.patch.object(+ sched_delivery, "_run_bot_chat_turn",+ return_value=_completed(returncode=1, stdout=banner, stderr=""),+ ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):+ err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")+ assert err is not None+ assert "exit code 1" in err+ assert "stdout was only the resume banner" in err+ assert "Resumed session" not in err+ assert "stderr:" not in err+def test_deliver_failure_persisted_stdout_tail_is_short_and_redacted():diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.pyindex df09189ae5a..428fac891d8 100644--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@ -15,6 +15,8 @@ import sysimport textwrapfrom datetime import datetime, timedelta, timezonefrom pathlib import Path+from types import SimpleNamespace+from typing import castimport pytest@@ -565,8 +567,58 @@ class TestRunJobEnvVarCleanup:class TestScriptTimeoutTreeKill:"""Phase 4a (#85125): a script timeout must leave zero living descendants."""+ @staticmethod+ def _stub_kills(monkeypatch, tree_kill_result):+ """Record both OS-signalling paths instead of sending real signals."""+ from agent import deadline+ from cron import scheduler_script as sched_script++ tree_kill_calls, fallback_calls = [], []+ monkeypatch.setattr(+ deadline, "kill_process_tree",+ lambda pid: tree_kill_calls.append(pid) or tree_kill_result,+ )+ monkeypatch.setattr(sched_script, "_terminate_cron_script_process", fallback_calls.append)+ return tree_kill_calls, fallback_calls++ def test_unified_tree_kill_failure_falls_back(self, monkeypatch):+ """A tree-kill that signals nothing must not leave the timed-out script+ running: the process-group termination still runs."""+ from cron import scheduler_script as sched_script++ proc = SimpleNamespace(pid=12345, poll=lambda: None)+ tree_kill_calls, fallback_calls = self._stub_kills(monkeypatch, False)++ sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))++ assert tree_kill_calls == [12345]+ assert fallback_calls == [proc]++ def test_invalid_pid_never_reaches_unified_tree_kill(self, monkeypatch):+ """pid 0 must never reach kill_process_tree: on POSIX its final+ ``os.kill(0, SIGKILL)`` signals the scheduler's own process group."""+ from cron import scheduler_script as sched_script++ proc = SimpleNamespace(pid=0, poll=lambda: None)+ tree_kill_calls, fallback_calls = self._stub_kills(monkeypatch, True)++ sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))++ assert tree_kill_calls == []+ assert fallback_calls == [proc]++ def test_already_exited_proc_is_left_alone(self, monkeypatch):+ """A script that finished right at the deadline is already reaped: its+ pid may be recycled, so neither kill path may signal it."""+ from cron import scheduler_script as sched_script++ proc = SimpleNamespace(pid=12345, poll=lambda: 0)+ tree_kill_calls, fallback_calls = self._stub_kills(monkeypatch, True)+ sched_script._terminate_cron_script_tree(cast("subprocess.Popen", proc))+ assert tree_kill_calls == []+ assert fallback_calls == []def test_cancel_path_also_tree_kills(self, monkeypatch, cron_env):"""The ownership-lost/cancel kill site is the timeout site's sibling:diff --git a/tests/cron/test_oneshot_guard_warning.py b/tests/cron/test_oneshot_guard_warning.pyindex 719f184d2a5..ed19e0f3b03 100644--- a/tests/cron/test_oneshot_guard_warning.py+++ b/tests/cron/test_oneshot_guard_warning.py@@ -1,10 +1,14 @@-"""Due-scan dispatch-limit guard: a re-armed consumed one-shot never fires twice.+"""Due-scan dispatch-limit guard: removal of a re-armed consumed one-shot is+operator-visible (#93524 follow-up to #93615).Pre-#93615 stores (or hand edits) can hold a record that already completed arun (last_run_at set) but was re-armed without a budget reset. The due-scan-guard removes it without firing — re-runs go through `cron resume`.+guard removes it without firing — correct, since #93615's policy routes+re-runs through `cron resume` — but the removal must log at WARNING with a+remediation hint, never a silent INFO delete."""+import loggingfrom datetime import timedeltaimport pytest@@ -30,7 +34,7 @@ def temp_home(tmp_path, monkeypatch):return tmp_path-def test_rearmed_consumed_oneshot_is_removed_without_firing(temp_home):+def test_guard_warns_on_rearmed_consumed_record(temp_home, caplog):job = create_job(prompt="x",schedule=(_hermes_now() + timedelta(hours=1)).isoformat(),@@ -50,9 +54,14 @@ def test_rearmed_consumed_oneshot_is_removed_without_firing(temp_home):j["next_run_at"] = (_hermes_now() - timedelta(seconds=5)).isoformat()save_jobs(jobs)- due = get_due_jobs()+ with caplog.at_level(logging.INFO, logger="cron"):+ due = get_due_jobs()assert jid not in [d["id"] for d in due]assert jid not in [j["id"] for j in load_jobs()]--+ warnings = [+ r for r in caplog.records+ if r.levelno == logging.WARNING and "WITHOUT firing" in r.getMessage()+ ]+ assert warnings, "expected WARNING on removal of a re-armed consumed one-shot"+ assert "cron resume" in warnings[0].getMessage()diff --git a/tests/hermes_state/test_hermes_state_conn_lock_audit.py b/tests/hermes_state/test_hermes_state_conn_lock_audit.pynew file mode 100644index 00000000000..1b05f788b76--- /dev/null+++ b/tests/hermes_state/test_hermes_state_conn_lock_audit.py@@ -0,0 +1,109 @@+"""Lock audit for every call on the shared writer connection (#99349).++``SessionDB._conn`` is opened with ``check_same_thread=False`` and shared+across threads (``AsyncSessionDB`` offloads every method via+``asyncio.to_thread``), so every *call* on it must hold ``self._lock``.+A lock-free ``self._conn.execute(...)`` — even a pure SELECT — can run+concurrently with ``close()`` deallocating the connection's pysqlite+statement cache, which segfaults the interpreter (observed in the field:+``_PyDict_GetItem_KnownHash`` via ``bounded_lru_cache_wrapper`` on one+thread while ``pysqlite_connection_close`` tears the cache down on+another). "Read-only" is not an exemption: the race is on the connection+object, not the database file.++Reads that must not contend on the writer lock go through+``SessionDB._read_ctx()`` instead — it borrows a pooled read connection+(exclusively checked out for the block) and its non-WAL fallback is the+writer connection *under* ``self._lock``.++This is an AST audit in the spirit of+``tests/gateway/test_async_session_db.py``: it fails on the next+``self._conn.<method>(...)`` call site added outside ``with self._lock:``.+"""++import ast+from pathlib import Path++# Functions allowed to touch self._conn without the lock: construction-time+# code that runs before the instance is ever shared with another thread.+_ALLOWED_UNLOCKED_FNS = frozenset({+ "__init__",+ "_connect_and_init",+ "_connect_and_init_with_lock_patience",+})+++def _repo_root() -> Path:+ return Path(__file__).resolve().parents[2]+++def _nearest_enclosing_fn(tree: ast.AST) -> dict:+ """Map id(node) -> name of the nearest enclosing function ("<module>"+ at module level). Nested defs override their parents."""+ enclosing: dict = {}++ def visit(node: ast.AST, current: str) -> None:+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ current = node.name+ enclosing[id(node)] = current+ for child in ast.iter_child_nodes(node):+ visit(child, current)++ visit(tree, "<module>")+ return enclosing+++def _unlocked_conn_calls(tree: ast.AST):+ """Return (lineno, enclosing_fn, method) for each self._conn.<m>(...)+ call that is not lexically inside a ``with self._lock:`` block."""+ locked_ids = set()+ for node in ast.walk(tree):+ if isinstance(node, (ast.With, ast.AsyncWith)):+ for item in node.items:+ ctx = item.context_expr+ if (+ isinstance(ctx, ast.Attribute)+ and ctx.attr == "_lock"+ and isinstance(ctx.value, ast.Name)+ and ctx.value.id == "self"+ ):+ locked_ids.update(id(child) for child in ast.walk(node))++ enclosing = _nearest_enclosing_fn(tree)++ offending = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not (+ isinstance(func, ast.Attribute)+ and isinstance(func.value, ast.Attribute)+ and func.value.attr == "_conn"+ and isinstance(func.value.value, ast.Name)+ and func.value.value.id == "self"+ ):+ continue+ if id(node) in locked_ids:+ continue+ fn = enclosing.get(id(node), "<module>")+ if fn in _ALLOWED_UNLOCKED_FNS:+ continue+ offending.append((node.lineno, fn, func.attr))+ return offending+++def test_every_conn_call_outside_construction_holds_the_lock():+ src = (_repo_root() / "hermes_state.py").read_text(encoding="utf-8")+ tree = ast.parse(src)+ offending = _unlocked_conn_calls(tree)+ assert not offending, (+ "self._conn.<method>() called without `with self._lock:` — this "+ "races SessionDB.close() inside pysqlite's statement cache and "+ "segfaults the process (#99349). Use `with self._read_ctx() as "+ "conn:` for reads, or take self._lock. Sites: "+ + ", ".join(+ f"line {lineno} in {fn}(): self._conn.{meth}(...)"+ for lineno, fn, meth in offending+ )+ )diff --git a/tests/perf_guards/test_pattern_b_scaling.py b/tests/perf_guards/test_pattern_b_scaling.pynew file mode 100644index 00000000000..ddacc4afa0d--- /dev/null+++ b/tests/perf_guards/test_pattern_b_scaling.py@@ -0,0 +1,75 @@+"""Pattern-B perf-regression guards: hot paths must not degrade to O(N·M).++Pattern B ("rebuild everything per delta/row") has no lintable signature, so+the durable guard is behavioral: pin the *scaling shape* of a known hot path+with a deterministic operation count (SQL statements via sqlite trace+callbacks), never wall-clock timing.+"""++from __future__ import annotations++import contextlib+from pathlib import Path++import pytest+++class TestListSessionsRichQueryBound:+ """Listing sessions must not walk compression chains with nested per-row queries.++ Today ``list_sessions_rich`` still issues ~2 statements per listed+ compression root (the N+1 tracked in #95380). This guard allows that legacy+ budget but fails on a regression to N·M (nested walks, per-hop re-queries).+ Statements are counted on every connection the call can use: pooled read+ connections from ``_read_ctx()`` and the writer connection.+ """++ N_CHAINS = 12++ @pytest.fixture()+ def chain_db(self, tmp_path: Path):+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ for i in range(self.N_CHAINS):+ root, child = f"root_{i}", f"child_{i}"+ db.create_session(root, source="cli")+ db.create_session(child, source="cli", parent_session_id=root)+ db.end_session(root, end_reason="compression")+ yield db+ db.close()++ @staticmethod+ def _list_and_count_statements(db, monkeypatch):+ statements: list[str] = []+ real_read_ctx = db._read_ctx++ @contextlib.contextmanager+ def traced_read_ctx():+ with real_read_ctx() as conn:+ conn.set_trace_callback(statements.append)+ try:+ yield conn+ finally:+ conn.set_trace_callback(None)++ monkeypatch.setattr(db, "_read_ctx", traced_read_ctx)+ db._conn.set_trace_callback(statements.append)+ try:+ rows = db.list_sessions_rich(limit=50)+ finally:+ db._conn.set_trace_callback(None)+ return rows, statements++ def test_statement_count_does_not_scale_with_sessions(self, chain_db, monkeypatch):+ rows, statements = self._list_and_count_statements(chain_db, monkeypatch)++ assert len(rows) == self.N_CHAINS+ assert statements, "trace captured nothing: the guard is no longer observing list_sessions_rich"+ budget = 4 * self.N_CHAINS + 8+ assert len(statements) <= budget, (+ f"list_sessions_rich issued {len(statements)} statements for "+ f"{self.N_CHAINS} sessions, beyond even the legacy N+1 budget "+ f"({budget}). A nested per-row walk has been introduced. "+ f"Captured SQL: {[s[:80] for s in statements[:10]]}"+ )