Understand first
New to this knowledge point
Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.
Start with core principles →Understand → Implement → Debug → Design
Run real SDK transport and trace export against local fixtures while keeping business receipts and process limits explicit.
Knowledge content check2026-10-30 · Check the source of the original question2026-10-30
It is recommended to understand first:
Task contracts and independent acceptance checks →Task causality and resource attribution →Idempotency, unknown outcomes, and task recovery →Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.
New to this knowledge point
Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.
Start with core principles →Prepare to write the principles into code
Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.
Reading implementation and trade-offs →Need to handle failures and changes in conditions
Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.
Continue to delve deeper into the problem →Need to design or review plans
Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.
Analyze engineering scenarios →LEARN · PRACTICE · REFLECT
First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.
Can be practiced directly. After logging in, answers, favorites, and notes will be saved to your account.
Log in and saveEach modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.
Core concept · Harness integration: official SDK, recovery and OTLP
Preparatory concepts:HTTP/JSON, SQLite transactions, Trace context
Reproduce the integration and explain exactly which local boundaries passed, which failed, and what remains unverified.
A local SDK response tests transport; a bound merchant receipt proves its effect. Export acknowledgement does not establish durable audit retention. Select the figure to open it at full size.
The local fixture combines a model-shaped endpoint, merchant handler and miniature OTLP receiver. A production design must replace each boundary with an actual service contract: provider authentication and quotas, merchant authorization and current receipt semantics, and collector/storage retention. The OpenAI client is an API SDK, not the Agents SDK or a general agent runtime. This package neither proves a model’s tool choice nor integrates all vendor frameworks.
The child launcher constructs an environment allowlist, sets finite CPU/file/open-file limits, imposes a wall-clock deadline, kills the process group on timeout and waits for the direct child. This demonstrates credential omission and lifecycle control. It does not deny file/network access, impose memory isolation or protect a host from malicious source. Decide whether the task needs a container, microVM or managed execution service; define artifact mounts, credential proxy, outbound destinations and host-owned teardown, then test the chosen boundary.
Dockerfile.example and the Docker/microVM discussion in README are unexecuted recipes. A real rollout needs observed image build/run, non-root ownership, persisted audit outside disposable storage, current identity checks, failure injection and release rollback. No cloud deployment, autoscaling, multi-host failover, production capacity, model quality, dollar cost or SLA is established by this small local sample. Additional OTel instrumentations need separate redaction tests; exporter acknowledgement alone cannot promise retention.
Use a pinned real SDK against an explicitly local authored fixture, persist original business intent before dispatch, and recover from a lost response through an independently queried bound receipt. Export real spans with propagated context and recovery links, then reject the collector to show telemetry delivery is separate from business audit. Bound child environment/lifecycle without calling it a hostile-code sandbox.
A model API response, a merchant receipt and a collector acknowledgement answer different questions. Here the SDK parses an authored localhost response. That demonstrates a real library/HTTP boundary while making no statement about generated reasoning. The merchant owns the unique operation key and effect. Its SQLite transaction commits before the socket is deliberately closed. An application transport exception therefore cannot establish that nothing happened.
Save the business key, binding digest and pending call before the action. A replacement worker reads these facts from disk and queries the original receipt. It must compare the receipt's key and digest before linking it to a task. A new key would turn reconciliation into another action. A checkpoint improves recovery only when its interpretation agrees with the effect authority.
Traceparent and a recovery Link connect work across HTTP and process boundaries. They explain causality but do not grant authority or deduplicate effects. Even a successful OTLP response is a local receiver acknowledgement, not proof of retained audit data. The local business ledger remains the authority when the exporter fails.
Download the source ZIP and enter harness-production-integration-v1. Use Python 3.12 and the full pinned requirements.txt. The validated versions are openai 3.41.0, httpx2 2.16.0 and OpenTelemetry 1.45.2; this lab does not assume a future major SDK has the same constructor. The package needs fixture.py beside lab.py. The embedded lab.py below is the exact main source, not a standalone replacement for the ZIP.
python3.12 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -B -m unittest -v
.venv/bin/python -B lab.py demo --work work/ok
Six test methods must pass. The demo starts only 127.0.0.1 servers and cleans them up. Start and recover execute in different worker PIDs, with exits 75 and 0. The parent catches 75 and continues the designed recovery; do not treat the first worker as an unexpected route failure.
client_for supplies a fixed fake key, an exact local origin, max_retries=0, a finite timeout and a client that ignores environment proxies and redirects. It does not read a model key. The first SDK Responses call returns create_ticket. The worker saves all returned function items and the call ID. A later SDK request includes the matching function_call_output with the independently queried receipt. One additional wrong-call-ID request is a negative control: three Responses HTTP requests are zero model generations.
The real OTel SDK creates spans. Its official OTLP/HTTP exporter serializes protobuf; fixture.py parses it at the local test receiver. Inspect otlp-batches.json and otlp-spans.json, both the propagated parent and the persisted recovery Link. The receiver is not the Collector distribution or a durable storage service. Read the bilingual guide for exact output and artifact fields.
Read this source with fixture.py from the same ZIP; this module is not standalone.
"""Real official SDK transport and OTLP export; fictional localhost data only."""
import argparse
import base64
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import signal
import sqlite3
import subprocess
import sys
import tempfile
from urllib.parse import urlsplit
import httpx2
from openai import OpenAI, APIConnectionError, APIStatusError
from opentelemetry.propagate import inject
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExportResult
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.trace import Link, SpanContext, TraceFlags
import requests
from fixture import Fixture, KEY, CALL_ID, PAYLOAD, SENSITIVE, canonical, digest
ROOT = Path(__file__).resolve().parent
VERSIONS = ['openai', 'httpx2', 'opentelemetry-sdk', 'opentelemetry-exporter-otlp-proto-http', 'protobuf']
def normalize_usage(value):
keys = ['input_tokens', 'output_tokens', 'total_tokens']
if not isinstance(value, dict) or any(type(value.get(k)) is not int or value[k] < 0 for k in keys):
return None
if value['input_tokens'] + value['output_tokens'] != value['total_tokens']:
return None
return {k: value[k] for k in keys}
def local_url(url, path=''):
u = urlsplit(url)
if u.scheme != 'http' or u.hostname != '127.0.0.1' or u.username or u.password or not u.port or u.path != path or u.query or u.fragment:
raise ValueError('explicit_local_fixture_endpoint_required')
return url
def client_for(url):
local_url(url)
return OpenAI(api_key='fixture-not-a-credential', base_url=url + '/v1', max_retries=0, timeout=2,
http_client=httpx2.Client(trust_env=False, follow_redirects=False))
class RecordingExporter(OTLPSpanExporter):
"""Keep the real exporter result; force_flush alone cannot attest delivery."""
def __init__(self, endpoint):
local_url(endpoint, urlsplit(endpoint).path)
session = requests.Session(); session.trust_env = False
super().__init__(endpoint=endpoint, session=session, headers={'x-fixture': 'local'}, timeout=1)
self.results = []
def export(self, spans):
result = super().export(spans)
self.results.append(result == SpanExportResult.SUCCESS)
return result
class Telemetry:
def __init__(self, endpoint):
self.exporter = RecordingExporter(endpoint)
self.provider = TracerProvider(resource=Resource({'service.name': 'harness-local-lab'}))
self.provider.add_span_processor(SimpleSpanProcessor(self.exporter))
self.tracer = self.provider.get_tracer('harness-production', '1.0.0')
def close(self):
flushed = self.provider.force_flush(timeout_millis=2000)
self.provider.shutdown()
return {'force_flush_returned': flushed, 'export_results': self.exporter.results,
'is_durable_audit': False}
def safe_env():
# Construct values; never copy the parent environment or read a model key.
return {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'PYTHONDONTWRITEBYTECODE': '1'}
def launch(command, timeout=15):
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
# Set resource limits after exec, avoiding preexec_fn in a threaded parent.
bootstrap = ('import os,resource,sys; '
'resource.setrlimit(resource.RLIMIT_CPU,(2,2)); '
'resource.setrlimit(resource.RLIMIT_NOFILE,(64,64)); '
'resource.setrlimit(resource.RLIMIT_FSIZE,(65536,65536)); '
'os.execv(sys.argv[1],sys.argv[1:])')
process = subprocess.Popen([sys.executable, '-I', '-c', bootstrap, *command],
env=safe_env(), cwd=ROOT, stdin=subprocess.DEVNULL,
stdout=stdout, stderr=stderr, start_new_session=True)
timed_out = False
try:
process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=3)
stdout.seek(0); stderr.seek(0)
return {'pid': process.pid, 'exit_code': process.returncode, 'timed_out': timed_out,
'reaped': process.poll() is not None, 'stdout': stdout.read(8192).decode(errors='replace'),
'stderr': stderr.read(8192).decode(errors='replace')}
def bounded_child(mode='inspect', timeout=.2):
code = "import json,os,time; " + ("time.sleep(5); " if mode == 'sleep' else '') + \
"print(json.dumps({'sentinel_seen':'HARNESS_PARENT_SENTINEL' in os.environ,'credential_seen':'OPENAI_API_KEY' in os.environ}))"
result = launch([sys.executable, '-I', '-c', code], timeout)
return {**result, **(json.loads(result['stdout']) if result['stdout'] else {})}
def state(path):
db = sqlite3.connect(path)
try:
row = db.execute('SELECT value FROM task WHERE id=1').fetchone()
return json.loads(row[0]) if row else None
finally:
db.close()
def save(path, value):
db = sqlite3.connect(path)
try:
db.execute('PRAGMA synchronous=FULL')
db.execute('CREATE TABLE IF NOT EXISTS task(id INTEGER PRIMARY KEY,value TEXT NOT NULL)')
db.execute('CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY,event TEXT NOT NULL)')
with db:
db.execute('INSERT INTO task VALUES(1,?) ON CONFLICT(id) DO UPDATE SET value=excluded.value', (canonical(value),))
db.execute('INSERT INTO audit(event) VALUES(?)', (canonical({'state': value['state'], 'operation_key': value['operation_key']}),))
finally:
db.close()
def headers():
result = {}; inject(result); return result
def request_model(client, telemetry, items):
with telemetry.tracer.start_as_current_span('sdk.responses'):
return client.responses.create(model='local-fixture-no-model', input=items, store=False,
tools=[{'type': 'function', 'name': 'create_ticket', 'parameters': {'type': 'object',
'properties': {'topic': {'type': 'string'}, 'note': {'type': 'string'}},
'required': ['topic', 'note'], 'additionalProperties': False}, 'strict': True}],
extra_headers=headers())
def worker(path, url, endpoint, phase):
telemetry = Telemetry(endpoint)
old = state(path) if path.exists() else None
links = []
if old:
links = [Link(SpanContext(int(old['trace_id'], 16), int(old['span_id'], 16), False, TraceFlags(1)))]
outcome = 0
try:
with client_for(url) as client, telemetry.tracer.start_as_current_span('harness.' + phase, links=links) as span:
span.set_attribute('task.id', 'demo')
if phase == 'start':
if old:
raise ValueError('fresh_task_required')
original_input = [{'role': 'user', 'content': SENSITIVE}]
first = request_model(client, telemetry, original_input)
calls = [i for i in first.output if i.type == 'function_call']
if len(calls) != 1 or calls[0].name != 'create_ticket' or json.loads(calls[0].arguments) != PAYLOAD:
raise ValueError('fixture_tool_contract')
context = span.get_span_context()
old = {'state': 'intent', 'operation_key': KEY, 'payload': json.loads(calls[0].arguments),
'input': original_input,
'output': [x.model_dump() for x in first.output], 'call_id': calls[0].call_id,
'usage': normalize_usage(first.usage.model_dump() if first.usage else None),
'trace_id': format(context.trace_id, '032x'), 'span_id': format(context.span_id, '016x')}
save(path, old) # Intent and original business identity commit before dispatch.
try:
with telemetry.tracer.start_as_current_span('merchant.write'):
client.post('/effects', cast_to=dict, body={'operation_key': KEY, 'payload': old['payload']},
options={'headers': {**headers(), 'X-Fixture-Drop': '1'}})
except APIConnectionError:
old['state'] = 'outcome_unknown'; save(path, old); outcome = 75
elif phase == 'recover':
if not old or old['state'] != 'outcome_unknown':
raise ValueError('unknown_intent_required')
with telemetry.tracer.start_as_current_span('merchant.receipt_lookup'):
receipt = client.get('/receipts/' + old['operation_key'], cast_to=dict, options={'headers': headers()})
if not receipt['found']:
return 76 # Unknown remains held; a missing lookup never permits a new write.
receipt = receipt['receipt']
if receipt['operation_key'] != old['operation_key'] or receipt['binding_sha256'] != digest(old['payload']):
raise ValueError('receipt_binding_mismatch')
final = request_model(client, telemetry, old['input'] + old['output'] + [{'type': 'function_call_output',
'call_id': old['call_id'], 'output': canonical(receipt)}])
old.update(state='completed', receipt=receipt,
continuation_usage=normalize_usage(final.usage.model_dump() if final.usage else None))
save(path, old)
else:
raise ValueError('unknown_phase')
finally:
print(canonical({'telemetry': telemetry.close(), 'state': state(path)['state'] if path.exists() else None}))
return outcome
def run_demo(work, reject_export=False):
work = Path(work); work.mkdir(parents=True, exist_ok=True)
if any(work.iterdir()):
raise ValueError('fresh_empty_work_directory_required')
workers = []
with Fixture(work / 'merchant.sqlite', reject_export) as fixture:
endpoint = fixture.url + ('/reject-traces' if reject_export else '/v1/traces')
service_telemetry = Telemetry(endpoint); fixture.tracer = service_telemetry.tracer
for phase in ['start', 'recover']:
run = launch([sys.executable, '-B', str(ROOT / 'lab.py'), 'worker', '--work', str(work.resolve()),
'--url', fixture.url, '--endpoint', endpoint, '--phase', phase])
workers.append(run)
if run['exit_code'] != (75 if phase == 'start' else 0):
raise AssertionError(run)
if phase == 'start':
before = state(work / 'agent.sqlite')['state']
after = state(work / 'agent.sqlite')
with client_for(fixture.url) as client:
replay = client.post('/effects', cast_to=dict, body={'operation_key': KEY, 'payload': PAYLOAD})
conflict, wrong = False, False
try:
client.post('/effects', cast_to=dict, body={'operation_key': KEY, 'payload': {**PAYLOAD, 'topic': 'changed'}})
except APIStatusError as exc:
conflict = exc.status_code == 409
try:
client.responses.create(model='local-fixture-no-model', input=[{'type': 'function_call_output',
'call_id': 'wrong-id', 'output': canonical(after['receipt'])}])
except APIStatusError as exc:
wrong = exc.status_code == 400
flush = service_telemetry.close()
spans = fixture.spans
span_ids = {(s['trace_id'], s['span_id']) for s in spans}
raw = b''.join(fixture.otlp_bytes)
writes = [x for x in fixture.requests if x['path'] == '/v1/effects']
report = {'scope': 'real SDK + OTLP localhost integration; no generated model or remote merchant',
'before_recovery': before, 'after_recovery': after['state'], 'worker_exits': [x['exit_code'] for x in workers],
'worker_pids': [x['pid'] for x in workers], 'sdk_model_requests': fixture.model_requests,
'call_output_correlated': fixture.correlated, 'wrong_call_id_rejected': wrong,
'original_input_preserved': fixture.original_input_preserved,
'effect_count': len(fixture.ledger()), 'same_key_replayed': replay == after['receipt'],
'changed_binding_rejected': conflict, 'recovery_used_original_key': after['receipt']['operation_key'] == KEY,
'sdk_max_retries': 0, 'ambiguous_write_request_count': sum(x['response_dropped'] for x in writes),
'otlp_export_observed': bool(spans), 'exported_span_count': len(spans),
'propagated_parent_observed': any(s['name'] == 'fixture.receive' and (s['trace_id'], s['parent_id']) in span_ids for s in spans),
'recovery_link_observed': any(s['name'] == 'harness.recover' and any((x['trace_id'], x['span_id']) in span_ids for x in s['links']) for s in spans),
'raw_sensitive_payload_absent': (SENSITIVE.encode() not in raw and b'fictional-parent-secret' not in raw) if raw else None,
'collector_rejections': fixture.rejections, 'telemetry_is_durable_audit': False,
'audit_authority': 'merchant_sqlite_receipt', 'first_usage': after['usage'],
'continuation_usage': after['continuation_usage'], 'collector_flush': flush,
'usage_scope': 'Authored fixture counters, not provider tokens or monetary cost.',
'provider_requests': 0, 'hostile_code_isolation_verified': False,
'source_sha256': {n: hashlib.sha256((ROOT / n).read_bytes()).hexdigest()
for n in ['lab.py', 'fixture.py', 'test_lab.py', 'requirements.txt']},
'versions': {x: importlib.metadata.version(x) for x in VERSIONS}, 'python': sys.version.split()[0]}
for name, value in [('report.json', report), ('workers.json', workers), ('otlp-spans.json', spans),
('otlp-batches.json', [base64.b64encode(x).decode() for x in fixture.otlp_bytes]),
('http-audit.json', fixture.requests), ('merchant-ledger.json', fixture.ledger())]:
(work / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
return report
def main():
p = argparse.ArgumentParser(); p.add_argument('command', choices=['demo', 'worker'])
p.add_argument('--work', type=Path, required=True); p.add_argument('--url'); p.add_argument('--endpoint')
p.add_argument('--phase', choices=['start', 'recover']); p.add_argument('--reject-export', action='store_true')
args = p.parse_args()
if args.command == 'worker':
return worker(args.work / 'agent.sqlite', args.url, args.endpoint, args.phase)
report = run_demo(args.work, args.reject_export)
print(canonical({k: report[k] for k in ['before_recovery', 'after_recovery', 'effect_count', 'sdk_model_requests',
'call_output_correlated', 'wrong_call_id_rejected', 'otlp_export_observed', 'propagated_parent_observed',
'recovery_link_observed', 'raw_sensitive_payload_absent']}))
return 0
if __name__ == '__main__':
raise SystemExit(main())
Run the controlled collector rejection into another empty directory:
.venv/bin/python -B lab.py demo --work work/rejected --reject-export
HTTP 400 exporter errors on stderr are intentional. completed and one merchant effect remain. No exported bytes means raw_sensitive_payload_absent is null; an empty collection cannot establish redaction. force_flush_returned may still be true because it is a processor API result, while the real exporter results are false. Read workers.json and collector_rejections before interpreting a green process exit.
For the lost response, inspect the single dropped action HTTP attempt, the persisted original key, outcome_unknown and the later GET receipt. The SDK's max_retries=0 prevents its connection-error policy from replaying the ambiguous POST. Explicitly replaying the same key/binding returns the old receipt; changing the binding is rejected with 409. The bad function call ID returns 400 and cannot be presented as a successful continuation. Request IDs and trace IDs do not replace a business deduplication key.
The initial red log has six test methods and seventeen failed assertions/subcases; the subsequent green log is a different observation. Usage probes reject empty, bool, negative and inconsistent fields. Process probes use named fictional secret sentinels and a real timeout; they do not inspect real secrets. When changing source, preserve before/after reports and source hashes. A changed output expectation cannot prove the application was repaired. The recorded evidence is a reproducible local reference, not independent learner mastery.
The following wrapper launches the packaged lab; the full lab.py source is in the course implementation layer above and the ZIP, beside required fixture.py.
import subprocess, sys
subprocess.run([sys.executable, '-B', 'lab.py', 'demo', '--work', 'work/interview'], check=True)
{"after_recovery":"completed","before_recovery":"outcome_unknown","call_output_correlated":true,"effect_count":1,"otlp_export_observed":true,"propagated_parent_observed":true,"raw_sensitive_payload_absent":true,"recovery_link_observed":true,"sdk_model_requests":3,"wrong_call_id_rejected":true}
Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.
Level 1The collector returns 400 but force_flush returns true. Did the audit succeed?
Delivery and business truth have separate authorities.
No. Inspect the actual exporter result and independent business receipt. A processor flush result is not receiver retention or business completion.
Follow this answer further
Level 2The worker lost the write response and the receipt query is empty. Should it retry under a new key?
The earlier request may still commit.
Keep the original intent and unknown state. A point-in-time empty read does not establish terminal absence; use the service’s current reconciliation and fencing contract.
Follow this answer further
Level 3What new evidence would permit a safe transition from unknown?
The effect authority must settle the ambiguity.
A receipt with the original business identity and immutable binding establishes the committed effect. Terminal absence needs service-enforced fencing/closure semantics, not just a local timeout, process kill or trace status. Document the service’s deduplication lifetime.
Level 1What does a real OpenAI SDK call to the fixture prove?
Real library execution and real model evaluation are different observations.
It proves this installed SDK/HTTP path, typed parsing and application correlation under authored responses. It does not prove provider-origin generation, account access, model quality, a successful remote transaction or an Agents SDK integration.
Level 1Does an environment allowlist plus a timeout make malicious code safe?
A process boundary is not a capability boundary.
No. This launcher omits credentials and controls direct-child lifecycle with finite CPU/file/open-file limits. File/network access, memory isolation, syscall policy and host control remain separate. Test the selected container/microVM or managed boundary; recipes here are unexecuted.
First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.
Changing conditions:OTLP receiver is remote and sampled; acknowledgements do not promise retention.
Extended question:Which records decide completion?
Use the current authorized business receipt and separately specified durable task audit. Telemetry loss/sampling changes diagnosis coverage, not the definition of a committed action. Implement retention and audit failure policy explicitly.
The principles that remain unchanged:Business truth and diagnostic delivery remain separate.
Changing conditions:The child may deliberately read host files or contact the network.
Extended question:Which existing controls are insufficient?
The env allowlist, timeout and resource limits do not deny those capabilities. Use and test a capability-restricted execution boundary with explicit mounts, egress, credentials and host-owned teardown. Container/microVM recipes are still unexecuted in this release.
The principles that remain unchanged:Claims of isolation require observed enforcement at the relevant boundary.
Site-authored integration exercise, supported by official library docs and recorded local runs; not a company interview or measured model benchmark. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.
After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.
Run both demo routes, preserve the initial output, and independently add a mismatched-receipt test without changing acceptance or contacting a provider.