Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Harness integration: official SDK, recovery and OTLP

Run real SDK transport and trace export against local fixtures while keeping business receipts and process limits explicit.

Learning objectives: Reproduce the integration and explain exactly which local boundaries passed, which failed, and what remains unverified.

Content checked: 2026-10-30 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Readers able to use Python venv, HTTP and SQLite.

OTLP
OpenTelemetry Protocol carries telemetry; a received span is distinct from a durable business receipt.
Recovery Link
A span link connects the replacement worker’s trace to the earlier persisted trace/span identity.

How does the mechanism work?

Step-by-step explanation
  1. Effect authority

    The merchant receipt survives a lost response.

  2. Transport policy

    Disable SDK replay here and reconcile the original write key.

  3. Diagnostic delivery

    OTLP failure does not change the business ledger.

Implementation · Build it

Run the pinned SDK and exporter integration

Objectives of this level: Reproduce transport, persisted recovery and actual exported protobuf.

Visual guide · Three acknowledgements, three meanings

Three acknowledgements, three meanings

The SDK parses authored local responses. Export failure leaves business effects unchanged; collector acknowledgement does not prove audit retention. Select the figure to open it at full size.

Extract the complete package

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.

Inspect the concrete adapters

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.

Verify the exported boundary

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.

Exact main module from the complete package

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())

code example

Expected stable demo fields

{"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}

Acceptance task for this level

Run the unchanged package into a new empty work directory, then inspect report, HTTP audit, merchant ledger, worker PIDs and protobuf spans.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why does the report call the second usage 10/2/12 fixture data?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.