The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): managed-worker stderr goes to a private, redacted, bounded profile log
Teknium7b1a29d41f61
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex 49e122bef77..71bea7b6a38 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -7,7 +7,7 @@ Neither assignment secrets nor launch credentials appear in argv or logs.# Spawned as a bare ``sys.executable -m``: in a PM install that interpreter carries no dependencies# until hermes_bootstrap selects the committed environment, so it must be the first import.try:- import hermes_bootstrap # noqa: F401+ import hermes_bootstrapexcept ModuleNotFoundError as exc:if exc.name != "hermes_bootstrap":raise@@ -382,8 +382,9 @@ def hello():def main():channel = WorkerChannel(os.fdopen(os.dup(sys.stdout.fileno()), 'wb', buffering=0)) # windows-footgun: ok — binary framesos.dup2(sys.stderr.fileno(), sys.stdout.fileno())- # This process's own stderr only (the owner discards it): never the channel, and never the- # profile's log files, which the module contract keeps free of assignment secrets.+ # This process's own stderr only, never the channel. The owner drains it into the profile's+ # private managed-worker.log, redacting each line (patterns plus this worker's launch key and+ # assignment secret) before it reaches disk; this process never opens a profile log itself.if not logger.handlers:logger.addHandler(logging.StreamHandler(sys.stderr))logger.propagate = Falsediff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex a7f65df1e3b..e0ab545d6ef 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -129,6 +129,9 @@ class ManagedWorker:self._requested = Falseself._frames = deque()self._arrived = None+ self.stderr_drain = None+ # Exact secrets this worker was handed; the stderr sink scrubs them besides the patterns.+ self.secrets = []def _write_controls(self):try:@@ -172,6 +175,14 @@ class ManagedWorker:self._arrived.clear()return item+ def drain_stderr(self, path):+ """Route the child's stderr (its tracebacks and redirected prints) into the profile's+ bounded, redacted, private log instead of discarding it."""+ from gateway.session_managed_worker_log import drain_worker_stderr+ self.stderr_drain = threading.Thread(target=drain_worker_stderr, name='managed-stderr-drain', daemon=True,+ args=(self.process.stderr, path, self.process.pid, lambda: self.secrets))+ self.stderr_drain.start()+def control(self, frame):if self.closed.is_set():raise RuntimeStoreError('managed_worker_lost')@@ -265,6 +276,10 @@ class ManagedWorker:self.process.stdout.close()else:self.reader.join(timeout=5)+ if self.stderr_drain is not None:+ self.stderr_drain.join(timeout=5) # EOF once the child is gone; the thread closes it+ elif self.process.stderr is not None:+ self.process.stderr.close()def interrupt_managed(authority, actor, ref, generation):@@ -384,13 +399,17 @@ async def execute_managed(authority, ref, row, policy):env = await asyncio.to_thread(_worker_env, authority)cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]from gateway.session_worker_spawn import acquire_process+ from gateway.session_managed_worker_log import worker_log_path+ log_path = worker_log_path(authority.profile_id)process = await acquire_process(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],- cwd=cwd, stdin=subprocess.PIPE, env=env,- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)+ cwd=cwd, stdin=subprocess.PIPE, env=env, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL if log_path is None else subprocess.PIPE, close_fds=True)except asyncio.CancelledError:# acquire_process owns late-child cleanup; no bootstrap or reservation was sent.return _interrupted_before_bootstrap(authority, row)worker = ManagedWorker(process)+ if log_path is not None:+ worker.drain_stderr(log_path)workers = getattr(authority, '_managed_workers', None)if workers is None:workers = authority._managed_workers = {}@@ -412,6 +431,7 @@ async def execute_managed(authority, ref, row, policy):worker.worker = (scope['pid'], scope['birth'])# The child reads nothing else until the exact reservation has committed.frame = await asyncio.to_thread(_bootstrap, authority, ref, row, policy, scope)+ worker.secrets.extend(v for v in (frame['api_key'], scope['secret']) if isinstance(v, str) and v)await asyncio.to_thread(worker.send, frame)worker.writer.start()while True:diff --git a/gateway/session_managed_worker_log.py b/gateway/session_managed_worker_log.pynew file mode 100644index 00000000000..c93485212bb--- /dev/null+++ b/gateway/session_managed_worker_log.py@@ -0,0 +1,89 @@+"""Bounded, redacted per-profile sink for managed-worker stderr.++The worker routes its own stderr AND its ordinary stdout (``os.dup2``) here, so tracebacks,+provider error echoes and tool prints land in this stream. The owner drains it on a dedicated+thread (an undrained pipe would block the child), redacts every line before it touches disk,+and keeps ``<home>/logs/managed-worker.log`` private (0600) and capped at+``MAX_LOG_BYTES`` plus one rotated copy.+"""+import logging+import os+from pathlib import Path+import threading++logger = logging.getLogger(__name__)++LOG_NAME = 'managed-worker.log'+MAX_LOG_BYTES = 1024 * 1024+# A line longer than this is redacted whole, then cut; the rest of it is discarded.+MAX_LINE_BYTES = 64 * 1024+KEPT_LINE_CHARS = 4096+_locks = {}+_locks_guard = threading.Lock()+++def worker_log_path(profile_id):+ """The owning profile's sink, or None when the authority has no home path (test doubles)."""+ home = Path(str(profile_id))+ return home / 'logs' / LOG_NAME if home.is_absolute() else None+++def _lock_for(path):+ with _locks_guard:+ return _locks.setdefault(str(path), threading.Lock())+++def _append(path, text):+ """Append under the per-file lock; rotate once the cap would be exceeded. 0600 always."""+ from hermes_constants import mkdir_under_hermes_home+ data = text.encode('utf-8', 'replace')+ with _lock_for(path):+ mkdir_under_hermes_home(path.parent)+ try:+ size = path.stat().st_size+ except FileNotFoundError:+ size = 0+ if size and size + len(data) > MAX_LOG_BYTES:+ os.replace(path, path.with_name(LOG_NAME + '.1'))+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)+ try:+ if hasattr(os, 'fchmod'):+ os.fchmod(fd, 0o600)+ os.write(fd, data[:MAX_LOG_BYTES])+ finally:+ os.close(fd)+++def _redact(line, scrub):+ from agent.redact import redact_sensitive_text+ for value in sorted((v for v in scrub() if isinstance(v, str) and v), key=len, reverse=True):+ line = line.replace(value, '***')+ return redact_sensitive_text(line, force=True)+++def drain_worker_stderr(stream, path, pid, scrub):+ """Thread body: read ``stream`` to EOF; ``scrub()`` returns this worker's exact secrets+ (launch key, assignment secret) known so far. Never stops reading on a write failure."""+ skipping = False+ warned = False+ try:+ while True:+ chunk = stream.readline(MAX_LINE_BYTES)+ if not chunk:+ return+ whole = chunk.endswith(b'\n')+ if skipping:+ skipping = not whole+ continue+ skipping = not whole+ try:+ line = _redact(chunk.decode('utf-8', 'replace'), scrub)+ _append(path, f'[pid {pid}] ' + (line if whole else line[:KEPT_LINE_CHARS] + ' [truncated]\n'))+ except Exception as exc:+ # Keep draining regardless: a child blocked on a full stderr pipe would wedge.+ if not warned:+ warned = True+ logger.warning('managed worker log %s not written (%s); dropping its lines', path,+ type(exc).__name__)+ finally:+ stream.close()diff --git a/tests/gateway/test_managed_spawn_cancellation.py b/tests/gateway/test_managed_spawn_cancellation.pyindex 8fd631d2f07..98d2ce5e0fb 100644--- a/tests/gateway/test_managed_spawn_cancellation.py+++ b/tests/gateway/test_managed_spawn_cancellation.py@@ -23,7 +23,7 @@ async def test_cancelled_spawn_reaps_late_child(monkeypatch):return childmonkeypatch.setattr(managed.subprocess, 'Popen', spawn)monkeypatch.setattr(managed, '_worker_env', lambda authority: None)- authority = SimpleNamespace(pending_results={})+ authority = SimpleNamespace(profile_id='profile', pending_results={})task = asyncio.create_task(managed.execute_managed(authority, SimpleNamespace(session_id='s'), {'admission_id': 'unstarted'}, None))try:diff --git a/tests/gateway/test_managed_turn_contract.py b/tests/gateway/test_managed_turn_contract.pyindex 8ba20eaf9be..701fcf7ef0c 100644--- a/tests/gateway/test_managed_turn_contract.py+++ b/tests/gateway/test_managed_turn_contract.py@@ -128,7 +128,7 @@ async def test_stop_during_environment_preparation_prevents_bootstrap(tmp_path,monkeypatch.setattr(managed, '_worker_env', env)monkeypatch.setattr(managed.subprocess, 'Popen', lambda *a, **k: object())monkeypatch.setattr(managed, 'ManagedWorker', Worker)- authority = SimpleNamespace(pending_stops={}, pending_results={})+ authority = SimpleNamespace(profile_id='profile', pending_stops={}, pending_results={})def adopt(sid, generation, worker):if authority.pending_stops.pop(sid, None) == generation:worker.interrupt()diff --git a/tests/gateway/test_managed_worker_stderr_log.py b/tests/gateway/test_managed_worker_stderr_log.pynew file mode 100644index 00000000000..3e3f2015143--- /dev/null+++ b/tests/gateway/test_managed_worker_stderr_log.py@@ -0,0 +1,54 @@+"""Managed-worker stderr (its tracebacks and redirected prints) lands in the owning profile's+private, redacted, size-capped ``logs/managed-worker.log`` instead of being discarded."""+import asyncio+import io+import stat+import subprocess+import sys+from types import SimpleNamespace++import pytest++from gateway.session_contract import SessionRef++SECRET = 'sk-proj-' + 'Q' * 40+CRASH = f"""import sys+sys.stderr.write('Traceback (most recent call last):\\n')+sys.stderr.write('RuntimeError: provider refused api_key={SECRET} Authorization: Bearer {SECRET}\\n')+sys.stderr.flush()+raise SystemExit(1)+"""++[email protected]("linux")+def test_worker_stderr_reaches_a_private_redacted_profile_log(tmp_path, monkeypatch):+ from gateway import session_managed_worker as managed+ original = subprocess.Popen++ def crashing_child(args, **kwargs):+ return original([sys.executable, '-c', CRASH], **kwargs)+ monkeypatch.setattr(managed.subprocess, 'Popen', crashing_child)+ monkeypatch.setattr(managed, '_worker_env', lambda authority: None)+ authority = SimpleNamespace(profile_id=str(tmp_path), pending_results={}, waiters={},+ adopt_agent=lambda session_id, generation, worker: None)+ row = {'admission_id': 'adm', 'principal_id': 'owner', 'generation': 3, 'payload': {'text': 'go'}}+ with pytest.raises(EOFError):+ asyncio.run(asyncio.wait_for(managed.execute_managed(authority, SessionRef('p', 's'), row, None), 20))+ log = tmp_path / 'logs' / 'managed-worker.log'+ text = log.read_text()+ assert 'Traceback (most recent call last)' in text and 'RuntimeError: provider refused' in text+ assert SECRET not in text and 'QQQQQQQQQQ' not in text+ assert stat.S_IMODE(log.stat().st_mode) == 0o600+++def test_worker_log_is_bounded_and_scrubs_the_workers_exact_secrets(tmp_path):+ from gateway.session_managed_worker_log import LOG_NAME, MAX_LOG_BYTES, drain_worker_stderr+ path = tmp_path / 'logs' / LOG_NAME+ assignment = 'opaque-assignment-secret-value'+ noise = (f'line {assignment} ' + 'x' * 200 + '\n') * 12_000 + 'y' * 300_000 + '\nlast\n'+ drain_worker_stderr(io.BytesIO(noise.encode()), path, 7, lambda: [assignment])+ files = [path.with_name(LOG_NAME + '.1'), path] # oldest first+ assert all(f.stat().st_size <= MAX_LOG_BYTES for f in files)+ assert not list(path.parent.glob(LOG_NAME + '.2'))+ text = ''.join(f.read_text() for f in files)+ assert assignment not in text and '[truncated]' in text and text.endswith('[pid 7] last\n')