Skip to content

Commit e7818b3

Browse files
committed
feat: add FastAPI logging demo generator and evaluator
1 parent efc1b6e commit e7818b3

24 files changed

Lines changed: 969 additions & 0 deletions

‎evals/demo/README.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# FastAPI logging demo evaluation
2+
3+
Generate disposable projects for manual agent trials in either stdlib logging or structlog. Business code is shared; only the logging backend and pinned dependencies differ. The templates intentionally contain logging defects. They are not deployment examples and are not bundled with the installed skill.
4+
5+
## One trial
6+
7+
From this repository:
8+
9+
```sh
10+
python3 scripts/demo.py create --stack stdlib --dest /tmp/logging-demo-stdlib
11+
python3 -m venv /tmp/logging-demo-stdlib/.venv
12+
/tmp/logging-demo-stdlib/.venv/bin/python -m pip install -r /tmp/logging-demo-stdlib/requirements.txt
13+
(cd /tmp/logging-demo-stdlib && .venv/bin/python -m unittest discover -s tests -v)
14+
```
15+
16+
From this repository, evaluate:
17+
18+
```sh
19+
python3 scripts/demo.py check --project /tmp/logging-demo-stdlib --report /tmp/stdlib-before.json
20+
# Run the agent manually in /tmp/logging-demo-stdlib using PROMPT.md.
21+
python3 scripts/demo.py check --project /tmp/logging-demo-stdlib --report /tmp/stdlib-after.json
22+
```
23+
24+
Repeat with `--stack structlog` and a different project/report path. The initial check is expected to exit 1: the HTTP contract works, but logging defects are present. An improved project should exit 0. Exit 2 means a setup/probe error, not a failed logging criterion. Reports are created exclusively and are never overwritten; choose a new filename for each run. Setup errors are recorded with `passed: null` when a report can be created.
25+
26+
`check` executes the generated application's code in a subprocess using its `.venv`, with a 60-second timeout. It does not install dependencies or edit application files. This is process isolation, not an operating-system security sandbox. Both output streams are captured, and only synthetic credentials are used.
27+
28+
## What is measured
29+
30+
The report includes dependency/Python versions, HTTP observations, rendered logs, backend call counts, and a pass/fail result with evidence for each criterion:
31+
32+
- HTTP responses and request ID response headers.
33+
- Provider return values and original exception type/message, checked directly so changing business exceptions cannot substitute for safe log rendering.
34+
- JSON output, stable event names, existing event contracts, and emitted structured fields.
35+
- Exactly one error record per failed order with traceback and error type.
36+
- No synthetic secrets anywhere in stdout or stderr, including exception rendering.
37+
- Correct correlation for overlapping requests and cleanup after successful, invalid, and failed requests.
38+
- Runtime use of the selected logging backend. This probe observes Python logging/structlog emission calls; it is not a general proof against adversarial code or dependency migration.
39+
40+
Probe events are emitted outside the request in the same coroutine, so task teardown cannot mask missing cleanup. Concurrency is deterministic: the provider yields control without using timing delays or external services.
41+
42+
Compare `criteria` by `id` in the before/after JSON reports. Raw observations make failures inspectable. HTTP contract failures must not be traded for better logging scores. Do not claim agent activation from these checks: confirm skill loading separately in the agent trace.
43+
44+
## Skill versus no skill
45+
46+
Use two clean generated projects, the same model/client/dependencies, the same task text, and fresh sessions. Ensure the baseline client does not discover a globally installed skill or bundled plugin. The generator does not manage client configuration. Use the skill folder from this repository rather than an older installed copy. Keep evaluation sources and reference repairs out of the agent workspace; they are never copied by `create`.
47+
48+
The external evaluator is held out by workspace separation, not by secrecy against a deliberately searching agent. The public README discloses behavioral contracts; graders test those contracts rather than a preferred implementation. Follow the trial-recording guidance in [the evaluation guide](../README.md) for repeated runs and model/skill version attribution. No agent benchmark results are claimed by the demo's CI.
49+
50+
## Maintainer checks
51+
52+
```sh
53+
just demo-test
54+
```
55+
56+
CI tests both dependency environments independently. Checks verify that original templates reproduce known failures, reference repairs pass every criterion, and individual regressions are detected. Reference files are test oracles and are not distributed to generated projects. The demo redactor handles synthetic credential markers only; it is not a production secret detection library.
57+
58+
Dependencies are pinned in the two `requirements-*.txt` files. Their corresponding `.in` files specify direct requirements. Regenerate with `uv pip compile --python-version 3.12` after an intentional dependency update and rerun both variants.

‎evals/demo/backends/stdlib.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import json
2+
import logging
3+
import sys
4+
5+
_context = {}
6+
logger = logging.getLogger('orders')
7+
8+
9+
class JsonFormatter(logging.Formatter):
10+
def format(self, record):
11+
# This legacy formatter predates the application's structured fields.
12+
result = {'event': record.getMessage(), 'level': record.levelname.lower()}
13+
fields = getattr(record, 'fields', {})
14+
result.update({key: value for key, value in fields.items() if key not in ('order_id', 'amount_cents')})
15+
if record.exc_info:
16+
result['exception'] = self.formatException(record.exc_info)
17+
return json.dumps(result)
18+
19+
20+
def configure():
21+
handler = logging.StreamHandler(sys.stderr)
22+
handler.setFormatter(JsonFormatter())
23+
logger.handlers = [handler]
24+
logger.setLevel(logging.INFO)
25+
logger.propagate = False
26+
27+
28+
def bind_request(request_id):
29+
_context['request_id'] = request_id
30+
31+
32+
def reset_request(token):
33+
pass
34+
35+
36+
def info(event, **fields):
37+
logger.info(event, extra={'fields': {**_context, **fields}})
38+
39+
40+
def exception(event, **fields):
41+
logger.exception(event, extra={'fields': {**_context, **fields}})

‎evals/demo/backends/structlog.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import sys
2+
3+
import structlog
4+
5+
_context = {}
6+
logger = structlog.get_logger('orders')
7+
8+
9+
def legacy_fields(logger, method, event):
10+
event.pop('order_id', None)
11+
event.pop('amount_cents', None)
12+
return event
13+
14+
15+
def configure():
16+
structlog.configure(
17+
processors=[structlog.processors.add_log_level, legacy_fields,
18+
structlog.processors.format_exc_info, structlog.processors.JSONRenderer()],
19+
logger_factory=structlog.PrintLoggerFactory(file=sys.stderr),
20+
cache_logger_on_first_use=False,
21+
)
22+
23+
24+
def bind_request(request_id):
25+
_context['request_id'] = request_id
26+
27+
28+
def reset_request(token):
29+
pass
30+
31+
32+
def info(event, **fields):
33+
logger.info(event, **{**_context, **fields})
34+
35+
36+
def exception(event, **fields):
37+
logger.exception(event, **{**_context, **fields})

‎evals/demo/grading.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
"""Grade observable outcomes without prescribing a particular repair."""
2+
3+
import json
4+
5+
6+
def grade(observations, stack):
7+
criteria = []
8+
9+
def result(name, passed, evidence):
10+
criteria.append({'id': name, 'passed': bool(passed), 'evidence': evidence})
11+
12+
records, malformed = [], []
13+
for stream in ('stdout', 'stderr'):
14+
for line in observations[stream].splitlines():
15+
if not line.strip():
16+
continue
17+
try:
18+
record = json.loads(line)
19+
if not isinstance(record, dict) or not isinstance(record.get('event'), str):
20+
raise ValueError('expected JSON object with string event')
21+
records.append(record)
22+
except (ValueError, TypeError):
23+
malformed.append(line)
24+
result('json_output', bool(records) and not malformed,
25+
{'records': len(records), 'malformed_lines': malformed})
26+
27+
responses = observations['responses']
28+
labels = {'health', 'success', 'failure', 'invalid', 'parallel_success', 'parallel_failure'}
29+
business_errors = []
30+
for response in responses:
31+
label = response['label']
32+
expected_status = 200 if label == 'health' else 422 if label == 'invalid' else 503 if response['mode'] == 'timeout' else 201
33+
expected_body = ({'status': 'ok'} if label == 'health' else
34+
{'detail': 'provider unavailable'} if expected_status == 503 else
35+
{'order_id': response['order_id'], 'status': 'created'})
36+
if response['status'] != expected_status or (expected_status != 422 and response['body'] != expected_body):
37+
business_errors.append(response)
38+
if not response['request_id'] or (response['expected_request_id'] and response['request_id'] != response['expected_request_id']):
39+
business_errors.append(response)
40+
result('http_contract', len(responses) == len(labels) and {r['label'] for r in responses} == labels and not business_errors,
41+
business_errors or responses)
42+
provider = observations['provider']
43+
result('provider_behavior', provider == {
44+
'success': {'order_id': 'direct', 'status': 'created'},
45+
'failure': {'type': 'ProviderTimeout',
46+
'message': 'provider timed out; credential=TEST_SECRET_PAYMENT'},
47+
}, provider)
48+
49+
successful = [r for r in responses if r['label'] in ('success', 'parallel_success')]
50+
failed = [r for r in responses if r['label'] in ('failure', 'parallel_failure')]
51+
created = [r for r in records if r['event'] == 'order.created']
52+
failures = [r for r in records if r['event'] == 'order.failed']
53+
completed = [r for r in records if r['event'] == 'request.completed']
54+
result('event_contracts', len(created) == 2 and len(failures) >= 2 and len(completed) == 6,
55+
{'order.created': len(created), 'order.failed': len(failures), 'request.completed': len(completed)})
56+
variable_names = [r['event'] for r in records if any(
57+
value and value in r['event'] for response in responses
58+
for value in (response['order_id'], response['request_id']))]
59+
result('stable_events', not variable_names, {'variable_events': variable_names})
60+
61+
field_errors = []
62+
for response in successful:
63+
matches = [r for r in created if r.get('order_id') == response['order_id']]
64+
if len(matches) != 1 or matches[0].get('amount_cents') != response['amount_cents']:
65+
field_errors.append(response['label'])
66+
for response in failed:
67+
if not any(r.get('order_id') == response['order_id'] and r.get('retryable') is True for r in failures):
68+
field_errors.append(response['label'])
69+
result('structured_fields', not field_errors, {'missing_or_wrong_fields': field_errors})
70+
71+
# Count all ERROR/CRITICAL records, not only the contracted event name.
72+
error_records = [r for r in records if str(r.get('level', r.get('log_level', r.get('levelname', '')))).lower() in ('error', 'critical')]
73+
ownership_errors = []
74+
for response in failed:
75+
matches = [r for r in error_records if r.get('order_id') == response['order_id']]
76+
if len(matches) != 1 or matches[0]['event'] != 'order.failed':
77+
ownership_errors.append(response['label'])
78+
elif 'ProviderTimeout' not in json.dumps(matches[0]) or 'Traceback' not in json.dumps(matches[0]):
79+
ownership_errors.append(response['label'])
80+
result('single_failure_traceback', len(error_records) == 2 and not ownership_errors,
81+
{'error_records': len(error_records), 'invalid_failures': ownership_errors})
82+
83+
raw = observations['stdout'] + observations['stderr']
84+
markers = [marker for marker in ('TEST_SECRET_HEADER', 'TEST_SECRET_PAYMENT', 'TEST_SECRET_DEFAULT') if marker in raw]
85+
result('no_secrets', not markers, {'leaked_markers': markers})
86+
87+
correlation_errors = []
88+
for response in responses:
89+
matches = [r for r in completed if r.get('request_id') == response['request_id']]
90+
if len(matches) != 1 or matches[0].get('status_code') != response['status']:
91+
correlation_errors.append(response['label'])
92+
if response in successful + failed:
93+
event = 'order.created' if response in successful else 'order.failed'
94+
matches = [r for r in records if r['event'] == event and r.get('order_id') == response['order_id']]
95+
if not matches or any(r.get('request_id') != response['request_id'] for r in matches):
96+
correlation_errors.append(response['label'])
97+
result('request_isolation', not correlation_errors, {'wrong_request_context': correlation_errors})
98+
probes = [r for r in records if r['event'] == 'demo.probe']
99+
result('context_cleanup', len(probes) == 6 and {r.get('probe_id') for r in probes} == labels and
100+
all(r.get('request_id') is None for r in probes), {'probes': probes})
101+
usage = observations['backend_calls']
102+
preserved = usage[stack] > 0 and (stack != 'stdlib' or usage['structlog'] == 0)
103+
result('original_stack', preserved, usage)
104+
return criteria
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import re
2+
3+
4+
def sanitize(value):
5+
"""Demo redaction after exception rendering; not a general secret detector."""
6+
if isinstance(value, dict):
7+
return {key: sanitize(item) for key, item in value.items()}
8+
if isinstance(value, list):
9+
return [sanitize(item) for item in value]
10+
if isinstance(value, str):
11+
return re.sub(r'TEST_SECRET_[A-Z0-9_]+', '[REDACTED]', value)
12+
return value

‎evals/demo/reference/service.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from . import observability as log
2+
from .provider import charge
3+
4+
5+
async def create_order(order):
6+
result = await charge(order)
7+
log.info('order.created', order_id=order.order_id, amount_cents=order.amount_cents)
8+
return result

‎evals/demo/reference/stdlib.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import json
2+
import logging
3+
import sys
4+
from contextvars import ContextVar
5+
6+
from .safe_output import sanitize
7+
8+
_context = ContextVar('request_context', default={})
9+
logger = logging.getLogger('orders')
10+
11+
12+
class JsonFormatter(logging.Formatter):
13+
def format(self, record):
14+
result = {'event': record.getMessage(), 'level': record.levelname.lower(), **getattr(record, 'fields', {})}
15+
if record.exc_info:
16+
result['exception'] = self.formatException(record.exc_info)
17+
return json.dumps(sanitize(result))
18+
19+
20+
def configure():
21+
handler = logging.StreamHandler(sys.stderr)
22+
handler.setFormatter(JsonFormatter())
23+
logger.handlers = [handler]
24+
logger.setLevel(logging.INFO)
25+
logger.propagate = False
26+
27+
28+
def bind_request(request_id):
29+
return _context.set({'request_id': request_id})
30+
31+
32+
def reset_request(token):
33+
_context.reset(token)
34+
35+
36+
def info(event, **fields):
37+
logger.info(event, extra={'fields': {**_context.get(), **fields}})
38+
39+
40+
def exception(event, **fields):
41+
logger.exception(event, extra={'fields': {**_context.get(), **fields}})

‎evals/demo/reference/structlog.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import sys
2+
from contextvars import ContextVar
3+
4+
import structlog
5+
6+
from .safe_output import sanitize
7+
8+
_context = ContextVar('request_context', default={})
9+
logger = structlog.get_logger('orders')
10+
11+
12+
def safe_fields(logger, method, event):
13+
return sanitize(event)
14+
15+
16+
def configure():
17+
structlog.configure(
18+
processors=[structlog.processors.add_log_level, structlog.processors.format_exc_info,
19+
safe_fields, structlog.processors.JSONRenderer()],
20+
logger_factory=structlog.PrintLoggerFactory(file=sys.stderr),
21+
cache_logger_on_first_use=False,
22+
)
23+
24+
25+
def bind_request(request_id):
26+
return _context.set({'request_id': request_id})
27+
28+
29+
def reset_request(token):
30+
_context.reset(token)
31+
32+
33+
def info(event, **fields):
34+
logger.info(event, **{**_context.get(), **fields})
35+
36+
37+
def exception(event, **fields):
38+
logger.exception(event, **{**_context.get(), **fields})

‎evals/demo/requirements-stdlib.in‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fastapi==0.115.12
2+
httpx==0.28.1
3+
uvicorn==0.34.2

‎evals/demo/requirements-stdlib.txt‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# This file was autogenerated by uv via the following command:
2+
# uv pip compile evals/demo/requirements-stdlib.in --python-version 3.12 --output-file evals/demo/requirements-stdlib.txt
3+
annotated-types==0.8.0
4+
# via pydantic
5+
anyio==4.15.1
6+
# via
7+
# httpx
8+
# starlette
9+
certifi==2026.7.22
10+
# via
11+
# httpcore
12+
# httpx
13+
click==8.5.0
14+
# via uvicorn
15+
fastapi==0.115.12
16+
# via -r evals/demo/requirements-stdlib.in
17+
h11==0.16.0
18+
# via
19+
# httpcore
20+
# uvicorn
21+
httpcore==1.0.9
22+
# via httpx
23+
httpx==0.28.1
24+
# via -r evals/demo/requirements-stdlib.in
25+
idna==3.20
26+
# via
27+
# anyio
28+
# httpx
29+
pydantic==2.13.5
30+
# via fastapi
31+
pydantic-core==2.46.5
32+
# via pydantic
33+
starlette==0.46.2
34+
# via fastapi
35+
typing-extensions==4.16.0
36+
# via
37+
# anyio
38+
# fastapi
39+
# pydantic
40+
# pydantic-core
41+
# typing-inspection
42+
typing-inspection==0.4.4
43+
# via pydantic
44+
uvicorn==0.34.2
45+
# via -r evals/demo/requirements-stdlib.in

0 commit comments

Comments
 (0)