amos 9d633e9e67 Batch 15 (20261023-C-hwe-scale-15): 320 HWE-derived repair tasks
One user-space repair task per eligible HWE debug-diag / compile-deploy base
ID: 320 admitted (C 218, C++ 97, build scripts 5), 1 skipped by the content
filter. Each ships a public spec with a check-to-basis table, at least two
defects with single-fix fixtures, a symptom-masking fixture and an alternative
correct implementation. Claude re-checked all 320: structure, the HWE quality
items and trace6 Docker calibration receipts against current digests
(320/320 USABLE). Difficulty is unmeasured. Known follow-up: 212 tasks use 120
ad-hoc family names; the next batch maps them to the canonical list.
The batch's 1,256-line progress log stays in its factory report and the
36-local branch batch15-hwe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:55:56 +08:00

312 lines
31 KiB
Python

import base64
import bz2
import hashlib
import json
import math
import os
from pathlib import Path
import random
import subprocess
import sys
import tempfile
import time
RECOVERY_SECONDS = 3
RECORD_WIRE = False
SUPERVISOR = "\nimport base64,bz2,ctypes,hashlib,json,os,selectors,signal,subprocess,sys,time\ncfg=json.loads(sys.argv[1]); start=time.monotonic(); errors=[]; tracked={}; signals={}; waits=[]\nleader=None; leader_start=None; output=bytearray(); diagnostic=bytearray(); timed_out=False\nreaped=False; leader_rc=None; remaining=[]; pg_absent=False; pipes={}; selector=selectors.DefaultSelector()\npayload=sys.stdin.buffer.read(); sent=0\n\ndef fault(op,error): errors.append([op,type(error).__name__,str(error)])\ndef exact(pid):\n try:\n with open('/proc/%d/stat'%pid,'rb') as stream: data=stream.read()\n w=data[data.rfind(b')')+2:].split()\n return {'pid':pid,'state':w[0].decode('ascii'),'ppid':int(w[1]),'pg':int(w[2]),'start':int(w[19])}\n except (FileNotFoundError,ProcessLookupError): return None\n\ndef table_now():\n table={}\n for name in os.listdir('/proc'):\n if name.isascii() and name.isdigit():\n value=exact(int(name))\n if value is not None: table[value['pid']]=value\n return table\n\ndef closure(table,supervisor,remembered):\n roots={supervisor}\n for pid,token in remembered.items():\n current=table.get(pid)\n if current and current['start']==token['start'] and current['state'] not in ('Z','X'): roots.add(pid)\n found={}; changed=True\n while changed:\n changed=False\n for pid,value in table.items():\n if pid!=supervisor and pid not in found and (value['ppid'] in roots or pid in roots):\n found[pid]=value;roots.add(pid);changed=True\n return found\n\ndef discover():\n table=table_now();found=closure(table,os.getpid(),tracked)\n for pid,token in found.items(): tracked[pid]=dict(token)\n return table,found\n\ndef send_fresh(pid,token):\n current=exact(pid)\n if current is None or current['start']!=token['start'] or current['state'] in ('Z','X'): return\n os.kill(pid,signal.SIGKILL)\n key=(pid,token['start']);signals[key]=signals.get(key,0)+1\n\ndef own_wait():\n global reaped,leader_rc\n if leader is not None:\n if leader.poll() is not None:\n leader_rc=leader.wait(timeout=0);reaped=True\n\ndef adopted_wait():\n if leader is not None and not reaped:return\n while True:\n try:pid,status=os.waitpid(-1,os.WNOHANG)\n except ChildProcessError:break\n if pid==0:break\n # waitpid supplies no starttime. Never infer it from a stale tracked PID.\n waits.append([pid,None,os.waitstatus_to_exitcode(status)])\n\ndef close_pipe(stream):\n try:selector.unregister(stream)\n except KeyError:pass\n pipes.pop(stream.fileno(),None);stream.close()\n\ndef pump(wait):\n global sent\n for key,event in selector.select(wait):\n stream,kind=key.fileobj,key.data\n if kind=='in':\n try:\n count=os.write(stream.fileno(),payload[sent:sent+65536]);sent+=count\n if sent==len(payload):close_pipe(stream)\n except BrokenPipeError:close_pipe(stream)\n except BlockingIOError:pass\n else:\n try:chunk=os.read(stream.fileno(),65536)\n except BlockingIOError:continue\n if not chunk:close_pipe(stream)\n else:(output if kind=='out' else diagnostic).extend(chunk)\n\nsupervisor_start=exact(os.getpid())['start']\ntry:\n libc=ctypes.CDLL(None,use_errno=True)\n if libc.prctl(36,1,0,0,0)!=0:raise OSError(ctypes.get_errno(),'subreaper')\n leader=subprocess.Popen(cfg['argv'],cwd=cfg['cwd'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,start_new_session=True)\n info=exact(leader.pid)\n if info is None:raise RuntimeError('leader identity disappeared before capture')\n leader_start=info['start'];tracked[leader.pid]=info\n for stream,kind in [(leader.stdin,'in'),(leader.stdout,'out'),(leader.stderr,'err')]:\n if kind=='in' and not payload:stream.close();continue\n os.set_blocking(stream.fileno(),False);pipes[stream.fileno()]=stream\n selector.register(stream,selectors.EVENT_WRITE if kind=='in' else selectors.EVENT_READ,kind)\n while True:\n pump(0.02);own_wait();discover()\n if reaped and not pipes:break\n if time.monotonic()-start>=cfg['deadline']:timed_out=True;break\nexcept BaseException as error:fault('execute',error)\nfinally:\n recovery_end=time.monotonic()+cfg['recovery']\n while True:\n try:own_wait()\n except BaseException as error:fault('own_wait',error)\n found={}\n try:_,found=discover()\n except BaseException as error:fault('discover',error)\n for pid,token in list(found.items()):\n try:send_fresh(pid,token)\n except (FileNotFoundError,ProcessLookupError):pass\n except BaseException as error:fault('signal',error)\n try:own_wait()\n except BaseException as error:fault('own_wait',error)\n try:adopted_wait()\n except BaseException as error:fault('adopted_wait',error)\n try:pump(0.01)\n except BaseException as error:fault('drain',error)\n fresh=False\n try:\n table,found=discover();remaining=[[p,t['start'],t['state']] for p,t in found.items()]\n pg_absent=leader is not None and not any(t['pg']==leader.pid for t in table.values());fresh=True\n except BaseException as error:fault('absence',error);remaining=[['unknown']];pg_absent=False\n if fresh and reaped and not pipes and not remaining and pg_absent:break\n if time.monotonic()>=recovery_end:fault('recovery',RuntimeError('unconfirmed closure at deadline'));break\n time.sleep(0.01)\n for stream in list(pipes.values()):\n try:close_pipe(stream)\n except BaseException as error:fault('close',error)\n selector.close()\noutput=bytes(output);diagnostic=bytes(diagnostic)\nmeta={'phase':cfg['phase'],'nonce':cfg['nonce'],'argv':cfg['argv'],'uid':os.getuid(),'gid':os.getgid(),\n 'groups':os.getgroups(),'supervisor_pid':os.getpid(),'supervisor_start':supervisor_start,\n 'leader_pid':None if leader is None else leader.pid,'leader_start':leader_start,'leader_rc':leader_rc,\n 'leader_reaped':reaped,'timeout':timed_out,'controlled_rc':124 if timed_out else leader_rc,\n 'elapsed':time.monotonic()-start,'deadline':cfg['deadline'],'recovery':cfg['recovery'],\n 'pg_absent':pg_absent,'remaining':remaining,'exceptions':errors,\n 'descendants':[[p,t['start'],signals.get((p,t['start']),0)] for p,t in tracked.items() if leader is None or p!=leader.pid],\n 'adopted_waits':waits,'stdout_len':len(output),'stdout_sha256':hashlib.sha256(output).hexdigest(),\n 'stderr_len':len(diagnostic),'stderr_sha256':hashlib.sha256(diagnostic).hexdigest()}\nwire={'meta':meta,'stdout':base64.b64encode(bz2.compress(output)).decode('ascii'),\n 'stderr':base64.b64encode(bz2.compress(diagnostic)).decode('ascii')}\nsys.stdout.write(json.dumps(wire,separators=(',',':'))+'\\n')\n"
CLEANUP = 'import shutil,sys; shutil.rmtree(sys.argv[1])'
ABSENCE = 'import os,sys\ntry: os.lstat(sys.argv[1])\nexcept FileNotFoundError: sys.exit(0)\nsys.exit(1)'
def identity_int(value, minimum=0):
return type(value) is int and value >= minimum
def validate_meta(meta, config, out, err):
required = {'phase','nonce','argv','uid','gid','groups','supervisor_pid','supervisor_start',
'leader_pid','leader_start','leader_rc','leader_reaped','timeout','controlled_rc',
'elapsed','deadline','recovery','pg_absent','remaining','exceptions','descendants',
'adopted_waits','stdout_len','stdout_sha256','stderr_len','stderr_sha256'}
if type(meta) is not dict or not required <= meta.keys():
raise ValueError('missing stage metadata')
if meta['phase'] != config['phase'] or meta['nonce'] != config['nonce'] or meta['argv'] != config['argv']:
raise ValueError('stage binding conflict')
for name in ('uid','gid','supervisor_pid','supervisor_start','leader_pid','leader_start'):
if not identity_int(meta[name], 1 if name not in ('uid','gid') else 0):
raise ValueError('invalid identity '+name)
if meta['supervisor_pid'] == meta['leader_pid']:
raise ValueError('supervisor and leader identical')
isolated = os.environ.get('ROLLOUT_GRADE_ISOLATION') == 'uid65534'
expected_identity = (65534,65534,[]) if isolated else (os.getuid(),os.getgid(),os.getgroups())
if type(meta['groups']) is not list or any(type(x) is not int or x < 0 for x in meta['groups']):
raise ValueError('invalid groups')
if (meta['uid'],meta['gid'],meta['groups']) != expected_identity:
raise ValueError('execution identity conflict')
if type(meta['deadline']) is not int or meta['deadline'] != config['deadline']:
raise ValueError('deadline conflict')
if type(meta['recovery']) is not int or meta['recovery'] != RECOVERY_SECONDS:
raise ValueError('recovery conflict')
elapsed = meta['elapsed']
if type(elapsed) not in (int,float) or not math.isfinite(elapsed) or not 0 <= elapsed <= config['deadline']+RECOVERY_SECONDS+2:
raise ValueError('invalid elapsed')
for name in ('timeout','leader_reaped','pg_absent'):
if type(meta[name]) is not bool:
raise ValueError('invalid boolean '+name)
for name in ('leader_rc','controlled_rc'):
if type(meta[name]) is not int:
raise ValueError('invalid return code '+name)
if meta['controlled_rc'] != (124 if meta['timeout'] else meta['leader_rc']):
raise ValueError('return code conflict')
for name in ('remaining','exceptions','descendants','adopted_waits'):
if type(meta[name]) is not list:
raise ValueError('invalid list '+name)
for row in meta['descendants']:
if type(row) is not list or len(row) != 3 or not all(identity_int(x,1) for x in row[:2]) or not identity_int(row[2]):
raise ValueError('invalid descendant record')
for row in meta['adopted_waits']:
if type(row) is not list or len(row) != 3 or not identity_int(row[0],1) or row[1] is not None or type(row[2]) is not int:
raise ValueError('invalid adopted wait record')
for name,data in (('stdout',out),('stderr',err)):
if not identity_int(meta[name+'_len']) or meta[name+'_len'] != len(data):
raise ValueError('invalid IO length')
if type(meta[name+'_sha256']) is not str or meta[name+'_sha256'] != hashlib.sha256(data).hexdigest():
raise ValueError('invalid IO digest')
if meta['exceptions'] or meta['remaining'] or not meta['leader_reaped'] or not meta['pg_absent']:
raise ValueError('stage recovery or exception failure')
if meta['timeout'] or meta['leader_rc'] != 0 or meta['controlled_rc'] != 0:
raise ValueError('controlled timeout' if meta['timeout'] else 'leader nonzero exit')
DIAGNOSTIC_OUTPUT = None
COMPILER_SECONDS = 20
CANDIDATE_SECONDS = 10
CLEANUP_SECONDS = 5
ABSENCE_SECONDS = 5
def save_diagnostic(name,data):
if DIAGNOSTIC_OUTPUT is not None:
(Path(DIAGNOSTIC_OUTPUT)/name).write_bytes(data)
def execute_stage(phase,argv,cwd,deadline,payload,evidence):
nonce=os.urandom(8).hex()
config=dict(phase=phase,argv=argv,cwd=str(cwd),deadline=deadline,recovery=RECOVERY_SECONDS,nonce=nonce)
wrapper=[sys.executable,'-I','-c',SUPERVISOR,json.dumps(config,separators=(',',':'))]
raw=subprocess.run(wrapper,input=payload,capture_output=True,timeout=deadline+RECOVERY_SECONDS+5)
entry=dict(phase=phase,nonce=nonce,wrapper_rc=raw.returncode,wire_len=len(raw.stdout),
wire_sha256=hashlib.sha256(raw.stdout).hexdigest(),wrapper_stderr_len=len(raw.stderr),
wrapper_stderr_sha256=hashlib.sha256(raw.stderr).hexdigest())
evidence.append(entry)
save_diagnostic(phase+'.wire',raw.stdout)
save_diagnostic(phase+'.wrapper-stderr',raw.stderr)
if raw.returncode!=0:raise ValueError(phase+' supervisor nonzero')
wire=json.loads(raw.stdout)
out=bz2.decompress(base64.b64decode(wire['stdout'],validate=True))
err=bz2.decompress(base64.b64decode(wire['stderr'],validate=True))
save_diagnostic(phase+'.stdout',out);save_diagnostic(phase+'.stderr',err)
entry['meta']=wire['meta']
validate_meta(entry['meta'],config,out,err)
return out,err
from fractions import Fraction
import re
def commands_for_check():
commands=['H','L','S 1','P 1','C 1 0 0','B 1 0 0','Z 1','X 0','Y 1 2',
'D 1 9 5 32000 -100000 200000 1','C 1 0 100000','C 1 0 0','C 1 0 -40000',
'C 1 1 212000','C 1 1 32000','C 1 1 -40000','S 1','P 1','L']
for p in [(2,1,2,0,-100,100,3),(3,-9,5,-32000,-100000,200000,2),
(4,1000,1,1000000,-1000000,1000000,0),(5,1,1000,-1,-1000000,1000000,3),
(6,1,1,0,0,0,0)]:commands.append('D '+' '.join(map(str,p)))
commands+=['D 7 1 1 0 -100 100 3','D 1 0 1 0 -100 100 3','P 1','L',
'C 2 0 1','C 2 0 -1','C 2 1 50','C 2 1 51','C 4 0 1000000','S 4',
'C 1 2 0','C 0 0 0','C 256 0 0','B 1 2 0','B 222 3 0',
'B 1 0 3 0 200001 1','S 1','B 1 0 3 -100000 0 200000','S 1',
'Y 1 7','Y 99 0','Y 99 2','Y 1 2','P 2','S 2','Y 1 1','S 1',
'X 3','Y 2 3','P 3','L','Z 2','S 2','R','L','R','L']
# Deterministic Cartesian cases emphasize exact half bins, signed gains,
# pre-round domain boundaries and full replacement transactions.
for n,d,o in [(9,5,32000),(5,9,-32000),(-7,3,17),(3,2,0),(1,2,0),
(1,1000,999999),(-1000,1,-1000000),(1000,999,-13)]:
for dec in range(4):
commands+=['R',f'D 1 {n} {d} {o} -1000000 1000000 {dec}']
for x in [-1000001,-1000000,-500001,-1001,-501,-1,0,1,5,501,1001,500001,1000000,1000001]:
commands.append(f'C 1 0 {x}')
for y in [-1000000000,-1000001,-32001,-1,0,1,17,32000,212000,1000001,1000000000]:
commands.append(f'C 1 1 {y}')
commands+=['B 1 0 16 -1000000 -999999 -500001 -1001 -501 -1 0 1 5 501 1001 10001 500001 999999 1000000 42','B 1 0 0','B 1 1 0','B 1 0 4 0 1 -1 500','B 1 0 3 1 1000001 0','S 1','L']
rng=random.Random(2026102503)
for k in range(28):
commands.append('R')
ids=rng.sample(range(1,256),6)
for i in ids:
n=rng.choice([-999,-17,-3,-1,1,3,11,999]);d=rng.choice([1,2,3,7,13,1000]);o=rng.randint(-1000000,1000000)
lo=rng.randint(-1000000,0);hi=rng.randint(0,1000000);dec=rng.randrange(4)
commands.append(f'D {i} {n} {d} {o} {lo} {hi} {dec}')
for i in ids:
commands += [f'C {i} 0 {rng.randint(-1000000,1000000)}',f'C {i} 1 {rng.randint(-1000000,1000000)}',
f'B {i} 0 4 0 1 -1 1000001',f'S {i}',f'P {i}']
commands += [f'Y {ids[0]} {ids[1]}',f'Z {ids[2]}',f'X {ids[3]}','L',f'S {ids[3]}']
# Each invalid field is independent, must preserve a previously valid profile.
commands+=['R','D 1 2 3 12 -100 100 3','C 1 0 0']
for p in [(0,1,1,0,-1,1,0),(256,1,1,0,-1,1,0),(1,0,1,0,-1,1,0),
(1,-1001,1,0,-1,1,0),(1,1001,1,0,-1,1,0),(1,1,0,0,-1,1,0),
(1,1,1001,0,-1,1,0),(1,1,1,-1000001,-1,1,0),(1,1,1,1000001,-1,1,0),
(1,1,1,0,-1000001,1,0),(1,1,1,0,-1,1000001,0),(1,1,1,0,2,1,0),
(1,1,1,0,-1,1,-1),(1,1,1,0,-1,1,4)]:
commands+=['D '+' '.join(map(str,p)),'P 1','S 1','L']
return commands
NUMBER=re.compile(rb'[+-]?[0-9]+')
def parse_number(token):
if NUMBER.fullmatch(token) is None:raise ValueError('non-decimal stdout token')
negative=token[:1]==b'-'
digits=token[1:] if token[:1] in (b'+',b'-') else token
digits=digits.lstrip(b'0') or b'0'
if len(digits)>19:raise ValueError('stdout value outside observable integer range')
value=int(digits)
return -value if negative else value
def parse_observations(out):
lines=out.split(b'\n')
if lines[-1:]==[b'']:lines.pop()
rows=[]
for line in lines:
pieces=re.split(rb'[ \t\r]+',line.strip(b' \t\r'))
if not pieces or pieces==[b'']:raise ValueError('blank observation line')
rows.append([parse_number(token) for token in pieces])
return rows
OPS={'D':0,'X':1,'C':2,'B':3,'S':4,'L':5,'Z':6,'R':7,'P':8,'Y':9,'H':10}
def round_away(value, quantum):
v=value/quantum
sign=-1 if v<0 else 1
a=abs(v)
n,r=divmod(a.numerator,a.denominator)
return sign*(n+(2*r>=a.denominator))*quantum
def valid_profile(p):
i,n,d,o,l,h,dec=p
return 1<=i<=255 and 0<abs(n)<=1000 and 1<=d<=1000 and abs(o)<=1000000 and -1000000<=l<=h<=1000000 and 0<=dec<=3
def evaluate(p,direction,value):
if direction not in (0,1) or abs(value)>1000000000:return 1,None
_,n,d,o,l,h,dec=p
x=Fraction(value) if direction==0 else Fraction((value-o)*d,n)
if not l<=x<=h:return 4,None
y=Fraction(value*n,d)+o if direction==0 else x
result=round_away(y,10**(3-dec))
return (5,None) if abs(result)>1000000000 else (0,result)
def model(commands):
profiles={}; events={}; rejects={}; revision=0; rows=[]
def stats(i):
v=events[i]
return [len(v),rejects[i],int(bool(v)),min(v) if v else 0,max(v) if v else 0,sum(v),v[-1] if v else 0]
for line in commands:
w=line.split(); op=w[0]; a=list(map(int,w[1:])); row=[OPS[op]]; status=0; extra=[]
i=a[0] if a else 0
if op=='H':
extra=[1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,4,1234567,4,1234567,1234567,0,0,6,0,0,0,0,0,0,1,1,0,6,0,2,1]
elif op=='D':
if not valid_profile(a):status=1
elif i not in profiles and len(profiles)==6:status=3
else:profiles[i]=a;events[i]=[];rejects[i]=0;revision+=1
elif op in ('X','Z','P','S'):
if not 1<=i<=255:status=1
elif i not in profiles:status=2
elif op=='X':del profiles[i];del events[i];del rejects[i];revision+=1
elif op=='Z':events[i]=[];rejects[i]=0
elif op=='P':extra=profiles[i]
else:extra=stats(i)
elif op=='Y':
dest=a[1]
if not 1<=i<=255 or not 1<=dest<=255:status=1
elif i not in profiles:status=2
elif dest not in profiles and len(profiles)==6:status=3
else:profiles[dest]=[dest]+profiles[i][1:];events[dest]=[];rejects[dest]=0;revision+=1
elif op in ('C','B'):
direction=a[1]; values=a[2:] if op=='C' else a[3:]
if not 1<=i<=255 or direction not in (0,1) or any(abs(v)>1000000000 for v in values):status=1
elif i not in profiles:status=2
else:
result=[evaluate(profiles[i],direction,v) for v in values]
status=next((s for s,v in result if s),0)
if not status:
out=[v for s,v in result];events[i].extend(out)
extra=out if op=='C' else [len(out)]+out
if status:
extra=[1234567] if op=='C' else [len(values)]+[1234567]*len(values)
if i in profiles:rejects[i]+=1
elif op=='L':
extra=[revision,len(profiles),sum(len(v) for v in events.values()),sum(rejects.values())]+sorted(profiles)
elif op=='R':profiles={};events={};rejects={};revision+=1
rows.append(row+[status]+extra)
return rows
CANDIDATE_FILES = ['src/unit_profile.c', 'src/unit_registry.c']
HEADER = '#ifndef UNIT_PROFILE_H\n#define UNIT_PROFILE_H\n#include <stddef.h>\n#include <stdint.h>\n#define UP_CAPACITY 6\n#define UP_BATCH_LIMIT 16\n#define UP_VALUE_LIMIT INT64_C(1000000000)\n#define UP_DOMAIN_LIMIT INT64_C(1000000)\ntypedef enum {\n UP_OK = 0,\n UP_ARG = 1,\n UP_MISSING = 2,\n UP_FULL = 3,\n UP_DOMAIN = 4,\n UP_RANGE = 5\n} up_status;\ntypedef struct {\n int id;\n int numerator;\n int denominator;\n int64_t offset;\n int64_t low;\n int64_t high;\n int decimals;\n} up_profile;\ntypedef struct {\n int64_t accepted;\n int64_t rejected;\n int has_value;\n int64_t minimum;\n int64_t maximum;\n int64_t sum;\n int64_t last;\n} up_statistics;\ntypedef struct {\n int occupied;\n up_profile profile;\n up_statistics statistics;\n} up_entry;\ntypedef struct {\n up_entry entries[UP_CAPACITY];\n uint32_t revision;\n} up_bank;\ntypedef struct {\n uint32_t revision;\n size_t count;\n int64_t accepted;\n int64_t rejected;\n} up_summary;\n/* Pure profile helpers: invalid/null configuration gives ARG from evaluate.\n * Validation returns 1 exactly for the profile domain in the contract.\n * Evaluation never updates a bank or writes output after a failure. */\nint up_valid_id(int id);\nint up_valid_direction(int direction);\nint up_valid_input(int64_t input);\nint up_profile_valid(const up_profile *profile);\nup_status up_evaluate(const up_profile *profile, int direction,\n int64_t input, int64_t *output);\n/* Bank is always an initialized, non-null caller-owned object. */\nvoid up_initialize(up_bank *bank);\nvoid up_reset(up_bank *bank);\nup_status up_define(up_bank *bank, const up_profile *profile);\nup_status up_erase(up_bank *bank, int id);\nup_status up_lookup(const up_bank *bank, int id, up_profile *profile);\nup_status up_statistics_get(const up_bank *bank, int id,\n up_statistics *statistics);\nup_status up_statistics_clear(up_bank *bank, int id);\nup_status up_summary_get(const up_bank *bank, up_summary *summary);\nsize_t up_enumerate(const up_bank *bank, int *ids, size_t capacity);\nup_status up_convert(up_bank *bank, int id, int direction,\n int64_t input, int64_t *output);\nup_status up_batch(up_bank *bank, int id, int direction,\n const int64_t *inputs, size_t count, int64_t *outputs);\nup_status up_duplicate(up_bank *bank, int source_id, int destination_id);\n#endif\n'
OBSERVER = '#include "unit_profile.h"\n#include <inttypes.h>\n#include <stdio.h>\nstatic int read_int(int *value)\n{\n return scanf("%d", value) == 1;\n}\nstatic int read_value(int64_t *value)\n{\n return scanf("%" SCNd64, value) == 1;\n}\nstatic void edge_observations(void)\n{\n up_bank b;\n up_profile p = {1, 3, 2, 100, -1000, 1000, 3};\n up_statistics statistics;\n up_summary summary;\n int64_t output = 1234567;\n int64_t inputs[2] = {0, 1001};\n int64_t outputs[2] = {1234567, 1234567};\n int ids[1] = {-7};\n up_initialize(&b);\n printf("10 0 %d", up_profile_valid(&p));\n printf(" %d", up_valid_id(0));\n printf(" %d", up_valid_direction(2));\n printf(" %d", up_valid_input(INT64_C(1000000001)));\n printf(" %d", up_evaluate(NULL, 0, 0, &output));\n printf(" %d", up_evaluate(&p, 0, 0, NULL));\n printf(" %d", up_define(&b, NULL));\n printf(" %d", up_define(&b, &p));\n printf(" %d", up_convert(&b, 1, 0, 0, NULL));\n printf(" %d", up_batch(&b, 1, 0, NULL, 1, outputs));\n printf(" %d", up_batch(&b, 1, 0, inputs, 1, NULL));\n printf(" %d", up_batch(&b, 1, 0, inputs, 17, outputs));\n printf(" %d", up_batch(&b, 1, 0, NULL, 0, NULL));\n printf(" %d", up_lookup(&b, 1, NULL));\n printf(" %d", up_statistics_get(&b, 1, NULL));\n printf(" %d", up_summary_get(&b, NULL));\n printf(" %zu", up_enumerate(&b, NULL, 1));\n printf(" %zu", up_enumerate(&b, NULL, 0));\n printf(" %d", up_convert(&b, 1, 0, 1001, &output));\n printf(" %" PRId64, output);\n printf(" %d", up_batch(&b, 1, 0, inputs, 2, outputs));\n printf(" %" PRId64 " %" PRId64, outputs[0], outputs[1]);\n printf(" %d", up_statistics_get(&b, 1, &statistics));\n printf(" %" PRId64 " %" PRId64 " %d %" PRId64 " %" PRId64\n " %" PRId64 " %" PRId64, statistics.accepted,\n statistics.rejected, statistics.has_value, statistics.minimum,\n statistics.maximum, statistics.sum, statistics.last);\n printf(" %d", up_summary_get(&b, &summary));\n printf(" %" PRIu32 " %zu %" PRId64 " %" PRId64, summary.revision,\n summary.count, summary.accepted, summary.rejected);\n p.id = 2;\n printf(" %d", up_define(&b, &p));\n printf(" %zu", up_enumerate(&b, ids, 1));\n printf(" %d\\n", ids[0]);\n}\nint main(void)\n{\n up_bank bank;\n char command;\n up_initialize(&bank);\n while (scanf(" %c", &command) == 1) {\n int id = 0;\n int direction = 0;\n up_status status = UP_ARG;\n if (command == \'H\') {\n edge_observations();\n } else if (command == \'D\') {\n up_profile p;\n if (!read_int(&p.id) || !read_int(&p.numerator) ||\n !read_int(&p.denominator) || !read_value(&p.offset) ||\n !read_value(&p.low) || !read_value(&p.high) ||\n !read_int(&p.decimals)) return 2;\n status = up_define(&bank, &p);\n printf("0 %d\\n", status);\n } else if (command == \'X\' || command == \'Z\') {\n if (!read_int(&id)) return 2;\n status = command == \'X\' ? up_erase(&bank, id) :\n up_statistics_clear(&bank, id);\n printf("%d %d\\n", command == \'X\' ? 1 : 6, status);\n } else if (command == \'C\') {\n int64_t input;\n int64_t output = INT64_C(1234567);\n if (!read_int(&id) || !read_int(&direction) ||\n !read_value(&input)) return 2;\n status = up_convert(&bank, id, direction, input, &output);\n printf("2 %d", status);\n printf(" %" PRId64, output);\n putchar(\'\\n\');\n } else if (command == \'B\') {\n int count;\n int64_t inputs[UP_BATCH_LIMIT];\n int64_t outputs[UP_BATCH_LIMIT];\n if (!read_int(&id) || !read_int(&direction) ||\n !read_int(&count) || count < 0 || count > UP_BATCH_LIMIT) return 2;\n for (int i = 0; i < count; ++i) {\n if (!read_value(&inputs[i])) return 2;\n outputs[i] = INT64_C(1234567);\n }\n status = up_batch(&bank, id, direction, inputs,\n (size_t)count, outputs);\n printf("3 %d", status);\n {\n printf(" %d", count);\n for (int i = 0; i < count; ++i)\n printf(" %" PRId64, outputs[i]);\n }\n putchar(\'\\n\');\n } else if (command == \'S\') {\n up_statistics s;\n if (!read_int(&id)) return 2;\n status = up_statistics_get(&bank, id, &s);\n printf("4 %d", status);\n if (status == UP_OK)\n printf(" %" PRId64 " %" PRId64 " %d %" PRId64\n " %" PRId64 " %" PRId64 " %" PRId64,\n s.accepted, s.rejected, s.has_value, s.minimum,\n s.maximum, s.sum, s.last);\n putchar(\'\\n\');\n } else if (command == \'L\') {\n up_summary s;\n int ids[UP_CAPACITY];\n status = up_summary_get(&bank, &s);\n size_t count = up_enumerate(&bank, ids, UP_CAPACITY);\n printf("5 %d", status);\n if (status == UP_OK) {\n printf(" %" PRIu32 " %zu %" PRId64 " %" PRId64,\n s.revision, s.count, s.accepted, s.rejected);\n for (size_t i = 0; i < count; ++i) printf(" %d", ids[i]);\n }\n putchar(\'\\n\');\n } else if (command == \'P\') {\n up_profile p;\n if (!read_int(&id)) return 2;\n status = up_lookup(&bank, id, &p);\n printf("8 %d", status);\n if (status == UP_OK)\n printf(" %d %d %d %" PRId64 " %" PRId64 " %" PRId64 " %d",\n p.id, p.numerator, p.denominator, p.offset,\n p.low, p.high, p.decimals);\n putchar(\'\\n\');\n } else if (command == \'Y\') {\n int destination;\n if (!read_int(&id) || !read_int(&destination)) return 2;\n status = up_duplicate(&bank, id, destination);\n printf("9 %d\\n", status);\n } else if (command == \'R\') {\n up_reset(&bank);\n puts("7 0");\n } else {\n return 2;\n }\n }\n return ferror(stdin) ? 2 : 0;\n}\n'
def main():
evidence=[];failures=[];scratch=None;business_ok=False
try:
commands=commands_for_check()
expected=model(commands)
payload=('\n'.join(commands)+'\n').encode('ascii')
source_root=Path(sys.argv[1])
source_contents={name:(source_root/name).read_bytes() for name in CANDIDATE_FILES}
scratch=Path(tempfile.mkdtemp(prefix='unit-profile-'))
for name,data in source_contents.items():
(scratch/Path(name).name).write_bytes(data)
(scratch/'unit_profile.h').write_text(HEADER)
(scratch/'observe.c').write_text(OBSERVER)
# The bos hook has already handed the root to the candidate identity.
# Files are readable and directly removable through the owned root.
for name in ['unit_profile.c','unit_registry.c','unit_profile.h','observe.c']:
os.chmod(scratch/name,0o644)
compiler=['gcc','-std=c11','-O2','-Wall','-Wextra','-pedantic','-I',str(scratch),
str(scratch/'unit_profile.c'),str(scratch/'unit_registry.c'),str(scratch/'observe.c'),
'-o',str(scratch/'program')]
execute_stage('compiler',compiler,scratch,COMPILER_SECONDS,b'',evidence)
out,err=execute_stage('candidate',[str(scratch/'program')],scratch,CANDIDATE_SECONDS,payload,evidence)
actual=parse_observations(out)
if actual!=expected:
limit=min(len(actual),len(expected))
first=next((i for i in range(limit) if actual[i]!=expected[i]),limit)
failures.append('first raw observation difference row '+str(first)+' actual='+repr(actual[first] if first<len(actual) else None)+' expected='+repr(expected[first] if first<len(expected) else None))
else:business_ok=True
except BaseException as error:
failures.append(type(error).__name__+': '+str(error))
finally:
if scratch is not None:
try:execute_stage('cleanup',[sys.executable,'-I','-c',CLEANUP,str(scratch)],'/',CLEANUP_SECONDS,b'',evidence)
except BaseException as error:failures.append('cleanup '+type(error).__name__+': '+str(error))
try:execute_stage('absence',[sys.executable,'-I','-c',ABSENCE,str(scratch)],'/',ABSENCE_SECONDS,b'',evidence)
except BaseException as error:failures.append('absence '+type(error).__name__+': '+str(error))
record={'scratch':None if scratch is None else str(scratch),'evidence':evidence,'business_ok':business_ok,'failures':failures}
save_diagnostic('parent-record.json',json.dumps(record,sort_keys=True).encode())
packed=base64.b64encode(bz2.compress(json.dumps(record,separators=(',',':')).encode())).decode('ascii')
sys.stderr.write('UNIT_PROFILE_EVIDENCE_BZ2='+packed+'\n')
if business_ok and not failures:
print('PASS');return 0
print('FAIL '+('; '.join(failures) if failures else 'business incomplete')[:500]);return 1
if __name__=='__main__':sys.exit(main())