Skip to content

Commit 4ae4a45

Browse files
fix(evals): bound JSON depth and capture execution provenance
1 parent 1ce349d commit 4ae4a45

10 files changed

Lines changed: 379 additions & 29 deletions

‎evals/incoming-context/README.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Local model inference additionally needs the Apple Silicon `mlx-decision` runtim
1717

1818
## What the selector sees
1919

20-
One scoring request is one contract. `REQUEST_VERSION` (`incoming-state-v2:keep-prompt-v2`) names the state and prompt. Comparisons also match the causal-context, selection-policy and protection versions. The current eligibility rules are `causal-context-v4`, `selection-evidence-v4` and `json-span-v3+evidence+source-v2`; results with older or missing identities are not current measurements. `rerender`/`sweep` preserve the input identities and never stamp newer ones.
20+
One scoring request is one contract. `REQUEST_VERSION` (`incoming-state-v2:keep-prompt-v2`) names the state and prompt. Comparisons also match the causal-context, selection-policy and protection versions. The current eligibility rules are `causal-context-v4`, `selection-evidence-v4` and `json-span-v4-depth64+evidence+source-v2`; results with older or missing identities are not current measurements. `rerender`/`sweep` preserve the input identities and never stamp newer ones.
2121

2222
- `state.recent_user_context` — every sourced human instruction strictly before the result, oldest first, verbatim. `causal_context` collects `message` records with role `user`, skips `assistant` and tool records entirely, and refuses harness envelopes, developer-role messages, opaque content and unknown wrappers instead of promoting them to instructions. Compacted history contributes only retained, client-authored user inputs that carry verified provenance; otherwise the case abstains for an ambiguous goal. Nothing is summarized. Generated handoff headers and historical replay wrappers make the goal ambiguous: omitted history cannot be replaced by generated text presented as a human instruction. Such cases retain their original output without scoring.
2323
- `state.tool_call` — the resolved originating call: name plus full command or arguments body, never truncated.
@@ -93,3 +93,27 @@ Frozen context, calls and request grouping are verified
9393
before dispatch; the request cap is enforced before each call. Local MLX calls
9494
have no enforced wall-clock timeout. Model-loading failures are recorded as
9595
rejections, not omitted from the result.
96+
97+
JSON admission uses one iterative structural inspector with a maximum container depth of
98+
64 (the root counts as one). Strings and escaped delimiters do not add depth. Over-depth
99+
output stays whole; envelope adapters abstain, and source records and call arguments are
100+
unavailable rather than decoded. Defensive decoder catches remain. The protection version
101+
owns this eligibility change; causal extraction, source matching, prompt and frozen-input
102+
formats retain their existing versions. Changed leaf or request identities require refreezing.
103+
Historical measurements in RESULTS have not been rerun under this policy.
104+
105+
Complete-edit runs and block receipts carry `execution-v1` evidence owned by that invocation.
106+
Real dispatch records the coupled loaded model/configuration/receipt, including on cache
107+
hits. A load alone does not attest execution. Injected scorers, patched loaders, preflight
108+
abstentions, failed loads and unattested HTTP responses cannot borrow a cached receipt.
109+
Receipts snapshot requested controls, actual applied/refused load options, runtime versions,
110+
machine/Python metadata and dispatch/failure counts. They are compact evidence, not a request
111+
journal; source paths and model labels are not weight-content hashes. Complete-edit runs do
112+
not warm up. Block runs report their requested warmup and measured warmup duration separately.
113+
114+
`compare-edits` preserves each execution receipt and reports `comparable`,
115+
`different-controls`, or `unverified`, with differing controls or missing evidence stated.
116+
Missing/unknown runtime evidence, failures and historical receipts remain descriptive data,
117+
not controlled measurements. Inconsistent requested/loaded sources or multiple runtime
118+
configurations are rejected. Machine differences qualify timing comparisons. Model identities
119+
are expected comparison dimensions, while load controls and runtime versions must match.

‎evals/incoming-context/causal_context.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@
100100
import re
101101
from dataclasses import dataclass
102102

103+
from json_bounds import exceeds_depth
104+
103105
AVAILABLE = 'available'
104106
MISSING = 'missing'
105107
AMBIGUOUS = 'ambiguous'
@@ -294,8 +296,10 @@ def _call_body(payload):
294296

295297
def _decoded_args(body):
296298
try:
299+
if isinstance(body, str) and exceeds_depth(body, len(body) - len(body.lstrip())):
300+
return None
297301
value = json.loads(body)
298-
except (TypeError, ValueError):
302+
except (TypeError, ValueError, RecursionError):
299303
return None
300304
return value if isinstance(value, dict) else None
301305

‎evals/incoming-context/evaluate.py‎

Lines changed: 144 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
import tiktoken
2121

22+
from json_bounds import exceeds_depth
23+
2224
import causal_context as causal
2325
from incoming import apply_incoming, replace_leaf, text_leaves
2426

@@ -30,7 +32,7 @@
3032
# decisions. Re-thresholding may only reuse a result that carries this identity; a result
3133
# recorded under another policy is stale and keeps everything, so old scores can never
3234
# silently inherit protection rules they were not measured with.
33-
PROTECTION_VERSION = 'json-span-v3+evidence+source-v2'
35+
PROTECTION_VERSION = 'json-span-v4-depth64+evidence+source-v2'
3436
# Request identity. Any frozen result without exactly REQUEST_VERSION in its `request_version`
3537
# field was measured against a different state, prompt or batching contract and must not be
3638
# compared with, or reported as, this revision.
@@ -182,7 +184,10 @@ def unique_fields(pairs):
182184

183185
for line_no, line in enumerate(raw_lines, 1):
184186
try:
185-
record = json.loads(line.decode('utf-8'), object_pairs_hook=unique_fields)
187+
text = line.decode('utf-8')
188+
if exceeds_depth(text, len(text) - len(text.lstrip())):
189+
raise ValueError('Source record exceeds JSON depth limit')
190+
record = json.loads(text, object_pairs_hook=unique_fields)
186191
except (ValueError, RecursionError):
187192
record = None
188193
row = dict(record) if isinstance(record, dict) else {}
@@ -410,8 +415,10 @@ def _symbol_terms(text, terms, seen, source, line):
410415
def _param_pairs(body):
411416
pairs = []
412417
try:
418+
if isinstance(body, str) and exceeds_depth(body, len(body) - len(body.lstrip())):
419+
return pairs
413420
value = json.loads(body)
414-
except (TypeError, ValueError):
421+
except (TypeError, ValueError, RecursionError):
415422
value = None
416423

417424
def walk(node, depth=0):
@@ -595,6 +602,8 @@ def _json_scan(raw):
595602
after_value = after_value and raw[i].isspace()
596603
i += 1
597604
continue
605+
if exceeds_depth(raw, i):
606+
return [], [0]
598607
try:
599608
value, end = _DECODER.raw_decode(raw, i)
600609
except RecursionError:
@@ -732,6 +741,8 @@ def unique(pairs):
732741
out[key] = value
733742
return out
734743
try:
744+
if isinstance(body, str) and exceeds_depth(body, len(body) - len(body.lstrip())):
745+
return None
735746
value = json.loads(body, object_pairs_hook=unique)
736747
except (TypeError, ValueError, RecursionError):
737748
return None
@@ -1073,6 +1084,8 @@ def pairs(items):
10731084
return obj
10741085

10751086
try:
1087+
if exceeds_depth(value, len(value) - len(value.lstrip())):
1088+
return 'json_nesting_not_in_state'
10761089
obj = json.loads(value, object_pairs_hook=pairs)
10771090
except RecursionError:
10781091
return 'json_nesting_not_in_state'
@@ -1271,6 +1284,7 @@ def http_score(a, payload):
12711284
remaining = _remaining_deadline(a)
12721285
timeout = a.timeout if remaining is None else min(a.timeout, remaining)
12731286
request_sent = True
1287+
_record_dispatch(a)
12741288
with _local_http_open(req, timeout=timeout) as response:
12751289
# The HTTP server exposes truncation in a header, not in the Jev response body.
12761290
# Scores from a shortened state cannot authorize removing any source content.
@@ -1289,13 +1303,108 @@ def http_score(a, payload):
12891303
return probs, elapsed, received.get('usage', {})
12901304

12911305

1292-
_MODEL = None
1293-
_MODEL_RECEIPT = {}
1294-
_MODEL_CONFIG = None
1306+
_LOADED = None
1307+
EXECUTION_VERSION = 'execution-v1'
1308+
1309+
1310+
def execution_args(a):
1311+
local = copy.copy(a)
1312+
local._execution = {
1313+
'version': EXECUTION_VERSION, 'protection_version': PROTECTION_VERSION,
1314+
'machine': machine(),
1315+
'requested': {key: getattr(a, key, None) for key in (
1316+
'backend', 'model', 'model_path', 'max_tokens', 'timeout', 'deadline_ms',
1317+
'prefix_cache_gb', 'max_input_tokens', 'noul_floor', 'warmup',
1318+
'request_budget', 'request_cap', 'illustrative', 'threshold',
1319+
'batch_tokens', 'batch_questions')},
1320+
'runtime': None, 'dispatches': 0, 'unattested_dispatches': 0,
1321+
'failed_requests': 0, 'mixed_runtime': False,
1322+
}
1323+
local._loaded_evidence = None
1324+
return local
1325+
1326+
1327+
def execution_receipt(a):
1328+
receipt = copy.deepcopy(getattr(a, '_execution', None))
1329+
if receipt is None:
1330+
return None
1331+
receipt['status'] = ('not-executed' if not receipt['dispatches'] else
1332+
'unattested' if receipt['unattested_dispatches'] or
1333+
receipt['failed_requests'] or receipt['mixed_runtime'] else 'attested')
1334+
return receipt
1335+
1336+
1337+
def _record_dispatch(a, runtime=None):
1338+
evidence = getattr(a, '_execution', None)
1339+
if evidence is None:
1340+
return
1341+
evidence['dispatches'] += 1
1342+
if runtime is None:
1343+
evidence['unattested_dispatches'] += 1
1344+
elif evidence['runtime'] is None:
1345+
evidence['runtime'] = copy.deepcopy(runtime)
1346+
elif evidence['runtime'] != runtime:
1347+
evidence['mixed_runtime'] = True
1348+
1349+
1350+
def compare_execution(runs):
1351+
reasons, controls, machines = [], [], []
1352+
for run in runs:
1353+
receipt = run.get('execution')
1354+
if not isinstance(receipt, dict) or receipt.get('version') != EXECUTION_VERSION:
1355+
reasons.append('missing or incompatible execution receipt')
1356+
continue
1357+
requested, runtime = receipt.get('requested'), receipt.get('runtime')
1358+
if not isinstance(requested, dict):
1359+
reasons.append('invalid requested controls')
1360+
continue
1361+
if any(requested.get(k) != run.get(k) for k in ('model', 'model_path', 'backend')):
1362+
raise ValueError('execution requested identity differs from run')
1363+
if runtime is not None:
1364+
if not isinstance(runtime, dict) or runtime.get('source') != (
1365+
requested.get('model_path') or requested.get('model')):
1366+
raise ValueError('execution runtime source differs from requested source')
1367+
if receipt.get('protection_version') != PROTECTION_VERSION:
1368+
reasons.append('missing or incompatible protection policy')
1369+
if receipt.get('mixed_runtime'):
1370+
raise ValueError('multiple runtime configurations in one run')
1371+
if (receipt.get('status') != 'attested' or not runtime or
1372+
not isinstance(receipt.get('dispatches'), int) or receipt['dispatches'] <= 0 or
1373+
receipt.get('unattested_dispatches') != 0 or receipt.get('failed_requests') != 0):
1374+
reasons.append('execution is absent, failed or unattested')
1375+
continue
1376+
if requested.get('backend') != 'mlx' or runtime.get('backend') != 'mlx-decision':
1377+
reasons.append('unattested transport')
1378+
if receipt['dispatches'] != run.get('requests'):
1379+
reasons.append('dispatch count differs from recorded requests')
1380+
required = ('runtime_version', 'mlx_version', 'info', 'load_options_requested',
1381+
'load_options_applied', 'load_options_refused')
1382+
if (not isinstance(receipt.get('machine'), dict) or not run.get('tokenizer')
1383+
or any(k not in requested for k in ('max_tokens', 'timeout', 'deadline_ms',
1384+
'warmup', 'request_budget', 'request_cap', 'illustrative'))):
1385+
reasons.append('execution controls are incomplete')
1386+
if any(k not in runtime or runtime[k] in (None, 'unknown') for k in required):
1387+
reasons.append('runtime controls are incomplete')
1388+
control = {'requested.' + k: v for k, v in requested.items()
1389+
if k not in ('model', 'model_path')}
1390+
control.update({'runtime.' + k: runtime.get(k) for k in required if k != 'info'})
1391+
control.update({'protection_version': receipt.get('protection_version'),
1392+
'tokenizer': run.get('tokenizer')})
1393+
controls.append(control)
1394+
machines.append(receipt.get('machine'))
1395+
differences = sorted({key for control in controls[1:] for key in
1396+
set(control) | set(controls[0])
1397+
if control.get(key) != controls[0].get(key)})
1398+
return {'status': 'unverified' if reasons else
1399+
'different-controls' if differences else 'comparable',
1400+
'reasons': sorted(set(reasons)), 'differences': differences,
1401+
'timing_comparable': not reasons and not differences and
1402+
all(m == machines[0] for m in machines)}
12951403

12961404

12971405
def load_mlx(a):
1298-
global _MODEL, _MODEL_RECEIPT, _MODEL_CONFIG
1406+
global _LOADED
1407+
a._loaded_evidence = None
12991408
source_arg = a.model_path or a.model
13001409
wanted = {}
13011410
if a.prefix_cache_gb is not None:
@@ -1305,8 +1414,9 @@ def load_mlx(a):
13051414
if a.noul_floor is not None:
13061415
wanted['noul_floor'] = a.noul_floor
13071416
configuration = (source_arg, tuple(sorted(wanted.items())))
1308-
if _MODEL is not None and _MODEL_CONFIG == configuration:
1309-
return _MODEL
1417+
if _LOADED is not None and _LOADED[1] == configuration:
1418+
a._loaded_evidence = _LOADED
1419+
return _LOADED[0]
13101420
import importlib.metadata
13111421
import mlx_decision
13121422
opts = dict(wanted)
@@ -1324,17 +1434,17 @@ def load_mlx(a):
13241434
refused.append(key)
13251435
receipt = {'backend': 'mlx-decision', 'source': source_arg,
13261436
'runtime_version': importlib.metadata.version('mlx-decision'),
1327-
'info': model.info(), 'load_options_applied': opts,
1437+
'info': model.info(), 'load_options_requested': wanted,
1438+
'mlx_version': 'unknown', 'load_options_applied': opts,
13281439
'load_options_refused': sorted(set(refused))}
13291440
try:
13301441
import mlx.core as mx
13311442
receipt['mlx_version'] = getattr(mx, '__version__', 'unknown')
13321443
except Exception:
13331444
pass
1334-
_MODEL = model
1335-
_MODEL_CONFIG = configuration
1336-
_MODEL_RECEIPT = receipt
1337-
return _MODEL
1445+
_LOADED = (model, configuration, copy.deepcopy(receipt))
1446+
a._loaded_evidence = _LOADED
1447+
return model
13381448

13391449

13401450
def warmup(a):
@@ -1358,9 +1468,12 @@ def mlx_score(a, payload):
13581468
try:
13591469
oversize(a, payload)
13601470
_remaining_deadline(a)
1471+
a._loaded_evidence = None
13611472
model = load_mlx(a)
1473+
loaded = a._loaded_evidence
13621474
_remaining_deadline(a)
13631475
request_sent = True
1476+
_record_dispatch(a, loaded[2] if loaded is not None and loaded[0] is model else None)
13641477
result = model.decide_request(payload)
13651478
elapsed = (time.perf_counter() - start) * 1000
13661479
if getattr(result, 'truncated', False):
@@ -1383,7 +1496,12 @@ def mlx_score(a, payload):
13831496

13841497

13851498
def score_request(a, payload):
1386-
return http_score(a, payload) if a.backend == 'http' else mlx_score(a, payload)
1499+
try:
1500+
return http_score(a, payload) if a.backend == 'http' else mlx_score(a, payload)
1501+
except Exception:
1502+
if getattr(a, '_execution', None) is not None:
1503+
a._execution['failed_requests'] += 1
1504+
raise
13871505

13881506

13891507
def prefix_bytes(c, keep=400):
@@ -1924,8 +2042,10 @@ def category(decision):
19242042

19252043
def receipts_for(a):
19262044
expected = request_version_for(a)
1927-
receipt = {'machine': machine(),
1928-
'runtime': _MODEL_RECEIPT if a.backend == 'mlx' and a.policy == 'decision' else None,
2045+
execution = execution_receipt(a)
2046+
receipt = {'machine': execution['machine'] if execution else machine(),
2047+
'runtime': (execution or {}).get('runtime'),
2048+
'execution': execution,
19292049
'tokenizer': 'o200k_base comparison proxy; not provider billing tokens',
19302050
'chunker': CHUNKER,
19312051
# Identity of the exact request contract, so a frozen result cannot pass as this one.
@@ -1946,21 +2066,23 @@ def receipts_for(a):
19462066

19472067

19482068
def run(a):
2069+
a = execution_args(a)
19492070
cases = json.loads(Path(a.cases).read_text())['cases']
19502071
results = []
19512072
report = {'policy': a.policy, 'threshold': a.threshold, 'quality_status': 'no cases'}
19522073
receipts = receipts_for(a)
1953-
if a.policy == 'decision' and a.backend == 'mlx':
1954-
load_mlx(a)
1955-
receipts = receipts_for(a)
1956-
if a.warmup:
1957-
receipts['warmup_ms'] = round(warmup(a), 1)
2074+
warmup_ms = None
2075+
if a.policy == 'decision' and a.backend == 'mlx' and a.warmup:
2076+
warmup_ms = round(warmup(a), 1)
19582077
for c in cases:
19592078
if a.split != 'all' and c['split'] != a.split:
19602079
continue
19612080
if len(results) >= a.limit:
19622081
break
19632082
results.append(score_case(a, c))
2083+
receipts = receipts_for(a)
2084+
if warmup_ms is not None:
2085+
receipts['warmup_ms'] = warmup_ms
19642086
report = build_report(a, results, receipts)
19652087
# Persist completed observations so a local server interruption does not lose measurements.
19662088
Path(a.out).write_text(json.dumps(report, indent=2))

‎evals/incoming-context/incoming.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import json
55
import re
66

7+
from json_bounds import exceeds_depth
8+
79

810
_JSON_WS = re.compile(r'[ \t\r\n]*')
911

@@ -61,6 +63,9 @@ def apply_incoming(prefix: bytes, incoming: dict, replacement_output):
6163
def text_leaves(value):
6264
"""Locate strings, including output inside an incoming JSON tool envelope."""
6365
if isinstance(value, str):
66+
start = len(value) - len(value.lstrip(' \t\r\n'))
67+
if start < len(value) and value[start] in '[{' and exceeds_depth(value, start):
68+
return [([], value)]
6469
try:
6570
obj = json.loads(value)
6671
except (ValueError, TypeError, RecursionError):
@@ -87,6 +92,9 @@ def replace_leaf(value, path, replacement):
8792
selected = copy.deepcopy(value)
8893
key, *rest = path
8994
if key == 'json':
95+
start = len(value) - len(value.lstrip(' \t\r\n'))
96+
if start < len(value) and value[start] in '[{' and exceeds_depth(value, start):
97+
raise ValueError('JSON nesting exceeds limit')
9098
obj = json.loads(value)
9199
if rest != ['output'] or not isinstance(obj, dict) or not isinstance(obj.get('output'), str):
92100
raise ValueError('Only the text output of a JSON tool envelope may be changed')

0 commit comments

Comments
 (0)