v4.3.31: 답변 수치가 실제 검색 결과에서 나왔는지 대조하는 가드 신설

기존 세 가드가 모두 엉뚱한 질문을 하고 있었음:
- AUTO-RECOVER    "근거 도구를 호출했는가?"   → 예
- EMPTY-GROUNDING "결과가 비어있는가?"        → 아니오
- looksLikeUnverifiedSpecClaim은 검색을 아예 안 했을 때만 발동
아무도 "그 숫자가 검색 결과에서 나왔는가?"를 묻지 않았음.

실사고(2026-07-29): 벤치마크가 존재하지 않는 조합(Tesla M40 2장 + Qwen3.6 35B)의
처리량을 묻자, 모델이 검색을 수행하고(이름이 비슷한 Apple M4 가이드가 걸림)
"초당 약 2~5 토큰"이라 단정. 세 가드 모두 통과시킴.

src/gateway/chat/numeric-grounding.ts 신설 — 답변의 (숫자, 단위) 주장이 이번 턴
도구 출력에 실제로 등장하는지 대조. 단위 근처(40자 이내)에 같은 숫자가 있어야
근거로 인정.

임계값을 실전에서 두 번 틀렸고, 두 번 다 실제 데이터가 잡아줌 — 둘 다 테스트로
고정:
1차 "모든 수치가 미근거일 때" → 답변이 질문의 "24GB"를 되뇐 것이 유일한 근거로
    잡혀 발동 실패. 질문에 등장한 숫자는 전제의 반복이지 모델의 주장이 아니므로
    제외하도록 수정
2차 여전히 실패 — 모델이 "157.66 tok/s on RTX 3090"을 페이지에서 정확히 인용
    했고, 그 진짜 수치 하나가 옆의 날조를 가려줌. "어딘가 근거가 있으면 통과"는
    안전한 규칙이 아니었음
3차 질문이 명시한 단위(몇 토큰/몇 GB/몇 와트/몇 퍼센트)로 범위를 좁히고, 그 안에서
    질문에 직접 답하는 수치(=선두 주장)만 검증. 비교·파생 수치는 자유롭게 허용

배포 후 확인 — 같은 질문에 대한 답변이 바뀜:
  이전: "초당 약 2~5 토큰 내외의 매우 낮은 속도가 예상됩니다"
  이후: "검색 결과에는 해당 조합의 실측 성능 수치가 없어서 단정하기 어렵습니다.
        다만 유사한 Tesla P40 1장에서 약 26.2 tokens per second ... M40은 이전
        세대이므로 이보다 낮을 것으로 보입니다"
모른다고 말하면서 실제로 찾은 인접 데이터는 제시하고 방향만 정성적으로 설명함.

테스트 137개 통과(수치 대조 15개 신규).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-07-29 19:54:37 +09:00
1 parent 0c75b946d9
commit ca7e6e49af
3 files changed
+307

No files matched your search

+27
View File
@@ -74,6 +74,7 @@ import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool
import { buildChatSystemPrompt } from './system-prompt';
import { evaluateSearchBudget } from './search-budget';
import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions';
import { checkNumericGrounding } from './numeric-grounding';
const MAX_TOOL_ROUNDS = 50;
type ExecutionMode = 'interactive' | 'background_task' | 'heartbeat' | 'cron';
@@ -270,6 +271,8 @@ async function handleChat(
const MAX_MESSAGING_FORCED_RETRIES = 2;
let emptyGroundingForcedRetries = 0;
const MAX_EMPTY_GROUNDING_FORCED_RETRIES = 1;
let numericGroundingForcedRetries = 0;
const MAX_NUMERIC_GROUNDING_FORCED_RETRIES = 1;
// Uncapped-round, unconditional-tool-history version of the round-0 tool-skip recovery
// below: a model that calls one irrelevant tool (e.g. coder_list_files while answering a
// GPU spec question) must not permanently disarm the safety net for the rest of the turn.
@@ -1674,6 +1677,30 @@ async function handleChat(
continue;
}
// NUMERIC-GROUNDING POST-CHECK (2026-07-29). The three checks above all pass an answer
// that searched, got results, and then stated figures those results never contained —
// the exact case that shipped "초당 약 2~5 토큰" for an unbenchmarked GPU pair. This one
// compares the answer's (number, unit) claims against the grounding tool output and only
// objects when EVERY claim is unsupported, so derived figures and partial misses pass.
const _numeric = checkNumericGrounding(
candidateText,
groundingResultsThisTurn.map((r) => String(r?.result || '')),
message,
);
const shouldForceNumericRetry = _numeric.allUnsupported
&& numericGroundingForcedRetries < MAX_NUMERIC_GROUNDING_FORCED_RETRIES;
if (shouldForceNumericRetry) {
numericGroundingForcedRetries++;
console.log(`[v2] NUMERIC-GROUNDING POST-CHECK (${numericGroundingForcedRetries}/${MAX_NUMERIC_GROUNDING_FORCED_RETRIES}): ${_numeric.unsupported.length} figure(s) not found in tool output [${_numeric.unsupported.map((c) => c.text).join(', ')}]. Re-prompting...`);
sendSSE('info', { message: 'Re-prompting model: stated figures were not in the search results...' });
messages.push({ role: 'assistant', content: candidateText });
messages.push({
role: 'user',
content: `None of the figures you just gave (${_numeric.unsupported.map((c) => c.text).join(', ')}) appear anywhere in the tool results from this turn — you produced them from memory, not from what you found. Rewrite the answer using ONLY numbers the tools actually returned. If the specific figure the user asked for is not in those results, say plainly that you could not find it and explain what IS known qualitatively, WITHOUT substituting an estimate. A stated range like "약 2~5" reads as a measurement to the user; do not offer one you cannot source.`,
});
continue;
}
if (shouldForceBrowserRetry) {
browserForcedRetries++;
const reason = `browser advisor route=${browserAdvisorRoute || 'continue_browser'} requires continued execution`;
+150
View File
@@ -0,0 +1,150 @@
/**
* numeric-grounding.ts
*
* Checks whether the concrete figures in an answer actually appear in the tool output that
* answer was supposedly based on.
*
* This closes the last gap left by the existing guards, all of which ask the wrong question:
* - AUTO-RECOVER asks "was a grounding tool called?" → yes
* - EMPTY-GROUNDING asks "did the tools return anything?" → yes
* - looksLikeUnverifiedSpecClaim only fires when nothing was searched at all
* None of them ask whether the NUMBER came from the search. Verified 2026-07-29: asked for the
* throughput of a Tesla M40 + Qwen3.6 35B pair — a combination nobody has benchmarked — the
* model searched, got back an Apple M4 guide (matched on the similar name) plus a generic Qwen
* page, and stated "초당 약 2~5 토큰" anyway. All three guards passed it.
*
* WHY UNIT-AWARE. Matching bare digits does not work: the failing answer's "2" and "5" both
* occur somewhere in the sources as fragments of unrelated numbers, so a naive check calls the
* fabrication supported. A claim is therefore (number, unit) — "2~5 토큰", "48GB" — and counts
* as supported only when the same number appears near the same unit in the source text.
*
* SCOPE IT TO WHAT WAS ASKED. An "every claim must miss" threshold looked safe but failed on the
* very case it was built for: asked for M40 throughput, the model correctly quoted a real
* "157.66 tok/s on RTX 3090" from the fetched page and then invented "초당 약 2~5 토큰" for the
* combination actually asked about. One genuine figure shielded the fabricated one. So when the
* question names a unit ("몇 토큰", "몇 GB"), only claims in THAT unit are judged — the answer to
* the question has to be sourced, while surrounding context figures are free to be derived.
*
* AND WITHIN THAT SCOPE, JUDGE THE DIRECT ANSWER. Narrowing to the unit was still not enough:
* both "초당 약 2~5 토큰" (invented, about the M40 pair actually asked about) and "157 tok/s"
* (real, quoted about an RTX 3090 for comparison) are tok/s claims, so the genuine comparison
* figure kept shielding the invented answer. The figure that ANSWERS the question is the one
* that must be sourced, and in practice it leads the reply — the surrounding comparisons and
* derivations are context. So only the FIRST in-scope claim is judged.
*
* False positives cost one wasted retry; false negatives ship an invented specification as a
* measurement, which is the failure this exists to catch.
*/
/** Units whose numbers are worth verifying — the fabrication-prone, checkable kind. */
const CLAIM_PATTERN = /(\d[\d,]*(?:\.\d+)?)\s*(?:[~\-–]\s*(\d[\d,]*(?:\.\d+)?)\s*)?(GB|TB|MB|tok\/s|tps|TFLOPS?|GFLOPS?|토큰|GHz|MHz|W\b|%)/gi;
/** How far from the unit the number may sit in the source and still count as the same claim. */
const PROXIMITY_CHARS = 40;
export interface NumericClaim {
/** Raw numbers stated together with the unit ("2~5 토큰" yields ['2','5']). */
numbers: string[];
unit: string;
/** The matched text, for logging. */
text: string;
}
export interface NumericGroundingResult {
claims: NumericClaim[];
unsupported: NumericClaim[];
/** The claim judged as the direct answer — first one in scope. */
primaryClaim: NumericClaim | null;
/** The unit the question asked about, when it named one. */
askedUnit: string | null;
/** True when every claim in scope is unsupported — the caller's retry trigger. */
allUnsupported: boolean;
}
/** Units the user can ask for by name, mapped to the claim units that answer them. */
const ASKED_UNIT_PATTERNS: Array<[RegExp, string[]]> = [
[/몇\s*토큰|토큰\s*(수|은|이)?\s*(얼마|몇)|초당.*토큰|tok\/s|tokens?\s+per\s+second|처리량|throughput/i, ['토큰', 'tok/s', 'tps']],
[/몇\s*기가|용량|vram|메모리\s*(얼마|몇)|how much (vram|memory)/i, ['GB', 'TB', 'MB']],
[/몇\s*와트|소비\s*전력|전력\s*(얼마|몇)|wattage|power draw/i, ['W']],
[/몇\s*퍼센트|비율|성능\s*(차이|손실|향상)|percent/i, ['%']],
];
/** Which claim units would answer this question, or null when it named none. */
export function detectAskedUnits(userMessage: string): string[] | null {
const m = String(userMessage || '');
for (const [re, units] of ASKED_UNIT_PATTERNS) if (re.test(m)) return units;
return null;
}
const normalizeNumber = (n: string) => n.replace(/,/g, '');
/** Strip code fences — numeric literals in code are not factual claims. */
const withoutCode = (s: string) => String(s || '').replace(/```[\s\S]*?```/g, ' ');
export function extractNumericClaims(answer: string): NumericClaim[] {
const text = withoutCode(answer);
const out: NumericClaim[] = [];
const re = new RegExp(CLAIM_PATTERN.source, 'gi');
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
const numbers = [m[1], m[2]].filter(Boolean).map(normalizeNumber);
if (!numbers.length) continue;
out.push({ numbers, unit: m[3], text: m[0].trim() });
}
return out;
}
/** Is `number` present in `source` within PROXIMITY_CHARS of `unit`? */
function isClaimSupported(claim: NumericClaim, source: string): boolean {
const haystack = source.toLowerCase();
const unit = claim.unit.toLowerCase();
for (const raw of claim.numbers) {
// Accept the source writing the number with or without thousands separators.
for (const variant of new Set([raw, raw.replace(/\B(?=(\d{3})+(?!\d))/g, ',')])) {
let from = 0;
for (;;) {
const idx = haystack.indexOf(variant.toLowerCase(), from);
if (idx === -1) break;
const window = haystack.slice(Math.max(0, idx - PROXIMITY_CHARS), idx + variant.length + PROXIMITY_CHARS);
if (window.includes(unit)) return true;
from = idx + 1;
}
}
}
return false;
}
export function checkNumericGrounding(
answer: string,
sourceTexts: readonly string[],
userMessage = '',
): NumericGroundingResult {
const source = sourceTexts.join('\n');
// Numbers the user themselves supplied ("Tesla M40 24GB 2장으로...") are the premise being
// restated, not something the model asserted — counting them as evidence let a fabricated
// answer look grounded purely because it echoed the question back (observed 2026-07-29: the
// question's own "24GB" was the single supported claim in an otherwise invented answer, which
// kept allUnsupported false and the retry from firing).
const askedNumbers = new Set(extractNumericClaims(userMessage).flatMap(c => c.numbers));
const allClaims = extractNumericClaims(answer)
.filter(c => !c.numbers.every(n => askedNumbers.has(n)));
// Narrow to the unit the question asked about, when it named one; otherwise judge everything.
const askedUnits = detectAskedUnits(userMessage);
const inScope = (c: NumericClaim) =>
!askedUnits || askedUnits.some(u => u.toLowerCase() === c.unit.toLowerCase());
const claims = askedUnits && allClaims.some(inScope) ? allClaims.filter(inScope) : allClaims;
const unsupported = claims.filter(c => !isClaimSupported(c, source));
// The reply leads with its answer; later figures are comparisons and derivations.
const primaryClaim = claims[0] || null;
return {
claims,
unsupported,
primaryClaim,
askedUnit: askedUnits ? askedUnits[0] : null,
// No claims at all → nothing to verify. Sources empty is handled upstream by the
// empty-grounding check, so treat it as "cannot verify" rather than "all fabricated".
allUnsupported: !!primaryClaim && source.trim().length > 0 && unsupported.includes(primaryClaim),
};
}
+130
View File
@@ -0,0 +1,130 @@
/**
* numeric-grounding.test.ts
*
* The last guard in the chain, and the only one that asks whether a NUMBER came from the search
* rather than whether a search happened. Its failure mode is the worst in the codebase: an
* invented specification delivered as a measurement, with a real search in the transcript to
* make it look sourced.
*
* Both directions matter equally here and pull against each other:
* - miss a fabrication → the user acts on an invented figure
* - flag a good answer → a pointless retry, and eventually the guard gets disabled
* The balance comes from scoping: judge the figure that ANSWERS the question (first claim in the
* unit the question named), not every number in the reply. Two earlier thresholds failed live and
* both are pinned below — "every claim must miss" was shielded by the question's own echoed
* numbers, and then by a genuine comparison figure quoted alongside the invented one.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { checkNumericGrounding, extractNumericClaims } from '../src/gateway/chat/numeric-grounding';
describe('주장 추출 — (숫자, 단위) 쌍', () => {
test('단위가 붙은 수치만 뽑는다', () => {
const c = extractNumericClaims('VRAM은 32GB이고 대략 5개 정도 있습니다.');
assert.equal(c.length, 1);
assert.deepEqual(c[0].numbers, ['32']);
assert.equal(c[0].unit, 'GB');
});
test('범위는 양 끝을 모두 담는다', () => {
const c = extractNumericClaims('초당 약 2~5 토큰');
assert.deepEqual(c[0].numbers, ['2', '5']);
});
test('천단위 쉼표를 정규화한다', () => {
assert.deepEqual(extractNumericClaims('1,024GB')[0].numbers, ['1024']);
});
test('코드블록 안 숫자는 주장이 아니다', () => {
assert.equal(extractNumericClaims('```py\nSIZE_GB = 80\n```').length, 0);
});
});
describe('근거 판정 — 단위 근처에 있어야 인정', () => {
test('도구가 준 수치는 근거 있음', () => {
const r = checkNumericGrounding(
'내일 구미는 최저 23.0°C 최고 33.0°C, 강수확률은 20%입니다.',
['기상청 단기예보\n 기온: 23.0~33.0°C\n 강수확률: 20%'],
);
assert.equal(r.allUnsupported, false);
});
test('[2026-07-29] 출처에 없는 수치는 걸린다 — 실제 사고 케이스', () => {
// M40+Qwen 조합의 실측치는 어디에도 없는데 모델이 값을 냈다. 검색은 실제로 수행됐고
// 결과도 비어있지 않아서 앞선 세 가드가 모두 통과시킨 상황.
const r = checkNumericGrounding(
'초당 약 2~5 토큰 정도 나옵니다.',
['[1] Running Local LLMs on M4: 24GB RAM Performance Guide ... [2] Qwen 3.6 35B MoE 일반 가이드'],
);
assert.equal(r.allUnsupported, true);
assert.equal(r.unsupported[0].text, '2~5 토큰');
});
test('맨숫자 우연 일치로 통과시키지 않는다', () => {
// "2"와 "5"는 출처 어딘가에 파편으로 존재한다. 단위를 함께 보지 않으면 근거 있음이 된다.
const r = checkNumericGrounding('초당 2 토큰입니다.', ['버전 2.5 문서, 페이지 5, 항목 2개']);
assert.equal(r.allUnsupported, true);
});
});
describe('직접 답변 판정 — 진짜 인용이 날조를 가리지 못하게', () => {
test('[2026-07-29] 같은 단위의 진짜 인용이 옆에 있어도 날조를 잡는다', () => {
// 실제 2차 실패: "157.66 tok/s on RTX 3090"은 페이지에 진짜 있는 값이라 근거 있음으로
// 잡히고, 그 하나가 질문 대상(M40 조합)의 날조를 가려주고 있었다.
const r = checkNumericGrounding(
'총 48GB 구성에서 초당 약 2~5 토큰입니다. 참고로 RTX 3090은 157 tok/s.',
['UD-Q4_K_M ... runs at 157.66 tok/s on our own RTX 3090'],
'Tesla M40 24GB 2장으로 Qwen3.6 35B 돌리면 초당 몇 토큰?',
);
assert.equal(r.allUnsupported, true);
assert.equal(r.primaryClaim?.text, '2~5 토큰');
});
test('질문이 물은 수치를 제대로 인용하면 통과', () => {
const r = checkNumericGrounding(
'RTX 3090은 157.66 tok/s가 나옵니다.',
['runs at 157.66 tok/s on our own RTX 3090'],
'RTX 3090 초당 몇 토큰?',
);
assert.equal(r.allUnsupported, false);
});
test('질문 단위 밖의 수치는 판정 대상이 아니다', () => {
// "몇 토큰"을 물었으면 GB 수치는 맥락일 뿐이다.
const r = checkNumericGrounding(
'초당 5 토큰이며 VRAM은 99GB 필요합니다.',
['throughput: 5 토큰'],
'초당 몇 토큰?',
);
assert.equal(r.askedUnit, '토큰');
assert.equal(r.allUnsupported, false);
});
});
describe('보수적 임계값 — 오탐 방지가 우선', () => {
test('파생 수치는 허용한다 — 앞선 근거가 답을 지탱하면 통과', () => {
// 48GB는 24GB×2로 유도한 값이라 출처에 없다. 이런 계산을 막으면 안 된다.
const r = checkNumericGrounding('카드당 24GB이므로 2장이면 48GB입니다.', ['spec: 24GB per card']);
assert.equal(r.allUnsupported, false);
});
test('질문에 있던 숫자를 되뇌는 것은 근거로 치지 않는다', () => {
// 이 예외가 없으면 질문의 "24GB"가 유일한 근거로 잡혀 날조 답변이 통과한다(실제로 그랬음).
const r = checkNumericGrounding(
'Tesla M40 24GB 2장이면 초당 약 2~5 토큰입니다.',
['관련 없는 검색 결과'],
'Tesla M40 24GB 2장으로 돌리면 초당 몇 토큰?',
);
assert.equal(r.allUnsupported, true);
});
test('수치 주장이 없으면 발동하지 않는다', () => {
assert.equal(checkNumericGrounding('메모리 대역폭이 병목입니다.', ['아무 문서']).allUnsupported, false);
});
test('출처 자체가 비면 발동하지 않는다 — 빈검색결과 가드 담당', () => {
assert.equal(checkNumericGrounding('32GB입니다.', []).allUnsupported, false);
assert.equal(checkNumericGrounding('32GB입니다.', [' ']).allUnsupported, false);
});
});