Files
ARTEX/db/finding_dedup_pool.go
T
Николай Гусев 24cd7da9af agent: advisory duplicate check on report_finding via a decision model
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
2026-11-23 16:59:40 +03:00

72 lines
3.0 KiB
Go

package db
import (
"strings"
)
// prefixedNodeCols mirrors nodeCols with an alias, for queries that join
// exploration_nodes with another table carrying an `id` of its own.
const prefixedNodeCols = `n.id, n.kind, n.payload, n.priority, n.state, ` +
`COALESCE(n.origin,''), COALESCE(n.owner,''), COALESCE(n.blocked_reason,''), ` +
`COALESCE(n.delete_reason,''), n.created_at`
// FindingsSharingAssets returns finding nodes from OTHER tasks that are anchored to
// at least one of assetIDs.
//
// ListByKindWithSources covers the task's own findings plus its directly related
// tasks (task_relations). Two tasks run independently against the same target are
// NOT related, so a defect registered in one and re-registered in the other is
// invisible to a dedup check built only on that pool — measured live: three such
// duplicates across two tasks, all answered "distinct" because the question never
// offered them. Assets are the join that catches them.
//
// Returned nodes carry Inherited=true and SourceTaskID so callers can mark them as
// belonging to another task (read-only for extension).
func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask int64, limit int) ([]*Node, error) {
if len(assetIDs) == 0 {
return nil, nil
}
if limit <= 0 {
// 50: самый широкий наблюдённый пул по ассету — 31 находка на ассете [1]
// (53 находки в графе, 2026-11-22), запас 1.6x; вызывающий всё равно отбирает
// из результата не больше triageMaxExisting, так что 50 — верхняя граница запроса.
// при превышении: хвост по f.id DESC отбрасывается, вопрос всё равно ограничен.
limit = 50
}
// One containment per asset, OR-joined: asset_ids is a jsonb array and the GIN
// index (jsonb_path_ops) serves @>, not a list-membership operator.
ors := make([]string, 0, len(assetIDs))
args := []any{excludeTask}
for _, id := range assetIDs {
args = append(args, "["+itoa(id)+"]")
ors = append(ors, "f.asset_ids @> $"+itoa(int64(len(args)))+"::jsonb")
}
args = append(args, limit)
q := `SELECT ` + prefixedNodeCols + `, f.id, f.task_id
FROM findings f
JOIN exploration_nodes n ON n.id = f.node_id
WHERE f.task_id <> $1 AND (` + strings.Join(ors, " OR ") + `)
ORDER BY f.id DESC LIMIT $` + itoa(int64(len(args)))
rows, err := s.db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Node
for rows.Next() {
var n Node
var payload []byte
var findingID, taskID int64
if err := rows.Scan(&n.ID, &n.Kind, &payload, &n.Priority, &n.State, &n.Origin, &n.Owner,
&n.BlockedReason, &n.DeleteReason, &n.CreatedAt, &findingID, &taskID); err != nil {
return nil, err
}
n.Payload = payload
n.FindingID = findingID
n.SourceTaskID = taskID
n.Inherited = true
out = append(out, &n)
}
return out, rows.Err()
}