Import calibrated Bos n2 batch 9 group 12
This commit is contained in:
parent
63bc36c53b
commit
8749babe6f
@ -26,6 +26,8 @@
|
||||
|
||||
第11组新增/修订 10 题(119,123,127,130,133,136,139,131,134,137)已完成当前摘要双门校准:本地305/305、trace6正式305/305符合预期且cleanup confirmed;原判据/gold/valid摘要保持,README澄清及升版逐题见spec,root只读/交叉审与回执核验见root-review-group11.json。累计提交110道不同新题,均CALIBRATED/UNMEASURED;不调用模型、不推送,继续本批。
|
||||
|
||||
第12组新增/修订 10 题(066,140,142,143,145,146,148,149,151,152)已完成当前摘要双门校准:本地305/305、trace6正式305/305符合预期且cleanup confirmed;原判据/gold/valid摘要保持,README澄清及升版逐题见spec,root只读/交叉审与回执核验见root-review-group12.json。累计提交120道不同新题,均CALIBRATED/UNMEASURED;不调用模型、不推送,继续本批。
|
||||
|
||||
## 此前进度记录(原文保留)
|
||||
|
||||
2026-10-19 第6批会话3续跑:按 BRIEF → CONTINUE → CONTINUE-2 的覆盖顺序,从 main=a79211f 继续(git pull --ff-only 已最新,/home 约115GiB)。下一步先复核 archive-staged-tar 超时轨迹因果及 config-overlay-relocation 结案口径,再只补剩余6题,累计每题原始尝试最多15次;trace6/Qwen全局2路、3600秒、30GiB停止线保持,DIR/ELF最后。涉及已跟踪 difficulty-review.json、本进度及本批过程证据;不增题、不改平台/题库索引/其他批次,不推送。验收为剩余题逐一结案(不足则列作废原因)、真实失败依据复核、完整轨迹重判归档、最终报告与核验冷迁后删热;外部依赖为Qwen服务、Docker与JuiceFS,Salty可用性另按事实报告。
|
||||
|
||||
32
tasks/S500_n2_066/cheat/task.py
Normal file
32
tasks/S500_n2_066/cheat/task.py
Normal file
@ -0,0 +1,32 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);A=[vec(p,2) for p in arr(field(d,'left'))];B=[vec(p,2) for p in arr(field(d,'right'))]
|
||||
if any(a>=b for a,b in A+B):raise ValueError('interval')
|
||||
return A,B
|
||||
import bisect
|
||||
def solve(data):
|
||||
A,B=prepare(data);A=[list(p) for p in sorted(set(map(tuple,A)))];right=sorted((a,b,i) for i,(a,b) in enumerate(B));starts=[a for a,b,i in right];rows=[]
|
||||
for i,(a,b) in enumerate(A):
|
||||
for c,d,j in right[:bisect.bisect_left(starts,b)]:
|
||||
if d<=a:continue
|
||||
lo=max(a,c);hi=min(b,d);rows.append([i,j,lo,hi,hi-lo])
|
||||
rows.sort(key=lambda r:(r[2],r[3],r[0],r[1]));return rows
|
||||
32
tasks/S500_n2_066/cheat_only_first_overlap/task.py
Normal file
32
tasks/S500_n2_066/cheat_only_first_overlap/task.py
Normal file
@ -0,0 +1,32 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);A=[vec(p,2) for p in arr(field(d,'left'))];B=[vec(p,2) for p in arr(field(d,'right'))]
|
||||
if any(a>=b for a,b in A+B):raise ValueError('interval')
|
||||
return A,B
|
||||
import bisect
|
||||
def solve(data):
|
||||
A,B=prepare(data);right=sorted((a,b,i) for i,(a,b) in enumerate(B));starts=[a for a,b,i in right];rows=[]
|
||||
for i,(a,b) in enumerate(A):
|
||||
for c,d,j in right[:bisect.bisect_left(starts,b)]:
|
||||
if d<=a:continue
|
||||
lo=max(a,c);hi=min(b,d);rows.append([i,j,lo,hi,hi-lo]);break
|
||||
rows.sort(key=lambda r:(r[2],r[3],r[0],r[1]));return rows
|
||||
73
tasks/S500_n2_066/check.py
Normal file
73
tasks/S500_n2_066/check.py
Normal file
@ -0,0 +1,73 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
cases=[dict(left=[[0,2],[2,3],[0,2]],right=[[2,4],[1,2],[0,5]]),dict(left=[],right=[[0,1]]),dict(left=[[3,5],[-2,4]],right=[[5,6],[-3,-2],[0,3]])];rng=random.Random(1066)
|
||||
for n in [10,1000]:
|
||||
A=[[i*10+rng.randrange(3),i*10+5+rng.randrange(3)] for i in range(n)];B=[[i*10-1,i*10+3] for i in range(n)];rng.shuffle(A);rng.shuffle(B);cases.append(dict(left=A,right=B))
|
||||
def oracle(d):
|
||||
rows=[]
|
||||
for i,(a,b) in enumerate(d['left']):
|
||||
for j,(c,e) in enumerate(d['right']):
|
||||
start=max(a,c);end=min(b,e)
|
||||
if start<end:rows.append([i,j,float(start),float(end),float(end-start)])
|
||||
return sorted(rows,key=lambda r:(r[2],r[3],r[0],r[1]))
|
||||
base=dict(left=[],right=[]);bad=[None,{},dict(base,left=[[0,0]]),dict(base,right=[[2,1]]),dict(base,left=[[0,True]]),dict(base,right=[[0,float('nan')]]),dict(base,left=[[0]]),dict(base,right={})]
|
||||
return cases+bad,[{'ok':oracle(d)} for d in cases]+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'left': [[-1000000, 1000000]], 'right': [[-500000, 500000]]}, [[0, 0, -500000.0, 500000.0, 1000000.0]])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
35
tasks/S500_n2_066/gold/task.py
Normal file
35
tasks/S500_n2_066/gold/task.py
Normal file
@ -0,0 +1,35 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);A=[vec(p,2) for p in arr(field(d,'left'))];B=[vec(p,2) for p in arr(field(d,'right'))]
|
||||
if any(a>=b for a,b in A+B):raise ValueError('interval')
|
||||
return A,B
|
||||
def solve(data):
|
||||
A,B=prepare(data);events=[]
|
||||
for side,P in enumerate((A,B)):
|
||||
for i,(a,b) in enumerate(P):events.extend([(a,1,side,i),(b,0,side,i)])
|
||||
active=[set(),set()];out=[]
|
||||
for t,kind,side,i in sorted(events):
|
||||
if kind==0:active[side].remove(i);continue
|
||||
for j in active[1-side]:
|
||||
li,ri=(i,j) if side==0 else (j,i);start=max(A[li][0],B[ri][0]);end=min(A[li][1],B[ri][1]);out.append([li,ri,start,end,end-start])
|
||||
active[side].add(i)
|
||||
return sorted(out,key=lambda r:(r[2],r[3],r[0],r[1]))
|
||||
2
tasks/S500_n2_066/noop/task.py
Normal file
2
tasks/S500_n2_066/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_066/prompt.md
Normal file
3
tasks/S500_n2_066/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成传感有效时间区间关联并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_066/spec.md
Normal file
63
tasks/S500_n2_066/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_066
|
||||
|
||||
本规格仅供控制侧,路线 A 只填写第 1、4、7 节,其余沿用 Bos 原题。规范见 [任务制作规范](../../docs/task-authoring.md)。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 任务版本 | S500_n2_066 / 2 |
|
||||
| 作者 / 独立评审人 | Bos 原作者;本批 Codex lane1 / 待主控只读复核 |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 来源路线 | A 导入成熟任务;bos.origin=original_authored |
|
||||
| 来源 ID / split 分组键 | S500_n2_066;new_n2_066_sensor_interval_overlap_join / bos:new_n2_066_sensor_interval_overlap_join |
|
||||
| 原项目与冻结版本 | Bos-qiao task_factory_500_20260914;本批只读本地快照 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_066;原 task.json SHA-256 4b8e96e05fc9f4b78c61356a2870c31106d78f8b3148a89a8dc20f08f3bd7049;无独立上游 commit |
|
||||
| 授权与隐私 | 用户 2026-10-20 明确授权本批全部剩余 n2 导入;仅保留任务资产,不执行来源脚本,不含用户会话与凭据 |
|
||||
| 来源组 / 任务族 | Bos n2 / motor-sensor-control |
|
||||
| 替身测试与用途 | software:异步曝光/采样分析器查找两路有效时间区间的重叠;合成输入可完整复现,无外设依赖 |
|
||||
| 与已有任务关系 | 独立来源 S500_n2_066,保持来源 split;未声称已经完成跨全部来源的语义去重 |
|
||||
| 验证范围 | README 声明的纯软件数学/事件模型 |
|
||||
| 未验证范围 | 真实 Agent、模型难度、板卡/外设/电气/真实时序和物理安全 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 场景与可观察结果 | 检查方法与容差 |
|
||||
| --- | --- | --- | --- |
|
||||
| 每对半开时间交集 | README第3段“begin<end”“每一对有正时长交集”“仅端点接触不输出” | 重复/重叠/乱序原区间、端点相触、1000×1000流、正负百万端点 | oracle双重循环max/min并保留原索引,按(start,end,i,j)排序;索引严格int,数值1e-8 |
|
||||
| 空与全验证 | README第3段“空流合法,另一流仍需验证”及末段 | 空侧、零/反向区间、bool、NaN、错维数拒绝 | ValueError及输入保持 |
|
||||
| 通用输入与输出合同 | template/README.md 末段“有限int/float且不包括bool”“必须抛ValueError”“不得改写传入数据” | 缺字段、类型、超域/极大整数等非法输入抛 ValueError;输入保持;仅提交 task.py 自包含 | RUNNER 子进程回传结果/异常,pickle 比对输入;结构精确、浮点 math.isclose(rel_tol=1e-8,abs_tol=1e-8),本题专用容差优先 |
|
||||
|
||||
- 判据独立性:oracle枚举全部跨流区间对,与gold事件扫线或valid起点二分筛候选不同,不去重。
|
||||
- 合法替代解:gold结束事件优先于开始确保半开规则;valid_alternative按右起点排序加bisect枚举,允许任何同一结果的实现。
|
||||
- 题面歧义审查:已完整读取 prompt、README、check 与根目录附属 Python、gold、valid、template/noop/cheat;核对阈值等号、实数/浮点、int/float/bool、数量/空输入/异常/容差。题面改动:v2仅补solve顶层返回的列表类型、顺序/长度及空列表语义,依据check.fixtures期望列表结构与RUNNER一调用一结果、same列表比较;gold/oracle未改。
|
||||
- 隔离:候选只在 RUNNER 子进程导入,check 保留用例、期望与比对;沿用统一 verify.py 的受保护 grader 与 UID65534 降权探针,不把 host 当隔离证明。候选运行后 check 不再读取其临时文件。
|
||||
- 历史可见性:Agent 只获得 prompt/template,正式判据、gold、spec 与 factory/runs 不进入候选工作区。
|
||||
- 限制:有限隐藏组合不穷尽整个合法输入域;验收结论只到公开软件模型。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不调用 Qwen 或任何真实模型,难度 UNMEASURED。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- [x] 作者逐题核对来源、完整初态、公开行为依据、判据独立性、合法替代解与负例。
|
||||
- [x] 本地与 trace6 Docker 两门完成;每类样例各五次,Docker 全部符合预期且 cleanup confirmed 才记 CALIBRATED。
|
||||
- [ ] 主控独立只读复核与真实试采;本批不记 ADMITTED,不宣称真实模型/硬件通过。
|
||||
|
||||
审核记录:2026-10-20,Codex lane1;状态 CALIBRATED,难度 UNMEASURED。题面修改与依据见第 4 节。
|
||||
|
||||
闸门 1:`runs/20261020-A-bos-n2-9/local/calibration-73e3b0c2998a46bf9b913c47c9448508`,status=PASS,30 次,cleanup=confirmed,accepted=True。闸门 2:`runs/20261020-A-bos-n2-9/docker/calibration-a11d821d31d64b80853d9a95c756ff38`,status=PASS,30 次,cleanup=confirmed,accepted=True。
|
||||
|
||||
固定镜像:`ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。最终 task digest `07b17bca3083687ba701453af3b3aa72de50142084549720cfa0ad8df4ac0e78`;原始事实见两门 receipt.json 及本批 gates/S500_n2_066/latest.json,历史输出不覆盖。
|
||||
36
tasks/S500_n2_066/task.json
Normal file
36
tasks/S500_n2_066/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_066",
|
||||
"version": "2",
|
||||
"family": "motor-sensor-control",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_066",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_only_first_overlap": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_066_sensor_interval_overlap_join",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_collapse_duplicate_intervals.sh",
|
||||
"cheat_only_first_overlap": "cheat_only_first_overlap.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
7
tasks/S500_n2_066/template/README.md
Normal file
7
tasks/S500_n2_066/template/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 传感有效时间区间关联
|
||||
|
||||
输入{left:[[begin,end],...],right:[[begin,end],...]}。所有端点有限,每区间begin<end,按半开[begin,end)解释;输入可无序,同流区间可以重叠或完全重复。返回两流每一对有正时长交集的记录[left_index,right_index,start,end,duration],start=max(beginL,beginR),end=min(endL,endR),duration=end-start;仅端点接触不输出。结果按(start,end,left_index,right_index)升序排序,索引必须保留原输入位置,重复区间代表独立观测不可去重。支持各流1000区间和最多20000交集输出;空流合法,另一流仍需验证。该题关联有效时间段,不是点时间戳配对。
|
||||
|
||||
solve(data)的顶层返回值是包含全部上述交集记录的列表,遵循已规定的排序;没有正时长交集时返回[],包含任一输入流为空的情况。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
3
tasks/S500_n2_066/template/task.py
Normal file
3
tasks/S500_n2_066/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
32
tasks/S500_n2_066/valid_alternative/task.py
Normal file
32
tasks/S500_n2_066/valid_alternative/task.py
Normal file
@ -0,0 +1,32 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);A=[vec(p,2) for p in arr(field(d,'left'))];B=[vec(p,2) for p in arr(field(d,'right'))]
|
||||
if any(a>=b for a,b in A+B):raise ValueError('interval')
|
||||
return A,B
|
||||
import bisect
|
||||
def solve(data):
|
||||
A,B=prepare(data);right=sorted((a,b,i) for i,(a,b) in enumerate(B));starts=[a for a,b,i in right];rows=[]
|
||||
for i,(a,b) in enumerate(A):
|
||||
for c,d,j in right[:bisect.bisect_left(starts,b)]:
|
||||
if d<=a:continue
|
||||
lo=max(a,c);hi=min(b,d);rows.append([i,j,lo,hi,hi-lo])
|
||||
rows.sort(key=lambda r:(r[2],r[3],r[0],r[1]));return rows
|
||||
130
tasks/S500_n2_066/verify.py
Normal file
130
tasks/S500_n2_066/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
63
tasks/S500_n2_140/cheat/task.py
Normal file
63
tasks/S500_n2_140/cheat/task.py
Normal file
@ -0,0 +1,63 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import hashlib
|
||||
|
||||
def utf8(x,nonempty=False):
|
||||
if not isinstance(x,str) or (nonempty and not x):raise ValueError('text')
|
||||
try:b=x.encode('utf-8')
|
||||
except UnicodeError:raise ValueError('utf8')
|
||||
if len(b)>1024:raise ValueError('text length')
|
||||
return b
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);bits=field(d,'bits');E=[]
|
||||
if type(bits) is not int or not 1<=bits<=16:raise ValueError('bits')
|
||||
for row in arr(field(d,'events')):
|
||||
row=obj(row);op=field(row,'op')
|
||||
if op in ('add','remove'):
|
||||
node=field(row,'node');utf8(node,True);replicas=field(row,'replicas') if op=='add' else None
|
||||
if op=='add' and (type(replicas) is not int or not 1<=replicas<=32):raise ValueError('replicas')
|
||||
E.append((op,node,replicas))
|
||||
elif op=='lookup':key=field(row,'key');utf8(key);E.append((op,key,None))
|
||||
elif op=='ring':E.append((op,None,None))
|
||||
else:raise ValueError('op')
|
||||
return bits,E
|
||||
|
||||
def digest(bits,prefix,name,index=None):
|
||||
encoded=utf8(name);payload=prefix+len(encoded).to_bytes(4,'big')+encoded
|
||||
if index is not None:payload+=index.to_bytes(4,'big')
|
||||
return int.from_bytes(hashlib.sha256(payload).digest()[:8],'big')&((1<<bits)-1)
|
||||
def solve(data):
|
||||
import bisect
|
||||
bits,E=prepare(data);nodes={};ring=[];positions=[];dirty=False;out=[]
|
||||
for op,node,replicas in E:
|
||||
if op=='add':new=node not in nodes;nodes[node]=replicas;dirty=True;out.append(new)
|
||||
elif op=='remove':exists=node in nodes;nodes.pop(node,None);dirty=True;out.append(exists)
|
||||
else:
|
||||
if dirty:
|
||||
ring=sorted((digest(bits,b'V',n,i),n,i) for n,count in nodes.items() for i in range(count));positions=[r[0] for r in ring];dirty=False
|
||||
if op=='ring':out.append([dict(position=p,node=n,replica=i) for p,n,i in ring])
|
||||
elif not ring:out.append(None)
|
||||
else:
|
||||
h=digest(bits,b'K',node);index=bisect.bisect_right(positions,h)-1
|
||||
if index==len(ring):index=0
|
||||
out.append(ring[index][1])
|
||||
return out
|
||||
63
tasks/S500_n2_140/cheat_stale_replica_update/task.py
Normal file
63
tasks/S500_n2_140/cheat_stale_replica_update/task.py
Normal file
@ -0,0 +1,63 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import hashlib
|
||||
|
||||
def utf8(x,nonempty=False):
|
||||
if not isinstance(x,str) or (nonempty and not x):raise ValueError('text')
|
||||
try:b=x.encode('utf-8')
|
||||
except UnicodeError:raise ValueError('utf8')
|
||||
if len(b)>1024:raise ValueError('text length')
|
||||
return b
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);bits=field(d,'bits');E=[]
|
||||
if type(bits) is not int or not 1<=bits<=16:raise ValueError('bits')
|
||||
for row in arr(field(d,'events')):
|
||||
row=obj(row);op=field(row,'op')
|
||||
if op in ('add','remove'):
|
||||
node=field(row,'node');utf8(node,True);replicas=field(row,'replicas') if op=='add' else None
|
||||
if op=='add' and (type(replicas) is not int or not 1<=replicas<=32):raise ValueError('replicas')
|
||||
E.append((op,node,replicas))
|
||||
elif op=='lookup':key=field(row,'key');utf8(key);E.append((op,key,None))
|
||||
elif op=='ring':E.append((op,None,None))
|
||||
else:raise ValueError('op')
|
||||
return bits,E
|
||||
|
||||
def digest(bits,prefix,name,index=None):
|
||||
encoded=utf8(name);payload=prefix+len(encoded).to_bytes(4,'big')+encoded
|
||||
if index is not None:payload+=index.to_bytes(4,'big')
|
||||
return int.from_bytes(hashlib.sha256(payload).digest()[:8],'big')&((1<<bits)-1)
|
||||
def solve(data):
|
||||
import bisect
|
||||
bits,E=prepare(data);nodes={};ring=[];positions=[];dirty=False;out=[]
|
||||
for op,node,replicas in E:
|
||||
if op=='add':new=node not in nodes;nodes[node]=replicas;dirty=dirty or new;out.append(new)
|
||||
elif op=='remove':exists=node in nodes;nodes.pop(node,None);dirty=True;out.append(exists)
|
||||
else:
|
||||
if dirty:
|
||||
ring=sorted((digest(bits,b'V',n,i),n,i) for n,count in nodes.items() for i in range(count));positions=[r[0] for r in ring];dirty=False
|
||||
if op=='ring':out.append([dict(position=p,node=n,replica=i) for p,n,i in ring])
|
||||
elif not ring:out.append(None)
|
||||
else:
|
||||
h=digest(bits,b'K',node);index=bisect.bisect_left(positions,h)
|
||||
if index==len(ring):index=0
|
||||
out.append(ring[index][1])
|
||||
return out
|
||||
92
tasks/S500_n2_140/check.py
Normal file
92
tasks/S500_n2_140/check.py
Normal file
@ -0,0 +1,92 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
import hashlib
|
||||
def add(n,c):return dict(op='add',node=n,replicas=c)
|
||||
def remove(n):return dict(op='remove',node=n)
|
||||
def lookup(k):return dict(op='lookup',key=k)
|
||||
ring=dict(op='ring');cases=[dict(bits=1,events=[lookup(''),add('b',4),add('a',4),ring]+[lookup(str(i)) for i in range(10)]+[add('a',1),ring,remove('a'),ring,remove('missing'),remove('b'),lookup('')]),dict(bits=16,events=[add('节点\0',3),add('é',2),ring,lookup('汉字'),lookup('\0'),lookup(''),add('é',1),ring])];rng=random.Random(1240)
|
||||
events=[]
|
||||
for i in range(10000):
|
||||
op=rng.randrange(10);node='node'+str(rng.randrange(128))
|
||||
if op<2:events.append(add(node,rng.randrange(1,9)))
|
||||
elif op==2:events.append(remove(node))
|
||||
elif i%1000==0:events.append(ring)
|
||||
else:events.append(lookup('key'+str(rng.randrange(10000))))
|
||||
cases.append(dict(bits=8,events=events))
|
||||
def oracle(d):
|
||||
def hash_value(tag,text,index=None):
|
||||
b=text.encode('utf-8');encoded=tag+bytes([(len(b)>>shift)&255 for shift in [24,16,8,0]])+b
|
||||
if index is not None:encoded+=bytes([(index>>shift)&255 for shift in [24,16,8,0]])
|
||||
first=hashlib.sha256(encoded).hexdigest()[:16];return int(first,16)%(2**d['bits'])
|
||||
nodes={};out=[];cache=None
|
||||
for e in d['events']:
|
||||
op=e['op']
|
||||
if op=='add':out.append(e['node'] not in nodes);nodes[e['node']]=e['replicas'];cache=None;continue
|
||||
if op=='remove':out.append(e['node'] in nodes);nodes.pop(e['node'],None);cache=None;continue
|
||||
if cache is None:cache=[(hash_value(b'V',node,i),node,i) for node,n in nodes.items() for i in range(n)]
|
||||
if op=='ring':out.append([dict(position=p,node=n,replica=i) for p,n,i in sorted(cache)])
|
||||
elif not cache:out.append(None)
|
||||
else:
|
||||
h=hash_value(b'K',e['key']);distance=min((position-h)%(2**d['bits']) for position,node,i in cache);choices=[(node,i) for position,node,i in cache if (position-h)%(2**d['bits'])==distance];out.append(min(choices)[0])
|
||||
return out
|
||||
base=dict(bits=8,events=[]);bad=[None,{},dict(base,bits=0),dict(base,bits=17),dict(base,bits=True),dict(base,events=[add('',1)]),dict(base,events=[add('a',0)]),dict(base,events=[add('a',33)]),dict(base,events=[add('a',True)]),dict(base,events=[lookup(1)]),dict(base,events=[lookup('\ud800')]),dict(base,events=[add('a'*1025,1)]),dict(base,events=[dict(op='change')]),dict(base,events=[dict(op='lookup')])]
|
||||
return cases+bad,[{'ok':oracle(d)} for d in cases]+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'bits': 16, 'events': [{'op': 'add', 'node': 'a', 'replicas': 32}, {'op': 'lookup', 'key': ''}, {'op': 'remove', 'node': 'a'}, {'op': 'lookup', 'key': ''}]}, [True, 'a', True, None])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
63
tasks/S500_n2_140/gold/task.py
Normal file
63
tasks/S500_n2_140/gold/task.py
Normal file
@ -0,0 +1,63 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import hashlib
|
||||
|
||||
def utf8(x,nonempty=False):
|
||||
if not isinstance(x,str) or (nonempty and not x):raise ValueError('text')
|
||||
try:b=x.encode('utf-8')
|
||||
except UnicodeError:raise ValueError('utf8')
|
||||
if len(b)>1024:raise ValueError('text length')
|
||||
return b
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);bits=field(d,'bits');E=[]
|
||||
if type(bits) is not int or not 1<=bits<=16:raise ValueError('bits')
|
||||
for row in arr(field(d,'events')):
|
||||
row=obj(row);op=field(row,'op')
|
||||
if op in ('add','remove'):
|
||||
node=field(row,'node');utf8(node,True);replicas=field(row,'replicas') if op=='add' else None
|
||||
if op=='add' and (type(replicas) is not int or not 1<=replicas<=32):raise ValueError('replicas')
|
||||
E.append((op,node,replicas))
|
||||
elif op=='lookup':key=field(row,'key');utf8(key);E.append((op,key,None))
|
||||
elif op=='ring':E.append((op,None,None))
|
||||
else:raise ValueError('op')
|
||||
return bits,E
|
||||
|
||||
def digest(bits,prefix,name,index=None):
|
||||
encoded=utf8(name);payload=prefix+len(encoded).to_bytes(4,'big')+encoded
|
||||
if index is not None:payload+=index.to_bytes(4,'big')
|
||||
return int.from_bytes(hashlib.sha256(payload).digest()[:8],'big')&((1<<bits)-1)
|
||||
def solve(data):
|
||||
import bisect
|
||||
bits,E=prepare(data);nodes={};ring=[];positions=[];dirty=False;out=[]
|
||||
for op,node,replicas in E:
|
||||
if op=='add':new=node not in nodes;nodes[node]=replicas;dirty=True;out.append(new)
|
||||
elif op=='remove':exists=node in nodes;nodes.pop(node,None);dirty=True;out.append(exists)
|
||||
else:
|
||||
if dirty:
|
||||
ring=sorted((digest(bits,b'V',n,i),n,i) for n,count in nodes.items() for i in range(count));positions=[r[0] for r in ring];dirty=False
|
||||
if op=='ring':out.append([dict(position=p,node=n,replica=i) for p,n,i in ring])
|
||||
elif not ring:out.append(None)
|
||||
else:
|
||||
h=digest(bits,b'K',node);index=bisect.bisect_left(positions,h)
|
||||
if index==len(ring):index=0
|
||||
out.append(ring[index][1])
|
||||
return out
|
||||
2
tasks/S500_n2_140/noop/task.py
Normal file
2
tasks/S500_n2_140/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_140/prompt.md
Normal file
3
tasks/S500_n2_140/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成分片遥测一致性哈希并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
65
tasks/S500_n2_140/spec.md
Normal file
65
tasks/S500_n2_140/spec.md
Normal file
@ -0,0 +1,65 @@
|
||||
# 任务规格:S500_n2_140
|
||||
|
||||
规范:[任务制作规范](../../docs/task-authoring.md)。路线 A 仅填第 1、4、7 节。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 版本 | S500_n2_140 / 2 |
|
||||
| 作者 / 独立评审人 | Codex lane2 / root(2026-10-20,只读审阅通过;证据见本批 root-review-group12.json) |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 原项目与快照 | Bos-qiao envs/S500_n2_140;本批只读复制到 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_140 |
|
||||
| 来源路线 / 来源ID | A 导入成熟任务(Bos 原题) / S500_n2_140 |
|
||||
| 来源与授权 | 用户 2026-10-20 第9批 BRIEF;2026-10-12 项目资产接入授权;来源只读,样例脚本仅解析 |
|
||||
| 隐私处理 | 无真实用户会话;本批不读取凭据 |
|
||||
| 替身测试 | 软件输入驱动纯 Python 行为;不需要板卡或真实外设,software |
|
||||
| split 分组键 | bos:new_n2_140_route_consistent_hash_ring |
|
||||
| 来源组 / 根因族 | Bos n2 / serial-protocol |
|
||||
| 与已有任务的关系 | 本批剩余来源独立导入;非已有任务改名 |
|
||||
| 导入方式 | 直接导入 |
|
||||
| 验证范围 | 原 README 公开合同与原隐藏行为判据 |
|
||||
| 未验证范围 | 只验证纯软件行为;未验证真实硬件、实时性能或模型难度。 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 可观察结果与检查 |
|
||||
| --- | --- | --- |
|
||||
| 精确字节编码与哈希 | template/README.md:3(SHA256摘要前8字节按大端无符号整数) | 独立hexdigest前16位+显式长度bytes oracle,golddigest/bisect与valid模环距离扫描 |
|
||||
| 碰撞与环绕择优 | template/README.md:3(相同position按(node字符串字典序,replica索引)) | bits1真实碰撞不丢token,position>=h否则环绕;同点按node/replica |
|
||||
| 替换删除与空环 | template/README.md:3(更新/删除后不能复用陈旧环) | 重复add原子换replicas返回False,remove存在bool,空环lookupNone,ring全token排序 |
|
||||
| 字符串型域及批量 | template/README.md:9(与 events 等长且顺序一致的 Python list) | bits/replicas int非bool,严格UTF8/1024bytes含NUL非ASCII,10000事件/128节点支持;空[] |
|
||||
|
||||
- 题面改动:solve(data) 的整体返回值是与 events 等长且顺序一致的 Python list,每项分别为对应事件规定的 bool、node 字符串、None 或 token 列表;events 为空时返回 [],仍须验证 bits。
|
||||
- 改动依据:原文每事件对应输出未明确solve外层类型,原check/gold/valid均为保序等长list;只补容器和空返回,输入字节编码/数值类型已明确。
|
||||
- 判据与标准答案:原判据、gold 和 valid 未因校准结果而改写;重写隔离时仅迁移执行边界,保留原断言语义。
|
||||
- 合法解:只要求原公开接口、类型和行为;原 valid 样例(如有)作为合法替代解校准,不限定实现算法或源码形态。
|
||||
- 隔离:沿用受保护 verify.py 的 root 判据和降权候选子进程;正式容器独立校准;本地模式只执行本仓库可信样例。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不运行 Qwen 或其他模型;难度 UNMEASURED,未试采。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- 作者已逐题完整读 README、check.py、附属 Python 判据、gold 与 valid(如有),核对阈值等号、精确/浮点语义、int/float/bool、规模、空输入、异常及容差。
|
||||
- 状态:CALIBRATED;只到两道校准闸门,尚未真实试采,不记 ADMITTED。
|
||||
- 闸门1可信本地:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/local/calibration-90909e4cd519494da087facad1e38361。
|
||||
- 闸门2trace6 Docker:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/docker/calibration-09f07d9f17ff4184807775f94b1af5e0。
|
||||
- 正式镜像:ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1。
|
||||
- 每类样例分别五次;若含 cheat_read_grader,本地无隔离可读而 PASS 仅按规范 §7 记例外,正式 Docker 必须 FAIL。
|
||||
- 独立只读审阅由主控另存本批 review 证据;本 spec 不代替独立审阅或模型难度测量。
|
||||
|
||||
<!-- shortcut: 原10000事件随机例同时活跃node峰值98,未覆盖128同时活跃恰界,后续获准扩充判据并升版重校准时补齐 -->
|
||||
36
tasks/S500_n2_140/task.json
Normal file
36
tasks/S500_n2_140/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_140",
|
||||
"version": "2",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_140",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_stale_replica_update": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_140_route_consistent_hash_ring",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_predecessor_instead_of_successor.sh",
|
||||
"cheat_stale_replica_update": "cheat_stale_replica_update.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
tasks/S500_n2_140/template/README.md
Normal file
9
tasks/S500_n2_140/template/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# 分片遥测一致性哈希
|
||||
|
||||
输入{bits:b,events:[event,...]},b为1..16的int不含bool,环大小2^b。哈希H(bytes)=SHA256摘要前8字节按大端无符号整数解释后,与(2^b-1)按位AND。节点名须非空str,key可为空str;都必须能严格UTF-8编码且编码长度<=1024字节(允许NUL和非ASCII)。虚拟节点i(0起)token输入字节为b'V'+节点UTF8字节数的4字节大端整数+节点UTF8+i的4字节大端整数。key哈希输入字节为b'K'+key字节数的4字节大端整数+key UTF8。事件add:{op:'add',node,replicas},replicas为1..32的int;新增节点或原子替换已有节点的虚拟节点数量,输出是否此前不存在的bool。remove:{op:'remove',node}删除其全部token,输出是否存在bool。lookup:{op:'lookup',key}选择position>=key哈希的第一个token,若无则环绕到最小position;相同position按(node字符串字典序,replica索引)取最小,输出所属node,空环输出None。ring:{op:'ring'}输出全部token列表[{position,node,replica},...],按(position,node,replica)排序。solve返回每事件对应输出,初始无节点。支持128个活跃节点及10000事件。小bits故意允许真实哈希碰撞,不能丢弃碰撞token;更新/删除后不能复用陈旧环。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
|
||||
## 本批公开约定澄清
|
||||
|
||||
solve(data) 的整体返回值是与 events 等长且顺序一致的 Python list,每项分别为对应事件规定的 bool、node 字符串、None 或 token 列表;events 为空时返回 [],仍须验证 bits。
|
||||
3
tasks/S500_n2_140/template/task.py
Normal file
3
tasks/S500_n2_140/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
58
tasks/S500_n2_140/valid_alternative/task.py
Normal file
58
tasks/S500_n2_140/valid_alternative/task.py
Normal file
@ -0,0 +1,58 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import hashlib
|
||||
|
||||
def utf8(x,nonempty=False):
|
||||
if not isinstance(x,str) or (nonempty and not x):raise ValueError('text')
|
||||
try:b=x.encode('utf-8')
|
||||
except UnicodeError:raise ValueError('utf8')
|
||||
if len(b)>1024:raise ValueError('text length')
|
||||
return b
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);bits=field(d,'bits');E=[]
|
||||
if type(bits) is not int or not 1<=bits<=16:raise ValueError('bits')
|
||||
for row in arr(field(d,'events')):
|
||||
row=obj(row);op=field(row,'op')
|
||||
if op in ('add','remove'):
|
||||
node=field(row,'node');utf8(node,True);replicas=field(row,'replicas') if op=='add' else None
|
||||
if op=='add' and (type(replicas) is not int or not 1<=replicas<=32):raise ValueError('replicas')
|
||||
E.append((op,node,replicas))
|
||||
elif op=='lookup':key=field(row,'key');utf8(key);E.append((op,key,None))
|
||||
elif op=='ring':E.append((op,None,None))
|
||||
else:raise ValueError('op')
|
||||
return bits,E
|
||||
|
||||
def digest(bits,prefix,name,index=None):
|
||||
encoded=utf8(name);payload=prefix+len(encoded).to_bytes(4,'big')+encoded
|
||||
if index is not None:payload+=index.to_bytes(4,'big')
|
||||
return int.from_bytes(hashlib.sha256(payload).digest()[:8],'big')&((1<<bits)-1)
|
||||
def solve(data):
|
||||
bits,E=prepare(data);tokens={};out=[];mod=1<<bits
|
||||
for op,name,count in E:
|
||||
if op=='add':new=name not in tokens;tokens[name]=[(digest(bits,b'V',name,i),name,i) for i in range(count)];out.append(new)
|
||||
elif op=='remove':out.append(name in tokens);tokens.pop(name,None)
|
||||
else:
|
||||
entries=[token for seq in tokens.values() for token in seq]
|
||||
if op=='ring':out.append([{'position':p,'node':n,'replica':i} for p,n,i in sorted(entries)])
|
||||
elif not entries:out.append(None)
|
||||
else:h=digest(bits,b'K',name);out.append(min(entries,key=lambda token:((token[0]-h)%mod,token[1],token[2]))[1])
|
||||
return out
|
||||
130
tasks/S500_n2_140/verify.py
Normal file
130
tasks/S500_n2_140/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
46
tasks/S500_n2_142/cheat/task.py
Normal file
46
tasks/S500_n2_142/cheat/task.py
Normal file
@ -0,0 +1,46 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);N=arr(field(d,'nodes'));raw=arr(field(d,'edges'));E=arr(field(d,'events'))
|
||||
if any(not isinstance(n,str) or not n for n in N) or len(set(N))!=len(N):raise ValueError('nodes')
|
||||
graph={n:set() for n in N}
|
||||
for pair in raw:
|
||||
a,b=arr(pair,2)
|
||||
if not isinstance(a,str) or not isinstance(b,str) or a not in graph or b not in graph:raise ValueError('edge')
|
||||
graph[a].add(b);graph[b].add(a)
|
||||
events=[]
|
||||
for e in E:
|
||||
e=obj(e);i=field(e,'id');s=field(e,'source');t=field(e,'ttl')
|
||||
if not isinstance(i,str) or not i or not isinstance(s,str) or s not in graph or type(t) is not int or not 0<=t<=64:raise ValueError('message')
|
||||
events.append((i,s,t))
|
||||
return graph,events
|
||||
from collections import deque
|
||||
def solve(data):
|
||||
graph,E=prepare(data);seen={n:set() for n in graph};out=[]
|
||||
for mid,source,ttl in E:
|
||||
seen={n:set() for n in graph};todo=deque([(source,ttl)]);delivered=[]
|
||||
while todo:
|
||||
n,t=todo.popleft()
|
||||
if mid in seen[n]:continue
|
||||
seen[n].add(mid);delivered.append({'node':n,'ttl':t})
|
||||
if t>0:todo.extend((v,t-1) for v in sorted(graph[n]))
|
||||
out.append(sorted(delivered,key=lambda x:x['node']))
|
||||
return out
|
||||
46
tasks/S500_n2_142/cheat_ttl_zero_dropped/task.py
Normal file
46
tasks/S500_n2_142/cheat_ttl_zero_dropped/task.py
Normal file
@ -0,0 +1,46 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);N=arr(field(d,'nodes'));raw=arr(field(d,'edges'));E=arr(field(d,'events'))
|
||||
if any(not isinstance(n,str) or not n for n in N) or len(set(N))!=len(N):raise ValueError('nodes')
|
||||
graph={n:set() for n in N}
|
||||
for pair in raw:
|
||||
a,b=arr(pair,2)
|
||||
if not isinstance(a,str) or not isinstance(b,str) or a not in graph or b not in graph:raise ValueError('edge')
|
||||
graph[a].add(b);graph[b].add(a)
|
||||
events=[]
|
||||
for e in E:
|
||||
e=obj(e);i=field(e,'id');s=field(e,'source');t=field(e,'ttl')
|
||||
if not isinstance(i,str) or not i or not isinstance(s,str) or s not in graph or type(t) is not int or not 0<=t<=64:raise ValueError('message')
|
||||
events.append((i,s,t))
|
||||
return graph,events
|
||||
from collections import deque
|
||||
def solve(data):
|
||||
graph,E=prepare(data);seen={n:set() for n in graph};out=[]
|
||||
for mid,source,ttl in E:
|
||||
todo=deque([(source,ttl)]);delivered=[]
|
||||
while todo:
|
||||
n,t=todo.popleft()
|
||||
if mid in seen[n] or t==0:continue
|
||||
seen[n].add(mid);delivered.append({'node':n,'ttl':t})
|
||||
if t>0:todo.extend((v,t-1) for v in sorted(graph[n]))
|
||||
out.append(sorted(delivered,key=lambda x:x['node']))
|
||||
return out
|
||||
79
tasks/S500_n2_142/check.py
Normal file
79
tasks/S500_n2_142/check.py
Normal file
@ -0,0 +1,79 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
base=dict(nodes=['a','b','c','d','z'],edges=[['a','b'],['b','c'],['c','a'],['c','d'],['a','a'],['a','b']],events=[dict(id='m',source='a',ttl=1),dict(id='m',source='a',ttl=5),dict(id='m',source='d',ttl=5),dict(id='m',source='z',ttl=0),dict(id='n',source='d',ttl=2)]);cases=[base,dict(nodes=[],edges=[],events=[])];rng=random.Random(1142);N=[str(i) for i in range(2000)];edges=[[str(i),str((i+1)%2000)] for i in range(2000)]+[[rng.choice(N),rng.choice(N)] for _ in range(3000)];events=[dict(id='m'+str(rng.randrange(200)),source=rng.choice(N),ttl=rng.randrange(7)) for _ in range(5000)];cases.append(dict(nodes=N,edges=edges,events=events))
|
||||
def oracle(d):
|
||||
import heapq
|
||||
G={n:set() for n in d['nodes']}
|
||||
for a,b in d['edges']:G[a].add(b);G[b].add(a)
|
||||
seen={n:set() for n in G};out=[]
|
||||
for e in d['events']:
|
||||
mid=e['id'];dist={};heap=[(0,e['source'])]
|
||||
while heap:
|
||||
length,n=heapq.heappop(heap)
|
||||
if length>e['ttl'] or n in dist or mid in seen[n]:continue
|
||||
dist[n]=length
|
||||
for v in G[n]:heapq.heappush(heap,(length+1,v))
|
||||
for n in dist:seen[n].add(mid)
|
||||
out.append([dict(node=n,ttl=e['ttl']-dist[n]) for n in sorted(dist)])
|
||||
return out
|
||||
bad=[None,{},dict(base,nodes=['a','a']),dict(base,edges=[['a','unknown']]),dict(base,events=[dict(id='m',source='q',ttl=1)]),dict(base,events=[dict(id='m',source='a',ttl=-1)]),dict(base,events=[dict(id='m',source='a',ttl=65)]),dict(base,events=[dict(id='m',source='a',ttl=True)]),dict(base,events=[dict(id='',source='a',ttl=0)]),dict(base,edges=[['a']])]
|
||||
return cases+bad,[{'ok':oracle(d)} for d in cases]+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'nodes': ['a'], 'edges': [], 'events': [{'id': 'm', 'source': 'a', 'ttl': 64}]}, [[{'node': 'a', 'ttl': 64}]])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
46
tasks/S500_n2_142/gold/task.py
Normal file
46
tasks/S500_n2_142/gold/task.py
Normal file
@ -0,0 +1,46 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);N=arr(field(d,'nodes'));raw=arr(field(d,'edges'));E=arr(field(d,'events'))
|
||||
if any(not isinstance(n,str) or not n for n in N) or len(set(N))!=len(N):raise ValueError('nodes')
|
||||
graph={n:set() for n in N}
|
||||
for pair in raw:
|
||||
a,b=arr(pair,2)
|
||||
if not isinstance(a,str) or not isinstance(b,str) or a not in graph or b not in graph:raise ValueError('edge')
|
||||
graph[a].add(b);graph[b].add(a)
|
||||
events=[]
|
||||
for e in E:
|
||||
e=obj(e);i=field(e,'id');s=field(e,'source');t=field(e,'ttl')
|
||||
if not isinstance(i,str) or not i or not isinstance(s,str) or s not in graph or type(t) is not int or not 0<=t<=64:raise ValueError('message')
|
||||
events.append((i,s,t))
|
||||
return graph,events
|
||||
from collections import deque
|
||||
def solve(data):
|
||||
graph,E=prepare(data);seen={n:set() for n in graph};out=[]
|
||||
for mid,source,ttl in E:
|
||||
todo=deque([(source,ttl)]);delivered=[]
|
||||
while todo:
|
||||
n,t=todo.popleft()
|
||||
if mid in seen[n]:continue
|
||||
seen[n].add(mid);delivered.append({'node':n,'ttl':t})
|
||||
if t>0:todo.extend((v,t-1) for v in sorted(graph[n]))
|
||||
out.append(sorted(delivered,key=lambda x:x['node']))
|
||||
return out
|
||||
2
tasks/S500_n2_142/noop/task.py
Normal file
2
tasks/S500_n2_142/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_142/prompt.md
Normal file
3
tasks/S500_n2_142/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成带TTL转发去环并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_142/spec.md
Normal file
63
tasks/S500_n2_142/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_142
|
||||
|
||||
本规格仅供控制侧,路线 A 只填写第 1、4、7 节,其余沿用 Bos 原题。规范见 [任务制作规范](../../docs/task-authoring.md)。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 任务版本 | S500_n2_142 / 2 |
|
||||
| 作者 / 独立评审人 | Bos 原作者;本批 Codex lane1 / 待主控只读复核 |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 来源路线 | A 导入成熟任务;bos.origin=original_authored |
|
||||
| 来源 ID / split 分组键 | S500_n2_142;new_n2_142_route_multicast_ttl / bos:new_n2_142_route_multicast_ttl |
|
||||
| 原项目与冻结版本 | Bos-qiao task_factory_500_20260914;本批只读本地快照 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_142;原 task.json SHA-256 b64f41f93836688ade63f0f197edbe680d435ef696b2470604a22c360f8c1ecc;无独立上游 commit |
|
||||
| 授权与隐私 | 用户 2026-10-20 明确授权本批全部剩余 n2 导入;仅保留任务资产,不执行来源脚本,不含用户会话与凭据 |
|
||||
| 来源组 / 任务族 | Bos n2 / serial-protocol |
|
||||
| 替身测试与用途 | software:工业无线/机器人网状通信仿真器带TTL转发多播消息;合成输入可完整复现,无外设依赖 |
|
||||
| 与已有任务关系 | 独立来源 S500_n2_142,保持来源 split;未声称已经完成跨全部来源的语义去重 |
|
||||
| 验证范围 | README 声明的纯软件数学/事件模型 |
|
||||
| 未验证范围 | 真实 Agent、模型难度、板卡/外设/电气/真实时序和物理安全 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 场景与可观察结果 | 检查方法与容差 |
|
||||
| --- | --- | --- | --- |
|
||||
| BFS TTL与跨事件去重 | README第3段ttl0本地接收不转发、同事件首次最多剩余ttl、seen跨事件、重复边/自环 | 环/自环/重复边、旧节点不再帮转发、相同id换新source/断连、ttl0/64;2000节点5000边5000事件 | oracle最短路径heap在删去已见节点的图上传播,输出ttl=初TTL-distance;严格结构 |
|
||||
| 嵌套输出/空/验证 | README第3段按node排序、空图只空边/事件及v2外层events列表 | 空图空[]、源已见返回对应[]、未知节点/ttl-1/65/bool/空id/坏边拒绝 | ValueError和输入保持;v2明确ttl内置int/拒float |
|
||||
| 通用输入与输出合同 | template/README.md 末段“有限int/float且不包括bool”“必须抛ValueError”“不得改写传入数据” | 缺字段、类型、超域/极大整数等非法输入抛 ValueError;输入保持;仅提交 task.py 自包含 | RUNNER 子进程回传结果/异常,pickle 比对输入;结构精确、浮点 math.isclose(rel_tol=1e-8,abs_tol=1e-8),本题专用容差优先 |
|
||||
|
||||
- 判据独立性:oracle用距离最小heap并在事件末统一加入seen,独立于gold逐个deque接收标记/valid按层集合传播;相同事件最短距离保证最多TTL。
|
||||
- 合法替代解:gold deque BFS,valid_alternative按层集合批处理;跨事件seen均保留,tie不影响最终按node排序结果。
|
||||
- 题面歧义审查:已完整读取 prompt、README、check 与根目录附属 Python、gold、valid、template/noop/cheat;核对阈值等号、实数/浮点、int/float/bool、数量/空输入/异常/容差。题面改动:v2明确solve顶层events等长保序列表、每项为node排序记录列表/无新接收[]/空events[],并明确ttl内置int拒float与bool;依据原check输出嵌套列表/prepare,gold/oracle不变。
|
||||
- 隔离:候选只在 RUNNER 子进程导入,check 保留用例、期望与比对;沿用统一 verify.py 的受保护 grader 与 UID65534 降权探针,不把 host 当隔离证明。候选运行后 check 不再读取其临时文件。
|
||||
- 历史可见性:Agent 只获得 prompt/template,正式判据、gold、spec 与 factory/runs 不进入候选工作区。
|
||||
- 限制:有限隐藏组合不穷尽整个合法输入域;验收结论只到公开软件模型。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不调用 Qwen 或任何真实模型,难度 UNMEASURED。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- [x] 作者逐题核对来源、完整初态、公开行为依据、判据独立性、合法替代解与负例。
|
||||
- [x] 本地与 trace6 Docker 两门完成;每类样例各五次,Docker 全部符合预期且 cleanup confirmed 才记 CALIBRATED。
|
||||
- [ ] 主控独立只读复核与真实试采;本批不记 ADMITTED,不宣称真实模型/硬件通过。
|
||||
|
||||
审核记录:2026-10-20,Codex lane1;状态 CALIBRATED,难度 UNMEASURED。题面修改与依据见第 4 节。
|
||||
|
||||
闸门 1:`runs/20261020-A-bos-n2-9/local/calibration-bfec869965fd4f3da146041c245458e0`,status=PASS,30 次,cleanup=confirmed,accepted=True。闸门 2:`runs/20261020-A-bos-n2-9/docker/calibration-c3ca9cd37e734a458f3f24677382510c`,status=PASS,30 次,cleanup=confirmed,accepted=True。
|
||||
|
||||
固定镜像:`ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。最终 task digest `7c2c6843e52973a96c8c1abfa7fd0ef309d7577c2ad173f74523128d8eaeead0`;原始事实见两门 receipt.json 及本批 gates/S500_n2_142/latest.json,历史输出不覆盖。
|
||||
36
tasks/S500_n2_142/task.json
Normal file
36
tasks/S500_n2_142/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_142",
|
||||
"version": "2",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_142",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_ttl_zero_dropped": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_142_route_multicast_ttl",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_reset_seen_per_event.sh",
|
||||
"cheat_ttl_zero_dropped": "cheat_ttl_zero_dropped.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
7
tasks/S500_n2_142/template/README.md
Normal file
7
tasks/S500_n2_142/template/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 带TTL转发去环
|
||||
|
||||
输入{nodes:[唯一非空字符串,...],edges:[[nodeA,nodeB],...],events:[{id:非空字符串,source:已知node,ttl:0..64整数},...]},ttl不含bool。无向图允许重复边、自环但不重复转发;边端点必须存在。每节点维护跨事件的已见消息id集合。注入时若该source已见该id,则该事件无新投递;否则source先本地接收并标记已见。接收ttl>0的节点向所有邻居转发ttl-1,已见该id的节点丢弃且不再转发;ttl=0仍本地接收但停止转发。采用广度优先传播,同事件每节点首次接收拥有最多剩余ttl。每事件输出新接收记录[{node:名称,ttl:剩余整数},...],按node字典序排序。消息相同id可在不连通或尚未到达节点的新source再次注入;旧节点仍不会帮助继续转发。空图只允许空events/edges,空events合法。支持2000节点、5000边、5000事件;不声称真实网络送达。
|
||||
|
||||
solve(data)返回与events等长且保持事件输入顺序的列表,每项是该事件按node排序的新接收记录列表;无新接收时该项为[],空events返回[]。ttl仅接受Python内置int,不接受bool或任何float(包括1.0等整数值浮点数)。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
3
tasks/S500_n2_142/template/task.py
Normal file
3
tasks/S500_n2_142/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
44
tasks/S500_n2_142/valid_alternative/task.py
Normal file
44
tasks/S500_n2_142/valid_alternative/task.py
Normal file
@ -0,0 +1,44 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);N=arr(field(d,'nodes'));raw=arr(field(d,'edges'));E=arr(field(d,'events'))
|
||||
if any(not isinstance(n,str) or not n for n in N) or len(set(N))!=len(N):raise ValueError('nodes')
|
||||
graph={n:set() for n in N}
|
||||
for pair in raw:
|
||||
a,b=arr(pair,2)
|
||||
if not isinstance(a,str) or not isinstance(b,str) or a not in graph or b not in graph:raise ValueError('edge')
|
||||
graph[a].add(b);graph[b].add(a)
|
||||
events=[]
|
||||
for e in E:
|
||||
e=obj(e);i=field(e,'id');s=field(e,'source');t=field(e,'ttl')
|
||||
if not isinstance(i,str) or not i or not isinstance(s,str) or s not in graph or type(t) is not int or not 0<=t<=64:raise ValueError('message')
|
||||
events.append((i,s,t))
|
||||
return graph,events
|
||||
def solve(data):
|
||||
G,E=prepare(data);old=set();out=[]
|
||||
for message,start,ttl in E:
|
||||
layer={start};fresh={};remaining=ttl
|
||||
while layer:
|
||||
good={n for n in layer if (n,message) not in old};old.update((n,message) for n in good);fresh.update((n,remaining) for n in good)
|
||||
if remaining==0:break
|
||||
layer=set(v for n in good for v in G[n]);remaining-=1
|
||||
out.append([{'node':n,'ttl':fresh[n]} for n in sorted(fresh)])
|
||||
return out
|
||||
130
tasks/S500_n2_142/verify.py
Normal file
130
tasks/S500_n2_142/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
62
tasks/S500_n2_143/cheat/task.py
Normal file
62
tasks/S500_n2_143/cheat/task.py
Normal file
@ -0,0 +1,62 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re
|
||||
def prepare(data):
|
||||
d=obj(data)
|
||||
def name(v):
|
||||
if not isinstance(v,str) or re.fullmatch(r'[A-Za-z0-9_-]{1,32}',v) is None:raise ValueError('identity')
|
||||
return v
|
||||
def integer(v,lo,hi):
|
||||
if type(v) is not int or not lo<=v<=hi:raise ValueError('integer')
|
||||
return v
|
||||
bridge=name(field(d,'bridge_id'));epoch=integer(field(d,'initial_epoch'),0,1000000);ports=[name(x) for x in arr(field(d,'ports'))];cap=integer(field(d,'cache_capacity'),1,1000);events=arr(field(d,'events'))
|
||||
if not 1<=len(ports)<=8 or len(set(ports))!=len(ports) or len(events)>2000:raise ValueError('size or duplicate ports')
|
||||
for e in events:
|
||||
e=obj(e);op=field(e,'op')
|
||||
if op=='reset':integer(field(e,'epoch'),0,1000000)
|
||||
elif op=='ingress':
|
||||
if field(e,'port') not in ports:raise ValueError('port')
|
||||
f=obj(field(e,'frame'));name(field(f,'origin'));integer(field(f,'origin_epoch'),0,1000000);integer(field(f,'sequence'),0,1000000);remaining=integer(field(f,'remaining'),0,16);payload=field(f,'payload_hex');path=arr(field(f,'path'))
|
||||
if not isinstance(payload,str) or len(payload)>128 or len(payload)%2 or any(c not in '0123456789abcdef' for c in payload) or len(path)+remaining>16:raise ValueError('frame bounds')
|
||||
for item in path:item=obj(item);name(field(item,'bridge'));integer(field(item,'epoch'),0,1000000)
|
||||
else:raise ValueError('op')
|
||||
return bridge,epoch,ports,cap,events
|
||||
from collections import OrderedDict
|
||||
def solve(data):
|
||||
bridge,epoch,ports,cap,events=prepare(data);cache=OrderedDict();out=[]
|
||||
for e in events:
|
||||
accepted=False;forwards=[]
|
||||
if e['op']=='reset':
|
||||
reason='stale_epoch'
|
||||
if e['epoch']>epoch:epoch=e['epoch'];cache.clear();accepted=True;reason='reset'
|
||||
else:
|
||||
f=e['frame'];key=(f['origin'],f['origin_epoch'],f['sequence'])
|
||||
if any(h['bridge']==bridge for h in f['path']):reason='loop'
|
||||
elif f['remaining']==0:reason='hop_limit'
|
||||
elif f['payload_hex'] in cache.values():reason='duplicate'
|
||||
elif key in cache:reason='duplicate' if cache[key]==f['payload_hex'] else 'identity_conflict'
|
||||
else:
|
||||
reason='forward';accepted=True;cache[key]=f['payload_hex']
|
||||
if len(cache)>cap:cache.popitem(last=False)
|
||||
frame={k:f[k] for k in ('origin','origin_epoch','sequence','payload_hex')};frame['remaining']=f['remaining']-1;frame['path']=[dict(bridge=h['bridge'],epoch=h['epoch']) for h in f['path']]+[dict(bridge=bridge,epoch=epoch)]
|
||||
forwards=[dict(port=p,frame=dict(frame,path=[dict(h) for h in frame['path']])) for p in ports if p!=e['port']]
|
||||
out.append(dict(accepted=accepted,reason=reason,epoch=epoch,cache_size=len(cache),forwards=forwards))
|
||||
return out
|
||||
61
tasks/S500_n2_143/cheat_forgets_loop_after_restart/task.py
Normal file
61
tasks/S500_n2_143/cheat_forgets_loop_after_restart/task.py
Normal file
@ -0,0 +1,61 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re
|
||||
def prepare(data):
|
||||
d=obj(data)
|
||||
def name(v):
|
||||
if not isinstance(v,str) or re.fullmatch(r'[A-Za-z0-9_-]{1,32}',v) is None:raise ValueError('identity')
|
||||
return v
|
||||
def integer(v,lo,hi):
|
||||
if type(v) is not int or not lo<=v<=hi:raise ValueError('integer')
|
||||
return v
|
||||
bridge=name(field(d,'bridge_id'));epoch=integer(field(d,'initial_epoch'),0,1000000);ports=[name(x) for x in arr(field(d,'ports'))];cap=integer(field(d,'cache_capacity'),1,1000);events=arr(field(d,'events'))
|
||||
if not 1<=len(ports)<=8 or len(set(ports))!=len(ports) or len(events)>2000:raise ValueError('size or duplicate ports')
|
||||
for e in events:
|
||||
e=obj(e);op=field(e,'op')
|
||||
if op=='reset':integer(field(e,'epoch'),0,1000000)
|
||||
elif op=='ingress':
|
||||
if field(e,'port') not in ports:raise ValueError('port')
|
||||
f=obj(field(e,'frame'));name(field(f,'origin'));integer(field(f,'origin_epoch'),0,1000000);integer(field(f,'sequence'),0,1000000);remaining=integer(field(f,'remaining'),0,16);payload=field(f,'payload_hex');path=arr(field(f,'path'))
|
||||
if not isinstance(payload,str) or len(payload)>128 or len(payload)%2 or any(c not in '0123456789abcdef' for c in payload) or len(path)+remaining>16:raise ValueError('frame bounds')
|
||||
for item in path:item=obj(item);name(field(item,'bridge'));integer(field(item,'epoch'),0,1000000)
|
||||
else:raise ValueError('op')
|
||||
return bridge,epoch,ports,cap,events
|
||||
from collections import OrderedDict
|
||||
def solve(data):
|
||||
bridge,epoch,ports,cap,events=prepare(data);cache=OrderedDict();out=[]
|
||||
for e in events:
|
||||
accepted=False;forwards=[]
|
||||
if e['op']=='reset':
|
||||
reason='stale_epoch'
|
||||
if e['epoch']>epoch:epoch=e['epoch'];cache.clear();accepted=True;reason='reset'
|
||||
else:
|
||||
f=e['frame'];key=(f['origin'],f['origin_epoch'],f['sequence'])
|
||||
if any(h['bridge']==bridge and h['epoch']==epoch for h in f['path']):reason='loop'
|
||||
elif f['remaining']==0:reason='hop_limit'
|
||||
elif key in cache:reason='duplicate' if cache[key]==f['payload_hex'] else 'identity_conflict'
|
||||
else:
|
||||
reason='forward';accepted=True;cache[key]=f['payload_hex']
|
||||
if len(cache)>cap:cache.popitem(last=False)
|
||||
frame={k:f[k] for k in ('origin','origin_epoch','sequence','payload_hex')};frame['remaining']=f['remaining']-1;frame['path']=[dict(bridge=h['bridge'],epoch=h['epoch']) for h in f['path']]+[dict(bridge=bridge,epoch=epoch)]
|
||||
forwards=[dict(port=p,frame=dict(frame,path=[dict(h) for h in frame['path']])) for p in ports if p!=e['port']]
|
||||
out.append(dict(accepted=accepted,reason=reason,epoch=epoch,cache_size=len(cache),forwards=forwards))
|
||||
return out
|
||||
101
tasks/S500_n2_143/check.py
Normal file
101
tasks/S500_n2_143/check.py
Normal file
@ -0,0 +1,101 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
def frame(seq=0,origin='motor',epoch=0,payload='00',remaining=16,path=None):return dict(origin=origin,origin_epoch=epoch,sequence=seq,payload_hex=payload,remaining=remaining,path=[] if path is None else path)
|
||||
def ingress(f=None,port='can0'):return dict(op='ingress',port=port,frame=frame() if f is None else f)
|
||||
def reset(e):return dict(op='reset',epoch=e)
|
||||
def case(E=(),cap=2,ports=None):return dict(bridge_id='gateway',initial_epoch=0,ports=['can0','uart0','can1'] if ports is None else ports,cache_capacity=cap,events=list(E))
|
||||
old=[dict(bridge='gateway',epoch=0)];other=[dict(bridge='other',epoch=1000000)]
|
||||
cases=[case(),case([ingress(),ingress(port='uart0'),ingress(frame(payload='ff')),ingress(frame(1)),ingress(frame(0,epoch=1))]),case([ingress(frame(0)),ingress(frame(1)),ingress(frame(0)),ingress(frame(2)),ingress(frame(0))]),case([ingress(frame(0,remaining=0)),ingress(frame(0)),ingress(frame(0,remaining=0,path=old)),reset(1),ingress(frame(0,remaining=1,path=old)),ingress(frame(0)),reset(1),reset(0)]),case([ingress(frame(0,remaining=1,path=other*15))]),case([ingress(frame(payload=''))],ports=['can0']),case([ingress(frame(0,payload='00')),ingress(frame(1,payload='00'))]),case([reset(1000000),ingress(frame(1000000,epoch=1000000,payload='ff'*64))])]
|
||||
rng=random.Random(2143)
|
||||
for _ in range(55):
|
||||
E=[]
|
||||
for j in range(rng.randrange(1,50)):
|
||||
if rng.randrange(8)==0:E.append(reset(rng.randrange(5)))
|
||||
else:E.append(ingress(frame(rng.randrange(10),origin=rng.choice(['motor','imu']),epoch=rng.randrange(3),payload=rng.choice(['','00','ff','c0ffee']),remaining=rng.randrange(0,15),path=rng.choice([[],old,other])),rng.choice(['can0','can1','uart0'])))
|
||||
cases.append(case(E,cap=rng.randrange(1,10)))
|
||||
def oracle(d):
|
||||
epoch=d['initial_epoch'];accepted_log=[];out=[]
|
||||
for e in d['events']:
|
||||
forwards=[];reason='stale_epoch';ok=False
|
||||
if e['op']=='reset':
|
||||
if e['epoch']>epoch:epoch=e['epoch'];accepted_log=[];ok=True;reason='reset'
|
||||
else:
|
||||
f=e['frame'];identity=(f['origin'],f['origin_epoch'],f['sequence']);recent=accepted_log[-d['cache_capacity']:];matches=[x for x in recent if x[0]==identity]
|
||||
if sum(x['bridge']==d['bridge_id'] for x in f['path']):reason='loop'
|
||||
elif f['remaining']<1:reason='hop_limit'
|
||||
elif matches:reason='duplicate' if matches[0][1]==f['payload_hex'] else 'identity_conflict'
|
||||
else:
|
||||
ok=True;reason='forward';accepted_log.append((identity,f['payload_hex']));route=[{'bridge':x['bridge'],'epoch':x['epoch']} for x in f['path']]+[{'bridge':d['bridge_id'],'epoch':epoch}]
|
||||
for port in d['ports']:
|
||||
if port!=e['port']:forwards.append({'port':port,'frame':dict(origin=identity[0],origin_epoch=identity[1],sequence=identity[2],payload_hex=f['payload_hex'],remaining=f['remaining']-1,path=route)})
|
||||
out.append(dict(accepted=ok,reason=reason,epoch=epoch,cache_size=min(d['cache_capacity'],len(accepted_log)),forwards=forwards))
|
||||
return out
|
||||
truth=[{'ok':oracle(d)} for d in cases]
|
||||
E=[ingress(frame(i,payload='ff'*64)) for i in range(1000)]+[ingress(frame(i,payload='ff'*64)) for i in range(1000)];d=case(E,cap=1000,ports=['can0']+['bus'+str(i) for i in range(7)]);cases.append(d);truth.append({'ok':oracle(d)})
|
||||
base=case();bad=[None,{},case([reset(0)]*2001)]
|
||||
for key,values in [('bridge_id',[None,'','a'*33,'中']),('initial_epoch',[True,0.,-1,1000001]),('ports',[None,[],['can0']*2,['p'+str(i) for i in range(9)],[None]]),('cache_capacity',[True,1.,0,1001]),('events',[None,[None],[{}]])]:
|
||||
for v in values:bad.append(dict(base,**{key:v}))
|
||||
for key,values in [('origin',[None,'']),('origin_epoch',[True,0.,-1,1000001]),('sequence',[True,0.,-1,1000001]),('payload_hex',[None,'0','GG','aa '*2,'00'*65]),('remaining',[True,0.,-1,17]),('path',[None,[None],[{}],[dict(bridge='x',epoch=0)]*17,[dict(bridge='x',epoch=True)],[dict(bridge='x',epoch=1000001)]])]:
|
||||
for v in values:bad.append(case([ingress(dict(frame(),**{key:v}))]))
|
||||
bad.extend([case([ingress(port='missing')]),case([ingress(None,port=True)]),case([ingress(frame(remaining=16,path=other))])])
|
||||
for v in (True,0.,-1,1000001):bad.append(case([reset(v)]))
|
||||
return cases+bad,truth+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'bridge_id': 'gateway', 'initial_epoch': 1000000, 'ports': ['can0'], 'cache_capacity': 1000, 'events': [{'op': 'reset', 'epoch': 1000000}]}, [{'accepted': False, 'reason': 'stale_epoch', 'epoch': 1000000, 'cache_size': 0, 'forwards': []}])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
61
tasks/S500_n2_143/gold/task.py
Normal file
61
tasks/S500_n2_143/gold/task.py
Normal file
@ -0,0 +1,61 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re
|
||||
def prepare(data):
|
||||
d=obj(data)
|
||||
def name(v):
|
||||
if not isinstance(v,str) or re.fullmatch(r'[A-Za-z0-9_-]{1,32}',v) is None:raise ValueError('identity')
|
||||
return v
|
||||
def integer(v,lo,hi):
|
||||
if type(v) is not int or not lo<=v<=hi:raise ValueError('integer')
|
||||
return v
|
||||
bridge=name(field(d,'bridge_id'));epoch=integer(field(d,'initial_epoch'),0,1000000);ports=[name(x) for x in arr(field(d,'ports'))];cap=integer(field(d,'cache_capacity'),1,1000);events=arr(field(d,'events'))
|
||||
if not 1<=len(ports)<=8 or len(set(ports))!=len(ports) or len(events)>2000:raise ValueError('size or duplicate ports')
|
||||
for e in events:
|
||||
e=obj(e);op=field(e,'op')
|
||||
if op=='reset':integer(field(e,'epoch'),0,1000000)
|
||||
elif op=='ingress':
|
||||
if field(e,'port') not in ports:raise ValueError('port')
|
||||
f=obj(field(e,'frame'));name(field(f,'origin'));integer(field(f,'origin_epoch'),0,1000000);integer(field(f,'sequence'),0,1000000);remaining=integer(field(f,'remaining'),0,16);payload=field(f,'payload_hex');path=arr(field(f,'path'))
|
||||
if not isinstance(payload,str) or len(payload)>128 or len(payload)%2 or any(c not in '0123456789abcdef' for c in payload) or len(path)+remaining>16:raise ValueError('frame bounds')
|
||||
for item in path:item=obj(item);name(field(item,'bridge'));integer(field(item,'epoch'),0,1000000)
|
||||
else:raise ValueError('op')
|
||||
return bridge,epoch,ports,cap,events
|
||||
from collections import OrderedDict
|
||||
def solve(data):
|
||||
bridge,epoch,ports,cap,events=prepare(data);cache=OrderedDict();out=[]
|
||||
for e in events:
|
||||
accepted=False;forwards=[]
|
||||
if e['op']=='reset':
|
||||
reason='stale_epoch'
|
||||
if e['epoch']>epoch:epoch=e['epoch'];cache.clear();accepted=True;reason='reset'
|
||||
else:
|
||||
f=e['frame'];key=(f['origin'],f['origin_epoch'],f['sequence'])
|
||||
if any(h['bridge']==bridge for h in f['path']):reason='loop'
|
||||
elif f['remaining']==0:reason='hop_limit'
|
||||
elif key in cache:reason='duplicate' if cache[key]==f['payload_hex'] else 'identity_conflict'
|
||||
else:
|
||||
reason='forward';accepted=True;cache[key]=f['payload_hex']
|
||||
if len(cache)>cap:cache.popitem(last=False)
|
||||
frame={k:f[k] for k in ('origin','origin_epoch','sequence','payload_hex')};frame['remaining']=f['remaining']-1;frame['path']=[dict(bridge=h['bridge'],epoch=h['epoch']) for h in f['path']]+[dict(bridge=bridge,epoch=epoch)]
|
||||
forwards=[dict(port=p,frame=dict(frame,path=[dict(h) for h in frame['path']])) for p in ports if p!=e['port']]
|
||||
out.append(dict(accepted=accepted,reason=reason,epoch=epoch,cache_size=len(cache),forwards=forwards))
|
||||
return out
|
||||
2
tasks/S500_n2_143/noop/task.py
Normal file
2
tasks/S500_n2_143/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_143/prompt.md
Normal file
3
tasks/S500_n2_143/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成桥接双总线回环抑制并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_143/spec.md
Normal file
63
tasks/S500_n2_143/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_143
|
||||
|
||||
规范:[任务制作规范](../../docs/task-authoring.md)。路线 A 仅填第 1、4、7 节。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 版本 | S500_n2_143 / 2 |
|
||||
| 作者 / 独立评审人 | Codex lane2 / root(2026-10-20,只读审阅通过;证据见本批 root-review-group12.json) |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 原项目与快照 | Bos-qiao envs/S500_n2_143;本批只读复制到 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_143 |
|
||||
| 来源路线 / 来源ID | A 导入成熟任务(Bos 原题) / S500_n2_143 |
|
||||
| 来源与授权 | 用户 2026-10-20 第9批 BRIEF;2026-10-12 项目资产接入授权;来源只读,样例脚本仅解析 |
|
||||
| 隐私处理 | 无真实用户会话;本批不读取凭据 |
|
||||
| 替身测试 | 软件输入驱动纯 Python 行为;不需要板卡或真实外设,software |
|
||||
| split 分组键 | bos:new_n2_143_route_origin_suppression |
|
||||
| 来源组 / 根因族 | Bos n2 / serial-protocol |
|
||||
| 与已有任务的关系 | 本批剩余来源独立导入;非已有任务改名 |
|
||||
| 导入方式 | 直接导入 |
|
||||
| 验证范围 | 原 README 公开合同与原隐藏行为判据 |
|
||||
| 未验证范围 | 只验证纯软件行为;未验证真实硬件、实时性能或模型难度。 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 可观察结果与检查 |
|
||||
| --- | --- | --- |
|
||||
| loop/hop/identity优先级 | template/README.md:5(不比较其epoch) | 任何path本bridge先loop,再remaining0,再三元identity缓存;同payloadduplicate/异payloadconflict |
|
||||
| FIFO与端口转发 | template/README.md:5(重复访问不刷新FIFO) | 独立accepted_log尾cap oracle,goldOrderedDict和validlist;单端口仍cache,ports顺序排除ingress |
|
||||
| 代次reset与公开帧 | template/README.md:6(严格大于当前epoch) | 新epoch清cache但不能绕过path桥id,输出只6字段/path2键,不传播额外键、不改输入 |
|
||||
| 严格类型/边界与逐事件输出 | template/README.md:13(必须是 Python 内置 int) | 所有专属整数字段排bool/float;原cap1000/8ports/2000events大例,ASCIIid、hex及len(path)+remaining<=16 |
|
||||
|
||||
- 题面改动:本题各处标为“整数”的输入字段(initial_epoch、cache_capacity、origin_epoch、sequence、remaining、path 项的 epoch 以及 reset 的 epoch)必须是 Python 内置 int;bool 和所有 float(包括 0.0、1.0 等整数值)均非法并抛 ValueError,通用 int/float 数值段不能放宽这些字段。输出帧与状态中的整数也使用 Python 内置 int。
|
||||
- 改动依据:原文整数不含bool与通用数值段可能误允整数值float;原check逐整数字段含0.0/1.0非法,gold/valid严格type is int。原文已明确逐events列表、帧完整字段与优先级,不改其他合同。
|
||||
- 判据与标准答案:原判据、gold 和 valid 未因校准结果而改写;重写隔离时仅迁移执行边界,保留原断言语义。
|
||||
- 合法解:只要求原公开接口、类型和行为;原 valid 样例(如有)作为合法替代解校准,不限定实现算法或源码形态。
|
||||
- 隔离:沿用受保护 verify.py 的 root 判据和降权候选子进程;正式容器独立校准;本地模式只执行本仓库可信样例。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不运行 Qwen 或其他模型;难度 UNMEASURED,未试采。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- 作者已逐题完整读 README、check.py、附属 Python 判据、gold 与 valid(如有),核对阈值等号、精确/浮点语义、int/float/bool、规模、空输入、异常及容差。
|
||||
- 状态:CALIBRATED;只到两道校准闸门,尚未真实试采,不记 ADMITTED。
|
||||
- 闸门1可信本地:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/local/calibration-48f98891c04e4269a6ae42ac72161700。
|
||||
- 闸门2trace6 Docker:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/docker/calibration-e797a67957764da9bd62df866782d753。
|
||||
- 正式镜像:ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1。
|
||||
- 每类样例分别五次;若含 cheat_read_grader,本地无隔离可读而 PASS 仅按规范 §7 记例外,正式 Docker 必须 FAIL。
|
||||
- 独立只读审阅由主控另存本批 review 证据;本 spec 不代替独立审阅或模型难度测量。
|
||||
36
tasks/S500_n2_143/task.json
Normal file
36
tasks/S500_n2_143/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_143",
|
||||
"version": "2",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_143",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_forgets_loop_after_restart": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_143_route_origin_suppression",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_deduplicates_payload_not_identity.sh",
|
||||
"cheat_forgets_loop_after_restart": "cheat_forgets_loop_after_restart.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
13
tasks/S500_n2_143/template/README.md
Normal file
13
tasks/S500_n2_143/template/README.md
Normal file
@ -0,0 +1,13 @@
|
||||
# 桥接双总线回环抑制
|
||||
|
||||
这是嵌入式网关在多条设备总线之间转发帧时的回环/重复抑制软件模型,不执行真实CAN/UART网络发送。输入{bridge_id,initial_epoch,ports,cache_capacity,events}全部必需。所有标识bridge_id、端口名、origin以及path中的bridge均为1..32字符ASCII字母/数字/下划线/连字符。initial_epoch为0..1000000整数,ports为1..8个互异端口名,按此顺序转发;cache_capacity为1..1000整数,events为0..2000个对象。所有整数不含bool。
|
||||
op='ingress'事件必需port和frame,port须在配置中。frame必需{origin,origin_epoch,sequence,payload_hex,remaining,path}:origin_epoch、sequence均0..1000000整数;payload_hex为0..128字符偶数长度小写十六进制(原始设备二进制载荷,不根据载荷相等判消息相同);remaining为0..16整数剩余转发跳数;path为0..16个{bridge,epoch}对象,epoch为0..1000000整数;要求len(path)+remaining<=16。path可含重复桥标记,本地只执行下述规则。op='reset'事件必需epoch,0..1000000整数,表示本桥重启到新代次。
|
||||
初始缓存空,当前桥代次initial_epoch。ingress依次判定:①path中任何bridge等于本bridge_id即拒绝loop,不比较其epoch(重启不能解除旧帧的回环标记);②remaining=0拒绝hop_limit;③消息身份=(origin,origin_epoch,sequence)已缓存则,payload_hex相同拒绝duplicate,否则identity_conflict。路径、来源端口不同不改变身份;拒绝不登记新身份、不刷新缓存顺序。④其余接受forward,将身份和payload记入先进先出缓存,超过capacity只驱逐最早接受的一个身份;重复访问不刷新FIFO。产生输出帧,payload和身份不变,remaining减1,path尾追加{bridge:本ID,epoch:当前代次}。依ports配置顺序向除 ingress端口以外的所有端口各输出一份;只有一个端口时仍接受/cache但forward列表为空。
|
||||
reset仅当请求epoch严格大于当前epoch时接受reset并清空缓存;否则拒绝stale_epoch且状态不变。清缓存后没有本桥path标记的相同身份允许重新接受,已经带本bridge_id的帧仍拒绝loop。
|
||||
返回逐events列表,每行{accepted,reason,epoch,cache_size,forwards}。accepted仅forward或成功reset时True;reason使用上述固定字符串;epoch和cache_size为本行之后状态;forwards为{port,frame}列表,所有拒绝/reset时为空。输出frame只含公开6个必需字段,path项只含bridge/epoch;允许源对象额外键但不向输出帧传播。不得修改输入path或frame。不声称缓存覆盖了无限历史,也不以单网关模拟证明整个真实网络无环。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
|
||||
## 本批公开约定澄清
|
||||
|
||||
本题各处标为“整数”的输入字段(initial_epoch、cache_capacity、origin_epoch、sequence、remaining、path 项的 epoch 以及 reset 的 epoch)必须是 Python 内置 int;bool 和所有 float(包括 0.0、1.0 等整数值)均非法并抛 ValueError,通用 int/float 数值段不能放宽这些字段。输出帧与状态中的整数也使用 Python 内置 int。
|
||||
3
tasks/S500_n2_143/template/task.py
Normal file
3
tasks/S500_n2_143/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
58
tasks/S500_n2_143/valid_alternative/task.py
Normal file
58
tasks/S500_n2_143/valid_alternative/task.py
Normal file
@ -0,0 +1,58 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re
|
||||
def prepare(data):
|
||||
d=obj(data)
|
||||
def name(v):
|
||||
if not isinstance(v,str) or re.fullmatch(r'[A-Za-z0-9_-]{1,32}',v) is None:raise ValueError('identity')
|
||||
return v
|
||||
def integer(v,lo,hi):
|
||||
if type(v) is not int or not lo<=v<=hi:raise ValueError('integer')
|
||||
return v
|
||||
bridge=name(field(d,'bridge_id'));epoch=integer(field(d,'initial_epoch'),0,1000000);ports=[name(x) for x in arr(field(d,'ports'))];cap=integer(field(d,'cache_capacity'),1,1000);events=arr(field(d,'events'))
|
||||
if not 1<=len(ports)<=8 or len(set(ports))!=len(ports) or len(events)>2000:raise ValueError('size or duplicate ports')
|
||||
for e in events:
|
||||
e=obj(e);op=field(e,'op')
|
||||
if op=='reset':integer(field(e,'epoch'),0,1000000)
|
||||
elif op=='ingress':
|
||||
if field(e,'port') not in ports:raise ValueError('port')
|
||||
f=obj(field(e,'frame'));name(field(f,'origin'));integer(field(f,'origin_epoch'),0,1000000);integer(field(f,'sequence'),0,1000000);remaining=integer(field(f,'remaining'),0,16);payload=field(f,'payload_hex');path=arr(field(f,'path'))
|
||||
if not isinstance(payload,str) or len(payload)>128 or len(payload)%2 or any(c not in '0123456789abcdef' for c in payload) or len(path)+remaining>16:raise ValueError('frame bounds')
|
||||
for item in path:item=obj(item);name(field(item,'bridge'));integer(field(item,'epoch'),0,1000000)
|
||||
else:raise ValueError('op')
|
||||
return bridge,epoch,ports,cap,events
|
||||
def solve(data):
|
||||
bridge,epoch,ports,cap,events=prepare(data);history=[];out=[]
|
||||
for event in events:
|
||||
forwards=[];accepted=False
|
||||
if event['op']=='reset':
|
||||
accepted=event['epoch']>epoch;reason='reset' if accepted else 'stale_epoch'
|
||||
if accepted:epoch=event['epoch'];history=[]
|
||||
else:
|
||||
f=event['frame'];identity=[f[k] for k in ['origin','origin_epoch','sequence']];old=next((r for r in history if r[0]==identity),None)
|
||||
conditions=[(bridge in [p['bridge'] for p in f['path']],'loop'),(f['remaining']==0,'hop_limit'),(old is not None and old[1]==f['payload_hex'],'duplicate'),(old is not None,'identity_conflict')];reason=next((reason for condition,reason in conditions if condition),'forward');accepted=reason=='forward'
|
||||
if accepted:
|
||||
history=(history+[(identity,f['payload_hex'])])[-cap:]
|
||||
for port in ports:
|
||||
if port==event['port']:continue
|
||||
frame=dict(origin=identity[0],origin_epoch=identity[1],sequence=identity[2],payload_hex=f['payload_hex'],remaining=f['remaining']-1,path=[{'bridge':p['bridge'],'epoch':p['epoch']} for p in f['path']]+[{'bridge':bridge,'epoch':epoch}]);forwards.append(dict(port=port,frame=frame))
|
||||
out.append(dict(accepted=accepted,reason=reason,epoch=epoch,cache_size=len(history),forwards=forwards))
|
||||
return out
|
||||
130
tasks/S500_n2_143/verify.py
Normal file
130
tasks/S500_n2_143/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
54
tasks/S500_n2_145/cheat/task.py
Normal file
54
tasks/S500_n2_145/cheat/task.py
Normal file
@ -0,0 +1,54 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);B=field(d,'max_bytes');D=num(field(d,'max_delay'));E=arr(field(d,'events'));last=-math.inf;out=[]
|
||||
if type(B) is not int or not 1<=B<=1000000 or D<1e-6:raise ValueError('batch parameters')
|
||||
for e in E:
|
||||
e=obj(e);op=field(e,'op');t=num(field(e,'time'))
|
||||
if op not in ('message','tick','flush') or t<last:raise ValueError('event/time')
|
||||
last=t;p=None;n=0
|
||||
if op=='message':
|
||||
p=field(e,'payload')
|
||||
if not isinstance(p,str):raise ValueError('payload')
|
||||
try:n=len(p)
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
out.append((op,t,p,n))
|
||||
return B,D,out
|
||||
def solve(data):
|
||||
B,D,E=prepare(data);batch=[];size=0;first=None;out=[]
|
||||
for op,t,p,n in E:
|
||||
emitted=[]
|
||||
def emit(reason):
|
||||
nonlocal batch,size,first
|
||||
if batch:emitted.append(dict(messages=batch[:],bytes=size,reason=reason))
|
||||
batch=[];size=0;first=None
|
||||
if batch and t-first>=D:emit('delay')
|
||||
if op=='flush':emit('manual')
|
||||
elif op=='message':
|
||||
if n>B:
|
||||
emit('capacity');emitted.append(dict(messages=[p],bytes=n,reason='oversize'))
|
||||
else:
|
||||
if batch and size+n>B:emit('capacity')
|
||||
if not batch:first=t
|
||||
batch.append(p);size+=n
|
||||
if size==B:emit('full')
|
||||
out.append(emitted)
|
||||
return dict(emissions=out,pending=batch)
|
||||
54
tasks/S500_n2_145/cheat_reset_timer_on_append/task.py
Normal file
54
tasks/S500_n2_145/cheat_reset_timer_on_append/task.py
Normal file
@ -0,0 +1,54 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);B=field(d,'max_bytes');D=num(field(d,'max_delay'));E=arr(field(d,'events'));last=-math.inf;out=[]
|
||||
if type(B) is not int or not 1<=B<=1000000 or D<1e-6:raise ValueError('batch parameters')
|
||||
for e in E:
|
||||
e=obj(e);op=field(e,'op');t=num(field(e,'time'))
|
||||
if op not in ('message','tick','flush') or t<last:raise ValueError('event/time')
|
||||
last=t;p=None;n=0
|
||||
if op=='message':
|
||||
p=field(e,'payload')
|
||||
if not isinstance(p,str):raise ValueError('payload')
|
||||
try:n=len(p.encode('utf-8'))
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
out.append((op,t,p,n))
|
||||
return B,D,out
|
||||
def solve(data):
|
||||
B,D,E=prepare(data);batch=[];size=0;first=None;out=[]
|
||||
for op,t,p,n in E:
|
||||
emitted=[]
|
||||
def emit(reason):
|
||||
nonlocal batch,size,first
|
||||
if batch:emitted.append(dict(messages=batch[:],bytes=size,reason=reason))
|
||||
batch=[];size=0;first=None
|
||||
if batch and t-first>=D:emit('delay')
|
||||
if op=='flush':emit('manual')
|
||||
elif op=='message':
|
||||
if n>B:
|
||||
emit('capacity');emitted.append(dict(messages=[p],bytes=n,reason='oversize'))
|
||||
else:
|
||||
if batch and size+n>B:emit('capacity')
|
||||
first=t
|
||||
batch.append(p);size+=n
|
||||
if size==B:emit('full')
|
||||
out.append(emitted)
|
||||
return dict(emissions=out,pending=batch)
|
||||
90
tasks/S500_n2_145/check.py
Normal file
90
tasks/S500_n2_145/check.py
Normal file
@ -0,0 +1,90 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
def M(t,p):return dict(op='message',time=t,payload=p)
|
||||
def T(t):return dict(op='tick',time=t)
|
||||
def F(t):return dict(op='flush',time=t)
|
||||
cases=[dict(max_bytes=4,max_delay=3,events=[M(0,'ab'),M(1,'c'),T(3),M(3,'机器人'),M(4,'1234'),M(5,''),F(5),F(6)]),dict(max_bytes=4,max_delay=10,events=[M(0,'abc'),M(1,'xy'),M(2,'z'),M(3,'!'),M(4,'a')]),dict(max_bytes=9,max_delay=2,events=[M(0,'a'),M(1,'b'),T(2)]),dict(max_bytes=1,max_delay=1,events=[])];rng=random.Random(1145);E=[]
|
||||
for i in range(50000):
|
||||
op=rng.choice(['message','message','tick','flush']);E.append(M(i/4,rng.choice(['','a','é','机器人','123456789'])) if op=='message' else T(i/4) if op=='tick' else F(i/4))
|
||||
cases.append(dict(max_bytes=7,max_delay=2,events=E))
|
||||
def oracle(d):
|
||||
rows=[];pending=[];start=None
|
||||
for e in d['events']:
|
||||
emitted=[]
|
||||
def push(reason):
|
||||
nonlocal pending,start
|
||||
if pending:emitted.append(dict(messages=pending[:],bytes=sum(len(p.encode()) for p in pending),reason=reason))
|
||||
pending=[];start=None
|
||||
if pending and e['time']-start>=d['max_delay']:push('delay')
|
||||
if e['op']=='flush':push('manual')
|
||||
if e['op']=='message':
|
||||
p=e['payload'];size=len(p.encode());old=sum(len(s.encode()) for s in pending)
|
||||
if old+size>d['max_bytes']:push('capacity')
|
||||
if size>d['max_bytes']:emitted.append(dict(messages=[p],bytes=size,reason='oversize'))
|
||||
else:
|
||||
if not pending:start=e['time']
|
||||
pending.append(p)
|
||||
if sum(len(s.encode()) for s in pending)==d['max_bytes']:push('full')
|
||||
rows.append(emitted)
|
||||
return dict(emissions=rows,pending=pending)
|
||||
base=dict(max_bytes=1,max_delay=1,events=[]);bad=[None,{},dict(base,max_bytes=0),dict(base,max_bytes=True),dict(base,max_delay=0),dict(base,events=[M(2,'a'),T(1)]),dict(base,events=[M(1,1)]),dict(base,events=[M(0,'\ud800')]),dict(base,events=[dict(op='tick',time=float('nan'))]),dict(base,events=[dict(op='x',time=0)])]
|
||||
return cases+bad,[{'ok':oracle(d)} for d in cases]+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'max_bytes': 1000000, 'max_delay': 1, 'events': [{'op': 'message', 'time': -1000000, 'payload': 'a'}, {'op': 'tick', 'time': -999999}]}, {'emissions': [[], [{'messages': ['a'], 'bytes': 1, 'reason': 'delay'}]], 'pending': []})
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
54
tasks/S500_n2_145/gold/task.py
Normal file
54
tasks/S500_n2_145/gold/task.py
Normal file
@ -0,0 +1,54 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);B=field(d,'max_bytes');D=num(field(d,'max_delay'));E=arr(field(d,'events'));last=-math.inf;out=[]
|
||||
if type(B) is not int or not 1<=B<=1000000 or D<1e-6:raise ValueError('batch parameters')
|
||||
for e in E:
|
||||
e=obj(e);op=field(e,'op');t=num(field(e,'time'))
|
||||
if op not in ('message','tick','flush') or t<last:raise ValueError('event/time')
|
||||
last=t;p=None;n=0
|
||||
if op=='message':
|
||||
p=field(e,'payload')
|
||||
if not isinstance(p,str):raise ValueError('payload')
|
||||
try:n=len(p.encode('utf-8'))
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
out.append((op,t,p,n))
|
||||
return B,D,out
|
||||
def solve(data):
|
||||
B,D,E=prepare(data);batch=[];size=0;first=None;out=[]
|
||||
for op,t,p,n in E:
|
||||
emitted=[]
|
||||
def emit(reason):
|
||||
nonlocal batch,size,first
|
||||
if batch:emitted.append(dict(messages=batch[:],bytes=size,reason=reason))
|
||||
batch=[];size=0;first=None
|
||||
if batch and t-first>=D:emit('delay')
|
||||
if op=='flush':emit('manual')
|
||||
elif op=='message':
|
||||
if n>B:
|
||||
emit('capacity');emitted.append(dict(messages=[p],bytes=n,reason='oversize'))
|
||||
else:
|
||||
if batch and size+n>B:emit('capacity')
|
||||
if not batch:first=t
|
||||
batch.append(p);size+=n
|
||||
if size==B:emit('full')
|
||||
out.append(emitted)
|
||||
return dict(emissions=out,pending=batch)
|
||||
2
tasks/S500_n2_145/noop/task.py
Normal file
2
tasks/S500_n2_145/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_145/prompt.md
Normal file
3
tasks/S500_n2_145/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成按字节与时限遥测批处理并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_145/spec.md
Normal file
63
tasks/S500_n2_145/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_145
|
||||
|
||||
本规格仅供控制侧,路线 A 只填写第 1、4、7 节,其余沿用 Bos 原题。规范见 [任务制作规范](../../docs/task-authoring.md)。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 任务版本 | S500_n2_145 / 2 |
|
||||
| 作者 / 独立评审人 | Bos 原作者;本批 Codex lane1 / 待主控只读复核 |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 来源路线 | A 导入成熟任务;bos.origin=original_authored |
|
||||
| 来源 ID / split 分组键 | S500_n2_145;new_n2_145_telemetry_batch_size_time / bos:new_n2_145_telemetry_batch_size_time |
|
||||
| 原项目与冻结版本 | Bos-qiao task_factory_500_20260914;本批只读本地快照 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_145;原 task.json SHA-256 4009e4b53aa21b16f37c65879e5903f2d87aef42eced3fbacd08b5bbb5e79e86;无独立上游 commit |
|
||||
| 授权与隐私 | 用户 2026-10-20 明确授权本批全部剩余 n2 导入;仅保留任务资产,不执行来源脚本,不含用户会话与凭据 |
|
||||
| 来源组 / 任务族 | Bos n2 / serial-protocol |
|
||||
| 替身测试与用途 | software:嵌入式网关按UTF-8字节上限与等待时限批量封装遥测;合成输入可完整复现,无外设依赖 |
|
||||
| 与已有任务关系 | 独立来源 S500_n2_145,保持来源 split;未声称已经完成跨全部来源的语义去重 |
|
||||
| 验证范围 | README 声明的纯软件数学/事件模型 |
|
||||
| 未验证范围 | 真实 Agent、模型难度、板卡/外设/电气/真实时序和物理安全 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 场景与可观察结果 | 检查方法与容差 |
|
||||
| --- | --- | --- | --- |
|
||||
| 字节容量/首条延时及事件优先 | README第3段UTF8字节、每事件先delay>=D、capacity>、full==、oversize独立、手动flush/禁止空批 | 多字节é/机器人、空消息、oversize前旧批、恰B、同时间flush/超时、禁止尾自动flush;50000事件 | oracle逐步从pending字符串重算bytes/最早time,按同优先序排emissions;所有结构/整数精确 |
|
||||
| 虚拟时间/验证 | README第3段time有限非递减可负和v2 float差比较 | delay等号、time=-1e6、逆序/NaN、孤立surrogate、payload非str/配置bool拒绝;空events | ValueError、全输入保持;Pythonfloat elapsed>=D无epsilon |
|
||||
| 通用输入与输出合同 | template/README.md 末段“有限int/float且不包括bool”“必须抛ValueError”“不得改写传入数据” | 缺字段、类型、超域/极大整数等非法输入抛 ValueError;输入保持;仅提交 task.py 自包含 | RUNNER 子进程回传结果/异常,pickle 比对输入;结构精确、浮点 math.isclose(rel_tol=1e-8,abs_tol=1e-8),本题专用容差优先 |
|
||||
|
||||
- 判据独立性:oracle每事件从pending内容重算UTF8总字节,保存首项时间,避免信任候选累计size或输出;虚拟time驱动,无真实睡眠/网络。
|
||||
- 合法替代解:gold维护batch/size/first,valid_alternative保存逐条(time,payload,size)再重算;不限定候选数据结构。
|
||||
- 题面歧义审查:已完整读取 prompt、README、check 与根目录附属 Python、gold、valid、template/noop/cheat;核对阈值等号、实数/浮点、int/float/bool、数量/空输入/异常/容差。题面改动:v2只明确时间门time/first/max_delay按Pythonfloat值、elapsed用float减法再>=比较,无epsilon;依据原oracle e.time-start>=max_delay及gold/valid num转换和减法,不改gold/oracle。
|
||||
- 隔离:候选只在 RUNNER 子进程导入,check 保留用例、期望与比对;沿用统一 verify.py 的受保护 grader 与 UID65534 降权探针,不把 host 当隔离证明。候选运行后 check 不再读取其临时文件。
|
||||
- 历史可见性:Agent 只获得 prompt/template,正式判据、gold、spec 与 factory/runs 不进入候选工作区。
|
||||
- 限制:有限隐藏组合不穷尽整个合法输入域;验收结论只到公开软件模型。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不调用 Qwen 或任何真实模型,难度 UNMEASURED。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- [x] 作者逐题核对来源、完整初态、公开行为依据、判据独立性、合法替代解与负例。
|
||||
- [x] 本地与 trace6 Docker 两门完成;每类样例各五次,Docker 全部符合预期且 cleanup confirmed 才记 CALIBRATED。
|
||||
- [ ] 主控独立只读复核与真实试采;本批不记 ADMITTED,不宣称真实模型/硬件通过。
|
||||
|
||||
审核记录:2026-10-20,Codex lane1;状态 CALIBRATED,难度 UNMEASURED。题面修改与依据见第 4 节。
|
||||
|
||||
闸门 1:`runs/20261020-A-bos-n2-9/local/calibration-8d0ca21d05814a36b5504b1845439443`,status=PASS,30 次,cleanup=confirmed,accepted=True。闸门 2:`runs/20261020-A-bos-n2-9/docker/calibration-ec43123f0be44fcd94e964515b32745f`,status=PASS,30 次,cleanup=confirmed,accepted=True。
|
||||
|
||||
固定镜像:`ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。最终 task digest `e2ea8050149f6681d2e19bf760c74f364523fe69e4947114192dd008ea08d975`;原始事实见两门 receipt.json 及本批 gates/S500_n2_145/latest.json,历史输出不覆盖。
|
||||
36
tasks/S500_n2_145/task.json
Normal file
36
tasks/S500_n2_145/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_145",
|
||||
"version": "2",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_145",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_reset_timer_on_append": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_145_telemetry_batch_size_time",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_count_characters.sh",
|
||||
"cheat_reset_timer_on_append": "cheat_reset_timer_on_append.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
7
tasks/S500_n2_145/template/README.md
Normal file
7
tasks/S500_n2_145/template/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 按字节与时限遥测批处理
|
||||
|
||||
输入{max_bytes:B,max_delay:D,events:[event,...]},B为1..1000000的int且不含bool;D有限且>=1e-6。event.op为message/tick/flush,每项有有限time且全序列非递减(可负/相同);message另有payload字符串,必须可编码UTF-8(孤立surrogate非法)。消息尺寸为payload.encode('utf-8')字节数,不加分隔符,空字符串合法。初始批次为空。每事件先检查当前非空批次距首条入批时间>=D,则发出reason='delay'。之后message处理:单条尺寸>B时先发出已有批次reason='capacity'(若非空),该条独立发出reason='oversize';否则若已有字节+新条>B先发出旧批次reason='capacity',再将新条加入批次,新批次首时刻为当前事件time;加入后字节恰等于B立即发出reason='full'。flush事件在前置超时检查后发出剩余非空批次reason='manual';tick无其它动作。每次发出清空批次与首时刻,禁止空批次输出,不能因追加消息延长首条最大等待。返回{emissions:[每事件发出的批次列表,...],pending:[最终未发payload,...]};批次记录为{messages:[字符串...],bytes:整数,reason:上述枚举},输出保留消息顺序。不会在输入结束自动flush。支持50000事件,完全由输入虚拟时间驱动,不做真实sleep或网络操作。
|
||||
|
||||
超时门的time、首条入批时刻和max_delay先按Python float数值解释,elapsed按Python float减法计算,再以elapsed>=max_delay比较,不添加epsilon;即使数学精确差与浮点舍入后的差不同,也遵循此浮点比较。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
3
tasks/S500_n2_145/template/task.py
Normal file
3
tasks/S500_n2_145/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
50
tasks/S500_n2_145/valid_alternative/task.py
Normal file
50
tasks/S500_n2_145/valid_alternative/task.py
Normal file
@ -0,0 +1,50 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(d):
|
||||
d=obj(d);B=field(d,'max_bytes');D=num(field(d,'max_delay'));E=arr(field(d,'events'));last=-math.inf;out=[]
|
||||
if type(B) is not int or not 1<=B<=1000000 or D<1e-6:raise ValueError('batch parameters')
|
||||
for e in E:
|
||||
e=obj(e);op=field(e,'op');t=num(field(e,'time'))
|
||||
if op not in ('message','tick','flush') or t<last:raise ValueError('event/time')
|
||||
last=t;p=None;n=0
|
||||
if op=='message':
|
||||
p=field(e,'payload')
|
||||
if not isinstance(p,str):raise ValueError('payload')
|
||||
try:n=len(p.encode('utf-8'))
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
out.append((op,t,p,n))
|
||||
return B,D,out
|
||||
def solve(data):
|
||||
limit,delay,E=prepare(data);pending=[];result=[]
|
||||
for op,time,payload,n in E:
|
||||
batches=[]
|
||||
if pending and time-pending[0][0]>=delay:
|
||||
batches.append(([p for t,p,n in pending],sum(n for t,p,n in pending),'delay'));pending=[]
|
||||
if op=='message':
|
||||
total=sum(size for t,p,size in pending)
|
||||
if pending and total+n>limit:batches.append(([p for t,p,size in pending],total,'capacity'));pending=[]
|
||||
if n>limit:batches.append(([payload],n,'oversize'))
|
||||
else:
|
||||
pending.append((time,payload,n));size=sum(size for t,p,size in pending)
|
||||
if size==limit:batches.append(([p for t,p,size in pending],size,'full'));pending=[]
|
||||
elif op=='flush' and pending:batches.append(([p for t,p,n in pending],sum(n for t,p,n in pending),'manual'));pending=[]
|
||||
result.append([dict(messages=p,bytes=n,reason=r) for p,n,r in batches])
|
||||
return {'emissions':result,'pending':[p for t,p,n in pending]}
|
||||
130
tasks/S500_n2_145/verify.py
Normal file
130
tasks/S500_n2_145/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
42
tasks/S500_n2_146/cheat/task.py
Normal file
42
tasks/S500_n2_146/cheat/task.py
Normal file
@ -0,0 +1,42 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re,hashlib
|
||||
def prepare(data):
|
||||
d=obj(data);p=field(d,'precision')
|
||||
if type(p) is not int or not 4<=p<=10:raise ValueError('precision')
|
||||
m=1<<p;R=arr(field(d,'registers'),m);merges=arr(field(d,'merges'));values=arr(field(d,'values'));hashes=arr(field(d,'hashes'))
|
||||
if len(merges)>20 or len(values)>5000 or len(hashes)>5000:raise ValueError('size')
|
||||
for r in [R]+merges:
|
||||
arr(r,m)
|
||||
if any(type(x) is not int or not 0<=x<=65-p for x in r):raise ValueError('register')
|
||||
if any(not isinstance(v,str) or len(v)>128 for v in values) or any(not isinstance(h,str) or not re.fullmatch('[0-9a-f]{16}',h) for h in hashes):raise ValueError('value')
|
||||
# Surrogate code points cannot encode as UTF-8, and are therefore invalid strings here.
|
||||
try:
|
||||
for v in values:v.encode('utf-8')
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
return p,R,merges,values,hashes
|
||||
def solve(data):
|
||||
p,R,merges,values,hashes=prepare(data);m=1<<p;w=64-p;r=[max(items) for items in zip(R,*merges)];mask=(1<<w)-1
|
||||
integers=[int.from_bytes(hashlib.sha256(v.encode('utf-8')).digest()[:8],'big') for v in values]+[int(h,16) for h in hashes]
|
||||
for h in integers:
|
||||
index=h>>w;tail=h&mask;rho=w-tail.bit_length()+1;r[index]=max(r[index],rho)
|
||||
zeros=r.count(0);alpha={16:.673,32:.697,64:.709}.get(m,.7213/(1+1.079/m));raw=alpha*m*m/math.fsum(math.ldexp(1.,-x) for x in r);estimate=m*math.log(m/zeros) if zeros and raw<=2.5*m else raw
|
||||
return dict(registers=r,zeros=zeros,estimate=estimate)
|
||||
42
tasks/S500_n2_146/cheat_ignores_merge_states/task.py
Normal file
42
tasks/S500_n2_146/cheat_ignores_merge_states/task.py
Normal file
@ -0,0 +1,42 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re,hashlib
|
||||
def prepare(data):
|
||||
d=obj(data);p=field(d,'precision')
|
||||
if type(p) is not int or not 4<=p<=10:raise ValueError('precision')
|
||||
m=1<<p;R=arr(field(d,'registers'),m);merges=arr(field(d,'merges'));values=arr(field(d,'values'));hashes=arr(field(d,'hashes'))
|
||||
if len(merges)>20 or len(values)>5000 or len(hashes)>5000:raise ValueError('size')
|
||||
for r in [R]+merges:
|
||||
arr(r,m)
|
||||
if any(type(x) is not int or not 0<=x<=65-p for x in r):raise ValueError('register')
|
||||
if any(not isinstance(v,str) or len(v)>128 for v in values) or any(not isinstance(h,str) or not re.fullmatch('[0-9a-f]{16}',h) for h in hashes):raise ValueError('value')
|
||||
# Surrogate code points cannot encode as UTF-8, and are therefore invalid strings here.
|
||||
try:
|
||||
for v in values:v.encode('utf-8')
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
return p,R,merges,values,hashes
|
||||
def solve(data):
|
||||
p,R,merges,values,hashes=prepare(data);m=1<<p;w=64-p;r=[max(items) for items in zip(R)];mask=(1<<w)-1
|
||||
integers=[int.from_bytes(hashlib.sha256(v.encode('utf-8')).digest()[:8],'big') for v in values]+[int(h,16) for h in hashes]
|
||||
for h in integers:
|
||||
index=h>>w;tail=h&mask;rho=w-tail.bit_length()+1;r[index]=max(r[index],rho)
|
||||
zeros=r.count(0);scale=65-p;units=sum(1<<(scale-x) for x in r);an,ad={16:(673,1000),32:(697,1000),64:(709,1000)}.get(m,(7213*m,10*(1000*m+1079)));numerator=an*m*m*(1<<scale);denominator=ad*units;small=2*numerator<=5*m*denominator;estimate=m*math.log(m/zeros) if zeros and small else numerator/denominator
|
||||
return dict(registers=r,zeros=zeros,estimate=estimate)
|
||||
42
tasks/S500_n2_146/cheat_trailing_zero_rank/task.py
Normal file
42
tasks/S500_n2_146/cheat_trailing_zero_rank/task.py
Normal file
@ -0,0 +1,42 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re,hashlib
|
||||
def prepare(data):
|
||||
d=obj(data);p=field(d,'precision')
|
||||
if type(p) is not int or not 4<=p<=10:raise ValueError('precision')
|
||||
m=1<<p;R=arr(field(d,'registers'),m);merges=arr(field(d,'merges'));values=arr(field(d,'values'));hashes=arr(field(d,'hashes'))
|
||||
if len(merges)>20 or len(values)>5000 or len(hashes)>5000:raise ValueError('size')
|
||||
for r in [R]+merges:
|
||||
arr(r,m)
|
||||
if any(type(x) is not int or not 0<=x<=65-p for x in r):raise ValueError('register')
|
||||
if any(not isinstance(v,str) or len(v)>128 for v in values) or any(not isinstance(h,str) or not re.fullmatch('[0-9a-f]{16}',h) for h in hashes):raise ValueError('value')
|
||||
# Surrogate code points cannot encode as UTF-8, and are therefore invalid strings here.
|
||||
try:
|
||||
for v in values:v.encode('utf-8')
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
return p,R,merges,values,hashes
|
||||
def solve(data):
|
||||
p,R,merges,values,hashes=prepare(data);m=1<<p;w=64-p;r=[max(items) for items in zip(R,*merges)];mask=(1<<w)-1
|
||||
integers=[int.from_bytes(hashlib.sha256(v.encode('utf-8')).digest()[:8],'big') for v in values]+[int(h,16) for h in hashes]
|
||||
for h in integers:
|
||||
index=h>>w;tail=h&mask;rho=w+1 if tail==0 else (tail&-tail).bit_length();r[index]=max(r[index],rho)
|
||||
zeros=r.count(0);scale=65-p;units=sum(1<<(scale-x) for x in r);an,ad={16:(673,1000),32:(697,1000),64:(709,1000)}.get(m,(7213*m,10*(1000*m+1079)));numerator=an*m*m*(1<<scale);denominator=ad*units;small=2*numerator<=5*m*denominator;estimate=m*math.log(m/zeros) if zeros and small else numerator/denominator
|
||||
return dict(registers=r,zeros=zeros,estimate=estimate)
|
||||
113
tasks/S500_n2_146/check.py
Normal file
113
tasks/S500_n2_146/check.py
Normal file
File diff suppressed because one or more lines are too long
42
tasks/S500_n2_146/gold/task.py
Normal file
42
tasks/S500_n2_146/gold/task.py
Normal file
@ -0,0 +1,42 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re,hashlib
|
||||
def prepare(data):
|
||||
d=obj(data);p=field(d,'precision')
|
||||
if type(p) is not int or not 4<=p<=10:raise ValueError('precision')
|
||||
m=1<<p;R=arr(field(d,'registers'),m);merges=arr(field(d,'merges'));values=arr(field(d,'values'));hashes=arr(field(d,'hashes'))
|
||||
if len(merges)>20 or len(values)>5000 or len(hashes)>5000:raise ValueError('size')
|
||||
for r in [R]+merges:
|
||||
arr(r,m)
|
||||
if any(type(x) is not int or not 0<=x<=65-p for x in r):raise ValueError('register')
|
||||
if any(not isinstance(v,str) or len(v)>128 for v in values) or any(not isinstance(h,str) or not re.fullmatch('[0-9a-f]{16}',h) for h in hashes):raise ValueError('value')
|
||||
# Surrogate code points cannot encode as UTF-8, and are therefore invalid strings here.
|
||||
try:
|
||||
for v in values:v.encode('utf-8')
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
return p,R,merges,values,hashes
|
||||
def solve(data):
|
||||
p,R,merges,values,hashes=prepare(data);m=1<<p;w=64-p;r=[max(items) for items in zip(R,*merges)];mask=(1<<w)-1
|
||||
integers=[int.from_bytes(hashlib.sha256(v.encode('utf-8')).digest()[:8],'big') for v in values]+[int(h,16) for h in hashes]
|
||||
for h in integers:
|
||||
index=h>>w;tail=h&mask;rho=w-tail.bit_length()+1;r[index]=max(r[index],rho)
|
||||
zeros=r.count(0);scale=65-p;units=sum(1<<(scale-x) for x in r);an,ad={16:(673,1000),32:(697,1000),64:(709,1000)}.get(m,(7213*m,10*(1000*m+1079)));numerator=an*m*m*(1<<scale);denominator=ad*units;small=2*numerator<=5*m*denominator;estimate=m*math.log(m/zeros) if zeros and small else numerator/denominator
|
||||
return dict(registers=r,zeros=zeros,estimate=estimate)
|
||||
2
tasks/S500_n2_146/noop/task.py
Normal file
2
tasks/S500_n2_146/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_146/prompt.md
Normal file
3
tasks/S500_n2_146/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成可合并HyperLogLog遥测基数草图并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_146/spec.md
Normal file
63
tasks/S500_n2_146/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_146
|
||||
|
||||
规范:[任务制作规范](../../docs/task-authoring.md)。路线 A 仅填第 1、4、7 节。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 版本 | S500_n2_146 / 2 |
|
||||
| 作者 / 独立评审人 | Codex lane2 / root(2026-10-20,只读审阅通过;证据见本批 root-review-group12.json) |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 原项目与快照 | Bos-qiao envs/S500_n2_146;本批只读复制到 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_146 |
|
||||
| 来源路线 / 来源ID | A 导入成熟任务(Bos 原题) / S500_n2_146 |
|
||||
| 来源与授权 | 用户 2026-10-20 第9批 BRIEF;2026-10-12 项目资产接入授权;来源只读,样例脚本仅解析 |
|
||||
| 隐私处理 | 无真实用户会话;本批不读取凭据 |
|
||||
| 替身测试 | 软件输入驱动纯 Python 行为;不需要板卡或真实外设,software |
|
||||
| split 分组键 | bos:new_n2_146_hyperloglog_cardinality_merge |
|
||||
| 来源组 / 根因族 | Bos n2 / serial-protocol |
|
||||
| 与已有任务的关系 | 本批剩余来源独立导入;非已有任务改名 |
|
||||
| 导入方式 | 直接导入 |
|
||||
| 验证范围 | 原 README 公开合同与原隐藏行为判据 |
|
||||
| 未验证范围 | 只验证纯软件行为;未验证真实硬件、实时性能或模型难度。 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 可观察结果与检查 |
|
||||
| --- | --- | --- |
|
||||
| 合并/哈希与桶rank | template/README.md:4(最高p位是桶index) | 独立逐threshold前导零oracle,goldbit_length与valid64字符bits;全零tail rho=65-p,所有p/rank覆盖 |
|
||||
| 精确系数与分支门限 | template/README.md:5(所有十进制系数表示精确有理数) | 原4组float误分支hist和36组临界harmonic quanta;raw<=2.5*m精确含等号,再estimatefloat |
|
||||
| 输出/空流与规模 | template/README.md:5(estimate:非负有限数值) | registers/zeros严格int,estimate有限非负1e-8;p10/20merges/5000values+hashes原最大例 |
|
||||
| 整型/字符串全验证 | template/README.md:11(必须是 Python 内置 int) | precision/registers/merges排float/bool;Unicode原UTF8、128字符、孤立代理非法、hex16小写,空流仍验所有state |
|
||||
|
||||
- 题面改动:precision、registers 及 merges 中的所有寄存器值必须是 Python 内置 int;bool 和所有 float(包括 0.0、4.0 等整数值)均非法并抛 ValueError,通用 int/float 数值段不能放宽这些字段。输出 registers 与 zeros 使用 Python 内置 int;estimate 仍按正文有限非负数值及公共浮点容差验收。
|
||||
- 改动依据:原文整数不含bool与通用int/float段可能误允整数值float;原check含precision=4.0及register/merge=0.0非法,gold/valid严格type is int。只补类型,原精确十进制系数与临界分支合同完全保留。
|
||||
- 判据与标准答案:原判据、gold 和 valid 未因校准结果而改写;重写隔离时仅迁移执行边界,保留原断言语义。
|
||||
- 合法解:只要求原公开接口、类型和行为;原 valid 样例(如有)作为合法替代解校准,不限定实现算法或源码形态。
|
||||
- 隔离:沿用受保护 verify.py 的 root 判据和降权候选子进程;正式容器独立校准;本地模式只执行本仓库可信样例。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不运行 Qwen 或其他模型;难度 UNMEASURED,未试采。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- 作者已逐题完整读 README、check.py、附属 Python 判据、gold 与 valid(如有),核对阈值等号、精确/浮点语义、int/float/bool、规模、空输入、异常及容差。
|
||||
- 状态:CALIBRATED;只到两道校准闸门,尚未真实试采,不记 ADMITTED。
|
||||
- 闸门1可信本地:PASS;35 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/local/calibration-5f3c122921164204826a54a62c05d6d9。
|
||||
- 闸门2trace6 Docker:PASS;35 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/docker/calibration-419f077a62ff484985f08e5199fb09b5。
|
||||
- 正式镜像:ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1。
|
||||
- 每类样例分别五次;若含 cheat_read_grader,本地无隔离可读而 PASS 仅按规范 §7 记例外,正式 Docker 必须 FAIL。
|
||||
- 独立只读审阅由主控另存本批 review 证据;本 spec 不代替独立审阅或模型难度测量。
|
||||
38
tasks/S500_n2_146/task.json
Normal file
38
tasks/S500_n2_146/task.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"id": "S500_n2_146",
|
||||
"version": "2",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_146",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_ignores_merge_states": "FAIL",
|
||||
"cheat_trailing_zero_rank": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_146_hyperloglog_cardinality_merge",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_float_threshold_branch.sh",
|
||||
"cheat_ignores_merge_states": "cheat_ignores_merge_states.sh",
|
||||
"cheat_trailing_zero_rank": "cheat_trailing_zero_rank.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
11
tasks/S500_n2_146/template/README.md
Normal file
11
tasks/S500_n2_146/template/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
# 可合并HyperLogLog遥测基数草图
|
||||
|
||||
输入{precision:p,registers:[...],merges:[[...],...],values:[text,...],hashes:[hex,...]},全部字段必需。p为4..10整数,m=2^p,初始registers恰好m个整数,每个为0..65-p;merges最多20个同长度/范围的寄存器数组。values最多5000个Unicode字符串,每个最多128个字符且必须能按UTF-8编码(拒绝孤立代理码点);按原UTF-8编码(不归一化、不加分隔符),SHA-256摘要的前8个字节按大端解释为无符号64位哈希。hashes最多5000个恰好16字符的小写十六进制字符串[0-9a-f],直接表示已有64位哈希,允许全零;这是公开预哈希输入接口,不再对其字符串哈希。所有整数不含bool。
|
||||
先逐桶取初始与所有merges的最大值,再吸收values与hashes(这些操作可交换)。对每个64位h,最高p位是桶index,其余w=64-p位为tail;rho为tail从高位到低位第一个1的位置(从1计数);若tail全零,rho=w+1。该桶更新为max(原值,rho)。同值重复不累加,不把前导零跨过桶位计算。输入寄存器0表示尚无观察,但允许任何范围内的已有状态,不要求重新给出其原样本。
|
||||
最终令Z为零桶数,S=sum(2^(-register_i))。alpha在m=16/32/64分别为0.673/0.697/0.709,其它m为0.7213/(1+1.079/m)。raw=alpha*m*m/S。所有十进制系数表示精确有理数,raw<=2.5*m的分支必须按精确值判断,不能用浮点舍入结果选择分支;estimate输出才允许浮点。若raw<=2.5*m且Z>0,estimate=m*ln(m/Z);否则estimate=raw。这里明确不实施其它经验偏差或大基数修正,也不截断到2^64。返回{registers:[最终整数],zeros:Z,estimate:非负有限数值},estimate使用公共浮点容差;输入空值流合法且仍须完整校验全部状态。该模型仅估计不同哈希的基数,不保证特定数据集的统计误差或真实设备遥测已经收集。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
|
||||
## 本批公开约定澄清
|
||||
|
||||
precision、registers 及 merges 中的所有寄存器值必须是 Python 内置 int;bool 和所有 float(包括 0.0、4.0 等整数值)均非法并抛 ValueError,通用 int/float 数值段不能放宽这些字段。输出 registers 与 zeros 使用 Python 内置 int;estimate 仍按正文有限非负数值及公共浮点容差验收。
|
||||
3
tasks/S500_n2_146/template/task.py
Normal file
3
tasks/S500_n2_146/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
48
tasks/S500_n2_146/valid_alternative/task.py
Normal file
48
tasks/S500_n2_146/valid_alternative/task.py
Normal file
@ -0,0 +1,48 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
import re,hashlib
|
||||
def prepare(data):
|
||||
d=obj(data);p=field(d,'precision')
|
||||
if type(p) is not int or not 4<=p<=10:raise ValueError('precision')
|
||||
m=1<<p;R=arr(field(d,'registers'),m);merges=arr(field(d,'merges'));values=arr(field(d,'values'));hashes=arr(field(d,'hashes'))
|
||||
if len(merges)>20 or len(values)>5000 or len(hashes)>5000:raise ValueError('size')
|
||||
for r in [R]+merges:
|
||||
arr(r,m)
|
||||
if any(type(x) is not int or not 0<=x<=65-p for x in r):raise ValueError('register')
|
||||
if any(not isinstance(v,str) or len(v)>128 for v in values) or any(not isinstance(h,str) or not re.fullmatch('[0-9a-f]{16}',h) for h in hashes):raise ValueError('value')
|
||||
# Surrogate code points cannot encode as UTF-8, and are therefore invalid strings here.
|
||||
try:
|
||||
for v in values:v.encode('utf-8')
|
||||
except UnicodeEncodeError:raise ValueError('UTF-8')
|
||||
return p,R,merges,values,hashes
|
||||
from collections import Counter
|
||||
def solve(data):
|
||||
p,initial,merges,values,hashes=prepare(data);m=1<<p;buckets=[set([x]) for x in initial]
|
||||
for state in merges:
|
||||
for bucket,value in zip(buckets,state):bucket.add(value)
|
||||
rawbytes=[hashlib.sha256(v.encode()).digest()[:8] for v in values]+[bytes.fromhex(v) for v in hashes]
|
||||
for value in rawbytes:
|
||||
bits=''.join(format(b,'08b') for b in value);index=int(bits[:p],2);suffix=bits[p:];first=suffix.find('1');rho=len(suffix)+1 if first<0 else first+1;buckets[index].add(rho)
|
||||
from fractions import Fraction as F
|
||||
r=[max(b) for b in buckets];counts=Counter(r);scale=max(r);units=sum(count*(2**(scale-rank)) for rank,count in counts.items());harmonic=F(units,2**scale);alpha=F('0.673') if p==4 else F('0.697') if p==5 else F('0.709') if p==6 else F('0.7213')/(1+F('1.079')/m);raw=alpha*m*m/harmonic;z=counts[0]
|
||||
if z and raw<=F(5*m,2):estimate=m*math.log1p((m-z)/z)
|
||||
else:estimate=float(raw)
|
||||
return dict(registers=r,zeros=z,estimate=estimate)
|
||||
130
tasks/S500_n2_146/verify.py
Normal file
130
tasks/S500_n2_146/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
43
tasks/S500_n2_148/cheat/task.py
Normal file
43
tasks/S500_n2_148/cheat/task.py
Normal file
@ -0,0 +1,43 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);origin=num(field(d,'origin'));width=num(field(d,'width'));samples=arr(field(d,'samples'))
|
||||
if width<=0 or len(samples)>100000:raise ValueError('width/length')
|
||||
out=[];previous=-math.inf
|
||||
for row in samples:
|
||||
t,v=vec(row,2)
|
||||
if t<previous:raise ValueError('order')
|
||||
previous=t;out.append((t,v))
|
||||
return origin,width,out
|
||||
def solve(data):
|
||||
from fractions import Fraction as Q
|
||||
origin,width,samples=prepare(data);o=Q(origin);w=Q(width);out=[];current=None;first=last=low=high=None
|
||||
def emit():
|
||||
if current is not None:out.append({'bucket':current,'indices':sorted({first,last,low,high})})
|
||||
for i,(t,v) in enumerate(samples):
|
||||
bucket=(Q(t)-o)//w
|
||||
if bucket!=current:
|
||||
emit();current=bucket;first=last=low=high=i
|
||||
else:
|
||||
last=i
|
||||
if v<=samples[low][1]:low=i
|
||||
if v>=samples[high][1]:high=i
|
||||
emit();return out
|
||||
43
tasks/S500_n2_148/cheat_rounded_float_bucket/task.py
Normal file
43
tasks/S500_n2_148/cheat_rounded_float_bucket/task.py
Normal file
@ -0,0 +1,43 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);origin=num(field(d,'origin'));width=num(field(d,'width'));samples=arr(field(d,'samples'))
|
||||
if width<=0 or len(samples)>100000:raise ValueError('width/length')
|
||||
out=[];previous=-math.inf
|
||||
for row in samples:
|
||||
t,v=vec(row,2)
|
||||
if t<previous:raise ValueError('order')
|
||||
previous=t;out.append((t,v))
|
||||
return origin,width,out
|
||||
def solve(data):
|
||||
from fractions import Fraction as Q
|
||||
origin,width,samples=prepare(data);o=Q(origin);w=Q(width);out=[];current=None;first=last=low=high=None
|
||||
def emit():
|
||||
if current is not None:out.append({'bucket':current,'indices':sorted({first,last,low,high})})
|
||||
for i,(t,v) in enumerate(samples):
|
||||
bucket=math.floor((t-origin)/width)
|
||||
if bucket!=current:
|
||||
emit();current=bucket;first=last=low=high=i
|
||||
else:
|
||||
last=i
|
||||
if v<samples[low][1]:low=i
|
||||
if v>samples[high][1]:high=i
|
||||
emit();return out
|
||||
81
tasks/S500_n2_148/check.py
Normal file
81
tasks/S500_n2_148/check.py
Normal file
@ -0,0 +1,81 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
def case(o,w,S):return dict(origin=o,width=w,samples=S)
|
||||
cases=[case(0,1,[[0,0],[.1,4],[.2,-2],[.3,4],[.9,0],[1,9]]),case(0,.1,[[0,1],[.1,2],[.2,3],[1,4]]),case(.1,.1,[[-.3,0],[-.2,1],[-.1,2],[0,3],[.1,4]]),case(0,1,[[0,2],[0,2],[0,2]]),case(0,5e-324,[[-1,0],[0,1],[5e-324,2],[1,3]]),case(1000000,1,[[-1000000,0],[1000000,1]]),case(0,1,[])];rng=random.Random(1248)
|
||||
for _ in range(80):
|
||||
samples=sorted([[rng.randrange(-100,101)/8,rng.randrange(-5,6)] for _ in range(80)],key=lambda x:x[0]);cases.append(case(rng.randrange(-5,6)/8,rng.choice([.1,.2,.3,.5,1,2]),samples))
|
||||
def oracle(d):
|
||||
# Common power-of-two integer time coordinates give exact floor independently of Fraction arithmetic.
|
||||
vals=[float(d['origin']),float(d['width'])]+[float(t) for t,v in d['samples']];ratios=[x.as_integer_ratio() for x in vals];den=max(q for p,q in ratios);ints=[p*(den//q) for p,q in ratios];o,w=ints[:2];group={}
|
||||
for i,t in enumerate(ints[2:]):group.setdefault((t-o)//w,[]).append(i)
|
||||
out=[]
|
||||
for b,ids in sorted(group.items()):
|
||||
chosen={ids[0],ids[-1]}
|
||||
for index in ids:
|
||||
value=d['samples'][index][1]
|
||||
if all(value<=d['samples'][j][1] for j in ids) and not any(d['samples'][j][1]==value for j in ids if j<index):chosen.add(index)
|
||||
if all(value>=d['samples'][j][1] for j in ids) and not any(d['samples'][j][1]==value for j in ids if j<index):chosen.add(index)
|
||||
out.append(dict(bucket=b,indices=sorted(chosen)))
|
||||
return out
|
||||
truth=[{'ok':oracle(d)} for d in cases];S=[[i,(-1 if i%4==1 else 1 if i%4==2 else 0)] for i in range(100000)];cases.append(case(0,100,S));truth.append({'ok':[dict(bucket=b,indices=[100*b,100*b+1,100*b+2,100*b+99]) for b in range(1000)]})
|
||||
base=case(0,1,[]);bad=[None,{},dict(base,width=0),dict(base,width=-1),dict(base,width=True),dict(base,width=float('inf')),dict(base,origin=10**400),dict(base,samples=[[1,0],[0,1]]),dict(base,samples=[[0,False]]),dict(base,samples=[[0,float('nan')]]),dict(base,samples=[[0]]),dict(base,samples=[[0,0]]*100001)]
|
||||
return cases+bad,truth+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'origin': -1000000, 'width': 1000000, 'samples': [[-1000000, 1000000], [0, -1000000], [1000000, 0]]}, [{'bucket': 0, 'indices': [0]}, {'bucket': 1, 'indices': [1]}, {'bucket': 2, 'indices': [2]}])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
43
tasks/S500_n2_148/gold/task.py
Normal file
43
tasks/S500_n2_148/gold/task.py
Normal file
@ -0,0 +1,43 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);origin=num(field(d,'origin'));width=num(field(d,'width'));samples=arr(field(d,'samples'))
|
||||
if width<=0 or len(samples)>100000:raise ValueError('width/length')
|
||||
out=[];previous=-math.inf
|
||||
for row in samples:
|
||||
t,v=vec(row,2)
|
||||
if t<previous:raise ValueError('order')
|
||||
previous=t;out.append((t,v))
|
||||
return origin,width,out
|
||||
def solve(data):
|
||||
from fractions import Fraction as Q
|
||||
origin,width,samples=prepare(data);o=Q(origin);w=Q(width);out=[];current=None;first=last=low=high=None
|
||||
def emit():
|
||||
if current is not None:out.append({'bucket':current,'indices':sorted({first,last,low,high})})
|
||||
for i,(t,v) in enumerate(samples):
|
||||
bucket=(Q(t)-o)//w
|
||||
if bucket!=current:
|
||||
emit();current=bucket;first=last=low=high=i
|
||||
else:
|
||||
last=i
|
||||
if v<samples[low][1]:low=i
|
||||
if v>samples[high][1]:high=i
|
||||
emit();return out
|
||||
2
tasks/S500_n2_148/noop/task.py
Normal file
2
tasks/S500_n2_148/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_148/prompt.md
Normal file
3
tasks/S500_n2_148/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成峰值保留降采样并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_148/spec.md
Normal file
63
tasks/S500_n2_148/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_148
|
||||
|
||||
本规格仅供控制侧,路线 A 只填写第 1、4、7 节,其余沿用 Bos 原题。规范见 [任务制作规范](../../docs/task-authoring.md)。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 任务版本 | S500_n2_148 / 1 |
|
||||
| 作者 / 独立评审人 | Bos 原作者;本批 Codex lane1 / 待主控只读复核 |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 来源路线 | A 导入成熟任务;bos.origin=original_authored |
|
||||
| 来源 ID / split 分组键 | S500_n2_148;new_n2_148_telemetry_downsample_extrema / bos:new_n2_148_telemetry_downsample_extrema |
|
||||
| 原项目与冻结版本 | Bos-qiao task_factory_500_20260914;本批只读本地快照 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_148;原 task.json SHA-256 45005e4debf0ef7f495cec32177dc08f44cea758ec171fa39dfddb3a1b6ac66d;无独立上游 commit |
|
||||
| 授权与隐私 | 用户 2026-10-20 明确授权本批全部剩余 n2 导入;仅保留任务资产,不执行来源脚本,不含用户会话与凭据 |
|
||||
| 来源组 / 任务族 | Bos n2 / motor-sensor-control |
|
||||
| 替身测试与用途 | software:嵌入式波形遥测降采样器在固定时间桶保留极值;合成输入可完整复现,无外设依赖 |
|
||||
| 与已有任务关系 | 独立来源 S500_n2_148,保持来源 split;未声称已经完成跨全部来源的语义去重 |
|
||||
| 验证范围 | README 声明的纯软件数学/事件模型 |
|
||||
| 未验证范围 | 真实 Agent、模型难度、板卡/外设/电气/真实时序和物理安全 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 场景与可观察结果 | 检查方法与容差 |
|
||||
| --- | --- | --- | --- |
|
||||
| 精确二进制桶号与极值索引 | README第3/4/5段float精确值floor、负桶、0.1例子、四角色/极值tie最小索引/同项去重 | 负时间、同time同value保首末、极小5e-324宽/巨大桶号、0.1误差边界、100000样本 | oracle把所有时间同乘公共2幂分母转整数取整;独立扫描每桶first/last/min/max最先索引,输出整数精确 |
|
||||
| 空/范围/顺序 | README第3段最多100000、time非递减、空samples合法及末段 | 空[]、width<=0/bool/inf、巨大origin、逆序/NaN/boolvalue/错维/100001拒绝 | ValueError和输入保持;输出bucket不受输入数值范围约束 |
|
||||
| 通用输入与输出合同 | template/README.md 末段“有限int/float且不包括bool”“必须抛ValueError”“不得改写传入数据” | 缺字段、类型、超域/极大整数等非法输入抛 ValueError;输入保持;仅提交 task.py 自包含 | RUNNER 子进程回传结果/异常,pickle 比对输入;结构精确、浮点 math.isclose(rel_tol=1e-8,abs_tol=1e-8),本题专用容差优先 |
|
||||
|
||||
- 判据独立性:oracle提升到公共二进制分母整数进行floor,逐桶全成员比较极值;不同于gold Fraction流式与valid逐点as_integer_ratio商。
|
||||
- 合法替代解:gold Fraction流式四角色索引,valid_alternative精确分式整数商+桶映射与min键;不生成空桶。
|
||||
- 题面歧义审查:已完整读取 prompt、README、check 与根目录附属 Python、gold、valid、template/noop/cheat;核对阈值等号、实数/浮点、int/float/bool、数量/空输入/异常/容差。题面改动:无;逐项核对后沿用 Bos 原题。
|
||||
- 隔离:候选只在 RUNNER 子进程导入,check 保留用例、期望与比对;沿用统一 verify.py 的受保护 grader 与 UID65534 降权探针,不把 host 当隔离证明。候选运行后 check 不再读取其临时文件。
|
||||
- 历史可见性:Agent 只获得 prompt/template,正式判据、gold、spec 与 factory/runs 不进入候选工作区。
|
||||
- 限制:有限隐藏组合不穷尽整个合法输入域;验收结论只到公开软件模型。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不调用 Qwen 或任何真实模型,难度 UNMEASURED。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- [x] 作者逐题核对来源、完整初态、公开行为依据、判据独立性、合法替代解与负例。
|
||||
- [x] 本地与 trace6 Docker 两门完成;每类样例各五次,Docker 全部符合预期且 cleanup confirmed 才记 CALIBRATED。
|
||||
- [ ] 主控独立只读复核与真实试采;本批不记 ADMITTED,不宣称真实模型/硬件通过。
|
||||
|
||||
审核记录:2026-10-20,Codex lane1;状态 CALIBRATED,难度 UNMEASURED。题面修改与依据见第 4 节。
|
||||
|
||||
闸门 1:`runs/20261020-A-bos-n2-9/local/calibration-982d63f994ed4950bf47df69aae28e88`,status=PASS,30 次,cleanup=confirmed,accepted=True。闸门 2:`runs/20261020-A-bos-n2-9/docker/calibration-a49e0c0aaead4f35bd6e869450a9dd78`,status=PASS,30 次,cleanup=confirmed,accepted=True。
|
||||
|
||||
固定镜像:`ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。最终 task digest `6adf88d4a6e121b6ef81bc8b02b48c9211987ec59a0b82fa38aa71961de1abe6`;原始事实见两门 receipt.json 及本批 gates/S500_n2_148/latest.json,历史输出不覆盖。
|
||||
36
tasks/S500_n2_148/task.json
Normal file
36
tasks/S500_n2_148/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_148",
|
||||
"version": "1",
|
||||
"family": "motor-sensor-control",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_148",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_rounded_float_bucket": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_148_telemetry_downsample_extrema",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_last_equal_extremum.sh",
|
||||
"cheat_rounded_float_bucket": "cheat_rounded_float_bucket.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
7
tasks/S500_n2_148/template/README.md
Normal file
7
tasks/S500_n2_148/template/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 峰值保留降采样
|
||||
|
||||
输入{origin:数值,width:正数值,samples:[[time,value],...]}。所有数值遵守公共有限数值域;samples最多100000项且time非递减,重复time合法,空samples合法。每个样本按输入列表下标标识。
|
||||
时间桶编号为floor((time-origin)/width),负编号合法,桶是左闭右开。这里把每个输入int/float视为其精确数值计算桶号:float即其精确二进制值,不允许先做易舍入的浮点减法/除法改变桶归属。例如origin=0,width=0.1,time=1应属桶9(float 0.1略大于十进制0.1)。不生成空桶。
|
||||
每个非空桶保留四种样本:输入顺序首项、末项、value最小项、value最大项。最小/最大值并列均选输入下标最小者;四种角色选中同一项只保留一次,最终按原下标升序输出。返回按桶号升序的列表,每项恰为{bucket:整数编号,indices:[保留下标,...]}。即使相同time且相同value的首末项不同,下标仍不同并须分别保留。目标是保留遥测峰谷与桶端点,不是均值滤波或频域抗混叠。支持极小非零width及大范围桶号,不可逐一枚举空桶。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
3
tasks/S500_n2_148/template/task.py
Normal file
3
tasks/S500_n2_148/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
34
tasks/S500_n2_148/valid_alternative/task.py
Normal file
34
tasks/S500_n2_148/valid_alternative/task.py
Normal file
@ -0,0 +1,34 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);origin=num(field(d,'origin'));width=num(field(d,'width'));samples=arr(field(d,'samples'))
|
||||
if width<=0 or len(samples)>100000:raise ValueError('width/length')
|
||||
out=[];previous=-math.inf
|
||||
for row in samples:
|
||||
t,v=vec(row,2)
|
||||
if t<previous:raise ValueError('order')
|
||||
previous=t;out.append((t,v))
|
||||
return origin,width,out
|
||||
def solve(data):
|
||||
origin,width,samples=prepare(data);on,od=origin.as_integer_ratio();wn,wd=width.as_integer_ratio();groups={}
|
||||
for i,(t,v) in enumerate(samples):
|
||||
tn,td=t.as_integer_ratio();bucket=((tn*od-on*td)*wd)//(td*od*wn);groups.setdefault(bucket,[]).append(i)
|
||||
return [{'bucket':k,'indices':sorted({ids[0],ids[-1],min(ids,key=lambda i:(samples[i][1],i)),min(ids,key=lambda i:(-samples[i][1],i))})} for k,ids in sorted(groups.items())]
|
||||
130
tasks/S500_n2_148/verify.py
Normal file
130
tasks/S500_n2_148/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
74
tasks/S500_n2_149/cheat/task.py
Normal file
74
tasks/S500_n2_149/cheat/task.py
Normal file
@ -0,0 +1,74 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);raw=arr(field(d,'events'))
|
||||
if len(raw)>500:raise ValueError('size')
|
||||
events=[];grants=set();messages=set()
|
||||
for row in raw:
|
||||
obj(row);op=field(row,'op');name=field(row,'id')
|
||||
if op not in ('grant','revoke','reserve','commit','cancel','ack') or not isinstance(name,str) or not 1<=len(name)<=32 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' for c in name):raise ValueError('event')
|
||||
(grants if op in ('grant','revoke') else messages).add(name);amount=field(row,'amount') if op in ('grant','reserve') else None
|
||||
if op in ('grant','reserve') and (type(amount) is not int or not 1<=amount<=1000000):raise ValueError('amount')
|
||||
events.append((op,name,amount))
|
||||
if len(grants)>20 or len(messages)>20:raise ValueError('id budget')
|
||||
return events
|
||||
def solve(data):
|
||||
import copy
|
||||
events=prepare(data);G={};M={};out=[]
|
||||
def release(m):
|
||||
for gid,size in m['allocations']:
|
||||
g=G[gid];g['in_use']-=size
|
||||
if g['active']:g['available']+=size
|
||||
else:g['destroyed']+=size
|
||||
def process(op,name,amount):
|
||||
if op=='grant':
|
||||
if name in G:return (True,'duplicate',None) if G[name]['amount']==amount else (False,'grant_conflict',None)
|
||||
G[name]=dict(id=name,amount=amount,active=True,available=amount,in_use=0,destroyed=0);return True,'granted',None
|
||||
if op=='revoke':
|
||||
if name not in G:return False,'unknown_grant',None
|
||||
g=G[name]
|
||||
if not g['active']:return True,'duplicate',None
|
||||
g['active']=False;g['destroyed']+=g['available'];g['available']=0;return True,'revoked',None
|
||||
if op=='reserve':
|
||||
if name in M:return (True,'duplicate',None) if M[name]['amount']==amount else (False,'message_conflict',None)
|
||||
if sum(g['available'] for g in G.values())<amount:return False,'insufficient_credit',None
|
||||
remaining=amount;alloc=[]
|
||||
for gid,g in G.items():
|
||||
take=min(remaining,g['available'])
|
||||
if take:alloc.append([gid,take]);g['available']-=take;g['in_use']+=take;remaining-=take
|
||||
if remaining==0:break
|
||||
M[name]=dict(id=name,amount=amount,state='reserved',allocations=alloc);return True,'reserved',None
|
||||
if name not in M:return False,'unknown_message',None
|
||||
m=M[name];state=m['state']
|
||||
if op=='commit':
|
||||
if state in ('committed','acked'):return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
m['state']='committed';return True,'committed',dict(id=name,amount=m['amount'],allocations=copy.deepcopy(m['allocations']))
|
||||
if op=='cancel':
|
||||
if state=='cancelled':return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
release(m);m['state']='cancelled';return True,'cancelled',None
|
||||
if state=='acked':release(m);return True,'duplicate',None
|
||||
if state!='committed':return False,'invalid_state',None
|
||||
release(m);m['state']='acked';return True,'acknowledged',None
|
||||
for event in events:
|
||||
accepted,reason,sent=process(*event);totals=dict(issued=sum(g['amount'] for g in G.values()),**{key:sum(g[key] for g in G.values()) for key in ('available','in_use','destroyed')});out.append(dict(accepted=accepted,reason=reason,sent=sent,ledger=copy.deepcopy(dict(grants=list(G.values()),messages=list(M.values()),totals=totals))))
|
||||
return out
|
||||
@ -0,0 +1,74 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);raw=arr(field(d,'events'))
|
||||
if len(raw)>500:raise ValueError('size')
|
||||
events=[];grants=set();messages=set()
|
||||
for row in raw:
|
||||
obj(row);op=field(row,'op');name=field(row,'id')
|
||||
if op not in ('grant','revoke','reserve','commit','cancel','ack') or not isinstance(name,str) or not 1<=len(name)<=32 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' for c in name):raise ValueError('event')
|
||||
(grants if op in ('grant','revoke') else messages).add(name);amount=field(row,'amount') if op in ('grant','reserve') else None
|
||||
if op in ('grant','reserve') and (type(amount) is not int or not 1<=amount<=1000000):raise ValueError('amount')
|
||||
events.append((op,name,amount))
|
||||
if len(grants)>20 or len(messages)>20:raise ValueError('id budget')
|
||||
return events
|
||||
def solve(data):
|
||||
import copy
|
||||
events=prepare(data);G={};M={};out=[]
|
||||
def release(m):
|
||||
for gid,size in m['allocations']:
|
||||
g=G[gid];g['in_use']-=size
|
||||
if True:g['available']+=size
|
||||
else:g['destroyed']+=size
|
||||
def process(op,name,amount):
|
||||
if op=='grant':
|
||||
if name in G:return (True,'duplicate',None) if G[name]['amount']==amount else (False,'grant_conflict',None)
|
||||
G[name]=dict(id=name,amount=amount,active=True,available=amount,in_use=0,destroyed=0);return True,'granted',None
|
||||
if op=='revoke':
|
||||
if name not in G:return False,'unknown_grant',None
|
||||
g=G[name]
|
||||
if not g['active']:return True,'duplicate',None
|
||||
g['active']=False;g['destroyed']+=g['available'];g['available']=0;return True,'revoked',None
|
||||
if op=='reserve':
|
||||
if name in M:return (True,'duplicate',None) if M[name]['amount']==amount else (False,'message_conflict',None)
|
||||
if sum(g['available'] for g in G.values())<amount:return False,'insufficient_credit',None
|
||||
remaining=amount;alloc=[]
|
||||
for gid,g in G.items():
|
||||
take=min(remaining,g['available'])
|
||||
if take:alloc.append([gid,take]);g['available']-=take;g['in_use']+=take;remaining-=take
|
||||
if remaining==0:break
|
||||
M[name]=dict(id=name,amount=amount,state='reserved',allocations=alloc);return True,'reserved',None
|
||||
if name not in M:return False,'unknown_message',None
|
||||
m=M[name];state=m['state']
|
||||
if op=='commit':
|
||||
if state in ('committed','acked'):return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
m['state']='committed';return True,'committed',dict(id=name,amount=m['amount'],allocations=copy.deepcopy(m['allocations']))
|
||||
if op=='cancel':
|
||||
if state=='cancelled':return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
release(m);m['state']='cancelled';return True,'cancelled',None
|
||||
if state=='acked':return True,'duplicate',None
|
||||
if state!='committed':return False,'invalid_state',None
|
||||
release(m);m['state']='acked';return True,'acknowledged',None
|
||||
for event in events:
|
||||
accepted,reason,sent=process(*event);totals=dict(issued=sum(g['amount'] for g in G.values()),**{key:sum(g[key] for g in G.values()) for key in ('available','in_use','destroyed')});out.append(dict(accepted=accepted,reason=reason,sent=sent,ledger=copy.deepcopy(dict(grants=list(G.values()),messages=list(M.values()),totals=totals))))
|
||||
return out
|
||||
131
tasks/S500_n2_149/check.py
Normal file
131
tasks/S500_n2_149/check.py
Normal file
@ -0,0 +1,131 @@
|
||||
import math,random,collections,itertools
|
||||
def fixtures():
|
||||
import copy
|
||||
def e(op,n,a=None):return dict(op=op,id=n,**({} if a is None else {'amount':a}))
|
||||
def case(E):return dict(events=E)
|
||||
cases=[case([]),case([e('reserve','m',5),e('grant','g',3),e('reserve','m',2)]),case([e('reserve','m',3),e('grant','g',5),e('reserve','m',3),e('commit','m'),e('commit','m'),e('ack','m'),e('ack','m'),e('reserve','m',3),e('reserve','m',4),e('cancel','m')]),case([e('grant','a',3),e('grant','b',5),e('reserve','x',6),e('revoke','a'),e('commit','x'),e('ack','x'),e('grant','a',3),e('grant','a',4),e('reserve','y',5),e('cancel','y'),e('commit','y')]),case([e('grant','g',8),e('reserve','m',5),e('revoke','g'),e('cancel','m'),e('revoke','g'),e('reserve','n',1)]),case([e('commit','m'),e('ack','m'),e('cancel','m'),e('revoke','g'),e('grant','g',3),e('reserve','m',3),e('ack','m'),e('cancel','m'),e('cancel','m'),e('ack','m')])];rng=random.Random(1249)
|
||||
for _ in range(35):
|
||||
E=[]
|
||||
for _ in range(70):
|
||||
op=rng.choice(['grant','revoke','reserve','commit','cancel','ack']);name=('g' if op in ('grant','revoke') else 'm')+str(rng.randrange(4));E.append(e(op,name,rng.randrange(1,9) if op in ('grant','reserve') else None))
|
||||
cases.append(case(E))
|
||||
def oracle(d):
|
||||
# Independent discrete byte provenance: each unit retains its grant label, including after destruction.
|
||||
grants={};messages={};free=[];destroyed=[];out=[]
|
||||
for row in d['events']:
|
||||
op=row['op'];name=row['id'];accepted=True;reason='duplicate';sent=None
|
||||
if op=='grant':
|
||||
a=row['amount']
|
||||
if name not in grants:grants[name]=[a,True];free.extend([name]*a);reason='granted'
|
||||
elif grants[name][0]!=a:accepted=False;reason='grant_conflict'
|
||||
elif op=='revoke':
|
||||
if name not in grants:accepted=False;reason='unknown_grant'
|
||||
elif grants[name][1]:grants[name][1]=False;destroyed.extend(g for g in free if g==name);free=[g for g in free if g!=name];reason='revoked'
|
||||
elif op=='reserve':
|
||||
a=row['amount']
|
||||
if name in messages:
|
||||
if messages[name][0]!=a:accepted=False;reason='message_conflict'
|
||||
elif len(free)<a:accepted=False;reason='insufficient_credit'
|
||||
else:
|
||||
order={g:i for i,g in enumerate(grants)};free.sort(key=order.get);assigned=free[:a];free=free[a:];messages[name]=[a,'reserved',assigned];reason='reserved'
|
||||
elif name not in messages:accepted=False;reason='unknown_message'
|
||||
else:
|
||||
size,state,assigned=messages[name]
|
||||
if op=='commit' and state=='reserved':
|
||||
messages[name][1]='committed';reason='committed';sent=dict(id=name,amount=size,allocations=[[g,assigned.count(g)] for g in grants if g in assigned])
|
||||
elif (op=='cancel' and state=='reserved') or (op=='ack' and state=='committed'):
|
||||
for g in assigned:(free if grants[g][1] else destroyed).append(g)
|
||||
messages[name][1]='cancelled' if op=='cancel' else 'acked';reason='cancelled' if op=='cancel' else 'acknowledged'
|
||||
elif not (op=='commit' and state in ('committed','acked') or op=='cancel' and state=='cancelled' or op=='ack' and state=='acked'):accepted=False;reason='invalid_state'
|
||||
live=[g for a,s,tokens in messages.values() if s in ('reserved','committed') for g in tokens];G=[dict(id=g,amount=a,active=active,available=free.count(g),in_use=live.count(g),destroyed=destroyed.count(g)) for g,(a,active) in grants.items()];M=[dict(id=n,amount=a,state=s,allocations=[[g,tokens.count(g)] for g in grants if g in tokens]) for n,(a,s,tokens) in messages.items()];totals=dict(issued=sum(g['amount'] for g in G),available=len(free),in_use=len(live),destroyed=len(destroyed));out.append(dict(accepted=accepted,reason=reason,sent=copy.deepcopy(sent),ledger=copy.deepcopy(dict(grants=G,messages=M,totals=totals))))
|
||||
return out
|
||||
E=[e('grant','g'+str(i),1) for i in range(20)]+[e('reserve','all',20),e('commit','all')]+[e('revoke','g'+str(i)) for i in range(0,20,2)]+[e('ack','all'),e('reserve','remaining',10),e('cancel','remaining')];cases.append(case(E))
|
||||
E=[e('grant','g'+str(i),5) for i in range(20)]
|
||||
for i in range(20):E.extend([e('reserve','m'+str(i),5),e('commit','m'+str(i)),e('ack','m'+str(i))])
|
||||
E.extend([e('ack','m19')]*(500-len(E)));cases.append(case(E));truth=[{'ok':{'__credit':oracle(d)}} for d in cases]
|
||||
# Exact numeric upper bound, no million-unit token materialization required.
|
||||
d=case([e('grant','big',1000000)]);cases.append(d);truth.append({'ok':{'__credit':[dict(accepted=True,reason='granted',sent=None,ledger=dict(grants=[dict(id='big',amount=1000000,active=True,available=1000000,in_use=0,destroyed=0)],messages=[],totals=dict(issued=1000000,available=1000000,in_use=0,destroyed=0)))]}})
|
||||
small=case([e('grant','big',1),e('reserve','packet',1),e('revoke','big'),e('commit','packet'),e('ack','packet')]);large=copy.deepcopy(small)
|
||||
for row in large['events']:
|
||||
if 'amount' in row:row['amount']*=1000000
|
||||
def scale(value):
|
||||
if type(value) is int:return value*1000000
|
||||
if isinstance(value,list):return [scale(v) for v in value]
|
||||
if isinstance(value,dict):return {k:scale(v) for k,v in value.items()}
|
||||
return value
|
||||
cases.append(large);truth.append({'ok':{'__credit':scale(oracle(small))}})
|
||||
bad=[None,{},case([e('grant','',1)]),case([e('grant','x'*33,1)]),case([e('grant','中',1)]),case([e('other','x')]),case([e('grant','x')]),case([dict(op='grant',id='x',amount=None)]),case([dict(op='reserve',id='x',amount=None)]),case([e('grant','x',0)]),case([e('grant','x',True)]),case([e('reserve','x',1000001)]),case([e('revoke','g'+str(i)) for i in range(21)]),case([e('ack','m'+str(i)) for i in range(21)]),case([e('ack','x')]*501)]
|
||||
return cases+bad,truth+[{'error':'ValueError'} for _ in bad]
|
||||
|
||||
|
||||
_original_fixtures=fixtures
|
||||
def fixtures():
|
||||
import copy
|
||||
cases,expected=_original_fixtures()
|
||||
boundary_case,boundary_truth=({'events': [{'op': 'grant', 'id': 'g', 'amount': 1000000}]}, [{'accepted': True, 'reason': 'granted', 'sent': None, 'ledger': {'grants': [{'id': 'g', 'amount': 1000000, 'active': True, 'available': 1000000, 'in_use': 0, 'destroyed': 0}], 'messages': [], 'totals': {'issued': 1000000, 'available': 1000000, 'in_use': 0, 'destroyed': 0}}}])
|
||||
cases.append(boundary_case);expected.append({'ok':boundary_truth})
|
||||
def replace_first(x,value):
|
||||
if isinstance(x,dict):
|
||||
for k,v in x.items():
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[k]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
elif isinstance(x,list):
|
||||
for i,v in enumerate(x):
|
||||
if isinstance(v,(int,float)) and not isinstance(v,bool):x[i]=value;return True
|
||||
if replace_first(v,value):return True
|
||||
return False
|
||||
for bad in [1000001,-1000001,1e308,-1e308,10**400,-10**400]:
|
||||
case=copy.deepcopy(boundary_case)
|
||||
if not replace_first(case,bad):continue # Tasks without numeric fields use structural boundary fixtures.
|
||||
cases.append(case);expected.append({'error':'ValueError'})
|
||||
return cases,expected
|
||||
|
||||
import pathlib,sys,tempfile,shutil,subprocess,json,math,secrets
|
||||
ROOT=pathlib.Path(sys.argv[1]).resolve()
|
||||
def require(ok,message):
|
||||
if not ok:raise AssertionError(message)
|
||||
def same(actual,expected):
|
||||
if isinstance(expected,dict) and '__credit' in expected:
|
||||
if not same(actual,expected['__credit']):return False
|
||||
for row in actual:
|
||||
ledger=row['ledger'];G={g['id']:g for g in ledger['grants']};used={g:0 for g in G}
|
||||
for message in ledger['messages']:
|
||||
allocations=message['allocations']
|
||||
if sum(a for _,a in allocations)!=message['amount']:return False
|
||||
if message['state'] in ('reserved','committed'):
|
||||
for g,amount in allocations:used[g]+=amount
|
||||
for name,g in G.items():
|
||||
if g['in_use']!=used[name] or g['amount']!=g['available']+g['in_use']+g['destroyed'] or min(g['available'],g['in_use'],g['destroyed'])<0 or not g['active'] and g['available']!=0:return False
|
||||
totals=ledger['totals']
|
||||
if totals!={key:sum(g['amount' if key=='issued' else key] for g in G.values()) for key in ('issued','available','in_use','destroyed')} or totals['issued']!=sum(totals[k] for k in ('available','in_use','destroyed')):return False
|
||||
return True
|
||||
if isinstance(expected,bool) or expected is None or isinstance(expected,str):return type(actual) is type(expected) and actual==expected
|
||||
if isinstance(expected,int):return type(actual) is int and actual==expected
|
||||
if isinstance(expected,float):return not isinstance(actual,bool) and isinstance(actual,(int,float)) and math.isfinite(actual) and math.isclose(actual,expected,rel_tol=1e-8,abs_tol=1e-8)
|
||||
if isinstance(expected,list):return isinstance(actual,list) and len(actual)==len(expected) and all(same(a,b) for a,b in zip(actual,expected))
|
||||
if isinstance(expected,dict):return isinstance(actual,dict) and actual.keys()==expected.keys() and all(same(actual[k],v) for k,v in expected.items())
|
||||
return False
|
||||
RUNNER="""import sys,json,copy,pickle\nsys.path.insert(0,sys.argv[1])\nnonce=sys.argv[2]\nimport task\nrows=[]\nfor case in json.load(sys.stdin):\n value=copy.deepcopy(case);before=pickle.dumps(value)\n try:rows.append({'ok':task.solve(value)})\n except ValueError:rows.append({'error':'ValueError'})\n if pickle.dumps(value)!=before:raise AssertionError('input mutated')\nprint('RESULT:'+nonce+':'+json.dumps(rows,ensure_ascii=True,allow_nan=True))\nprint('COMPLETE:'+nonce)\n"""
|
||||
try:
|
||||
cases,expected=fixtures()
|
||||
require(len(cases)==len(expected),'internal fixture size')
|
||||
with tempfile.TemporaryDirectory(prefix='n2-check-',dir='/tmp') as td:
|
||||
scratch=pathlib.Path(td);source=ROOT/'task.py'
|
||||
require(source.is_file() and not source.is_symlink(),'missing task.py')
|
||||
shutil.copyfile(source,scratch/'task.py');(scratch/'runner.py').write_text(RUNNER)
|
||||
nonce=secrets.token_hex(16)
|
||||
p=subprocess.run([sys.executable,'-I','-B',str(scratch/'runner.py'),str(scratch),nonce],input=json.dumps(cases,allow_nan=True),text=True,capture_output=True,cwd=scratch,timeout=25)
|
||||
require(p.returncode==0,'candidate execution failed')
|
||||
lines=p.stdout.splitlines();prefix='RESULT:'+nonce+':'
|
||||
require(lines.count('COMPLETE:'+nonce)==1,'trusted runner did not complete')
|
||||
result_lines=[x[len(prefix):] for x in lines if x.startswith(prefix)]
|
||||
require(len(result_lines)==1,'result marker count')
|
||||
try:got=json.loads(result_lines[0])
|
||||
except (ValueError,TypeError):raise AssertionError('candidate output protocol')
|
||||
require(isinstance(got,list) and len(got)==len(expected),'result count')
|
||||
for i,(a,e) in enumerate(zip(got,expected)):require(same(a,e),'case '+str(i)+' mismatch')
|
||||
print('PASS')
|
||||
except Exception as exc:
|
||||
message=str(exc)
|
||||
if 'scratch' in globals():message=message.replace(str(scratch),'<scratch>')
|
||||
print('FAIL:',type(exc).__name__,message[:500]);sys.exit(1)
|
||||
74
tasks/S500_n2_149/gold/task.py
Normal file
74
tasks/S500_n2_149/gold/task.py
Normal file
@ -0,0 +1,74 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);raw=arr(field(d,'events'))
|
||||
if len(raw)>500:raise ValueError('size')
|
||||
events=[];grants=set();messages=set()
|
||||
for row in raw:
|
||||
obj(row);op=field(row,'op');name=field(row,'id')
|
||||
if op not in ('grant','revoke','reserve','commit','cancel','ack') or not isinstance(name,str) or not 1<=len(name)<=32 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' for c in name):raise ValueError('event')
|
||||
(grants if op in ('grant','revoke') else messages).add(name);amount=field(row,'amount') if op in ('grant','reserve') else None
|
||||
if op in ('grant','reserve') and (type(amount) is not int or not 1<=amount<=1000000):raise ValueError('amount')
|
||||
events.append((op,name,amount))
|
||||
if len(grants)>20 or len(messages)>20:raise ValueError('id budget')
|
||||
return events
|
||||
def solve(data):
|
||||
import copy
|
||||
events=prepare(data);G={};M={};out=[]
|
||||
def release(m):
|
||||
for gid,size in m['allocations']:
|
||||
g=G[gid];g['in_use']-=size
|
||||
if g['active']:g['available']+=size
|
||||
else:g['destroyed']+=size
|
||||
def process(op,name,amount):
|
||||
if op=='grant':
|
||||
if name in G:return (True,'duplicate',None) if G[name]['amount']==amount else (False,'grant_conflict',None)
|
||||
G[name]=dict(id=name,amount=amount,active=True,available=amount,in_use=0,destroyed=0);return True,'granted',None
|
||||
if op=='revoke':
|
||||
if name not in G:return False,'unknown_grant',None
|
||||
g=G[name]
|
||||
if not g['active']:return True,'duplicate',None
|
||||
g['active']=False;g['destroyed']+=g['available'];g['available']=0;return True,'revoked',None
|
||||
if op=='reserve':
|
||||
if name in M:return (True,'duplicate',None) if M[name]['amount']==amount else (False,'message_conflict',None)
|
||||
if sum(g['available'] for g in G.values())<amount:return False,'insufficient_credit',None
|
||||
remaining=amount;alloc=[]
|
||||
for gid,g in G.items():
|
||||
take=min(remaining,g['available'])
|
||||
if take:alloc.append([gid,take]);g['available']-=take;g['in_use']+=take;remaining-=take
|
||||
if remaining==0:break
|
||||
M[name]=dict(id=name,amount=amount,state='reserved',allocations=alloc);return True,'reserved',None
|
||||
if name not in M:return False,'unknown_message',None
|
||||
m=M[name];state=m['state']
|
||||
if op=='commit':
|
||||
if state in ('committed','acked'):return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
m['state']='committed';return True,'committed',dict(id=name,amount=m['amount'],allocations=copy.deepcopy(m['allocations']))
|
||||
if op=='cancel':
|
||||
if state=='cancelled':return True,'duplicate',None
|
||||
if state!='reserved':return False,'invalid_state',None
|
||||
release(m);m['state']='cancelled';return True,'cancelled',None
|
||||
if state=='acked':return True,'duplicate',None
|
||||
if state!='committed':return False,'invalid_state',None
|
||||
release(m);m['state']='acked';return True,'acknowledged',None
|
||||
for event in events:
|
||||
accepted,reason,sent=process(*event);totals=dict(issued=sum(g['amount'] for g in G.values()),**{key:sum(g[key] for g in G.values()) for key in ('available','in_use','destroyed')});out.append(dict(accepted=accepted,reason=reason,sent=sent,ledger=copy.deepcopy(dict(grants=list(G.values()),messages=list(M.values()),totals=totals))))
|
||||
return out
|
||||
2
tasks/S500_n2_149/noop/task.py
Normal file
2
tasks/S500_n2_149/noop/task.py
Normal file
@ -0,0 +1,2 @@
|
||||
import os
|
||||
os._exit(0)
|
||||
3
tasks/S500_n2_149/prompt.md
Normal file
3
tasks/S500_n2_149/prompt.md
Normal file
@ -0,0 +1,3 @@
|
||||
当前目录task.py尚未实现。请按README.md公开契约完成可撤销字节信用的预留与归还账本并自行验证。
|
||||
|
||||
最终只提交并评分以下文件:`task.py`。
|
||||
63
tasks/S500_n2_149/spec.md
Normal file
63
tasks/S500_n2_149/spec.md
Normal file
@ -0,0 +1,63 @@
|
||||
# 任务规格:S500_n2_149
|
||||
|
||||
规范:[任务制作规范](../../docs/task-authoring.md)。路线 A 仅填第 1、4、7 节。
|
||||
|
||||
## 1. 身份与来源
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| task-id / 版本 | S500_n2_149 / 1 |
|
||||
| 作者 / 独立评审人 | Codex lane2 / root(2026-10-20,只读审阅通过;证据见本批 root-review-group12.json) |
|
||||
| 审核状态 / 难度 | CALIBRATED / UNMEASURED |
|
||||
| 原项目与快照 | Bos-qiao envs/S500_n2_149;本批只读复制到 factory/20261020-A-bos-n2-9/bos-envs/S500_n2_149 |
|
||||
| 来源路线 / 来源ID | A 导入成熟任务(Bos 原题) / S500_n2_149 |
|
||||
| 来源与授权 | 用户 2026-10-20 第9批 BRIEF;2026-10-12 项目资产接入授权;来源只读,样例脚本仅解析 |
|
||||
| 隐私处理 | 无真实用户会话;本批不读取凭据 |
|
||||
| 替身测试 | 软件输入驱动纯 Python 行为;不需要板卡或真实外设,software |
|
||||
| split 分组键 | bos:new_n2_149_revocable_credit_ledger |
|
||||
| 来源组 / 根因族 | Bos n2 / serial-protocol |
|
||||
| 与已有任务的关系 | 本批剩余来源独立导入;非已有任务改名 |
|
||||
| 导入方式 | 直接导入 |
|
||||
| 验证范围 | 原 README 公开合同与原隐藏行为判据 |
|
||||
| 未验证范围 | 只验证纯软件行为;未验证真实硬件、实时性能或模型难度。 |
|
||||
|
||||
## 2. 初态与环境
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 3. 公开题面与接口
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 4. 判据检查项 ↔ 依据与合法解
|
||||
|
||||
| 判据检查项 | 公开依据 | 可观察结果与检查 |
|
||||
| --- | --- | --- |
|
||||
| grant/reserve幂等与身份 | template/README.md:5(额度不足拒绝insufficient_credit) | 独立逐字节provenance oracle,gold余额增减、valid由活跃消息重算;不足不占ID/拒绝无副作用 |
|
||||
| 提交取消确认与撤销归还 | template/README.md:6(inactive则销毁,绝不能重新授权) | 首次commit sent一次,commit/ack/cancel合法状态表;撤销grant后归还变destroyed不复活 |
|
||||
| 分配顺序及账本守恒 | template/README.md:7(每grant及全局必须满足issued=available+in_use+destroyed) | 首次grant顺序分配/保留历史allocation,specialsame独立核每grant与全局守恒/in_use对应活消息 |
|
||||
| 类型规模及等长输出 | template/README.md:7(返回与events等长列表) | amount明确int非bool;20ID各命名空间含未知引用/500事件闭界、空[];百万额度解析及缩放例,快照输入保全 |
|
||||
|
||||
- 题面改动:无;逐项核对后原公开行为与判据一致。
|
||||
- 改动依据:原文已有外层等长列表和完整ledger嵌套结构、严格int输入、状态表/幂等/守恒/顺序;无需澄清。
|
||||
- 判据与标准答案:原判据、gold 和 valid 未因校准结果而改写;重写隔离时仅迁移执行边界,保留原断言语义。
|
||||
- 合法解:只要求原公开接口、类型和行为;原 valid 样例(如有)作为合法替代解校准,不限定实现算法或源码形态。
|
||||
- 隔离:沿用受保护 verify.py 的 root 判据和降权候选子进程;正式容器独立校准;本地模式只执行本仓库可信样例。
|
||||
|
||||
## 5. 四类样例与校准
|
||||
|
||||
沿用 Bos 原题。
|
||||
|
||||
## 6. 真实试采与证据
|
||||
|
||||
沿用 Bos 原题。本批按 BRIEF 不运行 Qwen 或其他模型;难度 UNMEASURED,未试采。
|
||||
|
||||
## 7. 评审与准入
|
||||
|
||||
- 作者已逐题完整读 README、check.py、附属 Python 判据、gold 与 valid(如有),核对阈值等号、精确/浮点语义、int/float/bool、规模、空输入、异常及容差。
|
||||
- 状态:CALIBRATED;只到两道校准闸门,尚未真实试采,不记 ADMITTED。
|
||||
- 闸门1可信本地:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/local/calibration-0d451d1a97b445afbf3b624d1c43bdac。
|
||||
- 闸门2trace6 Docker:PASS;30 次;cleanup=confirmed;证据 runs/20261020-A-bos-n2-9/docker/calibration-28cf7506da5141f583e70c55861e76b2。
|
||||
- 正式镜像:ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1。
|
||||
- 每类样例分别五次;若含 cheat_read_grader,本地无隔离可读而 PASS 仅按规范 §7 记例外,正式 Docker 必须 FAIL。
|
||||
- 独立只读审阅由主控另存本批 review 证据;本 spec 不代替独立审阅或模型难度测量。
|
||||
36
tasks/S500_n2_149/task.json
Normal file
36
tasks/S500_n2_149/task.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "S500_n2_149",
|
||||
"version": "1",
|
||||
"family": "serial-protocol",
|
||||
"source": "bos-qiao/task_factory_500_20260914/envs/S500_n2_149",
|
||||
"template": "template",
|
||||
"verifier": "verify.py",
|
||||
"candidate_files": [
|
||||
"task.py"
|
||||
],
|
||||
"timeout_seconds": 120,
|
||||
"fixtures": {
|
||||
"gold": "PASS",
|
||||
"template": "FAIL",
|
||||
"noop": "FAIL",
|
||||
"cheat": "FAIL",
|
||||
"cheat_revoked_credit_returns_available": "FAIL",
|
||||
"valid_alternative": "PASS"
|
||||
},
|
||||
"grader_files": [
|
||||
"check.py"
|
||||
],
|
||||
"bos": {
|
||||
"source_qid": "new_n2_149_revocable_credit_ledger",
|
||||
"origin": "original_authored",
|
||||
"image": "python@sha256:78387bc3881b8273120a12ebe6c1ab22b018ccc2c9adf565ae1ac9b536e184ea",
|
||||
"budget_s": 600,
|
||||
"fixture_scripts": {
|
||||
"gold": "gold.sh",
|
||||
"noop": "cheat_exit_zero.sh",
|
||||
"cheat": "cheat_double_ack_refunds.sh",
|
||||
"cheat_revoked_credit_returns_available": "cheat_revoked_credit_returns_available.sh",
|
||||
"valid_alternative": "valid_alternative.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
tasks/S500_n2_149/template/README.md
Normal file
9
tasks/S500_n2_149/template/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# 可撤销字节信用的预留与归还账本
|
||||
|
||||
输入{events:[事件,...]},最多500事件。每事件有op和id;op为grant/revoke/reserve/commit/cancel/ack。id为1..32个ASCII字母/数字/下划线;grant/revoke使用grant ID命名空间,其余使用message ID命名空间,两空间可同名。全输入中每种命名空间最多出现20个不同ID,包括未知ID引用。grant和reserve另需amount,为1..1000000整数int不含bool。其它额外字段可忽略。所有结构先验证,结构/范围错误抛ValueError。
|
||||
初态为空。grant(id,amount):新ID建立不可撤销历史的授予记录,全部amount可用、active=True,reason="granted";已有ID同amount幂等成功duplicate,不使已撤销grant重新active;不同amount拒绝grant_conflict。revoke(id):未知拒绝unknown_grant;已inactive幂等duplicate;否则置inactive,将其全部可用额度销毁,但保留已被消息占用的额度,成功revoked。
|
||||
reserve(id,amount):若ID曾成功reserve且amount相同,则幂等duplicate,不论消息已提交/确认/取消均不复活;若amount不同拒绝message_conflict。新ID只有总可用额度>=amount才成功reserved,按grant首次成功授予顺序分配,先耗尽前面的可用额度再拆到下一个;成功后保存分配列表并处于reserved。额度不足拒绝insufficient_credit,完全无副作用且不占用message ID,之后可重试。
|
||||
commit(id):未知拒绝unknown_message;reserved变committed,reason=committed并发出一次sent描述;committed或acked重复commit幂等duplicate且不再次sent;cancelled拒绝invalid_state。cancel(id):reserved变cancelled并返还额度,reason=cancelled;cancelled重复幂等duplicate;committed/acked拒绝invalid_state。ack(id):committed变acked并返还额度,reason=acknowledged;acked重复幂等duplicate;reserved/cancelled拒绝invalid_state。cancel/ack未知均拒绝unknown_message。返还逐原grant进行:active则重新可用,inactive则销毁,绝不能重新授权。所有拒绝无副作用。
|
||||
返回与events等长列表,每项{accepted:bool,reason:上述字符串,sent:None或{id,amount,allocations},ledger:{grants:[{id,amount,active,available,in_use,destroyed},...],messages:[{id,amount,state,allocations},...],totals:{issued,available,in_use,destroyed}}}。grants按首次grant顺序,messages按首次成功reserve顺序。allocations为[[grant_id,正整数字节数],...],按grant顺序,不含零项;终态消息仍保留历史分配。sent仅首次commit时含该消息id/amount/allocations。in_use仅统计reserved/committed消息的分配。每grant及全局必须满足issued=available+in_use+destroyed(grant的issued即amount),inactive的available为0。信用无时间补充,不模拟传输重试或ACK投票;这是软件授权额度账本。
|
||||
|
||||
这是经授权原创的纯软件数学/事件处理题,source_qid以new_开头,不是历史工程恢复,也不证明任何板卡或外设结果。实现当前目录task.py中的solve(data),允许额外正常日志,判据只比较函数结果。仅依赖Python标准库。输入中的“数值”指绝对值<=1000000的有限int/float且不包括bool(范围限制适用于所有输入数值,输出不受此范围限制);无效输入(包括缺必需字段、类型错误及下述越界)必须抛ValueError。未说明的额外字典键可忽略。不得改写传入数据。允许添加额外文件,但task.py必须自包含,判据仅复制它到干净临时目录导入。输出浮点容差绝对/相对1e-8。可用python3导入task并调用solve自行验证。
|
||||
3
tasks/S500_n2_149/template/task.py
Normal file
3
tasks/S500_n2_149/template/task.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Implement solve(data) according to README.md."""
|
||||
def solve(data):
|
||||
raise NotImplementedError("not implemented")
|
||||
70
tasks/S500_n2_149/valid_alternative/task.py
Normal file
70
tasks/S500_n2_149/valid_alternative/task.py
Normal file
@ -0,0 +1,70 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
d=obj(data);raw=arr(field(d,'events'))
|
||||
if len(raw)>500:raise ValueError('size')
|
||||
events=[];grants=set();messages=set()
|
||||
for row in raw:
|
||||
obj(row);op=field(row,'op');name=field(row,'id')
|
||||
if op not in ('grant','revoke','reserve','commit','cancel','ack') or not isinstance(name,str) or not 1<=len(name)<=32 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_' for c in name):raise ValueError('event')
|
||||
(grants if op in ('grant','revoke') else messages).add(name);amount=field(row,'amount') if op in ('grant','reserve') else None
|
||||
if op in ('grant','reserve') and (type(amount) is not int or not 1<=amount<=1000000):raise ValueError('amount')
|
||||
events.append((op,name,amount))
|
||||
if len(grants)>20 or len(messages)>20:raise ValueError('id budget')
|
||||
return events
|
||||
def solve(data):
|
||||
import copy
|
||||
events=prepare(data);G={};M={};out=[]
|
||||
def balance():
|
||||
used={g:0 for g in G}
|
||||
for amount,state,alloc in M.values():
|
||||
if state in ('reserved','committed'):
|
||||
for g,size in alloc:used[g]+=size
|
||||
return {g:dict(id=g,amount=amount,active=active,available=amount-used[g] if active else 0,in_use=used[g],destroyed=0 if active else amount-used[g]) for g,(amount,active) in G.items()}
|
||||
for op,name,amount in events:
|
||||
accepted=True;sent=None;reason='duplicate'
|
||||
if op=='grant':
|
||||
if name not in G:G[name]=(amount,True);reason='granted'
|
||||
elif G[name][0]!=amount:accepted=False;reason='grant_conflict'
|
||||
elif op=='revoke':
|
||||
if name not in G:accepted=False;reason='unknown_grant'
|
||||
elif G[name][1]:G[name]=(G[name][0],False);reason='revoked'
|
||||
elif op=='reserve':
|
||||
if name in M:
|
||||
if M[name][0]!=amount:accepted=False;reason='message_conflict'
|
||||
else:
|
||||
B=balance()
|
||||
if sum(g['available'] for g in B.values())<amount:accepted=False;reason='insufficient_credit'
|
||||
else:
|
||||
alloc=[];left=amount
|
||||
for gid,g in B.items():
|
||||
count=min(left,g['available'])
|
||||
if count:alloc.append([gid,count]);left-=count
|
||||
M[name]=(amount,'reserved',alloc);reason='reserved'
|
||||
elif name not in M:accepted=False;reason='unknown_message'
|
||||
else:
|
||||
size,state,alloc=M[name]
|
||||
if op=='commit' and state=='reserved':M[name]=(size,'committed',alloc);sent=dict(id=name,amount=size,allocations=copy.deepcopy(alloc));reason='committed'
|
||||
elif op=='cancel' and state=='reserved':M[name]=(size,'cancelled',alloc);reason='cancelled'
|
||||
elif op=='ack' and state=='committed':M[name]=(size,'acked',alloc);reason='acknowledged'
|
||||
elif not ((op=='commit' and state in ('committed','acked')) or (op=='cancel' and state=='cancelled') or (op=='ack' and state=='acked')):accepted=False;reason='invalid_state'
|
||||
grants=list(balance().values());messages=[dict(id=n,amount=a,state=s,allocations=copy.deepcopy(alloc)) for n,(a,s,alloc) in M.items()];totals={key:sum(g['amount' if key=='issued' else key] for g in grants) for key in ('issued','available','in_use','destroyed')};out.append(dict(accepted=accepted,reason=reason,sent=sent,ledger=dict(grants=grants,messages=messages,totals=totals)))
|
||||
return out
|
||||
130
tasks/S500_n2_149/verify.py
Normal file
130
tasks/S500_n2_149/verify.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
GRADER = Path(__file__).resolve().parent
|
||||
BLOCKED = "isolation-blocked.txt"
|
||||
GUARD = 86
|
||||
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
|
||||
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
|
||||
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
|
||||
CHECK = (
|
||||
"import os, runpy, subprocess, sys, tempfile\n"
|
||||
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
|
||||
"untrusted = [os.path.realpath(sys.argv[1])]\n"
|
||||
"def inside(path):\n"
|
||||
" path = os.path.realpath(str(path))\n"
|
||||
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
|
||||
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
|
||||
"def guard(event, args):\n"
|
||||
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
|
||||
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
|
||||
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
|
||||
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
|
||||
" sys.__stderr__.flush()\n"
|
||||
" os._exit(%d)\n"
|
||||
"mkdtemp = tempfile.mkdtemp\n"
|
||||
"def scratch(*args, **kwargs):\n"
|
||||
" path = mkdtemp(*args, **kwargs)\n"
|
||||
" untrusted.append(os.path.realpath(path))\n"
|
||||
" if isolated:\n"
|
||||
" os.chown(path, 65534, 65534)\n"
|
||||
" return path\n"
|
||||
"tempfile.mkdtemp = scratch\n"
|
||||
"popen = subprocess.Popen.__init__\n"
|
||||
"def drop(self, *args, **kwargs):\n"
|
||||
" if isolated:\n"
|
||||
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
|
||||
" popen(self, *args, **kwargs)\n"
|
||||
"subprocess.Popen.__init__ = drop\n"
|
||||
"real = subprocess.run\n"
|
||||
"def run(*args, **kwargs):\n"
|
||||
" result = real(*args, **kwargs)\n"
|
||||
" if result.returncode and result.stderr:\n"
|
||||
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
|
||||
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
|
||||
" return result\n"
|
||||
"subprocess.run = run\n"
|
||||
"sys.addaudithook(guard)\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
|
||||
|
||||
|
||||
class UnsupportedEnvironment(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def candidate_user():
|
||||
os.setgroups([])
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
|
||||
|
||||
def isolation():
|
||||
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
|
||||
return None
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
|
||||
probe = (
|
||||
"from pathlib import Path\n"
|
||||
"try: Path('/grader/verify.py').read_bytes()\n"
|
||||
"except PermissionError: raise SystemExit(0)\n"
|
||||
"raise SystemExit(1)\n"
|
||||
)
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "-I", "-c", probe],
|
||||
capture_output=True, timeout=10, preexec_fn=candidate_user)
|
||||
except subprocess.SubprocessError as error:
|
||||
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
|
||||
if result.returncode != 0:
|
||||
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
|
||||
return candidate_user
|
||||
|
||||
|
||||
def verify(candidate):
|
||||
if (GRADER / BLOCKED).exists():
|
||||
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
|
||||
isolated = isolation() is not None
|
||||
if shutil.which("gcc") is None:
|
||||
raise UnsupportedEnvironment("C compiler unavailable")
|
||||
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
|
||||
root = Path(temporary)
|
||||
work, grader = root / "work", root / "grader"
|
||||
shutil.copytree(candidate, work, symlinks=True)
|
||||
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
|
||||
if isolated:
|
||||
os.chmod(root, 0o711)
|
||||
os.chmod(grader, 0o700)
|
||||
for path in (work, *work.rglob("*")):
|
||||
os.lchown(path, 65534, 65534)
|
||||
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
|
||||
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
|
||||
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
|
||||
str(grader / "check.py"), str(work)],
|
||||
cwd=root, capture_output=True, text=True, timeout=100)
|
||||
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
|
||||
sys.stderr.write(completed.stderr[-4000:])
|
||||
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
|
||||
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
|
||||
lines = completed.stdout.splitlines()
|
||||
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
|
||||
return {"status": "PASS", "checks": 1}
|
||||
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = verify(Path(sys.argv[1]))
|
||||
except UnsupportedEnvironment as error:
|
||||
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
|
||||
except subprocess.TimeoutExpired:
|
||||
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
|
||||
except Exception as error:
|
||||
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))
|
||||
49
tasks/S500_n2_151/cheat/task.py
Normal file
49
tasks/S500_n2_151/cheat/task.py
Normal file
@ -0,0 +1,49 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
out=[]
|
||||
for pair in arr(field(obj(data),'pairs')):
|
||||
pair=obj(pair);clouds=[]
|
||||
for key in ['left','right']:
|
||||
cloud=[]
|
||||
for row in arr(field(pair,key)):
|
||||
arr(row,2)
|
||||
if any(type(v) is not int or abs(v)>1000000 for v in row):raise ValueError('integer point')
|
||||
cloud.append(tuple(row))
|
||||
clouds.append(cloud)
|
||||
out.append(clouds)
|
||||
return out
|
||||
|
||||
def cross(a,b):return a[0]*b[1]-a[1]*b[0]
|
||||
def sub(a,b):return (a[0]-b[0],a[1]-b[1])
|
||||
def hull(P):
|
||||
P=sorted(set(P))
|
||||
if len(P)<2:return P
|
||||
low=[];up=[]
|
||||
for collection,seq in [(low,P),(up,reversed(P))]:
|
||||
for p in seq:
|
||||
while len(collection)>1 and cross(sub(collection[-1],collection[-2]),sub(p,collection[-1]))<=0:collection.pop()
|
||||
collection.append(p)
|
||||
return low[:-1]+up[:-1]
|
||||
def solve(data):
|
||||
out=[]
|
||||
for A,B in prepare(data):out.append([list(p) for p in hull([(a[0]+b[0],a[1]+b[1]) for a,b in zip(A,B)])])
|
||||
return out
|
||||
49
tasks/S500_n2_151/cheat_union_instead_of_sum/task.py
Normal file
49
tasks/S500_n2_151/cheat_union_instead_of_sum/task.py
Normal file
@ -0,0 +1,49 @@
|
||||
import math
|
||||
|
||||
def obj(x):
|
||||
if not isinstance(x,dict):raise ValueError('expected object')
|
||||
return x
|
||||
|
||||
def arr(x,n=None):
|
||||
if not isinstance(x,list) or (n is not None and len(x)!=n):raise ValueError('expected list')
|
||||
return x
|
||||
|
||||
def num(x):
|
||||
if isinstance(x,bool) or not isinstance(x,(int,float)) or abs(x)>1000000 or not math.isfinite(x):raise ValueError('expected finite number')
|
||||
return float(x)
|
||||
|
||||
def vec(x,n):return [num(v) for v in arr(x,n)]
|
||||
|
||||
def field(d,k):
|
||||
if k not in d:raise ValueError('missing field')
|
||||
return d[k]
|
||||
|
||||
def prepare(data):
|
||||
out=[]
|
||||
for pair in arr(field(obj(data),'pairs')):
|
||||
pair=obj(pair);clouds=[]
|
||||
for key in ['left','right']:
|
||||
cloud=[]
|
||||
for row in arr(field(pair,key)):
|
||||
arr(row,2)
|
||||
if any(type(v) is not int or abs(v)>1000000 for v in row):raise ValueError('integer point')
|
||||
cloud.append(tuple(row))
|
||||
clouds.append(cloud)
|
||||
out.append(clouds)
|
||||
return out
|
||||
|
||||
def cross(a,b):return a[0]*b[1]-a[1]*b[0]
|
||||
def sub(a,b):return (a[0]-b[0],a[1]-b[1])
|
||||
def hull(P):
|
||||
P=sorted(set(P))
|
||||
if len(P)<2:return P
|
||||
low=[];up=[]
|
||||
for collection,seq in [(low,P),(up,reversed(P))]:
|
||||
for p in seq:
|
||||
while len(collection)>1 and cross(sub(collection[-1],collection[-2]),sub(p,collection[-1]))<=0:collection.pop()
|
||||
collection.append(p)
|
||||
return low[:-1]+up[:-1]
|
||||
def solve(data):
|
||||
out=[]
|
||||
for A,B in prepare(data):out.append([list(p) for p in hull(A+B)])
|
||||
return out
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user