Skip to content

Commit c513435

Browse files
authored
Merge pull request #2 from mrKazzila/update-by-mattpocock
Update by mattpocock
2 parents 672f081 + ca83e00 commit c513435

16 files changed

Lines changed: 177 additions & 47 deletions

File tree

‎.agents/skills/python-structured-logging/SKILL.md‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@ description: Review or improve Python logging with structlog, stdlib logging, or
77

88
Make logs useful operational events while preserving the user's scope and project contracts.
99

10+
## Workflow
11+
12+
1. Determine whether the request is a review, a local logging change, or integration work. Review requests produce findings without edits.
13+
2. Trace the affected logging path: its API, formatter/processors, event consumers, and failure owner as relevant. For a local change, stop when you can identify where the changed event renders and which contracts it touches; record unavailable configuration as an assumption.
14+
3. Read the matching resources below, perform the requested work, and verify the applicable completion criteria.
15+
1016
## Scope and contracts
1117

12-
- Review requests need findings with locations and concrete effects, not edits.
13-
- Inspect the logger API, formatter/processors, event conventions, and failure ownership. Keep the stack and wrappers; migration requires authorization.
18+
- Keep the stack and wrappers; migration requires authorization.
1419
- Preserve business behavior, signatures, exception propagation, and retry decisions.
1520
- Event names and fields may feed alerts, dashboards, and queries. Preserve existing contracts, including dotted names. Before an authorized rename, inspect available consumers and explain their updates; report external consumers you cannot verify.
1621
- With no existing convention, use stable `snake_case` events such as `invoice_processed` and put variable values in fields. Follow existing field names; give new units explicit keys such as `duration_ms`.
@@ -26,7 +31,7 @@ Read the matching example pair for substantial refactoring, integration setup, o
2631

2732
Read only the relevant reference when:
2833

29-
- Changing formatters/processors, diagnosing missing fields, serialization, or duplicate handlers: [output pipeline](references/output-pipeline.md).
34+
- Changing formatters/processors, configuring runtime logging, diagnosing missing fields, serialization, or duplicate handlers, or checking sensitive data across output paths: [output pipeline](references/output-pipeline.md).
3035
- Working with cross-module or concurrent context or cleanup: [context lifecycle](references/context-lifecycle.md).
3136
- Resolving failure ownership or sanitizing exception output: [exceptions and sensitive data](references/exceptions-and-sensitive-data.md).
3237

@@ -40,10 +45,12 @@ Read only the relevant reference when:
4045

4146
## Verify
4247

43-
Use focused tests/output capture proportional to the change, through the complete configured runtime output boundary (see [output pipeline](references/output-pipeline.md)):
48+
Choose checks for the affected behavior; combine criteria when a task spans branches:
4449

45-
- Contracts and application behavior preserved; fields survive formatting without API errors.
46-
- One appropriate failure record, with traceback when needed; no sensitive values in fields, messages, or rendered exceptions.
47-
- Request/job context isolated and cleaned up.
50+
- **Review:** each finding has a location, concrete effect, and supporting evidence. Distinguish observed defects from unverified risks. Static review is sufficient when it establishes the finding; report runtime assumptions without requiring application startup.
51+
- **Local change:** capture the changed event through the configured formatter, or a representative formatter when runtime configuration is unavailable. Confirm added fields survive and affected event contracts and application behavior remain intact. Keep checks scoped to the changed path.
52+
- **Pipeline or sensitive-output change:** capture the complete configured runtime output boundary described in [output pipeline](references/output-pipeline.md), including failure and fallback paths. Verify configured output format and absence of sensitive values in fields, messages, and rendered exceptions.
53+
- **Failure ownership change:** exercise the affected failure path; verify one appropriate failure record, traceback when needed, and unchanged propagation/retry behavior.
54+
- **Context change:** exercise overlapping operations and cleanup on success and failure; check parent-context restoration for nested scopes.
4855

49-
Report checks performed and unverified pipeline assumptions.
56+
Report checks performed, their observed results, and unverified pipeline assumptions. A representative formatter check does not establish full runtime safety.

‎.agents/skills/python-structured-logging/references/Python Logging Style Guide.md‎

Lines changed: 0 additions & 14 deletions
This file was deleted.

‎.agents/skills/python-structured-logging/references/context-lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,5 @@ For a structlog application already using contextvars, check that `merge_context
77
Test two overlapping requests with distinct IDs and a subsequent operation with no ID. Their outputs must not share identifiers. Thread/task boundaries and hybrid sync/async frameworks may require explicit propagation; do not assume every execution context shares the same values.
88

99
For stdlib, retain the existing adapter, filter, or record factory. Check the supported Python version and adapter behavior before relying on per-call `extra` merging.
10+
11+
Source: [structlog context variables](https://www.structlog.org/en/stable/contextvars.html).

‎.agents/skills/python-structured-logging/references/exceptions-and-sensitive-data.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
Choose the owner based on the call chain: a request boundary, worker, or command may already record failures. Adding another exception log below it can duplicate alerts. If a lower layer owns the only failure record and propagates the exception, document that its caller must not log it again.
44

5-
`logger.exception` normally renders the exception message too. Allowlisting structured fields alone does not sanitize credentials embedded in a URL, exception text, or captured locals. Exercise the configured sanitizer with synthetic sensitive values and inspect its final output. Never use real secrets as fixtures.
5+
`logger.exception` normally renders the exception message too. Allowlisting structured fields alone does not sanitize credentials embedded in a URL, exception text, or captured locals. Exercise the configured sanitizer with synthetic sensitive values and inspect its final output. Never use real secrets as fixtures. When changing sanitization or checking safety across output paths, follow [output pipeline](output-pipeline.md) to cover runtime loggers and formatter fallback as well as application records.
66

77
The paired examples use a non-retryable negative amount to illustrate preserved behavior. Both versions raise the same exception for the same input. The good version changes logging only; it does not add retry logic or invent payment metadata.

‎.agents/skills/python-structured-logging/references/output-pipeline.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ Capture the final rendered output as well as records. Check JSON decoding where
99
At the application's configuration boundary, include framework/server/access/error/lifecycle loggers and the actual stdout/stderr or collector path, not just the application logger. Exercise an unexpected failure through that runtime: a safe application formatter is insufficient if another output path can emit raw data. Keep reusable modules free of global logging configuration.
1010

1111
Formatter failure is part of this safety boundary. Probe non-finite numbers, unsupported objects and cyclic structured values through the public logging API, including stdlib `handleError`/diagnostic fallback. Use bounded safe normalization or a safe structured fallback: logging must not raise into application code, disclose the original exception/source through fallback, or emit invalid JSON when JSON is the output contract. Capture both streams and verify that a subsequent event still emits; silent record loss is not a successful fallback.
12+
13+
Sources: [Python logging API](https://docs.python.org/3/library/logging.html), [logging cookbook](https://docs.python.org/3/howto/logging-cookbook.html).

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ The skill inspects the logging stack already in use before changing anything. If
5656

5757
- Main skill: [`plugins/python-structured-logging/skills/python-structured-logging/SKILL.md`](plugins/python-structured-logging/skills/python-structured-logging/SKILL.md)
5858
- Examples: [`examples/structlog`](plugins/python-structured-logging/skills/python-structured-logging/examples/structlog) and [`examples/stdlib`](plugins/python-structured-logging/skills/python-structured-logging/examples/stdlib)
59-
- Reference guide: [`references/Python Logging Style Guide.md`](plugins/python-structured-logging/skills/python-structured-logging/references/Python Logging Style Guide.md)
59+
- References: [output pipeline](plugins/python-structured-logging/skills/python-structured-logging/references/output-pipeline.md), [context lifecycle](plugins/python-structured-logging/skills/python-structured-logging/references/context-lifecycle.md), and [exceptions and sensitive data](plugins/python-structured-logging/skills/python-structured-logging/references/exceptions-and-sensitive-data.md)
6060
- Agent metadata: [`agents/openai.yaml`](plugins/python-structured-logging/skills/python-structured-logging/agents/openai.yaml)
6161

6262
## When to Use This Skill

‎evals/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ These cases evaluate agent decisions separately from deterministic repository ch
44

55
For a complete generated HTTP application with before/after checks, see the [FastAPI demo](demo/README.md).
66

7+
## Decision coverage
8+
9+
Compare `event_contract` with `event_contract_discovery`: the former explicitly states the contract, while the latter leaves event consumers in the project for the agent to discover. `local_change_scope` checks whether a single-field request stays local and whether verification claims match the captured boundary. `wrapper_api` exercises a mapping-based facade rather than a standard logger API.
10+
11+
`indirect_context_activation` asks for correlation without naming logging or the skill. Together with `unrelated_python_with_logging` and `unrelated_cli`, it probes both missed activation and false positives. Inspect skill-load traces rather than inferring activation from the final code. These are unbenchmarked scenarios, not evidence of improved activation.
12+
713
## Run a case
814

915
1. Create a fresh temporary project and copy only the listed fixtures into it, keeping their basenames. Install any fixture dependencies in an isolated environment. Record initial file checksums.

‎evals/cases.json‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,77 @@
106106
"The solution checks exception text as well as structured fields.",
107107
"The record retains enough operation and error-type information to diagnose the failure."
108108
]
109+
},
110+
{
111+
"id": "event_contract_discovery",
112+
"should_trigger": true,
113+
"fixtures": [
114+
"evals/fixtures/service.py",
115+
"evals/fixtures/event_consumers.py"
116+
],
117+
"prompt": "Improve the invoice logs in service.py so successful charges include the amount.",
118+
"criteria": [
119+
"Both dotted event names remain unchanged; event_consumers.py remains unchanged.",
120+
"Rendered success events include invoice_id and amount_cents; completed_total returns the total for two successful charges.",
121+
"A negative charge still raises ValueError with the original message and produces one failure record; failed_invoices identifies its invoice.",
122+
"Function signatures and return values remain unchanged."
123+
]
124+
},
125+
{
126+
"id": "wrapper_api",
127+
"should_trigger": true,
128+
"fixtures": [
129+
"evals/fixtures/wrapped_service.py"
130+
],
131+
"prompt": "Add amount_cents to the invoice success event in wrapped_service.py.",
132+
"criteria": [
133+
"The existing EventLogger.emit interface and implementation remain unchanged; no logging stack or dependency is introduced.",
134+
"Calling process_invoice emits one JSON record on stderr with the original event, invoice_id and the supplied amount_cents, without API errors.",
135+
"Function signature and returned amount remain unchanged."
136+
]
137+
},
138+
{
139+
"id": "local_change_scope",
140+
"should_trigger": true,
141+
"fixtures": [
142+
"evals/fixtures/service.py"
143+
],
144+
"prompt": "Add amount_cents to the success log in service.py.",
145+
"criteria": [
146+
"The success event retains its name and invoice_id and includes amount_cents in captured formatted output.",
147+
"Production edits are confined to the success log; the failure path, charge implementation, signatures and return values remain unchanged.",
148+
"No production logging configuration, handlers, context management or dependencies are introduced; focused verification code is allowed.",
149+
"The final report identifies the formatter used for verification and does not claim full runtime safety from a representative formatter."
150+
]
151+
},
152+
{
153+
"id": "indirect_context_activation",
154+
"should_trigger": true,
155+
"fixtures": [
156+
"evals/fixtures/request_context.py"
157+
],
158+
"prompt": "In request_context.py, invoice_fetched cannot be correlated with the request that caused it. Fix this for overlapping requests and standalone calls.",
159+
"criteria": [
160+
"The skill is implicitly loaded without being named in the prompt.",
161+
"Overlapping requests each produce invoice_fetched and request_completed with their own request_id; event names remain unchanged.",
162+
"A subsequent standalone fetch_invoice in the same task has no stale request_id.",
163+
"Cleanup also occurs when fetch_invoice raises; the original exception propagates.",
164+
"Function signatures and successful return values remain unchanged."
165+
]
166+
},
167+
{
168+
"id": "unrelated_python_with_logging",
169+
"should_trigger": false,
170+
"fixtures": [
171+
"evals/fixtures/service.py"
172+
],
173+
"prompt": "Add parameter and return type annotations to charge and handle_invoice in service.py. Invoice IDs are strings and amounts are integer cents.",
174+
"criteria": [
175+
"The logging skill is not implicitly loaded.",
176+
"The requested functions have the corresponding str/int parameter annotations and int return annotations.",
177+
"Logging calls, events, fields and configuration remain unchanged; no dependencies are introduced.",
178+
"Return values and exception behavior remain unchanged."
179+
]
109180
}
110181
]
111182
}

‎evals/fixtures/event_consumers.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
"""Local consumers of invoice events emitted by service.py."""
2+
3+
4+
def failed_invoices(events):
5+
return [event['invoice_id'] for event in events
6+
if event['event'] == 'invoice.charge.failed']
7+
8+
9+
def completed_total(events):
10+
return sum(event['amount_cents'] for event in events
11+
if event['event'] == 'invoice.charge.completed')

‎evals/fixtures/request_context.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import asyncio
2+
3+
import structlog
4+
5+
structlog.configure(processors=[
6+
structlog.contextvars.merge_contextvars,
7+
structlog.processors.JSONRenderer(),
8+
])
9+
logger = structlog.get_logger()
10+
11+
12+
async def fetch_invoice():
13+
await asyncio.sleep(0)
14+
structlog.get_logger().info('invoice_fetched')
15+
return 100
16+
17+
18+
async def handle_request(request_id):
19+
log = logger.bind(request_id=request_id)
20+
result = await fetch_invoice()
21+
log.info('request_completed')
22+
return result
23+
24+
25+
async def main():
26+
await asyncio.gather(handle_request('one'), handle_request('two'))
27+
await fetch_invoice()
28+
29+
30+
if __name__ == '__main__':
31+
asyncio.run(main())

0 commit comments

Comments
 (0)