Skip to content

agent: advisory duplicate check on report_finding via a decision model - #470

Merged
BaaRai merged 4 commits into
BaaRai:mainfrom
NikolayGusev-astra:feat/systemone-profile-format
Nov 23, 2026
Merged

BaaRai merged 4 commits into
BaaRai:mainfrom
NikolayGusev-astra:feat/systemone-profile-format

Conversation

@NikolayGusev-astra

@NikolayGusev-astra NikolayGusev-astra commented Nov 22, 2026 •

Copy link
Copy Markdown

Duplicates are the cheapest way to lose reviewer trust, and the only guard today is
a prompt instruction: the worker is told to check list_findings before registering.
It does not hold — in one run against a deliberately vulnerable app three defect
classes were registered twice each (two SQLi, two IDOR, two admin-endpoint
findings), and one of the pairs differed only in wording.

A decision model answers exactly this kind of closed-list question (same defect as
one of these N findings, or not?) with probabilities and no generated text, so the
judgement costs one small request instead of a main-model turn over a six-figure
context. Measured on our own findings before writing any of this (15 candidates,
hand labels): the correct partner 8/8 on a 27B decider and 7/8 on the flash one,
against 7/15 for the constant "always distinct", at 0.66 s and ~1.7k input tokens
per call with zero output tokens. Repeated calls were stable (30/30 identical).

Changes

  • agent/triage.go: TriageClient interface, a /v1/systemone HTTP client, and the pure
    pieces (state builder, criteria builder, answer parser, threshold) so the logic is
    testable without a server.
  • report_finding: consults the client before registering. On a duplicate above the
    confidence threshold the finding is not registered again; the caller is told which
    finding_id it matched and to extend it with update_finding_report.
  • Wiring: agent.SetTriageClient on the worker/planner ToolSets, a triage_profile_id
    setting (any llm_profiles row whose base_url serves the decision contract; 0 = off),
    exposed through the settings API.

Fail-open, by construction

Triage changes an outcome only when it is confident; every other path behaves exactly
as today: no client, no existing findings, empty summary, transport error, non-200,
malformed body, an id the question never offered, or confidence below the threshold
all fall through to normal registration. A wrong suppression loses evidence, a wrong
registration only costs a row — hence the threshold, and hence "advisory".

Verification

  • go test ./agent/ passes, including new tests: request shape (model/state/criteria
    carry every candidate), distinct answer, unknown id reads as distinct, probability
    fallback when confidence is absent, error on 500, no HTTP call without input, state
    cap, threshold boundaries.
  • red/green on two independent breakages: forcing the threshold false and accepting
    an unoffered id both fail the suite; restored, it passes.
  • go test ./server/ shows one failure,
    TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (bind 127.0.0.2 —
    environment), reproduced on clean main in a separate worktree.
  • gofmt -l agent/ server/ clean.

Notes

  • The profile must serve /v1/systemone. A chat-only decider endpoint (one that refuses
    /v1/chat/completions) needs a thin adapter; a decision endpoint works directly.
  • Off by default: with no triage_profile_id the platform behaves as before.

Found while running the platform against a live target.

Calibration (measured before the shape was frozen)

A labelled corpus of 538 same-target finding pairs (8 true duplicates, 75 hard
negatives — same class, different endpoint) says the shape barely moves recall and
that precision is what the threshold buys:

question shape recall FP on hard negatives
pair, both summaries (probe) 1.00 —
live shape, ids + none 1.00 0.47
live shape + endpoint/parameter lines 1.00 0.50
live shape + explicit rule 0.88 0.40
broken control (no summaries) 1.00 0.60

Confidence on true duplicates is 0.58-0.73 in the many-way shape versus ~0.92
pairwise, so the 0.5 threshold is deliberate: raising it to 0.75 (which the pairwise
numbers would suggest) would have dropped two of the three live duplicates.

Cross-task pool

task_relations links only spawned tasks, so two tasks created independently against
the same target never see each other's findings — measured live, three such duplicates
were all answered "distinct" because the question never offered them.
db.FindingsSharingAssets joins on the candidate's own asset ids (jsonb containment,
GIN-served) and adds those findings, marked with their task. On those three cases the
wider question names the right partner in all three.


Both PRs come from the same live run.

Live acceptance run (same fixture, same goal, same constraints, triage ON)

Nine questions, eight named a partner from another task, six duplicates suppressed
(confidence 0.50-0.79), two slipped (0.30 and 0.47 — both with the correct partner
named). Registered findings: 4 instead of roughly 10, since six of the registration
attempts were re-registrations of defects already in the graph; goals 6/10.

The two misses are what turned the threshold into a setting: the model's confidence on
TRUE duplicates moves with the question's width — 0.73-0.79 on a small pool, 0.30-0.53
with twenty candidates — so one fixed number cannot fit both ends. Lowering it is
affordable because the suppression result tells the agent to re-register explicitly
when the finding is in fact distinct.

The candidate cap is a selection, not "the newest N"

Both limits in the question builder were mine and both were wrong in the same way.
triageMaxExisting took the newest findings, so on a wide graph the true partner could
simply fall out of the list; and triageMaxStateChars truncated the assembled state
mid-line, leaving criteria entries whose state line had been cut. Candidates are now
ranked by relevance (same class, overlapping endpoint, another task on a shared asset —
that last one arrives pre-filtered by asset, which is itself a signal) with recency
only breaking ties, and summaries are capped per entry so every offered finding stays
present and readable. The whole-state cap remains as a safety net.

Limits, each with a cause

Every number that bounds the question was given a measured cause (no-limit discipline);
limit-scan.py --since origin/main --fail-on commented exits 0 on this branch.

limit value cause
suppression threshold 0.5 calibration on 538 same-target pairs: recall 1.00 at FP 0.47 over 75 hard negatives; live true-duplicate confidence 0.30-0.79
candidates offered 10 width sweep on a real duplicate: confidence 0.81-0.91 up to 11, 0.64 at 19, 0.56 at 29
summary cap 400 summary length p50 189 / p90 334 / max 564 over 53 findings — 400 keeps 90% intact
state safety cap 6000 arithmetic at 10 entries: 10*(400+60)+480 ≈ 5.1 KB, margin 1.17x
HTTP timeout 20 s observed decider latency 0.26-1.29 s, 3.83-3.96 s on the 27B model; margin ~5x
pool query limit 50 widest observed asset pool 31 findings; margin 1.6x
response body cap 1 MiB observed answer 0.3-2 KB; margin ~500x

One number was corrected rather than argued: the per-entry summary cap went 240 -> 400 once
the length distribution was measured.

@BaaRai BaaRai left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for the PR and the benchmark numbers the advisory, fail-open design and pure unit tests in agent/triage_test.go are clean, and this directly relates to #473. Holding for two blockers before merge:

  1. No override path on false-positive suppression, and ID mismatch with update_finding_report (agent/tools.go):
    • The suppression note tells the agent: "if it is in fact a distinct defect (different endpoint, parameter or root cause), register it again explicitly." However, report_finding has no override/force flag to bypass triageDuplicate, so retrying hits the same decision-model check and loops.
    • The response returns duplicate_of_finding_id (the standalone findings.id), while update_finding_report takes finding_node_id (the exploration node ID). Returning duplicate_of_finding_node_id alongside duplicate_of_finding_id (or clarifying which ID to pass) avoids sending the agent down an ID error.
  2. Unvalidated triage_profile_id and unguarded HTTP client (server/server.go, agent/triage.go):
    • putSettings persists arbitrary triage_profile_id values (including negative or unknown profile IDs) without verifying the profile exists when > 0.
    • SystemOneClient creates a bare &http.Client{Timeout: 20 * time.Second} rather than reusing the server's LLM endpoint guard / private-endpoint checks (ARTEX_LLM_PRIVATE_ENDPOINTS).
    • Minor in the same file: buildDuplicateState truncates with out[:triageMaxStateChars] by byte index, which can split a multi-byte UTF-8 rune.

Once those are addressed (with tests covering the override path and node-ID return), we can re-review.

@NikolayGusev-astra
NikolayGusev-astra force-pushed the feat/systemone-profile-format branch 7 times, most recently from 3f95b25 to 9c6af39 Compare November 22, 2026 17:22

@BaaRai BaaRai left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for the rework. The cross-task pool and the wider candidate selection help, but the original blockers are not all closed on 9c6af39.

Blocking:

  1. No override path. agent/tools.go:1573-1589 suppresses a duplicate and tells the agent to "register it again explicitly", but report_finding has no force or override flag; a second identical call is triaged again and suppressed. Add an explicit override or drop the suppression.
  2. ID mismatch. The suppression response returns duplicate_of_finding_id (the findings table id) while telling the agent to call update_finding_report, whose finding_id is the exploration node id. Return both ids or point at the correct tool.
  3. Private endpoints. SystemOneClient.http() returns a bare &http.Client{Timeout: ...} and ignores ARTEX_LLM_PRIVATE_ENDPOINTS, so a triage profile can dial an internal host. Use the same guarded client as the LLM provider.

Should:

  1. UTF-8 truncation. buildDuplicateState and capText cut by byte index; a CJK summary can split a rune. Truncate on rune boundaries.
  2. Profile validation. putSettings accepts triage_profile_id -5 and 999888777; resolution fails open, but reject invalid ids and out-of-range confidence at save.
  3. Threshold description. The description announces a triage_min_confidence setting; at 9c6af39 the threshold is a hardcoded const 0.5. Either add the setting or fix the description.

Please add a test for the override path and for the id returned to the caller.

Николай Гусев added 2 commits November 23, 2026 16:59
Duplicates are the cheapest way to lose reviewer trust, and the only guard today is
a prompt instruction: the worker is told to check list_findings before registering.
It does not hold — in one run against a deliberately vulnerable app three defect
classes were registered twice each (two SQLi, two IDOR, two admin-endpoint
findings), and one of the pairs differed only in wording.

A decision model answers exactly this kind of closed-list question (same defect as
one of these N findings, or not?) with probabilities and no generated text, so the
judgement costs one small request instead of a main-model turn over a six-figure
context. Measured on our own findings before writing any of this (15 candidates,
hand labels): the correct partner 8/8 on a 27B decider and 7/8 on the flash one,
against 7/15 for the constant "always distinct", at 0.66 s and ~1.7k input tokens
per call with zero output tokens. Repeated calls were stable (30/30 identical).

Changes

- agent/triage.go: TriageClient interface, a /v1/systemone HTTP client, and the pure
  pieces (state builder, criteria builder, answer parser, threshold) so the logic is
  testable without a server.
- report_finding: consults the client before registering. On a duplicate above the
  confidence threshold the finding is not registered again; the caller is told which
  finding_id it matched and to extend it with update_finding_report.
- Wiring: agent.SetTriageClient on the worker/planner ToolSets, a triage_profile_id
  setting (any llm_profiles row whose base_url serves the decision contract; 0 = off),
  exposed through the settings API.

Fail-open, by construction

Triage changes an outcome only when it is confident; every other path behaves exactly
as today: no client, no existing findings, empty summary, transport error, non-200,
malformed body, an id the question never offered, or confidence below the threshold
all fall through to normal registration. A wrong suppression loses evidence, a wrong
registration only costs a row — hence the threshold, and hence "advisory".

Verification

- go test ./agent/ passes, including new tests: request shape (model/state/criteria
  carry every candidate), distinct answer, unknown id reads as distinct, probability
  fallback when confidence is absent, error on 500, no HTTP call without input, state
  cap, threshold boundaries.
- red/green on two independent breakages: forcing the threshold false and accepting
  an unoffered id both fail the suite; restored, it passes.
- go test ./server/ shows one failure,
  TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (bind 127.0.0.2 —
  environment), reproduced on clean main in a separate worktree.
- gofmt -l agent/ server/ clean.

Notes

- The profile must serve /v1/systemone. A chat-only decider endpoint (one that refuses
  /v1/chat/completions) needs a thin adapter; a decision endpoint works directly.
- Off by default: with no triage_profile_id the platform behaves as before.

The cap on offered findings is a SELECTION, not "the newest N": with a wide graph
the true partner falls out of a newest-first list, so candidates are ranked by
relevance (same class, overlapping endpoint, another task on a shared asset) with
recency only breaking ties. Per-entry summary capping replaces the whole-state
truncation, which used to cut mid-line and leave criteria ids whose state line had
been dropped.

Threshold is a knob, not a constant (live acceptance): on a run with the wider
cross-task pool the model named the right partner in 8 of 9 questions, but its
confidence moved with the question's width — 0.73-0.79 on a small pool, 0.30-0.53
with twenty candidates. Six duplicates were suppressed, and exactly the two that
slipped were the 0.30 and 0.47 ones, both with the correct partner named. A fixed
0.5 cannot fit both ends, so the threshold is a setting (triage_min_confidence,
default 0.5); the low end is affordable because the suppression result tells the
agent to re-register explicitly when the finding is in fact distinct.

Cross-task pool (found by re-measuring the live miss): task_relations only links
spawned tasks, so two tasks created independently against the same target never see
each other's findings and a defect registered in both is invisible to the dedup
question. FindingsSharingAssets joins on the candidate's own asset ids (jsonb
containment, GIN-served) and adds those findings to the question, marked with their
task. On three real cross-task duplicates the wider question names the right partner
in all three (confidence 0.58-0.73, above the threshold), where the own-task pool
could only answer "none".

Regression note (found on a live run, not in CI): FindingID is filled from the findings table, so building the candidate list straight from the nodes dropped every entry and triage never fired ("nodes=6, no usable existing findings"). Covered by TestTriageCandidates_SkipsNodesWithoutFindingRow; findings inherited from a directly related task are kept and marked in the question.

---

Found while running the platform against a live target.

limits: triageDupMinConfidence 0.5 - калибровка 538 пар одной цели (stage3_calibrate.py, 2026-11-22): recall 1.00 при FP 0.47 на 75 жёстких негативах; на истинных дублях в живом прогоне 0.30-0.79
limits: triageMaxExisting 10 - ширина вопроса на реальном дубле (stage3_width.py, 2026-11-22): уверенность 0.81-0.91 до 11 кандидатов, 0.64 на 19, 0.56 на 29; латентность 0.44->1.29 с
limits: triageMaxSummaryChars 400 - p90 длины сводки 334, максимум 564 по 53 находкам графа (2026-11-22)
limits: triageMaxStateChars 6000 - арифметика при потолке 10 записей: 10*(400+60)+480 ~= 5.1 КБ, запас 1.17x
limits: triageHTTPTimeout 20s - наблюдаемая латентность decider 0.26-1.29 с, 3.83-3.96 с на 27B; запас ~5x к худшему
limits: findings pool query limit 50 - самый широкий пул по ассету 31 находка (53 в графе, 2026-11-22), запас 1.6x
limits: ответ decider 1 MiB - наблюдаемый ответ 0.3-2 КБ, запас ~500x
Fixes the three blockers and three shoulds from the review of BaaRai#470, rebased
onto current main.

Blocker 1 — no way out of a wrong suppression. The suppression note told the
agent to register a distinct defect again, but report_finding had no override:
the retry hit the same check and was suppressed again. report_finding now takes
force_register, which skips the duplicate check for that call and logs the
override. Covered end to end: suppress, then register with the flag.

Blocker 2 — id mismatch. The suppression answer returned duplicate_of_finding_id
(the findings-table id) while update_finding_report addresses the exploration
NODE. The answer now carries duplicate_of_finding_node_id as well, and the note
names the node id to pass. withNodeID resolves it from the candidates the
question offered, so an id the model was never shown maps to nothing.

Blocker 3 — unguarded HTTP client. SystemOneClient.http() returned a bare client,
so a stored triage profile could point the server at an internal host. The client
is now built by the server under the same endpoint guard as the model-list path:
ARTEX_LLM_PRIVATE_ENDPOINTS allow-list, private and metadata addresses refused,
no proxy, redirects not followed. A refused base_url leaves triage off (fail
open, as every other triage failure). TriageHTTPTimeout is exported so the
injected client uses the same budget instead of a second number.

Should 4 — UTF-8 truncation. capText and buildDuplicateState cut by byte index,
splitting a multi-byte rune on CJK or Cyrillic summaries. Both now cut on a rune
boundary.

Should 5 — settings validation. putSettings accepts and stores any
triage_profile_id and any confidence. Both are validated before anything is
written: a negative or unknown profile id and a threshold outside 0..1 are
rejected with 400; 0 still turns the check off.

Should 6 — the threshold is a setting (triage_min_confidence), read on boot and
on change; the description matches the code.

Verification: go build ./... and go vet clean; gofmt clean. go test ./agent/
./db/ ./llmrec/ ./server/ with ARTEX_PG_DSN on a local PostgreSQL — green except
TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (binds 127.0.0.2) and
TestPauseShiftsTaskDeadlineOnResume, which fail the same way on clean main on
macOS. Red/green: with the force_register branch disabled the override test
fails naming the ignored flag; restored, it passes.
@NikolayGusev-astra
NikolayGusev-astra force-pushed the feat/systemone-profile-format branch from 9c6af39 to a3e44d3 Compare November 23, 2026 14:22
@NikolayGusev-astra

Copy link
Copy Markdown
Author

Rebased onto current main (ab2a026) and reworked. All six points:

Blocking

  1. Override path — report_finding now takes force_register; set, it skips the duplicate check for that call and logs the override. The suppression note says so explicitly. Covered end to end in agent/triage_override_test.go: register, suppress the same call, then register with the flag.
  2. ID mismatch — the answer carries duplicate_of_finding_node_id next to duplicate_of_finding_id, and the note names the node id to pass to update_finding_report. withNodeID resolves it from the candidates the question offered, so an id the model was never shown maps to nothing. The override test asserts both ids and the node id in the text.
  3. Private endpoints — the client is built by the server (server/triage.go) under the same guard as the model-list path: ARTEX_LLM_PRIVATE_ENDPOINTS allow-list, private and metadata addresses refused, proxy dropped, redirects not followed. A refused base_url leaves triage off, i.e. fail open like every other triage failure. TriageHTTPTimeout is exported so the injected client keeps the same budget instead of a second number. server/triage_review_test.go covers refuse/allow.

Should

  1. capText and buildDuplicateState cut on rune boundaries now (Cyrillic/CJK covered).
  2. putSettings rejects a negative or unknown triage_profile_id and a triage_min_confidence outside 0..1 with 400, before writing anything; 0 still turns the check off.
  3. The threshold is the triage_min_confidence setting (read on boot and on change) — description and code agree.

Verification: go build ./..., go vet, gofmt clean. go test ./agent/ ./db/ ./llmrec/ ./server/ against a local PostgreSQL: green apart from TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (binds 127.0.0.2) and TestPauseShiftsTaskDeadlineOnResume, both of which fail identically on clean main on macOS. Red/green: disabling the force_register branch fails the override test naming the ignored flag.

#499 is rebased on top of this branch.

The threshold is written by the settings path and read by the report_finding
worker, so a plain float global is a data race. Store the bits in an
atomic.Uint64, restore the default on 0 or negative, and accept 0 in
applyTriageThreshold so a reset takes effect.

Adds a two-goroutine -race test and the Set(0) reset test.

@BaaRai BaaRai left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for the rework. The six points from my earlier review are addressed: the force_register override, the node id next to the findings-table id, the guarded triage HTTP client, the rune-safe truncation, the settings validation, and the threshold as a stored setting.

One correction on my side: my earlier review said the threshold was a hardcoded const at 9c6af39. That was wrong. 32f2a6f had the const, and 9c6af39 already carried the var and the setter. I am sorry for the noise.

What remained is a data race on that var. It is written by the settings path and read from the report_finding worker, so a settings save concurrent with a task is a real race. I reproduced it with a two-goroutine -race test on a3e44d3. The CI -race job did not catch it because no test drives the pair.

I pushed c8c6df4 on your branch: the threshold is now kept as an atomic.Uint64 of float bits, SetTriageMinConfidence(0) or a negative value restores 0.5, applyTriageThreshold accepts 0..1 so a reset takes effect, and the commit adds the race test and the reset test. Your commits are unchanged.

The rest looks good to me. I will merge once CI is green.

@BaaRai
BaaRai merged commit a2d011a into BaaRai:main Nov 23, 2026
6 checks passed
@BaaRai

BaaRai commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Merged. Thanks @NikolayGusev-astra for the advisory duplicate check: the force_register path, the node id next to the findings-table id, the guarded triage client and the settings validation all hold. The atomic threshold fix rides on top, and CI is green.

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.

2 participants