Repository navigation
Add unified-session BM25 audit search with automatic evidence grouping - #70998
Conversation
Co-authored-by: Copilot App <[email protected]>
Keep BM25 ranking independent of Drain3, mine only crowded results, and retain template groups only when they save excerpt text. Preserve structured outcomes and use compact exact-duplicate counts without mining. Update audit guidance and regression coverage. Co-authored-by: Copilot App <[email protected]>
|
✅ Design Decision Gate 🏗️ completed the design decision gate check. See the comment below for the result and any generated ADR draft.
|
|
🔬 Test Quality Sentinel is analyzing test quality on this pull request... |
|
🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅
|
|
✅ PR Code Quality Reviewer completed the code quality review.
|
|
✅ Ponytail Reviewer completed successfully! Ponytail ReviewerOutcome: The agent completed and reported no action. A no-op output alone does not verify that all required work was completed or that publication was possible. Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.
|
Regenerate audit and logs-jsonl schemas for the evidence_search field added by the audit evidence retrieval changes. Co-authored-by: Copilot App <[email protected]>
🏗️ Design Decision Gate — ADR RequiredThis PR has more than 100 new lines in core business logic (1,388 additions in 📄 Draft ADR committed: The draft records this decision: add
📋 What to do next
After the PR body links an ADR, this gate runs again and checks that the implementation matches the decision. ❓ Why ADRs MatterADRs create a searchable, permanent record of why the codebase looks the way it does. Future contributors, including your future self, will benefit from it. 📋 Michael Nygard ADR Format ReferenceA complete ADR has these four sections:
ADRs are stored in
|
Comment MemoryPeek at saved memory (pr-code-quality-reviewer)Note This comment is managed by comment memory.Expand the saved memory block to view or edit the persistent context for this thread.
|
There was a problem hiding this comment.
Verdict
Request changes: exact duplicate evidence with different structured outcomes is currently merged into one ungrouped result, which misreports success/failure occurrence counts.
Details
pkg/cli/audit_search.go: the zero-cluster key is based only on stage and text, while BM25 deduplication intentionally ignores outcome. This needs a separate outcome partition before counts are emitted.- No tests were run; this was a static review of the pre-fetched diff.
🔎 Code quality review by PR Code Quality Reviewer · copilot · gpt50 · 2.98 AIC · ⌖ 0.685 AIC · ⊞ 1.6K
Comment /review to run again
| } | ||
|
|
||
| func auditEvidenceClusterKey(doc auditSearchDocument) string { | ||
| if doc.clusterID == 0 { |
There was a problem hiding this comment.
Exact duplicate events with different structured outcomes are collapsed into the same ungrouped key here, so successes and failures can be reported as one occurrences/matching_occurrences total even though outcome partitioning is required.
💡 Keep outcome partitions for exact duplicates
rankAuditEvidence deduplicates by stage + text, and when Drain3 is not enabled clusterID remains zero, making auditEvidenceClusterKey identical for every outcome variant. selectAuditEvidence then counts all of them together. For a retry stream containing identical success and failure payload text, this produces a misleading combined count and loses the outcome distinction. Include the outcome in the unmined grouping key (while retaining outcome-independent BM25 deduplication), or partition exact-duplicate representatives before counting.
There was a problem hiding this comment.
Skills-Based Review 🧠
Applied /tdd and /codebase-design (via pr-triage: new_feature). Thorough, well-tested feature addition; only a minor maintainability nit flagged inline.
📋 Key Themes & Highlights
Review scope
Reviewed pkg/cli/audit_search.go, audit_search_grouping.go, audit_search_session.go, audit_command.go, and audit_run_pipeline.go (the pr-triage high-impact set), plus the full new test suites (audit_search_test.go, audit_search_grouping_test.go) and doc updates. Verified go build ./... succeeds and go test ./pkg/cli/... -run TestAuditSearch passes (all test functions/subtests green), along with the new test_guidance.py contract test.
Positive highlights (/tdd)
- ✅ Excellent test coverage: BM25 scoring math is asserted against a closed-form expected value (TestAuditSearchBM25), not just snapshot comparisons.
- ✅ Dedicated invariance tests prove Drain3 grouping never perturbs BM25 ranking ("Drain3 must never change BM25 scores or ranks") — a strong regression guard for the PR's core safety claim.
- ✅ Boundary/cancellation tests cover all declared limits (64 MiB, 20k events, 256 stages, 64-level nesting, context cancellation) with explicit error-string assertions.
- ✅ Cache-isolation test (TestAuditSearchReportDoesNotChangeFindingsOrCache) confirms --search never mutates deterministic cached audit data on disk — directly verifies a key safety property called out in the PR description.
- ✅ UTF-8 offset-mapping edge cases (case-folding expanding byte length) are specifically tested in TestAuditSearchOutputBoundsAndExcerpt.
Minor finding (/codebase-design)
- The 256-stage limit check is duplicated between clusterAuditEvidence (audit_search.go) and validateAuditSearchStages (audit_search_grouping.go). Both are exercised by tests and correct today, but a shared constant/helper would prevent future drift — see inline comment.
Documentation (/grill-with-docs)
- New vocabulary ("evidence group", "BM25 relevance", run-local Drain3 cluster IDs) is consistently distinguished from existing fleet failure_clusters and audit --group finding codes across analyzing-runs.md, cli-commands.md, debug-agentic-workflow.md, instructions.md, and the debugging-workflows skill — reinforced by a new guidance contract test. No ambiguity introduced into the existing audit vocabulary.
@copilot please address the review comments above.
🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · copilot · sonnet50 · 128.2 AIC · ⌖ 15.1 AIC · ⊞ 10.2K
Comment /matt to run again
| for _, doc := range docs { | ||
| stages[doc.stage] = struct{}{} | ||
| if len(stages) > 256 { | ||
| return errors.New("unified session exceeds the 256-stage search input limit") |
There was a problem hiding this comment.
[/codebase-design] The 256-stage limit check is duplicated verbatim in clusterAuditEvidence (audit_search.go:213) and validateAuditSearchStages here. Low risk today, but if the bound ever changes one call site will silently drift from the other.
💡 Suggested consolidation
Extract a shared helper, e.g.:
const maxAuditSearchStages = 256
func countAuditSearchStages(docs []auditSearchDocument) (map[string]struct{}, error) {
stages := make(map[string]struct{})
for _, doc := range docs {
stages[doc.stage] = struct{}{}
if len(stages) > maxAuditSearchStages {
return nil, fmt.Errorf("unified session exceeds the %d-stage search input limit", maxAuditSearchStages)
}
}
return stages, nil
}and have both call sites use it. This is a minor maintainability nit, not a correctness bug — the current duplicated checks are both exercised and passing in audit_search_grouping_test.go/audit_search_test.go.
@copilot please address this.
🧪 Test Quality Sentinel Report✅ Test Quality Score: 89/100 — Excellent
📊 Metrics (20 tests)
Test Quality HighlightsExcellent design coverage:
Strong edge-case protection:
Data integrity invariants:
Scoring BreakdownVerdict
|
There was a problem hiding this comment.
✅ Test Quality Sentinel: 89/100 — Excellent. 60% implementation tests (threshold: 30%). All hard violations absent: no forbidden mocks, build tags present, inflation within bounds (1.58:1), and comprehensive behavioral coverage across 20 tests with 13+ edge cases and 8 design contracts.
🧪 Test quality analysis by Test Quality Sentinel · copilot · haiku45 · 86 AIC · ⌖ 10.1 AIC · ⊞ 9.2K
Comment /review to run again
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Copilot review overview
4 open issues
strings.FieldsFuncSeqis not part of the Go standard library as of Go 1.22 (and will fail to… · New Schema/type mismatch:timestampis emitted as a JSON string in the tests… · New This drops the underlying JSON error, making malformed-input debugging much harder. Wrap the… · New The map value (int) is never read; this is effectively a set. Switching tomap[string]struct{}… · New
What changed in this PR
Adds optional, query-specific evidence retrieval to gh aw audit by locally searching the redacted unified session with BM25 and (when beneficial) automatic Drain3 grouping, while ensuring deterministic audit findings/caches remain unchanged.
Changes:
- Introduces
--search/--search-limitflags and plumbs results into audit rendering without persisting query output to shared caches. - Implements unified-session parsing, BM25 ranking, bounded excerpts/context, and automatic repetition grouping with outcome-safe partitions.
- Updates JSON schemas and documentation/guidance to describe the new
evidence_searchoutput and its guarantees/limitations.
| File | Description |
|---|---|
| schemas/logs-jsonl.schema.json | Adds evidence_search shape to logs JSONL schema for emitted search results. |
| schemas/audit.schema.json | Adds evidence_search to audit JSON schema for stable JSON output validation. |
| pkg/cli/audit_search_test.go | Adds comprehensive unit tests for tokenization, BM25, session provenance, bounds, output truncation, and CLI option interactions. |
| pkg/cli/audit_search_session.go | Implements unified-session discovery, bounded parsing, and field flattening into searchable documents. |
| pkg/cli/audit_search_grouping_test.go | Tests automatic Drain3 activation criteria, rank invariance, and outcome partitioning. |
| pkg/cli/audit_search_grouping.go | Implements outcome detection, stage limits, and “useful grouping” selection logic. |
| pkg/cli/audit_search.go | Implements BM25 ranking, optional grouping, excerpting, and console rendering of evidence search results. |
| pkg/cli/audit_run_pipeline.go | Threads Search/SearchLimit through run config and ensures cache bypass/marker invalidation when session is missing. |
| pkg/cli/audit_report_render.go | Renders evidence_search in console output. |
| pkg/cli/audit_report.go | Extends AuditData with EvidenceSearch field for JSON/console reports. |
| pkg/cli/audit_render_output.go | Ensures evidence search is computed at render time and not written into deterministic caches. |
| pkg/cli/audit_command.go | Adds CLI flags, validation, and compatibility constraints for single-run --search. |
| pkg/cli/audit_cache.go | Ensures EvidenceSearch is never persisted in the cached audit file. |
| pkg/cli/audit.go | Extends AuditOptions and run config with search fields. |
| docs/src/content/docs/reference/audit.md | Documents --search behavior, bounds, grouping semantics, and interpretation guidance. |
| .github/skills/debugging-workflows/SKILL.md | Adds guidance on using evidence_search vs other clustering/grouping concepts. |
| .github/skills/agentic-workflows/tests/test_guidance.py | Adds contract test to ensure guidance text includes required --search caveats and distinctions. |
| .github/aw/instructions.md | Updates agent instructions to incorporate audit --search usage and interpretation constraints. |
| .github/aw/debug-agentic-workflow.md | Adds debugging workflow guidance for using evidence_search responsibly. |
| .github/aw/cli-commands.md | Adds CLI examples and guardrails around --search. |
| .github/aw/analyzing-runs.md | Adds a dedicated section explaining session evidence retrieval and clustering distinctions. |
Review effort: Lite
| // Preserve exact identifiers as well as their components, without stemming paths or error codes. | ||
| func auditSearchTokens(text string) []string { | ||
| var tokens []string | ||
| for word := range strings.FieldsFuncSeq(strings.ToLower(text), func(r rune) bool { |
| if len(bytes.TrimSpace(line)) > 0 { | ||
| var event auditSearchSessionEvent | ||
| if err := json.Unmarshal(line, &event); err != nil { | ||
| return nil, fmt.Errorf("invalid unified session search record on line %d", lineNumber) |
| matching := make(map[string]int) | ||
| for _, hit := range ranked { | ||
| doc := docs[hit.index] //nolint:uncheckedsliceindex // ranked indexes come from ranging over this document slice | ||
| matching[doc.stage+"\n"+doc.text] = hit.index |
|
🎉 This pull request is included in a new release. Release: |



Summary
Audits expose deterministic findings and metrics, but locating the relevant event inside a large session still requires scanning logs. This adds optional local evidence retrieval over the actual redacted unified session, without changing audit completeness, findings, severity, or confidence.
gh aw audit RUN_ID --search "query" --search-limit 5with JSON and console output. Readusage/aw_session.jsonlor rootaw_session.jsonl; never substitute native engine logs or synthesized run summaries.audit --groupfinding codes.Validation
Live evaluation
Collected unified sessions from 1,000 completed runs across 231 workflows. Of these, 999 were searchable; one correctly failed the existing record-size limit. Replayed six fixed queries per searchable session: 5,994 query evaluations over 399,905 events. No workflows were dispatched.
Across 1,879 query/session cases with structured relevant evidence:
Grouping appeared in 13.9% of queries. The replay verified unchanged first-result identities and scores, outcome-safe group counts, source references, and output bounds.
These are structured-field relevance proxies, not human-rated diagnostic outcomes or fleet-health claims. The sample selects available artifacts: 587 additional inspected runs lacked usage artifacts. Raw transcripts and local evaluation artifacts are not included in this PR.