Compare commits

...

12 Commits

Author SHA1 Message Date
Hermes Agent
ed43dbaa7f hermes: split AI usage exporter engines 2026-08-17 15:33:56 +00:00
Hermes Agent
fcc8f650c2 Merge remote-tracking branch 'origin/main' into wt/t_1e95ea6d 2026-08-17 15:22:34 +00:00
flux-bot
d8f2d818b9 chore(bstein-dev-home): automated image update 2026-08-17 10:08:46 +00:00
flux-bot
30259b526b chore(bstein-dev-home): automated image update 2026-08-17 10:06:40 +00:00
ab346f5550 Merge pull request 'hermes: harden worker isolation and blocked-task semantics' (#13) from wt/t_cca008de into main
Reviewed-on: atlas/titan-iac#13
2026-08-17 08:33:41 +00:00
flux-bot
d9a88713a7 chore(maintenance): automated image update 2026-08-17 05:31:09 +00:00
flux-bot
9ada3ba6d0 chore(maintenance): automated image update 2026-08-17 02:00:37 +00:00
flux-bot
b4f78a615b chore(maintenance): automated image update 2026-08-17 01:51:36 +00:00
Hermes Agent
750dfa241f hermes: fail closed on kanban created-event producer drift
The sticky-block gate added in the previous commit classifies a task from
the `created` event payload that upstream `create_task` writes. That
producer is code we do not own, so trusting it silently was the gap: if
upstream renamed the key, dropped it, or stopped deriving it from
`initial_status`, the image would still build and ship a consumer that
mis-classifies every task it reads.

Anchor the producer contract at build time, before the regression suite
runs, with three assert-only preconditions: the `initial_status="blocked"`
park resolves `task_status` to `"blocked"`, every non-park creation
resolves it to something else, and the `created` event carries that same
variable under `"status"`. None of them rewrite the producer.

Textual anchors cannot see dataflow, so add the runtime net the reviewer
asked for. The suite now drives the real API: create + claim an ordinary
task, trip the circuit breaker once at failure_limit=1 so it parks with a
`gave_up` event (leaving its own `created` event as the most recent
create/block/unblock row), then recompute at failure_limit=2 and require
promotion to ready. That case is red under an unconditional-true created
predicate and red under producer drift that labels every created event
blocked, while the explicit block/unblock, dependency-promotion and
circuit-breaker-at-current-limit cases stay green. Non-blocked and
malformed created payloads are pinned as controls, and the gate now
rejects non-dict payloads rather than trusting `.get`.

Also make the live placement correction durable: titan-04 is cordoned
after repeated kernel undervoltage and kubelet failure and titan-19 was
probe/Longhorn unstable under worker load, so both join the hard NotIn
list; titan-05 is healthy but sits at 3592m/3600m requested CPU, so the
main hermes container gives back 50m (350m -> 300m) to schedule there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 22:42:18 +00:00
flux-bot
9bf1ab8a9c chore(bstein-dev-home): automated image update 2026-08-16 22:08:05 +00:00
flux-bot
b53e4cda45 chore(bstein-dev-home): automated image update 2026-08-16 22:06:05 +00:00
Hermes Agent
4f8dcfbbf7 hermes: harden worker isolation and blocked-task semantics
Three narrowly scoped Hermes reliability fixes backed by live evidence
from the Cassandra/titan-iac proof run.

Worker concurrency. Three simultaneous direct CLI workers on the 4-core
hermes-agent node drove load to ~45 and made the hermes and oauth2-proxy
containers fail their probes, leaving the pod 8/10 Ready; two workers
stayed at 10/10. Cap HERMES_CLI_LANE_CONCURRENCY at 2 and lower the
cli-lane-runner CPU limit from 3 to 2 so the dashboard and auth sidecars
keep a guaranteed share of the node. Requests are unchanged: the pod
still asks for 745m total, so placement does not move.

Service links. Kubernetes injects a service-link variable pair for every
service in the namespace, and hermes-claude-broker produces
HERMES_CLAUDE_BROKER_PORT=tcp://10.43.31.76:9006 — a value the broker
parses as an int. That contaminated worker and test environments even
though the deployment already addresses every service by DNS name. Set
enableServiceLinks: false on the hermes-agent pod spec.

Blocked-task scheduling. create_task(initial_status="blocked") records a
created event carrying status=blocked but never a blocked event, while
_has_sticky_block() only inspects blocked/unblocked events. recompute_ready()
considers blocked tasks, so an explicitly parked task with no incomplete
parent auto-promoted on the next dispatcher cycle. Teach _has_sticky_block()
to also recognize a created event whose payload status is blocked, which
covers tasks created before this image patch without adding a persisted
field. Dependency-driven promotion and the circuit-breaker failure-limit
guard are untouched; unblock_task() still releases either kind of block.

hermes-kanban-blocked-regression.py runs against the real upstream
kanban_db API during the image build, so the build fails if any of these
semantics regress.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 20:53:22 +00:00
18 changed files with 1328 additions and 379 deletions

View File

@ -629,16 +629,125 @@ source = source[:runs_start] + runs_source
path.write_text(source)
PY
# A manual evidence-based close must not expose a parked task to the dispatcher
# between separate `unblock` and `complete` commands. Upstream already permits
# direct completion from `blocked`; extend the same atomic path to `scheduled`
# and make that contract visible in CLI help so agents do not create a ready
# window that can launch redundant work.
# ``create_task(initial_status="blocked")`` is an explicit operator park, but
# upstream only treats later block_task() events as sticky. Recognize the
# existing created(status=blocked) event too. This also protects tasks created
# before this image patch without making dependency or circuit-breaker blocks
# depend on a new persisted field.
RUN python - <<'PY'
from pathlib import Path
db_path = Path("/opt/hermes/hermes_cli/kanban_db.py")
db_source = db_path.read_text()
# The rewritten sticky-block gate below classifies a task from the ``created``
# event payload that ``create_task`` writes. That producer is upstream code we
# do not own, so anchor the exact contract the consumer depends on instead of
# trusting it: an ``initial_status="blocked"`` park must resolve ``task_status``
# to ``"blocked"``, every other creation must resolve it to something else, and
# the ``created`` event must carry that same variable under the ``"status"``
# key. If upstream renames the key, drops it, hardcodes it, or stops deriving it
# from ``initial_status``, fail the build here rather than ship a consumer that
# silently mis-classifies every task it reads. These assert only -- they
# deliberately do not rewrite the producer. The regression suite copied in below
# is the second net: it proves the same contract against the real create_task,
# for the drift these textual anchors cannot see.
producer_park_anchor = ''' if initial_status == "blocked":
task_status = "blocked"
'''
if db_source.count(producer_park_anchor) != 1:
raise SystemExit(
"Hermes Kanban create_task park semantics changed: expected 1, "
f"found {db_source.count(producer_park_anchor)}"
)
# The mirror of the park branch: every non-park creation must resolve to a
# status the gate does *not* read as a park. Without this, drift that widened
# the ladder to park ordinary work would leave both other anchors intact.
producer_unparked_anchor = ''' elif triage:
task_status = "triage"
else:
task_status = "ready"
'''
if db_source.count(producer_unparked_anchor) != 1:
raise SystemExit(
"Hermes Kanban create_task non-park status ladder changed: expected 1, "
f"found {db_source.count(producer_unparked_anchor)}"
)
producer_event_anchor = ''' _append_event(
conn,
task_id,
"created",
{
"assignee": assignee,
"status": task_status,
'''
if db_source.count(producer_event_anchor) != 1:
raise SystemExit(
"Hermes Kanban created-event status payload changed: expected 1, "
f"found {db_source.count(producer_event_anchor)}"
)
sticky_doc_before = ''' The cheapest signal that distinguishes the two is the most recent
``"blocked"`` / ``"unblocked"`` event for the task. If the most
recent one is ``"blocked"`` (or there is a ``"blocked"`` event and
no ``"unblocked"`` event has fired since), the task is sticky and
``recompute_ready`` must *not* auto-promote it.
Returns ``False`` when there is no such event at all (e.g. the task
'''
sticky_doc_after = ''' The cheapest signal that distinguishes the two is the most recent
``"created"`` / ``"blocked"`` / ``"unblocked"`` event for the task.
A ``"created"`` event whose payload has ``status="blocked"`` is the
explicit park requested by ``create_task(initial_status="blocked")``.
A later ``"unblocked"`` event clears either kind of sticky block.
Returns ``False`` when there is no such event at all (e.g. the task
'''
if db_source.count(sticky_doc_before) != 1:
raise SystemExit(
"Hermes Kanban sticky-block documentation changed: expected 1, "
f"found {db_source.count(sticky_doc_before)}"
)
db_source = db_source.replace(sticky_doc_before, sticky_doc_after, 1)
sticky_before = ''' row = conn.execute(
"SELECT kind FROM task_events "
"WHERE task_id = ? AND kind IN ('blocked', 'unblocked') "
"ORDER BY id DESC LIMIT 1",
(task_id,),
).fetchone()
return bool(row) and row["kind"] == "blocked"
'''
sticky_after = ''' row = conn.execute(
"SELECT kind, payload FROM task_events "
"WHERE task_id = ? AND kind IN ('created', 'blocked', 'unblocked') "
"ORDER BY id DESC LIMIT 1",
(task_id,),
).fetchone()
if not row or row["kind"] == "unblocked":
return False
if row["kind"] == "blocked":
return True
try:
payload = json.loads(row["payload"] or "{}")
except (TypeError, ValueError):
return False
if not isinstance(payload, dict):
return False
return payload.get("status") == "blocked"
'''
if db_source.count(sticky_before) != 1:
raise SystemExit(
"Hermes Kanban sticky-block gate changed: expected 1, "
f"found {db_source.count(sticky_before)}"
)
db_source = db_source.replace(sticky_before, sticky_after, 1)
# A manual evidence-based close must not expose a parked task to the dispatcher
# between separate `unblock` and `complete` commands. Upstream already permits
# direct completion from `blocked`; extend the same atomic path to `scheduled`
# and make that contract visible in CLI help so agents do not create a ready
# window that can launch redundant work.
state_before = ''' WHERE id = ?
AND status IN ('running', 'ready', 'blocked')
'''
@ -671,6 +780,10 @@ if cli_source.count(help_before) != 1:
cli_path.write_text(cli_source.replace(help_before, help_after, 1))
PY
COPY dockerfiles/hermes-kanban-blocked-regression.py /tmp/hermes-kanban-blocked-regression.py
RUN /opt/hermes/.venv/bin/python /tmp/hermes-kanban-blocked-regression.py \
&& rm /tmp/hermes-kanban-blocked-regression.py
COPY dockerfiles/hermes-python-sandbox-tool.py /opt/hermes/tools/python_sandbox_tool.py
COPY dockerfiles/hermes-public-extract/__init__.py /opt/hermes/plugins/web/public_extract/__init__.py
COPY dockerfiles/hermes-public-extract/plugin.yaml /opt/hermes/plugins/web/public_extract/plugin.yaml

View File

@ -1,4 +1,5 @@
**
!dockerfiles/hermes-kanban-blocked-regression.py
!dockerfiles/hermes-python-sandbox-tool.py
!dockerfiles/hermes-public-extract/
!dockerfiles/hermes-public-extract/**

View File

@ -0,0 +1,249 @@
"""Regression tests for Hermes Kanban blocked-task scheduling semantics."""
from __future__ import annotations
import json
import os
import tempfile
import unittest
from pathlib import Path
_HERMES_HOME = tempfile.TemporaryDirectory(prefix="hermes-kanban-test-home-")
os.environ["HERMES_HOME"] = _HERMES_HOME.name
from hermes_cli import kanban_db # noqa: E402
class BlockedTaskSchedulingTests(unittest.TestCase):
"""Exercise the real upstream database API against isolated databases."""
def setUp(self) -> None:
self._database_dir = tempfile.TemporaryDirectory(
prefix="hermes-kanban-test-db-"
)
self.connection = kanban_db.connect(
Path(self._database_dir.name) / "kanban.db"
)
def tearDown(self) -> None:
self.connection.close()
self._database_dir.cleanup()
def create_task(self, title: str, **kwargs: object) -> str:
return kanban_db.create_task(self.connection, title=title, **kwargs)
def status(self, task_id: str) -> str:
task = kanban_db.get_task(self.connection, task_id)
self.assertIsNotNone(task)
return task.status
def created_payload(self, task_id: str) -> dict:
"""Return the decoded payload of the task's ``created`` event."""
row = self.connection.execute(
"SELECT payload FROM task_events "
"WHERE task_id = ? AND kind = 'created' ORDER BY id LIMIT 1",
(task_id,),
).fetchone()
self.assertIsNotNone(row, "create_task emitted no 'created' event")
return json.loads(row["payload"] or "{}")
def set_created_payload(self, task_id: str, payload: object) -> None:
"""Overwrite a ``created`` event payload to simulate producer drift."""
with self.connection:
self.connection.execute(
"UPDATE task_events SET payload = ? "
"WHERE task_id = ? AND kind = 'created'",
(payload, task_id),
)
def block_via_circuit_breaker(self, title: str) -> str:
"""Create + claim a normal task, then trip the breaker once on it.
The resulting task is ``blocked`` with exactly one recorded failure and
-- critically -- no ``blocked`` event, because the breaker emits
``gave_up``. Its most recent created/blocked/unblocked event is
therefore its own ``created`` event, which is what makes it the right
probe for the created-event branch of the sticky gate.
"""
task_id = self.create_task(title)
self.assertIsNotNone(kanban_db.claim_task(self.connection, task_id))
self.assertTrue(
kanban_db._record_spawn_failure(
self.connection,
task_id,
"worker failed",
failure_limit=1,
)
)
self.assertEqual(self.status(task_id), "blocked")
return task_id
def test_initial_block_without_parents_is_sticky(self) -> None:
task_id = self.create_task("operator parked", initial_status="blocked")
self.assertEqual(kanban_db.recompute_ready(self.connection), 0)
self.assertEqual(self.status(task_id), "blocked")
def test_initial_block_with_complete_parents_is_sticky(self) -> None:
parent_id = self.create_task("completed prerequisite")
self.assertTrue(kanban_db.complete_task(self.connection, parent_id))
task_id = self.create_task(
"operator parked after prerequisite",
initial_status="blocked",
parents=[parent_id],
)
self.assertEqual(kanban_db.recompute_ready(self.connection), 0)
self.assertEqual(self.status(task_id), "blocked")
def test_initial_block_remains_sticky_when_parent_later_completes(self) -> None:
parent_id = self.create_task("incomplete prerequisite")
task_id = self.create_task(
"operator parked before prerequisite completes",
initial_status="blocked",
parents=[parent_id],
)
self.assertEqual(self.status(task_id), "blocked")
self.assertTrue(kanban_db.complete_task(self.connection, parent_id))
self.assertEqual(self.status(task_id), "blocked")
def test_initial_block_is_released_by_an_explicit_unblock(self) -> None:
task_id = self.create_task("operator parked", initial_status="blocked")
self.assertTrue(kanban_db.unblock_task(self.connection, task_id))
self.assertEqual(self.status(task_id), "ready")
def test_dependency_block_promotes_after_parent_completes(self) -> None:
parent_id = self.create_task("incomplete prerequisite")
task_id = self.create_task("dependency gated", parents=[parent_id])
self.assertEqual(self.status(task_id), "todo")
self.assertTrue(kanban_db.complete_task(self.connection, parent_id))
self.assertEqual(self.status(task_id), "ready")
def test_explicit_block_and_unblock_remain_sticky_and_reversible(self) -> None:
task_id = self.create_task("worker handoff")
self.assertTrue(
kanban_db.block_task(
self.connection,
task_id,
reason="human review required",
)
)
self.assertEqual(kanban_db.recompute_ready(self.connection), 0)
self.assertEqual(self.status(task_id), "blocked")
self.assertTrue(kanban_db.unblock_task(self.connection, task_id))
self.assertEqual(self.status(task_id), "ready")
def test_circuit_breaker_block_is_not_auto_promoted(self) -> None:
task_id = self.create_task("repeated worker failure")
self.assertIsNotNone(kanban_db.claim_task(self.connection, task_id))
# Upstream has no public circuit-breaker entry point; exercise the
# dispatcher helper that owns its persisted failure-limit semantics.
self.assertTrue(
kanban_db._record_spawn_failure(
self.connection,
task_id,
"worker failed",
failure_limit=1,
)
)
self.assertEqual(self.status(task_id), "blocked")
self.assertEqual(
kanban_db.recompute_ready(self.connection, failure_limit=1),
0,
)
self.assertEqual(self.status(task_id), "blocked")
def test_circuit_breaker_block_is_promoted_below_the_failure_limit(self) -> None:
"""Non-sticky oracle for the created-event branch of the sticky gate.
A circuit-breaker block must still auto-recover once the effective
failure limit rises above the recorded failure count -- that is the
pre-existing upstream contract the sticky-block patch must not widen.
This task's most recent created/blocked/unblocked event is its own
``created`` event carrying ``status="ready"``, so it is exactly the
case that a mis-classifying gate strands. It fails if the gate treats
any ``created`` event as a park (over-broad consumer) and it fails if
``create_task`` drifts to labelling every ``created`` event
``"blocked"`` (over-broad producer), while the
circuit-breaker-at-current-limit case above still holds.
"""
task_id = self.block_via_circuit_breaker("recoverable worker failure")
self.assertFalse(
kanban_db._has_sticky_block(self.connection, task_id),
"a circuit-breaker block must never be classified as a park",
)
self.assertEqual(
kanban_db.recompute_ready(self.connection, failure_limit=2),
1,
)
self.assertEqual(self.status(task_id), "ready")
def test_created_event_carries_the_status_the_sticky_gate_reads(self) -> None:
"""Producer contract asserted directly against the real create_task.
The sticky gate reads ``created`` payload ``status``. Pin both poles of
that contract so producer drift is a test failure here as well as a
build failure at the Dockerfile source anchor.
"""
parked_id = self.create_task("operator parked", initial_status="blocked")
normal_id = self.create_task("ordinary work")
self.assertEqual(self.created_payload(parked_id).get("status"), "blocked")
self.assertEqual(self.created_payload(normal_id).get("status"), "ready")
def test_non_blocked_created_payloads_are_not_treated_as_a_park(self) -> None:
"""Only ``status="blocked"`` parks; every other value must promote."""
for payload_status in ("ready", "todo", "running", "triage"):
with self.subTest(payload_status=payload_status):
task_id = self.block_via_circuit_breaker(
f"breaker trip with {payload_status} created payload"
)
self.set_created_payload(
task_id, json.dumps({"status": payload_status})
)
self.assertFalse(
kanban_db._has_sticky_block(self.connection, task_id)
)
self.assertEqual(
kanban_db.recompute_ready(self.connection, failure_limit=2),
1,
)
self.assertEqual(self.status(task_id), "ready")
def test_malformed_created_payloads_fail_closed_to_not_parked(self) -> None:
"""Undecodable or non-object payloads must not park -- or crash.
``recompute_ready`` walks every blocked task in one pass, so an
exception escaping the gate would stall promotion board-wide. Falling
back to "not parked" preserves upstream's pre-patch auto-recover
default for rows the gate cannot interpret.
"""
malformed = (None, "", " ", "{not json", "[]", "null", '"blocked"', "17")
for payload in malformed:
with self.subTest(payload=payload):
task_id = self.block_via_circuit_breaker(
f"breaker trip with payload {payload!r}"
)
self.set_created_payload(task_id, payload)
self.assertFalse(
kanban_db._has_sticky_block(self.connection, task_id)
)
self.assertEqual(
kanban_db.recompute_ready(self.connection, failure_limit=2),
1,
)
self.assertEqual(self.status(task_id), "ready")
if __name__ == "__main__":
unittest.main(verbosity=2)

View File

@ -20,9 +20,9 @@ resources:
- ingress.yaml
images:
- name: registry.bstein.dev/bstein/bstein-dev-home-frontend
newTag: 0.1.1-468 # {"$imagepolicy": "bstein-dev-home:bstein-dev-home-frontend:tag"}
newTag: 0.1.1-471 # {"$imagepolicy": "bstein-dev-home:bstein-dev-home-frontend:tag"}
- name: registry.bstein.dev/bstein/bstein-dev-home-backend
newTag: 0.1.1-468 # {"$imagepolicy": "bstein-dev-home:bstein-dev-home-backend:tag"}
newTag: 0.1.1-471 # {"$imagepolicy": "bstein-dev-home:bstein-dev-home-backend:tag"}
configMapGenerator:
- name: chat-ai-gateway
namespace: bstein-dev-home

View File

@ -25,7 +25,7 @@ spec:
ai.bstein.dev/execution: Hermes Kanban with durable direct Codex and Claude Code CLI workers
ai.bstein.dev/model-policy: Jetson-assisted AUTO routing, low through xhigh, cross-provider fallback
ai.bstein.dev/placement: rpi5 preferred; Jetson deferred until state storage is available
ai.bstein.dev/config-rev: "20260816-ai-usage-poller-v1"
ai.bstein.dev/config-rev: "20260817-ai-usage-exporter-split-v2"
prometheus.io/scrape: "true"
prometheus.io/path: /metrics
prometheus.io/port: "9010"
@ -91,6 +91,7 @@ spec:
vault.hashicorp.com/agent-limits-mem: 128Mi
spec:
serviceAccountName: hermes-agent
enableServiceLinks: false
automountServiceAccountToken: true
securityContext:
fsGroup: 10000
@ -110,7 +111,7 @@ spec:
values: ["true"]
- key: kubernetes.io/hostname
operator: NotIn
values: [titan-08, titan-13, titan-14, titan-17, titan-18]
values: [titan-04, titan-08, titan-13, titan-14, titan-17, titan-18, titan-19]
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
@ -689,7 +690,7 @@ spec:
seccompProfile:
type: RuntimeDefault
resources:
requests: {cpu: 350m, memory: 768Mi}
requests: {cpu: 300m, memory: 768Mi}
limits: {cpu: "3", memory: 6Gi}
- name: oauth2-proxy
image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3@sha256:10a1165743a192e1940b4708fb9647027185ce11a681a1c5519b442ff7f1f561
@ -873,7 +874,7 @@ spec:
- {name: CLAUDE_CONFIG_DIR, value: /runtime-access/claude}
- {name: KUBECONFIG, value: /opt/data/home/.kube/config}
- {name: PYTHONPATH, value: /opt/hermes}
- {name: HERMES_CLI_LANE_CONCURRENCY, value: "4"}
- {name: HERMES_CLI_LANE_CONCURRENCY, value: "2"}
- {name: HERMES_AUTO_ROUTER_PROFILE, value: agent}
- {name: PATH, value: /opt/coordinator:/opt/data/tools/bin:/opt/data/home/.local/bin:/opt/hermes/.venv/bin:/usr/local/bin:/usr/bin:/bin}
securityContext:
@ -896,7 +897,7 @@ spec:
- {name: tmp, mountPath: /tmp}
resources:
requests: {cpu: 100m, memory: 256Mi}
limits: {cpu: "3", memory: 6Gi}
limits: {cpu: "2", memory: 6Gi}
- name: model-steward
image: registry.bstein.dev/bstein/hermes-agent@sha256:81970563e542f0720773e72297810b3a844b83e381e278f25c0916c78d930107
imagePullPolicy: IfNotPresent

View File

@ -58,7 +58,9 @@ configMapGenerator:
- name: hermes-coordinator
namespace: hermes
files:
- ai_usage_codex.py=scripts/ai_usage_codex.py
- ai_usage_exporter.py=scripts/ai_usage_exporter.py
- ai_usage_http.py=scripts/ai_usage_http.py
- claude=scripts/claude
- claude_command_policy.py=scripts/claude_command_policy.py
- cli_lane_goal.py=scripts/cli_lane_goal.py

View File

@ -0,0 +1,138 @@
"""Bounded Codex app-server query and child-process cleanup."""
from __future__ import annotations
import json
import os
import selectors
import subprocess
import time
from typing import Any
CODEX_BIN = os.environ.get("ATLAS_AI_CODEX_BIN", "/opt/data/tools/bin/codex")
CODEX_HOME = os.environ.get("CODEX_HOME", "/runtime-access/codex")
CODEX_CLEANUP_TIMEOUT_SECONDS = 5
def _close_stream(stream: Any) -> bool:
"""Close a subprocess pipe without allowing cleanup errors to escape."""
if stream is None:
return True
try:
stream.close()
except Exception:
return False
return True
def _cleanup_codex_process(
process: subprocess.Popen[str], selector: selectors.BaseSelector | None
) -> bool:
"""Stop and reap a Codex child within two fixed waits, then close its pipes."""
cleanup_ok = True
if selector is not None:
try:
selector.close()
except Exception:
cleanup_ok = False
# Closing the request pipe first also gives a responsive app-server an EOF.
cleanup_ok = _close_stream(getattr(process, "stdin", None)) and cleanup_ok
try:
process.terminate()
except ProcessLookupError:
pass
except Exception:
cleanup_ok = False
needs_kill = False
try:
process.wait(timeout=CODEX_CLEANUP_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
needs_kill = True
except Exception:
cleanup_ok = False
needs_kill = True
if needs_kill:
try:
process.kill()
except ProcessLookupError:
pass
except Exception:
cleanup_ok = False
try:
process.wait(timeout=CODEX_CLEANUP_TIMEOUT_SECONDS)
except Exception:
cleanup_ok = False
cleanup_ok = _close_stream(getattr(process, "stdout", None)) and cleanup_ok
cleanup_ok = _close_stream(getattr(process, "stderr", None)) and cleanup_ok
return cleanup_ok
def query_codex(timeout: float = 20) -> tuple[dict[str, Any], dict[str, Any]]:
"""Read Codex account quota and usage through its structured app-server protocol."""
process = subprocess.Popen(
[CODEX_BIN, "app-server", "--stdio"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
env={**os.environ, "CODEX_HOME": CODEX_HOME},
)
requests = (
{
"id": 1,
"method": "initialize",
"params": {
"clientInfo": {
"name": "atlas-ai-usage-exporter",
"title": "Atlas AI Usage Exporter",
"version": "1.0.0",
},
"capabilities": {"experimentalApi": True},
},
},
{"method": "initialized", "params": {}},
{"id": 2, "method": "account/rateLimits/read", "params": None},
{"id": 3, "method": "account/usage/read", "params": None},
)
selector: selectors.BaseSelector | None = None
rate_result: dict[str, Any]
usage_result: dict[str, Any]
try:
if process.stdin is None or process.stdout is None:
raise RuntimeError("Codex app-server pipes are unavailable")
for message in requests:
process.stdin.write(json.dumps(message, separators=(",", ":")) + "\n")
process.stdin.flush()
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
responses: dict[int, dict[str, Any]] = {}
deadline = time.monotonic() + timeout
while len(responses) < 3 and time.monotonic() < deadline:
for key, _ in selector.select(min(1, max(0, deadline - time.monotonic()))):
line = key.fileobj.readline()
if not line:
continue
message = json.loads(line)
if message.get("id") in (1, 2, 3):
responses[int(message["id"])] = message
for response_id in (1, 2, 3):
response = responses.get(response_id)
if (
not response
or "error" in response
or not isinstance(response.get("result"), dict)
):
raise RuntimeError(f"Codex app-server response {response_id} failed")
rate_result = responses[2]["result"]
usage_result = responses[3]["result"]
finally:
cleanup_ok = _cleanup_codex_process(process, selector)
if not cleanup_ok:
raise RuntimeError("Codex app-server cleanup failed")
return rate_result, usage_result

View File

@ -5,20 +5,18 @@ from __future__ import annotations
import json
import os
import selectors
import subprocess
import threading
import time
from dataclasses import dataclass, field
from datetime import UTC, date, datetime, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.request import Request, urlopen
import ai_usage_codex as codex_query
import ai_usage_http as http_engine
CODEX_BIN = os.environ.get("ATLAS_AI_CODEX_BIN", "/opt/data/tools/bin/codex")
CODEX_HOME = os.environ.get("CODEX_HOME", "/runtime-access/codex")
CLAUDE_CREDENTIALS = Path(
os.environ.get(
"ATLAS_AI_CLAUDE_CREDENTIALS",
@ -48,7 +46,6 @@ METRIC_HELP = {
"atlas_ai_quota_used_percent": "Used percentage in a first-party coding CLI quota window.",
"atlas_ai_quota_window_duration_seconds": "Nominal duration of a coding CLI quota window.",
}
CODEX_CLEANUP_TIMEOUT_SECONDS = 5
POLL_STARTUP_GRACE_SECONDS = 45
POLL_PROGRESS_BUDGET_SECONDS = 60
@ -78,7 +75,9 @@ def _number(value: Any) -> float | None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
converted = float(value)
return converted if converted == converted and abs(converted) != float("inf") else None
return (
converted if converted == converted and abs(converted) != float("inf") else None
)
def _timestamp(value: Any) -> float | None:
@ -115,7 +114,10 @@ def _codex_limit_name(limit_id: str, snapshot: dict[str, Any]) -> str:
def parse_codex_payloads(
rate_response: dict[str, Any], usage_response: dict[str, Any], *, today: date | None = None
rate_response: dict[str, Any],
usage_response: dict[str, Any],
*,
today: date | None = None,
) -> list[Sample]:
"""Convert structured Codex app-server responses into bounded metrics."""
samples: list[Sample] = []
@ -143,15 +145,23 @@ def parse_codex_payloads(
samples.extend(
(
Sample("atlas_ai_quota_used_percent", labels, used),
Sample("atlas_ai_quota_remaining_percent", labels, max(0, 100 - used)),
Sample(
"atlas_ai_quota_remaining_percent", labels, max(0, 100 - used)
),
)
)
reset = _timestamp(raw_window.get("resetsAt"))
duration = _number(raw_window.get("windowDurationMins"))
if reset is not None:
samples.append(Sample("atlas_ai_quota_reset_timestamp_seconds", labels, reset))
samples.append(
Sample("atlas_ai_quota_reset_timestamp_seconds", labels, reset)
)
if duration is not None:
samples.append(Sample("atlas_ai_quota_window_duration_seconds", labels, duration * 60))
samples.append(
Sample(
"atlas_ai_quota_window_duration_seconds", labels, duration * 60
)
)
summary = usage_response.get("summary")
if isinstance(summary, dict):
@ -192,8 +202,16 @@ def parse_codex_payloads(
anchor_day = max((start for start, _ in parsed_daily), default=current_day)
for period, days in (("latest_day", 1), ("seven_day", 7), ("thirty_day", 30)):
earliest = anchor_day - timedelta(days=days - 1)
value = sum(tokens for start, tokens in parsed_daily if earliest <= start <= anchor_day)
samples.append(Sample("atlas_ai_account_tokens", {"provider": "openai", "period": period}, value))
value = sum(
tokens for start, tokens in parsed_daily if earliest <= start <= anchor_day
)
samples.append(
Sample(
"atlas_ai_account_tokens",
{"provider": "openai", "period": period},
value,
)
)
return samples
@ -216,7 +234,9 @@ def parse_claude_payload(payload: dict[str, Any]) -> list[Sample]:
)
reset = _timestamp(window.get("resets_at"))
if reset is not None:
samples.append(Sample("atlas_ai_quota_reset_timestamp_seconds", labels, reset))
samples.append(
Sample("atlas_ai_quota_reset_timestamp_seconds", labels, reset)
)
extra = payload.get("extra_usage")
if isinstance(extra, dict):
enabled = extra.get("is_enabled")
@ -231,123 +251,7 @@ def parse_claude_payload(payload: dict[str, Any]) -> list[Sample]:
return samples
def _close_stream(stream: Any) -> bool:
"""Close a subprocess pipe without allowing cleanup errors to escape."""
if stream is None:
return True
try:
stream.close()
except Exception:
return False
return True
def _cleanup_codex_process(
process: subprocess.Popen[str], selector: selectors.BaseSelector | None
) -> bool:
"""Stop and reap a Codex child within two fixed waits, then close its pipes."""
cleanup_ok = True
if selector is not None:
try:
selector.close()
except Exception:
cleanup_ok = False
# Closing the request pipe first also gives a responsive app-server an EOF.
cleanup_ok = _close_stream(getattr(process, "stdin", None)) and cleanup_ok
try:
process.terminate()
except ProcessLookupError:
pass
except Exception:
cleanup_ok = False
needs_kill = False
try:
process.wait(timeout=CODEX_CLEANUP_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
needs_kill = True
except Exception:
cleanup_ok = False
needs_kill = True
if needs_kill:
try:
process.kill()
except ProcessLookupError:
pass
except Exception:
cleanup_ok = False
try:
process.wait(timeout=CODEX_CLEANUP_TIMEOUT_SECONDS)
except Exception:
cleanup_ok = False
cleanup_ok = _close_stream(getattr(process, "stdout", None)) and cleanup_ok
cleanup_ok = _close_stream(getattr(process, "stderr", None)) and cleanup_ok
return cleanup_ok
def query_codex(timeout: float = 20) -> tuple[dict[str, Any], dict[str, Any]]:
"""Read Codex account quota and usage through its structured app-server protocol."""
process = subprocess.Popen(
[CODEX_BIN, "app-server", "--stdio"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
env={**os.environ, "CODEX_HOME": CODEX_HOME},
)
requests = (
{
"id": 1,
"method": "initialize",
"params": {
"clientInfo": {
"name": "atlas-ai-usage-exporter",
"title": "Atlas AI Usage Exporter",
"version": "1.0.0",
},
"capabilities": {"experimentalApi": True},
},
},
{"method": "initialized", "params": {}},
{"id": 2, "method": "account/rateLimits/read", "params": None},
{"id": 3, "method": "account/usage/read", "params": None},
)
selector: selectors.BaseSelector | None = None
rate_result: dict[str, Any]
usage_result: dict[str, Any]
try:
if process.stdin is None or process.stdout is None:
raise RuntimeError("Codex app-server pipes are unavailable")
for message in requests:
process.stdin.write(json.dumps(message, separators=(",", ":")) + "\n")
process.stdin.flush()
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
responses: dict[int, dict[str, Any]] = {}
deadline = time.monotonic() + timeout
while len(responses) < 3 and time.monotonic() < deadline:
for key, _ in selector.select(min(1, max(0, deadline - time.monotonic()))):
line = key.fileobj.readline()
if not line:
continue
message = json.loads(line)
if message.get("id") in (1, 2, 3):
responses[int(message["id"])] = message
for response_id in (1, 2, 3):
response = responses.get(response_id)
if not response or "error" in response or not isinstance(response.get("result"), dict):
raise RuntimeError(f"Codex app-server response {response_id} failed")
rate_result = responses[2]["result"]
usage_result = responses[3]["result"]
finally:
cleanup_ok = _cleanup_codex_process(process, selector)
if not cleanup_ok:
raise RuntimeError("Codex app-server cleanup failed")
return rate_result, usage_result
query_codex = codex_query.query_codex
def query_claude() -> dict[str, Any]:
@ -393,7 +297,9 @@ class Collector:
) -> None:
"""Record a failed attempt while retaining the provider's last good samples."""
attempted_at = time.time() if started is None else started
duration_started = time.monotonic() if monotonic_started is None else monotonic_started
duration_started = (
time.monotonic() if monotonic_started is None else monotonic_started
)
with self._lock:
state = self._providers[provider]
state.last_attempt = attempted_at
@ -412,7 +318,10 @@ class Collector:
else:
raise ValueError("unknown provider")
except Exception as error:
print(f"{provider} quota collection deferred: {type(error).__name__}", flush=True)
print(
f"{provider} quota collection deferred: {type(error).__name__}",
flush=True,
)
self.record_failure(
provider,
started=started,
@ -440,10 +349,24 @@ class Collector:
samples.extend(state.samples)
samples.extend(
(
Sample("atlas_ai_quota_fetch_success", labels, float(state.fetch_success)),
Sample("atlas_ai_quota_last_attempt_timestamp_seconds", labels, state.last_attempt),
Sample("atlas_ai_quota_last_success_timestamp_seconds", labels, state.last_success),
Sample("atlas_ai_quota_fetch_duration_seconds", labels, state.duration),
Sample(
"atlas_ai_quota_fetch_success",
labels,
float(state.fetch_success),
),
Sample(
"atlas_ai_quota_last_attempt_timestamp_seconds",
labels,
state.last_attempt,
),
Sample(
"atlas_ai_quota_last_success_timestamp_seconds",
labels,
state.last_success,
),
Sample(
"atlas_ai_quota_fetch_duration_seconds", labels, state.duration
),
)
)
lines: list[str] = []
@ -525,7 +448,9 @@ class PollingEngine:
try:
self.poll_once()
except Exception as error:
print(f"quota polling cycle deferred: {type(error).__name__}", flush=True)
print(
f"quota polling cycle deferred: {type(error).__name__}", flush=True
)
time.sleep(self.interval)
def start(self) -> None:
@ -552,47 +477,8 @@ class PollingEngine:
return now - last_progress <= self.progress_timeout
def make_handler(collector: Collector, poller: PollingEngine) -> type[BaseHTTPRequestHandler]:
"""Build an HTTP handler bound to one collector and polling engine."""
class Handler(BaseHTTPRequestHandler):
def _respond(self, status: int, payload: bytes, content_type: str) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self) -> None: # noqa: N802
try:
if self.path == "/metrics":
self._respond(
200,
collector.render(),
"text/plain; version=0.0.4",
)
elif self.path == "/healthz":
healthy = poller.is_healthy()
self._respond(
200 if healthy else 503,
b"ok\n" if healthy else b"poller unhealthy\n",
"text/plain; charset=utf-8",
)
else:
self.send_error(404)
except (BrokenPipeError, ConnectionResetError):
return
def log_message(self, _format: str, *_args: object) -> None:
return
return Handler
class Server(ThreadingHTTPServer):
"""Threaded metrics server that does not retain disconnected clients."""
daemon_threads = True
make_handler = http_engine.make_handler
Server = http_engine.Server
def main() -> int:

View File

@ -0,0 +1,49 @@
"""Disconnect-safe HTTP serving for the AI usage exporter."""
from __future__ import annotations
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
def make_handler(collector: Any, poller: Any) -> type[BaseHTTPRequestHandler]:
"""Build an HTTP handler bound to one collector and polling engine."""
class Handler(BaseHTTPRequestHandler):
def _respond(self, status: int, payload: bytes, content_type: str) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self) -> None: # noqa: N802
try:
if self.path == "/metrics":
self._respond(
200,
collector.render(),
"text/plain; version=0.0.4",
)
elif self.path == "/healthz":
healthy = poller.is_healthy()
self._respond(
200 if healthy else 503,
b"ok\n" if healthy else b"poller unhealthy\n",
"text/plain; charset=utf-8",
)
else:
self.send_error(404)
except (BrokenPipeError, ConnectionResetError):
return
def log_message(self, _format: str, *_args: object) -> None:
return
return Handler
class Server(ThreadingHTTPServer):
"""Threaded metrics server that does not retain disconnected clients."""
daemon_threads = True

View File

@ -15,7 +15,7 @@ data:
METIS_MAX_DEVICE_BYTES: "1000000000000"
METIS_NAMESPACE: maintenance
METIS_REMOTE_POD_TIMEOUT_SEC: "14400"
METIS_RUNNER_IMAGE_AMD64: registry.bstein.dev/bstein/metis:0.1.0-295-amd64 # {"$imagepolicy": "maintenance:metis-amd64"}
METIS_RUNNER_IMAGE_AMD64: registry.bstein.dev/bstein/metis:0.1.0-296-amd64 # {"$imagepolicy": "maintenance:metis-amd64"}
METIS_RUNNER_IMAGE_ARM64: registry.bstein.dev/bstein/metis:0.1.0-295-arm64 # {"$imagepolicy": "maintenance:metis-arm64"}
METIS_HARBOR_REGISTRY: registry.bstein.dev
METIS_HARBOR_PROJECT: metis

View File

@ -11,7 +11,7 @@ resources:
- networking
images:
- name: registry.bstein.dev/bstein/ariadne
newTag: 0.1.0-460 # {"$imagepolicy": "maintenance:ariadne:tag"}
newTag: 0.1.0-461 # {"$imagepolicy": "maintenance:ariadne:tag"}
- name: registry.bstein.dev/bstein/metis
newTag: 0.1.0-295-arm64 # {"$imagepolicy": "maintenance:metis-arm64:tag"}
- name: registry.bstein.dev/bstein/soteria

View File

@ -32,7 +32,7 @@ spec:
kubernetes.io/arch: amd64
containers:
- name: metis-sentinel
image: registry.bstein.dev/bstein/metis-sentinel:0.1.0-295-amd64 # {"$imagepolicy": "maintenance:metis-sentinel-amd64"}
image: registry.bstein.dev/bstein/metis-sentinel:0.1.0-296-amd64 # {"$imagepolicy": "maintenance:metis-sentinel-amd64"}
imagePullPolicy: Always
envFrom:
- configMapRef:

View File

@ -0,0 +1,255 @@
"""Adversarial tests for bounded Codex quota-query process handling."""
from __future__ import annotations
import importlib.util
import json
import subprocess
import sys
from io import StringIO
from pathlib import Path
from types import SimpleNamespace
import pytest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "services/hermes/scripts/ai_usage_codex.py"
def load_module():
"""Load the standalone Codex query helper as a fresh test module."""
name = "ai_usage_codex_tested"
spec = importlib.util.spec_from_file_location(name, SCRIPT)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules[name] = module
spec.loader.exec_module(module)
return module
def test_codex_query_uses_structured_app_server_protocol(tmp_path, monkeypatch):
mod = load_module()
request_log = tmp_path / "requests.jsonl"
mock = tmp_path / "codex-mock"
mock.write_text(
"""#!/usr/bin/env python3
import json, os, sys
messages = [json.loads(sys.stdin.readline()) for _ in range(4)]
with open(os.environ['REQUEST_LOG'], 'w') as handle:
for message in messages:
handle.write(json.dumps(message) + '\\n')
responses = {
1: {},
2: {'rateLimits': {'primary': {'usedPercent': 10}}},
3: {'summary': {}, 'dailyUsageBuckets': []},
}
for response_id, result in responses.items():
print(json.dumps({'id': response_id, 'result': result}), flush=True)
"""
)
mock.chmod(0o755)
monkeypatch.setattr(mod, "CODEX_BIN", str(mock))
monkeypatch.setenv("REQUEST_LOG", str(request_log))
rate, usage = mod.query_codex(timeout=5)
requests = [json.loads(line) for line in request_log.read_text().splitlines()]
assert rate["rateLimits"]["primary"]["usedPercent"] == 10
assert usage["summary"] == {}
assert [request["method"] for request in requests] == [
"initialize",
"initialized",
"account/rateLimits/read",
"account/usage/read",
]
assert all("/status" not in json.dumps(request) for request in requests)
def test_codex_cleanup_is_bounded_when_process_cannot_be_reaped(monkeypatch):
mod = load_module()
processes = []
selectors = []
class StubbornProcess:
def __init__(self, *_args, **_kwargs):
self.stdin = StringIO()
self.stdout = StringIO(
"\n".join(
json.dumps({"id": response_id, "result": result})
for response_id, result in (
(1, {}),
(2, {"rateLimits": {}}),
(3, {"summary": {}, "dailyUsageBuckets": []}),
)
)
+ "\n"
)
self.stderr = None
self.terminate_calls = 0
self.kill_calls = 0
self.wait_timeouts = []
processes.append(self)
def terminate(self):
self.terminate_calls += 1
def kill(self):
self.kill_calls += 1
def wait(self, timeout):
self.wait_timeouts.append(timeout)
raise subprocess.TimeoutExpired("codex-mock", timeout)
class TrackingSelector:
def __init__(self):
self.fileobj = None
self.closed = False
selectors.append(self)
def register(self, fileobj, _events):
self.fileobj = fileobj
def select(self, _timeout):
return [(SimpleNamespace(fileobj=self.fileobj), None)]
def close(self):
self.closed = True
monkeypatch.setattr(mod.subprocess, "Popen", StubbornProcess)
monkeypatch.setattr(mod.selectors, "DefaultSelector", TrackingSelector)
with pytest.raises(RuntimeError, match="^Codex app-server cleanup failed$"):
mod.query_codex(timeout=1)
process = processes[0]
assert process.terminate_calls == 1
assert process.kill_calls == 1
assert process.wait_timeouts == [5, 5]
assert process.stdin.closed
assert process.stdout.closed
assert selectors[0].closed
def test_cleanup_contains_all_pipe_and_process_api_failures():
mod = load_module()
class BrokenStream:
def close(self):
raise OSError("private pipe detail")
class BrokenSelector:
def close(self):
raise OSError("private selector detail")
class BrokenProcess:
stdin = BrokenStream()
stdout = BrokenStream()
stderr = BrokenStream()
def __init__(self):
self.wait_calls = 0
def terminate(self):
raise OSError("private terminate detail")
def wait(self, timeout):
assert timeout == mod.CODEX_CLEANUP_TIMEOUT_SECONDS
self.wait_calls += 1
raise OSError("private wait detail")
def kill(self):
raise OSError("private kill detail")
assert mod._close_stream(None)
assert not mod._close_stream(BrokenStream())
assert not mod._cleanup_codex_process(BrokenProcess(), BrokenSelector())
def test_cleanup_accepts_already_exited_process_during_terminate_and_kill():
mod = load_module()
class AlreadyExited:
stdin = None
stdout = None
stderr = None
def __init__(self, *, timeout_first):
self.timeout_first = timeout_first
self.wait_calls = 0
def terminate(self):
raise ProcessLookupError
def wait(self, timeout):
self.wait_calls += 1
if self.timeout_first and self.wait_calls == 1:
raise subprocess.TimeoutExpired("codex", timeout)
def kill(self):
raise ProcessLookupError
assert mod._cleanup_codex_process(AlreadyExited(timeout_first=False), None)
assert mod._cleanup_codex_process(AlreadyExited(timeout_first=True), None)
def test_query_rejects_missing_pipes_and_structured_errors(monkeypatch):
mod = load_module()
class Process:
stderr = None
def __init__(self, *_args, **_kwargs):
self.stdin = None
self.stdout = None
def terminate(self):
return None
def wait(self, timeout):
return 0
monkeypatch.setattr(mod.subprocess, "Popen", Process)
with pytest.raises(RuntimeError, match="pipes are unavailable"):
mod.query_codex(timeout=0)
class InvalidProcess(Process):
def __init__(self, *_args, **_kwargs):
self.stdin = StringIO()
self.stdout = SequencedOutput()
class SequencedOutput:
def __init__(self):
self.lines = iter(
[
"",
json.dumps({"id": 99, "result": {}}) + "\n",
json.dumps({"id": 1, "result": {}}) + "\n",
json.dumps({"id": 2, "error": {"message": "secret"}}) + "\n",
json.dumps({"id": 3, "result": {}}) + "\n",
]
)
def readline(self):
return next(self.lines)
def close(self):
return None
class Selector:
def register(self, fileobj, _events):
self.fileobj = fileobj
def select(self, _timeout):
return [(SimpleNamespace(fileobj=self.fileobj), None)]
def close(self):
return None
monkeypatch.setattr(mod.subprocess, "Popen", InvalidProcess)
monkeypatch.setattr(mod.selectors, "DefaultSelector", Selector)
with pytest.raises(
RuntimeError, match="^Codex app-server response 2 failed$"
) as caught:
mod.query_codex(timeout=1)
assert "secret" not in str(caught.value)

View File

@ -3,13 +3,10 @@
from __future__ import annotations
import importlib.util
import json
import subprocess
import sys
from datetime import date
from io import BytesIO, StringIO
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[2]
@ -18,6 +15,9 @@ SCRIPT = ROOT / "services/hermes/scripts/ai_usage_exporter.py"
def load_module():
"""Load the standalone exporter script as a test module."""
script_directory = str(SCRIPT.parent)
if script_directory not in sys.path:
sys.path.insert(0, script_directory)
spec = importlib.util.spec_from_file_location("ai_usage_exporter", SCRIPT)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
@ -57,7 +57,9 @@ def test_codex_payloads_include_real_windows_and_bounded_token_periods():
}
samples = mod.parse_codex_payloads(rate, usage, today=date(2026, 8, 16))
values = {(item.name, tuple(sorted(item.labels.items()))): item.value for item in samples}
values = {
(item.name, tuple(sorted(item.labels.items()))): item.value for item in samples
}
codex_labels = (
("limit", "codex"),
@ -72,18 +74,24 @@ def test_codex_payloads_include_real_windows_and_bounded_token_periods():
assert values[("atlas_ai_quota_used_percent", codex_labels)] == 41
assert values[("atlas_ai_quota_remaining_percent", codex_labels)] == 59
assert values[("atlas_ai_quota_used_percent", spark_labels)] == 0
assert values[
(
"atlas_ai_account_tokens",
(("period", "latest_day"), ("provider", "openai")),
)
] == 100
assert values[
(
"atlas_ai_account_tokens",
(("period", "seven_day"), ("provider", "openai")),
)
] == 150
assert (
values[
(
"atlas_ai_account_tokens",
(("period", "latest_day"), ("provider", "openai")),
)
]
== 100
)
assert (
values[
(
"atlas_ai_account_tokens",
(("period", "seven_day"), ("provider", "openai")),
)
]
== 150
)
def test_claude_payload_uses_only_supported_quota_fields():
@ -134,120 +142,21 @@ def test_render_reports_failure_and_freshness_without_logging_credentials():
rendered = collector.render().decode()
assert 'atlas_ai_quota_fetch_success{provider="openai"} 0' in rendered
assert 'atlas_ai_quota_last_success_timestamp_seconds{provider="openai"} 100' in rendered
assert 'atlas_ai_quota_used_percent{limit="codex",provider="openai",window="seven_day"} 42' in rendered
assert (
'atlas_ai_quota_last_success_timestamp_seconds{provider="openai"} 100'
in rendered
)
assert (
'atlas_ai_quota_used_percent{limit="codex",provider="openai",window="seven_day"} 42'
in rendered
)
assert "accessToken" not in rendered
assert "refreshToken" not in rendered
def test_codex_query_uses_structured_app_server_protocol(tmp_path, monkeypatch):
mod = load_module()
request_log = tmp_path / "requests.jsonl"
mock = tmp_path / "codex-mock"
mock.write_text(
"""#!/usr/bin/env python3
import json, os, sys
messages = [json.loads(sys.stdin.readline()) for _ in range(4)]
with open(os.environ['REQUEST_LOG'], 'w') as handle:
for message in messages:
handle.write(json.dumps(message) + '\\n')
responses = {
1: {},
2: {'rateLimits': {'primary': {'usedPercent': 10}}},
3: {'summary': {}, 'dailyUsageBuckets': []},
}
for response_id, result in responses.items():
print(json.dumps({'id': response_id, 'result': result}), flush=True)
"""
)
mock.chmod(0o755)
monkeypatch.setattr(mod, "CODEX_BIN", str(mock))
monkeypatch.setenv("REQUEST_LOG", str(request_log))
rate, usage = mod.query_codex(timeout=5)
requests = [json.loads(line) for line in request_log.read_text().splitlines()]
assert rate["rateLimits"]["primary"]["usedPercent"] == 10
assert usage["summary"] == {}
assert [request["method"] for request in requests] == [
"initialize",
"initialized",
"account/rateLimits/read",
"account/usage/read",
]
assert all("/status" not in json.dumps(request) for request in requests)
def test_codex_cleanup_is_bounded_when_process_cannot_be_reaped(monkeypatch):
mod = load_module()
processes = []
selectors = []
class StubbornProcess:
def __init__(self, *_args, **_kwargs):
self.stdin = StringIO()
self.stdout = StringIO(
"\n".join(
json.dumps({"id": response_id, "result": result})
for response_id, result in (
(1, {}),
(2, {"rateLimits": {}}),
(3, {"summary": {}, "dailyUsageBuckets": []}),
)
)
+ "\n"
)
self.terminate_calls = 0
self.kill_calls = 0
self.wait_timeouts = []
processes.append(self)
def terminate(self):
self.terminate_calls += 1
def kill(self):
self.kill_calls += 1
def wait(self, timeout):
self.wait_timeouts.append(timeout)
raise subprocess.TimeoutExpired("codex-mock", timeout)
class TrackingSelector:
def __init__(self):
self.fileobj = None
self.closed = False
selectors.append(self)
def register(self, fileobj, _events):
self.fileobj = fileobj
def select(self, _timeout):
return [(SimpleNamespace(fileobj=self.fileobj), None)]
def close(self):
self.closed = True
monkeypatch.setattr(mod.subprocess, "Popen", StubbornProcess)
monkeypatch.setattr(mod.selectors, "DefaultSelector", TrackingSelector)
try:
mod.query_codex(timeout=1)
except Exception as error: # The cleanup result must be sanitized and non-TimeoutExpired.
assert type(error) is RuntimeError
assert str(error) == "Codex app-server cleanup failed"
else:
raise AssertionError("unreaped Codex process was reported as successful")
process = processes[0]
assert process.terminate_calls == 1
assert process.kill_calls == 1
assert process.wait_timeouts == [5, 5]
assert process.stdin.closed
assert process.stdout.closed
assert selectors[0].closed
def test_unexpected_provider_failure_is_sanitized_and_preserves_last_good(monkeypatch, capsys):
def test_unexpected_provider_failure_is_sanitized_and_preserves_last_good(
monkeypatch, capsys
):
mod = load_module()
collector = mod.Collector()
previous = mod.Sample(

View File

@ -0,0 +1,275 @@
"""Focused edge coverage for AI usage exporter provider and polling boundaries."""
from __future__ import annotations
import importlib.util
import json
import sys
from io import BytesIO
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "services/hermes/scripts/ai_usage_exporter.py"
def load_module():
"""Load a fresh exporter while making its sibling modules importable."""
script_directory = str(SCRIPT.parent)
if script_directory not in sys.path:
sys.path.insert(0, script_directory)
name = "ai_usage_exporter_coverage"
spec = importlib.util.spec_from_file_location(name, SCRIPT)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules[name] = module
spec.loader.exec_module(module)
return module
def test_parser_rejects_nonfinite_and_malformed_optional_fields():
mod = load_module()
assert mod._number(True) is None
assert mod._number("1") is None
assert mod._number(float("nan")) is None
assert mod._number(float("inf")) is None
assert mod._timestamp(None) is None
assert mod._timestamp("not-a-time") is None
assert mod._window_name({}, "fallback") == "fallback"
assert mod._codex_limit_name("other", {}) == "additional"
samples = mod.parse_codex_payloads(
{
"rateLimitsByLimitId": {
1: {},
"not-a-snapshot": "invalid",
"unnamed": {
"primary": {"usedPercent": None},
"secondary": {
"usedPercent": 120,
"resetsAt": "invalid",
},
},
}
},
{
"summary": {
"lifetimeTokens": None,
"currentStreakDays": 2,
"longestStreakDays": 3,
"longestRunningTurnSec": 4,
},
"dailyUsageBuckets": [
None,
{"startDate": "invalid", "tokens": 2},
{"startDate": "2026-08-17", "tokens": None},
],
},
)
assert any(sample.value == 120 for sample in samples)
assert not any(
sample.name == "atlas_ai_quota_reset_timestamp_seconds" for sample in samples
)
assert mod.parse_codex_payloads({"rateLimits": None}, {"summary": None})
def test_claude_parser_ignores_unbounded_fields_and_invalid_extra_usage():
mod = load_module()
assert mod.parse_claude_payload(
{
"five_hour": {"utilization": None},
"seven_day": {"utilization": 10, "resets_at": None},
"extra_usage": {"is_enabled": "yes"},
}
)
assert mod.parse_claude_payload({"extra_usage": "invalid"}) == []
def test_provider_queries_validate_credentials_and_response_shape(
tmp_path, monkeypatch
):
mod = load_module()
credentials = tmp_path / "credentials.json"
credentials.write_text("{}", encoding="utf-8")
monkeypatch.setattr(mod, "CLAUDE_CREDENTIALS", credentials)
with pytest.raises(RuntimeError, match="credentials are incomplete"):
mod.query_claude()
credentials.write_text(
json.dumps({"claudeAiOauth": {"accessToken": "runtime-only-token"}}),
encoding="utf-8",
)
bodies = iter([{"five_hour": {}}, []])
requests = []
class Response:
def __enter__(self):
return self
def __exit__(self, *_args):
return None
def read(self, maximum):
assert maximum == 1 << 20
return json.dumps(next(bodies)).encode()
def open_request(request, timeout):
requests.append(request)
assert timeout == 15
return Response()
monkeypatch.setattr(mod, "urlopen", open_request)
assert mod.query_claude() == {"five_hour": {}}
assert requests[0].get_header("Authorization") == "Bearer runtime-only-token"
with pytest.raises(RuntimeError, match="response is not an object"):
mod.query_claude()
assert mod.query_codex is mod.codex_query.query_codex
def test_collector_refreshes_both_providers_and_contains_unknown_provider(
monkeypatch, capsys
):
mod = load_module()
collector = mod.Collector()
monkeypatch.setattr(
mod,
"query_codex",
lambda: ({"rateLimits": {"primary": {"usedPercent": 1}}}, {}),
)
monkeypatch.setattr(mod, "query_claude", lambda: {"five_hour": {"utilization": 2}})
collector.refresh_provider("openai")
collector.refresh_provider("anthropic")
assert collector._providers["openai"].fetch_success
assert collector._providers["anthropic"].fetch_success
assert collector._providers["openai"].last_success > 0
collector.record_failure("openai")
assert not collector._providers["openai"].fetch_success
with pytest.raises(KeyError, match="unknown"):
collector.refresh_provider("unknown")
assert "unknown quota collection deferred: ValueError" in capsys.readouterr().out
def test_polling_failure_accounting_and_cycle_errors_are_sanitized(monkeypatch, capsys):
mod = load_module()
secret = "must-not-leak"
class Failure(Exception):
pass
class Collector:
def refresh_provider(self, _provider):
raise Failure(secret)
def record_failure(self, *_args, **_kwargs):
raise Failure(secret)
engine = mod.PollingEngine(Collector(), interval=60)
engine.poll_once()
output = capsys.readouterr().out
assert "quota failure accounting deferred: Failure" in output
assert secret not in output
monkeypatch.setattr(
engine, "poll_once", lambda: (_ for _ in ()).throw(Failure(secret))
)
monkeypatch.setattr(
mod.time, "sleep", lambda _interval: (_ for _ in ()).throw(StopIteration)
)
with pytest.raises(StopIteration):
engine.run()
output = capsys.readouterr().out
assert "quota polling cycle deferred: Failure" in output
assert secret not in output
def test_poller_start_is_idempotent_and_main_wires_server(monkeypatch):
mod = load_module()
threads = []
class Thread:
def __init__(self, **kwargs):
self.kwargs = kwargs
self.started = False
threads.append(self)
def start(self):
self.started = True
monkeypatch.setattr(mod.threading, "Thread", Thread)
engine = mod.PollingEngine(mod.Collector(), interval=60)
engine.start()
engine.start()
assert len(threads) == 1
assert threads[0].started
assert threads[0].kwargs["daemon"] is True
events = []
class Poller:
def __init__(self, collector, *, interval):
events.append(("poller", collector, interval))
def start(self):
events.append("started")
class Server:
def __init__(self, address, handler):
events.append(("server", address, handler))
def serve_forever(self):
events.append("served")
monkeypatch.setattr(mod, "PollingEngine", Poller)
monkeypatch.setattr(mod, "Server", Server)
monkeypatch.setattr(
mod, "make_handler", lambda collector, poller: (collector, poller)
)
monkeypatch.setenv("ATLAS_AI_USAGE_INTERVAL_SECONDS", "1")
monkeypatch.setenv("ATLAS_AI_USAGE_PORT", "19010")
assert mod.main() == 0
assert events[0][0] == "poller"
assert events[0][2] == 60
assert events[2][1][1] == 19010
assert events[-1] == "served"
def test_http_handler_covers_not_found_logging_and_connection_reset():
mod = load_module()
class Collector:
def render(self):
return b"metrics\n"
class Poller:
def is_healthy(self):
return True
handler_class = mod.make_handler(Collector(), Poller())
handler = object.__new__(handler_class)
handler.path = "/missing"
statuses = []
handler.send_error = statuses.append
handler.do_GET()
assert statuses == [404]
assert handler.log_message("ignored") is None
class Reset(BytesIO):
def write(self, _body):
raise ConnectionResetError
handler.path = "/metrics"
handler.send_response = lambda _status: None
handler.send_header = lambda _name, _value: None
handler.end_headers = lambda: None
handler.wfile = Reset()
handler.do_GET()

View File

@ -59,9 +59,7 @@ def test_auto_boundary_selects_only_a_public_switchyard_route(tmp_path, monkeypa
assert source == "auto"
def test_legacy_maximum_default_migrates_to_adaptive_agent_route(
tmp_path, monkeypatch
):
def test_legacy_maximum_default_migrates_to_adaptive_agent_route(tmp_path, monkeypatch):
path = tmp_path / "route-policy.json"
path.write_text(
json.dumps({"mode": "auto", "auto_route": "atlas/auto/maximum"}),
@ -90,9 +88,7 @@ def test_ui_priority_changes_auto_posture_without_selecting_a_target(
assert route in router.AUTO_ROUTES
def test_ui_manual_model_and_effort_are_forwarded_as_constraints(
tmp_path, monkeypatch
):
def test_ui_manual_model_and_effort_are_forwarded_as_constraints(tmp_path, monkeypatch):
monkeypatch.setattr(router, "POLICY_PATH", tmp_path / "route-policy.json")
agent = _agent(
model="atlas/manual/claude/opus",
@ -107,9 +103,7 @@ def test_ui_manual_model_and_effort_are_forwarded_as_constraints(
)
def test_cli_exact_manual_route_remains_exact_across_boundaries(
tmp_path, monkeypatch
):
def test_cli_exact_manual_route_remains_exact_across_boundaries(tmp_path, monkeypatch):
monkeypatch.setattr(router, "POLICY_PATH", tmp_path / "route-policy.json")
agent = _agent(
model="atlas/manual/claude/opus/xhigh",
@ -222,39 +216,58 @@ def test_adapter_contains_no_content_classifier_or_direct_ollama_call():
def test_provider_status_separates_observed_activity_from_plan_quota(monkeypatch):
status = sys.modules["hermes_auto_router"].provider_status_text.__globals__
module = sys.modules[status["provider_status_payload"].__module__]
monkeypatch.setattr(module, "_get_json", lambda url, timeout=3.0: (
{"status": "ok"} if url.endswith("/health") else {
"total_requests": 3,
"total_errors": 1,
"total_tokens": {"total": 900},
"models": {
"route/codex/sol/xhigh": {
"calls": 1,
"errors": 0,
"total_tokens": 600,
"avg_latency_ms": 1200,
monkeypatch.setattr(
module,
"_get_json",
lambda url, timeout=3.0: (
{"status": "ok"}
if url.endswith("/health")
else {
"total_requests": 3,
"total_errors": 1,
"total_tokens": {"total": 900},
"models": {
"route/codex/sol/xhigh": {
"calls": 1,
"errors": 0,
"total_tokens": 600,
"avg_latency_ms": 1200,
},
"route/claude/sonnet/high": {
"calls": 0,
"errors": 1,
"total_tokens": 0,
},
"route/local/qwen2.5-14b/medium": {
"calls": 1,
"errors": 0,
"total_tokens": 300,
},
},
"route/claude/sonnet/high": {
"calls": 0,
"errors": 1,
"total_tokens": 0,
},
"route/local/qwen2.5-14b/medium": {
"calls": 1,
"errors": 0,
"total_tokens": 300,
},
},
"routing_fallbacks": {"unavailable": 1},
"classifier": {"total_requests": 3, "total_errors": 0},
}
))
monkeypatch.setattr(module, "_codex_account", lambda: {
"authenticated": True, "plan": "plus", "quota_reported": False,
})
monkeypatch.setattr(module, "_claude_account", lambda: {
"authenticated": True, "plan": "max", "quota_reported": False,
})
"routing_fallbacks": {"unavailable": 1},
"classifier": {"total_requests": 3, "total_errors": 0},
}
),
)
monkeypatch.setattr(
module,
"_codex_account",
lambda: {
"authenticated": True,
"plan": "plus",
"quota_reported": False,
},
)
monkeypatch.setattr(
module,
"_claude_account",
lambda: {
"authenticated": True,
"plan": "max",
"quota_reported": False,
},
)
monkeypatch.setattr(module, "_fresh_health", lambda *_args, **_kwargs: {})
payload = module.provider_status_payload()
@ -359,15 +372,20 @@ def test_claude_account_treats_a_live_refresh_token_as_refreshable(
status = sys.modules["hermes_auto_router"].provider_status_text.__globals__
module = sys.modules[status["provider_status_payload"].__module__]
path = tmp_path / ".credentials.json"
path.write_text(json.dumps({
"claudeAiOauth": {
"accessToken": "expired-access",
"refreshToken": "live-refresh",
"expiresAt": 1,
"refreshTokenExpiresAt": 32_472_192_000,
"subscriptionType": "max",
}
}), encoding="utf-8")
path.write_text(
json.dumps(
{
"claudeAiOauth": {
"accessToken": "expired-access",
"refreshToken": "live-refresh",
"expiresAt": 1,
"refreshTokenExpiresAt": 32_472_192_000,
"subscriptionType": "max",
}
}
),
encoding="utf-8",
)
monkeypatch.setattr(module, "CLAUDE_AUTH_PATH", path)
account = module._claude_account()
@ -382,13 +400,18 @@ def test_codex_account_treats_a_refresh_token_as_refreshable(tmp_path, monkeypat
status = sys.modules["hermes_auto_router"].provider_status_text.__globals__
module = sys.modules[status["provider_status_payload"].__module__]
path = tmp_path / "auth.json"
path.write_text(json.dumps({
"auth_mode": "chatgpt",
"tokens": {
"access_token": "expired-access",
"refresh_token": "live-refresh",
},
}), encoding="utf-8")
path.write_text(
json.dumps(
{
"auth_mode": "chatgpt",
"tokens": {
"access_token": "expired-access",
"refresh_token": "live-refresh",
},
}
),
encoding="utf-8",
)
monkeypatch.setattr(module, "CODEX_AUTH_PATH", path)
account = module._codex_account()
@ -406,7 +429,8 @@ def test_agent_mounts_provider_status_dashboard_into_auto_router_plugin():
(root / "services/hermes/agent-deployment.yaml").read_text(encoding="utf-8")
)
volume = next(
item for item in deployment["spec"]["template"]["spec"]["volumes"]
item
for item in deployment["spec"]["template"]["spec"]["volumes"]
if item["name"] == "auto-router-plugin"
)
paths = {item["path"] for item in volume["configMap"]["items"]}

View File

@ -120,6 +120,9 @@ def test_agent_image_completes_parked_kanban_tasks_atomically():
"Atomically mark running, ready, blocked, or scheduled tasks done"
in dockerfile
)
assert "kind IN ('created', 'blocked', 'unblocked')" in dockerfile
assert "payload.get(\"status\") == \"blocked\"" in dockerfile
assert "hermes-kanban-blocked-regression.py" in dockerfile
def test_sandbox_shares_only_the_tenant_workspace_without_credentials():

View File

@ -1074,6 +1074,7 @@ def test_agent_uses_one_native_kanban_control_plane():
deployment = _agent_deployment()
pod = deployment["spec"]["template"]["spec"]
assert pod["enableServiceLinks"] is False
names = {item["name"] for item in pod["containers"]}
assert "cli-lane-runner" in names
assert "terminal" in names
@ -1083,6 +1084,49 @@ def test_agent_uses_one_native_kanban_control_plane():
assert "herdr-dispatch" not in rendered
def test_cli_lane_reserves_cpu_headroom_for_ui_and_auth():
deployment = _agent_deployment()
containers = {
item["name"]: item
for item in deployment["spec"]["template"]["spec"]["containers"]
}
lane = containers["cli-lane-runner"]
environment = {item["name"]: item["value"] for item in lane["env"]}
assert environment["HERMES_CLI_LANE_CONCURRENCY"] == "2"
assert lane["resources"] == {
"requests": {"cpu": "100m", "memory": "256Mi"},
"limits": {"cpu": "2", "memory": "6Gi"},
}
def test_agent_avoids_unhealthy_nodes_and_fits_its_remaining_capacity():
"""Placement correction: keep the agent off nodes that cannot hold it.
titan-04 is cordoned after repeated kernel undervoltage and kubelet
failure, and titan-19 was probe/Longhorn unstable under worker load, so
both must join the existing hard exclusions. That leaves titan-05 as the
healthy candidate, which is tight enough on requested CPU that the main
container has to give back 50m to schedule there.
"""
pod = _agent_deployment()["spec"]["template"]["spec"]
hostnames = next(
item
for item in pod["affinity"]["nodeAffinity"][
"requiredDuringSchedulingIgnoredDuringExecution"
]["nodeSelectorTerms"][0]["matchExpressions"]
if item["key"] == "kubernetes.io/hostname"
)
assert hostnames["operator"] == "NotIn"
assert set(hostnames["values"]) >= {"titan-04", "titan-19"}
hermes = next(
item for item in pod["containers"] if item["name"] == "hermes"
)
assert hermes["resources"]["requests"]["cpu"] == "300m"
def test_agent_root_is_stock_dashboard_and_terminal_is_a_separate_path():
deployment = _agent_deployment()
pod = deployment["spec"]["template"]["spec"]