291 lines
15 KiB
Python
291 lines
15 KiB
Python
import copy
|
|
import json
|
|
import pytest
|
|
|
|
from test_investigation_lean import lean_context
|
|
from test_lean_investigation_decision import reply
|
|
from test_case_builder import case_setup
|
|
from test_investigation_tools import tool_case
|
|
from viano_bug_analysis.analysis import InvestigationError
|
|
from viano_bug_analysis.analysis.investigation_prompt import build_prompt
|
|
from viano_bug_analysis.analysis.investigation_compact import validate_tool_shape
|
|
from viano_bug_analysis.analysis.tool_guidance import HEADER,FILTER_REQUIREMENT,filter_feedback
|
|
|
|
|
|
def context(lean=False):
|
|
c=lean_context()
|
|
if lean:c['lean_protocol']=2
|
|
else:c.pop('lean_session')
|
|
return c
|
|
|
|
|
|
@pytest.mark.parametrize('lean',[False,True])
|
|
@pytest.mark.parametrize('filters',[[],['column','id','operator','eq','value',23487]])
|
|
def test_recorded_filter_failures_get_exact_value_free_repair_and_valid_shape_passes(lean,filters):
|
|
c=context(lean)
|
|
action={'kind':'tool','operation':'project.query','arguments':{
|
|
'kind':'database.rows','table':'objects','columns':['id'],
|
|
'filters':filters,'offset':0,'limit':5}}
|
|
if lean:r={'assessment':None,'observation':'Scoped observation.','next':action}
|
|
else:
|
|
r=reply();r['next']=action;r['update']['next_step']=None
|
|
r['update']['working_brief']['findings']=[]
|
|
before=copy.deepcopy(r)
|
|
with pytest.raises(InvestigationError) as error:validate_tool_shape(c,r)
|
|
assert r==before
|
|
feedback=error.value.feedback
|
|
assert feedback['requirement']==FILTER_REQUIREMENT and len(FILTER_REQUIREMENT)<=160
|
|
assert '23487' not in json.dumps(feedback)
|
|
fixed=copy.deepcopy(r);fixed['next']['arguments']['filters']=[{'column':'id','operator':'eq','value':23487}]
|
|
validate_tool_shape(c,fixed)
|
|
|
|
|
|
@pytest.mark.parametrize('lean',[False,True])
|
|
def test_explicit_argument_shapes_once_in_full_and_slim_requests(lean):
|
|
c=context(lean);c['tool_guidance_version']=1
|
|
b=c['tool_schema']['x-project-bindings'];b['relation_profiles']={'inspect':{}};b['source_analysis']={'version':1}
|
|
request=build_prompt(c);system=request['messages'][0]['content']
|
|
assert system.count(HEADER)==1
|
|
assert '"kind":"database.relations"' in system and '"profile"' in system
|
|
assert '"kind":"source.context"' in system and '"path_prefix":""' in system
|
|
assert 'nonempty array of objects' in system and 'No table or SQL argument' in system
|
|
# Already stored contexts without the new marker keep their old messages.
|
|
c.pop('tool_guidance_version')
|
|
assert HEADER not in build_prompt(c)['messages'][0]['content']
|
|
|
|
|
|
def test_no_new_research_instructions_during_consolidation():
|
|
c=context(True);c['tool_guidance_version']=1;c['lean_session']['checkpoint']=True
|
|
c['tool_schema']['x-project-bindings']['relation_profiles']={'inspect':{}}
|
|
assert HEADER not in build_prompt(c)['messages'][0]['content']
|
|
|
|
|
|
def test_saved_generic_feedback_is_not_retroactively_rewritten():
|
|
from viano_bug_analysis.analysis.investigation_lean import repair_feedback
|
|
old={'validation_path':'/next/arguments/filters/0','validation_fields':[],
|
|
'requirement':'match_expected_type_at_validation_path'}
|
|
assert repair_feedback(old)==old
|
|
assert filter_feedback(old)['requirement']==FILTER_REQUIREMENT
|
|
nested={'validation_path':'/next/arguments/filters/0/operator','requirement':'use_allowed_value_at_validation_path'}
|
|
assert filter_feedback(nested)==nested
|
|
|
|
|
|
def test_feedback_persists_then_fixture_model_corrects_without_extra_tool_actions(tool_case):
|
|
from test_working_brief import service_for
|
|
from test_investigator import LoopAdapter,run,state
|
|
from test_case_interpreter import gateway
|
|
from test_project_research import rows
|
|
from viano_bug_analysis.analysis import Investigator
|
|
from viano_bug_analysis.tools import InvestigationToolRouter
|
|
from viano_bug_analysis.package import PackageReader
|
|
attempts=[]
|
|
def change(r,c):
|
|
if c.get('previous_rejection_details'):
|
|
assert c['previous_rejection_details']['requirement']==FILTER_REQUIREMENT
|
|
q=rows()
|
|
if not attempts:q['filters']=[]
|
|
attempts.append(q)
|
|
r['next']={'kind':'tool','operation':'project.query','arguments':q}
|
|
adapter=LoopAdapter(change)
|
|
loop=Investigator(tool_case[0],gateway(adapter),router=InvestigationToolRouter(project_research=service_for(tool_case)))
|
|
first=run(loop,steps=1)
|
|
assert state(first)['hypotheses']['H1']['invalid_responses']==1
|
|
second=run(loop,steps=1)
|
|
assert len(attempts)==2 and state(second)['active'] is None
|
|
assert state(second)['hypotheses']['H1']['invalid_responses']==0
|
|
with PackageReader(second.package) as reader:
|
|
assert len([p for p in reader.files if p.startswith('analysis/evidence/captures/')])==1
|
|
|
|
|
|
@pytest.mark.parametrize('lean', [False, True])
|
|
def test_unknown_table_feedback_survives_full_and_lean_projection(lean):
|
|
from viano_bug_analysis.analysis.tool_guidance import database_rejection_feedback
|
|
c = context(lean)
|
|
c['previous_rejection'] = 'PROJECT_DATABASE_TABLE_UNKNOWN'
|
|
answer = {'next': {'operation': 'project.query', 'arguments': {
|
|
'table': 'cata_world.item_template', 'filters': [{'value': 'do-not-copy'}]}}}
|
|
detail = database_rejection_feedback(c['previous_rejection'], answer, c)
|
|
assert detail['selected_database'] == 'cata_world'
|
|
assert detail['rejected_table'] == 'cata_world.item_template'
|
|
assert len(detail['requirement']) <= 160
|
|
assert 'do-not-copy' not in json.dumps(detail)
|
|
c['previous_rejection_details'] = detail
|
|
request = build_prompt(c)
|
|
assert 'database.tables' in request['messages'][1]['content']
|
|
assert 'cata_world.item_template' in request['messages'][1]['content']
|
|
|
|
|
|
@pytest.mark.parametrize('legacy_feedback', [False, True])
|
|
def test_unknown_table_repeated_query_is_not_sent_to_provider_and_discovery_recovers(tool_case, monkeypatch, legacy_feedback):
|
|
from test_investigator import LoopAdapter, run, state
|
|
from test_case_interpreter import gateway
|
|
from test_project_research import FakeDB, rows
|
|
from viano_bug_analysis.analysis import Investigator
|
|
from viano_bug_analysis.tools import InvestigationToolRouter, ToolError
|
|
from viano_bug_analysis.tools.project_query import ProjectResearch
|
|
from viano_bug_analysis.package import PackageReader
|
|
class MissingTable(FakeDB):
|
|
missing_calls = 0
|
|
def validate(self, args):
|
|
if args.get('table') == 'item_template':
|
|
self.missing_calls += 1
|
|
raise ToolError('PROJECT_DATABASE_TABLE_UNKNOWN')
|
|
db = MissingTable()
|
|
with PackageReader(tool_case[1]) as reader:
|
|
service = ProjectResearch(reader.manifest['project'], database=db)
|
|
attempts = []
|
|
def change(reply, c):
|
|
if attempts:
|
|
assert c['previous_rejection_details']['rejected_table'] == 'item_template'
|
|
query = rows(table='item_template')
|
|
if len(attempts) == 1:
|
|
query['columns'] = ['different_column']
|
|
elif len(attempts) == 2:
|
|
query = {'kind':'database.tables', 'text':'item', 'offset':0, 'limit':20}
|
|
attempts.append(query)
|
|
reply['next'] = {'kind':'tool', 'operation':'project.query', 'arguments':query}
|
|
loop = Investigator(tool_case[0], gateway(LoopAdapter(change)),
|
|
router=InvestigationToolRouter(project_research=service))
|
|
from viano_bug_analysis.analysis import tool_guidance
|
|
original_feedback = tool_guidance.database_rejection_feedback
|
|
if legacy_feedback:
|
|
monkeypatch.setattr(tool_guidance, 'database_rejection_feedback', lambda *args: None)
|
|
assert state(run(loop, steps=1))['hypotheses']['H1']['invalid_responses'] == 1
|
|
monkeypatch.setattr(tool_guidance, 'database_rejection_feedback', original_feedback)
|
|
assert db.missing_calls == 1
|
|
assert state(run(loop, steps=1))['hypotheses']['H1']['invalid_responses'] == 2
|
|
assert db.missing_calls == 1
|
|
result = run(loop, steps=1)
|
|
assert state(result)['hypotheses']['H1']['invalid_responses'] == 0
|
|
assert db.calls == 1
|
|
assert db.missing_calls == 1
|
|
|
|
|
|
@pytest.mark.parametrize('code', ['PROJECT_DATABASE_TABLE_UNKNOWN', 'PROJECT_DATABASE_COLUMN_UNKNOWN'])
|
|
@pytest.mark.parametrize('interrupted', [False, True, 'blocked'])
|
|
def test_execution_metadata_failure_returns_to_model_without_fabricating_evidence(tool_case, code, interrupted, monkeypatch):
|
|
from test_investigator import LoopAdapter, run, state, CASE
|
|
from test_case_interpreter import gateway
|
|
from test_project_research import FakeDB
|
|
from viano_bug_analysis.analysis import Investigator
|
|
from viano_bug_analysis.tools import InvestigationToolRouter, ToolError
|
|
from viano_bug_analysis.tools.project_query import ProjectResearch
|
|
from viano_bug_analysis.budget import BudgetManager
|
|
from viano_bug_analysis.package import PackageReader, PackageValidator
|
|
class ExecutionFailure(FakeDB):
|
|
failure_code = code
|
|
def query(self, args):
|
|
if args.get('table') == 'item_template':
|
|
raise ToolError(self.failure_code)
|
|
return super().query(args)
|
|
db = ExecutionFailure()
|
|
with PackageReader(tool_case[1]) as reader:
|
|
service = ProjectResearch(reader.manifest['project'], database=db)
|
|
calls = []
|
|
def change(reply, c):
|
|
if calls:
|
|
assert c['previous_rejection'] == code
|
|
assert c['previous_result'] is None
|
|
assert c['previous_rejection_details']['rejected_table'] == 'item_template'
|
|
query = {'kind':'database.tables','text':'item','offset':0,'limit':10}
|
|
else:
|
|
query = {'kind':'database.schema','table':'item_template'}
|
|
calls.append(query)
|
|
reply['next'] = {'kind':'tool','operation':'project.query','arguments':query}
|
|
loop = Investigator(tool_case[0], gateway(LoopAdapter(change)),
|
|
router=InvestigationToolRouter(project_research=service))
|
|
if interrupted == 'blocked':
|
|
# Also verifies that a real provider outage remains an operator block,
|
|
# and an already reserved execution can resume under the new handling.
|
|
db.failure_code = 'PROJECT_DATABASE_UNAVAILABLE'
|
|
blocked = run(loop, steps=1)
|
|
assert blocked.status == 'BLOCKED'
|
|
with PackageReader(blocked.package) as reader:
|
|
assert reader.manifest['routing']['reason'] == 'RESEARCH_UNAVAILABLE'
|
|
generation = reader.manifest['package_generation']
|
|
assert BudgetManager(tool_case[0]).snapshot(*CASE).state['accounts']['H1']['actions']['INV-1-H1-1']['status'] == 'reserved'
|
|
monkeypatch.setattr(tool_case[0], 'retry_due', lambda manifest: True)
|
|
tool_case[0].advance(*CASE, 'INVESTIGATING_HYPOTHESES', step_id='fixture-provider-restored', expected_generation=generation)
|
|
db.failure_code = code
|
|
elif interrupted:
|
|
original = loop._invalid
|
|
class SimulatedCrash(BaseException):
|
|
pass
|
|
def crash(*args, **kwargs):
|
|
raise SimulatedCrash('crash after failed reservation was settled')
|
|
monkeypatch.setattr(loop, '_invalid', crash)
|
|
with pytest.raises(SimulatedCrash, match='crash after'):
|
|
run(loop, steps=1)
|
|
monkeypatch.setattr(loop, '_invalid', original)
|
|
result = run(loop, steps=1)
|
|
assert result.status == 'YIELDED'
|
|
assert state(result)['hypotheses']['H1']['notes'][-1]['code'] == code
|
|
active = state(result)['active']
|
|
assert active['phase'] == 'prompt' and active['execution_retries'] == 1
|
|
account = BudgetManager(tool_case[0]).snapshot(*CASE).state['accounts']['H1']
|
|
failed = account['actions']['INV-1-H1-1']
|
|
assert failed['failed'] and failed['reward'] == 0 and failed['status'] == 'settled'
|
|
assert account['rewarded'] == 0
|
|
with PackageReader(result.package) as reader:
|
|
assert reader.manifest['state'] == 'INVESTIGATING_HYPOTHESES'
|
|
assert not [n for n in reader.files if n.startswith('analysis/evidence/captures/')]
|
|
result = run(loop, steps=1)
|
|
assert state(result)['active'] is None
|
|
account = BudgetManager(tool_case[0]).snapshot(*CASE).state['accounts']['H1']
|
|
assert 'INV-1-H1-1-recovery-1' in account['actions']
|
|
assert account['actions']['INV-1-H1-1']['failed']
|
|
assert PackageValidator().validate(result.package).valid
|
|
|
|
|
|
@pytest.mark.parametrize('lean',[False,True])
|
|
def test_shared_database_failure_hints_survive_bounded_prompt_views(lean):
|
|
c=context(lean);c['tool_guidance_version']=1
|
|
c['database_query_failures']=[{'table':'missing_items','database':'cata_world'}]
|
|
request=build_prompt(c)
|
|
assert 'missing_items' in request['messages'][1]['content']
|
|
assert 'database_query_failures' in request['messages'][1]['content']
|
|
assert 'not causal evidence' in request['messages'][0]['content']
|
|
|
|
|
|
def test_failed_tables_are_shared_across_hypotheses_and_bounded():
|
|
from viano_bug_analysis.analysis.tool_guidance import database_failure_history
|
|
class Archive:
|
|
def namelist(self):return [f'call{i}' for i in range(20)]
|
|
class Reader:
|
|
_archive=Archive()
|
|
state={'hypotheses':{'H1':{'notes':[{'kind':'invalid_response','code':'PROJECT_DATABASE_TABLE_UNKNOWN','llm_ref':f'call{i}'} for i in range(10)]},
|
|
'H2':{'notes':[{'kind':'invalid_response','code':'PROJECT_DATABASE_TABLE_UNKNOWN','llm_ref':f'call{i}'} for i in range(10,20)]}}}
|
|
def read(reader,ref,contract):
|
|
return {'outcome':{'document':{'next':{'operation':'project.query','arguments':{'table':'db.items'+ref[4:]}}}}}
|
|
entries=database_failure_history(Reader(),state,{},read)
|
|
assert len(entries)==8 and entries[0]=={'database':'db','table':'items12'}
|
|
assert entries[-1]=={'database':'db','table':'items19'}
|
|
|
|
|
|
|
|
def test_failed_table_is_visible_when_scheduler_moves_to_another_hypothesis(tool_case):
|
|
from test_investigator import LoopAdapter,run
|
|
from test_case_interpreter import gateway
|
|
from test_project_research import FakeDB,rows
|
|
from viano_bug_analysis.analysis import Investigator
|
|
from viano_bug_analysis.tools import InvestigationToolRouter,ToolError
|
|
from viano_bug_analysis.tools.project_query import ProjectResearch
|
|
from viano_bug_analysis.package import PackageReader
|
|
class Missing(FakeDB):
|
|
def validate(self,args):
|
|
if args.get('table')=='missing_items':raise ToolError('PROJECT_DATABASE_TABLE_UNKNOWN')
|
|
with PackageReader(tool_case[1]) as reader:
|
|
service=ProjectResearch(reader.manifest['project'],database=Missing())
|
|
selected=[]
|
|
def change(reply,c):
|
|
selected.append(c['selected_hypothesis'])
|
|
if len(selected)==1:
|
|
query=rows(table='missing_items')
|
|
else:
|
|
assert c['database_query_failures']==[{'table':'missing_items','database':None}]
|
|
query={'kind':'database.tables','text':'item','offset':0,'limit':10}
|
|
reply['next']={'kind':'tool','operation':'project.query','arguments':query}
|
|
loop=Investigator(tool_case[0],gateway(LoopAdapter(change)),router=InvestigationToolRouter(project_research=service))
|
|
run(loop,steps=3)
|
|
assert selected==['H1','H1','H2']
|