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

504 lines
22 KiB
Python

import base64
import bz2
import hashlib
import json
import math
import os
from pathlib import Path
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
RECOVERY_SECONDS = 3
RECORD_WIRE = False
SUPERVISOR = r'''
import base64,bz2,ctypes,hashlib,json,os,signal,subprocess,sys,time
cfg=json.loads(sys.argv[1]); start=time.monotonic(); errors=[]; tracked={}; signals={}; waits={}
leader=None; leader_start=None; output=b''; diagnostic=b''; timed_out=False; drained=False
reaped=False; leader_rc=None; remaining=[]; pg_absent=False
def fault(op, error):
errors.append([op,type(error).__name__,str(error)])
def exact(pid):
try:
with open('/proc/%d/stat'%pid,'rb') as stream: data=stream.read()
words=data[data.rfind(b')')+2:].split()
return {'pid':pid,'state':words[0].decode('ascii'),'ppid':int(words[1]),'pg':int(words[2]),'start':int(words[19])}
except (FileNotFoundError,ProcessLookupError): return None
def table_now():
result={}
for name in os.listdir('/proc'):
if name.isascii() and name.isdigit():
value=exact(int(name))
if value is not None: result[value['pid']]=value
return result
def closure(table, supervisor, remembered):
roots={supervisor}
for pid,old in remembered.items():
current=table.get(pid)
if current and current['start']==old['start'] and current['state'] not in ('Z','X'):
roots.add(pid)
found={}
changed=True
while changed:
changed=False
for pid,current in table.items():
if pid!=supervisor and pid not in found and (current['ppid'] in roots or pid in roots):
found[pid]=current; roots.add(pid); changed=True
return found
def discover():
table=table_now(); found=closure(table,os.getpid(),tracked)
for pid,current in found.items():
if pid not in tracked or tracked[pid]['start']!=current['start']:
tracked[pid]=dict(current)
return table,found
def send_fresh(pid, token):
current=exact(pid)
if current is None or current['start']!=token['start'] or current['state'] in ('Z','X'): return
os.kill(pid,signal.SIGKILL)
signals[(pid,token['start'])]=signals.get((pid,token['start']),0)+1
def own_wait():
global reaped,leader_rc
if leader is not None:
value=leader.poll()
if value is not None:
leader_rc=leader.wait(timeout=0)
reaped=True
def adopted_wait():
if leader is not None and not reaped: return
while True:
try: pid,status=os.waitpid(-1,os.WNOHANG)
except ChildProcessError: break
if pid==0: break
waits[pid]=os.waitstatus_to_exitcode(status)
supervisor_start=exact(os.getpid())['start']
try:
libc=ctypes.CDLL(None,use_errno=True)
if libc.prctl(36,1,0,0,0)!=0: raise OSError(ctypes.get_errno(),'subreaper')
leader=subprocess.Popen(cfg['argv'],cwd=cfg['cwd'],stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True)
info=exact(leader.pid)
if info is None: raise RuntimeError('leader identity disappeared before capture')
leader_start=info['start']; tracked[leader.pid]=info
payload=sys.stdin.buffer.read()
first=True
while True:
try:
output,diagnostic=leader.communicate(input=payload if first else None,timeout=0.04)
drained=True; own_wait(); break
except subprocess.TimeoutExpired:
first=False
own_wait()
discover()
if time.monotonic()-start>=cfg['deadline']:
timed_out=True; break
except BaseException as error:
fault('execute',error)
finally:
recovery_end=time.monotonic()+cfg['recovery']
while True:
try: own_wait()
except BaseException as error: fault('own_wait',error)
found={}
try: _,found=discover()
except BaseException as error: fault('discover',error)
for pid,token in list(found.items()):
try: send_fresh(pid,token)
except (FileNotFoundError,ProcessLookupError): pass
except BaseException as error: fault('signal',error)
try: own_wait()
except BaseException as error: fault('own_wait',error)
try: adopted_wait()
except BaseException as error: fault('adopted_wait',error)
if leader is not None and not drained:
try:
output,diagnostic=leader.communicate(timeout=0.03)
drained=True; own_wait()
except subprocess.TimeoutExpired: pass
except BaseException as error: fault('drain',error)
try:
table,found=discover()
remaining=[[p,v['start'],v['state']] for p,v in found.items()]
pg_absent=leader is not None and not any(v['pg']==leader.pid for v in table.values())
except BaseException as error:
fault('absence',error); remaining=[['unknown']]; pg_absent=False
if reaped and drained and not remaining and pg_absent: break
if time.monotonic()>=recovery_end:
fault('recovery',RuntimeError('deadline with unconfirmed closure')); break
time.sleep(0.01)
meta={'phase':cfg['phase'],'nonce':cfg['nonce'],'argv':cfg['argv'],
'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups(),
'supervisor_pid':os.getpid(),'supervisor_start':supervisor_start,
'leader_pid':None if leader is None else leader.pid,'leader_start':leader_start,
'leader_rc':leader_rc,'leader_reaped':reaped,'timeout':timed_out,
'controlled_rc':124 if timed_out else leader_rc,'elapsed':time.monotonic()-start,
'deadline':cfg['deadline'],'recovery':cfg['recovery'],
'pg_absent':pg_absent,'remaining':remaining,'exceptions':errors,
'descendants':[[p,t['start'],signals.get((p,t['start']),0)]
for p,t in tracked.items() if leader is None or p!=leader.pid],
'adopted_waits':[[p,None,status] for p,status in waits.items()],
'stdout_len':len(output),'stdout_sha256':hashlib.sha256(output).hexdigest(),
'stderr_len':len(diagnostic),'stderr_sha256':hashlib.sha256(diagnostic).hexdigest()}
wire={'meta':meta,'stdout':base64.b64encode(bz2.compress(output)).decode('ascii'),
'stderr':base64.b64encode(bz2.compress(diagnostic)).decode('ascii')}
sys.stdout.write(json.dumps(wire,separators=(',',':'))+'\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',
'stdout_len','stdout_sha256','stderr_len','stderr_sha256','adopted_waits'}
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'):
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')
if type(meta['adopted_waits']) is not list:
raise ValueError('invalid adopted waits')
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 unknown identity')
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')
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_argv = [sys.executable,'-I','-c',SUPERVISOR,json.dumps(config,separators=(',',':'))]
raw = subprocess.run(wrapper_argv,input=payload,capture_output=True,timeout=deadline+RECOVERY_SECONDS+5)
# Preserve actual wrapper facts before touching or trusting its wire protocol.
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())
entry['body_retention'] = 'not retained; actual captured byte lengths and SHA256 only'
evidence.append(entry)
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))
meta = wire['meta']
entry['meta'] = meta
validate_meta(meta,config,out,err)
return out,err
CANDIDATES = ('config.h','config_table.c','config_parse.c','config_load.c')
COMPILE_DEADLINE = 15
CANDIDATE_DEADLINE = 12
CLEANUP_DEADLINE = 8
ABSENCE_DEADLINE = 8
def ascii_decimal(token, minimum, maximum):
if type(token) is not str or re.fullmatch(r'[+-]?[0-9]+', token, flags=re.ASCII) is None:
raise ValueError('decimal grammar')
negative = token.startswith('-')
digits = token.lstrip('+-').lstrip('0') or '0'
if len(digits) > max(len(str(abs(minimum))),len(str(abs(maximum)))):
raise ValueError('decimal range')
value = int(('-' if negative else '') + digits)
if not minimum <= value <= maximum:
raise ValueError('decimal range')
return value
def objects(raw):
text = raw.decode('utf-8', errors='strict')
decoder = json.JSONDecoder()
offset = 0
found = []
while offset < len(text):
while offset < len(text) and text[offset] in ' \t\r\n':
offset += 1
if offset == len(text):
break
obj, offset = decoder.raw_decode(text, offset)
found.append(obj)
return found
def model_file(data, old, revision):
table = dict(old)
section = 'global'
assignments = deletions = 0
name = re.compile(rb'[a-z][a-z0-9_]{0,30}\Z')
for raw in data.split(b'\n'):
if len(raw) > 255 or any(c > 126 or c < 32 and c not in (9,13) for c in raw):
return None
line = raw.strip(b' \t\r')
if not line or line.startswith(b'#'):
continue
if line.startswith(b'['):
end = line.find(b']')
if end < 0 or line[end+1:].strip(b' \t\r'):
return None
token = line[1:end].strip(b' \t\r')
if name.fullmatch(token) is None:
return None
section = token.decode('ascii')
continue
if line.startswith(b'!'):
token = line[1:].strip(b' \t\r')
if name.fullmatch(token) is None:
return None
table.pop((section,token.decode('ascii')),None)
revision += 1
deletions += 1
continue
if b'=' not in line:
return None
key,value = [part.strip(b' \t\r') for part in line.split(b'=',1)]
if name.fullmatch(key) is None or len(value) > 127 or any(c < 32 or c > 126 for c in value):
return None
identity = section,key.decode('ascii')
if identity not in table and len(table) == 64:
return None
table[identity] = value.decode('ascii')
assignments += 1
revision += 1
return table, revision, assignments, deletions
def make_cases(rng):
files = []
def add(data):
files.append(data if data is None else data.encode('ascii') if isinstance(data,str) else data)
add('')
add('# initial\n[service]\nname = camera\nrate = 12\n')
add('[service]\nrate = 24\nlabel = north camera\n')
for i in range(96):
section = 's%d' % rng.randrange(4)
key = 'k%d' % rng.randrange(8)
value = 'v%d_%d' % (i,rng.randrange(100000))
text = '[ %s ]\r\n\t%s = %s\t\r\n' % (section,key,value)
if i % 9 == 0:
text += '! absent\n'
add(text)
if i % 17 == 0:
add(None)
# Independent malformed transactions, each starts with visible mutation.
add('[broken]\npoison = should_rollback\nnot an assignment\n')
add('[service]\nrate = 0\nUPPER = bad\n')
add(b'[broken]\nzero = rollback\nnul = x\x00y\n')
add('[broken]\nlong = rollback\n' + 'x'*256 + '\n')
add('[broken]\nvalue = rollback\nbig = ' + 'y'*128 + '\n')
add('[broken]\nsection = rollback\n[bad] trailing\n')
add('[broken]\ncontrol = rollback\na = x\ty\n')
add('[service]\n! rate\nlabel = value=contains=#data\n')
# Remove all normal identities, then fill exact capacity, overflow atomically.
lines = ['[service]','! name','! rate','! label']
for s in range(4):
lines += ['[s%d]'%s] + ['! k%d'%k for k in range(8)]
add('\n'.join(lines)+'\n')
add('[capacity]\n' + ''.join('key%d = value%d\n'%(i,i) for i in range(64)))
add('[capacity]\nkey0 = update_must_rollback\nextra = overflow\n')
add('[capacity]\nkey63 = replacement\n! key63\nnew_key = allowed\n')
add('[capacity]\n' + ''.join('! key%d\n'%i for i in range(64))+'! new_key\n')
add('[final]\n'+'a'*31+' = '+'z'*127+'\nempty =\nquote = a"b\\c\n')
add(' \t\r\n#'+'c'*254+'\n[global]\nlast = final_without_lf')
add(None)
return files
def oracle(files, repeats):
table = {}
revision = 0
stats = dict.fromkeys(('attempted','opened','open_failed','parsed','rejected','bytes','assignments','deletions'),0)
expected = []
for round_index in range(1,repeats+1):
status = 0
for data in files:
stats['attempted'] += 1
if data is None:
stats['open_failed'] += 1
status = -1
continue
stats['opened'] += 1
stats['bytes'] += len(data)
result = model_file(data,table,revision)
if result is None:
stats['rejected'] += 1
status = -1
else:
table,revision,assignments,deletions = result
stats['parsed'] += 1
stats['assignments'] += assignments
stats['deletions'] += deletions
expected.append(dict(round=round_index,status=status,stats=dict(stats),revision=revision,
entries=[[s,k,v] for (s,k),v in sorted(table.items())],
live=0,peak=int(stats['opened']>0),opens=stats['opened'],closes=stats['opened'],boundary=0))
return expected
def check_object(actual, expected):
if type(actual) is not dict or set(actual) != set(expected):
raise ValueError('observation object fields')
for name in expected:
if name == 'stats':
value = actual[name]
if type(value) is not dict or set(value) != set(expected[name]):
raise ValueError('stats object fields')
if any(type(x) is not int or x < 0 for x in value.values()):
raise ValueError('stats numeric types')
elif name == 'entries':
value = actual[name]
if type(value) is not list or any(type(row) is not list or len(row)!=3 or any(type(s) is not str for s in row) for row in value):
raise ValueError('entry structure')
elif type(actual[name]) is not int:
raise ValueError('numeric type '+name)
if actual[name] != expected[name]:
raise ValueError('first raw observation mismatch '+name+': '+repr(actual[name])[:280]+' expected '+repr(expected[name])[:280])
def main():
evidence = []
exceptions = []
business_ok = cleanup_ok = absence_ok = False
scratch = None
failure = None
try:
context = json.loads((Path(__file__).parent/'context.json').read_text())
sources = {name:(Path(sys.argv[1])/name).read_bytes() for name in CANDIDATES}
files = make_cases(random.Random(context['seed']))
expected = oracle(files,3)
scratch = Path(tempfile.mkdtemp(prefix='rcs-'))
# All preparation precedes first untrusted child; bos may own scratch as UID65534.
work = scratch/'work'
work.mkdir(mode=0o777)
work.chmod(0o777)
for name,data in context['support'].items():
dest = work/name
dest.parent.mkdir(parents=True,exist_ok=True)
dest.write_text(data)
for name,data in sources.items():
(work/name).write_bytes(data)
inputs = work/'inputs'
inputs.mkdir()
paths = []
for index,data in enumerate(files):
path = inputs/('%04d.cfg'%index)
paths.append(str(path))
if data is not None:
path.write_bytes(data)
manifest = work/'cases.txt'
manifest.write_text('\n'.join(paths)+'\n')
for folder in work.rglob('*'):
if folder.is_dir():
folder.chmod(0o777)
argv = ['gcc','-std=c11','-O2','-Wall','-Wextra','-Werror','main.c','observer.c',
'config_table.c','config_parse.c','config_load.c','-Wl,--wrap=fopen','-Wl,--wrap=fclose','-o','config-sequence']
execute_stage('compiler',argv,work,COMPILE_DEADLINE,b'',evidence)
stdout,stderr = execute_stage('candidate',[str(work/'config-sequence'),str(manifest),'3'],work,CANDIDATE_DEADLINE,b'',evidence)
observed = objects(stdout)
if len(observed) != len(expected):
raise ValueError('observation count')
for actual,want in zip(observed,expected):
check_object(actual,want)
business_ok = True
except BaseException as error:
exceptions.append(['business',type(error).__name__,str(error)])
failure = 'business: '+type(error).__name__+': '+str(error)
finally:
if scratch is not None:
try:
execute_stage('cleanup',[sys.executable,'-I','-c',CLEANUP,str(scratch)],'/',CLEANUP_DEADLINE,b'',evidence)
cleanup_ok = True
except BaseException as error:
exceptions.append(['cleanup',type(error).__name__,str(error)])
failure = 'cleanup: '+type(error).__name__+': '+str(error)
try:
execute_stage('absence',[sys.executable,'-I','-c',ABSENCE,str(scratch)],'/',ABSENCE_DEADLINE,b'',evidence)
absence_ok = True
except BaseException as error:
exceptions.append(['absence',type(error).__name__,str(error)])
failure = 'absence: '+type(error).__name__+': '+str(error)
passed = business_ok and cleanup_ok and absence_ok and not exceptions
# Full compact metadata, actual wire/IO nSHA; bodies intentionally absent from bos tail.
bundle = dict(phases=evidence,business_ok=business_ok,cleanup_ok=cleanup_ok,absence_ok=absence_ok,exceptions=exceptions)
encoded = base64.b85encode(bz2.compress(json.dumps(bundle,separators=(',',':')).encode())).decode('ascii')
print('RCS_EVIDENCE '+encoded,file=sys.stderr)
if passed:
print('PASS')
return 0
print('FAIL '+str(failure))
return 1
if __name__ == '__main__':
sys.exit(main())