Files
reverse-engineering-anything/tests/support/analysis-efficiency/catalog-eval.py
T
morluto 5c53bcaed8 feat(mcp)!: retire the full schema profiles and declare schema facts as typed annotations (#10693)
* test(mcp): check advertised schemas against a portable dialect in every profile

* fix(mcp): re-emit advertised patterns in a portable regex grammar

* fix(mcp): present discover_tools input through the selected profile

The hot-cold catalog registered discover_tools directly with the SDK, so
the default compact input profile still advertised its canonical schema,
including page-size defaults clients apply on their own (#5322). Route
every listed input schema, transport discovery included, through one
server-owned presentation, and pass the selected presentation to the
deferred server, which serves recorded tool schemas but not discovery.

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* fix(mcp): validate advertised dialect by selected profile

* fix(mcp): preserve schema widening through references

* feat(mcp): project compact input schemas into the portable advertised dialect

One projection (advertisedDialectProjection.ts) owns the compact input
advertisement: one type per node, items on every array, string literals
as enums, oneOf widened to anyOf, allOf merged, tuples as element unions,
exclusive bounds made inclusive, and every keyword outside the dialect
dropped. Each rewrite is exact or widening; server validation is
unchanged. The root description and sentences for dropped cross-field
constraints move to the tool description, which Codex and Zed keep.

The compact baseline falls to nullable values only (29), which the
dialect cannot express without narrowing an input. The gateway shape
repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second
dependentRequired-to-prose copy and the strict-gateway test denylist are
removed; the dialect checker gates the inline presentation instead.

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* docs: describe omitted output schemas as the default in README translations

* fix(mcp): select schemas in verification workflows

* fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns

* fix(mcp): keep projected schemas permissive

* fix(mcp): keep references valid when presentation widens their targets

* fix(mcp): keep a single union branch's closure scoped to its properties

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): keep an allOf member's tuple tail with its own positions

* fix(mcp): relax references into negations and conditionals presentation may remove

* refactor(contracts): declare root discriminators as typed schema annotations

* test(mcp): select the borrowed Evidence contract from its family

* fix(mcp): keep astral literals and dynamic references widening in every mode

* fix(mcp): omit astral literals and relax untracked references when presentation widens

* fix(mcp): select complete output schemas in every verifier transport

* fix(mcp): read reference pointers by schema position, not segment spelling

* fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse

* fix(mcp): keep reduced schemas open when their root admits names by pattern

* test(mcp): keep the reduced-schema pattern case outside the size-limited block

* fix(mcp): omit patterns whose classes name astral characters

* fix(mcp): decide union collapse and pointer protection from canonical branches

* docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes

* fix(mcp): keep prototype-named properties as own properties in the dialect projection

* test(mcp): select full output schemas in packet and signal schema checks

* test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe

* fix(mcp): protect references into unevaluated keywords lost evaluation removes

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings

* fix(mcp): protect references into literal siblings of relaxed draft-07 references

* feat(mcp): omit output schemas from tools/list by default (#10646)

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* fix(mcp): select schemas in verification workflows

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): select complete output schemas in every verifier transport

* test(mcp): select full output schemas in packet and signal schema checks

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): keep the Evidence union on described borrowed inputs (#10597)

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* test(mcp): select the borrowed Evidence contract from its family

* docs(mcp): admit baseline growth only for restored contract declarations

* fix(mcp): state reduced multi-type properties as typed branches, not type lists

The reduced fallback derived a property's types and emitted them as a type
list, which Gemini, Moonshot and Ark reject. A property whose canonical
schema is anyOf string and number therefore traded a typed union for a
rejected construct when the inline projection fell back. Emit one type, or
anyOf typed branches, so [T, null] becomes the dialect's nullable union.

* feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718)

* refactor(mcp): declare complete observations as a typed annotation applied only on the wire

* test(mcp): compare complete-observation declarations with their owning text

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725)

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords

* refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754)

* refactor(schema): declare pattern approximations and object output roots as typed annotations

* fix(schema): refuse pattern declarations JSON Schema cannot state

* test(schema): select guided_workflows from its contract family

* feat(mcp)!: retire the full input and output schema profiles (#10841)

* feat(mcp)!: retire the full input and output schema profiles

The compact input presentation is now the only advertised input schema, and
output schemas are either omitted (`off`, the default) or bounded
(`compact`). Catalog identity, the build-recorded digests and the recorded
startup catalog collapse to those presentations: two digest profiles instead
of six, one recorded catalog instead of two, and no input dialect baseline.

Tests and verifiers that validated replies against listed full output
schemas now validate against the canonical output contract, which REA
already enforces server-side; tests that asserted canonical input
restrictions read the canonical input schema instead of a full listing.

BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and
`REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup`
with a configuration error naming the setting. Remove the setting from the
client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact`
/ `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE`
still accepts `compact`. Server-side validation is unchanged.

* test(mcp): validate replies against canonical output contracts at every listed-schema reader

tools/list omits output schemas by default, so fixtures, verifiers and the
Android analysis runners that read a listed outputSchema now bind the
canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas
hand the SDK a definition carrying the canonical output schema, so the SDK
client and caller-supplied validators check every successful reply.

* test(mcp): resolve Android runners' output contracts from the selected repository

The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv.

* test(mcp): let Android runners compare revisions before the canonical output helper

A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports.

* fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment

The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes.

* test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held

tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions.

* test(mcp): record the advertised catalog summary without the retired full profiles

Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
2026-11-15 21:51:18 +08:00

284 lines
16 KiB
Python

"""Measure catalog loading in real Codex sessions, never by a bytes/token ratio."""
import argparse
import hashlib
import json
from pathlib import Path
import statistics
import subprocess
import sys
from codex_context import token_counts
from runtime_identity import runtime_fingerprint
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
MARKER = 'CATALOG_OK'
PROMPT = 'Reply with exactly ' + MARKER + '.\n'
TOKEN_KEYS = ('input_tokens', 'cached_input_tokens', 'output_tokens')
def write_json(path, value):
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')
def usage_counts(value):
counts = token_counts(value)
if not all(key in counts for key in TOKEN_KEYS) \
or counts['input_tokens'] == 0 or counts['cached_input_tokens'] > counts['input_tokens']:
raise ValueError('Missing or invalid observed token usage')
return counts
def assess_trial(directory, returncode, expected_runtime_digest):
"""Collect independent partial observations before grading the trial."""
result = {'status': 'invalid', 'directory': str(directory), 'exit_code': returncode}
issues = []
def observe(stage, work):
try:
return work()
except (OSError, ValueError, KeyError, TypeError) as error:
issues.append({'stage': stage, 'reason': str(error)})
return None
def require(condition, stage, reason):
if not condition:
issues.append({'stage': stage, 'reason': reason})
def read_object(name):
value = json.loads((directory / name).read_text())
if not isinstance(value, dict):
raise ValueError('Expected an object in ' + name)
return value
summary = observe('summary', lambda: read_object('summary.json'))
settings = observe('settings', lambda: read_object('trial-settings.json'))
cleanup = observe('cleanup', lambda: read_object('cleanup.json'))
if summary is not None:
result['summary'] = summary
result['runtime_fingerprint_sha256'] = summary.get('runtime_files_sha256_before')
require(returncode == 0 and summary.get('exit_code') == 0 and summary.get('timeout') is False,
'completion', 'Trial failed or timed out')
require(expected_runtime_digest is not None and summary.get('runtime_bytes_unchanged') is True
and summary.get('runtime_files_sha256_before') == expected_runtime_digest
and summary.get('runtime_files_sha256_after') == expected_runtime_digest,
'identity', 'Runtime does not match the pinned matrix fingerprint')
if settings is not None:
require(settings.get('catalog_load') is True and settings.get('workspace_isolated_from_runtime') is True,
'settings', 'Trial was not an isolated catalog-load measurement')
if cleanup is not None:
result['cleanup'] = cleanup
require(cleanup.get('profile_removed') is True, 'cleanup', 'Trial profile cleanup was not verified')
events = []
def read_events():
with (directory / 'events.jsonl').open() as lines:
for ordinal, line in enumerate(lines, 1):
if not line.strip():
continue
def parse():
value = json.loads(line)
if not isinstance(value, dict):
raise ValueError('Expected a JSONL event object')
return value
event = observe('events line ' + str(ordinal), parse)
if event is not None:
events.append(event)
observe('events', read_events)
turns = [event for event in events if event.get('type') == 'turn.completed']
require(len(turns) == 1, 'usage', 'Expected exactly one completed turn')
usage = observe('usage', lambda: usage_counts(turns[0].get('usage'))) if len(turns) == 1 else None
if usage is not None:
result['usage'] = usage
result['usage']['uncached_input_tokens'] = (
usage['input_tokens'] - usage['cached_input_tokens'])
for event in events:
require(event.get('type') not in ['error', 'turn.failed'], 'client',
'Client reported an error or failed turn: ' + str(event.get('message', event.get('error'))))
items = [event.get('item') for event in events if event.get('type') in ['item.started', 'item.completed']]
for item in items:
if isinstance(item, dict) and item.get('type') == 'error':
require(False, 'client', 'Client item error: ' + str(item.get('message')))
else:
require(isinstance(item, dict) and item.get('type') in ['agent_message', 'reasoning'],
'actions', 'A load-only trial performed a tool/action or an unknown item')
completed = [event.get('item') for event in events if event.get('type') == 'item.completed']
answers = [item.get('text') for item in completed if isinstance(item, dict) and item.get('type') == 'agent_message']
require(answers == [MARKER], 'answer', 'Load-only answer did not match the oracle')
def read_resources():
receipts = []
for line in directory.with_suffix('.log').read_text().splitlines():
try:
row = json.loads(line)
except ValueError:
continue
if isinstance(row, dict) and 'resource_scope' in row:
receipts.append(row)
if len(receipts) != 1:
raise ValueError('Missing or ambiguous resource receipt')
return receipts[0]
receipt = observe('resources', read_resources)
if receipt is not None:
result['resources'] = receipt
observation = receipt.get('payload_resource_observation')
require(isinstance(observation, dict) and receipt.get('abort') is None
and receipt.get('payload_resource_observation_verified') is True
and observation.get('payload_exit_code') == 0 and observation.get('payload_cleanup_verified') is True,
'resources', 'Resource stop, payload failure, or unverified process cleanup')
def metrics():
cpu = observation['cpu_stat']['usage_usec']
peak = observation['memory_peak_bytes']
if any(not isinstance(value, int) or isinstance(value, bool) or value < 0 for value in [cpu, peak]):
raise ValueError('Invalid resource counters')
return {'elapsed_seconds': receipt.get('elapsed_seconds'), 'cpu_seconds': cpu / 1_000_000,
'peak_process_family_bytes': peak,
'scope': 'Kernel cgroup counters at payload exit, including observer and file cache; not final scope counters.'}
measured = observe('resource metrics', metrics)
if measured is not None:
result['resource_metrics'] = measured
result['status'] = 'invalid' if issues else 'valid'
if issues:
result['issues'] = issues
result['reason'] = '; '.join(issue['reason'] for issue in issues)
return result
def comparison(rows, expected_runtime_digest):
"""Pair each catalog with its same-mode, same-repetition no-server control."""
controls = {(row['mode'], row['repetition']): row for row in rows if row['arm'] == 'none'}
pairs = []
for row in rows:
if row['arm'] == 'none':
continue
baseline = controls.get((row['mode'], row['repetition']))
valid = expected_runtime_digest is not None and row['status'] == 'valid' and baseline is not None and baseline['status'] == 'valid' \
and row.get('runtime_fingerprint_sha256') == expected_runtime_digest \
and baseline.get('runtime_fingerprint_sha256') == expected_runtime_digest
pairs.append({
'mode': row['mode'], 'arm': row['arm'], 'repetition': row['repetition'],
'status': 'valid' if valid else 'invalid',
'input_token_delta': row['usage']['input_tokens'] - baseline['usage']['input_tokens'] if valid else None,
})
groups = []
for mode, arm in sorted({(pair['mode'], pair['arm']) for pair in pairs}):
selected = [pair for pair in pairs if pair['mode'] == mode and pair['arm'] == arm]
deltas = [pair['input_token_delta'] for pair in selected if pair['status'] == 'valid']
groups.append({'mode': mode, 'arm': arm, 'valid_pairs': len(deltas), 'attempted_pairs': len(selected),
'median_input_token_delta': statistics.median(deltas) if deltas else None,
'min_input_token_delta': min(deltas) if deltas else None,
'max_input_token_delta': max(deltas) if deltas else None})
return {'pairs': pairs, 'groups': groups}
def catalog_receipt(root, selected):
source = root / 'dist' / 'mcp-catalog.json'
data = source.read_bytes()
catalog = json.loads(data)
names = {tool['name'] for tool in catalog['tools']}
if len(selected) != len(set(selected)) or not selected or not set(selected) <= names:
raise ValueError('Selected tools must be unique exact names in the built catalog')
size = lambda value: len(json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode())
return {'path': str(source), 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data),
'tool_count': len(names), 'selected_tools': selected,
'tools_json_bytes': size(catalog['tools']),
'description_json_bytes': sum(size(tool.get('description')) for tool in catalog['tools']),
'input_schema_json_bytes': sum(size(tool.get('inputSchema')) for tool in catalog['tools']),
'output_schema_json_bytes': sum(size(tool.get('outputSchema')) for tool in catalog['tools']),
'scope': 'Built server catalog, not submitted model context. Client filtering still discovers the server catalog.'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runtime-root', type=Path, default=ROOT)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--model', required=True, help='Explicit Codex model alias; never inferred from user config')
parser.add_argument('--reasoning', default='low')
parser.add_argument('--modes', nargs='+', choices=['direct', 'client-code'], default=['client-code'],
help='Default: supported host mode. direct disables the host as a diagnostic control.')
parser.add_argument('--selected-tools', nargs='+', default=['binary_session'])
parser.add_argument('--repetitions', type=int, default=1)
parser.add_argument('--timeout', type=int, default=180)
parser.add_argument('--codex', default='codex')
parser.add_argument('--plan', action='store_true', help='Show the matrix without invoking a model')
args = parser.parse_args()
if args.repetitions < 1 or args.timeout < 1 or len(set(args.modes)) != len(args.modes):
parser.error('Repetitions/timeout must be positive; modes must be unique')
root = args.runtime_root.resolve()
output = args.output.resolve()
runtime_files, pinned_digest = (None, None) if args.plan else runtime_fingerprint(root)
receipt = catalog_receipt(root, args.selected_tools)
if not args.plan:
catalog_path = Path(receipt['path']).relative_to(root).as_posix()
pinned_catalog = next((row for row in runtime_files if row['path'] == catalog_path), None)
if pinned_catalog is None or pinned_catalog['sha256'] != receipt['sha256']:
raise ValueError('Catalog changed while pinning the matrix runtime; rebuild and retry')
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip()
matrix = []
for repetition in range(args.repetitions):
# Reverse both mode and arm ordering on alternating rounds to expose
# order/cache effects. Every invocation still has a fresh client/server.
for mode in args.modes[::1 if repetition % 2 == 0 else -1]:
for arm in ['none', 'all', 'selected'][::1 if repetition % 2 == 0 else -1]:
matrix.append({'repetition': repetition + 1, 'mode': mode, 'arm': arm})
experiment = {'version': 1, 'runtime_revision': revision, 'model': args.model, 'reasoning': args.reasoning,
'catalog': receipt, 'matrix': matrix,
'sources_sha256': {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest()
for name in ['catalog-eval.py', 'agent-trial.py', 'codex_context.py', 'runtime_identity.py',
'resource-run.py', 'resource_payload.py', 'provider-environment.json']},
'scope': 'Fresh-session load-only usage. Warm OS/API caches are possible; no cache-miss claim or task-quality claim.',
'usage_scope': 'Codex turn.completed observed usage; deltas include server instructions and client framing, not an exact schema-only token count.'}
if args.plan:
print(json.dumps(experiment, indent=2))
return 0
experiment['runtime_files_sha256'] = pinned_digest
output.mkdir(parents=True, exist_ok=False, mode=0o700)
write_json(output / 'experiment.json', experiment)
write_json(output / 'runtime-files.json', runtime_files)
(output / 'prompt.txt').write_text(PROMPT)
write_json(output / 'selected-tools.json', args.selected_tools)
write_json(output / 'providers.json', {})
rows = []
for index, cell in enumerate(matrix):
reason = 'Runtime changed between trials; no further model calls were made'
try:
_, current_digest = runtime_fingerprint(root)
except (OSError, ValueError) as error:
current_digest = None
reason = 'Runtime identity unavailable; no further model calls were made: ' + str(error)
if current_digest != pinned_digest:
report = {'experiment': experiment, 'trials': rows, 'comparison': comparison(rows, pinned_digest),
'unattempted': matrix[index:], 'observed_runtime_digest': current_digest, 'reason': reason}
write_json(output / 'report.json', report)
print(report['reason'], flush=True)
return 1
directory = output / ('{repetition:02d}-{mode}-{arm}'.format(**cell))
command = [sys.executable, str(HERE / 'resource-run.py'), '--observe-payload-exit', '--',
sys.executable, str(HERE / 'agent-trial.py'), '--runtime-root', str(root), '--revision', revision,
'--prompt', str(output / 'prompt.txt'), '--output', str(directory), '--model', args.model,
'--reasoning', args.reasoning, '--mode', cell['mode'], '--timeout', str(args.timeout),
'--codex', args.codex, '--providers', str(output / 'providers.json'),
'--catalog-load', '--capture-tool-context']
if cell['arm'] == 'none':
command.append('--no-mcp')
elif cell['arm'] == 'selected':
command.extend(['--enabled-tools', str(output / 'selected-tools.json')])
print(json.dumps({'starting': cell}), flush=True)
with directory.with_suffix('.log').open('w') as log:
outcome = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=False)
row = {**cell, **assess_trial(directory, outcome.returncode, pinned_digest)}
rows.append(row)
report = {'experiment': experiment, 'trials': rows, 'comparison': comparison(rows, pinned_digest)}
write_json(output / 'report.json', report)
print(json.dumps({'completed': cell, 'status': row['status'], 'usage': row.get('usage'), 'reason': row.get('reason')}), flush=True)
print(json.dumps(report['comparison']['groups'], indent=2))
return 0 if all(row['status'] == 'valid' for row in rows) else 1
if __name__ == '__main__':
sys.exit(main())