77def _append(root: Path, sample: TimingSample) ->
None:
78 """Serialize one bounded record under a nonblocking interprocess lock."""
80 path = root /
".option_c" /
"logs" /
"timings.jsonl"
81 path.parent.mkdir(parents=
True, exist_ok=
True)
82 with (path.parent /
"timings.lock").open(
"a+b")
as lock:
90 msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
93 fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
96 data[
"stage"] =
_token(sample.stage)
or "unknown"
97 data[
"scope"] =
_token(sample.scope)
98 data[
"kind"] = sample.kind
if sample.kind
in (
"stage",
"wait")
else "stage"
99 data[
"outcome"] = sample.outcome
if type(sample.outcome)
is int
or sample.outcome
in (
"ok",
"error")
else "error"
100 data[
"files"] = sample.files
if type(sample.files)
is int
and sample.files >= 0
else None
101 line = json.dumps(data, separators=(
",",
":")) +
"\n"
102 with path.open(
"a+", encoding=
"utf-8", newline=
"\n")
as stream:
104 lines = stream.readlines()
105 if len(lines) > 5000:
108 stream.writelines((lines + [line])[-4000:])
110 if lines
and not lines[-1].endswith(
"\n"):
116 msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
118 fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
143def timed_stage(root: Path, stage: str, *, kind: str =
"stage", scope: str |
None =
None, files: int |
None =
None, outcome: int | str =
"ok") -> Iterator[TimingSample]:
144 """Measure one operation and preserve all success and exception semantics."""
146 sample =
TimingSample(datetime.now(timezone.utc).isoformat(), socket.gethostname(), os.cpu_count()
or 1,
_token(stage)
or "unknown", kind=kind, scope=scope, files=files, outcome=outcome)
151 diagnostic = dbg_timed(
"GENERAL", func, label=sample.stage, _depth=3)
153 diagnostic = dbg_timed(
"GENERAL", func, label=sample.stage)
157 diagnostic.__enter__()
161 started = time.perf_counter_ns()
162 cpu = time.process_time_ns()
165 except BaseException
as exc:
166 code = getattr(exc,
"exit_code", getattr(exc,
"code",
None))
167 if isinstance(exc, SystemExit)
and code
is None:
169 sample.outcome = (code
if type(code)
is int
else 1)
if type(outcome)
is int
else "error"
172 sample.wall_ms = max(0, (time.perf_counter_ns() - started) // 1_000_000)
173 sample.cpu_ms = max(0, (time.process_time_ns() - cpu) // 1_000_000)
176 diagnostic.__exit__(
None,
None,
None)
Iterator[TimingSample] timed_stage(Path root, str stage, *, str kind="stage", str|None scope=None, int|None files=None, int|str outcome="ok")