Skip to content

feat: Reuse clean hunk reviews through the Warden service - #582

Open
gricha wants to merge 17 commits into
mainfrom
gricha/hunk-evidence-replay
Open

gricha wants to merge 17 commits into
mainfrom
gricha/hunk-evidence-replay

Conversation

@gricha

@gricha gricha commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Adds incremental = "evidence", a stricter incremental mode for skills such as security-review, backed by the Warden service. incremental = true keeps today's hunk-text matching, so each skill picks its mode:

[defaults]
incremental = true

[[skills]]
name = "security-review"
incremental = "evidence"

Incremental review skips a hunk when its path and body match the last clean run. It does not look at anything the reviewer relied on outside the hunk. A guard removed elsewhere in the same file, or a change to a file the reviewer read, does not trigger a re-review. That is why security-review and integrity-review stay on full re-review in the org config (getsentry/.github#235).

Rule

Reuse an earlier review of a hunk only when it found nothing and would see the same thing now:

  1. Same prompt. Same skill prompt, prompt template, model settings, PR title and body, hunk, and surrounding lines. Line numbers, the changed-file list, and recalled memory are ignored, because they change on most pushes.
  2. Same evidence. Every Read, Grep, Find, and Ls call that review made returns the same output when replayed against the current checkout.

Anything else gets a full review. Reviews with findings are never reused. The title and body stay in the key so text in one PR's description cannot earn a clean review that another PR reuses.

How it works

  • Recording: the Pi runtime records each checkout tool call with a hash of its output and returns evidence only when every call was recorded.
    • Skill resource reads are stored relative to the skill root, and error hashes leave out the checkout path, so evidence replays on another runner.
    • Grep and find results cut short by a match or byte limit are not recorded, because ripgrep does not sort output and the truncated subset varies between runs.
  • Storage: the service stores clean reviews in hunk_reviews (migration 0009).
    • POST /api/v1/hunk-reviews needs a new review_cache token role, not ingest: a stored review lets later runs skip analysis, so only the Warden workflow's token should be able to write one. POST /api/v1/hunk-reviews/recall needs read.
    • Records hold paths, search patterns, and output hashes, not file contents. The Data Profiles docs now list these under code.
    • They expire after 30 days, or sooner under the tenant's findings retention.
  • Action: recalls once per run, replays evidence locally (no model calls), and records new clean reviews at the end.
    • Requires a matched trigger with incremental = "evidence" and the code data profile, because stored search patterns often quote the code under review. Under any other profile Warden warns and reviews every hunk. Evidence mode does not use check-run baselines.
    • Every service failure falls back to a full review.

Measured

Security-review with the production lane (Grok 4.5 high, GPT 6 Luna high auxiliary) on 10 random consecutive commit pairs from merged getsentry/sentry PRs, 81 hunk reviews at the later commit:

Hunks at the later commit Share of hunks Share of cost
New or edited 27% 32%
Unchanged, evidence identical (reused) 21% 19%
Unchanged, evidence or context changed (reviewed) 52% 49%

Plain incremental review would skip both unchanged rows. This rule keeps reviewing the hunks whose evidence moved, which is most of them, because reviewers read and search the code the PR is changing.

End to end against a local service and Postgres, with Grok on getsentry/sentry#130528:

Run Hunks reviewed Reused
Commit N 11 0
Commit N again 0 11

A first pass reused 10 of 11 on the identical commit. The one miss was a grep that hit its match limit and returned a different subset, which led to the truncation rule above.

Tried: delta re-review

For hunks whose evidence changed, giving the agent its earlier verdict plus a diff of the changed code cost 137% of a full Grok re-review across 43 hunks. Turns did not drop (median 3 for both), and the diff added about 37% input tokens. Not included.

Rollout

After a release: grant the Warden workflow's service token the review_cache role, set the service data profile to code, then change incremental = false to incremental = "evidence" on security-review in getsentry/.github.

Not covered: the Claude runtime, which uses SDK built-in tools; the CLI, which has no cache wiring. Sorting search output in Pi would make truncated greps replayable too.

gricha and others added 2 commits November 25, 2026 15:41
Incremental review skips a hunk when its path and body match the last
clean run, even if code the reviewer relied on changed elsewhere. That gap
keeps security-review and integrity-review on full re-review.

Record each Read, Grep, Find, and Ls call with a hash of its output, and
add changedToolEvidence to re-run recorded calls against a checkout and
report which outputs changed. Search output is sorted before hashing
because ripgrep's output order is not stable.

Not wired into incremental review yet.
@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
warden-prod Ready Ready Preview Nov 26, 2026 3:38am UTC

Request Review

Code added above a hunk shifts its line numbers and the grep matches its
review saw, without changing what the reviewer read. On a random sample
of sentry commit pairs, about a fifth of unchanged hunks whose evidence
looked changed had only moved.

Drop grep line numbers before hashing, and add hunkContextFingerprint,
which keys a hunk prompt on file, scope, surrounding lines, and the change
without positions.
Add a hunk_reviews table and two endpoints so Warden can reuse a clean
hunk review on a later run. Each record holds a review key, the skill,
the reviewed commit, and the file-tool calls the review made with
output hashes. No file contents are stored.

POST /api/v1/hunk-reviews needs the ingest role and upserts by key.
POST /api/v1/hunk-reviews/recall needs the read role and returns
unexpired records. Records expire after 30 days, and the daily
retention job removes them sooner when findings retention is shorter.
Add reviewCache, a stricter alternative to incremental review for
skills such as security-review. A hunk is skipped only when an earlier
review found nothing and would see the same thing now: the same prompt,
model settings, PR title and body, hunk, and surrounding lines, and the
same output from every file read, search, and listing it made, replayed
against the current checkout.

The Pi runtime returns evidence only when every tool call was recorded.
Grep and find results cut short by a limit are not recorded, since
their unsorted output varies between runs. Skill resource reads are
recorded relative to the skill root so evidence replays on another
runner. The PR title and body stay in the key so one PR's description
cannot earn a clean review for another PR.

The Action uses the Warden service as the store when a matched trigger
sets reviewCache and the service data profile is not metrics. Every
service failure falls back to a full review.
@gricha gricha changed the title feat(sdk): Record and replay checkout tool evidence feat: Reuse clean hunk reviews through the Warden service Nov 26, 2026
export type HunkReviewRecallRequest = z.infer<typeof HunkReviewRecallRequestSchema>;

export const HunkReviewRecallResponseSchema = z.object({
reviews: z.array(HunkReviewSchema.pick({ key: true, evidence: true })).max(1_000),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 327 has a potentially vulnerable usage of zod, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of zod.
Affected versions of zod are vulnerable to Allocation of Resources Without Limits or Throttling. Zod parses every element of an array, set or map schema and records one validation issue per invalid element, with no cap or early stop. Upper size bounds (.max(), .length(), .size(), or z.maxLength()/z.length()/z.maxSize()/z.size() checks) only ran after all elements had been parsed, so they did not limit the work. An attacker who submits a very large collection (e.g. a million invalid items for z.array(z.string().uuid())) forces the allocation of millions of issue objects, which can exhaust memory and crash the process. Upgrade to zod 4.6.6 or later, which rejects oversized input before parsing its elements when the schema has an upper bound, and add an upper bound (e.g. .max(n)) to every collection schema that parses untrusted input: unbounded schemas stay exposed even after the upgrade.

References: GHSA, CVE

To resolve this comment:
Upgrade this dependency to at least version 4.6.6 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

export const HunkReviewRecallRequestSchema = z.object({
protocolVersion: z.literal(SERVICE_PROTOCOL_VERSION),
repository: RepositoryIdentitySchema,
keys: z.array(HunkReviewKeySchema).max(1_000),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 322 has a potentially vulnerable usage of zod, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of zod.
Affected versions of zod are vulnerable to Allocation of Resources Without Limits or Throttling. Zod parses every element of an array, set or map schema and records one validation issue per invalid element, with no cap or early stop. Upper size bounds (.max(), .length(), .size(), or z.maxLength()/z.length()/z.maxSize()/z.size() checks) only ran after all elements had been parsed, so they did not limit the work. An attacker who submits a very large collection (e.g. a million invalid items for z.array(z.string().uuid())) forces the allocation of millions of issue objects, which can exhaust memory and crash the process. Upgrade to zod 4.6.6 or later, which rejects oversized input before parsing its elements when the schema has an upper bound, and add an upper bound (e.g. .max(n)) to every collection schema that parses untrusted input: unbounded schemas stay exposed even after the upgrade.

References: GHSA, CVE

To resolve this comment:
Upgrade this dependency to at least version 4.6.6 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

export const HunkReviewRecordRequestSchema = z.object({
protocolVersion: z.literal(SERVICE_PROTOCOL_VERSION),
repository: RepositoryIdentitySchema,
reviews: z.array(HunkReviewSchema).max(500),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 310 has a potentially vulnerable usage of zod, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of zod.
Affected versions of zod are vulnerable to Allocation of Resources Without Limits or Throttling. Zod parses every element of an array, set or map schema and records one validation issue per invalid element, with no cap or early stop. Upper size bounds (.max(), .length(), .size(), or z.maxLength()/z.length()/z.maxSize()/z.size() checks) only ran after all elements had been parsed, so they did not limit the work. An attacker who submits a very large collection (e.g. a million invalid items for z.array(z.string().uuid())) forces the allocation of millions of issue objects, which can exhaust memory and crash the process. Upgrade to zod 4.6.6 or later, which rejects oversized input before parsing its elements when the schema has an upper bound, and add an upper bound (e.g. .max(n)) to every collection schema that parses untrusted input: unbounded schemas stay exposed even after the upgrade.

References: GHSA, CVE

To resolve this comment:
Upgrade this dependency to at least version 4.6.6 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

key: HunkReviewKeySchema,
skill: z.string().trim().min(1).max(512),
reviewedSha: z.string().trim().min(1).max(64).optional(),
evidence: z.array(HunkReviewEvidenceSchema).max(200),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 303 has a potentially vulnerable usage of zod, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of zod.
Affected versions of zod are vulnerable to Allocation of Resources Without Limits or Throttling. Zod parses every element of an array, set or map schema and records one validation issue per invalid element, with no cap or early stop. Upper size bounds (.max(), .length(), .size(), or z.maxLength()/z.length()/z.maxSize()/z.size() checks) only ran after all elements had been parsed, so they did not limit the work. An attacker who submits a very large collection (e.g. a million invalid items for z.array(z.string().uuid())) forces the allocation of millions of issue objects, which can exhaust memory and crash the process. Upgrade to zod 4.6.6 or later, which rejects oversized input before parsing its elements when the schema has an upper bound, and add an upper bound (e.g. .max(n)) to every collection schema that parses untrusted input: unbounded schemas stay exposed even after the upgrade.

References: GHSA, CVE

To resolve this comment:
Upgrade this dependency to at least version 4.6.6 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

Replace the separate reviewCache flag with a value of incremental, so
each skill picks one mode: true matches hunk text against the last clean
run on the PR, and "evidence" reuses a clean review only when its prompt
and every file read and search it made are unchanged.
- Writing hunk reviews needs a new review_cache token role. A stored
  review lets later runs skip analysis, so any ingest token could
  otherwise vouch for a hunk nobody reviewed.
- Leave recalled memory out of the review key. Recall changes with the
  PR's paths, which would make most reviews miss.
- Create the repository row when recording reviews. Reviews are recorded
  before the run is published, so a repo's first run stored nothing.
- Hash tool errors without the checkout path, and mark skill resource
  reads with a flag instead of a path prefix that real files could share.
- Include hunk reviews in tenant export, and drop the unused reused chunk
  flag and two unused exports.
Comment on lines 25 to 29
records: z.array(z.object({
type: z.enum(['repository', 'run', 'skill', 'usage', 'finding', 'memory']),
type: z.enum(['repository', 'run', 'skill', 'usage', 'finding', 'memory', 'hunk_review']),
id: z.string().min(1).max(128),
repositoryId: z.string().min(1).max(128).optional(),
data: z.record(z.string(), z.unknown()),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 25 has a potentially vulnerable usage of zod, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of zod.
Affected versions of zod are vulnerable to Allocation of Resources Without Limits or Throttling. Zod parses every element of an array, set or map schema and records one validation issue per invalid element, with no cap or early stop. Upper size bounds (.max(), .length(), .size(), or z.maxLength()/z.length()/z.maxSize()/z.size() checks) only ran after all elements had been parsed, so they did not limit the work. An attacker who submits a very large collection (e.g. a million invalid items for z.array(z.string().uuid())) forces the allocation of millions of issue objects, which can exhaust memory and crash the process. Upgrade to zod 4.6.6 or later, which rejects oversized input before parsing its elements when the schema has an upper bound, and add an upper bound (e.g. .max(n)) to every collection schema that parses untrusted input: unbounded schemas stay exposed even after the upgrade.

References: GHSA, CVE

To resolve this comment:
Upgrade this dependency to at least version 4.6.6 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

Comment on lines +248 to +251
database.query<{ id: string; repository_id: string; data: Record<string, unknown> }>(`
SELECT review_key AS id, repository_id, jsonb_build_object(
'skill', skill, 'reviewedSha', reviewed_sha, 'evidence', evidence, 'expiresAt', expires_at
) AS data FROM hunk_reviews WHERE tenant_id = $1 AND repository_id = ANY($2::uuid[]) LIMIT 50_000

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hunk_review export LIMIT pushes total records past ExportResponseSchema max

Adding up to 50_000 hunk_review rows raises the possible export size to 191_000 records, but /api/v1/export still parses the response with .max(151_000), so large tenants can make a successful store query fail at response validation.

Evidence
  • This hunk adds FROM hunk_reviews ... LIMIT 50_000 and includes 'hunk_review' in the export types array.
  • Existing query caps are 1_000 + 10_000 + 20_000 + 50_000 + 50_000 + 10_000 = 141_000 before this change; with hunk reviews the cap is 191_000.
  • ExportResponseSchema in administration/routes.ts still uses .max(151_000) and ExportResponseSchema.parse(...) runs on the full records array before the response is returned.
  • No export-path trimming or higher response max offsets the new 50_000-row source.

Identified by Warden · code-review · DEN-WKF

Comment on lines +102 to +118
const GREP_LINE = /^(.+?)([:-])\d+\2/;

/**
* Hash a tool result. Search and listing output order is not stable, so lines are sorted. Grep line
* numbers are dropped so a match that only moved, because lines were added above it, hashes the same.
*/
function hashToolOutput(toolName: string, result: unknown): string {
const content = (result as { content?: { type?: string; text?: string; data?: string; mimeType?: string }[] } | undefined)?.content ?? [];
// Hash image bytes too: the text note Pi adds for an image is the same for any image of that type.
const text = content.map((part) => (part.type === 'text'
? part.text ?? ''
: `[${part.type}:${part.mimeType ?? ''}:${part.data ?? ''}]`)).join('\n');
let canonical = text;
if (toolName !== 'read') {
const lines = text.split('\n');
canonical = (toolName === 'grep' ? lines.map((line) => line.replace(GREP_LINE, '$1$2')) : lines).sort().join('\n');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GREP_LINE strips in-path -digits- and collides distinct files

Grep evidence hashing can treat matches from different paths as identical when a path contains a -digits- segment, so evidence mode may reuse a clean review after the search hits a different file.

Evidence
  • Pi grep lines look like path:12: text / path-12- text, and hashToolOutput() canonicalizes them with GREP_LINE = /^(.+?)([:-])\d+\2/ before hashing.
  • Because the pattern is unanchored to the real line-number field and accepts either : or -, non-greedy .+? can match inside the path: svc-1-api/views.py:10: return True and svc-2-api/views.py:10: return True both become svc-api/views.py:10: return True.
  • changedToolEvidence() reuses a clean hunk when that hash is unchanged, so a later run can skip review after the same match text appears under a different -N- path segment.
  • Paths such as date folders (2024-01-15/...) and monorepo dirs (app-2-backend/...) hit this in normal greps, including default context: 0.

Identified by Warden · code-review · H5G-9GK

- Stop stripping grep line numbers before hashing. Output text cannot
  show where a path ends, so a path segment like svc-1-api was stripped
  too and matches in different files hashed the same.
- Keep the last review for a key repeated in one record batch. A single
  upsert cannot touch a row twice, so the whole batch failed.
- Cap exported hunk reviews at 10,000 so a full export stays within the
  export response limit.

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache rule itself holds up. Findings, max-turn and extraction failures, and any unrecorded or truncated tool call all keep a hunk out of the cache, and every service failure falls back to a full review. One thing before this lands:

Evidence mode sends tool arguments to the service under the default findings profile, which the service docs say never happens. HunkReviewEvidenceSchema stores path, pattern, and glob for every Read, Grep, Find, and Ls call. hunkReviewCacheFor only rules out metrics. But service.mdx lists "tool data" under Not sent for both findings and code, and says "Warden never sends ... tool arguments or results". Grep patterns are written by the model and often quote literals from the code under review, so a team that picked findings to keep code fragments out of the service would get them anyway once a skill turns on incremental = "evidence".

There are two ways to fix it: require data = "code" for evidence mode, or keep findings and update the Data Profiles table and the "never sends" line so they say evidence mode stores tool arguments and output hashes. In either case, the Evidence Mode section in workflow.mdx should link to whichever rule you pick.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 36ad1c9. Configure here.

Stored evidence includes file-tool arguments, and search patterns often
quote the code under review. The findings profile promises no tool data,
so evidence mode now needs data = "code" and otherwise warns and reviews
every hunk. The data profile docs now say what evidence mode sends.

Also replace the skill install path in the system prompt before hashing
the review key, so reviews recorded on one runner match on another.
@gricha

gricha commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@sentry-junior please re-review. Addressed in 17f8e72:

  • Evidence mode now requires data = "code". Under any other profile Warden warns and reviews every hunk.
  • The Data Profiles table and the "never sends" line in service.mdx now say evidence mode sends file-tool arguments (paths, search patterns, globs) and output hashes under code, never tool results.
  • The Evidence Mode section in workflow.mdx links to that table.

This branch was successfully deployed

2 active deployments
Preview – warden-prod — 423ba55e Deployed Nov 26, 2026 by vercel[bot]
Preview – warden — 423ba55e Deployed Nov 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant