coder-eval 0.8.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coder_eval/.gitattributes +2 -0
- coder_eval/__init__.py +3 -0
- coder_eval/agent.py +302 -0
- coder_eval/agents/__init__.py +41 -0
- coder_eval/agents/_logging.py +89 -0
- coder_eval/agents/antigravity_agent.py +811 -0
- coder_eval/agents/claude_code_agent.py +1701 -0
- coder_eval/agents/codex_agent.py +2055 -0
- coder_eval/agents/noop_agent.py +100 -0
- coder_eval/agents/registry.py +163 -0
- coder_eval/agents/watchdog.py +116 -0
- coder_eval/analysis.py +88 -0
- coder_eval/cli/__init__.py +87 -0
- coder_eval/cli/aggregate_command.py +153 -0
- coder_eval/cli/console.py +7 -0
- coder_eval/cli/evaluate_command.py +164 -0
- coder_eval/cli/plan_command.py +152 -0
- coder_eval/cli/report_command.py +121 -0
- coder_eval/cli/run_command.py +686 -0
- coder_eval/cli/run_helpers.py +137 -0
- coder_eval/cli/run_task_internal_command.py +210 -0
- coder_eval/cli/utils.py +37 -0
- coder_eval/config.py +212 -0
- coder_eval/criteria/__init__.py +163 -0
- coder_eval/criteria/_classification_aggregate.py +106 -0
- coder_eval/criteria/agent_judge.py +425 -0
- coder_eval/criteria/base.py +248 -0
- coder_eval/criteria/classification_match.py +107 -0
- coder_eval/criteria/command_executed.py +181 -0
- coder_eval/criteria/commands_efficiency.py +73 -0
- coder_eval/criteria/file_check.py +119 -0
- coder_eval/criteria/file_contains.py +85 -0
- coder_eval/criteria/file_exists.py +45 -0
- coder_eval/criteria/file_matches_regex.py +86 -0
- coder_eval/criteria/json_check.py +184 -0
- coder_eval/criteria/llm_judge.py +260 -0
- coder_eval/criteria/reference_comparison.py +130 -0
- coder_eval/criteria/run_command.py +220 -0
- coder_eval/criteria/skill_triggered.py +111 -0
- coder_eval/criteria/uipath_eval.py +223 -0
- coder_eval/errors/__init__.py +26 -0
- coder_eval/errors/agent.py +26 -0
- coder_eval/errors/budget.py +28 -0
- coder_eval/errors/categories.py +205 -0
- coder_eval/errors/categorization.py +240 -0
- coder_eval/errors/executor.py +124 -0
- coder_eval/errors/judge.py +12 -0
- coder_eval/errors/retry.py +211 -0
- coder_eval/errors/timeout.py +63 -0
- coder_eval/evaluation/__init__.py +10 -0
- coder_eval/evaluation/checker.py +260 -0
- coder_eval/evaluation/judge_anthropic.py +55 -0
- coder_eval/evaluation/judge_bedrock.py +114 -0
- coder_eval/evaluation/judge_context.py +497 -0
- coder_eval/evaluation/judge_models.py +53 -0
- coder_eval/evaluation/judge_persistence.py +291 -0
- coder_eval/evaluation/judge_usage.py +50 -0
- coder_eval/evaluation/sub_agent.py +231 -0
- coder_eval/evaluation/summaries.py +48 -0
- coder_eval/evaluation/verdict_tool.py +213 -0
- coder_eval/formatting.py +191 -0
- coder_eval/isolation/__init__.py +15 -0
- coder_eval/isolation/docker_runner.py +1253 -0
- coder_eval/logging_config.py +399 -0
- coder_eval/models/__init__.py +337 -0
- coder_eval/models/agent_config.py +373 -0
- coder_eval/models/container_paths.py +26 -0
- coder_eval/models/criteria.py +942 -0
- coder_eval/models/enums.py +121 -0
- coder_eval/models/experiment.py +314 -0
- coder_eval/models/judge.py +90 -0
- coder_eval/models/judge_defaults.py +11 -0
- coder_eval/models/limits.py +89 -0
- coder_eval/models/merge_strategy.py +132 -0
- coder_eval/models/mutations.py +95 -0
- coder_eval/models/results.py +787 -0
- coder_eval/models/routing.py +160 -0
- coder_eval/models/sandbox.py +371 -0
- coder_eval/models/tasks.py +631 -0
- coder_eval/models/telemetry.py +454 -0
- coder_eval/models/templates.py +108 -0
- coder_eval/orchestration/__init__.py +13 -0
- coder_eval/orchestration/batch.py +690 -0
- coder_eval/orchestration/config.py +111 -0
- coder_eval/orchestration/config_merge.py +431 -0
- coder_eval/orchestration/evaluation.py +94 -0
- coder_eval/orchestration/experiment.py +837 -0
- coder_eval/orchestration/overrides.py +206 -0
- coder_eval/orchestration/task_loader.py +437 -0
- coder_eval/orchestrator.py +2078 -0
- coder_eval/path_utils.py +79 -0
- coder_eval/plugins.py +81 -0
- coder_eval/pricing.py +169 -0
- coder_eval/py.typed +0 -0
- coder_eval/reports.py +1066 -0
- coder_eval/reports_experiment.py +761 -0
- coder_eval/reports_html.py +1659 -0
- coder_eval/reports_stats.py +250 -0
- coder_eval/resources/__init__.py +137 -0
- coder_eval/resources/default_experiment.yaml +85 -0
- coder_eval/resources/default_ignore_patterns.yaml +60 -0
- coder_eval/resources/tags.yaml +55 -0
- coder_eval/sandbox.py +1127 -0
- coder_eval/scoring/__init__.py +11 -0
- coder_eval/scoring/ast_similarity.py +38 -0
- coder_eval/scoring/complexity.py +115 -0
- coder_eval/scoring/quality.py +154 -0
- coder_eval/scoring/signature_similarity.py +57 -0
- coder_eval/scoring/similarity.py +103 -0
- coder_eval/scoring/token_similarity.py +44 -0
- coder_eval/simulation/__init__.py +27 -0
- coder_eval/simulation/termination.py +88 -0
- coder_eval/simulation/user_simulator.py +324 -0
- coder_eval/streaming/__init__.py +44 -0
- coder_eval/streaming/callbacks.py +57 -0
- coder_eval/streaming/collector.py +193 -0
- coder_eval/streaming/events.py +198 -0
- coder_eval/streaming/renderers.py +248 -0
- coder_eval/streaming/wire.py +115 -0
- coder_eval/telemetry.py +407 -0
- coder_eval/utils.py +517 -0
- coder_eval-0.8.2.dist-info/METADATA +242 -0
- coder_eval-0.8.2.dist-info/RECORD +127 -0
- coder_eval-0.8.2.dist-info/WHEEL +4 -0
- coder_eval-0.8.2.dist-info/entry_points.txt +5 -0
- coder_eval-0.8.2.dist-info/licenses/LICENSE +201 -0
- coder_eval-0.8.2.dist-info/licenses/NOTICE +18 -0
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
"""Logging configuration for coder_eval.
|
|
2
|
+
|
|
3
|
+
This module provides centralized logging setup with:
|
|
4
|
+
- Color-coded console output (if terminal supports it)
|
|
5
|
+
- Optional file logging
|
|
6
|
+
- ContextVar-based task_id injection for parallel log isolation
|
|
7
|
+
- Customizable log levels
|
|
8
|
+
- Per-task log file persistence via context managers
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
from collections import deque
|
|
16
|
+
from collections.abc import Generator
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from contextvars import ContextVar, Token
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from .path_utils import TASK_LOG_FILENAME
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
APP_LOGGER_NAME = "coder_eval"
|
|
27
|
+
|
|
28
|
+
# Bounded ring-buffer used by ``_LogTailBuffer`` to capture a sanitised tail of
|
|
29
|
+
# task logs for the HTML report. Sized so a 200 KB tail comfortably covers the
|
|
30
|
+
# last few hundred lines of a typical run without bloating ``task.json``.
|
|
31
|
+
DEFAULT_LOG_TAIL_MAX_BYTES = 200_000
|
|
32
|
+
|
|
33
|
+
# ANSI CSI escape sequences (e.g. ``\x1b[31m``). Stripped from the buffered tail
|
|
34
|
+
# only — the on-disk task.log keeps raw bytes so ``tail -f`` renders colour.
|
|
35
|
+
_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
|
|
36
|
+
# C0 control bytes except ``\t`` (\x09) and ``\n`` (\x0a). DEL (\x7f) is left
|
|
37
|
+
# alone — it is rare and harmless in HTML.
|
|
38
|
+
_C0_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _sanitise_log_text(text: str) -> str:
|
|
42
|
+
"""Strip ANSI CSI escapes and most C0 control bytes; keep ``\\t`` and ``\\n``."""
|
|
43
|
+
text = _ANSI_ESCAPE_RE.sub("", text)
|
|
44
|
+
text = _C0_CONTROL_RE.sub("", text)
|
|
45
|
+
return text
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _LogTailBuffer(logging.Handler):
|
|
49
|
+
"""Bounded in-memory ring buffer of formatted log records.
|
|
50
|
+
|
|
51
|
+
Eviction is byte-based (UTF-8) so non-ASCII content doesn't blow past the
|
|
52
|
+
cap. Used by ``task_log_handler`` as a sibling of the on-disk file handler;
|
|
53
|
+
``get_text()`` returns the sanitised concatenation suitable for embedding
|
|
54
|
+
in an HTML report.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, max_bytes: int = DEFAULT_LOG_TAIL_MAX_BYTES) -> None:
|
|
58
|
+
super().__init__()
|
|
59
|
+
self._max_bytes = max_bytes
|
|
60
|
+
self._records: deque[str] = deque()
|
|
61
|
+
self._size: int = 0
|
|
62
|
+
|
|
63
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
64
|
+
try:
|
|
65
|
+
msg = self.format(record)
|
|
66
|
+
except Exception:
|
|
67
|
+
self.handleError(record)
|
|
68
|
+
return
|
|
69
|
+
line = msg + "\n"
|
|
70
|
+
line_bytes = len(line.encode("utf-8"))
|
|
71
|
+
self._records.append(line)
|
|
72
|
+
self._size += line_bytes
|
|
73
|
+
while len(self._records) > 1 and self._size > self._max_bytes:
|
|
74
|
+
old = self._records.popleft()
|
|
75
|
+
self._size -= len(old.encode("utf-8"))
|
|
76
|
+
|
|
77
|
+
def get_text(self) -> str:
|
|
78
|
+
# Acquire the handler's lock so concurrent emit() calls (which also
|
|
79
|
+
# hold self.lock via Handler.handle()) cannot mutate _records while
|
|
80
|
+
# we iterate it for the join. Without this, a watchdog/proxy thread
|
|
81
|
+
# logging during the finally-block tail capture would raise
|
|
82
|
+
# "RuntimeError: deque mutated during iteration".
|
|
83
|
+
self.acquire()
|
|
84
|
+
try:
|
|
85
|
+
return _sanitise_log_text("".join(self._records))
|
|
86
|
+
finally:
|
|
87
|
+
self.release()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ContextVar that tracks the current task_id for the running async context.
|
|
91
|
+
# Each asyncio task gets its own copy, so parallel tasks are isolated.
|
|
92
|
+
# Set by task_log_handler; read by _TaskIdFilter to inject into plain-logger records.
|
|
93
|
+
_current_task_id: ContextVar[str | None] = ContextVar("_current_task_id", default=None)
|
|
94
|
+
|
|
95
|
+
# ANSI color codes for terminal output
|
|
96
|
+
COLORS = {
|
|
97
|
+
"DEBUG": "\033[36m", # Cyan
|
|
98
|
+
"INFO": "\033[32m", # Green
|
|
99
|
+
"WARNING": "\033[33m", # Yellow
|
|
100
|
+
"ERROR": "\033[31m", # Red
|
|
101
|
+
"CRITICAL": "\033[35m", # Magenta
|
|
102
|
+
"RESET": "\033[0m", # Reset
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TaskContextFormatter(logging.Formatter):
|
|
107
|
+
"""Formatter for console output.
|
|
108
|
+
|
|
109
|
+
Renders ``HH:MM:SS [LEVEL ] [task_id] <logger>: <msg>`` where:
|
|
110
|
+
- ``LEVEL`` is left-padded to 7 chars for column alignment. CRITICAL (8)
|
|
111
|
+
overflows by one — acceptable because it's not used in this codebase.
|
|
112
|
+
- ``<logger>`` has the ``coder_eval.`` prefix stripped for readability.
|
|
113
|
+
Non-coder_eval loggers (e.g. ``aiohttp.*``) pass through unchanged.
|
|
114
|
+
- ``[task_id]`` is only rendered when the record carries one.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
_LEVEL_PAD = 7
|
|
118
|
+
|
|
119
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
120
|
+
padded_level = record.levelname.ljust(self._LEVEL_PAD)
|
|
121
|
+
if sys.stderr.isatty():
|
|
122
|
+
color = COLORS.get(record.levelname, COLORS["RESET"])
|
|
123
|
+
level_field = f"{color}{padded_level}{COLORS['RESET']}"
|
|
124
|
+
else:
|
|
125
|
+
level_field = padded_level
|
|
126
|
+
|
|
127
|
+
name = getattr(record, "name", "") or ""
|
|
128
|
+
display_name = name.removeprefix(f"{APP_LOGGER_NAME}.") if isinstance(name, str) else str(name)
|
|
129
|
+
|
|
130
|
+
timestamp = self.formatTime(record, self.datefmt)
|
|
131
|
+
task_id = getattr(record, "task_id", None)
|
|
132
|
+
if task_id:
|
|
133
|
+
return f"{timestamp} [{level_field}] [{task_id}] {display_name}: {record.getMessage()}"
|
|
134
|
+
return f"{timestamp} [{level_field}] {display_name}: {record.getMessage()}"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _inject_task_id_from_contextvar(record: logging.LogRecord) -> str | None:
|
|
138
|
+
"""If ``record`` has no ``task_id`` attribute, copy the value from
|
|
139
|
+
``_current_task_id`` onto it (when set) and return the final value.
|
|
140
|
+
|
|
141
|
+
``None`` is returned when neither the record nor the ContextVar
|
|
142
|
+
carries a task_id, matching the prior behaviour of both filters.
|
|
143
|
+
|
|
144
|
+
Idempotent: an existing ``task_id`` on the record (including empty
|
|
145
|
+
string, which callers may set explicitly to mean "no task_id") is
|
|
146
|
+
preserved and returned as-is.
|
|
147
|
+
"""
|
|
148
|
+
record_task_id: str | None = getattr(record, "task_id", None)
|
|
149
|
+
if record_task_id is None:
|
|
150
|
+
cv_task_id = _current_task_id.get()
|
|
151
|
+
if cv_task_id is not None:
|
|
152
|
+
record.task_id = cv_task_id
|
|
153
|
+
return cv_task_id
|
|
154
|
+
return record_task_id
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class _ConsoleTaskIdInjector(logging.Filter):
|
|
158
|
+
"""Copy ``_current_task_id`` ContextVar onto records via
|
|
159
|
+
``_inject_task_id_from_contextvar`` so the console formatter can render
|
|
160
|
+
``[task_id]``. Idempotent: if ``task_id`` is already set (e.g. via
|
|
161
|
+
``LoggerAdapter`` extra or another filter), it is preserved.
|
|
162
|
+
Always returns True so no records are dropped.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
166
|
+
_inject_task_id_from_contextvar(record)
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def setup_logging(level: str = "INFO", log_file: Path | None = None, verbose: bool = False) -> None:
|
|
171
|
+
"""Configure logging for the application.
|
|
172
|
+
|
|
173
|
+
This configures the 'coder_eval' top-level logger and all child loggers will inherit.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
|
177
|
+
log_file: Optional path to log file
|
|
178
|
+
verbose: If True, set level to DEBUG (overrides level parameter)
|
|
179
|
+
|
|
180
|
+
Example:
|
|
181
|
+
>>> setup_logging(level="INFO", log_file=Path("run.log"))
|
|
182
|
+
>>> logger = logging.getLogger(__name__)
|
|
183
|
+
>>> logger.info("Application started")
|
|
184
|
+
"""
|
|
185
|
+
# Determine effective log level
|
|
186
|
+
log_level = logging.DEBUG if verbose else getattr(logging, level.upper(), logging.INFO)
|
|
187
|
+
|
|
188
|
+
# Get the top-level coder_eval logger (all module loggers will inherit from this)
|
|
189
|
+
app_logger = logging.getLogger(APP_LOGGER_NAME)
|
|
190
|
+
app_logger.setLevel(log_level)
|
|
191
|
+
for h in list(app_logger.handlers):
|
|
192
|
+
app_logger.removeHandler(h)
|
|
193
|
+
h.close()
|
|
194
|
+
|
|
195
|
+
# Console handler (stderr) with colored output
|
|
196
|
+
console_handler = logging.StreamHandler(sys.stderr)
|
|
197
|
+
console_handler.setLevel(log_level)
|
|
198
|
+
console_formatter = TaskContextFormatter(
|
|
199
|
+
fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S"
|
|
200
|
+
)
|
|
201
|
+
console_handler.setFormatter(console_formatter)
|
|
202
|
+
console_handler.addFilter(_ConsoleTaskIdInjector())
|
|
203
|
+
app_logger.addHandler(console_handler)
|
|
204
|
+
|
|
205
|
+
# File handler (optional)
|
|
206
|
+
if log_file:
|
|
207
|
+
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
file_handler = logging.FileHandler(log_file, encoding="utf-8")
|
|
209
|
+
file_handler.setLevel(log_level)
|
|
210
|
+
# File logs don't need colors
|
|
211
|
+
file_formatter = logging.Formatter(
|
|
212
|
+
fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
|
|
213
|
+
)
|
|
214
|
+
file_handler.setFormatter(file_formatter)
|
|
215
|
+
app_logger.addHandler(file_handler)
|
|
216
|
+
|
|
217
|
+
# Prevent propagation to root logger (avoid duplicate logs)
|
|
218
|
+
app_logger.propagate = False
|
|
219
|
+
|
|
220
|
+
# Log initial configuration (at DEBUG level so it doesn't clutter INFO output)
|
|
221
|
+
app_logger.debug(f"Logging configured: level={logging.getLevelName(log_level)}, file={log_file}")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _TaskIdFilter(logging.Filter):
|
|
225
|
+
"""Filter that injects task_id from ContextVar and accepts only matching records.
|
|
226
|
+
|
|
227
|
+
Two responsibilities:
|
|
228
|
+
1. If a record has no task_id, inject from the ContextVar (for plain-logger modules).
|
|
229
|
+
2. Strict equality check — records without task_id are rejected (no cross-contamination).
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
def __init__(self, task_id: str):
|
|
233
|
+
super().__init__()
|
|
234
|
+
self.task_id = task_id
|
|
235
|
+
|
|
236
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
237
|
+
return _inject_task_id_from_contextvar(record) == self.task_id
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# Lock for thread-safe handler add/remove and level restoration in parallel batch runs
|
|
241
|
+
_task_handler_lock = threading.Lock()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class _TaskHandlerRefState:
|
|
246
|
+
"""Mutable module-level state for ``task_log_handler`` ref counting.
|
|
247
|
+
|
|
248
|
+
Replaces the previous monkey-patched attributes on the app logger
|
|
249
|
+
(``_task_handler_count``, ``_task_handler_original_level``). There
|
|
250
|
+
is exactly one app logger (``APP_LOGGER_NAME``), so a single module-
|
|
251
|
+
level instance suffices — no keying needed. All reads and writes
|
|
252
|
+
are guarded by ``_task_handler_lock``.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
count: int = 0
|
|
256
|
+
original_level: int | None = None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
_task_handler_state: _TaskHandlerRefState = _TaskHandlerRefState()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@contextmanager
|
|
263
|
+
def task_log_handler(
|
|
264
|
+
task_log_file: Path, level: int = logging.DEBUG, task_id: str | None = None
|
|
265
|
+
) -> Generator[_LogTailBuffer]:
|
|
266
|
+
"""Context manager for task-specific logging.
|
|
267
|
+
|
|
268
|
+
Attaches a ``FileHandler`` (raw bytes, uncapped) and a sibling
|
|
269
|
+
``_LogTailBuffer`` (sanitised, bounded) to the app logger at the start and
|
|
270
|
+
removes both at the end, guaranteeing cleanup even if exceptions occur. The
|
|
271
|
+
buffer is yielded directly so callers can call ``get_text()`` to capture a
|
|
272
|
+
sanitised tail of the log alongside the on-disk file.
|
|
273
|
+
|
|
274
|
+
When task_id is provided, a filter is applied so that in parallel batch runs
|
|
275
|
+
each task's log file only contains its own messages. The ContextVar
|
|
276
|
+
``_current_task_id`` is set so that plain loggers (no LoggerAdapter)
|
|
277
|
+
automatically get the correct task_id injected by ``_TaskIdFilter``.
|
|
278
|
+
|
|
279
|
+
Thread-safe: uses a lock and reference counting so that concurrent handlers
|
|
280
|
+
correctly restore the original log level when the last handler exits. The
|
|
281
|
+
buffer is a passive sibling and does NOT participate in the refcount.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
task_log_file: Path to task log file
|
|
285
|
+
level: Logging level for file output (default: DEBUG)
|
|
286
|
+
task_id: Optional task ID for filtering in parallel runs
|
|
287
|
+
|
|
288
|
+
Yields:
|
|
289
|
+
``_LogTailBuffer`` exposing ``get_text()`` for the sanitised log tail.
|
|
290
|
+
|
|
291
|
+
Example:
|
|
292
|
+
>>> with task_log_handler(Path("task.log"), task_id="my_task") as log_tail:
|
|
293
|
+
... logger.info("This goes to both console and task.log")
|
|
294
|
+
... tail_text = log_tail.get_text()
|
|
295
|
+
"""
|
|
296
|
+
# Create handler
|
|
297
|
+
handler = logging.FileHandler(task_log_file, mode="w", encoding="utf-8")
|
|
298
|
+
handler.setLevel(level)
|
|
299
|
+
|
|
300
|
+
# Format with full details for file output
|
|
301
|
+
formatter = logging.Formatter(fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
|
302
|
+
handler.setFormatter(formatter)
|
|
303
|
+
|
|
304
|
+
# Sibling in-memory buffer; same level + formatter so the tail mirrors the
|
|
305
|
+
# file content (modulo sanitisation done at get_text() time).
|
|
306
|
+
tail_buffer = _LogTailBuffer()
|
|
307
|
+
tail_buffer.setLevel(level)
|
|
308
|
+
tail_buffer.setFormatter(formatter)
|
|
309
|
+
|
|
310
|
+
# Add task_id filter to prevent cross-contamination in parallel runs.
|
|
311
|
+
# Both handlers share an equivalent filter so the buffer is isolated too.
|
|
312
|
+
task_filter: _TaskIdFilter | None = None
|
|
313
|
+
buffer_filter: _TaskIdFilter | None = None
|
|
314
|
+
if task_id:
|
|
315
|
+
task_filter = _TaskIdFilter(task_id)
|
|
316
|
+
buffer_filter = _TaskIdFilter(task_id)
|
|
317
|
+
handler.addFilter(task_filter)
|
|
318
|
+
tail_buffer.addFilter(buffer_filter)
|
|
319
|
+
|
|
320
|
+
# Thread-safe handler registration with reference-counted level management.
|
|
321
|
+
# Refcount tracks the file handler only; the buffer rides along.
|
|
322
|
+
app_logger = logging.getLogger(APP_LOGGER_NAME)
|
|
323
|
+
with _task_handler_lock:
|
|
324
|
+
if _task_handler_state.count == 0:
|
|
325
|
+
_task_handler_state.original_level = app_logger.level
|
|
326
|
+
_task_handler_state.count += 1
|
|
327
|
+
app_logger.addHandler(handler)
|
|
328
|
+
app_logger.addHandler(tail_buffer)
|
|
329
|
+
if app_logger.level > level:
|
|
330
|
+
app_logger.setLevel(level)
|
|
331
|
+
|
|
332
|
+
# Set ContextVar so plain loggers in this async context get the correct task_id
|
|
333
|
+
token: Token[str | None] | None = None
|
|
334
|
+
if task_id:
|
|
335
|
+
token = _current_task_id.set(task_id)
|
|
336
|
+
|
|
337
|
+
try:
|
|
338
|
+
yield tail_buffer
|
|
339
|
+
finally:
|
|
340
|
+
# Guaranteed cleanup with thread-safe level restoration
|
|
341
|
+
with _task_handler_lock:
|
|
342
|
+
app_logger.removeHandler(handler)
|
|
343
|
+
app_logger.removeHandler(tail_buffer)
|
|
344
|
+
_task_handler_state.count = max(_task_handler_state.count - 1, 0)
|
|
345
|
+
if _task_handler_state.count == 0:
|
|
346
|
+
restored = _task_handler_state.original_level
|
|
347
|
+
if restored is not None:
|
|
348
|
+
app_logger.setLevel(restored)
|
|
349
|
+
_task_handler_state.original_level = None
|
|
350
|
+
# Reset ContextVar (token-based reset restores previous value in nested contexts)
|
|
351
|
+
if token is not None:
|
|
352
|
+
_current_task_id.reset(token)
|
|
353
|
+
handler.close()
|
|
354
|
+
tail_buffer.close()
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def aggregate_task_logs(run_dir: Path) -> None:
|
|
358
|
+
"""Aggregate all task logs into a single experiment.log file.
|
|
359
|
+
|
|
360
|
+
This function should be called after all tasks have completed.
|
|
361
|
+
It creates an experiment.log file by concatenating all task.log files
|
|
362
|
+
with clear separators and metadata.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
run_dir: Path to run directory containing task subdirectories
|
|
366
|
+
|
|
367
|
+
Example:
|
|
368
|
+
>>> # After running tasks
|
|
369
|
+
>>> aggregate_task_logs(Path("runs/2025-10-16_14-25-18"))
|
|
370
|
+
>>> # Creates: runs/2025-10-16_14-25-18/experiment.log
|
|
371
|
+
"""
|
|
372
|
+
run_log_path = run_dir / "experiment.log"
|
|
373
|
+
task_log_paths = sorted(run_dir.glob(f"**/{TASK_LOG_FILENAME}"))
|
|
374
|
+
|
|
375
|
+
if not task_log_paths:
|
|
376
|
+
# No task logs found - create empty experiment.log
|
|
377
|
+
run_log_path.write_text("No task logs found.\n", encoding="utf-8")
|
|
378
|
+
return
|
|
379
|
+
|
|
380
|
+
with open(run_log_path, "w", encoding="utf-8") as outfile:
|
|
381
|
+
outfile.write(f"# Run Log: {run_dir.name}\n")
|
|
382
|
+
outfile.write(f"# Aggregated from {len(task_log_paths)} task(s)\n")
|
|
383
|
+
outfile.write(f"# Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
|
384
|
+
outfile.write("\n" + "=" * 80 + "\n\n")
|
|
385
|
+
|
|
386
|
+
for task_log_file in task_log_paths:
|
|
387
|
+
# Use the path relative to run_dir so nested task ids from dataset
|
|
388
|
+
# fan-out (variant/suite/row) render with full context, not just
|
|
389
|
+
# the leaf directory name. as_posix() keeps the header consistent
|
|
390
|
+
# across platforms (experiment.log is commonly shared / pasted).
|
|
391
|
+
task_id = task_log_file.parent.relative_to(run_dir).as_posix()
|
|
392
|
+
outfile.write(f"\n{'=' * 80}\n")
|
|
393
|
+
outfile.write(f"TASK: {task_id}\n")
|
|
394
|
+
outfile.write(f"{'=' * 80}\n\n")
|
|
395
|
+
|
|
396
|
+
with open(task_log_file, encoding="utf-8") as infile:
|
|
397
|
+
outfile.write(infile.read())
|
|
398
|
+
|
|
399
|
+
outfile.write("\n")
|