1. Three branches agree: did we obtain more evidence?
A returns decision needs a policy, a reading and sometimes an exception. A sequential implementation waits for each read. It is tempting to introduce a policy Agent and an evidence Agent and attribute any speedup to collaboration. That skips two questions: could one coordinator overlap the reads, and do the branches actually contribute independent information?
This article is for developers who can read Python, HTTP and JSON. It compares three execution structures on a small fictional evidence task. The decision is ready, denied or review; no return, refund or external business write is performed. A ready result means that the authored evidence contract is satisfied, not that a model proved a business fact.
Conclusion: parallel I/O and independent model reasoning require different evidence. Compare parallel tools before introducing separate decision makers. Isolation adds input/result boundaries, process startup and merge failures; keep it only for a constraint it actually solves.
2. Define equal inputs and a shared acceptance boundary
The experiment contains 11 authored cases, with 3 trials for each case and structure. They cover a short read, two or three independent reads, an exception, copied origins, conflicting readings, missing documents, permission denial, service failure, a failed attempt consuming the budget, and a successful tool result dropped during delivery.
The source payloads, tenant headers, read budget, required roles and expected terminal decisions are identical across structures. Origins and minimum-origin requirements are authored fixture labels, not automatic source authentication or a universal rule for truth. Execution order rotates between trials/cases. The final merger is the same function, and the expected label is read only after the decision has been computed. Denied and review are correct for cases that require them; counting only ready results would penalize proper refusal.
Acceptance = trials whose final decision matches their predeclared contract / all executed trials. This is a fixed authored-case check, not an unseen-task model success rate. Three repetitions do not create three independent task samples.
3. What the three structures execute
| Structure | Execution | Shared control | Extra boundary |
|---|---|---|---|
| sequential | Read descriptors in order | Admission, evidence rules, acceptance | No branch join |
| parallel_tools | Threads overlap the same HTTP reads | One coordinator and merger | Concurrent result collection |
| isolated_branches | Spawned processes receive individual read descriptors | The same admission and merger | Serialized descriptors/results and process lifecycle |
The branch input contains the endpoint, tenant, source ID and run ID. It does not contain the expected label or another branch's evidence. These are deterministic evidence workers, with no LLM decision loop. Spawn separates address spaces under the same OS account; it is not a security sandbox. Consequently, the experiment can measure coordination and observe execution failure, but cannot establish that multiple LLM Agents reason better.
4. Architecture means ownership and data flow
Visual guide · Change the execution structure while keeping one acceptance boundary
All three structures read the same fixtures. The merger checks delivered evidence; HTTP success alone cannot replace a missing finding. Select the figure to open it at full size.
| Component | Owns | Failure detected here | Response |
|---|---|---|---|
| Task contract | Required evidence, tenant, budget | Invalid task or unsupported requirement | Reject or explicitly scope the experiment |
| Coordinator | Dispatch reservations and branch identity | Budget exhausted or branch delivery absent | Preserve skipped work and coverage gaps |
| HTTP fixture service | Source payload and per-request audit | Missing source, tenant mismatch, injected 503 | Return the actual error |
| Worker | One read and its result envelope | HTTP/read failure | Return a classified artifact, not a guessed finding |
| Merger | Origin deduplication, role coverage and conflicts | Missing or opposing findings | review or denied under the shared rules |
| Independent check | Compare final decision with authored label | Mismatch | Keep the failed trial |
Source fixtures and contracts are in cases.json. The coordinator retains trial artifacts and service audits in the report. There is no durable queue, distributed transaction or business effect ledger. All constraints in this experiment are enforced by Python; no model is asked to remember the budget or declare its own success.
5. Results from this run
Visual guide · Ordinary case: parallel reads overlap waiting; isolation adds work
These are medians for the same two-read task. The local process boundary adds startup and serialization; no model reasoning was measured. Select the figure to open it at full size.
| Structure | Accepted / all trials | Reserved/dispatched read slots | HTTP observations | Worker tasks submitted | Logical branch messages |
|---|---|---|---|---|---|
| sequential | 33/33 | 72 | 72 | 0 | 0 |
| parallel_tools | 33/33 | 72 | 72 | 0 | 0 |
| isolated_branches | 33/33 | 72 | 72 | 72 | 144 |
Read-slot reservations happen before dispatch and include failed attempts. Service audit rows separately show HTTP requests observed at the service. Worker tasks submitted are not an OS-process census: a pool may run more than one task in a process. Logical message counts refer to submitted descriptors and returned artifacts, not Python IPC frames. HTTP response bytes are recorded separately; IPC byte volume is not measured.
The following are within-case medians in milliseconds. The service deliberately injects zero or 25 milliseconds of wait per source. Times include local scheduling, HTTP work and, for isolated branches, pool startup/shutdown. They exclude starting the fixture service and are not end-to-end production measurements.
| Case | sequential | parallel_tools | isolated_branches |
|---|---|---|---|
| short-chain | 7.782 | 7.503 | 128.354 |
| ordinary | 84.163 | 40.702 | 173.718 |
| exception-required | 125.33 | 47.606 | 181.409 |
| missing-result | 84.453 | 46.012 | 173.061 |
The rows support a bounded choice: for these known independent reads, parallel tools can overlap waiting while preserving the same acceptance rules. The isolated structure supplies a process/input boundary with additional lifecycle and serialization work. Since every structure shares the deterministic evidence logic, the result does not establish a model-quality improvement from isolation. A real model comparison needs a separate task set and provider measurements.
No token or monetary cost was observed. Tool slots, HTTP requests and logical messages describe different resources; they must not be converted into dollars or combined into an invented cost score. The full run preserves every trial rather than selecting the fastest. No production P95 is reported from this small controlled sample.
6. A complete failure: the tool succeeded but its finding disappeared
Phenomenon: the service audit contains two HTTP 200 responses, but the coordinator is missing one required evidence artifact. Hypothesis A is missing source data; hypothesis B is result delivery loss. The audit and the delivered-artifact trace distinguish them. The injection removes the finding from the actual merge input, while keeping evidence that the read happened.
The deliberately unsafe baseline considers the successful reads sufficient and still reports ready. The repaired contract checks the evidence that actually reached the merger, sees the missing role and reports review. Restoring delivery on the same task makes the intact run ready again. This is a simulated delivery fault with real local HTTP/process execution, not a production incident.
{
"before": {
"decision": "ready",
"accepted": true,
"tool_attempts": 2,
"delivery_failures": 0,
"reasons": [],
"http_statuses": [
200,
200
]
},
"after": {
"decision": "review",
"accepted": false,
"tool_attempts": 2,
"delivery_failures": 1,
"reasons": [
"missing_evidence",
"missing_role:reading",
"insufficient_independent_origins"
],
"http_statuses": [
200,
200
]
},
"recovered": {
"decision": "ready",
"accepted": true,
"tool_attempts": 2,
"delivery_failures": 0,
"reasons": [],
"http_statuses": [
200,
200
]
},
"unsafe_after": "ready"
}
The repair introduces a useful constraint: a successful tool call cannot stand in for an accepted artifact. The original complete-delivery task remains unsatisfied during the fault, even though review is the safe fallback. A separate case that explicitly expects review can pass its own contract. Keep that distinction visible instead of relabeling all safe stops as successful deliveries.
Negative controls also reject copied-origin voting and preserve opposing readings. A service failure still consumes its reserved attempt, preventing a hidden extra read after the budget is exhausted. Changing role names or adding more workers cannot repair these acceptance errors.
7. Why choose one structure over another?
| Condition | First choice | Benefit | Cost or reason to stop |
|---|---|---|---|
| Short or dependent path | Sequential/fixed workflow | Clear state and simple diagnosis | No benefit from overlapping a dependency |
| Known independent reads | One coordinator with parallel tools | Overlap waiting without another planner | Shared admission and result validation remain necessary |
| Different trust or context boundaries | Isolated workers, then evaluate whether Agents are required | Separate input/tool surfaces | Serialization, process failures, provenance and join protocol |
| Open-ended independent exploration | A bounded real-model Agent experiment | Potentially distinct search trajectories | More model calls and coordination; benefit is unmeasured here |
| Missing required evidence or unresolved conflict | Review, partial delivery or stop | Honest result and bounded actions | Complete automatic delivery is unavailable |
In this contract the reads and evidence rules are known. I would start with parallel tools for independent reads and retain sequential execution for the short path. I would require an explicit isolation constraint before selecting spawned workers. This decision belongs to this controlled task; it does not generalize to open-ended research or a model overwhelmed by a shared context.
8. Reproduce and challenge the result
Use Python 3.10+ and the standard library on a machine that permits localhost HTTP and child processes. Copy the three complete files in the appendix to one fresh directory. No provider account, API key or package installation is required.
python3 comparison.py --trials 3 --out results.json
python3 comparison.py --fault-demo --out fault-demo.json
python3 -m unittest discover -s . -p test_comparison.py -v
Inspect runs, not just the summary. For each case/trial, compare input_sha256, dispatched sources and audited payload hashes between structures; compare decisions and failure reasons separately from elapsed time. Change one delay, one source origin or one required role, predict the result, then rerun all structures. Rotating order reduces one fixed-order bias; it does not make the experiment statistically representative.
Actual environment:
{
"python": "3.14.7",
"platform": "macOS-15.5-arm64-arm-64bit-Mach-O",
"cpu_count": 8,
"clock": "perf_counter_ns"
}
| Reproduction file | SHA-256 |
|---|---|
| comparison.py | 7b78b5211950a3b4a15681eb70b212b800a9b7c859d671adda448c527530515f |
| cases.json | 725a429cb17f7113abed177fb9a3afa759bfff6c9e7b27645d87943ea64682e7 |
| test_comparison.py | 031649cc3a0f84a602c907d7b77c427601a50cb6346797168b76a85752da191a |
9. Boundaries and a separate real-model experiment
The source tenant field is a fictional trusted fixture, not a test of a production identity provider. There is no cancellation protocol, dynamic task discovery, model router or remote write. Fixed waits demonstrate a scheduling condition, not vendor latency. The final label tests a restricted decision contract; it does not score free-text evidence entailment.
For a real-model comparison, freeze tasks, source snapshots, tools, model IDs, total budgets and acceptance criteria. Run all configurations on the same inputs; preserve every response, failure and actual usage. Verify important claims against their source text, then compare cost per accepted task and end-to-end latency without hiding hard failures. An HTTP 429 is a failed integration attempt, not evidence of model inability, and missing usage remains unknown.
The evaluation article separately records the bounded provider verification from this revision. It uses different cases and does not turn this orchestration comparison into a multi-model benchmark.
Anthropic's workflow/Agent distinction is useful here: prescribed execution paths and model-directed action selection are different architectures. Its research-system experience describes a particular model-backed system; its internal improvement figures are not results of our experiment. Sources checked 2026-10-30.
10. A reusable decision checklist
- Identify the failure: dependent steps, I/O waiting, missing evidence, context pressure or a need for independent exploration.
- Define the authoritative input and required artifact for each branch; keep origin, scope and version.
- Separate reserved attempts, observed requests, delivered results and business effects.
- Use one acceptance contract and include proper denial/review outcomes.
- Preserve delivery loss, conflict and failed-attempt accounting as negative controls.
- Add a separate model experiment before claiming a reasoning or quality benefit.
- Choose the simplest structure meeting the constraints and write the condition that would change that choice.
Complete reproduction files
comparison.py
"""Local execution comparison: synthetic HTTP evidence, no generation model."""
import argparse
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import multiprocessing
import os
from pathlib import Path
import platform
import statistics
import socketserver
import threading
import time
import urllib.error
import urllib.request
import uuid
STRATEGIES = ('sequential', 'parallel_tools', 'isolated_branches')
_SERVERS = {}
def encoded(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def sha(value):
return hashlib.sha256(encoded(value)).hexdigest()
def load_cases():
return json.loads(Path(__file__).with_name('cases.json').read_text())
class FixtureServer:
"""Real loopback HTTP; delay_ms is injected waiting, not a production sample."""
def __init__(self, sources):
self.sources, self.audit = sources, []
def __enter__(self):
fixture = self
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
started = time.perf_counter_ns()
source_id = self.path.removeprefix('/')
audit = {'run': self.headers.get('X-Run'), 'source': source_id,
'started_ns': started, 'status': None, 'finished_ns': None}
fixture.audit.append(audit)
source = fixture.sources.get(source_id)
status = 404 if source is None else 200
if source:
time.sleep(source['delay_ms'] / 1000)
status = source.get('http_status', 200)
if self.headers.get('X-Tenant') != source['tenant']:
status = 403
payload = ({'id': source_id, **{k: source[k] for k in
('role', 'value', 'origin')}} if status == 200 else {'error': status})
body = encoded(payload)
audit.update({
'status': status, 'started_ns': started, 'finished_ns': time.perf_counter_ns(),
'response_bytes': len(body), 'response_sha256': hashlib.sha256(body).hexdigest()})
try:
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
audit['delivery_error'] = 'client_disconnected'
class Server(ThreadingHTTPServer):
def server_bind(self):
socketserver.TCPServer.server_bind(self)
self.server_name, self.server_port = 'localhost', self.server_address[1]
self.http = Server(('127.0.0.1', 0), Handler)
self.thread = threading.Thread(target=self.http.serve_forever, daemon=True)
self.thread.start()
self.endpoint = 'http://127.0.0.1:' + str(self.http.server_port)
_SERVERS[self.endpoint] = self
return self.endpoint
def __exit__(self, *_):
self.http.shutdown()
self.http.server_close()
self.thread.join()
_SERVERS.pop(self.endpoint)
def fetch(descriptor):
"""A branch gets only its read descriptor, not other evidence or the case label."""
endpoint, tenant, source_id, run = descriptor
request = urllib.request.Request(endpoint + '/' + source_id,
headers={'X-Tenant': tenant, 'X-Run': run})
artifact = {'source': source_id, 'pid': os.getpid(), 'started_ns': time.perf_counter_ns()}
try:
with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(request, timeout=3) as response:
body = response.read(16384)
artifact.update(status=200, data=json.loads(body), response_bytes=len(body))
except urllib.error.HTTPError as error:
body = error.read(16384)
artifact.update(status=error.code, response_bytes=len(body))
error.close()
except (OSError, ValueError) as error:
artifact.update(status='read_error', error=type(error).__name__, response_bytes=0)
artifact['finished_ns'] = time.perf_counter_ns()
return artifact
def merge(case, artifacts, skipped):
good = [a['data'] for a in artifacts if a['status'] == 200 and not a.get('dropped')]
origins = sorted({a['origin'] for a in good})
reasons = []
if any(a['status'] == 403 for a in artifacts):
return 'denied', ['access_denied'], origins
if skipped:
reasons.append('attempt_budget_exhausted')
if len(good) != len(case['sources']):
reasons.append('missing_evidence')
for role in case['required_roles']:
values = {a['value'] for a in good if a['role'] == role}
if not values:
reasons.append('missing_role:' + role)
elif len(values) > 1:
reasons.append('conflict:' + role)
if len(origins) < case['min_origins']:
reasons.append('insufficient_independent_origins')
if reasons:
return 'review', reasons, origins
return ('denied' if any(a['value'] == 'deny' for a in good) else 'ready'), [], origins
def run_case(case, strategy, endpoint):
if strategy not in STRATEGIES:
raise ValueError('unknown strategy')
started = time.perf_counter_ns()
run = uuid.uuid4().hex
admitted, skipped = case['sources'][:case['budget']], case['sources'][case['budget']:]
descriptors = [(endpoint, case['tenant'], source, run) for source in admitted]
trace = [{'event': 'admit', 'source': s, 'attempt': i + 1} for i, s in enumerate(admitted)]
artifacts = []
if strategy == 'sequential' or not descriptors:
artifacts = [fetch(d) for d in descriptors]
else:
executor = ThreadPoolExecutor if strategy == 'parallel_tools' else ProcessPoolExecutor
options = {'max_workers': min(4, len(descriptors))}
if strategy == 'isolated_branches':
options['mp_context'] = multiprocessing.get_context('spawn')
with executor(**options) as pool:
futures = {pool.submit(fetch, d): d[2] for d in descriptors}
for future in as_completed(futures):
try:
artifacts.append(future.result())
except Exception as error:
artifacts.append({'source': futures[future], 'status': 'branch_error',
'error': type(error).__name__, 'response_bytes': 0})
artifacts.sort(key=lambda a: admitted.index(a['source']))
for artifact in artifacts:
if artifact['source'] == case.get('drop_result'):
artifact['dropped'] = True
artifact['discarded_sha256'] = sha(artifact.pop('data', None))
trace.append({'event': 'artifact', **artifact})
decision, reasons, origins = merge(case, artifacts, skipped)
trace.append({'event': 'merge', 'decision': decision, 'reasons': reasons})
audit = [dict(a) for a in _SERVERS[endpoint].audit if a['run'] == run]
return {'case_id': case['id'], 'strategy': strategy, 'input_sha256': sha(case),
'decision': decision, 'expected': case['expected'], 'accepted': decision == case['expected'],
'reasons': reasons, 'unique_origins': origins, 'tool_attempts': len(admitted),
'actual_http_requests': len(audit),
'tool_failures': sum(a['status'] != 200 for a in artifacts),
'delivery_failures': sum(bool(a.get('dropped')) for a in artifacts),
'branches_started': len(admitted) if strategy == 'isolated_branches' else 0,
'serialized_branch_messages': len(admitted) + sum(a['status'] != 'branch_error' for a in artifacts)
if strategy == 'isolated_branches' else 0,
'dispatched_sources': admitted, 'budget_skipped': skipped, 'merge_inputs': len(artifacts),
'response_bytes': sum(a['response_bytes'] for a in artifacts),
'elapsed_ms': round((time.perf_counter_ns() - started) / 1e6, 3),
'artifacts': artifacts, 'audit': audit, 'trace': trace}
def compare(trials=3):
data, rows = load_cases(), []
with FixtureServer(data['sources']) as endpoint:
for trial in range(trials):
for index, case in enumerate(data['cases']):
shift = (trial + index) % len(STRATEGIES)
order = STRATEGIES[shift:] + STRATEGIES[:shift]
for strategy in order:
rows.append({'trial': trial + 1, **run_case(case, strategy, endpoint)})
summaries = []
for case in data['cases']:
for strategy in STRATEGIES:
group = [r for r in rows if r['case_id'] == case['id'] and r['strategy'] == strategy]
summaries.append({'case_id': case['id'], 'strategy': strategy,
'accepted': sum(r['accepted'] for r in group), 'trials': len(group),
'median_ms': round(statistics.median(r['elapsed_ms'] for r in group), 3),
'all_ms': [r['elapsed_ms'] for r in group],
**{key: group[0][key] for key in ('decision', 'tool_attempts', 'actual_http_requests', 'tool_failures',
'delivery_failures', 'branches_started', 'serialized_branch_messages')}})
return {'schema_version': 1, 'environment': {'python': platform.python_version(),
'platform': platform.platform(), 'cpu_count': os.cpu_count(), 'clock': 'perf_counter_ns'},
'scope': 'Loopback HTTP with injected wait; no LLM, tokens, prices or production latency.',
'case_sha256': sha(data), 'files_sha256': {name: hashlib.sha256(
Path(__file__).with_name(name).read_bytes()).hexdigest()
for name in ('comparison.py', 'cases.json', 'test_comparison.py')},
'trials': trials, 'summary': summaries, 'runs': rows}
def fault_demo():
data = load_cases()
case = next(c for c in data['cases'] if c['id'] == 'ordinary')
with FixtureServer(data['sources']) as endpoint:
before = run_case(case, 'isolated_branches', endpoint)
after = run_case({**case, 'drop_result': 'reading'}, 'isolated_branches', endpoint)
recovered = run_case(case, 'isolated_branches', endpoint)
unsafe = 'ready' if all(a['status'] == 200 for a in after['artifacts']) else 'review'
return {'scope': 'Injected artifact discard after real HTTP read; not a killed process.',
'before': before, 'after': after, 'unsafe_after': unsafe, 'recovered': recovered,
'safe_fault_detected': after['decision'] == 'review',
'recovery': 'Fresh read-only run, not retransmission of a business write.'}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--trials', type=int, default=3)
parser.add_argument('--out', default='results.json')
parser.add_argument('--fault-demo', action='store_true')
args = parser.parse_args()
if args.trials < 1:
parser.error('--trials must be positive')
report = fault_demo() if args.fault_demo else compare(args.trials)
Path(args.out).write_text(json.dumps(report, indent=2) + '\n')
for row in report.get('summary', []):
print(row['case_id'], row['strategy'], row['decision'],
str(row['accepted']) + '/' + str(row['trials']), str(row['median_ms']) + 'ms')
if args.fault_demo:
print('before=' + report['before']['decision'], 'unsafe=' + report['unsafe_after'],
'safe=' + report['after']['decision'], 'fresh_read=' + report['recovered']['decision'])
passed = report['safe_fault_detected'] if args.fault_demo else all(r['accepted'] for r in report['runs'])
raise SystemExit(0 if passed else 1)
cases.json
{
"schema_version": 1,
"sources": {
"quick": {"tenant":"team-a","role":"policy","value":"allow","origin":"policy-author","delay_ms":0},
"policy": {"tenant":"team-a","role":"policy","value":"allow","origin":"policy-author","delay_ms":25},
"reading": {"tenant":"team-a","role":"reading","value":"allow","origin":"telemetry-owner","delay_ms":25},
"exception": {"tenant":"team-a","role":"exception","value":"allow","origin":"safety-owner","delay_ms":25},
"blocked-exception": {"tenant":"team-a","role":"exception","value":"deny","origin":"safety-owner","delay_ms":25},
"conflicting-reading": {"tenant":"team-a","role":"reading","value":"deny","origin":"second-sensor","delay_ms":25},
"copied-policy": {"tenant":"team-a","role":"policy","value":"allow","origin":"shared-upstream","delay_ms":25},
"copied-reading": {"tenant":"team-a","role":"reading","value":"allow","origin":"shared-upstream","delay_ms":25},
"foreign": {"tenant":"team-b","role":"reading","value":"allow","origin":"foreign-owner","delay_ms":25},
"broken": {"tenant":"team-a","role":"reading","value":"allow","origin":"telemetry-owner","delay_ms":25,"http_status":503}
},
"cases": [
{"id":"short-chain","tenant":"team-a","sources":["quick"],"required_roles":["policy"],"min_origins":1,"budget":1,"expected":"ready"},
{"id":"ordinary","tenant":"team-a","sources":["policy","reading"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"expected":"ready"},
{"id":"exception-required","tenant":"team-a","sources":["policy","reading","exception"],"required_roles":["policy","reading","exception"],"min_origins":3,"budget":3,"expected":"ready"},
{"id":"exception-denied","tenant":"team-a","sources":["policy","reading","blocked-exception"],"required_roles":["policy","reading","exception"],"min_origins":3,"budget":3,"expected":"denied"},
{"id":"copied-origins","tenant":"team-a","sources":["copied-policy","copied-reading"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"expected":"review"},
{"id":"conflict","tenant":"team-a","sources":["policy","reading","conflicting-reading"],"required_roles":["policy","reading"],"min_origins":2,"budget":3,"expected":"review"},
{"id":"missing-document","tenant":"team-a","sources":["policy","absent"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"expected":"review"},
{"id":"permission-denied","tenant":"team-a","sources":["policy","foreign"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"expected":"denied"},
{"id":"tool-failure","tenant":"team-a","sources":["policy","broken"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"expected":"review"},
{"id":"budget-with-failure","tenant":"team-a","sources":["policy","broken","exception"],"required_roles":["policy","reading","exception"],"min_origins":3,"budget":2,"expected":"review"},
{"id":"missing-result","tenant":"team-a","sources":["policy","reading"],"required_roles":["policy","reading"],"min_origins":2,"budget":2,"drop_result":"reading","expected":"review"}
]
}
test_comparison.py
"""Contract tests: shared inputs, source independence and fail-closed merging."""
import copy
import os
from pathlib import Path
import unittest
try:
import comparison as lab
except ImportError:
lab = None
class ComparisonTests(unittest.TestCase):
def setUp(self):
self.assertIsNotNone(lab, 'The comparison executor has not been implemented')
self.data = lab.load_cases()
self.server = lab.FixtureServer(self.data['sources'])
self.endpoint = self.server.__enter__()
self.addCleanup(self.server.__exit__, None, None, None)
def case(self, name):
return copy.deepcopy(next(c for c in self.data['cases'] if c['id'] == name))
# Counting URLs instead of origins would incorrectly mark this ready.
def test_copied_sources_cannot_vote_themselves_independent(self):
for strategy in lab.STRATEGIES:
result = lab.run_case(self.case('copied-origins'), strategy, self.endpoint)
self.assertEqual(result['decision'], 'review')
self.assertEqual(result['unique_origins'], ['shared-upstream'])
self.assertIn('insufficient_independent_origins', result['reasons'])
# Dropping a successful artifact must not be replaced by a guessed fact.
def test_missing_branch_result_cannot_claim_completion(self):
for strategy in lab.STRATEGIES:
result = lab.run_case(self.case('missing-result'), strategy, self.endpoint)
self.assertEqual(result['decision'], 'review')
self.assertEqual(result['delivery_failures'], 1)
self.assertEqual(result['tool_attempts'], 2)
self.assertIn('missing_evidence', result['reasons'])
dropped = next(a for a in result['artifacts'] if a.get('dropped'))
self.assertNotIn('data', dropped, 'Dropped evidence must actually leave the merge input')
def test_fault_demo_keeps_before_failure_and_recovery_records(self):
self.assertTrue(callable(getattr(lab, 'fault_demo', None)), 'Missing reproducible fault demo')
result = lab.fault_demo()
self.assertEqual(result['before']['decision'], 'ready')
self.assertEqual(result['unsafe_after'], 'ready')
self.assertEqual(result['after']['decision'], 'review')
self.assertEqual(result['recovered']['decision'], 'ready')
self.assertEqual([a['status'] for a in result['after']['audit']], [200, 200])
# A strategy-specific input or hidden extra call breaks this paired contract.
def test_all_strategies_use_identical_input_and_tools(self):
rows = [lab.run_case(self.case('ordinary'), s, self.endpoint) for s in lab.STRATEGIES]
self.assertEqual(len({r['input_sha256'] for r in rows}), 1)
self.assertEqual({r['decision'] for r in rows}, {'ready'})
self.assertEqual({r['tool_attempts'] for r in rows}, {2})
self.assertEqual({tuple(r['dispatched_sources']) for r in rows}, {('policy', 'reading')})
self.assertEqual(rows[2]['branches_started'], 2)
self.assertTrue(all(a['pid'] != os.getpid() for a in rows[2]['artifacts']))
# Excluding failed attempts from admission would dispatch a forbidden third read.
def test_budget_charges_failed_attempts(self):
for strategy in lab.STRATEGIES:
result = lab.run_case(self.case('budget-with-failure'), strategy, self.endpoint)
self.assertEqual(result['tool_attempts'], 2)
self.assertEqual(result['tool_failures'], 1)
self.assertEqual(result['budget_skipped'], ['exception'])
self.assertEqual(result['decision'], 'review')
def test_zero_budget_never_creates_executor_or_http_request(self):
case = {**self.case('ordinary'), 'budget': 0, 'expected': 'review'}
for strategy in lab.STRATEGIES:
result = lab.run_case(case, strategy, self.endpoint)
self.assertEqual(result['decision'], 'review')
self.assertEqual(result['tool_attempts'], 0)
self.assertEqual(len(result['audit']), 0)
def test_timeout_still_counts_request_observed_by_server(self):
self.server.sources['slow'] = {**self.data['sources']['quick'], 'delay_ms': 3100}
case = {**self.case('short-chain'), 'sources': ['slow'], 'expected': 'review'}
result = lab.run_case(case, 'sequential', self.endpoint)
self.assertEqual(result['tool_failures'], 1)
self.assertEqual(result['actual_http_requests'], 1)
self.assertEqual(result['decision'], 'review')
def test_conflict_is_review_and_permission_denial_is_terminal(self):
for name, decision in [('conflict', 'review'), ('permission-denied', 'denied')]:
for strategy in lab.STRATEGIES:
result = lab.run_case(self.case(name), strategy, self.endpoint)
self.assertEqual(result['decision'], decision)
self.assertTrue(result['accepted'])
def test_every_case_meets_its_predeclared_contract(self):
for case in self.data['cases']:
for strategy in lab.STRATEGIES:
with self.subTest(case=case['id'], strategy=strategy):
result = lab.run_case(case, strategy, self.endpoint)
self.assertTrue(result['accepted'], result)
self.assertLessEqual(result['tool_attempts'], case['budget'])
self.assertEqual(len(result['audit']), result['tool_attempts'])
if __name__ == '__main__':
unittest.main(verbosity=2)