Preserve database namespaces in bounded investigation context

This commit is contained in:
Nico committed 2026-11-20 11:11:26 +01:00
1 parent 4c50e548d3
commit 76e43f0f4d
12 files changed
+1767 -4

No files matched your search

@@ -0,0 +1,51 @@
# BUG-000023: Datenbankzuordnung im begrenzten Prompt
Generation 187 wurde nach einer ausdrücklich freigegebenen Antwort erneut
blockiert. Die Antwort wechselte von item_template zu item_sparse, verwendete
aber keinen Datenbanknamen. Das Tool löste die Anfrage daher in cata_world auf.
Der vorherige erfolgreiche Zugriff in H3 betraf cata_hotfixes.item_sparse.
Die tatsächlich gesendete begrenzte Promptansicht enthielt weder die
Standard-/Zusatzdatenbanken noch eine entsprechende Qualifizierungsregel.
Der gespeicherte Korrekturkontext war außerdem vor Einführung der gemeinsamen
Tabellenhinweise erzeugt worden. Die Sperre selbst war daher korrekt; die
Kontextübergabe war unvollständig.
Neue SQL-Untersuchungskontexte erhalten database_access_version=1. Ihre
Modellansicht enthält ausschließlich den Namen der Standarddatenbank, bis zu
16 konfigurierte Datenbanknamen mit Auslassungszähler und bis zu zwölf zuvor
gelesene Tabellen als vollständig qualifizierte Namen mit Beleg-ID. Die
Tabellenhinweise werden aus bereits archivierten erfolgreichen direkten
Datenbankabfragen aller Hypothesen abgeleitet. Snapshot, Standarddatenbank,
explizite Auswahl und erlaubte Tabellen müssen zur aktuellen Bindung passen.
Es werden keine Verbindungsadressen, Nutzernamen, Zugangsdaten, Tabelleninhalte
oder vollständigen Schemas zusätzlich übertragen.
Die Metadaten überstehen kompakte, schlanke und begrenzte Ansichten. Die
Qualifizierungsregel wird ausdrücklich an die endgültigen Systemanweisungen
der begrenzten Ansicht angehängt, statt sich auf vorherige, später ersetzte
Tool-Guidance zu verlassen. Frühere erfolgreiche Abfragen garantieren keine
aktuelle Verfügbarkeit und stellen keinen vollständigen Tabellenkatalog dar.
Unqualifizierte Tabellen verwenden weiterhin ausschließlich die Standard-DB;
der Controller verändert die angefragte Datenbank niemals automatisch.
Bei Wiederaufnahme eines älteren Kontexts wird nur vor einem noch nicht
gespeicherten Request ein neuer Kontext mit dem Versionsmarker und den aktuellen
gemeinsamen Fehlerhinweisen geschrieben. Alte Kontext- und Requestdateien bleiben
unverändert. Bereits gespeicherte Requests behalten ihre ursprüngliche Ansicht,
auch wenn ihr Aufruf nach einem Prozessabbruch erst noch verarbeitet werden muss.
Untersuchungsbudgets und Fehlergrenzen werden nicht zurückgesetzt.
111 lokale Tests zu Datenbankkontext, Tool-Guidance, Window-v2-Verträgen,
Promptfenstern, Mehrdatenbankzugriff, Antwortreparatur und Betreiberfreigabe
bestanden. Der neue Regressionstest verwendet einen kuratierten Ausschnitt der
tatsächlichen BUG-23-Bindung und des erfolgreichen Schemaabrufs E000009. Er
prüft die endgültigen kurzen und konsolidierenden Requests, einschließlich
20.000-Zeichen-Grenze, statt nur eine Zwischenansicht zu testen. Weitere Prüfungen
decken unzulässige Datenbanken, abweichende Snapshots, Wiederaufnahme eines alten
Korrekturkontexts sowie einen Abbruch nach Speichern eines alten Requests ohne
doppelte Modellanfrage ab. Keine kostenpflichtigen LLM-Aufrufe.
Die Verbrauchsbilanz bis Generation 187 liegt separat unter
token-usage/bug23-blocked-g00000187-20261120.json. Der frühere Snapshot bleibt
erhalten. Der kleine Ablehnungsfall und das für die Regression erforderliche
Datenbank-Metadatenfragment liegen im kuratierten Fehlerkorpus 20261120.
File diff suppressed because it is too large. Load diff
@@ -227,6 +227,9 @@ def model_view(context):
view['hypotheses'][selected]['legacy_notes']=copy.deepcopy(hypotheses[selected].get('notes',[]))
for field in ('previous_rejection','previous_rejection_details','database_query_failures'):
if field in context:view[field]=copy.deepcopy(context[field])
from .tool_guidance import database_access_view
access = database_access_view(context)
if access is not None:view['database_access'] = access
return consolidate_origins(view) if context.get('prompt_version') in {'investigation_project_v16','investigation_project_v17','investigation_project_v18'} else view
@@ -86,7 +86,7 @@ def build(context):
'known_schemas':schemas,
'evidence_catalog':view['evidence_catalog'],'archive_ids':view['archive_ids'],
'budget':view['budget'],
**{k:view[k] for k in ('shared_metadata','previous_rejection','previous_rejection_details','database_query_failures') if k in view}},
**{k:view[k] for k in ('shared_metadata','previous_rejection','previous_rejection_details','database_query_failures','database_access') if k in view}},
'output_schema':contract}
# Keep actual argument contracts in the stable prefix, not inferred from
# prose. No arbitrary SQL or shell is added by the lean protocol.
@@ -202,7 +202,7 @@ def project(request, context):
# Keep the separately validated output schema; describe the strict shape once.
view = {k: copy.deepcopy(inp[k]) for k in (
'hypothesis', 'alternatives', 'previous_result', 'checkpoint_intent',
'early_review', 'previous_rejection', 'previous_rejection_details','database_query_failures') if k in inp}
'early_review', 'previous_rejection', 'previous_rejection_details','database_query_failures','database_access') if k in inp}
view['case'] = inp.get('case', {})
if 'hypothesis' not in view:
hid = context['selected_hypothesis']
@@ -254,6 +254,9 @@ def project(request, context):
if key in old: body[key] = old[key]
result['messages'] = [{'role': 'system', 'content': instructions_v2() if v2(context) else INSTRUCTIONS},
{'role': 'user', 'content': compact(body)}]
if view.get('database_access'):
from .tool_guidance import DATABASE_ACCESS_INSTRUCTIONS
result['messages'][0]['content'] += DATABASE_ACCESS_INSTRUCTIONS
if context.get('research_guidance_version') == 1:
from .research_guidance import INSTRUCTIONS as research_instructions
result['messages'][0]['content'] += research_instructions
@@ -322,6 +322,8 @@ class Investigator:
if raw_size > 4000 or len(json_bytes(session.get('turns', []))) > 2000:
session['checkpoint'] = True
session['intent'] = 'review'
if context.get('tool_schema',{}).get('x-project-bindings',{}).get('database',{}).get('database'):
context['database_access_version'] = 1
with PackageReader(self._latest(state['case_id'],state['package_id']),self.store.limits) as reader:
from .tool_guidance import database_failure_history
failures = database_failure_history(reader,state,context,self._read)
@@ -473,6 +475,8 @@ class Investigator:
context['previous_rejection_details'] = detail
active['context_ref'] = active['context_ref'].removesuffix('.json') + '-database-feedback-v1.json'
state,_ = self._save(state,context=context)
state,context = self._upgrade_database_context(state,context,operation)
active = state['active']
if context.get('response_repair'):
from viano_bug_analysis.llm.response_recovery import admission_reason
plan=context['response_repair']
@@ -712,6 +716,20 @@ class Investigator:
if operation not in context["budget_policy"]["action_costs"]:raise InvestigationError("INVESTIGATION_TEST_COST")
budget_apply(projected,{"operation":"reserve","hypothesis_id":hid,"action_id":self._action_id(state),"action":operation},context["budget_policy"])
def _upgrade_database_context(self,state,context,operation):
if (context.get('database_access_version') != 1 and not context.get('response_repair')
and context.get('tool_schema',{}).get('x-project-bindings',{}).get('database',{}).get('database')):
request_ref = f"llm/operations/{key(str(state['analysis_revision']) + ':' + operation)}/request.json"
with PackageReader(self._latest(state['case_id'],state['package_id']),self.store.limits) as reader:
if request_ref not in reader.files:
from .tool_guidance import database_failure_history
context['database_access_version'] = 1
failures = database_failure_history(reader,state,context,self._read)
if failures:context['database_query_failures'] = failures
state['active']['context_ref'] = state['active']['context_ref'].removesuffix('.json') + '-database-access-v1.json'
state,_ = self._save(state,context=context)
return state,context
@staticmethod
def _action_id(state):
active = state['active']
@@ -3,6 +3,42 @@ import copy
import re
DATABASE_ACCESS_INSTRUCTIONS = ('\nDatabase access: unqualified tables use only database_access.default_database. '
'For another configured database use database.table explicitly. previously_read_tables are scoped past '
'lookups, not a guarantee of current availability or a complete table inventory. Discover unknown tables '
'with database.tables, then database.schema; never silently substitute another database. '
'database_query_failures are earlier metadata failures across hypotheses, not causal evidence; '
'do not repeat those pairs without new catalog/schema confirmation.\n')
def database_access_view(context):
"""Names and exact past lookup references only; no credentials or row data."""
if context.get('database_access_version') != 1:return None
binding = context.get('tool_schema',{}).get('x-project-bindings',{}).get('database',{})
default = binding.get('database')
if not isinstance(default,str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,63}',default):return None
allowlists = {default:binding.get('tables',[]), **binding.get('additional_databases',{})}
databases = [default] + sorted(n for n in allowlists if n != default)
known = {}
from viano_bug_analysis.tools.sql_database import is_table_reference
for eid, entry in sorted(context.get('evidence',{}).items(),reverse=True):
for item in entry.get('content',{}).get('items',[]):
origin, query = item.get('origin',{}), item.get('query',{})
if not isinstance(origin,dict) or not isinstance(query,dict):continue
table = query.get('table')
if (origin.get('kind')!='mariadb' or origin.get('snapshot_id')!=binding.get('snapshot_id')
or origin.get('database')!=default or query.get('kind') not in {'database.schema','database.rows','database.count'}
or not is_table_reference(table) or not isinstance(item.get('result'),dict)):continue
database, name = table.split('.') if '.' in table else (default,table)
if origin.get('selected_database',database)!=database or origin.get('selected_table',name)!=name:continue
allowed = allowlists.get(database,[])
if name not in allowed and list(allowed)!=['*']:continue
qualified = database+'.'+name
if qualified not in known and len(known)<12:known[qualified] = {'table':qualified,'evidence_id':eid}
return {'default_database':default,'databases':databases[:16],
'omitted_databases':max(0,len(databases)-16),'previously_read_tables':list(known.values())}
def database_failure_history(reader, state, context, read_call):
"""Bounded operational hints across hypotheses, never causal evidence."""
refs = {n['llm_ref'] for h in state['hypotheses'].values() for n in h.get('notes', [])
@@ -91,7 +127,7 @@ def instructions(context):
bindings = context['tool_schema'].get('x-project-bindings', {})
text = (HEADER + 'Use operation="project.query" for these arguments. Prefer a matching larger tool '
'before separate schema/search/read calls; primitive tools remain available.\n')
if (bindings.get('database') or {}).get('additional_databases'):
if (bindings.get('database') or {}).get('additional_databases') and context.get('database_access_version') != 1:
text+=('Database table references use configured_database.table. Unqualified tables use only '
'the default database. Use database.tables to discover allowed tables across configured '
'databases; never substitute an equally named table from another database.\n')
@@ -116,9 +152,11 @@ def instructions(context):
'Replace the illustrative column/value with schema-verified, case-grounded inputs. '
'Never emit [] or flatten an object into ["column",...,"operator",...,"value",...]. '
'Input compression encodings do not apply to output: return ordinary JSON objects.\n')
if context.get('database_query_failures'):
if context.get('database_query_failures') and context.get('database_access_version') != 1:
text += ('database_query_failures lists earlier failed metadata lookups across hypotheses, not causal evidence. '
'Do not reuse those database/table pairs without new catalog/schema evidence that they are available. '
'Use database.tables to discover permitted alternatives, then inspect their actual schema, or use source/package data. '
'A failed lookup is not proof that the underlying bug has a missing implementation.\n')
if database_access_view(context) is not None:
text += DATABASE_ACCESS_INSTRUCTIONS
return text
@@ -945,6 +945,9 @@
}
}
}
},
"database_access_version": {
"const": 1
}
}
}
@@ -0,0 +1,3 @@
# BUG-000023: unqualified Hotfix table
Generation 187. One explicit operator approval was applied. The next answer changed item_template to item_sparse but omitted its database qualifier. Unqualified tables resolve only to cata_world; the known successful schema query was cata_hotfixes.item_sparse (E000009, H3). The bounded user input omitted the configured default/additional database mapping and table qualification rule. Its frozen correction context predated shared database_query_failures; those hints appeared only in the new rejection context. The new reply was therefore correctly rejected and the exhausted counter immediately blocked again. This is not a connection outage, and it does not prove item_sparse is absent from all configured databases. Do not silently substitute another database. Restore compact database-access metadata and migrate pending contexts only before freezing their next request.
@@ -0,0 +1,81 @@
{
"database_binding": {
"additional_databases": {
"cata_characters": [
"*"
],
"cata_hotfixes": [
"*"
]
},
"database": "cata_world",
"kind": "mariadb",
"snapshot_id": "vps-live",
"table_reference": "database.table; unqualified tables use the default database only",
"tables": [
"*"
],
"time_scope": "configured_snapshot_not_current_production"
},
"past_schema_lookup": {
"record": {
"id": "E000009",
"hypothesis_id": "H3",
"action_id": "INV-1-H3-4"
},
"content": {
"coverage": "schema_only",
"items": [
{
"origin": {
"additional_databases": {
"cata_characters": [
"*"
],
"cata_hotfixes": [
"*"
]
},
"database": "cata_world",
"kind": "mariadb",
"selected_database": "cata_hotfixes",
"selected_table": "item_sparse",
"snapshot_id": "vps-live",
"table_reference": "database.table; unqualified tables use the default database only",
"tables": [
"*"
],
"time_scope": "configured_snapshot_not_current_production"
},
"query": {
"kind": "database.schema",
"table": "cata_hotfixes.item_sparse"
},
"result": {
"coverage": "schema_only",
"truncated": true,
"items": [
{
"table": "cata_hotfixes.item_sparse",
"columns": [
{
"COLUMN_KEY": "PRI",
"COLUMN_NAME": "ID",
"COLUMN_TYPE": "int(10) unsigned",
"IS_NULLABLE": "NO"
},
{
"COLUMN_KEY": "",
"COLUMN_NAME": "Quality",
"COLUMN_TYPE": "int(10) unsigned",
"IS_NULLABLE": "NO"
}
]
}
]
}
}
]
}
}
}
@@ -0,0 +1,15 @@
{
"assessment": {
"reason": "Search for 60678 in repository yielded unrelated SQL matches and broadcast text. Need to check item table schema in the database to inspect item 60678's spells.",
"semantic_score": 25
},
"next": {
"arguments": {
"kind": "database.schema",
"table": "item_sparse"
},
"kind": "tool",
"operation": "project.query"
},
"observation": "Item 60678 search in git returned unrelated matches. Checking item_sparse schema to look up spell IDs attached to item 60678."
}
+135
View File
@@ -0,0 +1,135 @@
import copy
import json
from pathlib import Path
import pytest
from test_bounded_contract_v2 import context as bounded_context
from test_case_builder import case_setup
from test_investigation_tools import tool_case
from viano_bug_analysis.analysis.investigation_prompt import build_prompt
from viano_bug_analysis.analysis.tool_guidance import database_access_view
from viano_bug_analysis.llm.investigation_size import characters
ROOT=Path(__file__).parent/'fixtures/llm_rejections/20261120/bug23-unqualified-hotfix-table'
def recorded_context():
fixture=json.loads((ROOT/'database-context.json').read_text(encoding='utf-8'))
c=bounded_context()
c['database_access_version']=1
c['tool_schema']['x-project-bindings']['database']=fixture['database_binding']
c['evidence']['E000009']=fixture['past_schema_lookup']
c['database_query_failures']=[{'database':'cata_world','table':'item_template'},
{'database':'cata_world','table':'item_sparse'}]
return c
@pytest.mark.parametrize('checkpoint',[False,True])
def test_real_bug23_database_mapping_reaches_final_bounded_wire_request(checkpoint):
c=recorded_context();c['lean_session']['checkpoint']=checkpoint
before=copy.deepcopy(c)
request=build_prompt(c);body=json.loads(request['messages'][1]['content'])
access=body['input']['database_access']
assert access['default_database']=='cata_world'
assert set(access['databases'])=={'cata_world','cata_hotfixes','cata_characters'}
assert {'table':'cata_hotfixes.item_sparse','evidence_id':'E000009'} in access['previously_read_tables']
assert body['input']['database_query_failures']==c['database_query_failures']
assert 'unqualified tables use only database_access.default_database' in request['messages'][0]['content']
assert 'not causal evidence' in request['messages'][0]['content']
assert characters(request)<=20000 and c==before
assert 'password' not in json.dumps(access).lower()
c.pop('database_access_version')
legacy=build_prompt(c)
assert 'database_access' not in json.loads(legacy['messages'][1]['content'])['input']
assert 'database_access.default_database' not in legacy['messages'][0]['content']
@pytest.mark.parametrize('change',[
lambda i:i['origin'].update(snapshot_id='other-snapshot'),
lambda i:i['origin'].update(selected_database='cata_world'),
lambda i:i['query'].update(table='cata_auth.item_sparse'),
lambda i:i['query'].update(table='cata_hotfixes.item_sparse;DROP TABLE x'),
])
def test_known_lookup_hints_keep_snapshot_identity_and_allowed_database_scope(change):
c=recorded_context();item=c['evidence']['E000009']['content']['items'][0]
change(item)
assert not database_access_view(c)['previously_read_tables']
def test_resume_upgrades_only_pending_context_and_preserves_old_request_bytes(tool_case):
from test_investigator import LoopAdapter,run,state,CASE
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,PackageValidator
class Database(FakeDB):
def binding(self):return {'kind':'mariadb','snapshot_id':'snapshot-A','database':'world',
'tables':['*'],'additional_databases':{'hotfix':['*']}}
def validate(self,args):
if args.get('table')=='missing':raise ToolError('PROJECT_DATABASE_TABLE_UNKNOWN')
with PackageReader(tool_case[1]) as reader:
service=ProjectResearch(reader.manifest['project'],database=Database())
calls=[]
def change(reply,c):
if calls:
assert c['database_access']['default_database']=='world'
assert c['database_query_failures']==[{'database':'world','table':'missing'}]
reply['next']={'kind':'tool','operation':'project.query','arguments':rows(table='missing' if not calls else 'switches')}
calls.append(1)
worker=Investigator(tool_case[0],gateway(LoopAdapter(change)),router=InvestigationToolRouter(project_research=service))
original=worker._context
def legacy(*args):
c=original(*args);c.pop('database_access_version',None);return c
worker._context=legacy
first=run(worker,steps=1)
with PackageReader(first.package) as reader:
preserved={n:reader.read_bytes(n) for n in reader.files if n!='manifest.json'}
worker._context=original
second=run(worker,steps=1)
assert state(second)['active'] is None
with PackageReader(second.package) as reader:
for n,raw in preserved.items():assert reader.read_bytes(n)==raw
contexts=[n for n in reader.files if n.endswith('-database-access-v1.json')]
assert len(contexts)==1
assert json.loads(reader.read_bytes(contexts[0]))['database_access_version']==1
assert PackageValidator().validate(second.package).valid
def test_already_frozen_request_is_replayed_without_database_metadata_upgrade(tool_case,monkeypatch):
from test_investigator import LoopAdapter,run,CASE
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
from viano_bug_analysis.tools.project_query import ProjectResearch
from viano_bug_analysis.package import PackageReader
class Database(FakeDB):
def binding(self):return {'kind':'mariadb','snapshot_id':'snapshot-A','database':'world','tables':['*']}
with PackageReader(tool_case[1]) as reader:
service=ProjectResearch(reader.manifest['project'],database=Database())
adapter=LoopAdapter(lambda r,c:r.update(next={'kind':'tool','operation':'project.query','arguments':rows()}))
worker=Investigator(tool_case[0],gateway(adapter),router=InvestigationToolRouter(project_research=service))
original_context=worker._context
def legacy(*args):
c=original_context(*args);c.pop('database_access_version',None);return c
monkeypatch.setattr(worker,'_context',legacy)
upgrade=worker._upgrade_database_context
monkeypatch.setattr(worker,'_upgrade_database_context',lambda state,context,operation:(state,context))
class Crash(BaseException):pass
original_validate=worker._validate_decision
def crash(*args):raise Crash()
monkeypatch.setattr(worker,'_validate_decision',crash)
with pytest.raises(Crash):run(worker,steps=1)
with PackageReader(tool_case[0].latest(*CASE)) as reader:
originals={n:reader.read_bytes(n) for n in reader.files if n!='manifest.json'}
monkeypatch.setattr(worker,'_context',original_context)
monkeypatch.setattr(worker,'_upgrade_database_context',upgrade)
monkeypatch.setattr(worker,'_validate_decision',original_validate)
result=run(worker,steps=1)
assert len(adapter.contexts)==1
with PackageReader(result.package) as reader:
for n,raw in originals.items():assert reader.read_bytes(n)==raw
assert not [n for n in reader.files if n.endswith('-database-access-v1.json')]