amos f611da1e57 Batch 24: add 23 calibrated tasks written from Bos seed directions
Batch 24 (20261102-C-bos-seed-24) screened all 3078 Bos seed queries.
Only 23 themes were in scope (pure user-space reliability, at most one
task per theme); the rest were single operations or explanations,
installs and networking, system administration, ROS2, board-only or GUI
requests. Two finished drafts were withdrawn as too close to existing
tasks. Seeds supply direction only: all sources, contracts and tests are
new, and no task shares more than 14 characters with its seed text.

Each task passed the local gate and the trace6 Docker gate (5 runs per
sample class). Claude rebuilt the catalog from the calibration receipts:
23/23 USABLE. 16 of 23 are C/C++.

Only the task directories are taken; the batch worktree's lowered disk
floor in rollout/core.py stays out of main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:21:50 +08:00

556 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Private independent integer oracle; all candidate execution is in subprocesses."""
import json
from pathlib import Path
import random
import struct
import subprocess
import sys
import tempfile
PRIVATE_READ_TOKEN = 'shared-clock-private-20261102'
FILES = ['clock.hpp', 'record.cpp', 'time_math.cpp', 'page.cpp', 'service.cpp', 'clockctl.cpp']
LIMIT = 2**52 - 1
PERIOD = 2**42
MASK = 2**64 - 1
MAX_SPAN = 10000000
EMPTY = bytes(64)
SNAP_SENTINEL = [901, 902, 903, -904, 905, 906]
EST_SENTINEL = [701, 702, -703, 704, 705]
PROJ_SENTINEL = [801, 802, 803]
SAMPLE_SENTINEL = [111, 112, 113, 114, 115, 116, 117, 118]
OBSERVER = r'''
#include "clock.hpp"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace shared_clock;
namespace {
std::string hx(const std::vector<std::uint8_t>& data) {
const char* digits = "0123456789abcdef";
std::string out;
for (auto b : data) { out.push_back(digits[b >> 4]); out.push_back(digits[b & 15]); }
return out.empty() ? "-" : out;
}
std::vector<std::uint8_t> raw(const std::string& text) {
std::vector<std::uint8_t> out;
if (text == "-") return out;
for (std::size_t i = 0; i < text.size(); i += 2) {
out.push_back(static_cast<std::uint8_t>(std::stoul(text.substr(i, 2), nullptr, 16)));
}
return out;
}
std::string str(const std::string& text) {
auto data = raw(text);
return std::string(data.begin(), data.end());
}
void sample(const Sample& v) {
std::cout << ' ' << v.id << ' ' << v.local_send << ' ' << v.local_receive;
std::cout << ' ' << v.remote_receive.seconds << ' ' << v.remote_receive.fraction;
std::cout << ' ' << v.remote_send.seconds << ' ' << v.remote_send.fraction << ' ' << v.hint;
}
void snapshot(const Snapshot& v) {
std::cout << ' ' << v.sequence << ' ' << v.local << ' ' << v.remote;
std::cout << ' ' << v.offset << ' ' << v.delay << ' ' << v.id;
}
}
int main() {
Engine engines[2];
Page pages[2];
unsigned selected = 0;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream in(line);
std::string op;
in >> op;
Engine& e = engines[selected];
Page& p = pages[selected];
std::cout << op;
if (op == "U") {
in >> selected;
std::cout << ' ' << selected;
} else if (op == "E") {
unsigned fp; std::string text; in >> fp >> text;
auto record = str(text);
auto status = e.submit(record, fp);
std::cout << ' ' << static_cast<int>(status) << ' ' << hx(e.page_bytes());
std::cout << ' ' << hx(std::vector<std::uint8_t>(record.begin(), record.end()));
} else if (op == "C") {
Tick delay; in >> delay;
auto status = e.configure(Policy{delay});
std::cout << ' ' << static_cast<int>(status) << ' ' << e.policy().max_delay;
} else if (op == "R" || op == "Q") {
Snapshot value{901,902,903,-904,905,906};
auto status = op == "R" ? e.latest(value) : p.read(value);
std::cout << ' ' << static_cast<int>(status); snapshot(value);
} else if (op == "J" || op == "K") {
Tick now, age; in >> now >> age;
Projection value{801,802,803};
auto status = op == "J" ? e.project(now,age,value) : shared_clock::project(p,now,age,value);
std::cout << ' ' << static_cast<int>(status) << ' ' << value.sequence;
std::cout << ' ' << value.remote_ticks << ' ' << value.microseconds;
} else if (op == "B") {
std::cout << ' ' << hx(e.page_bytes());
} else if (op == "Y") {
std::cout << ' ' << e.summary();
} else if (op == "Z") {
e.reset(); std::cout << ' ' << hx(e.page_bytes()) << ' ' << e.policy().max_delay;
} else if (op == "L") {
std::string text; in >> text; auto data = raw(text);
auto status = p.load(data);
std::cout << ' ' << static_cast<int>(status) << ' ' << hx(p.bytes()) << ' ' << hx(data);
} else if (op == "H") {
Snapshot value; unsigned fp;
in >> value.sequence >> value.local >> value.remote >> value.offset >> value.delay >> value.id >> fp;
auto status = p.publish(value,fp);
std::cout << ' ' << static_cast<int>(status) << ' ' << hx(p.bytes()); snapshot(value);
} else if (op == "N") {
p.reset(); std::cout << ' ' << hx(p.bytes());
} else if (op == "T") {
std::uint32_t sec; unsigned frac; Tick hint, value;
in >> sec >> frac >> hint >> value;
auto status = unfold(Stamp{sec,static_cast<std::uint16_t>(frac)},hint,value);
std::cout << ' ' << static_cast<int>(status) << ' ' << value;
} else if (op == "A" || op == "M") {
std::uint64_t input, value; in >> input >> value;
auto status = op == "A" ? ticks_to_microseconds(input,value) : microseconds_to_ticks(input,value);
std::cout << ' ' << static_cast<int>(status) << ' ' << value;
} else if (op == "D") {
std::string text; in >> text; auto record = str(text);
Sample value{111,112,113,{114,115},{116,117},118};
auto status = parse_record(record,value);
std::cout << ' ' << static_cast<int>(status); sample(value);
auto formatted = format_record(value);
std::cout << ' ' << hx(std::vector<std::uint8_t>(formatted.begin(),formatted.end()));
sample(value);
std::cout << ' ' << hx(std::vector<std::uint8_t>(record.begin(),record.end()));
} else if (op == "V") {
Sample value; Policy policy; unsigned rf,sf;
in >> value.id >> value.local_send >> value.local_receive >> value.remote_receive.seconds >> rf;
in >> value.remote_send.seconds >> sf >> value.hint >> policy.max_delay;
value.remote_receive.fraction = static_cast<std::uint16_t>(rf);
value.remote_send.fraction = static_cast<std::uint16_t>(sf);
Estimate result{701,702,-703,704,705};
auto status = evaluate(value,policy,result);
std::cout << ' ' << static_cast<int>(status) << ' ' << result.local << ' ' << result.remote;
std::cout << ' ' << result.offset << ' ' << result.delay << ' ' << result.id;
sample(value); std::cout << ' ' << policy.max_delay;
} else if (op == "X") {
std::string text; in >> text; auto source = str(text);
std::vector<std::uint8_t> result{170,187};
auto status = decode_hex(source,result);
std::cout << ' ' << static_cast<int>(status) << ' ' << hx(result);
std::cout << ' ' << hx(std::vector<std::uint8_t>(source.begin(),source.end()));
auto encoded = encode_hex(result);
std::cout << ' ' << (encoded.empty() ? "-" : encoded);
std::cout << ' ' << hx(result);
std::cout << ' ' << hx(std::vector<std::uint8_t>(source.begin(),source.end()));
}
std::cout << '\n';
}
}
'''
def hx(data):
if isinstance(data, str):
data = data.encode('ascii')
return data.hex() or '-'
def decimal_fields(text):
if len(text) > 512:
return -1, None
fields = [part.strip(' \t') for part in text.split(',')]
if len(fields) != 8 or any(not x or any(c not in '0123456789' for c in x) for x in fields):
return -1, None
values = [int(x) for x in fields]
maxima = [2**32-1,LIMIT,LIMIT,2**32-1,1023,2**32-1,1023,LIMIT]
if not values[0] or any(x > m for x,m in zip(values,maxima)):
return -2, None
return 0, values
def unfold(seconds, fraction, hint):
if fraction > 1023 or hint > LIMIT:
return -2, None
residue = seconds*1024+fraction
# Enumerate the finite supported eras, independently of the candidate search strategy.
possibilities = range(residue, LIMIT+1, PERIOD)
return 0, min(possibilities, key=lambda value:(abs(value-hint),value))
def micros(ticks):
return (ticks*1000000+512)//1024
def estimate(values, policy):
ident,ls,lr,rs,rf,ss,sf,hint = values
if not ident or max(ls,lr,hint) > LIMIT or max(rf,sf)>1023 or policy>MAX_SPAN:
return -2, None
if lr < ls:
return -3, None
r1 = unfold(rs,rf,hint)[1]
r2 = unfold(ss,sf,hint)[1]
if r2<r1 or r2-r1>4096 or lr-ls>MAX_SPAN or lr-ls<r2-r1:
return -3, None
delay = (lr-ls)-(r2-r1)
if delay>policy:
return -4, None
summed = (r1-ls)+(r2-lr)
offset = (abs(summed)//2)*(1 if summed>=0 else -1)
remote = lr+offset
if not 0<=remote<=LIMIT:
return -2, None
return 0,[lr,remote,offset,delay,ident]
def snapshot_valid(values):
seq,local,remote,offset,delay,ident = values
return bool(seq and ident and local<=LIMIT and remote<=LIMIT and -LIMIT<=offset<=LIMIT and remote==local+offset and delay<=MAX_SPAN)
def fnv(data):
value = 14695981039346656037
for byte in data:
value = ((value^byte)*1099511628211)&MASK
return value
def pack(values):
seq,local,remote,offset,delay,ident = values
prefix = struct.pack('<4sHHQQQqQII',b'CKS1',1,64,seq,local,remote,offset,delay,ident,0)
return prefix+struct.pack('<Q',fnv(prefix))
def read(data):
if data == EMPTY:
return -6,None
magic,schema,size,seq,local,remote,offset,delay,ident,reserved,checksum = struct.unpack('<4sHHQQQqQIIQ',data)
values=[seq,local,remote,offset,delay,ident]
if (magic,schema,size,reserved,checksum)!=(b'CKS1',1,64,0,fnv(data[:56])) or not snapshot_valid(values):
return -7,None
return 0,values
def projection(data,now,age):
status,snapshot=read(data)
if status:
return status,None
seq,local,remote,offset,delay,ident=snapshot
if max(now,age)>LIMIT:
return -2,None
if now<local or now-local>age:
return -8,None
remote+=now-local
if remote>LIMIT:
return -2,None
return 0,[seq,remote,micros(remote)]
class Engine:
def __init__(self):
self.reset()
def reset(self):
self.page=EMPTY; self.policy=10000; self.sequence=0; self.ident=0; self.delay=0
def configure(self,value):
if value>MAX_SPAN:
return -2
self.policy=value
return 0
def submit(self,text,point):
status,values=decimal_fields(text)
if status:
return status
status,value=estimate(values,self.policy)
if status:
return status
if values[0]<=self.ident:
return -4
if self.sequence==MASK:
return -2
if point>3:
return -1
if point:
return -5
self.sequence+=1; self.ident=values[0]; self.delay=value[3]
self.page=pack([self.sequence]+value)
return 0
def summary(self):
return 'empty' if not self.sequence else 'id=%d;sequence=%d;delay=%d'%(self.ident,self.sequence,self.delay)
class Suite:
def __init__(self):
self.commands=[]; self.expected=[]; self.labels=[]; self.selected=0
self.engines=[Engine(),Engine()]; self.pages=[EMPTY,EMPTY]
def add(self,command,label,clauses):
words=command.split(); op=words[0]; args=words[1:]
e=self.engines[self.selected]; page=self.pages[self.selected]
if op=='U':
self.selected=int(args[0]); result=[self.selected]
elif op=='E':
point=int(args[0]); text=bytes.fromhex(args[1]).decode('ascii') if args[1]!='-' else ''
result=[e.submit(text,point),hx(e.page),hx(text)]
elif op=='C':
result=[e.configure(int(args[0])),e.policy]
elif op in ('R','Q'):
status,value=read(e.page if op=='R' else page); result=[status]+(value if not status else SNAP_SENTINEL)
elif op in ('J','K'):
status,value=projection(e.page if op=='J' else page,*map(int,args)); result=[status]+(value if not status else PROJ_SENTINEL)
elif op=='B': result=[hx(e.page)]
elif op=='Y': result=[e.summary()]
elif op=='Z':
e.reset(); result=[hx(e.page),e.policy]
elif op=='L':
data=bytes.fromhex(args[0]) if args[0]!='-' else b''
status=0 if len(data)==64 else -1
if not status: self.pages[self.selected]=data
result=[status,hx(self.pages[self.selected]),hx(data)]
elif op=='H':
values=list(map(int,args[:6])); point=int(args[6])
status=-1 if point>3 else -2 if not snapshot_valid(values) else -5 if point else 0
if not status: self.pages[self.selected]=pack(values)
result=[status,hx(self.pages[self.selected])]+values
elif op=='N':
self.pages[self.selected]=EMPTY; result=[hx(EMPTY)]
elif op=='T':
seconds,fraction,hint,nonce=map(int,args); status,value=unfold(seconds,fraction,hint)
result=[status,nonce if status else value]
elif op in ('A','M'):
value,nonce=map(int,args)
converted=micros(value) if op=='A' else (value*1024+500000)//1000000
status=-2 if (value>LIMIT if op=='A' else converted>LIMIT) else 0
result=[status,nonce if status else converted]
elif op=='D':
text=bytes.fromhex(args[0]).decode('ascii') if args[0]!='-' else ''
status,values=decimal_fields(text); values=SAMPLE_SENTINEL if status else values
result=[status]+values+[hx(','.join(map(str,values)))]+values+[hx(text)]
elif op=='V':
numbers=list(map(int,args)); status,value=estimate(numbers[:8],numbers[8])
result=[status]+(EST_SENTINEL if status else value)+numbers
elif op=='X':
text=bytes.fromhex(args[0]).decode('ascii') if args[0]!='-' else ''
status=-1 if len(text)%2 or any(ch not in '0123456789abcdefABCDEF' for ch in text) else 0
data=bytes.fromhex(text) if not status else b'\xaa\xbb'
result=[status,hx(data),hx(text),hx(data),hx(data),hx(text)]
else:
raise ValueError(command)
self.commands.append(command); self.expected.append(op+' '+' '.join(map(str,result))); self.labels.append((label,clauses))
def record(self,point,text,label='sample',clauses='C04-C10,C15-C16'):
self.add('E %d %s'%(point,hx(text)),label,clauses)
def record(ident,local,remote,span=100,processing=20,hint=None):
r1=remote; r2=remote+processing
return ','.join(map(str,[ident,local,local+span,(r1//1024)%(2**32),r1%1024,(r2//1024)%(2**32),r2%1024,remote if hint is None else hint]))
def cases():
s=Suite(); rng=random.Random(0x53434c4b)
def add(command,label,clauses): s.add(command,label,clauses)
add('R','initial-engine','C12,C15-C16'); add('Q','initial-page','C12'); add('Y','initial-summary','C16')
add('J %d %d'%(MASK,MASK),'empty-priority','C14'); add('C 10000','normal-policy','C15')
s.record(0,record(1,1000,1054),'baseline')
for op in ('R','B','Y','J 1110 100','J 1099 100','J 1101 0','J %d 100'%MASK): add(op,'baseline-observation','C11-C16')
for point in (1,2,3):
s.record(point,record(2,2000+point,2080+point),'failed-publish','C13,C15')
for op in ('R','B','Y','J 1110 100'): add(op,'old-reading-after-failure','C04,C13-C16')
s.record(0,record(2,2200,2220),'same-id-retry','C15'); add('R','retry-committed','C15'); add('Y','retry-summary','C16')
s.record(0,record(2,2300,2400),'duplicate-reject','C15')
s.record(0,record(1,2400,2450),'older-id-reject','C15')
s.record(4,record(3,2500,2550),'invalid-failpoint','C13,C15')
add('R','error-preserves-page','C04,C15')
for era in (1,2,17,511,1023):
for delta in (-80,-1,0,1,80):
hint=era*PERIOD+delta
for residue in (0,1,63,PERIOD-1,PERIOD-47):
add('T %d %d %d 991'%((residue//1024),residue%1024,hint),'era-nearest','C07')
for delta in (-150,-10,0,15):
add('Z','cross-reset','C15')
remote=era*PERIOD+delta
s.record(0,record(1,remote-50,remote,120,30,era*PERIOD-3),'record-crossing','C07,C09-C10,C15')
add('R','cross-reading','C11-C12,C15'); add('J %d 100'%(remote+80),'cross-projection','C08,C14')
for residue in (0,1,1023,1024,PERIOD-1):
for hint in (0,LIMIT,residue+PERIOD//2,min(LIMIT,residue+3*PERIOD//2)):
add('T %d %d %d 992'%(residue//1024,residue%1024,hint),'tie-and-supported-range','C07')
for command in ('T 0 1024 0 993','T 0 65535 0 994','T 1 0 %d 995'%(LIMIT+1)):
add(command,'unfold-domain-output','C03-C04,C07')
for value in [0,1,7,8,16,64,1023,1024,LIMIT-1,LIMIT,LIMIT+1,MASK]+[rng.randrange(LIMIT+1) for _ in range(75)]:
add('A %d 997'%value,'ticks-rounding','C04,C08')
for value in [0,1,488,489,976,977,15624,15625,micros(LIMIT)-1000,micros(LIMIT),micros(LIMIT)+1000,MASK]+[rng.randrange(micros(LIMIT)+1000) for _ in range(75)]:
add('M %d 998'%value,'micros-rounding','C04,C08')
good=record(1,1000,1054)
parse_good=['0'*(512-len(good))+good,good,' \t'+good.replace(',', '\t, '),','.join('000'+x for x in good.split(',')), '0'*450+good]
parse_bad=['',good+',0',good.replace(',',';',1),good+'\n',good+'\r',good+'\x00',good+'#x',good.replace('1,','+1,',1),good.replace('1,','-1,',1),good.replace('1,','1e0,',1),good.replace('1,',',',1),'0'*513, '9'*100+',1,2,0,0,0,0,x']
for index,maxval in enumerate([2**32-1,LIMIT,LIMIT,2**32-1,1023,2**32-1,1023,LIMIT]):
fields=good.split(','); fields[index]=str(maxval+1); parse_bad.append(','.join(fields))
parse_bad+=['0,'+good.split(',',1)[1], '9'*100+',1,2,0,0,0,0,0']
for text in parse_good+parse_bad:
add('D '+hx(text),'record-domain-and-syntax','C03-C06')
s.record(0,text,'record-error-atomic','C04-C06,C15')
for text in ['', 'abCD0123','00','ffff','0','x0','0g',' 00','00\n','\x00\x00']:
add('X '+hx(text),'hex-codec','C04,C06')
base=[7,1000,1100,1,30,1,50,1050]
variations=[base]
for index,value in [(0,0),(1,LIMIT+1),(2,999),(2,LIMIT+1),(4,1024),(6,1024),(7,LIMIT+1)]:
v=base.copy();v[index]=value;variations.append(v)
for r1,r2,ls,lr in [(1000,1000,1000,1000),(1020,1040,1000,1001),(2000,1999,1000,1100),(1000,5097,1000,6100),(1000,5096,1000,6100),(1000,1001,0,MAX_SPAN+1),(LIMIT-1,LIMIT,0,100),(1,1,1,2),(0,0,0,1),(LIMIT-100,LIMIT-100,LIMIT-20,LIMIT)]:
variations.append([8,ls,lr,r1//1024%(2**32),r1%1024,r2//1024%(2**32),r2%1024,r1])
for values in variations:
for policy in (0,79,80,MAX_SPAN,MAX_SPAN+1):
add('V '+' '.join(map(str,values+[policy])),'estimate-priority-and-preservation','C03-C04,C07-C10')
for point in range(5):
for values in ([1,100,120,20,7,3],[MASK,LIMIT,LIMIT,0,MAX_SPAN,2],[0,100,120,20,7,3],[1,LIMIT+1,120,20,7,3],[1,100,120,21,7,3],[1,100,120,20,MAX_SPAN+1,3],[1,100,120,20,7,0],[1,100,120,-(LIMIT+1),7,3]):
add('H '+' '.join(map(str,list(values)+[point])),'direct-publication-transaction','C04,C11-C13')
add('Q','post-publication-read','C04,C12-C13')
add('K 125 100','post-publication-project','C14')
clean=pack([11,200,175,-25,80,123])
for position in range(64):
changed=bytearray(clean);changed[position]^=1
add('L '+changed.hex(),'corruption-import','C12'); add('Q','corruption-detected','C04,C11-C12')
for position in (0,4,6,52):
changed=bytearray(clean);changed[position]^=1
changed[56:]=struct.pack('<Q',fnv(changed[:56]))
add('L '+changed.hex(),'checksum-valid-format-error','C11-C12');add('Q','format-error-read','C12')
add('K %d %d'%(MASK,MASK),'corrupt-priority','C14')
for values in ([0,100,100,0,0,1],[1,100,100,0,0,0],[1,LIMIT+1,LIMIT+1,0,0,1],[1,100,100,1,0,1],[1,100,100,0,MAX_SPAN+1,1],[1,100,100,-2**63,0,1]):
add('L '+pack(values).hex(),'checksum-valid-invalid-domain','C12'); add('Q','domain-corruption','C12')
add('L '+clean.hex(),'valid-foreign-page','C11-C12'); add('Q','foreign-page-read','C12')
for length in (0,1,63,65,128):
add('L '+hx(bytes(length)),'load-size-preservation','C04,C12'); add('Q','load-retained','C12')
for now,age in [(199,100),(200,0),(201,0),(201,1),(300,100),(301,100),(LIMIT,LIMIT),(MASK,LIMIT),(200,MASK)]:
add('K %d %d'%(now,age),'project-age-priority','C04,C08,C14')
add('L '+pack([12,100,LIMIT,LIMIT-100,0,4]).hex(),'projection-overflow-page','C11-C12')
add('K 101 1','projection-overflow','C14');add('K 100 0','projection-max','C08,C14')
for _ in range(120):
era=rng.randrange(1024); residue=rng.randrange(PERIOD); hint=min(LIMIT,era*PERIOD+residue)
sec=rng.randrange(2**32);frac=rng.randrange(1024)
add('T %d %d %d 999'%(sec,frac,hint),'random-era','C07')
for selected in (0,1,0,1):
add('U %d'%selected,'independent-instance','C01')
add('Z','instance-reset','C15');add('N','page-reset','C12')
s.record(0,record(1,100,170),'instance-first')
for step in range(1,55):
if step%13==0: add('C %d'%rng.choice([0,79,80,10000,MAX_SPAN+1]),'policy-change','C15')
local=step*500+1000;remote=local+rng.randrange(-100,101)
point=rng.choice([0,0,0,1,2,3,4])
s.record(point,record(step+1,local,remote,100,rng.randrange(21)),'stateful-retry')
add('R','stateful-last-reading','C04,C11-C16');add('Y','stateful-summary','C16')
add('B','instance-bytes','C11-C16');add('R','instance-latest','C16')
for selected,ident,local in [(0,1,300),(1,9,900)]:
add('U %d'%selected,'interleave-select','C01')
add('Z','interleave-engine-reset','C01,C15')
add('N','interleave-page-reset','C01,C12')
s.record(0,record(ident,local,local+30),'interleave-record')
add('H %d %d %d 20 40 %d 0'%(ident,local,local+20,ident),'interleave-direct-page','C01,C11-C13')
for selected in (0,1,0,1):
add('U %d'%selected,'interleave-observe-select','C01')
for op in ('R','Q','Y','B','J 1000 1000','K 1000 1000'):
add(op,'interleave-retained-state','C01,C11-C16')
return s
def console_cases():
engine=Engine(); commands=[]; expected=[]
def add(text,result): commands.append(text);expected.append(result)
add('read','-6'); add('summary','empty'); add('bytes',EMPTY.hex())
for ident,point,local,remote in [(1,0,1000,1054),(2,1,2000,2080),(2,2,2000,2080),(2,3,2000,2080),(2,0,2000,2080),(2,0,3000,3050),(3,4,4000,4050),(3,0,PERIOD-70,PERIOD-30)]:
text=record(ident,local,remote)
add('sample %d %s'%(point,text),str(engine.submit(text,point)))
status,value=read(engine.page);add('read',' '.join(map(str,[status]+(value if not status else []))))
add('bytes',engine.page.hex());add('summary',engine.summary())
now=local+110; status,value=projection(engine.page,now,200)
add('project %d 200'%now,' '.join(map(str,[status]+(value if not status else []))))
for policy in (0,79,80,MAX_SPAN+1,10000): add('policy %d'%policy,str(engine.configure(policy)))
for text in ['unknown','read tail','bytes tail','summary tail','reset tail','sample','sample x '+record(4,100,120),'policy x','policy','project 1','project -1 1','project 1 x','project 1 2 3','', 'sample 0 invalid']:
add(text,'-1')
for text in ['read\x00','policy ١','policy 1','policy +1','policy -0','read\u00a0','\u00a0read','policy 1\x00','sample 0 1,0,0,0,0,0,0,١']:
add(text,'-1')
for value in (0,10000,MASK):
status=engine.configure(value)
add('\tpolicy\v'+'0'*5001+str(value)+'\f\r',str(status))
add('policy '+'0'*5001+str(MASK+1),'-1')
status,value=read(engine.page)
add(' \tread\v\f\r',' '.join(map(str,[status]+(value if not status else []))))
text=record(100,5000,5050)
add('sample\v0\f'+text,str(engine.submit(text,0)))
status,value=projection(engine.page,5110,100)
add('project\r0005110\v000100\f',' '.join(map(str,[status]+(value if not status else []))))
engine.reset();add('reset','0');add('read','-6');add('summary','empty');add('bytes',EMPTY.hex())
return commands,expected
FIELD_WHITESPACE = ' \t\r\v\f'
def records(data):
# LF is the physical record separator; CR/VT/FF remain available inside fields.
lines = data.decode('utf-8', 'strict').split('\n')
if lines[-1:] == ['']:
lines.pop()
return [line[:-1] if line.endswith('\r') else line for line in lines]
def decimal_key(word):
sign = ''
if word[:1] in ('+', '-'):
sign = '-' if word[0] == '-' else ''
word = word[1:]
if not word or any(ch not in '0123456789' for ch in word):
return None
digits = word.lstrip('0') or '0'
return sign+digits if digits != '0' else '0'
def console_equal(actual,expected,command):
op = command.split()[0] if command.split() else ''
if op in ('bytes','summary') and expected != '-1':
return actual == expected
# Splitting only the public ASCII field whitespace avoids Unicode token broadening.
fields = []
start = 0
for pos in range(len(actual)+1):
if pos == len(actual) or actual[pos] in FIELD_WHITESPACE:
if pos > start:
fields.append(actual[start:pos])
start = pos+1
wanted = expected.split(' ')
return len(fields) == len(wanted) and all(decimal_key(a) == b for a,b in zip(fields,wanted))
def compare(actual,expected,labels,commands=None):
failures=[]
for index in range(max(len(actual),len(expected))):
got=actual[index] if index<len(actual) else '<missing>'
wanted=expected[index] if index<len(expected) else '<end>'
equal = index<len(actual) and index<len(expected) and (
got == wanted if commands is None else console_equal(got,wanted,commands[index]))
if not equal:
label,clauses=labels[index] if index<len(labels) else ('extra-output','C17')
failures.append((index,label,clauses,got[:180],wanted[:180]))
return failures
def main():
suite=cases(); console,console_expected=console_cases()
candidate=Path(sys.argv[1])
source={name:(candidate/name).read_bytes() for name in FILES}
scratch=Path(tempfile.mkdtemp(prefix='clock-snapshot-',dir=Path.cwd()))
for name,data in source.items():
target=scratch/name;target.write_bytes(data);target.chmod(0o644)
for name,data in {'observe.cpp':OBSERVER,'observations.in':'\n'.join(suite.commands)+'\n','console.in':'\n'.join(console)}.items():
target=scratch/name;target.write_text(data);target.chmod(0o644)
# All scratch preparation is complete. From here the checker consumes subprocess pipes only.
common=['g++','-std=c++17','-O2','-Wall','-Wextra','-pedantic']
sources=['record.cpp','time_math.cpp','page.cpp','service.cpp']
for entry,output in [('observe.cpp','observe'),('clockctl.cpp','clockctl')]:
build=subprocess.run(common+[entry]+sources+['-o',output],cwd=scratch,capture_output=True,timeout=25)
if build.returncode:
print('build-failed C02 '+build.stderr[-1000:].decode('utf-8','replace').replace('\n',' '));return 1
observations=subprocess.run([str(scratch/'observe')],input=('\n'.join(suite.commands)+'\n').encode('utf-8'),cwd=scratch,capture_output=True,timeout=12)
console_run=subprocess.run([str(scratch/'clockctl')],input='\n'.join(console).encode('utf-8'),cwd=scratch,capture_output=True,timeout=8)
if observations.returncode or console_run.returncode:
print('candidate-exit C02,C17 %d %d'%(observations.returncode,console_run.returncode));return 1
try:
actual_observations=records(observations.stdout)
actual_console=records(console_run.stdout)
except UnicodeDecodeError:
print('invalid-output-encoding C17');return 1
failures=compare(actual_observations,suite.expected,suite.labels)
failures+=compare(actual_console,console_expected,[('console','C17')]*len(console_expected),console)
if failures:
for item in failures[:12]: print('observation=%d label=%s clauses=%s got=%r expected=%r'%item)
print('mismatches=%d observations=%d'%(len(failures),len(suite.expected)+len(console_expected)));return 1
print('PASS');return 0
if __name__=='__main__':
raise SystemExit(main())