Error handling
Catch what you can handle, and leave a record of what you swallowed. A handler with no log, comment or fallback looks exactly like an undiscovered bug.
The rule
| Obligation | Meaning |
|---|---|
| Catch specifically | Name everything the operation raises: file IO OSError; JSON ValueError; ContextVar.reset ValueError for a foreign token, RuntimeError for a spent one. Naming only part of the set turns a swallowed failure into an escaping one. |
| Never swallow a programmer error | AttributeError, TypeError, NameError are defects. A handler broad enough to hide one is narrowed, or logs. |
| Say why | Every remaining swallow has a log line with context or a comment on why ignoring is correct; both when not obvious. |
| Delete pointless handlers | Guarding an operation that swallows its own errors, or catching what cannot be raised. |
Boundaries
A broad except Exception is legitimate where propagation would take down more than the failed operation. It still logs enough to identify the session or operation.
- WebSocket handlers and HTTP routes: would drop the connection
- Thread and worker entry points: would die unobserved
- Callback invocation: caller code inside our loop
- Optional subsystems (memory, project git, usage metering): absence degrades a feature
- Best-effort bookkeeping the next turn re-derives
Log level
| Level | When |
|---|---|
error | The user notices and must act: channel message undelivered after retries, MCP server did not start, adapter stopped for good |
warning | Something was lost the user could notice: unlanded write, stale status, missing record |
info | Expected degraded path in a running process: network wait, retry, model failover, reconnect |
debug | Optional path degraded as designed: absent subsystem, best-effort cache, working fallback; developer traces |
Use exc_info=True and include the session id or equivalent.
What good handlers look like
# A lost durable write, made visible
except OSError:
_log.warning(
"index.json not saved for session %s", session_id, exc_info=True)
# Narrow where a broad catch hid defects
except (ValueError, RuntimeError):
# ContextVar.reset raises ValueError for a token minted in another
# context and RuntimeError for one already spent. Narrowing to only
# the first lets a cancelled turn's spent token escape and replace
# the CancelledError.
_log.debug("context var token already spent or foreign", exc_info=True)
# Optional subsystem, reason stated
except Exception:
# Memory is optional: an unavailable provider degrades to no memory
# block, never a failed turn.
_log.debug("memory system prompt block unavailable", exc_info=True)
The gate
.venv/bin/ruff check .
| Rule | Catches |
|---|---|
E722 | Bare except:, which also swallows KeyboardInterrupt and SystemExit |
S110 | try / except / pass |
T201 | print in library code |
Scope
- Covers all of
openprogram/.tests/andscripts/are muted: a test swallows on purpose to assert what follows; scripts run by hand. - A
per-file-ignores*crosses/, soopenprogram/*.pymutes every module. Check new patterns against a nested file. BLE001is off: a boundary handler that logs and degrades is correct, and those go through review under Boundaries.- Ruff does only this gate; formatting and import order are left alone.
Logging, not print
One module logger, _log = logging.getLogger(__name__). No [module] prefix; a bracketed tag stays only when it carries data, such as [wechat:<account>]. %s arguments, not f-strings.
print is allowed for the following; outside muted paths each call says which with # noqa: T201 - <reason>.
| Use | Example |
|---|---|
| Command output | openprogram cron-worker --list, a shell command the sandbox emulates, an assets.py subcommand |
| A stdout protocol | JSON lines or a sentinel another process reads |
| Terminal prompt or status | QR login, OAuth URL, a foreground run saying it is online and how to stop it |
T201 is muted for openprogram/interfaces/cli/**, worker commands (operations/worker/lifecycle.py, runner.py, startup_log.py, services/**), operations/self_update/**, models/providers/recording/**, **/probe_thinking.py.
Process logging
The library never configures logging. Each entry point calls configure_process_logging() from openprogram/host/process_logging.py once: one stderr handler on the root logger, format %(asctime)s %(levelname)s %(name)s: %(message)s, with httpx, httpcore, websockets, asyncio and mcp at WARNING (full output at DEBUG).
| Process | Default | Why |
|---|---|---|
Worker (run_foreground) | INFO | Stdout and stderr are the worker log, beside [worker +12.3s] lines |
Standalone scheduler (run_forever) | INFO | Its terminal is its log |
Foreground Server (python -m openprogram.interfaces.server) | INFO | Same |
CLI (interfaces/cli/application.py main) | WARNING | The interactive chat shares the terminal |
- A later call in the same process moves the level and adds no handler, so a worker started through the CLI logs at
INFO. The ACP server inside the CLI does this withOPENPROGRAM_ACP_LOG. - A root logger configured by someone else (embedding host, pytest) keeps its handlers.
OPENPROGRAM_LOG_LEVEL(level name, any case) overrides every process; invalid values are ignored.
Implementation status
- Implemented. The package passes
E722,S110andT201.ruffis in thedevextra, configured under[tool.ruff]; CI runs it overopenprogram,tests,scripts. - Handlers around calls that cannot raise or swallow their own errors (
emit_safe,emit_ws_frame) are removed. - The
printin the Server's runtime-log functions (interfaces/server/runtime_management.py,server_runtime/broadcasts.py), which also writeruntime.log, stays and is marked.
Unified execution control: why CancelledError is a BaseException. DAG overview: error as a terminal node status.