voliteľný log zamietnutých odpovedí s konceptom a posudkom; index mien bez zahrievania, testy bez ostrého kontextu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4a0dc506d0
commit
c333ace7bd
@ -13,8 +13,9 @@ WIKI = {"status": "ok", "reason": None, "accepted_for_delivery": True, "claims":
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def combo(monkeypatch):
|
||||
def combo(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("SEARCH_API_KEY", "combined-test-key")
|
||||
monkeypatch.setenv("ANSWER_CONTEXT_FILE", str(tmp_path / "conversation_pages.sqlite")) # never the live store
|
||||
monkeypatch.setenv("ANSWER_WITH_CRZP", "1")
|
||||
state = {"part": None, "match": {"name": "Ján Pták", "student": True}}
|
||||
monkeypatch.setattr("tools.crzp.answering.wiki_bridge.wiki_match", lambda q, db_file=None: state["match"])
|
||||
|
||||
@ -361,3 +361,47 @@ def test_the_audit_sees_plan_only_students_as_the_closing_notice_the_user_sees()
|
||||
"\n\nZdroje: https://zp.test/a, https://zp.test/b")
|
||||
assert "Téma je len v zadaní alebo pláne, bez zaznamenaného výsledku: Nikita Bodnar." in out["presentation_notes"]
|
||||
assert collapse_side_people({"answer": "**X**\n\n- iné"}) == {"answer": "**X**\n\n- iné"} # nothing to collapse
|
||||
|
||||
|
||||
def _audit_log(monkeypatch, tmp_path, enabled):
|
||||
import tools.rag.common as common
|
||||
monkeypatch.setattr(common, 'DB_FILE', tmp_path / 'rag.sqlite')
|
||||
(tmp_path / 'logs').mkdir()
|
||||
if enabled:
|
||||
(tmp_path / 'logs' / 'answer_audit.enabled').write_text('')
|
||||
return tmp_path / 'logs' / 'answer_audit.jsonl'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_a_rejection_is_logged_only_when_enabled_and_the_delivery_is_the_same(monkeypatch, tmp_path, enabled):
|
||||
log = _audit_log(monkeypatch, tmp_path, enabled)
|
||||
plan, result, index = fixture()
|
||||
out = c.enforce(plan.question, 'rag', plan, result, index=index, complete=audit(facts_supported=False))
|
||||
assert out['delivery_check']['code'] == 'request_not_fulfilled' and out['status'] == 'error'
|
||||
assert 'review' not in json.dumps(out) # nothing of the log reaches the answer
|
||||
if not enabled:
|
||||
assert not log.exists()
|
||||
return
|
||||
row = json.loads(log.read_text(encoding='utf-8').splitlines()[0])
|
||||
assert row['layer'] == 'fulfilment' and row['code'] == 'request_not_fulfilled' and row['engine'] == 'rag'
|
||||
assert 'funguje model BERT' in row['answer'] and row['evidence'][0]['phase'] == 'result'
|
||||
assert row['review']['why'] == 'facts' and row['review']['facts_supported'] is False
|
||||
assert 'question' not in row and set(row) == {'at', 'q', 'engine', 'layer', 'code', 'intent', 'facets', 'answer',
|
||||
'evidence', 'review'} # the question is no field of the log
|
||||
|
||||
|
||||
def test_a_mechanical_rejection_is_logged_without_a_review(monkeypatch, tmp_path):
|
||||
log = _audit_log(monkeypatch, tmp_path, True)
|
||||
plan, result, index = fixture()
|
||||
result['source_urls'].append('https://invented.test')
|
||||
out = c.enforce(plan.question, 'rag', plan, result, index=index, complete=audit())
|
||||
assert out['delivery_check']['code'] == 'invalid_citation'
|
||||
row = json.loads(log.read_text(encoding='utf-8').splitlines()[0])
|
||||
assert row['layer'] == 'answer' and row['code'] == 'invalid_citation' and row['review'] is None
|
||||
|
||||
|
||||
def test_an_accepted_answer_is_never_logged(monkeypatch, tmp_path):
|
||||
log = _audit_log(monkeypatch, tmp_path, True)
|
||||
plan, result, index = fixture()
|
||||
assert c.enforce(plan.question, 'rag', plan, result, index=index, complete=audit())['accepted_for_delivery']
|
||||
assert not log.exists()
|
||||
|
||||
@ -1671,8 +1671,8 @@ def answer(question: str, *, engine: str, limit: int = 5, context_token: str | N
|
||||
if enabled() and not _warmed.is_set(): # tag rarity for related topics, counted once in the background
|
||||
_warmed.set()
|
||||
_pool().submit(tag_frequencies)
|
||||
from tools.crzp.answering.names import _known_index
|
||||
_pool().submit(_known_index) # the names of the local register cache (misspelled or inflected CRZP names)
|
||||
# (the names of the local register cache are read on the first CRZP name that needs them, never ahead: reading
|
||||
# 156 000 records in the background slowed the answers running at the same time)
|
||||
parent = _parent.set(token_step(context_token)) # every step of this answer continues the sent one
|
||||
previous = unseal(context_token) if context_token else None
|
||||
subject = _subject.set((previous or {}).get("person") if isinstance(previous, dict) else None)
|
||||
|
||||
@ -84,3 +84,21 @@ def trace(question: str, engine: str, follow_up: bool, result: dict, record: dic
|
||||
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def audit(row: dict) -> None:
|
||||
"""Why an answer was rejected, with its draft and the audit's review, for finding the rejections' patterns.
|
||||
Written only while data/logs/answer_audit.enabled exists (off by default, like trace()); a local file, never
|
||||
sent anywhere. The question is no field of it, only the hash of the request (the "q" of answer_timings.jsonl);
|
||||
the review's requirement descriptions paraphrase what was asked, as trace() keeps the question itself."""
|
||||
try:
|
||||
from tools.rag.common import DB_FILE
|
||||
folder = DB_FILE.parent / "logs"
|
||||
if not (folder / "answer_audit.enabled").exists():
|
||||
return
|
||||
record = _current.get()
|
||||
out = {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "q": (record or {}).get("q"), **row}
|
||||
with _write_lock, (folder / "answer_audit.jsonl").open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(out, ensure_ascii=False, default=str) + "\n")
|
||||
except (OSError, TypeError, ValueError):
|
||||
pass
|
||||
|
||||
@ -230,6 +230,28 @@ def audit_evidence(rows,reverse,segments=None):
|
||||
return list(groups.values())
|
||||
|
||||
|
||||
def _reviewed(error,review,why):
|
||||
"""The audit's review kept with its rejection (for the opt-in rejection log, tools/answers/timing.audit)."""
|
||||
error.review={'why':why,**review.model_dump()}
|
||||
return error
|
||||
|
||||
|
||||
def _log_rejection(engine,plan,result,error):
|
||||
"""One line of data/logs/answer_audit.jsonl (only while answer_audit.enabled exists): the layer and code of the
|
||||
rejection, the draft answer, its evidence and the audit's review. Never changes the delivery."""
|
||||
try:
|
||||
from tools.answers import timing
|
||||
timing.audit({'engine':engine,'layer':error.layer,'code':error.code,
|
||||
'intent':getattr(plan,'intent',None),'facets':list(getattr(plan,'facets',None) or []),
|
||||
'answer':(result.get('answer') or '')[:4000],
|
||||
'evidence':[{k:(r.get(k) if k!='text' else (r.get('text') or '')[:200])
|
||||
for k in ('person','work_label','phase','kind','text')}
|
||||
for r in (result.get('evidence') or [])[:30]],
|
||||
'review':getattr(error,'review',None)})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def semantic_check(query,plan,result,*,complete=None):
|
||||
rows={r['id']:r for r in result.get('evidence',[]) if r.get('id')}
|
||||
aliases={f'E{i}':key for i,key in enumerate(rows,1)}
|
||||
@ -282,9 +304,9 @@ def semantic_check(query,plan,result,*,complete=None):
|
||||
'clear': review.clear, 'all_identified': review.all_requirements_identified,
|
||||
'statuses': [r.status for r in review.requirements]})
|
||||
if not review.plan_matches_request:
|
||||
raise ContractError('fulfilment','request_not_fulfilled')
|
||||
raise _reviewed(ContractError('fulfilment','request_not_fulfilled'),review,'plan')
|
||||
if not review.facts_supported:
|
||||
error=ContractError('fulfilment','request_not_fulfilled')
|
||||
error=_reviewed(ContractError('fulfilment','request_not_fulfilled'),review,'facts')
|
||||
error.unsupported_facts=True # The wording, not the request, failed.
|
||||
raise error
|
||||
notes=result.get('presentation_notes',[])
|
||||
@ -301,7 +323,7 @@ def semantic_check(query,plan,result,*,complete=None):
|
||||
weak.append(requirement)
|
||||
if answered and len(weak)==len(answered):
|
||||
timing.note('fulfilment_weak', len(weak))
|
||||
raise ContractError('fulfilment','request_not_fulfilled')
|
||||
raise _reviewed(ContractError('fulfilment','request_not_fulfilled'),review,'weak')
|
||||
statuses=[r.status for r in review.requirements]
|
||||
if statuses and all(status in {'unfulfilled','uncertain'} for status in statuses):
|
||||
# The answer itself discloses the doubt with the backend's deterministic
|
||||
@ -310,7 +332,7 @@ def semantic_check(query,plan,result,*,complete=None):
|
||||
disclosed=all(r.status=='uncertain' and any(note in segments.get(key,'') for note in notes
|
||||
for key in r.answer_segments) for r in review.requirements)
|
||||
if not disclosed:
|
||||
raise ContractError('fulfilment','request_not_fulfilled')
|
||||
raise _reviewed(ContractError('fulfilment','request_not_fulfilled'),review,'unfulfilled')
|
||||
return 'uncertain'
|
||||
# A reviewer's doubt about ONE part no longer discards the supported parts.
|
||||
# The answer is delivered as partial with an explicit, generic notice.
|
||||
@ -421,6 +443,7 @@ def enforce(query,engine,plan,result,*,index=None,facts=(),complete=None,prose_s
|
||||
elif (result.get('answer_coverage') or {}).get('status') in {'partial','unknown'}:state='partial'
|
||||
return {**result,'delivery_check':{'layer':'delivery','code':state,'request_fingerprint':mark}}
|
||||
except ContractError as error:
|
||||
_log_rejection(engine,plan,result,error)
|
||||
reason='verification_unavailable' if error.code=='verification_unavailable' else 'answer_rejected'
|
||||
return {**public_failure({'reason':reason,'engine':engine,'index_version':result.get('index_version')}),
|
||||
'delivery_check':{'layer':error.layer,'code':error.code,'request_fingerprint':mark}}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user