Skip to content

Commit eecb7f4

Browse files
authored
Fix: make the Python logger a client of the host logger (#2001)
Python and C++ were two logging systems that agreed only on a threshold. `Worker.init()` pushed the `simpler` logger's level into the native state, but a Python record was then formatted by whatever handler sat on the root logger as `[%(levelname)s] %(message)s` — no monotonic timestamp, no thread id. So a Python record could not be ordered against a C++ one no matter where either was written, and it went to the root logger's handler rather than to the host logger's own output. The issue this belongs to is titled *one clock, one grammar, one gate*; the Python side had the gate and neither of the others. Seeding the native threshold now also installs a handler on the `simpler` logger that forwards each record through `unified_log_*`, so every record in the process shares one envelope, one clock and one destination. - One new binding, `_emit_host_log(level, func, message)`, hands an already-formatted message to `HostLogger::log`. The message is passed as a `%s` argument, and a level outside the ladder is refused rather than cast. - A record's level is rounded toward the milder name (`35` becomes `WARN`), the opposite direction from `_normalize_threshold`: asking for a *threshold* of 35 must not silently admit warnings, but a record at 35 is a warning someone gave a custom number. - Forwarding is conditional on the host logger having a destination of its own. It writes to stderr until a run gives it a directory, and the root logger's handler already prints there, so forwarding unconditionally put one record on one stream twice, in two envelopes, for every run that does not ask for diagnostics. The check is per record because the directory arrives with a run's config, after this handler is installed. - `propagate` is deliberately untouched, so a record still reaches the root logger as well. That keeps an interactive console readable and keeps `caplog.at_level(..., logger="simpler")` working — five test files assert on warnings that way. The host log is the complete copy; the console is a view of it. Turning propagation off would make the file the only destination and blind all of them. - The handler is installed where the threshold is seeded, not at import. `import simpler` has to keep working when `_task_interface` is missing or stale, which the build-stamp guard makes routine on every source-tree move until a rebuild, so putting the extension on the import path of the logging surface would lose the logger exactly when it is needed to explain why. Records logged before a worker is initialized stay on the root handler. - The handler swallows its own failures through `handleError`: a logging call must not become the reason a run fails. - Installation takes a module-level lock. `Worker.init()` and `ChipWorker.init()` hold per-instance locks, so nothing above serializes two instances initializing from different threads, and an unguarded check-and-add would let both add a handler and forward every record twice. Tests cover the forwarded level/func/message, that nothing is forwarded while the host log writes to stderr, that propagation and `caplog` survive, idempotent and concurrent installation, the rounding direction, that a failing sink does not raise into its caller, and that `import simpler` installs nothing. Their fixture owns both the handler list and the logger level: this logger is process-global, `configure_logging("null")` earlier in the same file leaves the level at `NUL` without restoring it, and the suite's execution order is not the order the tests are written in, so inheriting either one makes an assertion pass or fail by position rather than by behaviour. One of them exists specifically because the others do not need it: every other test installs the handler itself, so without a test that `_initialize_host_log` installs it, the production line doing so could be deleted with the suite staying green. Verified by removing that line — exactly one test fails. #1945 gave the host logger a configurable destination, so a run's Python records now join its C++ records in `<output_prefix>/host.<pid>.log`. That PR's own description of what stays on the console is corrected here in the same change: it said routing Python's records through the host logger was a separate change, which this is.
1 parent 83598a3 commit eecb7f4

6 files changed

Lines changed: 348 additions & 9 deletions

File tree

‎docs/dfx/host-trace.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,15 @@ part in another. The first non-empty directory in a process wins, and a record
4242
falls back to stderr rather than being lost whenever the file cannot take it: a
4343
path that does not fit, a failed open, a failed write, or a failed flush.
4444

45-
**What stays on the console regardless:** messages Python logs through its own
46-
`logging` module. Those are a second logging system — same threshold, different
47-
envelope, no timestamp — so they are not part of this stream and cannot be
48-
ordered against it. Routing them through the host logger is a separate change.
45+
**Python's own log records are part of this stream too.** Seeding the native
46+
threshold installs a handler on the `simpler` logger that forwards each record
47+
through `unified_log_*`, so a Python `logger.warning(...)` carries the same
48+
envelope and the same clock as a C++ record and lands in the same place. It also
49+
still reaches the root logger, because propagation is left alone — that is what
50+
keeps a console readable and `caplog` working, and it makes the console a view of
51+
the log rather than a second half of it. Records logged before a worker is
52+
initialized have no handler to forward through yet and stay on the root logger.
53+
See [logging.md](../logging.md).
4954

5055
Each process's file is fully buffered. It is flushed when a depth-zero invocation
5156
record completes, which is the point at which the records so far describe a whole

‎docs/logging.md‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ Onboard AICPU uses the CANN dlog format. Device TIMING uses CANN WARN and adds a
245245
| Stage | Action | Source |
246246
| ----- | ------ | ------ |
247247
| Python import | Register `TIMING` / `NUL`; default the `simpler` logger to TIMING | `python/simpler/_log.py` |
248-
| `Worker.init()` | Normalize the Python logger level and seed native state before the first fork | `python/simpler/worker.py` |
248+
| `Worker.init()` | Normalize the Python logger level, seed native state before the first fork, and point the `simpler` logger at the host logger | `python/simpler/worker.py` |
249249
| `ChipWorker.init()` | Re-seed inherited native state in a chip child, then enter C++ | `python/simpler/task_interface.py` |
250250
| `_ChipWorker.init()` | Load sim context and host runtime, then bind each module's logger state | `src/common/worker/chip_worker.cpp` |
251251
| `simpler_init` | Onboard maps the bound threshold to CANN; attach and take executor binaries | `src/common/platform/{onboard,sim}/host/c_api_shared.cpp` |
@@ -258,6 +258,35 @@ reinitialize the worker to apply a new Python configuration. Within a process,
258258
all bound host modules observe a native state update immediately instead of
259259
requiring threshold fan-out to every DSO.
260260

261+
### The Python logger is a client, not a second system
262+
263+
Seeding the native threshold also installs a handler on the `simpler` logger that
264+
forwards each record through `unified_log_*`. Before that, Python and C++ agreed
265+
only on a threshold: a Python record carried `[%(levelname)s] %(message)s` — no
266+
timestamp, no thread id — so it could not be ordered against a C++ record no
267+
matter where either was written, and it went to whatever handler happened to be
268+
on the root logger rather than to the host logger's own output. Now one envelope,
269+
one clock and one destination cover every record in the process.
270+
271+
Two properties this deliberately keeps:
272+
273+
- **Propagation is untouched**, so a record still reaches the root logger as
274+
well. That is what keeps an interactive console readable and what keeps
275+
`caplog.at_level(..., logger="simpler")` working in the tests that assert on
276+
warnings. The host log is the complete copy; the console is a view of it.
277+
- **The handler is installed where the threshold is seeded, not at import.**
278+
`import simpler` must keep working when `_task_interface` is missing or stale —
279+
the build-stamp guard in `simpler/task_interface.py` raises on every
280+
source-tree move until a rebuild — so putting the extension on the import path
281+
of the logging surface would lose the logger exactly when it is needed to say
282+
why. Records logged before a worker is initialized stay on the root logger's
283+
handler.
284+
285+
A record's level is rounded toward the milder name on the way through (`35`
286+
becomes `WARN`), the opposite of how a *threshold* is normalized: asking for a
287+
threshold of 35 must not silently admit warnings, but a record at 35 is a warning
288+
someone gave a custom number.
289+
261290
### Forked chip subprocesses
262291

263292
The hierarchical parent seeds native state before `fork()` and passes the

‎python/bindings/task_interface.cpp‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1698,6 +1698,27 @@ NB_MODULE(_task_interface, m) {
16981698
},
16991699
"Return whether this extension currently emits TIMING-level host spans."
17001700
);
1701+
m.def(
1702+
"_host_log_directory",
1703+
[] {
1704+
const char *bound = HostLogger::get_instance().log_directory();
1705+
return bound == nullptr ? std::string() : std::string(bound);
1706+
},
1707+
"The directory this process's host log is written to, or an empty string while it writes to stderr."
1708+
);
1709+
m.def(
1710+
"_emit_host_log",
1711+
[](int level, const std::string &func, const std::string &message) {
1712+
if (!simpler::log::is_valid_level(level)) return false;
1713+
HostLogger::get_instance().log(
1714+
static_cast<simpler::log::LogLevel>(level), func.c_str(), "%s", message.c_str()
1715+
);
1716+
return true;
1717+
},
1718+
nb::arg("level"), nb::arg("func"), nb::arg("message"),
1719+
"Emit one already-formatted message through the host logger, so a Python record carries the same envelope, "
1720+
"clock and destination as a C++ one. Returns false for a level outside the ladder."
1721+
);
17011722
m.def(
17021723
"_initialize_host_log",
17031724
[](int level) {

‎python/simpler/_log.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"""
2121

2222
import logging
23+
import threading
2324

2425
# DEFAULT_LOG_THRESHOLD is exposed by the _task_interface nanobind module so
2526
# Python and C++ share one constant. During a fresh `pip install -e .` the
@@ -46,6 +47,12 @@
4647
setattr(logging, "NUL", NUL)
4748
setattr(logging, "NULL", NUL) # pytest upcases user's `--log-level null` → NULL
4849

50+
# Two Worker or ChipWorker instances can initialize concurrently from different
51+
# threads, and their locks are per instance, so nothing above serializes the
52+
# handler installation below. Without this, both callers can pass the "already
53+
# installed?" check and add a handler, and every record is then forwarded twice.
54+
_attach_mutex = threading.Lock()
55+
4956
_LOGGER_NAME = "simpler"
5057
_logger = logging.getLogger(_LOGGER_NAME)
5158
if _logger.level == logging.NOTSET:
@@ -72,6 +79,80 @@ def _normalize_threshold(threshold: int) -> int:
7279
return NUL
7380

7481

82+
def _ladder_level(levelno: int) -> int:
83+
"""Map an arbitrary record level down onto the public ladder.
84+
85+
Rounds toward the less severe name, unlike `_normalize_threshold`, which
86+
rounds a *threshold* up: a record at 35 is not an error, it is a warning that
87+
someone gave a custom number.
88+
"""
89+
if levelno >= logging.ERROR:
90+
return logging.ERROR
91+
if levelno >= logging.WARNING:
92+
return logging.WARNING
93+
if levelno >= TIMING:
94+
return TIMING
95+
if levelno >= logging.INFO:
96+
return logging.INFO
97+
return logging.DEBUG
98+
99+
100+
class _UnifiedLogHandler(logging.Handler):
101+
"""Forwards `simpler` records into the host logger the C++ side writes with.
102+
103+
The two were separate logging systems that shared only a threshold. A Python
104+
record carried no timestamp and no thread id, so it could not be ordered
105+
against a C++ record wherever either was written, and it went to whatever
106+
handler happened to be on the root logger rather than to the host logger's
107+
configured output. Forwarding gives every record in the process one envelope,
108+
one clock and one destination.
109+
110+
`propagate` is deliberately left alone, so a record still reaches the root
111+
logger as well: that is what keeps pytest's capture and an interactive
112+
console working. The host log is the complete copy; the console is a view of
113+
it.
114+
115+
Which is also why forwarding is conditional. The host logger writes to stderr
116+
until it is given a directory, and the root logger's handler already prints
117+
there — so forwarding unconditionally would put the same record on the same
118+
stream twice, once in each envelope, for every run that does not ask for
119+
diagnostics. A record is forwarded only once the host log has a destination
120+
of its own. That is checked per record because the directory arrives with a
121+
run's config, after this handler is installed.
122+
"""
123+
124+
def __init__(self, emit_record, host_log_directory):
125+
super().__init__()
126+
self._emit_record = emit_record
127+
self._host_log_directory = host_log_directory
128+
129+
def emit(self, record: logging.LogRecord) -> None:
130+
try:
131+
if not self._host_log_directory():
132+
return
133+
self._emit_record(_ladder_level(record.levelno), record.funcName or "python", self.format(record))
134+
except Exception: # noqa: BLE001 -- a logging sink must never raise into its caller
135+
self.handleError(record)
136+
137+
138+
def attach_unified_log_handler(emit_record, host_log_directory) -> bool:
139+
"""Send `simpler` records to the host logger as well as to the root logger.
140+
141+
Called from the same place that seeds the native log threshold, which is
142+
after the extension is loaded — installing this at import time would put the
143+
extension on the import path of the logging surface, which is the one thing
144+
that has to keep working when the extension is missing or stale.
145+
146+
Idempotent, and atomically so: returns True only for the call that installs
147+
the handler, even when several callers race.
148+
"""
149+
with _attach_mutex:
150+
if any(isinstance(handler, _UnifiedLogHandler) for handler in _logger.handlers):
151+
return False
152+
_logger.addHandler(_UnifiedLogHandler(emit_record, host_log_directory))
153+
return True
154+
155+
75156
def get_current_config() -> int:
76157
"""Return the current threshold for forwarding to ChipWorker.init().
77158

‎python/simpler/task_interface.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@
7272
get_element_size,
7373
read_args_from_blob,
7474
)
75+
from _task_interface import (
76+
_emit_host_log as _native_emit_host_log,
77+
)
78+
from _task_interface import (
79+
_host_log_directory as _native_host_log_directory,
80+
)
7581
from _task_interface import (
7682
_initialize_host_log as _native_initialize_host_log,
7783
)
@@ -1230,13 +1236,21 @@ def committed(self) -> bool:
12301236

12311237

12321238
def _initialize_host_log(log_level: int | None = None) -> None:
1233-
"""Seed the extension-owned host-log state before runtime use or fork."""
1234-
if log_level is None:
1235-
from . import _log # noqa: PLC0415
1239+
"""Seed the extension-owned host-log state before runtime use or fork.
1240+
1241+
Also points the Python `simpler` logger at that same host logger, so the two
1242+
stop being separate logging systems that agree only on a threshold. This is
1243+
the right moment for it: the extension is loaded by definition here, whereas
1244+
installing the handler at import time would put the extension on the import
1245+
path of the logging surface.
1246+
"""
1247+
from . import _log # noqa: PLC0415
12361248

1249+
if log_level is None:
12371250
log_level = _log.get_current_config()
12381251
if not _native_initialize_host_log(int(log_level)):
12391252
raise ValueError(f"unsupported simpler log threshold: {log_level}")
1253+
_log.attach_unified_log_handler(_native_emit_host_log, _native_host_log_directory)
12401254

12411255

12421256
class ChipWorker:

0 commit comments

Comments
 (0)