Skip to content

Commit 6388f94

Browse files
committed
WS5-2
codetracer-python-recorder/README.md: codetracer-python-recorder/codetracer_python_recorder/cli.py: codetracer-python-recorder/tests/python/unit/test_auto_start.py: design-docs/configurable-trace-filters-implementation-plan.status.md: design-docs/py-api-001.md: Signed-off-by: Tzanko Matev <[email protected]>
1 parent cfe7434 commit 6388f94

File tree

5 files changed

+85
-8
lines changed

5 files changed

+85
-8
lines changed

codetracer-python-recorder/README.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ python -m codetracer_python_recorder \
3030
--trace-dir ./trace-out \
3131
--format json \
3232
--activation-path app/main.py \
33-
--with-diff \
33+
--trace-filter config/trace-filter.toml \
3434
app/main.py --arg=value
3535
```
3636

@@ -40,9 +40,12 @@ python -m codetracer_python_recorder \
4040
integration with the DB backend importer.
4141
- `--activation-path` – optional gate that postpones tracing until the interpreter
4242
executes this file (defaults to the target script).
43-
- `--with-diff` / `--no-with-diff` – records the caller’s preference in
44-
`trace_metadata.json`. The desktop Codetracer CLI is responsible for generating
45-
diff artefacts; the recorder simply surfaces the flag.
43+
- `--trace-filter` – path to a filter file. Provide multiple times or use `//`
44+
separators within a single argument to build a chain. When present, the recorder
45+
prepends the project default `.codetracer/trace-filter.toml` (if found near the
46+
target script) so later entries override the defaults. The
47+
`CODETRACER_TRACE_FILTER` environment variable accepts the same syntax when using
48+
the auto-start hook.
4649

4750
All additional arguments are forwarded to the target script unchanged. The CLI
4851
reuses whichever interpreter launches it so wrappers such as `uv run`, `pipx`,

codetracer-python-recorder/codetracer_python_recorder/cli.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ def _parse_args(argv: Sequence[str]) -> RecorderCLIConfig:
7171
action="append",
7272
help=(
7373
"Path to a trace filter file. Provide multiple times to chain filters; "
74-
"specify multiple paths within a single argument using '//' separators."
74+
"specify multiple paths within a single argument using '//' separators. "
75+
"Filters load after any project default '.codetracer/trace-filter.toml' so "
76+
"later entries override earlier ones; the CODETRACER_TRACE_FILTER "
77+
"environment variable accepts the same syntax for env auto-start."
7578
),
7679
)
7780
parser.add_argument(
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""Unit tests for environment-driven auto-start behaviour."""
2+
from __future__ import annotations
3+
4+
from pathlib import Path
5+
6+
import pytest
7+
8+
from codetracer_python_recorder import auto_start, session
9+
import codetracer_python_recorder.codetracer_python_recorder as backend
10+
11+
12+
@pytest.fixture(autouse=True)
13+
def reset_session_state() -> None:
14+
"""Ensure each test runs with a clean global session handle."""
15+
session._active_session = None
16+
yield
17+
session._active_session = None
18+
19+
20+
def test_auto_start_resolves_filter_chain(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
21+
trace_dir = tmp_path / "trace-output"
22+
filter_dir = tmp_path / "filters"
23+
filter_dir.mkdir()
24+
default_filter = filter_dir / "default.toml"
25+
default_filter.write_text("# default\n", encoding="utf-8")
26+
override_filter = filter_dir / "override.toml"
27+
override_filter.write_text("# override\n", encoding="utf-8")
28+
29+
state: dict[str, bool] = {"active": False}
30+
captured_filters: list[list[str] | None] = []
31+
32+
def fake_start_backend(
33+
path: str,
34+
fmt: str,
35+
activation: str | None,
36+
filters: list[str] | None,
37+
) -> None:
38+
state["active"] = True
39+
captured_filters.append(filters)
40+
41+
def fake_stop_backend() -> None:
42+
state["active"] = False
43+
44+
monkeypatch.setenv(auto_start.ENV_TRACE_PATH, str(trace_dir))
45+
monkeypatch.setenv(
46+
auto_start.ENV_TRACE_FILTER, f"{default_filter}//{override_filter}"
47+
)
48+
49+
monkeypatch.setattr(session, "_start_backend", fake_start_backend)
50+
monkeypatch.setattr(session, "_stop_backend", fake_stop_backend)
51+
monkeypatch.setattr(session, "_flush_backend", lambda: None)
52+
monkeypatch.setattr(session, "_is_tracing_backend", lambda: bool(state["active"]))
53+
monkeypatch.setattr(session, "_configure_policy_from_env", lambda: None)
54+
monkeypatch.setattr(backend, "configure_policy_from_env", lambda: None)
55+
56+
auto_start.auto_start_from_env()
57+
58+
assert len(captured_filters) == 1
59+
assert captured_filters[0] == [
60+
str(default_filter.resolve()),
61+
str(override_filter.resolve()),
62+
]
63+
assert session._active_session is not None
64+
65+
session.stop()
66+
assert state["active"] is False

design-docs/configurable-trace-filters-implementation-plan.status.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- `codetracer-python-recorder/codetracer_python_recorder/session.py` *(WS5 python API wiring)*
1515
- `codetracer-python-recorder/codetracer_python_recorder/cli.py` *(WS5 CLI plumbing)*
1616
- `codetracer-python-recorder/codetracer_python_recorder/auto_start.py` *(WS5 env integration)*
17+
- `codetracer-python-recorder/tests/python/unit/test_auto_start.py` *(WS5 env regression coverage)*
1718
- `codetracer-python-recorder/tests/python/unit/test_session_helpers.py`
1819
- `codetracer-python-recorder/tests/python/unit/test_cli.py`
1920
- `codetracer-python-recorder/Cargo.toml`
@@ -25,7 +26,7 @@
2526
-**WS2 – Filter Model & Loader:** Added `trace_filter::config` with `TraceFilterConfig::from_paths`, strict schema validation, SHA256-backed `FilterSummary`, scope/value structs, and path normalisation for `file:` selectors. Dependencies `toml` and `sha2` wired via `Cargo.toml`. Unit tests cover composition, inheritance guards, unknown keys, IO validation, and literal path normalisation; exercised using `just cargo-test`.
2627
-**WS3 – Runtime Engine & Caching:** Implemented `trace_filter::engine` with `TraceFilterEngine::resolve` caching `ScopeResolution` entries per code id (DashMap), deriving module/object/file metadata, and compiling value policies with ordered pattern evaluation. Added `ValueKind` to align future runtime integration and unit tests proving caching, rule precedence (object > package/file), and relative path normalisation—all exercised via `just cargo-test`.
2728
-**WS4 – RuntimeTracer Integration:** `RuntimeTracer` now accepts an optional `Arc<TraceFilterEngine>`, caches `ScopeResolution` results per code id, and records `filter_scope_skip` when scopes are denied. Value capture helpers honour `ValuePolicy` with a reusable `<redacted>` sentinel, emit per-kind telemetry, and we persist the active filter summary plus skip/redaction counts into `trace_metadata.json`. Bootstrapping now discovers `.codetracer/trace-filter.toml`, instantiates `TraceFilterEngine`, and passes the shared `Arc` into `RuntimeTracer::new`; new `session::bootstrap` tests cover both presence/absence of the default filter and `just cargo-test` (nextest `--no-default-features`) confirms the flow end-to-end.
28-
- 🚧 **WS5 – Python Surface, CLI, Metadata:** In progress. Session helpers normalise chained specs, auto-start honours `CODETRACER_TRACE_FILTER`, PyO3 merges explicit/default chains, and the CLI now exposes `--trace-filter` with test coverage; documentation + env tests remain.
29+
- **WS5 – Python Surface, CLI, Metadata:** Session helpers normalise chained specs, auto-start honours `CODETRACER_TRACE_FILTER`, PyO3 merges explicit/default chains, CLI exposes `--trace-filter`, unit coverage exercises env auto-start filter chaining, and docs/CLI help now describe filter precedence and env wiring.
2930
-**WS6 – Hardening, Benchmarks & Documentation:** Pending prior stages.
3031

3132
## WS5 Progress Checklist
@@ -34,6 +35,6 @@
3435
3. ✅ Updated CLI/env plumbing (`--trace-filter`, `CODETRACER_TRACE_FILTER`) plus unit/integration coverage exercising CLI parsing and end-to-end filter metadata.
3536

3637
## Next Steps
37-
1. Add explicit tests for `CODETRACER_TRACE_FILTER` auto-start behaviour so env-driven sessions verify filter chaining.
38-
2. Draft docs/CLI help updates covering the new flag, env var, and filter discovery precedence ahead of WS5 sign-off.
38+
1. ✅ Added explicit tests for `CODETRACER_TRACE_FILTER` auto-start behaviour so env-driven sessions verify filter chaining (`codetracer_python_recorder/tests/python/unit/test_auto_start.py`).
39+
2. ✅ Drafted docs/CLI help updates covering the new flag, env var, and filter discovery precedence ahead of WS5 sign-off.
3940
3. Plan integration of `TraceFilterConfig::io` toggles with runtime IO capture enablement before moving into WS6.

design-docs/py-api-001.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ class TraceSession:
6161
## Environment Integration
6262
- Auto-start tracing when `CODETRACER_TRACE` is set; the value is interpreted as the output directory.
6363
- When `CODETRACER_FORMAT` is provided, it overrides the default output format.
64+
- Accept `CODETRACER_TRACE_FILTER` with either `//`-separated paths or multiple
65+
entries (mirroring the CLI). The env-driven chain is appended after any
66+
discovered project default `.codetracer/trace-filter.toml`, allowing overrides
67+
to refine or replace default rules.
6468

6569
## Usage Example
6670
```py

0 commit comments

Comments
 (0)