diff --git a/docs/calibration-checklist.md b/docs/calibration-checklist.md index 94d224e..1317657 100644 --- a/docs/calibration-checklist.md +++ b/docs/calibration-checklist.md @@ -18,6 +18,9 @@ - [ ] 保护相邻正常行为,阻止禁用缓存、无限缓存、截断内容等绕过。 - [ ] 并发场景使用确定性屏障或虚拟时钟,避免靠脆弱 sleep 排名。 - [ ] 挂起用例有有界清理;环境故障单列而非默认为零。 +- [ ] 评分结果走认证通道:评分器每次生成随机口令经 stdin 传给评测进程,`author/result-channel.mjs` 在载入提交代码前读走口令并保存输出函数;评测进程以 `--frozen-intrinsics` 启动,只接受恰好一行带本次口令的结果。提交代码自行打印、提前退出或改写全局对象都只会得到环境无效。 +- [ ] 需要隔离执行提交代码的子进程(如独立解码、独立同步端)用 Node 权限模型(Node 22 起 `--permission`,20 为 `--experimental-permission`),只放行运行脚本、提交目录与必要输入,授权路径先取真实路径;解码结果由父进程逐字节比对原文,不信任子进程自报的通过结论。 +- [ ] 留存风险写清:同进程提交代码仍可读取作者目录文件(题包本身公开,不构成泄题),调试器/inspector 类内存读取不在防护范围;对抗性排名场景需另行隔离。 - [ ] 实际运行日志、环境版本、清单与 SHA-256 留存。 ## 冻结与试跑 diff --git a/questions/codex-namespace-tool-collision/v1/author/editable.json b/questions/codex-namespace-tool-collision/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/codex-namespace-tool-collision/v1/author/evaluator.mjs b/questions/codex-namespace-tool-collision/v1/author/evaluator.mjs new file mode 100644 index 0000000..5a0be8b --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/author/evaluator.mjs @@ -0,0 +1,581 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir] = process.argv.slice(2); +const responsesMod = await import(pathToFileURL(path.join(subDir, 'responses.mjs')).href); +const nsMod = await import(pathToFileURL(path.join(subDir, 'namespace-tool-compat.mjs')).href); + +const { prepareResponsesCompatibility, createResponsesCompatibilityAdapter } = responsesMod; +const { NamespaceToolCollisionError, rewriteRoutedNamespaceToolsForUpstream } = nsMod; + +async function responseText(transform, text) { + let out = ''; + transform.setEncoding('utf8'); + transform.on('data', (chunk) => { out += chunk; }); + const done = new Promise((resolve, reject) => { + transform.on('end', () => resolve(out)); + transform.on('error', reject); + }); + transform.end(text); + return done; +} + +const DEFAULT_POLICY = { + customTools: 'preserve-apply-patch', + namespaceTools: 'functions', + repairFunctionArguments: true, +}; + +async function runItem(name, fn, items, errors) { + try { + await fn(); + items[name] = true; + } catch (err) { + items[name] = false; + errors.push(`${name}: ${err?.message ?? String(err)}`); + } +} + +const items = {}; +const errors = []; + +// Group 1: collision_disambiguation +await runItem('collide_roundtrip_json_sse', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + const parameters = { type: 'object', properties: { count: { type: 'integer' } } }; + const input = { + tools: [ + { type: 'function', name: 'collaboration__followup_task', parameters }, + { type: 'namespace', name: 'collaboration', tools: [{ type: 'function', name: 'followup_task', parameters }] }, + ], + input: [{ type: 'function_call', namespace: 'collaboration', name: 'followup_task', call_id: 'old', arguments: '{"count":1}' }], + tool_choice: { type: 'function', namespace: 'collaboration', name: 'followup_task' }, + }; + const request = adapter.adaptRequest(input, 1); + assert.equal(request.tools.length, 2); + assert.ok(request.tools.every((tool) => tool.type === 'function')); + const wireName = request.tools[1].name; + assert.notEqual(wireName, 'collaboration__followup_task'); + assert.deepEqual(request.tool_choice, { type: 'function', name: wireName }); + assert.equal(request.input[0].name, wireName); + assert.equal(request.input[0].call_id, 'old'); + assert.equal('namespace' in request.input[0], false); + + const output = [{ type: 'function_call', status: 'completed', name: wireName, call_id: 'new', arguments: '{"count":2.0}' }]; + const sse = contentType === 'text/event-stream'; + const wire = sse + ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` + : JSON.stringify({ status: 'completed', output }); + const text = await responseText(adapter.createResponseTransform(1, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const call = (sse ? parsed.response : parsed).output[0]; + assert.equal(call.type, 'function_call'); + assert.equal(call.namespace, 'collaboration'); + assert.equal(call.name, 'followup_task'); + assert.equal(call.call_id, 'new'); + assert.equal(call.arguments, '{"count":2}'); + } +}, items, errors); + +await runItem('collide_selector_kind_and_apply_patch', async () => { + for (const kind of ['function', 'custom']) { + const body = { + tools: [ + { type: 'function', name: 'collaboration__followup_task', parameters: { type: 'object', properties: {} } }, + { type: 'namespace', name: 'collaboration', tools: [{ type: kind, name: 'followup_task', description: 'Continue task' }] }, + ], + tool_choice: { type: 'allowed_tools', tools: [{ type: kind, namespace: 'collaboration', name: 'followup_task' }] }, + }; + const prepared = prepareResponsesCompatibility(body, { namespaceTools: 'functions', customTools: 'functions' }); + const wireName = prepared.body.tools[1].name; + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + output: [ + { type: 'function_call', name: wireName, call_id: 'ns', arguments: '{"input":"task"}' }, + { type: 'function_call', name: 'collaboration__followup_task', call_id: 'bare', arguments: '{}' }, + ], + }))); + assert.equal(restored.output[0].type, kind === 'custom' ? 'custom_tool_call' : 'function_call'); + assert.equal(restored.output[0].name, 'followup_task'); + assert.equal(restored.output[0].namespace, 'collaboration'); + if (kind === 'custom') assert.equal(restored.output[0].input, 'task'); + assert.deepEqual(restored.output[1], { type: 'function_call', name: 'collaboration__followup_task', call_id: 'bare', arguments: '{}' }); + + const denied = prepareResponsesCompatibility( + { ...body, tool_choice: { type: kind === 'custom' ? 'function' : 'custom', namespace: 'collaboration', name: 'followup_task' } }, + { namespaceTools: 'functions', customTools: 'functions' }, + ); + const deniedOut = JSON.parse(denied.restoreJson(JSON.stringify({ output: [{ type: 'function_call', name: wireName, arguments: '{}' }] }))); + assert.equal('namespace' in deniedOut.output[0], false); + } + + // apply_patch policy preserved by original logical name even after disambiguation + const tools = [ + { type: 'function', name: 'editor__apply_patch' }, + { type: 'namespace', name: 'editor', tools: [{ type: 'custom', name: 'apply_patch' }] }, + ]; + for (const customTools of ['preserve-apply-patch', 'functions']) { + const prepared = prepareResponsesCompatibility({ tools }, { namespaceTools: 'functions', customTools }); + assert.equal(prepared.body.tools[1].type, customTools === 'functions' ? 'function' : 'custom'); + assert.notEqual(prepared.body.tools[1].name, 'editor__apply_patch'); + } + + // Direct call with default disambiguate=false still throws NamespaceToolCollisionError + assert.throws(() => rewriteRoutedNamespaceToolsForUpstream({ tools }), NamespaceToolCollisionError); +}, items, errors); + +await runItem('collide_reservations_and_order', async () => { + // 1. Reserve later additional_tools names and keep duplicate declarations & bare selector stable + { + const bare = { type: 'function', name: 'collaboration__followup_task' }; + const group = { type: 'namespace', name: 'collaboration', tools: [{ type: 'function', name: 'followup_task' }] }; + for (const tools of [[bare, group], [group, bare]]) { + const input = [{ type: 'additional_tools', tools: [{ type: 'function', name: 'collaboration__followup_task_2' }, group] }]; + const prepared = prepareResponsesCompatibility({ tools, input, tool_choice: { type: 'function', name: bare.name } }, { namespaceTools: 'functions' }); + const allNames = [...prepared.body.tools, ...prepared.body.input[0].tools].map((t) => t.name).sort(); + assert.deepEqual(allNames, ['collaboration__followup_task', 'collaboration__followup_task_2', 'collaboration__followup_task_3']); + assert.deepEqual(prepared.body.tool_choice, { type: 'function', name: bare.name }); + const response = { output: [{ type: 'function_call', name: bare.name, arguments: '{}' }] }; + assert.deepEqual(JSON.parse(prepared.restoreJson(JSON.stringify(response))), response); + } + } + + // 2. Reserve namespace child logical names so generated suffix cannot capture a bare child selector + for (const kind of ['function', 'custom']) { + for (const inline of [false, true]) { + for (const allowed of [false, true]) { + const bare = { type: 'function', name: 'a__b' }; + const first = { type: 'namespace', name: 'a', tools: [{ type: kind, name: 'b' }] }; + const second = { type: 'namespace', name: 'a', tools: [{ type: kind, name: 'a__b_2' }] }; + const selector = { type: kind, name: 'a__b_2' }; + const prepared = prepareResponsesCompatibility({ + tools: inline ? [bare, first] : [bare, first, second], + ...(inline ? { input: [{ type: 'additional_tools', tools: [second] }] } : {}), + tool_choice: allowed ? { type: 'allowed_tools', tools: [selector] } : selector, + }, { namespaceTools: 'functions', customTools: 'functions' }); + const selected = { type: 'function', name: 'a__a__b_2' }; + assert.deepEqual(prepared.body.tool_choice, allowed ? { type: 'allowed_tools', tools: [selected] } : selected); + assert.equal(prepared.body.tools[1].name, 'a__b_3'); + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + output: [{ type: 'function_call', name: 'a__a__b_2', arguments: '{"input":"task"}' }], + }))); + assert.equal(restored.output[0].type, kind === 'custom' ? 'custom_tool_call' : 'function_call'); + assert.equal(restored.output[0].namespace, 'a'); + assert.equal(restored.output[0].name, 'a__b_2'); + } + } + } + + // 3. Reserve nested Chat-shaped function declarations across inline catalogs and order + { + const bare = { type: 'function', function: { name: 'a__b' } }; + const reserved = { type: 'function', function: { name: 'a__b_2' } }; + const group = { type: 'namespace', name: 'a', tools: [{ type: 'function', name: 'b' }] }; + for (const tools of [[bare, group], [group, bare]]) { + const prepared = prepareResponsesCompatibility({ + tools, + input: [{ type: 'additional_tools', tools: [reserved] }], + tool_choice: { type: 'allowed_tools', tools: [{ type: 'function', name: 'a__b' }, { type: 'function', namespace: 'a', name: 'b' }] }, + }, { namespaceTools: 'functions' }); + assert.deepEqual(prepared.body.tools.map((t) => t.name ?? t.function?.name).sort(), ['a__b', 'a__b_3']); + assert.deepEqual(prepared.body.input[0].tools, [reserved]); + assert.deepEqual(prepared.body.tool_choice, { + type: 'allowed_tools', + tools: [{ type: 'function', name: 'a__b' }, { type: 'function', name: 'a__b_3' }], + }); + } + } + + // 4. Keep functions-group tools canonical across catalog order (JSON & SSE) + for (const contentType of ['application/json', 'text/event-stream']) { + const bareName = 'collaboration__followup_task'; + const collaboration = { type: 'namespace', name: 'collaboration', tools: [{ type: 'function', name: 'followup_task' }] }; + const functions = { type: 'namespace', name: 'functions', tools: [{ type: 'function', name: bareName }] }; + for (const catalog of [ + { tools: [collaboration, functions], input: [] }, + { tools: [functions, collaboration], input: [] }, + { tools: [collaboration], input: [{ type: 'additional_tools', tools: [functions] }] }, + ]) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + const request = adapter.adaptRequest({ + ...catalog, + input: [...catalog.input, { type: 'function_call', name: bareName, call_id: 'old', arguments: '{}' }], + tool_choice: { + type: 'allowed_tools', + tools: [ + { type: 'function', name: bareName }, + { type: 'function', namespace: 'collaboration', name: 'followup_task' }, + ], + }, + }, 8); + const names = [...request.tools, ...request.input.flatMap((i) => i.tools ?? [])].map((t) => t.name); + assert.ok(names.includes(bareName)); + const namespaceName = names.find((n) => n !== bareName); + assert.equal(namespaceName, `${bareName}_2`); + assert.equal(request.input.at(-1).name, bareName); + assert.deepEqual(request.tool_choice.tools.map((t) => t.name), [bareName, namespaceName]); + + const output = [bareName, namespaceName].map((name) => ({ type: 'function_call', name, arguments: '{}' })); + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(8, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const restored = (sse ? parsed.response : parsed).output; + assert.deepEqual(restored[0], output[0]); + assert.equal(restored[1].name, 'followup_task'); + assert.equal(restored[1].namespace, 'collaboration'); + } + } +}, items, errors); + +await runItem('collide_native_schema_repair', async () => { + const body = { + tools: [ + { type: 'function', name: 'files__read', parameters: { type: 'object', properties: { value: { type: 'number' } } } }, + { type: 'namespace', name: 'files', tools: [{ type: 'function', name: 'read', parameters: { type: 'object', properties: { value: { type: 'string' } } } }] }, + ], + }; + const prepared = prepareResponsesCompatibility(body, { namespaceTools: 'native', repairFunctionArguments: true }); + assert.equal(prepared.body, body); + const result = JSON.parse(prepared.restoreJson(JSON.stringify({ + status: 'completed', + output: [ + { type: 'function_call', name: 'files__read', arguments: '{"value":3}' }, + { type: 'function_call', namespace: 'files', name: 'read', arguments: '{"value":3}' }, + ], + }))); + assert.deepEqual(result.output.map((i) => i.arguments), ['{"value":3}', '{"value":"3"}']); +}, items, errors); + +// Group 2: dotted_custom_alias +await runItem('dotted_custom_restoration', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + for (const bareName of ['mcp__run', 'mcp.run']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + adapter.adaptRequest({ + tools: [ + { type: 'function', name: bareName }, + { type: 'namespace', name: 'mcp', tools: [{ type: 'custom', name: 'run' }] }, + ], + }, 9); + const item = { type: 'function_call', name: 'mcp.run', call_id: 'run', arguments: '{"input":"task"}' }; + const output = [item]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(9, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const restored = (sse ? parsed.response : parsed).output[0]; + if (bareName === 'mcp.run') { + assert.deepEqual(restored, item); + } else { + assert.equal(restored.type, 'custom_tool_call'); + assert.equal(restored.namespace, 'mcp'); + assert.equal(restored.name, 'run'); + assert.equal(restored.call_id, 'run'); + assert.equal(restored.input, 'task'); + assert.equal('arguments' in restored, false); + } + } + } + + // Selector kind mismatch must not authorize dotted or qualified custom aliases + const prepared = prepareResponsesCompatibility({ + tools: [{ type: 'namespace', name: 'mcp', tools: [{ type: 'custom', name: 'run' }] }], + tool_choice: { type: 'function', namespace: 'mcp', name: 'run' }, + }, { namespaceTools: 'functions', customTools: 'functions' }); + const response = { + output: [ + { type: 'function_call', name: 'mcp.run', arguments: '{"input":"task"}' }, + { type: 'function_call', name: 'mcp__run', namespace: 'mcp', arguments: '{"input":"task"}' }, + ], + }; + assert.deepEqual(JSON.parse(prepared.restoreJson(JSON.stringify(response))), response); +}, items, errors); + +await runItem('qualified_custom_alias_restoration', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + for (const name of ['b', 'a__b_2', 'a.b']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + adapter.adaptRequest({ + tools: [ + { type: 'function', name: 'a__b' }, + { type: 'function', name: 'a__a__b_2' }, + { type: 'namespace', name: 'a', tools: [{ type: 'custom', name: 'b' }] }, + ], + }, 8); + const output = [ + { type: 'function_call', name, namespace: 'a', arguments: '{"input":"task"}' }, + { type: 'function_call', name, namespace: 'other', arguments: '{}' }, + { type: 'function_call', name: 'a__a__b_2', arguments: '{}' }, + ]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(8, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const restored = (sse ? parsed.response : parsed).output; + assert.equal(restored[0].type, 'custom_tool_call'); + assert.equal(restored[0].namespace, 'a'); + assert.equal(restored[0].name, 'b'); + assert.equal(restored[0].input, 'task'); + assert.equal('arguments' in restored[0], false); + assert.deepEqual(restored.slice(1), output.slice(1)); + } + } +}, items, errors); + +await runItem('sse_incremental_custom_aliases', async () => { + for (const spelling of ['wire', 'dotted', 'wire-qualified', 'dotted-qualified', 'original-qualified']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + const request = adapter.adaptRequest({ + tools: [ + { type: 'function', name: 'tasks__continue' }, + { type: 'namespace', name: 'tasks', tools: [{ type: 'custom', name: 'continue' }] }, + ], + }, 7); + const item = { + type: 'function_call', + id: 'fc_task', + call_id: 'task', + name: spelling.startsWith('original') + ? 'continue' + : spelling.startsWith('dotted') + ? 'tasks.continue' + : request.tools[1].name, + ...(spelling.endsWith('qualified') ? { namespace: 'tasks' } : {}), + arguments: '', + }; + const args = '{"input":"continue task"}'; + const events = [ + { type: 'response.output_item.added', output_index: 0, item }, + { type: 'response.function_call_arguments.delta', output_index: 0, item_id: item.id, delta: args }, + { type: 'response.function_call_arguments.done', output_index: 0, item_id: item.id, arguments: args }, + { type: 'response.output_item.done', output_index: 0, item: { ...item, status: 'completed', arguments: args } }, + ]; + const wire = events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join(''); + const text = await responseText(adapter.createResponseTransform(7, { contentType: 'text/event-stream', contentEncoding: '' }), wire); + const restored = text.trim().split('\n\n').map((block) => JSON.parse(block.slice(6))); + const done = restored.find((e) => e.type === 'response.output_item.done'); + assert.ok(done); + assert.equal(done.item.type, 'custom_tool_call'); + assert.equal(done.item.namespace, 'tasks'); + assert.equal(done.item.name, 'continue'); + assert.equal(done.item.call_id, 'task'); + assert.equal(done.item.input, 'continue task'); + assert.equal(restored.some((e) => e.type === 'response.function_call_arguments.delta'), false); + } +}, items, errors); + +await runItem('explicit_coordinate_precedence', async () => { + for (const format of ['json', 'sse']) { + const prepared = prepareResponsesCompatibility({ + tools: [ + { type: 'function', name: 'a__b' }, + { + type: 'namespace', + name: 'a', + tools: [ + { type: 'custom', name: 'b' }, + { type: 'function', name: 'a__b_2' }, + ], + }, + ], + }, { namespaceTools: 'functions', customTools: 'functions' }); + const original = { type: 'function_call', namespace: 'a', name: 'a__b_2', arguments: '{}' }; + const wireName = prepared.body.tools[1].name; + const output = [original, { type: 'function_call', name: wireName, arguments: '{"input":"task"}' }]; + const restored = format === 'json' + ? JSON.parse(prepared.restoreJson(JSON.stringify({ output }))).output + : JSON.parse(prepared.createStreamRewrite()(`data: ${JSON.stringify({ type: 'response.completed', response: { output } })}`)[0].slice(6)).response.output; + assert.deepEqual(restored[0], original); + assert.equal(restored[1].type, 'custom_tool_call'); + assert.equal(restored[1].namespace, 'a'); + assert.equal(restored[1].name, 'b'); + assert.equal(restored[1].input, 'task'); + } +}, items, errors); + +// Group 3: logical_name_guard +await runItem('logical_apply_patch_conflict_guard', async () => { + const parameters = { type: 'object', properties: {} }; + for (const contentType of ['application/json', 'text/event-stream']) { + for (const conflict of [false, true]) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + adapter.adaptRequest({ + input: [{ + type: 'additional_tools', + tools: [ + { type: 'custom', name: 'exec' }, + { type: 'function', name: 'foo', parameters }, + ...(conflict ? [ + { type: 'namespace', name: 'mcp', tools: [{ type: 'custom', name: 'apply_patch' }] }, + { type: 'namespace', name: 'foo', tools: [{ type: 'function', name: 'foo', parameters }] }, + ] : []), + ], + }], + }, 12); + const output = [ + { type: 'function_call', name: 'apply_patch', call_id: 'patch', arguments: '{"input":"patch"}' }, + { type: 'function_call', name: 'foo', namespace: 'foo', call_id: 'foo', arguments: '{}' }, + ]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(12, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const restored = (sse ? parsed.response : parsed).output; + if (conflict) { + assert.deepEqual(restored, output); + } else { + assert.equal(restored[0].type, 'custom_tool_call'); + assert.equal(restored[0].name, 'exec'); + assert.deepEqual(restored[1], { type: 'function_call', name: 'foo', call_id: 'foo', arguments: '{}' }); + } + } + } +}, items, errors); + +await runItem('lowered_custom_self_named_conflict', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + for (const conflict of [false, true]) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + adapter.adaptRequest({ + tools: [ + { type: 'namespace', name: 'x', tools: [{ type: 'custom', name: 'y' }] }, + ...(conflict ? [{ type: 'namespace', name: 'x__y', tools: [{ type: 'custom', name: 'x__y' }] }] : []), + ], + }, 13); + const output = [{ type: 'function_call', name: 'x__y', namespace: 'x__y', call_id: 'custom', arguments: '{"input":"task"}' }]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(13, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const call = (sse ? parsed.response : parsed).output[0]; + assert.equal(call.type, 'custom_tool_call'); + assert.equal(call.namespace, conflict ? 'x__y' : 'x'); + assert.equal(call.name, conflict ? 'x__y' : 'y'); + assert.equal(call.call_id, 'custom'); + assert.equal(call.input, 'task'); + } + } +}, items, errors); + +// Group 4: selected_self_named_scrub +await runItem('selected_only_scrub_scope', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + for (const kind of ['custom', 'function']) { + for (const selection of ['bare', 'allowed', 'namespace', 'auto']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + const tool = { type: kind, name: 'x', parameters: { type: 'object', properties: {} } }; + const selector = { type: kind, name: 'x' }; + const tool_choice = selection === 'auto' + ? 'auto' + : selection === 'allowed' + ? { type: 'allowed_tools', tools: [selector] } + : selection === 'namespace' + ? { ...selector, namespace: 'x' } + : selector; + adapter.adaptRequest({ tools: [tool, { type: 'namespace', name: 'x', tools: [tool] }], tool_choice }, 14); + const output = [{ type: 'function_call', name: 'x', namespace: 'x', call_id: 'selected', arguments: kind === 'custom' ? '{"input":"task"}' : '{}' }]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(14, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const call = (sse ? parsed.response : parsed).output[0]; + if (kind === 'custom') { + assert.equal(call.type, 'custom_tool_call'); + assert.equal(call.name, 'x'); + assert.equal(call.input, 'task'); + } else { + assert.equal(call.type, 'function_call'); + assert.equal(call.name, 'x'); + assert.equal(call.arguments, '{}'); + } + if (selection === 'namespace' || selection === 'auto') { + assert.equal(call.namespace, 'x'); + } else { + assert.equal('namespace' in call, false); + } + } + } + } +}, items, errors); + +await runItem('inline_namespace_conservative_guard', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + adapter.adaptRequest({ + tools: [ + { type: 'custom', name: 'x' }, + { type: 'custom', name: 'x', namespace: 'x' }, + ], + }, 15); + const output = [{ type: 'function_call', name: 'x', namespace: 'x', call_id: 'inline', arguments: '{"input":"task"}' }]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(15, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + assert.equal((sse ? parsed.response : parsed).output[0].namespace, 'x'); + } +}, items, errors); + +// Group 5: baseline_regression_guard +await runItem('baseline_non_colliding_namespace', async () => { + for (const contentType of ['application/json', 'text/event-stream']) { + const adapter = createResponsesCompatibilityAdapter(DEFAULT_POLICY); + const adapted = adapter.adaptRequest({ + tools: [ + { type: 'namespace', name: 'functions', tools: [{ type: 'function', name: 'search', defer_loading: true }] }, + { type: 'namespace', name: 'docs', tools: [{ type: 'function', name: 'lookup', defer_loading: true }, { type: 'custom', name: 'edit' }] }, + ], + }, 20); + assert.deepEqual(adapted.tools.map((t) => t.name), ['search', 'docs__lookup', 'docs__edit']); + assert.ok(adapted.tools.every((t) => !('defer_loading' in t))); + assert.equal(adapted.tools[2].type, 'function'); + + const output = [ + { type: 'function_call', name: 'search', call_id: 's1', arguments: '{}' }, + { type: 'function_call', name: 'docs__lookup', call_id: 's2', arguments: '{}' }, + { type: 'function_call', id: 'fc_3', name: 'docs__edit', call_id: 's3', arguments: '{"input":"hello"}' }, + ]; + const sse = contentType === 'text/event-stream'; + const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: { output } })}\n\n` : JSON.stringify({ output }); + const text = await responseText(adapter.createResponseTransform(20, { contentType, contentEncoding: '' }), wire); + const parsed = JSON.parse(sse ? text.trim().slice(6) : text); + const restored = (sse ? parsed.response : parsed).output; + assert.deepEqual(restored[0], output[0]); + assert.deepEqual(restored[1], { type: 'function_call', namespace: 'docs', name: 'lookup', call_id: 's2', arguments: '{}' }); + assert.deepEqual(restored[2], { type: 'custom_tool_call', id: 'ctc_3', namespace: 'docs', name: 'edit', call_id: 's3', input: 'hello' }); + } +}, items, errors); + +await runItem('baseline_function_arg_repair', async () => { + const prepared = prepareResponsesCompatibility({ + tools: [{ + type: 'function', + name: 'query', + parameters: { + type: 'object', + properties: { + limit: { type: 'integer' }, + cursor: { type: 'string' }, + weight: { type: 'integer' }, + }, + }, + }], + }, { repairFunctionArguments: true }); + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + status: 'completed', + output: [{ type: 'function_call', name: 'query', arguments: '{"limit":25.0,"cursor":7,"weight":1.5}' }], + }))); + assert.equal(restored.output[0].arguments, '{"limit":25,"cursor":"7","weight":1.5}'); +}, items, errors); + +trusted.emit(({ + status: 'graded', + items, + details: { errors }, +})); diff --git a/questions/codex-namespace-tool-collision/v1/author/grade.py b/questions/codex-namespace-tool-collision/v1/author/grade.py new file mode 100644 index 0000000..4f6d478 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=180 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/codex-namespace-tool-collision/v1/author/grade_impl.py b/questions/codex-namespace-tool-collision/v1/author/grade_impl.py new file mode 100644 index 0000000..c24cdf3 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/author/grade_impl.py @@ -0,0 +1,39 @@ +"""Isolated pure-Node capability grader for codex-namespace-tool-collision.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-codex-ns-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=120 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/codex-namespace-tool-collision/v1/author/result-channel.mjs b/questions/codex-namespace-tool-collision/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/CONTRACT.md b/questions/codex-namespace-tool-collision/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..85b9d28 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/CONTRACT.md @@ -0,0 +1,37 @@ +# Product & Protocol Contract + +## 1. Public Entrypoints (`src/responses.mjs`) + +- `prepareResponsesCompatibility(body, policy)`: + - `policy`: `{ namespaceTools?: 'native' | 'functions', customTools?: 'native' | 'functions' | 'preserve-apply-patch', repairFunctionArguments?: boolean }`. + - Returns `{ body, needsResponseTransform, restoreJson(text), createStreamRewrite() }`. +- `createResponsesCompatibilityAdapter(policy)`: + - Returns `{ adaptRequest(body, requestId, overrides?), releaseResponse(requestId), createResponseTransform(requestId, { contentType, contentEncoding }) }` supporting `application/json` and `text/event-stream`. + +## 2. Namespace Lowering & Collision Disambiguation (`namespaceTools: 'functions'`) + +- Top-level declarations (both flat `{ type, name }` and Chat-shaped nested `{ type: 'function', function: { name } }`) and children of the reserved `functions` namespace own their literal bare wire names regardless of declaration order across `tools` and `input[].additional_tools`. Duplicate declarations of the same logical tool deduplicate cleanly. +- Non-`functions` namespace children `(ns, name)` default to wire name `__`. When a wire name collides with a distinct logical tool, `prepareResponsesCompatibility` disambiguates deterministically (`_2`, `_3`, … capped at 64 chars: `prefix.slice(0, 64 - tail.length) + tail`) without hijacking any declared bare name, namespace child's logical name, or default flattened name across `tools` and `additional_tools`. +- Direct calls to `rewriteRoutedNamespaceToolsForUpstream(body)` default to `disambiguate = false` (throwing `NamespaceToolCollisionError` on collisions); passing `disambiguate = true` enables disambiguation. +- `tool_choice` (direct `{ type, name, namespace? }` and `allowed_tools`) and replayed `input` tool calls rewrite consistently to allocated wire names and drop private `namespace` fields. Authorization strictly matches original declared kinds (`function` vs `custom`). +- Under `customTools: 'preserve-apply-patch'`, any custom tool whose original logical name is `apply_patch` (even if namespaced and disambiguated) remains `type: 'custom'`; under `customTools: 'functions'`, all custom tools convert to `type: 'function'`. +- Canonical-only fields (`defer_loading`) are stripped from `tools` and `input[].additional_tools` when lowering. + +## 3. Round-Trip Restoration (JSON & Incremental SSE Parity) + +- Converted custom tools restore from `function_call` to `custom_tool_call` (`fc_` → `ctc_`, `{ "input": "..." }` unwrapped; incremental SSE emits `custom_tool_call` + `custom_tool_call_input` without leaking raw `function_call_arguments` deltas) across: + - the allocated wire name, + - unambiguous authorized dotted aliases (`.` when neither segment contains `__`, non-ambiguous across the catalog, and not declared as a bare tool), and + - provider echoes retaining matching `namespace` alongside original name, allocated wire name, or dotted alias. +- Calls with a non-matching `namespace` or unrelated bare names (e.g. `a__a__b_2`) remain untouched. +- If a call carries an explicit `(namespace, name)` matching an authorized declared namespace tool, that explicit declared identity takes precedence over another tool's alias spelling. + +## 4. Conflict Guards & Native-Namespace Repair + +- **Code Mode helper guard**: Helper rerouting toward bare custom `exec` must respect declared logical names (both unlowered and lowered, across `tools` and `additional_tools`) so declaring a namespaced `apply_patch` protects bare `apply_patch` from being rerouted to `exec`. +- **Self-named namespace scrubbing**: Strips redundant `namespace: x` from `{ name: x, namespace: x }` when bare `x` is authorized and no active same-name namespace conflict `(x, x)` exists. + - Must account for both original and lowered catalogs, including same-name namespaced `custom` tools that arrive upstream as `function_call`. + - Under `namespaceTools: 'functions'`, a same-name `type: 'namespace'` group declaration blocks scrubbing ONLY if authorized/selected by the turn's `tool_choice`; inline `spec.namespace` declarations retain the conservative guard. +- **Native-namespace argument repair (`namespaceTools: 'native'`, `repairFunctionArguments: true`)**: + - Request declarations pass through unchanged. + - Argument repair applies each tool's own schema keyed by exact `(namespace, name)` identity so bare `ns__name` and namespaced `(ns, name)` never cross-contaminate. Integral floats coerce to integers for `integer` fields; safe integers coerce to strings for `string`-only fields; non-integral floats stay untouched. diff --git a/questions/codex-namespace-tool-collision/v1/candidate/ENVIRONMENT.md b/questions/codex-namespace-tool-collision/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..531abf3 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering non-colliding tool lowering, restoration, and argument repair diff --git a/questions/codex-namespace-tool-collision/v1/candidate/TASK.md b/questions/codex-namespace-tool-collision/v1/candidate/TASK.md new file mode 100644 index 0000000..7b45802 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/TASK.md @@ -0,0 +1,15 @@ +# Task + +Production Codex sessions are hitting Responses API tool compatibility failures whenever bare tools, `functions` tools, MCP/namespaced tools, and `custom` tools interact or share wire spellings—across both JSON responses and incremental SSE streams. + +Reported issues include: +- Requests failing when bare and namespaced tools flatten to the same wire name. +- Converted namespaced `custom` tools failing to round-trip back to `custom_tool_call` across valid provider echo spellings, or colliding with other declared tools. +- Self-named namespace echo repair, Code Mode helper routing, and native-namespace argument repair misbehaving around colliding, converted, or unselected tools. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable protocol compatibility defects while preserving behavior for ordinary non-colliding requests. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/codex-namespace-tool-collision/v1/candidate/package.json b/questions/codex-namespace-tool-collision/v1/candidate/package.json new file mode 100644 index 0000000..4fe1fc6 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-codex-namespace-tool-collision", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/apply-patch-envelope.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/apply-patch-envelope.mjs new file mode 100644 index 0000000..74a315a --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/apply-patch-envelope.mjs @@ -0,0 +1,45 @@ +const PATCH_BEGIN = '*** Begin Patch'; +const PATCH_END = '*** End Patch'; +const TOP_LEVEL_PATCH_ENVELOPE = /^(\*\*\* Begin Patch(?: \*\*\*)?)(\r?\n)([\s\S]*)(\r?\n)(\*\*\* End Patch(?: \*\*\*)?)(\r?\n)?$/; +const PATCH_OPERATION_LINE = /^\*\*\* (?:Add|Update|Delete) File: .+$/m; + +export function unwrapFreeformToolInput(argumentsText) { + if (typeof argumentsText !== 'string') return ''; + try { + const parsed = JSON.parse(argumentsText); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + } + } catch { + // The string is the freeform body, not nested JSON. + } + return argumentsText; +} + +export function normalizeApplyPatchDelimiters(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return text; + const [, begin, beginBreak, body, endBreak, end, trailingBreak = ''] = match; + if (!PATCH_OPERATION_LINE.test(body)) return text; + if (begin === PATCH_BEGIN && end === PATCH_END) return text; + return `${PATCH_BEGIN}${beginBreak}${body}${endBreak}${PATCH_END}${trailingBreak}`; +} + +export function isCompletePatchEnvelope(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return false; + return PATCH_OPERATION_LINE.test(match[3] ?? ''); +} + +export function mayBecomePatchEnvelope(text) { + if (text === '') return false; + return text.startsWith(PATCH_BEGIN) || PATCH_BEGIN.startsWith(text); +} + +export function repairFreeformToolInput(argumentsText, toolName = '', namespace) { + const unwrapped = unwrapFreeformToolInput(argumentsText); + const ownsApplyPatchGrammar = namespace === undefined || namespace === 'functions'; + return ownsApplyPatchGrammar && toolName === 'apply_patch' + ? normalizeApplyPatchDelimiters(unwrapped) + : unwrapped; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/code-mode-helper-compat.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/code-mode-helper-compat.mjs new file mode 100644 index 0000000..0597745 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/code-mode-helper-compat.mjs @@ -0,0 +1,65 @@ +import { + isCompletePatchEnvelope, + normalizeApplyPatchDelimiters, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function unwrapPatchInput(value) { + try { + const parsed = JSON.parse(value); + if (isPlainObject(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + if (typeof parsed.patch === 'string') return parsed.patch; + } + } catch { + // Native custom calls carry the patch body directly. + } + return value; +} + +export function compileCodeModeHelperInput(argumentsText, toolName) { + if (typeof argumentsText !== 'string') return ''; + if (toolName === 'apply_patch') { + const patch = normalizeApplyPatchDelimiters(unwrapPatchInput(argumentsText)); + return `const result = await tools.apply_patch(${JSON.stringify(patch)});\ntext(result);`; + } + let parsed = argumentsText; + try { + parsed = JSON.parse(argumentsText); + } catch { + // Keep malformed provider text as data rather than executable source. + } + const args = isPlainObject(parsed) ? { ...parsed } : parsed; + if ( + toolName === 'shell_command' + && isPlainObject(args) + && typeof args.command === 'string' + && args.cmd === undefined + ) { + args.cmd = args.command; + delete args.command; + } + if (toolName === 'write_stdin') { + return `const result = await tools.write_stdin(${JSON.stringify(args)});\ntext(result);`; + } + return `const result = await tools.exec_command(${JSON.stringify(args)});\ntext(result);`; +} + +export function resolveCodeModeHelperName( + codeModeHelperName, + toolName, + argumentsText, + namespace, + declaredNames, +) { + if (codeModeHelperName) return codeModeHelperName; + if (toolName !== 'exec' || namespace !== undefined) return undefined; + if (!declaresCodeModeExec(declaredNames)) return undefined; + if (typeof argumentsText !== 'string' || argumentsText === '') return undefined; + return isCompletePatchEnvelope(unwrapFreeformToolInput(argumentsText)) ? 'apply_patch' : undefined; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/custom-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/custom-tool-compat.mjs new file mode 100644 index 0000000..acca89c --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/custom-tool-compat.mjs @@ -0,0 +1,345 @@ +import { namespacedToolName, normalizeDeclaredToolName } from './tools.mjs'; +import { + normalizeApplyPatchDelimiters, + repairFreeformToolInput, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +const ROUTED_CUSTOM_TOOL_PASSTHROUGH = new Set(['apply_patch']); +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function routedCustomToolPassesThrough(name, supportsResponsesCustomTools) { + return supportsResponsesCustomTools !== false && ROUTED_CUSTOM_TOOL_PASSTHROUGH.has(name); +} + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function customToolWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function toolChoiceAllowsRoutedCustomTool(body, wireName, candidateNames) { + if (!isPlainObject(body)) return true; + const choice = body.tool_choice; + if (choice === undefined || choice === null || choice === 'auto' || choice === 'required') { + return true; + } + if (choice === 'none') return false; + if (!isPlainObject(choice)) return true; + + const selectorAllows = (selector) => { + if (!isPlainObject(selector) || typeof selector.name !== 'string') return false; + if (selector.type !== 'custom') return false; + if (typeof selector.namespace === 'string') { + return customToolWireName(selector.namespace, selector.name) === wireName; + } + if (selector.name === wireName) return true; + const suffix = `__${selector.name}`; + const candidates = [...candidateNames].filter(name => name.endsWith(suffix)); + return candidates.length === 1 && candidates[0] === wireName; + }; + + if (choice.type === 'function' || choice.type === 'custom') return selectorAllows(choice); + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + return choice.tools.some(selectorAllows); + } + return false; +} + +export function routedCustomToolWireName(value) { + if (!isPlainObject(value) || typeof value.name !== 'string') return undefined; + return customToolWireName( + typeof value.namespace === 'string' ? value.namespace : undefined, + value.name, + ); +} + +export function routedCustomToolTargetName(value, names, declaredNames) { + const wireName = routedCustomToolWireName(value); + if (wireName === undefined) return undefined; + if (names.has(wireName)) return wireName; + if (!isPlainObject(value) || typeof value.namespace === 'string') return undefined; + const normalized = normalizeDeclaredToolName(wireName, declaredNames); + return normalized !== wireName && names.has(normalized) ? normalized : undefined; +} + +function collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, passthrough = false) { + const names = new Set(); + const groups = collectResponsesToolGroups(body); + const bareWireNames = new Set(); + for (const group of groups) { + for (const tool of group) { + if ( + isPlainObject(tool) + && tool.type !== 'namespace' + && typeof tool.name === 'string' + ) bareWireNames.add(tool.name); + } + } + + for (const group of groups) { + for (const tool of group) { + if (!isPlainObject(tool)) continue; + if ( + tool.type === 'custom' + && typeof tool.name === 'string' + && routedCustomToolPassesThrough(tool.name, supportsResponsesCustomTools) === passthrough + ) { + names.add(tool.name); + continue; + } + if (tool.type !== 'namespace' || typeof tool.name !== 'string' || !Array.isArray(tool.tools)) { + continue; + } + for (const child of tool.tools) { + if ( + isPlainObject(child) + && child.type === 'custom' + && typeof child.name === 'string' + && routedCustomToolPassesThrough(child.name, supportsResponsesCustomTools) === passthrough + && (!passthrough || tool.name === BUILTIN_FUNCTIONS_NAMESPACE) + && !(tool.name === BUILTIN_FUNCTIONS_NAMESPACE && bareWireNames.has(child.name)) + ) names.add(customToolWireName(tool.name, child.name)); + } + } + } + return names; +} + +export function customToolItemId(id) { + if (typeof id !== 'string') return id; + return id.startsWith('fc_') ? `ctc_${id.slice(3)}` : id; +} + +export function collectRoutedCustomToolNames(body, supportsResponsesCustomTools) { + const names = new Set(); + const visit = (value) => { + if (Array.isArray(value)) { + for (const entry of value) visit(entry); + return; + } + if (!isPlainObject(value)) return; + if ( + value.type === 'custom' + && typeof value.name === 'string' + && !routedCustomToolPassesThrough(value.name, supportsResponsesCustomTools) + ) { + names.add(value.name); + } + for (const key of ['tools', 'input', 'tool_choice']) visit(value[key]); + }; + visit(body); + return names; +} + +function collectConvertedCallIds(value, names, out) { + if (Array.isArray(value)) { + for (const entry of value) collectConvertedCallIds(entry, names, out); + return; + } + if (!isPlainObject(value)) return; + if ( + (value.type === 'custom_tool_call' || value.type === 'function_call') + && typeof value.name === 'string' + && names.has(value.name) + && typeof value.call_id === 'string' + ) { + out.add(value.call_id); + } + if (Array.isArray(value.input)) collectConvertedCallIds(value.input, names, out); +} + +function rewriteForUpstream(value, names, callIds) { + if (Array.isArray(value)) return value.map(entry => rewriteForUpstream(entry, names, callIds)); + if (!isPlainObject(value)) return value; + + if (value.type === 'custom' && typeof value.name === 'string' && names.has(value.name)) { + const { format: _format, ...rest } = value; + const isDefinition = typeof value.description === 'string' + || isPlainObject(value.format) + || isPlainObject(value.parameters); + if (!isDefinition) return { ...rest, type: 'function' }; + const inputDescription = value.name === 'exec' + ? 'JavaScript source for unified exec. Use await tools.exec_command(...) for shell commands and text(...) to return textual output; do not provide a bare shell command.' + : 'Raw input for this client-executed custom tool.'; + return { + ...rest, + type: 'function', + parameters: { + type: 'object', + properties: { + input: { + type: 'string', + description: inputDescription, + }, + }, + required: ['input'], + additionalProperties: false, + }, + }; + } + + if ( + value.type === 'custom_tool_call' + && typeof value.name === 'string' + && names.has(value.name) + ) { + const { input, id: _id, ...rest } = value; + return { + ...rest, + type: 'function_call', + arguments: JSON.stringify({ input: typeof input === 'string' ? input : '' }), + }; + } + + if ( + value.type === 'custom_tool_call_output' + && typeof value.call_id === 'string' + && callIds.has(value.call_id) + ) { + return { ...value, type: 'function_call_output' }; + } + + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(value)) { + const rewritten = ['tools', 'input', 'tool_choice'].includes(key) + ? rewriteForUpstream(entry, names, callIds) : entry; + next[key] = rewritten; + changed ||= rewritten !== entry; + } + return changed ? next : value; +} + +export function rewriteRoutedCustomToolsForUpstream(body, supportsResponsesCustomTools) { + const conversionNames = collectRoutedCustomToolNames(body, supportsResponsesCustomTools); + const names = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools); + const repairNames = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, true); + for (const name of repairNames) { + if (!toolChoiceAllowsRoutedCustomTool(body, name, repairNames)) repairNames.delete(name); + } + if (conversionNames.size === 0) return { body, names, repairNames }; + const callIds = new Set(); + collectConvertedCallIds(body, conversionNames, callIds); + return { body: rewriteForUpstream(body, conversionNames, callIds), names, repairNames }; +} + +export function restoreRoutedCustomCalls(value, names, repairNames = new Set(), declaredNames) { + if (!isPlainObject(value)) return { value, changed: false }; + + const restoreItem = (item) => { + if (!isPlainObject(item)) return { value: item, changed: false }; + const wireName = routedCustomToolWireName(item); + const targetName = routedCustomToolTargetName(item, names, declaredNames); + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + && wireName !== undefined + && targetName !== undefined + ) { + const sourceInput = item.type === 'function_call' ? item.arguments : item.input; + const aliased = targetName !== wireName; + const itemNamespace = typeof item.namespace === 'string' ? item.namespace : undefined; + const helper = aliased && sourceInput !== '' + ? item.name + : resolveCodeModeHelperName(undefined, targetName, sourceInput, itemNamespace, declaredNames); + if (item.type === 'custom_tool_call' && !aliased && !helper) { + const input = repairNames.has(wireName) && typeof sourceInput === 'string' + ? normalizeApplyPatchDelimiters(sourceInput) + : sourceInput; + return input !== sourceInput + ? { value: { ...item, input }, changed: true } + : { value: item, changed: false }; + } + const restored = { + ...item, + type: 'custom_tool_call', + id: customToolItemId(item.id), + name: aliased ? targetName : item.name, + input: helper + ? compileCodeModeHelperInput(sourceInput, helper) + : repairFreeformToolInput(sourceInput, targetName, itemNamespace), + }; + delete restored.arguments; + if (aliased) delete restored.namespace; + return { value: restored, changed: true }; + } + if ( + item.type === 'custom_tool_call' + && typeof item.name === 'string' + && wireName !== undefined + && repairNames.has(wireName) + && typeof item.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(item.input); + if (input !== item.input) return { value: { ...item, input }, changed: true }; + } + return { value: item, changed: false }; + }; + + const restoreOutput = (output) => { + if (!Array.isArray(output)) return { value: output, changed: false }; + let changed = false; + const restored = output.map(item => { + const result = restoreItem(item); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value: output, changed: false }; + }; + + let changed = false; + const restored = { ...value }; + const output = restoreOutput(value.output); + if (output.changed) { + restored.output = output.value; + changed = true; + } + + if ( + (value.type === 'response.output_item.added' || value.type === 'response.output_item.done') + && isPlainObject(value.item) + ) { + const item = restoreItem(value.item); + if (item.changed) { + restored.item = item.value; + changed = true; + } + } + + if ( + typeof value.type === 'string' + && value.type.startsWith('response.') + && isPlainObject(value.response) + ) { + const response = restoreRoutedCustomCalls(value.response, names, repairNames, declaredNames); + if (response.changed) { + restored.response = response.value; + changed = true; + } + } + + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedCustomCallsInJson(text, names, repairNames = new Set(), declaredNames) { + if (names.size === 0 && repairNames.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedCustomCalls(payload, names, repairNames, declaredNames); + return restored.changed ? JSON.stringify(restored.value) : text; +} + +export function unwrapRoutedCustomToolArguments(argumentsText, toolName = '', namespace) { + return toolName + ? repairFreeformToolInput(argumentsText, toolName, namespace) + : unwrapFreeformToolInput(argumentsText); +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/function-call-compat.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/function-call-compat.mjs new file mode 100644 index 0000000..7f75fe0 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/function-call-compat.mjs @@ -0,0 +1,147 @@ +import { coerceIntegerToolArguments } from './tool-argument-integers.mjs'; +import { namespacedToolName } from './tools.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream } from './namespace-tool-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function sameSchemaValue(left, right) { + if (left === right) return true; + if (Array.isArray(left) || Array.isArray(right)) { + return Array.isArray(left) && Array.isArray(right) && left.length === right.length + && left.every((value, index) => sameSchemaValue(value, right[index])); + } + if (!isObject(left) || !isObject(right)) return false; + const keys = Object.keys(left); + return keys.length === Object.keys(right).length + && keys.every(key => Object.hasOwn(right, key) && sameSchemaValue(left[key], right[key])); +} + +function namespaceOf(value) { + return typeof value === 'string' && value !== 'functions' ? value : undefined; +} + +function selectorAllows(selector, lowered, wireName, identity) { + if (!isObject(selector) || selector.type !== 'function' || typeof selector.name !== 'string') return false; + if ('namespace' in selector) { + if (typeof selector.namespace !== 'string' || selector.namespace.length === 0) return false; + return namespaceOf(selector.namespace) === identity.namespace && selector.name === identity.name; + } + return isObject(lowered) && lowered.type === 'function' && lowered.name === wireName; +} + +export function collectFunctionCallRepairSchemas(body) { + const schemas = new Map(); + if (!isObject(body)) return schemas; + const groups = collectResponsesToolGroups(body); + if (Array.isArray(body.input)) { + for (const entry of body.input) { + if (isObject(entry) && entry.type === 'tool_search_output' && Array.isArray(entry.tools)) groups.push(entry.tools); + } + } + const lowered = rewriteRoutedNamespaceToolsForUpstream({ ...body, tools: groups.flat(), input: [] }).body; + const choice = body.tool_choice; + const loweredChoice = isObject(lowered) ? lowered.tool_choice : undefined; + const occupied = new Map(); + const register = (tool, namespace) => { + if (!isObject(tool) || typeof tool.name !== 'string' || tool.name.length === 0) return; + const identity = { + name: tool.name, + ...(namespace ? { namespace } : {}), + ...(isObject(tool.parameters) ? { parameters: tool.parameters } : {}), + }; + const key = namespacedToolName(namespace, tool.name); + if (occupied.has(key)) { + const previous = occupied.get(key); + if (!previous || previous.kind !== tool.type + || previous.identity.namespace !== namespace + || previous.identity.name !== tool.name + || !sameSchemaValue(previous.identity.parameters, identity.parameters)) { + occupied.set(key, null); + } + } else occupied.set(key, { kind: tool.type, identity }); + }; + for (const group of groups) { + for (const tool of group) { + if (!isObject(tool)) continue; + if (tool.type === 'namespace') { + if (typeof tool.name !== 'string' || !tool.name || !Array.isArray(tool.tools)) continue; + for (const child of tool.tools) register(child, namespaceOf(tool.name)); + } else if (tool.type === 'function' && isObject(tool.function)) { + register({ ...tool.function, type: 'function' }); + } else register(tool); + } + } + for (const [key, entry] of occupied) { + if (!entry || entry.kind !== 'function') continue; + let allowed = choice === undefined || choice === 'auto' || choice === 'required'; + if (isObject(choice)) { + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + const selectors = isObject(loweredChoice) && Array.isArray(loweredChoice.tools) ? loweredChoice.tools : []; + allowed = choice.tools.some((selector, index) => selectorAllows(selector, selectors[index], key, entry.identity)); + } else allowed = selectorAllows(choice, loweredChoice, key, entry.identity); + } + if (allowed) schemas.set(key, entry.identity); + } + return schemas; +} + +function repairItem(item, schemas, completed) { + if (!isObject(item) || item.type !== 'function_call' || typeof item.name !== 'string' + || typeof item.arguments !== 'string') return item; + if (item.status !== 'completed' && !(item.status === undefined && completed)) return item; + if ('namespace' in item && (typeof item.namespace !== 'string' || !item.namespace)) return item; + const namespace = namespaceOf(item.namespace); + const schema = schemas.get(namespacedToolName(namespace, item.name)); + if (!schema) return item; + if ('namespace' in item && (schema.namespace !== namespace || schema.name !== item.name)) return item; + const raw = item.arguments; + if (raw !== '') { + try { + let unsafe = false; + JSON.parse(raw, (_key, value) => { + if (typeof value === 'number' && (!Number.isFinite(value) + || (Number.isInteger(value) && !Number.isSafeInteger(value)))) unsafe = true; + return value; + }); + if (unsafe) return item; + } catch { return item; } + } + const argumentsText = coerceIntegerToolArguments(raw || '{}', schema.parameters, schema.namespace ? undefined : schema.name); + return argumentsText === raw ? item : { ...item, arguments: argumentsText }; +} + +export function repairFunctionCalls(value, schemas) { + if (schemas.size === 0 || !isObject(value)) return { value, changed: false }; + if (typeof value.status === 'string' && ['failed', 'incomplete', 'cancelled', 'in_progress', 'queued'].includes(value.status)) return { value, changed: false }; + let next = value; + if (value.type === 'function_call') next = repairItem(value, schemas, false); + else if (value.type === 'response.output_item.done') { + const item = repairItem(value.item, schemas, true); + if (item !== value.item) next = { ...value, item }; + } else if (value.type === 'response.completed' && isObject(value.response)) { + const response = value.response; + if ((response.status === undefined || response.status === 'completed') && Array.isArray(response.output)) { + const original = response.output; + const output = original.map(item => repairItem(item, schemas, true)); + if (output.some((item, index) => item !== original[index])) next = { ...value, response: { ...response, output } }; + } + } else if (typeof value.type !== 'string' || !value.type.startsWith('response.')) { + if (Array.isArray(value.output)) { + const original = value.output; + const output = original.map(item => repairItem(item, schemas, value.status === 'completed')); + if (output.some((item, index) => item !== original[index])) next = { ...value, output }; + } + } + return { value: next, changed: next !== value }; +} + +export function repairFunctionCallsInJson(text, schemas) { + if (schemas.size === 0) return text; + let payload; + try { payload = JSON.parse(text); } catch { return text; } + const repaired = repairFunctionCalls(payload, schemas); + return repaired.changed ? JSON.stringify(repaired.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/namespace-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/namespace-tool-compat.mjs new file mode 100644 index 0000000..26c96e2 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/namespace-tool-compat.mjs @@ -0,0 +1,302 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous } from './tool-name-aliases.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function namespaceIdentity(namespace, name) { + return `${namespace}\u0000${name}`; +} + +function isRepresentableName(name) { + if (typeof name !== 'string' || name.length === 0) return false; + for (let index = 0; index < name.length; index += 1) { + const code = name.charCodeAt(index); + if (code <= 0x1f || code === 0x7f) return false; + } + return true; +} + +function parseNamespaceGroup(tool) { + if ( + !isPlainObject(tool) + || tool.type !== 'namespace' + || !isRepresentableName(tool.name) + || !Array.isArray(tool.tools) + ) return undefined; + const children = []; + for (const child of tool.tools) { + if (!isPlainObject(child) || child.type === 'namespace' || !isRepresentableName(child.name)) continue; + children.push(child); + } + return { namespace: tool.name, children }; +} + +function loweredIdentity(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE + ? namespaceIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name) + : namespaceIdentity(namespace, name); +} + +function loweredWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function addSelector(selectors, selector, wireName) { + const current = selectors.get(selector); + if (current === undefined) selectors.set(selector, wireName); + else if (current !== wireName) selectors.set(selector, null); +} + +/** Two distinct logical tools would occupy one wire name; the caller maps this to a 400. */ +export class NamespaceToolCollisionError extends Error {} + +function buildRewritePlan(groups) { + const aliases = new Map(); + const bareWireNames = new Set(); + const identities = new Map(); + const selectors = new Map(); + const wireOwners = new Map(); + + for (const group of groups) { + for (const tool of group) { + if (isPlainObject(tool) && tool.type !== 'namespace' && isRepresentableName(tool.name)) { + wireOwners.set(tool.name, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, tool.name)); + bareWireNames.add(tool.name); + addSelector(selectors, tool.name, tool.name); + } + } + } + + for (const group of groups) { + for (const tool of group) { + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const childName = child.name; + const identity = loweredIdentity(parsed.namespace, childName); + const wireName = loweredWireName(parsed.namespace, childName); + const owner = wireOwners.get(wireName); + if (owner !== undefined && owner !== identity) { + throw new NamespaceToolCollisionError( + `namespace tool wire-name collision for "${wireName}"; rename one of the colliding tools`, + ); + } + wireOwners.set(wireName, identity); + identities.set(identity, wireName); + addSelector(selectors, wireName, wireName); + addSelector(selectors, `${parsed.namespace}.${childName}`, wireName); + addSelector(selectors, childName, wireName); + if (parsed.namespace !== BUILTIN_FUNCTIONS_NAMESPACE) { + const kind = child.type === 'custom' ? 'custom' : 'function'; + aliases.set(wireName, { namespace: parsed.namespace, name: childName, kind }); + } + } + } + } + + return { aliases, bareWireNames, identities, selectors }; +} + +function rewriteToolList(tools, plan, emitted) { + let changed = false; + const rewritten = []; + for (const tool of tools) { + if (isPlainObject(tool) && tool.type === 'namespace') { + changed = true; + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const wireName = plan.identities.get(loweredIdentity(parsed.namespace, child.name)); + if ( + wireName === undefined + || (parsed.namespace === BUILTIN_FUNCTIONS_NAMESPACE && plan.bareWireNames.has(wireName)) + || emitted.has(wireName) + ) continue; + emitted.add(wireName); + rewritten.push(wireName === child.name ? child : { ...child, name: wireName }); + } + continue; + } + if (isPlainObject(tool) && isRepresentableName(tool.name)) { + if (emitted.has(tool.name)) { + changed = true; + continue; + } + emitted.add(tool.name); + } + rewritten.push(tool); + } + return changed ? rewritten : tools; +} + +function hasMalformedNamespace(value) { + return 'namespace' in value && typeof value.namespace !== 'string'; +} + +function rewriteNamedSelector(value, plan, bareFallback) { + if (!isPlainObject(value) || typeof value.name !== 'string') return value; + if (hasMalformedNamespace(value)) return value; + const namespace = value.namespace; + if (typeof namespace !== 'string') { + if (!bareFallback) return value; + const wireName = plan.selectors.get(value.name) ?? undefined; + return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName }; + } + const { namespace: _dropped, ...rest } = value; + const wireName = plan.identities.get(loweredIdentity(namespace, value.name)) + ?? loweredWireName(namespace, value.name); + return { ...rest, name: wireName }; +} + +function rewriteToolChoice(value, plan) { + if (!isPlainObject(value)) return value; + if ((value.type === 'function' || value.type === 'custom') && typeof value.name === 'string') { + return rewriteNamedSelector(value, plan, true); + } + if (value.type !== 'allowed_tools' || !Array.isArray(value.tools)) return value; + let changed = false; + const tools = value.tools.map(tool => { + if (!isPlainObject(tool) || typeof tool.name !== 'string') return tool; + const rewritten = rewriteNamedSelector(tool, plan, true); + changed ||= rewritten !== tool; + return rewritten; + }); + return changed ? { ...value, tools } : value; +} + +function authorizedAliases(aliases, toolChoice) { + if (toolChoice === undefined || toolChoice === 'auto' || toolChoice === 'required') return aliases; + if (toolChoice === 'none' || !isPlainObject(toolChoice)) return new Map(); + + let authorized; + if ( + (toolChoice.type === 'function' || toolChoice.type === 'custom') + && typeof toolChoice.name === 'string' + ) { + if (hasMalformedNamespace(toolChoice)) return new Map(); + authorized = new Map([[toolChoice.name, toolChoice.type]]); + } else if (toolChoice.type === 'allowed_tools' && Array.isArray(toolChoice.tools)) { + authorized = new Map(); + for (const tool of toolChoice.tools) { + if (!isPlainObject(tool)) continue; + if (tool.type !== 'function' && tool.type !== 'custom') continue; + if (typeof tool.name !== 'string') continue; + if (hasMalformedNamespace(tool)) continue; + authorized.set(tool.name, tool.type); + } + } else { + return new Map(); + } + + return new Map( + [...aliases].filter(([wireName, identity]) => authorized.get(wireName) === identity.kind), + ); +} + +function rewriteInputItem(item, plan, emitted) { + if (!isPlainObject(item)) return item; + if (item.type === 'additional_tools' && Array.isArray(item.tools)) { + const tools = rewriteToolList(item.tools, plan, emitted); + return tools === item.tools ? item : { ...item, tools }; + } + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + ) return rewriteNamedSelector(item, plan, false); + return item; +} + +export function rewriteRoutedNamespaceToolsForUpstream(body, convertedCustomToolNames) { + if (!isPlainObject(body)) return { body, aliases: new Map() }; + const groups = collectResponsesToolGroups(body); + const plan = buildRewritePlan(groups); + + const emitted = new Set(); + const tools = Array.isArray(body.tools) ? rewriteToolList(body.tools, plan, emitted) : body.tools; + + let input = body.input; + if (Array.isArray(body.input)) { + let inputChanged = false; + const rewrittenInput = body.input.map(item => { + const next = rewriteInputItem(item, plan, emitted); + if (next !== item) inputChanged = true; + return next; + }); + if (inputChanged) input = rewrittenInput; + } + + const toolChoice = rewriteToolChoice(body.tool_choice, plan); + const aliases = authorizedAliases(plan.aliases, toolChoice); + const ambiguousDotted = collectAmbiguousDottedAliases(groups); + for (const identity of [...aliases.values()]) { + const dotted = dottedToolName(identity.namespace, identity.name); + if (dottedAliasIsUnambiguous(identity.namespace, identity.name) + && !ambiguousDotted.has(dotted) && !plan.bareWireNames.has(dotted) + && !aliases.has(dotted)) aliases.set(dotted, identity); + } + for (const identity of aliases.values()) { + if (convertedCustomToolNames?.has(namespacedToolName(identity.namespace, identity.name))) identity.kind = 'custom'; + } + return { + body: { + ...body, + ...(tools !== body.tools ? { tools } : {}), + ...(input !== body.input ? { input } : {}), + ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}), + }, + aliases, + }; +} + +export function restoreRoutedNamespaceCalls(value, aliases) { + if (Array.isArray(value)) { + let changed = false; + const restored = value.map(entry => { + const result = restoreRoutedNamespaceCalls(entry, aliases); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + + let changed = false; + const restored = {}; + for (const [key, entry] of Object.entries(value)) { + const result = restoreRoutedNamespaceCalls(entry, aliases); + restored[key] = result.value; + changed ||= result.changed; + } + + if ( + (value.type === 'function_call' || value.type === 'custom_tool_call') + && typeof value.name === 'string' + ) { + const identity = aliases.get(value.name); + if (identity + && (value.type !== 'custom_tool_call' || identity.kind === 'custom') + && (!Object.hasOwn(value, 'namespace') || value.namespace === identity.namespace)) { + restored.name = identity.name; + restored.namespace = identity.namespace; + changed = true; + } + } + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedNamespaceCallsInJson(text, aliases) { + if (aliases.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedNamespaceCalls(payload, aliases); + return restored.changed ? JSON.stringify(restored.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/responses-custom-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/responses-custom-tool-repair.mjs new file mode 100644 index 0000000..6afa922 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/responses-custom-tool-repair.mjs @@ -0,0 +1,351 @@ +import { mayBecomePatchEnvelope, normalizeApplyPatchDelimiters } from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; +import { + customToolItemId, + restoreRoutedCustomCalls, + routedCustomToolTargetName, + routedCustomToolWireName, + unwrapRoutedCustomToolArguments, +} from './custom-tool-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const FREEFORM_WRAP_PREFIX = '{"input":"'; +const FREEFORM_WRAP_PREFIX_RE = /^\s*\{\s*"input"\s*:\s*"/; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function partialCustomToolInput(argumentsText) { + const match = FREEFORM_WRAP_PREFIX_RE.exec(argumentsText); + if (!match) return null; + const body = argumentsText.slice(match[0].length); + let output = ''; + for (let index = 0; index < body.length; index++) { + const char = body[index]; + if (char === '"') break; + if (char !== '\\') { + output += char; + continue; + } + const escaped = body[index + 1]; + if (escaped === undefined) break; + index += 1; + if (escaped === 'n') output += '\n'; + else if (escaped === 't') output += '\t'; + else if (escaped === 'r') output += '\r'; + else if (escaped === 'b') output += '\b'; + else if (escaped === 'f') output += '\f'; + else if (escaped === 'u') { + const hex = body.slice(index + 1, index + 5); + if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break; + output += String.fromCharCode(Number.parseInt(hex, 16)); + index += 4; + } else output += escaped; + } + return output; +} + +function replaceSseEventName(block, type) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + let replaced = false; + const next = lines.map(line => { + if (!replaced && line.startsWith('event:')) { + replaced = true; + return `event: ${type}`; + } + return line; + }); + return next.join(newline); +} + +export function createRoutedCustomToolRestoreBlockRewrite( + names, + budget, + repairNames = new Set(), + declaredNames, +) { + const itemNames = new Map(); + const customExecItemNames = new Map(); + const repairItemNames = new Map(); + const ordinaryItemIds = new Set(); + const openCalls = new Map(); + let pendingArguments = []; + let disposed = false; + + const releaseCall = (itemId) => { + const open = openCalls.get(itemId); + if (!open) return; + if (open.retainedBytes > 0) { + budget?.releaseRetained(open.retainedBytes, { kind: 'retained_collectors' }); + } + openCalls.delete(itemId); + }; + + const releaseAll = () => { + if (disposed) return; + disposed = true; + for (const itemId of openCalls.keys()) releaseCall(itemId); + const pendingBytes = pendingArguments.reduce((total, pending) => total + pending.retainedBytes, 0); + if (pendingBytes > 0) { + budget?.releaseRetained(pendingBytes, { kind: 'retained_collectors' }); + } + pendingArguments = []; + itemNames.clear(); + customExecItemNames.clear(); + repairItemNames.clear(); + ordinaryItemIds.clear(); + }; + + const retainPendingArgument = (block, itemId, outputIndex) => { + const retainedBytes = Buffer.byteLength(block, 'utf8'); + if (retainedBytes > 0) budget?.chargeRetained(retainedBytes, { kind: 'retained_collectors' }); + pendingArguments.push({ block, itemId, outputIndex, retainedBytes }); + }; + + const takePendingArguments = (itemId, outputIndex) => { + const matched = []; + const remaining = []; + for (const pending of pendingArguments) { + const matches = pending.itemId !== undefined + ? itemId !== undefined && pending.itemId === itemId + : outputIndex !== undefined && pending.outputIndex === outputIndex; + (matches ? matched : remaining).push(pending); + } + pendingArguments = remaining; + const retainedBytes = matched.reduce((total, pending) => total + pending.retainedBytes, 0); + if (retainedBytes > 0) { + budget?.releaseRetained(retainedBytes, { kind: 'retained_collectors' }); + } + return matched.map(pending => { + if (pending.itemId !== undefined || itemId === undefined) return pending.block; + const payload = sseDataPayload(pending.block); + if (payload === null) return pending.block; + try { + const parsed = JSON.parse(payload); + if (!isPlainObject(parsed)) return pending.block; + return replaceSseDataPayload(pending.block, JSON.stringify({ ...parsed, item_id: itemId })); + } catch { + return pending.block; + } + }); + }; + + const rewrite = (block) => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null || payload === '[DONE]') return [block]; + let parsed; + try { + parsed = JSON.parse(payload); + } catch { + return [block]; + } + if (!isPlainObject(parsed)) return [block]; + + const type = typeof parsed.type === 'string' ? parsed.type : ''; + const outputIndex = typeof parsed.output_index === 'number' + && Number.isInteger(parsed.output_index) + && parsed.output_index >= 0 + ? parsed.output_index + : undefined; + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'custom_tool_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const wireName = routedCustomToolWireName(parsed.item); + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const aliased = targetName !== undefined && targetName !== wireName; + const codeModeExec = targetName === 'exec' && parsed.item.name === 'exec' + && parsed.item.namespace === undefined && declaresCodeModeExec(declaredNames); + if (upstreamItemId && (aliased || codeModeExec)) { + customExecItemNames.set(upstreamItemId, parsed.item.name); + if (type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const repairable = wireName !== undefined && repairNames.has(wireName); + if (upstreamItemId && repairable) repairItemNames.set(upstreamItemId, parsed.item.name); + const restored = repairable || aliased || codeModeExec + ? restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames) + : { value: parsed, changed: false }; + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + } + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'function_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const routed = targetName !== undefined; + const wireName = routedCustomToolWireName(parsed.item); + if (upstreamItemId) { + if (routed) { + itemNames.set(upstreamItemId, { + name: parsed.item.name, + aliased: targetName !== wireName, + ...(typeof parsed.item.namespace === 'string' ? { namespace: parsed.item.namespace } : {}), + }); + ordinaryItemIds.delete(upstreamItemId); + } else { + ordinaryItemIds.add(upstreamItemId); + } + if (routed && type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const pending = takePendingArguments(upstreamItemId, outputIndex); + if (!routed) { + if (type === 'response.output_item.done' && upstreamItemId) ordinaryItemIds.delete(upstreamItemId); + return [...pending, block]; + } + if (upstreamItemId && pending.length > 0 && !openCalls.has(upstreamItemId)) { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const restoredBlock = restored.changed + ? replaceSseDataPayload(block, JSON.stringify(restored.value)) + : block; + const replayed = pending.flatMap(pendingBlock => rewrite(pendingBlock)); + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return type === 'response.output_item.added' + ? [restoredBlock, ...replayed] + : [...replayed, restoredBlock]; + } + + const upstreamItemId = typeof parsed.item_id === 'string' ? parsed.item_id : undefined; + if ( + type === 'response.custom_tool_call_input.delta' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (customExecItemNames.get(upstreamItemId) !== 'exec' + || mayBecomePatchEnvelope(open.argumentsText) + || open.argumentsText.trimStart() === '' + || open.argumentsText.trimStart().startsWith('{')) return []; + const inputDelta = open.argumentsText.slice(open.emittedInput.length); + open.emittedInput = open.argumentsText; + return inputDelta ? [replaceSseDataPayload(block, JSON.stringify({ ...parsed, delta: inputDelta }))] : []; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const source = typeof parsed.input === 'string' + ? parsed.input + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const name = customExecItemNames.get(upstreamItemId); + const helper = name === 'exec' + ? resolveCodeModeHelperName(undefined, name, source, undefined, declaredNames) + : name; + releaseCall(upstreamItemId); + return [replaceSseDataPayload(block, JSON.stringify({ + ...parsed, + input: helper ? compileCodeModeHelperInput(source, helper) : source, + }))]; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && repairItemNames.has(upstreamItemId) + && typeof parsed.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(parsed.input); + if (input !== parsed.input) { + return [replaceSseDataPayload(block, JSON.stringify({ ...parsed, input }))]; + } + } + const argumentEvent = type === 'response.function_call_arguments.delta' + || type === 'response.function_call_arguments.done'; + if (argumentEvent && (!upstreamItemId || (!itemNames.has(upstreamItemId) && !ordinaryItemIds.has(upstreamItemId)))) { + retainPendingArgument(block, upstreamItemId, outputIndex); + return []; + } + if ( + type === 'response.function_call_arguments.delta' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (itemNames.get(upstreamItemId)?.aliased) return []; + if (FREEFORM_WRAP_PREFIX.startsWith(open.argumentsText)) return []; + const fullInput = partialCustomToolInput(open.argumentsText); + if (fullInput === null) return []; + if ( + declaresCodeModeExec(declaredNames) + && itemNames.get(upstreamItemId)?.namespace === undefined + && itemNames.get(upstreamItemId)?.name === 'exec' + && mayBecomePatchEnvelope(fullInput) + ) return []; + if (!fullInput.startsWith(open.emittedInput) || fullInput.length === open.emittedInput.length) return []; + const inputDelta = fullInput.slice(open.emittedInput.length); + open.emittedInput = fullInput; + const nextType = 'response.custom_tool_call_input.delta'; + const next = { + ...parsed, + type: nextType, + item_id: customToolItemId(upstreamItemId), + delta: inputDelta, + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + if ( + type === 'response.function_call_arguments.done' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const nextType = 'response.custom_tool_call_input.done'; + const source = typeof parsed.arguments === 'string' + ? parsed.arguments + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const { arguments: _arguments, ...rest } = parsed; + const itemName = itemNames.get(upstreamItemId); + const helper = itemName?.aliased + ? itemName.name + : resolveCodeModeHelperName(undefined, itemName?.name ?? '', source, itemName?.namespace, declaredNames); + const next = { + ...rest, + type: nextType, + item_id: customToolItemId(upstreamItemId), + input: helper + ? compileCodeModeHelperInput(source, helper) + : unwrapRoutedCustomToolArguments(source, itemName?.name ?? '', itemName?.namespace), + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const terminal = type === 'response.completed' || type === 'response.failed' || type === 'response.incomplete'; + if (terminal) releaseAll(); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + }; + rewrite.dispose = releaseAll; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/responses-function-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/responses-function-tool-repair.mjs new file mode 100644 index 0000000..ae8dabf --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/responses-function-tool-repair.mjs @@ -0,0 +1,165 @@ +import { + TRANSLATOR_MAX_TURN_BYTES, + TranslatorBudgetExceededError, +} from './translator-budget.mjs'; +import { repairFunctionCalls } from './function-call-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const ENTRY_OVERHEAD_BYTES = 64; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function outputIndexOf(value) { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +export function createResponsesFunctionToolRepairBlockRewrite(schemas, budget) { + if (schemas.size === 0) return block => [block]; + const byId = new Map(); + const byIndex = new Map(); + let pending = []; + let retainedBytes = 0; + let disposed = false; + + const retain = (bytes) => { + if (retainedBytes + bytes > TRANSLATOR_MAX_TURN_BYTES) { + throw new TranslatorBudgetExceededError('retained_collectors', TRANSLATOR_MAX_TURN_BYTES); + } + budget?.chargeRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes += bytes; + }; + const release = (bytes) => { + budget?.releaseRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes -= bytes; + }; + const releaseIdentity = (identity) => { + if (identity.itemId !== undefined) byId.delete(identity.itemId); + if (identity.outputIndex !== undefined) byIndex.delete(identity.outputIndex); + release(identity.bytes); + }; + const dispose = () => { + if (disposed) return; + disposed = true; + release(retainedBytes); + byId.clear(); + byIndex.clear(); + pending = []; + }; + const lookup = (itemId, index) => { + const identity = itemId === undefined ? undefined : byId.get(itemId); + if (identity) return index === undefined || identity.outputIndex === undefined || identity.outputIndex === index ? identity : undefined; + const indexed = index === undefined ? undefined : byIndex.get(index); + return indexed && (itemId === undefined || indexed.itemId === undefined || indexed.itemId === itemId) ? indexed : undefined; + }; + const register = (item, index) => { + const itemId = typeof item.id === 'string' && item.id ? item.id : undefined; + if (itemId === undefined && index === undefined) return undefined; + const previous = new Set(); + if (itemId !== undefined && byId.has(itemId)) previous.add(byId.get(itemId)); + if (index !== undefined && byIndex.has(index)) previous.add(byIndex.get(index)); + for (const identity of previous) releaseIdentity(identity); + const metadata = { + type: item.type, + name: item.name, + ...('namespace' in item ? { namespace: item.namespace } : {}), + ...(item.status !== undefined && item.status !== 'in_progress' && item.status !== 'completed' ? { status: item.status } : {}), + }; + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(JSON.stringify([itemId, index, metadata]), 'utf8'); + retain(bytes); + const identity = { itemId, outputIndex: index, item: metadata, bytes }; + if (itemId !== undefined) byId.set(itemId, identity); + if (index !== undefined) byIndex.set(index, identity); + return identity; + }; + const repairCompletion = (block, event, identity) => { + if (typeof event.arguments !== 'string') return block; + const resolved = (typeof event.item_id !== 'string' || event.item_id === '') && identity.itemId !== undefined + ? { ...event, item_id: identity.itemId } + : event; + const repaired = repairFunctionCalls({ ...identity.item, status: identity.item.status ?? 'completed', arguments: event.arguments }, schemas); + if (repaired.changed && isObject(repaired.value)) { + return replaceSseDataPayload(block, JSON.stringify({ ...resolved, arguments: repaired.value.arguments })); + } + return resolved === event ? block : replaceSseDataPayload(block, JSON.stringify(resolved)); + }; + const flushPending = (identity) => { + const output = []; + const remaining = []; + for (const completion of pending) { + const matches = completion.itemId !== undefined + ? completion.itemId === identity.itemId + && (completion.outputIndex === undefined || identity.outputIndex === undefined || completion.outputIndex === identity.outputIndex) + : completion.outputIndex !== undefined && completion.outputIndex === identity.outputIndex; + if (!matches) { remaining.push(completion); continue; } + release(completion.bytes); + const payload = sseDataPayload(completion.block); + const event = payload === null ? undefined : JSON.parse(payload); + output.push(isObject(event) ? repairCompletion(completion.block, event, identity) : completion.block); + } + pending = remaining; + return output; + }; + + const rewrite = block => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null) return [block]; + if (payload === '[DONE]') { + const unfinished = pending.map(entry => entry.block); + dispose(); + return [...unfinished, block]; + } + let event; + try { event = JSON.parse(payload); } catch { return [block]; } + if (!isObject(event)) return [block]; + const index = outputIndexOf(event.output_index); + const itemId = typeof event.item_id === 'string' && event.item_id ? event.item_id : undefined; + try { + if ((event.type === 'response.output_item.added' || event.type === 'response.output_item.done') && isObject(event.item)) { + const identity = register(event.item, index); + const replayed = identity ? flushPending(identity) : []; + const repaired = repairFunctionCalls(event, schemas); + const output = repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block; + if (identity && (event.type === 'response.output_item.done' || replayed.length > 0)) releaseIdentity(identity); + return event.type === 'response.output_item.added' ? [output, ...replayed] : [...replayed, output]; + } + if (event.type === 'response.function_call_arguments.done' && typeof event.arguments === 'string') { + const identity = lookup(itemId, index); + if (identity) { + const output = repairCompletion(block, event, identity); + releaseIdentity(identity); + return [output]; + } + if (itemId !== undefined || index !== undefined) { + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(block, 'utf8'); + retain(bytes); + pending.push({ block, itemId, outputIndex: index, bytes }); + return []; + } + } + if (typeof event.type === 'string' && ['response.completed', 'response.failed', 'response.incomplete', 'response.cancelled'].includes(event.type)) { + const replayed = []; + if (event.type === 'response.completed' && isObject(event.response) && Array.isArray(event.response.output) + && (event.response.status === undefined || event.response.status === 'completed')) { + for (const [slot, item] of event.response.output.entries()) { + if (!isObject(item)) continue; + const identity = register(item, slot); + if (identity) replayed.push(...flushPending(identity)); + } + } + replayed.push(...pending.map(entry => entry.block)); + const repaired = repairFunctionCalls(event, schemas); + dispose(); + return [...replayed, repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block]; + } + return [block]; + } catch (error) { + dispose(); + throw error; + } + }; + rewrite.dispose = dispose; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/responses.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/responses.mjs new file mode 100644 index 0000000..2253c9d --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/responses.mjs @@ -0,0 +1,146 @@ +import { Transform } from 'node:stream'; +import { StringDecoder } from 'node:string_decoder'; +import { stripCanonicalOnlyToolFields } from './tool-groups.mjs'; +import { + collectSelfNamedNamespaceScrubAuthorization, + createSelfNamedToolCallNamespaceScrubRewrite, + scrubSelfNamedToolCallNamespaceInJson, +} from './self-named-namespace-scrub.mjs'; +import { rewriteRoutedCustomToolsForUpstream, restoreRoutedCustomCallsInJson } from './custom-tool-compat.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream, restoreRoutedNamespaceCallsInJson } from './namespace-tool-compat.mjs'; +import { collectFunctionCallRepairSchemas, repairFunctionCallsInJson } from './function-call-compat.mjs'; +import { createRoutedCustomToolRestoreBlockRewrite } from './responses-custom-tool-repair.mjs'; +import { createResponsesFunctionToolRepairBlockRewrite } from './responses-function-tool-repair.mjs'; +import { createTranslatorBudget } from './translator-budget.mjs'; +import { collectDeclaredWireToolNames } from './undeclared-tool-guard.mjs'; +import { composeSseBlockRewrites, payloadRewriteAsBlockRewrite, nextSseBlock } from './sse-payload-rewrite.mjs'; + +/** One request owns both forward conversion and reverse tool identities. */ +export function prepareResponsesCompatibility(body, policy = {}) { + const custom = policy.customTools && policy.customTools !== 'native' + ? rewriteRoutedCustomToolsForUpstream(body, policy.customTools === 'functions' ? false : undefined) + : { body, names: new Set(), repairNames: new Set() }; + const namespace = policy.namespaceTools === 'functions' + ? rewriteRoutedNamespaceToolsForUpstream(custom.body, custom.names) + : { body: custom.body, aliases: new Map() }; + const schemas = policy.repairFunctionArguments ? collectFunctionCallRepairSchemas(body) : new Map(); + const declared = collectDeclaredWireToolNames(body); + const scrubAuthorization = collectSelfNamedNamespaceScrubAuthorization( + body, + new Set([...custom.names, ...custom.repairNames]), + new Set(schemas.keys()), + ); + const restoreNamespace = (text) => restoreRoutedNamespaceCallsInJson(text, namespace.aliases); + return { + body: policy.namespaceTools === 'functions' ? stripCanonicalOnlyToolFields(namespace.body, false) : namespace.body, + needsResponseTransform: custom.names.size > 0 || custom.repairNames.size > 0 || namespace.aliases.size > 0 || schemas.size > 0, + restoreJson(text) { + let next = restoreNamespace(scrubSelfNamedToolCallNamespaceInJson(text, scrubAuthorization)); + next = restoreRoutedCustomCallsInJson(next, custom.names, custom.repairNames, declared); + next = repairFunctionCallsInJson(next, schemas); + return next; + }, + createStreamRewrite() { + const budget = createTranslatorBudget(); + const stages = [ + payloadRewriteAsBlockRewrite(createSelfNamedToolCallNamespaceScrubRewrite(scrubAuthorization)), + payloadRewriteAsBlockRewrite(restoreNamespace), + createRoutedCustomToolRestoreBlockRewrite(custom.names, budget, custom.repairNames, declared), + createResponsesFunctionToolRepairBlockRewrite(schemas, budget), + ]; + const rewrite = composeSseBlockRewrites(...stages); + const dispose = rewrite.dispose; + rewrite.dispose = () => { dispose?.(); budget.dispose(); }; + return rewrite; + }, + }; +} + +const MAX_RESPONSE_BYTES = 32 * 1024 * 1024; + +class CompatibilityResponseTransform extends Transform { + constructor(prepared, sse) { + super(); + this.prepared = prepared; + this.sse = sse; + this.decoder = new StringDecoder('utf8'); + this.buffer = ''; + this.rewrite = sse ? prepared.createStreamRewrite() : undefined; + } + + drain(final = false) { + if (this.sse) { + let frame; + while ((frame = nextSseBlock(this.buffer))) { + if (Buffer.byteLength(frame.block) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.buffer = frame.rest; + for (const block of this.rewrite(frame.block)) this.push(block + frame.delimiter); + } + if (final && this.buffer) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + for (const block of this.rewrite(this.buffer)) this.push(block + '\n\n'); + this.buffer = ''; + } + } else if (final) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.push(this.prepared.restoreJson(this.buffer)); + this.buffer = ''; + } + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + } + + _transform(chunk, _encoding, callback) { + try { + this.buffer += this.decoder.write(chunk); + this.drain(); + callback(); + } catch (error) { + callback(error); + } + } + + _flush(callback) { + try { + this.buffer += this.decoder.end(); + this.drain(true); + callback(); + } catch (error) { + callback(error); + } + } + + _destroy(error, callback) { + this.buffer = ''; + this.rewrite?.dispose?.(); + callback(error); + } +} + +export function createResponsesCompatibilityAdapter(policy = {}) { + const pending = new Map(); + return { + adaptRequest(body, requestId, overrides = {}) { + pending.delete(requestId); + const now = Date.now(); + for (const [id, entry] of pending) if (now - entry.at >= 15 * 60_000) pending.delete(id); + if (!pending.has(requestId) && pending.size >= 256) throw new Error('too many in-flight compatibility requests'); + const prepared = prepareResponsesCompatibility(body, { ...policy, ...overrides }); + if (prepared.needsResponseTransform) pending.set(requestId, { prepared, at: now }); + return prepared.body === body ? null : prepared.body; + }, + releaseResponse(requestId) { + pending.delete(requestId); + }, + createResponseTransform(requestId, response) { + const entry = pending.get(requestId); + pending.delete(requestId); + if (!entry) return null; + const encoding = (response.contentEncoding ?? '').trim().toLowerCase(); + if (encoding && encoding !== 'identity') throw new Error('compressed compatibility response cannot be rewritten'); + const type = (response.contentType ?? '').toLowerCase(); + const sse = type.startsWith('text/event-stream'); + if (!sse && !type.includes('application/json')) throw new Error('unsupported compatibility response content type'); + return new CompatibilityResponseTransform(entry.prepared, sse); + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/self-named-namespace-scrub.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/self-named-namespace-scrub.mjs new file mode 100644 index 0000000..d4c7800 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/self-named-namespace-scrub.mjs @@ -0,0 +1,149 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + specs, +) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) { + if (!isPlainObject(inner) || typeof inner.name !== 'string') continue; + if (namespace !== 'functions' && namespace === inner.name) { + if (inner.type === 'custom') sameNameNamespacedCustomNames.add(inner.name); + else if (inner.type === 'function') sameNameNamespacedFunctionNames.add(inner.name); + } + if (namespace === 'functions') { + if (inner.type === 'custom') bareCustomNames.add(inner.name); + else if (inner.type === 'function') bareFunctionNames.add(inner.name); + } + } + continue; + } + const nestedFunction = spec.type === 'function' && isPlainObject(spec.function) ? spec.function : undefined; + const name = typeof spec.name === 'string' && spec.name.length > 0 + ? spec.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; + if (!name) continue; + const namespace = typeof spec.namespace === 'string' ? spec.namespace : undefined; + if (namespace !== 'functions' && namespace === name) { + if (spec.type === 'custom') sameNameNamespacedCustomNames.add(name); + else if (spec.type === 'function') sameNameNamespacedFunctionNames.add(name); + } + if (!namespace || namespace === 'functions') { + if (spec.type === 'custom') bareCustomNames.add(name); + else if (spec.type === 'function') bareFunctionNames.add(name); + } + } +} + +export function collectSelfNamedNamespaceScrubAuthorization( + body, + authorizedBareCustomToolNames, + authorizedBareFunctionToolNames, +) { + const bareCustomNames = new Set(); + const bareFunctionNames = new Set(); + const sameNameNamespacedCustomNames = new Set(); + const sameNameNamespacedFunctionNames = new Set(); + if (isPlainObject(body)) { + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + body.tools, + ); + if (Array.isArray(body.input)) { + for (const item of body.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) { + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + item.tools, + ); + } + } + } + } + const authorizedCustomNames = [...bareCustomNames] + .filter(name => authorizedBareCustomToolNames.has(name)); + const authorizedFunctionNames = new Set([ + ...authorizedCustomNames, + ...[...bareFunctionNames].filter(name => authorizedBareFunctionToolNames.has(name)), + ]); + return { + customToolCallNames: new Set( + authorizedCustomNames.filter(name => !sameNameNamespacedCustomNames.has(name)), + ), + functionCallNames: new Set( + [...authorizedFunctionNames].filter(name => !sameNameNamespacedFunctionNames.has(name)), + ), + }; +} + +export function scrubSelfNamedToolCallNamespace(value, authorization) { + if (Array.isArray(value)) { + let changed = false; + const out = value.map(entry => { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: out, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + let changed = false; + const out = {}; + for (const [key, entry] of Object.entries(value)) { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + out[key] = result.value; + changed ||= result.changed; + } + const authorizedNames = value.type === 'custom_tool_call' + ? authorization.customToolCallNames + : value.type === 'function_call' + ? authorization.functionCallNames + : undefined; + if ( + authorizedNames + && typeof value.name === 'string' + && value.name.length > 0 + && value.namespace === value.name + && authorizedNames.has(value.name) + ) { + delete out.namespace; + changed = true; + } + return changed ? { value: out, changed: true } : { value, changed: false }; +} + +export function scrubSelfNamedToolCallNamespaceInJson(text, authorization) { + if (!text.includes('"namespace"')) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const result = scrubSelfNamedToolCallNamespace(payload, authorization); + return result.changed ? JSON.stringify(result.value) : text; +} + +export function createSelfNamedToolCallNamespaceScrubRewrite(authorization) { + return payload => scrubSelfNamedToolCallNamespaceInJson(payload, authorization); +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/sse-payload-rewrite.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/sse-payload-rewrite.mjs new file mode 100644 index 0000000..4798585 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/sse-payload-rewrite.mjs @@ -0,0 +1,74 @@ +/** Adapt a payload rewrite to the block contract (replace only on change). */ +export function payloadRewriteAsBlockRewrite(rewrite) { + return (block) => { + const payload = sseDataPayload(block); + if (payload === null) return [block]; + const rewritten = rewrite(payload); + return rewritten !== payload ? [replaceSseDataPayload(block, rewritten)] : [block]; + }; +} + +/** Chain block rewrites: every block stage N emits feeds stage N+1. */ +export function composeSseBlockRewrites(...rewrites) { + const active = rewrites.filter(Boolean); + if (active.length === 0) return Object.assign((block) => [block], {}); + const composed = (block) => { + let blocks = [block]; + for (const rewrite of active) { + const next = []; + for (const current of blocks) next.push(...rewrite(current)); + blocks = next; + } + return blocks; + }; + let disposed = false; + composed.dispose = () => { + if (disposed) return; + disposed = true; + for (const rewrite of active) { + try { rewrite.dispose?.(); } catch { /* teardown must not throw */ } + } + }; + return composed; +} + +/** Split one complete SSE event block while retaining its original blank-line delimiter. */ +export function nextSseBlock(buffer) { + const match = buffer.match(/\r?\n\r?\n/); + if (!match || match.index === undefined) return null; + return { + block: buffer.slice(0, match.index), + delimiter: match[0], + rest: buffer.slice(match.index + match[0].length), + }; +} + +/** Join all data lines from one SSE event according to the event-stream field rules. */ +export function sseDataPayload(block) { + const data = []; + for (const line of block.split(/\r?\n/)) { + if (!line.startsWith('data:')) continue; + const value = line.slice(5); + data.push(value.startsWith(' ') ? value.slice(1) : value); + } + return data.length > 0 ? data.join('\n') : null; +} + +/** Replace an SSE event's data field while preserving non-data fields and newline style. */ +export function replaceSseDataPayload(block, payload) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + const rewritten = []; + let replaced = false; + for (const line of lines) { + if (!line.startsWith('data:')) { + rewritten.push(line); + continue; + } + if (!replaced) { + rewritten.push(`data: ${payload}`); + replaced = true; + } + } + return replaced ? rewritten.join(newline) : block; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/tool-argument-integers.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-argument-integers.mjs new file mode 100644 index 0000000..9164255 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-argument-integers.mjs @@ -0,0 +1,130 @@ +function asSchema(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined; +} + +function declaresInteger(schema) { + const type = schema.type; + if (type === 'integer') return true; + return Array.isArray(type) && type.includes('integer'); +} + +function declaresString(schema) { + const type = schema.type; + if (type === 'string') return true; + return Array.isArray(type) && type.includes('string'); +} + +const U64_NUMBER_FIELDS = new Set(['timeout_ms']); +const U64_NUMBER_FIELDS_BY_TOOL = new Map([ + ['wait', new Set(['yield_time_ms', 'max_tokens'])], +]); + +function declaresNumeric(schema) { + const type = schema.type; + if (type === 'integer' || type === 'number') return true; + return Array.isArray(type) && (type.includes('integer') || type.includes('number')); +} + +function resolveRef(schema, root, seen) { + const ref = schema.$ref; + if (typeof ref !== 'string' || !ref.startsWith('#/')) return schema; + if (seen.has(ref)) return undefined; + seen.add(ref); + let node = root; + for (const rawSegment of ref.slice(2).split('/')) { + const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~'); + const current = asSchema(node); + if (!current) return undefined; + node = current[segment]; + } + const resolved = asSchema(node); + return resolved ? resolveRef(resolved, root, seen) : undefined; +} + +const COMPOSITION_KEYS = ['anyOf', 'oneOf', 'allOf']; + +function compositionBranches(schema) { + const branches = []; + for (const key of COMPOSITION_KEYS) { + const value = schema[key]; + if (!Array.isArray(value)) continue; + for (const branch of value) { + const node = asSchema(branch); + if (node) branches.push(node); + } + } + return branches; +} + +function safelyIntegral(value) { + return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; +} + +function coerceValue(value, schema, root, depth, toolName, propertyName) { + if (depth > 64) return { value, changed: false }; + const resolved = schema ? resolveRef(schema, root, new Set()) : undefined; + + if (typeof value === 'number') { + if (!resolved) return { value, changed: false }; + const branches = compositionBranches(resolved); + const nativeU64Field = propertyName !== undefined + && ( + U64_NUMBER_FIELDS.has(propertyName) + || U64_NUMBER_FIELDS_BY_TOOL.get(toolName ?? '')?.has(propertyName) === true + ); + const nativeU64Declared = nativeU64Field + && (declaresNumeric(resolved) || branches.some(declaresNumeric)); + const integerDeclared = declaresInteger(resolved) + || branches.some(declaresInteger) + || nativeU64Declared; + if (!integerDeclared && safelyIntegral(value)) { + const stringDeclared = declaresString(resolved) || branches.some(declaresString); + const numericDeclared = declaresNumeric(resolved) || branches.some(declaresNumeric); + if (stringDeclared && !numericDeclared) { + return { value: String(value), changed: true }; + } + } + if (!integerDeclared || !safelyIntegral(value)) return { value, changed: false }; + return { value, changed: true }; + } + + if (Array.isArray(value)) { + const itemSchema = resolved ? asSchema(resolved.items) : undefined; + let changed = false; + const next = value.map(entry => { + const result = coerceValue(entry, itemSchema, root, depth + 1, toolName); + if (result.changed) changed = true; + return result.value; + }); + return changed ? { value: next, changed: true } : { value, changed: false }; + } + + const object = asSchema(value); + if (!object) return { value, changed: false }; + + const properties = resolved ? asSchema(resolved.properties) : undefined; + const additional = resolved ? asSchema(resolved.additionalProperties) : undefined; + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(object)) { + const childSchema = asSchema(properties?.[key]) ?? additional; + const result = coerceValue(entry, childSchema, root, depth + 1, toolName, key); + if (result.changed) changed = true; + next[key] = result.value; + } + return changed ? { value: next, changed: true } : { value, changed: false }; +} + +export function coerceIntegerToolArguments(args, parameters, toolName) { + if (!parameters || !args) return args; + if (!/\d/.test(args)) return args; + let parsed; + try { + parsed = JSON.parse(args); + } catch { + return args; + } + const result = coerceValue(parsed, parameters, parameters, 0, toolName); + if (!result.changed) return args; + return JSON.stringify(result.value); +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/tool-groups.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-groups.mjs new file mode 100644 index 0000000..5b62304 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-groups.mjs @@ -0,0 +1,65 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** Collect top-level and Responses Lite tool containers without altering their order. */ +export function collectResponsesToolGroups(body) { + if (!isPlainObject(body)) return []; + + const groups = []; + if (Array.isArray(body.tools)) groups.push(body.tools); + if (!Array.isArray(body.input)) return groups; + + for (const item of body.input) { + if (isPlainObject(item) && item.type === 'additional_tools' && Array.isArray(item.tools)) { + groups.push(item.tools); + } + } + return groups; +} + +export const CANONICAL_ONLY_TOOL_FIELDS = [ + { field: 'external_web_access', toolTypes: new Set(['web_search', 'web_search_preview']), capabilityGated: true }, + { field: 'defer_loading' }, +]; + +export function stripCanonicalOnlyToolFields(body, includeCapabilityGated) { + if (!isPlainObject(body)) return body; + + const rewriteTools = (tools) => { + let changed = false; + const rewritten = tools.map(tool => { + if (!isPlainObject(tool)) return tool; + let next = tool; + for (const { field, toolTypes, capabilityGated } of CANONICAL_ONLY_TOOL_FIELDS) { + if (capabilityGated && !includeCapabilityGated) continue; + if (!Object.hasOwn(next, field)) continue; + if (toolTypes && (typeof next.type !== 'string' || !toolTypes.has(next.type))) continue; + const { [field]: _private, ...rest } = next; + next = rest; + } + if (next === tool) return tool; + changed = true; + return next; + }); + return changed ? rewritten : tools; + }; + + let rewrittenBody = body; + if (Array.isArray(body.tools)) { + const tools = rewriteTools(body.tools); + if (tools !== body.tools) rewrittenBody = { ...rewrittenBody, tools }; + } + if (!Array.isArray(body.input)) return rewrittenBody; + + let input; + for (let index = 0; index < body.input.length; index += 1) { + const item = body.input[index]; + if (!isPlainObject(item) || item.type !== 'additional_tools' || !Array.isArray(item.tools)) continue; + const tools = rewriteTools(item.tools); + if (tools === item.tools) continue; + input ??= [...body.input]; + input[index] = { ...item, tools }; + } + return input ? { ...rewrittenBody, input } : rewrittenBody; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/tool-name-aliases.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-name-aliases.mjs new file mode 100644 index 0000000..587befb --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/tool-name-aliases.mjs @@ -0,0 +1,68 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** + * A dotted spelling is a safe alias only when it cannot ALSO be read as some other identity's + * canonical `ns__name`. + */ +export function dottedAliasIsUnambiguous(namespace, name) { + return !namespace.includes('__') && !name.includes('__'); +} + +export function wireToolInnerName(tool) { + if (!isPlainObject(tool)) return undefined; + const nestedFunction = tool.type === 'function' && isPlainObject(tool.function) + ? tool.function + : undefined; + return typeof tool.name === 'string' && tool.name.length > 0 + ? tool.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; +} + +/** + * Dotted aliases that more than one declared identity would claim, plus dotted aliases that + * collide with a canonical or bare declared name. + */ +export function collectAmbiguousDottedAliases(specGroups) { + const owners = new Map(); + const claim = (alias, identity) => { + const owner = owners.get(alias); + if (owner === undefined) owners.set(alias, identity); + else if (owner !== identity) owners.set(alias, null); + }; + for (const specs of specGroups) { + if (!Array.isArray(specs)) continue; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + if (!namespace) continue; + for (const inner of spec.tools) { + const name = wireToolInnerName(inner); + if (!name) continue; + if (namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + claim(name, JSON.stringify([undefined, name])); + continue; + } + const identity = JSON.stringify([namespace, name]); + claim(dottedToolName(namespace, name), identity); + claim(namespacedToolName(namespace, name), identity); + claim(name, identity); + } + continue; + } + const name = wireToolInnerName(spec); + if (name) claim(name, JSON.stringify([undefined, name])); + } + } + const ambiguous = new Set(); + for (const [alias, owner] of owners) if (owner === null) ambiguous.add(alias); + return ambiguous; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/tools.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/tools.mjs new file mode 100644 index 0000000..203b692 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/tools.mjs @@ -0,0 +1,33 @@ +export function namespacedToolName(namespace, name) { + return namespace ? `${namespace}__${name}` : name; +} + +export function dottedToolName(namespace, name) { + return namespace ? `${namespace}.${name}` : name; +} + +const LEGACY_SHELL_BRIDGE_TOOL_NAMES = ['exec_command', 'shell_command']; +const CODE_MODE_HELPER_TOOL_NAMES = [ + ...LEGACY_SHELL_BRIDGE_TOOL_NAMES, + 'write_stdin', + 'apply_patch', +]; + +export const CODE_MODE_EXEC_TOOL_NAME = 'exec'; + +export function normalizeDeclaredToolName(name, declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return name; + if (declared.has(name)) return name; + if (name === 'apply_patch') return CODE_MODE_EXEC_TOOL_NAME; + if (LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy))) { + return name; + } + return CODE_MODE_HELPER_TOOL_NAMES.includes(name) + ? CODE_MODE_EXEC_TOOL_NAME + : name; +} + +export function declaresCodeModeExec(declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return false; + return !LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy)); +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/translator-budget.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/translator-budget.mjs new file mode 100644 index 0000000..1f11b9f --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/translator-budget.mjs @@ -0,0 +1,34 @@ +export const TRANSLATOR_MAX_TURN_BYTES = 16 * 1024 * 1024; +export const TRANSLATOR_MAX_CALL_ARGUMENT_BYTES = 8 * 1024 * 1024; + +export class TranslatorBudgetExceededError extends Error { + constructor(kind, limit) { + super(`translator buffer limit exceeded (${kind}: ${limit} bytes)`); + this.name = 'TranslatorBudgetExceededError'; + this.kind = kind; + this.limit = limit; + } +} + +export function createTranslatorBudget(options = {}) { + const maxTurnBytes = options.maxTurnBytes ?? TRANSLATOR_MAX_TURN_BYTES; + let charged = 0; + let disposed = false; + return { + chargeRetained(bytes, scope = { kind: 'retained_collectors' }) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + if (charged + bytes > maxTurnBytes) { + throw new TranslatorBudgetExceededError(scope.kind ?? 'retained_collectors', maxTurnBytes); + } + charged += bytes; + }, + releaseRetained(bytes) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + charged = Math.max(0, charged - bytes); + }, + dispose() { + disposed = true; + charged = 0; + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/src/undeclared-tool-guard.mjs b/questions/codex-namespace-tool-collision/v1/candidate/src/undeclared-tool-guard.mjs new file mode 100644 index 0000000..0cea492 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/src/undeclared-tool-guard.mjs @@ -0,0 +1,59 @@ +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from './tool-name-aliases.mjs'; +import { + CODE_MODE_EXEC_TOOL_NAME, + dottedToolName, + namespacedToolName, +} from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function addWireToolName(names, tool, namespace, ambiguousDottedAliases) { + if (!isPlainObject(tool)) return; + const name = wireToolInnerName(tool); + if (!name) return; + if (!namespace || namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + names.add(name); + return; + } + names.add(namespacedToolName(namespace, name)); + const dotted = dottedToolName(namespace, name); + if (dottedAliasIsUnambiguous(namespace, name) && !ambiguousDottedAliases?.has(dotted)) { + names.add(dotted); + } + if (name !== CODE_MODE_EXEC_TOOL_NAME) names.add(name); +} + +function addWireToolSpecs(names, specs, ambiguousDottedAliases) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases); + continue; + } + addWireToolName(names, spec, undefined, ambiguousDottedAliases); + } +} + +/** Tool names the outbound Responses body actually declared. */ +export function collectDeclaredWireToolNames(body) { + const names = new Set(); + if (!isPlainObject(body)) return names; + const specGroups = [body.tools]; + if (Array.isArray(body.input)) { + for (const item of body.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) specGroups.push(item.tools); + } + } + const ambiguousDottedAliases = collectAmbiguousDottedAliases(specGroups); + for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases); + return names; +} diff --git a/questions/codex-namespace-tool-collision/v1/candidate/tests/smoke.test.mjs b/questions/codex-namespace-tool-collision/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..bcf1887 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,121 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + createResponsesCompatibilityAdapter, + prepareResponsesCompatibility, +} from '../src/responses.mjs'; + +async function runTransform(transform, input) { + let out = ''; + transform.setEncoding('utf8'); + transform.on('data', (chunk) => { out += chunk; }); + const done = new Promise((resolve, reject) => { + transform.on('end', () => resolve(out)); + transform.on('error', reject); + }); + transform.end(input); + return done; +} + +test('lowers and restores ordinary non-colliding namespace function tools (JSON & SSE)', async () => { + const adapter = createResponsesCompatibilityAdapter({ + customTools: 'preserve-apply-patch', + namespaceTools: 'functions', + repairFunctionArguments: true, + }); + const body = { + tools: [ + { + type: 'namespace', + name: 'weather', + tools: [ + { + type: 'function', + name: 'forecast', + defer_loading: true, + parameters: { type: 'object', properties: { days: { type: 'integer' } } }, + }, + ], + }, + ], + tool_choice: { type: 'function', namespace: 'weather', name: 'forecast' }, + }; + const adapted = adapter.adaptRequest(body, 1); + assert.equal(adapted.tools.length, 1); + assert.equal(adapted.tools[0].name, 'weather__forecast'); + assert.equal('defer_loading' in adapted.tools[0], false); + assert.deepEqual(adapted.tool_choice, { type: 'function', name: 'weather__forecast' }); + + const jsonWire = JSON.stringify({ + status: 'completed', + output: [{ type: 'function_call', name: 'weather__forecast', call_id: 'c1', arguments: '{"days":3.0}' }], + }); + const restoredJson = JSON.parse(await runTransform( + adapter.createResponseTransform(1, { contentType: 'application/json', contentEncoding: '' }), + jsonWire, + )); + assert.deepEqual(restoredJson.output[0], { + type: 'function_call', + namespace: 'weather', + name: 'forecast', + call_id: 'c1', + arguments: '{"days":3}', + }); +}); + +test('lowers and restores ordinary custom tools and preserves apply_patch passthrough', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { type: 'custom', name: 'apply_patch', description: 'Patch files' }, + { type: 'custom', name: 'run_script', description: 'Run script' }, + ], + }, + { customTools: 'preserve-apply-patch', namespaceTools: 'functions', repairFunctionArguments: true }, + ); + assert.equal(prepared.body.tools[0].type, 'custom'); + assert.equal(prepared.body.tools[1].type, 'function'); + + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + output: [ + { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'run_script', arguments: '{"input":"echo hi"}' }, + ], + }))); + assert.deepEqual(restored.output[0], { + type: 'custom_tool_call', + id: 'ctc_1', + call_id: 'call_1', + name: 'run_script', + input: 'echo hi', + }); +}); + +test('repairs ordinary integer-float and bare-integer-to-string arguments without altering non-integral floats', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { + type: 'function', + name: 'cell_read', + parameters: { + type: 'object', + properties: { + cell_id: { type: 'string' }, + limit: { type: 'integer' }, + ratio: { type: 'integer' }, + }, + }, + }, + ], + }, + { repairFunctionArguments: true }, + ); + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + status: 'completed', + output: [ + { type: 'function_call', name: 'cell_read', arguments: '{"cell_id":4,"limit":10.0,"ratio":1.5}' }, + ], + }))); + assert.equal(restored.output[0].arguments, '{"cell_id":"4","limit":10,"ratio":1.5}'); +}); diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/CONTRACT.md b/questions/codex-namespace-tool-collision/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..85b9d28 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,37 @@ +# Product & Protocol Contract + +## 1. Public Entrypoints (`src/responses.mjs`) + +- `prepareResponsesCompatibility(body, policy)`: + - `policy`: `{ namespaceTools?: 'native' | 'functions', customTools?: 'native' | 'functions' | 'preserve-apply-patch', repairFunctionArguments?: boolean }`. + - Returns `{ body, needsResponseTransform, restoreJson(text), createStreamRewrite() }`. +- `createResponsesCompatibilityAdapter(policy)`: + - Returns `{ adaptRequest(body, requestId, overrides?), releaseResponse(requestId), createResponseTransform(requestId, { contentType, contentEncoding }) }` supporting `application/json` and `text/event-stream`. + +## 2. Namespace Lowering & Collision Disambiguation (`namespaceTools: 'functions'`) + +- Top-level declarations (both flat `{ type, name }` and Chat-shaped nested `{ type: 'function', function: { name } }`) and children of the reserved `functions` namespace own their literal bare wire names regardless of declaration order across `tools` and `input[].additional_tools`. Duplicate declarations of the same logical tool deduplicate cleanly. +- Non-`functions` namespace children `(ns, name)` default to wire name `__`. When a wire name collides with a distinct logical tool, `prepareResponsesCompatibility` disambiguates deterministically (`_2`, `_3`, … capped at 64 chars: `prefix.slice(0, 64 - tail.length) + tail`) without hijacking any declared bare name, namespace child's logical name, or default flattened name across `tools` and `additional_tools`. +- Direct calls to `rewriteRoutedNamespaceToolsForUpstream(body)` default to `disambiguate = false` (throwing `NamespaceToolCollisionError` on collisions); passing `disambiguate = true` enables disambiguation. +- `tool_choice` (direct `{ type, name, namespace? }` and `allowed_tools`) and replayed `input` tool calls rewrite consistently to allocated wire names and drop private `namespace` fields. Authorization strictly matches original declared kinds (`function` vs `custom`). +- Under `customTools: 'preserve-apply-patch'`, any custom tool whose original logical name is `apply_patch` (even if namespaced and disambiguated) remains `type: 'custom'`; under `customTools: 'functions'`, all custom tools convert to `type: 'function'`. +- Canonical-only fields (`defer_loading`) are stripped from `tools` and `input[].additional_tools` when lowering. + +## 3. Round-Trip Restoration (JSON & Incremental SSE Parity) + +- Converted custom tools restore from `function_call` to `custom_tool_call` (`fc_` → `ctc_`, `{ "input": "..." }` unwrapped; incremental SSE emits `custom_tool_call` + `custom_tool_call_input` without leaking raw `function_call_arguments` deltas) across: + - the allocated wire name, + - unambiguous authorized dotted aliases (`.` when neither segment contains `__`, non-ambiguous across the catalog, and not declared as a bare tool), and + - provider echoes retaining matching `namespace` alongside original name, allocated wire name, or dotted alias. +- Calls with a non-matching `namespace` or unrelated bare names (e.g. `a__a__b_2`) remain untouched. +- If a call carries an explicit `(namespace, name)` matching an authorized declared namespace tool, that explicit declared identity takes precedence over another tool's alias spelling. + +## 4. Conflict Guards & Native-Namespace Repair + +- **Code Mode helper guard**: Helper rerouting toward bare custom `exec` must respect declared logical names (both unlowered and lowered, across `tools` and `additional_tools`) so declaring a namespaced `apply_patch` protects bare `apply_patch` from being rerouted to `exec`. +- **Self-named namespace scrubbing**: Strips redundant `namespace: x` from `{ name: x, namespace: x }` when bare `x` is authorized and no active same-name namespace conflict `(x, x)` exists. + - Must account for both original and lowered catalogs, including same-name namespaced `custom` tools that arrive upstream as `function_call`. + - Under `namespaceTools: 'functions'`, a same-name `type: 'namespace'` group declaration blocks scrubbing ONLY if authorized/selected by the turn's `tool_choice`; inline `spec.namespace` declarations retain the conservative guard. +- **Native-namespace argument repair (`namespaceTools: 'native'`, `repairFunctionArguments: true`)**: + - Request declarations pass through unchanged. + - Argument repair applies each tool's own schema keyed by exact `(namespace, name)` identity so bare `ns__name` and namespaced `(ns, name)` never cross-contaminate. Integral floats coerce to integers for `integer` fields; safe integers coerce to strings for `string`-only fields; non-integral floats stay untouched. diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/ENVIRONMENT.md b/questions/codex-namespace-tool-collision/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..531abf3 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering non-colliding tool lowering, restoration, and argument repair diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/TASK.md b/questions/codex-namespace-tool-collision/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..7b45802 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/TASK.md @@ -0,0 +1,15 @@ +# Task + +Production Codex sessions are hitting Responses API tool compatibility failures whenever bare tools, `functions` tools, MCP/namespaced tools, and `custom` tools interact or share wire spellings—across both JSON responses and incremental SSE streams. + +Reported issues include: +- Requests failing when bare and namespaced tools flatten to the same wire name. +- Converted namespaced `custom` tools failing to round-trip back to `custom_tool_call` across valid provider echo spellings, or colliding with other declared tools. +- Self-named namespace echo repair, Code Mode helper routing, and native-namespace argument repair misbehaving around colliding, converted, or unselected tools. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable protocol compatibility defects while preserving behavior for ordinary non-colliding requests. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/package.json b/questions/codex-namespace-tool-collision/v1/controls/incomplete/package.json new file mode 100644 index 0000000..4fe1fc6 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-codex-namespace-tool-collision", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/apply-patch-envelope.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/apply-patch-envelope.mjs new file mode 100644 index 0000000..74a315a --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/apply-patch-envelope.mjs @@ -0,0 +1,45 @@ +const PATCH_BEGIN = '*** Begin Patch'; +const PATCH_END = '*** End Patch'; +const TOP_LEVEL_PATCH_ENVELOPE = /^(\*\*\* Begin Patch(?: \*\*\*)?)(\r?\n)([\s\S]*)(\r?\n)(\*\*\* End Patch(?: \*\*\*)?)(\r?\n)?$/; +const PATCH_OPERATION_LINE = /^\*\*\* (?:Add|Update|Delete) File: .+$/m; + +export function unwrapFreeformToolInput(argumentsText) { + if (typeof argumentsText !== 'string') return ''; + try { + const parsed = JSON.parse(argumentsText); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + } + } catch { + // The string is the freeform body, not nested JSON. + } + return argumentsText; +} + +export function normalizeApplyPatchDelimiters(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return text; + const [, begin, beginBreak, body, endBreak, end, trailingBreak = ''] = match; + if (!PATCH_OPERATION_LINE.test(body)) return text; + if (begin === PATCH_BEGIN && end === PATCH_END) return text; + return `${PATCH_BEGIN}${beginBreak}${body}${endBreak}${PATCH_END}${trailingBreak}`; +} + +export function isCompletePatchEnvelope(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return false; + return PATCH_OPERATION_LINE.test(match[3] ?? ''); +} + +export function mayBecomePatchEnvelope(text) { + if (text === '') return false; + return text.startsWith(PATCH_BEGIN) || PATCH_BEGIN.startsWith(text); +} + +export function repairFreeformToolInput(argumentsText, toolName = '', namespace) { + const unwrapped = unwrapFreeformToolInput(argumentsText); + const ownsApplyPatchGrammar = namespace === undefined || namespace === 'functions'; + return ownsApplyPatchGrammar && toolName === 'apply_patch' + ? normalizeApplyPatchDelimiters(unwrapped) + : unwrapped; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/code-mode-helper-compat.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/code-mode-helper-compat.mjs new file mode 100644 index 0000000..0597745 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/code-mode-helper-compat.mjs @@ -0,0 +1,65 @@ +import { + isCompletePatchEnvelope, + normalizeApplyPatchDelimiters, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function unwrapPatchInput(value) { + try { + const parsed = JSON.parse(value); + if (isPlainObject(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + if (typeof parsed.patch === 'string') return parsed.patch; + } + } catch { + // Native custom calls carry the patch body directly. + } + return value; +} + +export function compileCodeModeHelperInput(argumentsText, toolName) { + if (typeof argumentsText !== 'string') return ''; + if (toolName === 'apply_patch') { + const patch = normalizeApplyPatchDelimiters(unwrapPatchInput(argumentsText)); + return `const result = await tools.apply_patch(${JSON.stringify(patch)});\ntext(result);`; + } + let parsed = argumentsText; + try { + parsed = JSON.parse(argumentsText); + } catch { + // Keep malformed provider text as data rather than executable source. + } + const args = isPlainObject(parsed) ? { ...parsed } : parsed; + if ( + toolName === 'shell_command' + && isPlainObject(args) + && typeof args.command === 'string' + && args.cmd === undefined + ) { + args.cmd = args.command; + delete args.command; + } + if (toolName === 'write_stdin') { + return `const result = await tools.write_stdin(${JSON.stringify(args)});\ntext(result);`; + } + return `const result = await tools.exec_command(${JSON.stringify(args)});\ntext(result);`; +} + +export function resolveCodeModeHelperName( + codeModeHelperName, + toolName, + argumentsText, + namespace, + declaredNames, +) { + if (codeModeHelperName) return codeModeHelperName; + if (toolName !== 'exec' || namespace !== undefined) return undefined; + if (!declaresCodeModeExec(declaredNames)) return undefined; + if (typeof argumentsText !== 'string' || argumentsText === '') return undefined; + return isCompletePatchEnvelope(unwrapFreeformToolInput(argumentsText)) ? 'apply_patch' : undefined; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/custom-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/custom-tool-compat.mjs new file mode 100644 index 0000000..7b7cef5 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/custom-tool-compat.mjs @@ -0,0 +1,349 @@ +import { namespacedToolName, normalizeDeclaredToolName } from './tools.mjs'; +import { + normalizeApplyPatchDelimiters, + repairFreeformToolInput, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +const ROUTED_CUSTOM_TOOL_PASSTHROUGH = new Set(['apply_patch']); +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function routedCustomToolPassesThrough( + name, + supportsResponsesCustomTools, + passthroughNames = ROUTED_CUSTOM_TOOL_PASSTHROUGH, +) { + return supportsResponsesCustomTools !== false && passthroughNames.has(name); +} + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function customToolWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function toolChoiceAllowsRoutedCustomTool(body, wireName, candidateNames) { + if (!isPlainObject(body)) return true; + const choice = body.tool_choice; + if (choice === undefined || choice === null || choice === 'auto' || choice === 'required') { + return true; + } + if (choice === 'none') return false; + if (!isPlainObject(choice)) return true; + + const selectorAllows = (selector) => { + if (!isPlainObject(selector) || typeof selector.name !== 'string') return false; + if (selector.type !== 'custom') return false; + if (typeof selector.namespace === 'string') { + return customToolWireName(selector.namespace, selector.name) === wireName; + } + if (selector.name === wireName) return true; + const suffix = `__${selector.name}`; + const candidates = [...candidateNames].filter(name => name.endsWith(suffix)); + return candidates.length === 1 && candidates[0] === wireName; + }; + + if (choice.type === 'function' || choice.type === 'custom') return selectorAllows(choice); + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + return choice.tools.some(selectorAllows); + } + return false; +} + +export function routedCustomToolWireName(value) { + if (!isPlainObject(value) || typeof value.name !== 'string') return undefined; + return customToolWireName( + typeof value.namespace === 'string' ? value.namespace : undefined, + value.name, + ); +} + +export function routedCustomToolTargetName(value, names, declaredNames) { + const wireName = routedCustomToolWireName(value); + if (wireName === undefined) return undefined; + if (names.has(wireName)) return wireName; + if (!isPlainObject(value) || typeof value.namespace === 'string') return undefined; + const normalized = normalizeDeclaredToolName(wireName, declaredNames); + return normalized !== wireName && names.has(normalized) ? normalized : undefined; +} + +function collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, passthrough = false, passthroughNames) { + const names = new Set(); + const groups = collectResponsesToolGroups(body); + const bareWireNames = new Set(); + for (const group of groups) { + for (const tool of group) { + if ( + isPlainObject(tool) + && tool.type !== 'namespace' + && typeof tool.name === 'string' + ) bareWireNames.add(tool.name); + } + } + + for (const group of groups) { + for (const tool of group) { + if (!isPlainObject(tool)) continue; + if ( + tool.type === 'custom' + && typeof tool.name === 'string' + && routedCustomToolPassesThrough(tool.name, supportsResponsesCustomTools, passthroughNames) === passthrough + ) { + names.add(tool.name); + continue; + } + if (tool.type !== 'namespace' || typeof tool.name !== 'string' || !Array.isArray(tool.tools)) { + continue; + } + for (const child of tool.tools) { + if ( + isPlainObject(child) + && child.type === 'custom' + && typeof child.name === 'string' + && routedCustomToolPassesThrough(child.name, supportsResponsesCustomTools, passthroughNames) === passthrough + && (!passthrough || tool.name === BUILTIN_FUNCTIONS_NAMESPACE) + && !(tool.name === BUILTIN_FUNCTIONS_NAMESPACE && bareWireNames.has(child.name)) + ) names.add(customToolWireName(tool.name, child.name)); + } + } + } + return names; +} + +export function customToolItemId(id) { + if (typeof id !== 'string') return id; + return id.startsWith('fc_') ? `ctc_${id.slice(3)}` : id; +} + +export function collectRoutedCustomToolNames(body, supportsResponsesCustomTools, passthroughNames) { + const names = new Set(); + const visit = (value) => { + if (Array.isArray(value)) { + for (const entry of value) visit(entry); + return; + } + if (!isPlainObject(value)) return; + if ( + value.type === 'custom' + && typeof value.name === 'string' + && !routedCustomToolPassesThrough(value.name, supportsResponsesCustomTools, passthroughNames) + ) { + names.add(value.name); + } + for (const key of ['tools', 'input', 'tool_choice']) visit(value[key]); + }; + visit(body); + return names; +} + +function collectConvertedCallIds(value, names, out) { + if (Array.isArray(value)) { + for (const entry of value) collectConvertedCallIds(entry, names, out); + return; + } + if (!isPlainObject(value)) return; + if ( + (value.type === 'custom_tool_call' || value.type === 'function_call') + && typeof value.name === 'string' + && names.has(value.name) + && typeof value.call_id === 'string' + ) { + out.add(value.call_id); + } + if (Array.isArray(value.input)) collectConvertedCallIds(value.input, names, out); +} + +function rewriteForUpstream(value, names, callIds) { + if (Array.isArray(value)) return value.map(entry => rewriteForUpstream(entry, names, callIds)); + if (!isPlainObject(value)) return value; + + if (value.type === 'custom' && typeof value.name === 'string' && names.has(value.name)) { + const { format: _format, ...rest } = value; + const isDefinition = typeof value.description === 'string' + || isPlainObject(value.format) + || isPlainObject(value.parameters); + if (!isDefinition) return { ...rest, type: 'function' }; + const inputDescription = value.name === 'exec' + ? 'JavaScript source for unified exec. Use await tools.exec_command(...) for shell commands and text(...) to return textual output; do not provide a bare shell command.' + : 'Raw input for this client-executed custom tool.'; + return { + ...rest, + type: 'function', + parameters: { + type: 'object', + properties: { + input: { + type: 'string', + description: inputDescription, + }, + }, + required: ['input'], + additionalProperties: false, + }, + }; + } + + if ( + value.type === 'custom_tool_call' + && typeof value.name === 'string' + && names.has(value.name) + ) { + const { input, id: _id, ...rest } = value; + return { + ...rest, + type: 'function_call', + arguments: JSON.stringify({ input: typeof input === 'string' ? input : '' }), + }; + } + + if ( + value.type === 'custom_tool_call_output' + && typeof value.call_id === 'string' + && callIds.has(value.call_id) + ) { + return { ...value, type: 'function_call_output' }; + } + + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(value)) { + const rewritten = ['tools', 'input', 'tool_choice'].includes(key) + ? rewriteForUpstream(entry, names, callIds) : entry; + next[key] = rewritten; + changed ||= rewritten !== entry; + } + return changed ? next : value; +} + +export function rewriteRoutedCustomToolsForUpstream(body, supportsResponsesCustomTools, passthroughNames) { + const conversionNames = collectRoutedCustomToolNames(body, supportsResponsesCustomTools, passthroughNames); + const names = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, false, passthroughNames); + const repairNames = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, true); + for (const name of repairNames) { + if (!toolChoiceAllowsRoutedCustomTool(body, name, repairNames)) repairNames.delete(name); + } + if (conversionNames.size === 0) return { body, names, repairNames }; + const callIds = new Set(); + collectConvertedCallIds(body, conversionNames, callIds); + return { body: rewriteForUpstream(body, conversionNames, callIds), names, repairNames }; +} + +export function restoreRoutedCustomCalls(value, names, repairNames = new Set(), declaredNames) { + if (!isPlainObject(value)) return { value, changed: false }; + + const restoreItem = (item) => { + if (!isPlainObject(item)) return { value: item, changed: false }; + const wireName = routedCustomToolWireName(item); + const targetName = routedCustomToolTargetName(item, names, declaredNames); + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + && wireName !== undefined + && targetName !== undefined + ) { + const sourceInput = item.type === 'function_call' ? item.arguments : item.input; + const aliased = targetName !== wireName; + const itemNamespace = typeof item.namespace === 'string' ? item.namespace : undefined; + const helper = aliased && sourceInput !== '' + ? item.name + : resolveCodeModeHelperName(undefined, targetName, sourceInput, itemNamespace, declaredNames); + if (item.type === 'custom_tool_call' && !aliased && !helper) { + const input = repairNames.has(wireName) && typeof sourceInput === 'string' + ? normalizeApplyPatchDelimiters(sourceInput) + : sourceInput; + return input !== sourceInput + ? { value: { ...item, input }, changed: true } + : { value: item, changed: false }; + } + const restored = { + ...item, + type: 'custom_tool_call', + id: customToolItemId(item.id), + name: aliased ? targetName : item.name, + input: helper + ? compileCodeModeHelperInput(sourceInput, helper) + : repairFreeformToolInput(sourceInput, targetName, itemNamespace), + }; + delete restored.arguments; + if (aliased) delete restored.namespace; + return { value: restored, changed: true }; + } + if ( + item.type === 'custom_tool_call' + && typeof item.name === 'string' + && wireName !== undefined + && repairNames.has(wireName) + && typeof item.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(item.input); + if (input !== item.input) return { value: { ...item, input }, changed: true }; + } + return { value: item, changed: false }; + }; + + const restoreOutput = (output) => { + if (!Array.isArray(output)) return { value: output, changed: false }; + let changed = false; + const restored = output.map(item => { + const result = restoreItem(item); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value: output, changed: false }; + }; + + let changed = false; + const restored = { ...value }; + const output = restoreOutput(value.output); + if (output.changed) { + restored.output = output.value; + changed = true; + } + + if ( + (value.type === 'response.output_item.added' || value.type === 'response.output_item.done') + && isPlainObject(value.item) + ) { + const item = restoreItem(value.item); + if (item.changed) { + restored.item = item.value; + changed = true; + } + } + + if ( + typeof value.type === 'string' + && value.type.startsWith('response.') + && isPlainObject(value.response) + ) { + const response = restoreRoutedCustomCalls(value.response, names, repairNames, declaredNames); + if (response.changed) { + restored.response = response.value; + changed = true; + } + } + + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedCustomCallsInJson(text, names, repairNames = new Set(), declaredNames) { + if (names.size === 0 && repairNames.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedCustomCalls(payload, names, repairNames, declaredNames); + return restored.changed ? JSON.stringify(restored.value) : text; +} + +export function unwrapRoutedCustomToolArguments(argumentsText, toolName = '', namespace) { + return toolName + ? repairFreeformToolInput(argumentsText, toolName, namespace) + : unwrapFreeformToolInput(argumentsText); +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/function-call-compat.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/function-call-compat.mjs new file mode 100644 index 0000000..cfb6461 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/function-call-compat.mjs @@ -0,0 +1,154 @@ +import { coerceIntegerToolArguments } from './tool-argument-integers.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream } from './namespace-tool-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function sameSchemaValue(left, right) { + if (left === right) return true; + if (Array.isArray(left) || Array.isArray(right)) { + return Array.isArray(left) && Array.isArray(right) && left.length === right.length + && left.every((value, index) => sameSchemaValue(value, right[index])); + } + if (!isObject(left) || !isObject(right)) return false; + const keys = Object.keys(left); + return keys.length === Object.keys(right).length + && keys.every(key => Object.hasOwn(right, key) && sameSchemaValue(left[key], right[key])); +} + +function namespaceOf(value) { + return typeof value === 'string' && value !== 'functions' ? value : undefined; +} + +function schemaKey(namespace, name) { + return JSON.stringify([namespace ?? '', name]); +} + +function selectorAllows(selector, lowered, wireName, identity) { + if (!isObject(selector) || selector.type !== 'function' || typeof selector.name !== 'string') return false; + if ('namespace' in selector) { + if (typeof selector.namespace !== 'string' || selector.namespace.length === 0) return false; + return namespaceOf(selector.namespace) === identity.namespace && selector.name === identity.name; + } + return isObject(lowered) && lowered.type === 'function' && lowered.name === wireName; +} + +export function collectFunctionCallRepairSchemas(body) { + const schemas = new Map(); + if (!isObject(body)) return schemas; + const groups = collectResponsesToolGroups(body); + if (Array.isArray(body.input)) { + for (const entry of body.input) { + if (isObject(entry) && entry.type === 'tool_search_output' && Array.isArray(entry.tools)) groups.push(entry.tools); + } + } + const namespacePlan = rewriteRoutedNamespaceToolsForUpstream({ ...body, tools: groups.flat(), input: [] }, undefined, true); + const lowered = namespacePlan.body; + const choice = body.tool_choice; + const loweredChoice = isObject(lowered) ? lowered.tool_choice : undefined; + const occupied = new Map(); + const register = (tool, namespace) => { + if (!isObject(tool) || typeof tool.name !== 'string' || tool.name.length === 0) return; + const identity = { + name: tool.name, + ...(namespace ? { namespace } : {}), + ...(isObject(tool.parameters) ? { parameters: tool.parameters } : {}), + }; + const key = schemaKey(namespace, tool.name); + if (occupied.has(key)) { + const previous = occupied.get(key); + if (!previous || previous.kind !== tool.type + || previous.identity.namespace !== namespace + || previous.identity.name !== tool.name + || !sameSchemaValue(previous.identity.parameters, identity.parameters)) { + occupied.set(key, null); + } + } else occupied.set(key, { kind: tool.type, identity }); + }; + for (const group of groups) { + for (const tool of group) { + if (!isObject(tool)) continue; + if (tool.type === 'namespace') { + if (typeof tool.name !== 'string' || !tool.name || !Array.isArray(tool.tools)) continue; + for (const child of tool.tools) register(child, namespaceOf(tool.name)); + } else if (tool.type === 'function' && isObject(tool.function)) { + register({ ...tool.function, type: 'function' }); + } else register(tool); + } + } + for (const [key, entry] of occupied) { + if (!entry || entry.kind !== 'function') continue; + let allowed = choice === undefined || choice === 'auto' || choice === 'required'; + if (isObject(choice)) { + const wireName = entry.identity.namespace + ? [...namespacePlan.aliases].find(([, identity]) => identity.namespace === entry.identity.namespace && identity.name === entry.identity.name)?.[0] + : entry.identity.name; + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + const selectors = isObject(loweredChoice) && Array.isArray(loweredChoice.tools) ? loweredChoice.tools : []; + allowed = choice.tools.some((selector, index) => selectorAllows(selector, selectors[index], wireName, entry.identity)); + } else allowed = selectorAllows(choice, loweredChoice, wireName, entry.identity); + } + if (allowed) schemas.set(key, entry.identity); + } + return schemas; +} + +function repairItem(item, schemas, completed) { + if (!isObject(item) || item.type !== 'function_call' || typeof item.name !== 'string' + || typeof item.arguments !== 'string') return item; + if (item.status !== 'completed' && !(item.status === undefined && completed)) return item; + if ('namespace' in item && (typeof item.namespace !== 'string' || !item.namespace)) return item; + const namespace = namespaceOf(item.namespace); + const schema = schemas.get(schemaKey(namespace, item.name)); + if (!schema) return item; + if ('namespace' in item && (schema.namespace !== namespace || schema.name !== item.name)) return item; + const raw = item.arguments; + if (raw !== '') { + try { + let unsafe = false; + JSON.parse(raw, (_key, value) => { + if (typeof value === 'number' && (!Number.isFinite(value) + || (Number.isInteger(value) && !Number.isSafeInteger(value)))) unsafe = true; + return value; + }); + if (unsafe) return item; + } catch { return item; } + } + const argumentsText = coerceIntegerToolArguments(raw || '{}', schema.parameters, schema.namespace ? undefined : schema.name); + return argumentsText === raw ? item : { ...item, arguments: argumentsText }; +} + +export function repairFunctionCalls(value, schemas) { + if (schemas.size === 0 || !isObject(value)) return { value, changed: false }; + if (typeof value.status === 'string' && ['failed', 'incomplete', 'cancelled', 'in_progress', 'queued'].includes(value.status)) return { value, changed: false }; + let next = value; + if (value.type === 'function_call') next = repairItem(value, schemas, false); + else if (value.type === 'response.output_item.done') { + const item = repairItem(value.item, schemas, true); + if (item !== value.item) next = { ...value, item }; + } else if (value.type === 'response.completed' && isObject(value.response)) { + const response = value.response; + if ((response.status === undefined || response.status === 'completed') && Array.isArray(response.output)) { + const original = response.output; + const output = original.map(item => repairItem(item, schemas, true)); + if (output.some((item, index) => item !== original[index])) next = { ...value, response: { ...response, output } }; + } + } else if (typeof value.type !== 'string' || !value.type.startsWith('response.')) { + if (Array.isArray(value.output)) { + const original = value.output; + const output = original.map(item => repairItem(item, schemas, value.status === 'completed')); + if (output.some((item, index) => item !== original[index])) next = { ...value, output }; + } + } + return { value: next, changed: next !== value }; +} + +export function repairFunctionCallsInJson(text, schemas) { + if (schemas.size === 0) return text; + let payload; + try { payload = JSON.parse(text); } catch { return text; } + const repaired = repairFunctionCalls(payload, schemas); + return repaired.changed ? JSON.stringify(repaired.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/namespace-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/namespace-tool-compat.mjs new file mode 100644 index 0000000..3e60383 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/namespace-tool-compat.mjs @@ -0,0 +1,352 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from './tool-name-aliases.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function namespaceIdentity(namespace, name) { + return `${namespace}\u0000${name}`; +} + +function isRepresentableName(name) { + if (typeof name !== 'string' || name.length === 0) return false; + for (let index = 0; index < name.length; index += 1) { + const code = name.charCodeAt(index); + if (code <= 0x1f || code === 0x7f) return false; + } + return true; +} + +function parseNamespaceGroup(tool) { + if ( + !isPlainObject(tool) + || tool.type !== 'namespace' + || !isRepresentableName(tool.name) + || !Array.isArray(tool.tools) + ) return undefined; + const children = []; + for (const child of tool.tools) { + if (!isPlainObject(child) || child.type === 'namespace' || !isRepresentableName(child.name)) continue; + children.push(child); + } + return { namespace: tool.name, children }; +} + +function loweredIdentity(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE + ? namespaceIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name) + : namespaceIdentity(namespace, name); +} + +function loweredWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function addSelector(selectors, selector, wireName) { + const current = selectors.get(selector); + if (current === undefined) selectors.set(selector, wireName); + else if (current !== wireName) selectors.set(selector, null); +} + +/** Two distinct logical tools would occupy one wire name; the caller maps this to a 400. */ +export class NamespaceToolCollisionError extends Error {} + +function buildRewritePlan(groups, disambiguate) { + const aliases = new Map(); + const bareWireNames = new Set(); + const canonicalWireNames = new Set(); + const identities = new Map(); + const selectors = new Map(); + const wireOwners = new Map(); + const reserved = new Set(); + + // Reserve every natural spelling before allocating aliases, including declarations in + // later additional_tools groups. An alias must not steal another tool's ordinary name. + for (const group of groups) for (const tool of group) { + const name = wireToolInnerName(tool); + if (isPlainObject(tool) && tool.type !== 'namespace' && isRepresentableName(name)) reserved.add(name); + const parsed = parseNamespaceGroup(tool); + if (parsed) for (const child of parsed.children) { + // Bare tool_choice references can name a child by its original logical name. + reserved.add(child.name); + reserved.add(loweredWireName(parsed.namespace, child.name)); + } + } + + for (const group of groups) { + for (const tool of group) { + const name = wireToolInnerName(tool); + if (isPlainObject(tool) && tool.type !== 'namespace' && isRepresentableName(name)) { + wireOwners.set(name, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name)); + bareWireNames.add(name); + canonicalWireNames.add(name); + addSelector(selectors, name, name); + } + // Codex's reserved group is another representation of bare tools. Claim its + // names before ordinary namespaces, but do not mark its declarations emitted. + const parsed = disambiguate ? parseNamespaceGroup(tool) : undefined; + if (parsed?.namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + for (const child of parsed.children) { + const childName = child.name; + wireOwners.set(childName, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, childName)); + canonicalWireNames.add(childName); + addSelector(selectors, childName, childName); + } + } + } + } + + for (const group of groups) { + for (const tool of group) { + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const childName = child.name; + const identity = loweredIdentity(parsed.namespace, childName); + let wireName = identities.get(identity) ?? loweredWireName(parsed.namespace, childName); + const owner = wireOwners.get(wireName); + if (owner !== undefined && owner !== identity) { + if (!disambiguate) { + throw new NamespaceToolCollisionError( + `namespace tool wire-name collision for "${wireName}"; rename one of the colliding tools`, + ); + } + const prefix = wireName; + let suffix = 2; + do { + const tail = `_${suffix++}`; + wireName = `${prefix.slice(0, 64 - tail.length)}${tail}`; + } while (reserved.has(wireName)); + reserved.add(wireName); + } + wireOwners.set(wireName, identity); + identities.set(identity, wireName); + // A bare declaration owns its literal selector even if a namespace child's + // original flattened spelling collides with it. + addSelector(selectors, wireName, wireName); + addSelector(selectors, `${parsed.namespace}.${childName}`, wireName); + if (!disambiguate || !canonicalWireNames.has(childName)) addSelector(selectors, childName, wireName); + if (parsed.namespace !== BUILTIN_FUNCTIONS_NAMESPACE) { + const kind = child.type === 'custom' ? 'custom' : 'function'; + aliases.set(wireName, { namespace: parsed.namespace, name: childName, kind }); + } + } + } + } + + return { aliases, bareWireNames, identities, selectors }; +} + +function rewriteToolList(tools, plan, emitted) { + let changed = false; + const rewritten = []; + for (const tool of tools) { + if (isPlainObject(tool) && tool.type === 'namespace') { + changed = true; + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const wireName = plan.identities.get(loweredIdentity(parsed.namespace, child.name)); + if ( + wireName === undefined + || (parsed.namespace === BUILTIN_FUNCTIONS_NAMESPACE && plan.bareWireNames.has(wireName)) + || emitted.has(wireName) + ) continue; + emitted.add(wireName); + rewritten.push(wireName === child.name ? child : { ...child, name: wireName }); + } + continue; + } + const name = wireToolInnerName(tool); + if (isRepresentableName(name)) { + if (emitted.has(name)) { + changed = true; + continue; + } + emitted.add(name); + } + rewritten.push(tool); + } + return changed ? rewritten : tools; +} + +function hasMalformedNamespace(value) { + return 'namespace' in value && typeof value.namespace !== 'string'; +} + +function rewriteNamedSelector(value, plan, bareFallback) { + if (!isPlainObject(value) || typeof value.name !== 'string') return value; + if (hasMalformedNamespace(value)) return value; + const namespace = value.namespace; + if (typeof namespace !== 'string') { + if (!bareFallback) return value; + const wireName = plan.selectors.get(value.name) ?? undefined; + return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName }; + } + const { namespace: _dropped, ...rest } = value; + const wireName = plan.identities.get(loweredIdentity(namespace, value.name)) + ?? loweredWireName(namespace, value.name); + return { ...rest, name: wireName }; +} + +function rewriteToolChoice(value, plan) { + if (!isPlainObject(value)) return value; + if ((value.type === 'function' || value.type === 'custom') && typeof value.name === 'string') { + return rewriteNamedSelector(value, plan, true); + } + if (value.type !== 'allowed_tools' || !Array.isArray(value.tools)) return value; + let changed = false; + const tools = value.tools.map(tool => { + if (!isPlainObject(tool) || typeof tool.name !== 'string') return tool; + const rewritten = rewriteNamedSelector(tool, plan, true); + changed ||= rewritten !== tool; + return rewritten; + }); + return changed ? { ...value, tools } : value; +} + +function authorizedAliases(aliases, toolChoice) { + if (toolChoice === undefined || toolChoice === 'auto' || toolChoice === 'required') return aliases; + if (toolChoice === 'none' || !isPlainObject(toolChoice)) return new Map(); + + let authorized; + if ( + (toolChoice.type === 'function' || toolChoice.type === 'custom') + && typeof toolChoice.name === 'string' + ) { + if (hasMalformedNamespace(toolChoice)) return new Map(); + authorized = new Map([[toolChoice.name, toolChoice.type]]); + } else if (toolChoice.type === 'allowed_tools' && Array.isArray(toolChoice.tools)) { + authorized = new Map(); + for (const tool of toolChoice.tools) { + if (!isPlainObject(tool)) continue; + if (tool.type !== 'function' && tool.type !== 'custom') continue; + if (typeof tool.name !== 'string') continue; + if (hasMalformedNamespace(tool)) continue; + authorized.set(tool.name, tool.type); + } + } else { + return new Map(); + } + + return new Map( + [...aliases].filter(([wireName, identity]) => authorized.get(wireName) === identity.kind), + ); +} + +function rewriteInputItem(item, plan, emitted) { + if (!isPlainObject(item)) return item; + if (item.type === 'additional_tools' && Array.isArray(item.tools)) { + const tools = rewriteToolList(item.tools, plan, emitted); + return tools === item.tools ? item : { ...item, tools }; + } + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + ) return rewriteNamedSelector(item, plan, false); + return item; +} + +export function rewriteRoutedNamespaceToolsForUpstream(body, convertedCustomToolNames, disambiguate = false) { + if (!isPlainObject(body)) return { body, aliases: new Map(), declarations: new Map() }; + const groups = collectResponsesToolGroups(body); + const plan = buildRewritePlan(groups, disambiguate); + const declarations = new Map(plan.aliases); + + const emitted = new Set(); + const tools = Array.isArray(body.tools) ? rewriteToolList(body.tools, plan, emitted) : body.tools; + + let input = body.input; + if (Array.isArray(body.input)) { + let inputChanged = false; + const rewrittenInput = body.input.map(item => { + const next = rewriteInputItem(item, plan, emitted); + if (next !== item) inputChanged = true; + return next; + }); + if (inputChanged) input = rewrittenInput; + } + + const toolChoice = rewriteToolChoice(body.tool_choice, plan); + const aliases = authorizedAliases(plan.aliases, toolChoice); + const ambiguousDotted = collectAmbiguousDottedAliases(groups); + for (const identity of [...aliases.values()]) { + const dotted = dottedToolName(identity.namespace, identity.name); + if (dottedAliasIsUnambiguous(identity.namespace, identity.name) + && !ambiguousDotted.has(dotted) && !plan.bareWireNames.has(dotted) + && !aliases.has(dotted)) aliases.set(dotted, identity); + } + for (const identity of aliases.values()) { + if (convertedCustomToolNames?.has(namespacedToolName(identity.namespace, identity.name))) identity.kind = 'custom'; + } + return { + body: { + ...body, + ...(tools !== body.tools ? { tools } : {}), + ...(input !== body.input ? { input } : {}), + ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}), + }, + aliases, + declarations, + }; +} + +export function restoreRoutedNamespaceCalls( + value, + aliases, + originalCoordinates = new Set([...aliases.values()].map(identity => + namespaceIdentity(identity.namespace, identity.name))), +) { + if (Array.isArray(value)) { + let changed = false; + const restored = value.map(entry => { + const result = restoreRoutedNamespaceCalls(entry, aliases, originalCoordinates); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + + let changed = false; + const restored = {}; + for (const [key, entry] of Object.entries(value)) { + const result = restoreRoutedNamespaceCalls(entry, aliases, originalCoordinates); + restored[key] = result.value; + changed ||= result.changed; + } + + if ( + (value.type === 'function_call' || value.type === 'custom_tool_call') + && typeof value.name === 'string' + // An explicit declared coordinate wins over another tool's alias spelling. + && !(typeof value.namespace === 'string' + && originalCoordinates.has(namespaceIdentity(value.namespace, value.name))) + ) { + const identity = aliases.get(value.name); + if (identity + && (value.type !== 'custom_tool_call' || identity.kind === 'custom') + && (!Object.hasOwn(value, 'namespace') || value.namespace === identity.namespace)) { + restored.name = identity.name; + restored.namespace = identity.namespace; + changed = true; + } + } + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedNamespaceCallsInJson(text, aliases) { + if (aliases.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedNamespaceCalls(payload, aliases); + return restored.changed ? JSON.stringify(restored.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-custom-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-custom-tool-repair.mjs new file mode 100644 index 0000000..6afa922 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-custom-tool-repair.mjs @@ -0,0 +1,351 @@ +import { mayBecomePatchEnvelope, normalizeApplyPatchDelimiters } from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; +import { + customToolItemId, + restoreRoutedCustomCalls, + routedCustomToolTargetName, + routedCustomToolWireName, + unwrapRoutedCustomToolArguments, +} from './custom-tool-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const FREEFORM_WRAP_PREFIX = '{"input":"'; +const FREEFORM_WRAP_PREFIX_RE = /^\s*\{\s*"input"\s*:\s*"/; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function partialCustomToolInput(argumentsText) { + const match = FREEFORM_WRAP_PREFIX_RE.exec(argumentsText); + if (!match) return null; + const body = argumentsText.slice(match[0].length); + let output = ''; + for (let index = 0; index < body.length; index++) { + const char = body[index]; + if (char === '"') break; + if (char !== '\\') { + output += char; + continue; + } + const escaped = body[index + 1]; + if (escaped === undefined) break; + index += 1; + if (escaped === 'n') output += '\n'; + else if (escaped === 't') output += '\t'; + else if (escaped === 'r') output += '\r'; + else if (escaped === 'b') output += '\b'; + else if (escaped === 'f') output += '\f'; + else if (escaped === 'u') { + const hex = body.slice(index + 1, index + 5); + if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break; + output += String.fromCharCode(Number.parseInt(hex, 16)); + index += 4; + } else output += escaped; + } + return output; +} + +function replaceSseEventName(block, type) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + let replaced = false; + const next = lines.map(line => { + if (!replaced && line.startsWith('event:')) { + replaced = true; + return `event: ${type}`; + } + return line; + }); + return next.join(newline); +} + +export function createRoutedCustomToolRestoreBlockRewrite( + names, + budget, + repairNames = new Set(), + declaredNames, +) { + const itemNames = new Map(); + const customExecItemNames = new Map(); + const repairItemNames = new Map(); + const ordinaryItemIds = new Set(); + const openCalls = new Map(); + let pendingArguments = []; + let disposed = false; + + const releaseCall = (itemId) => { + const open = openCalls.get(itemId); + if (!open) return; + if (open.retainedBytes > 0) { + budget?.releaseRetained(open.retainedBytes, { kind: 'retained_collectors' }); + } + openCalls.delete(itemId); + }; + + const releaseAll = () => { + if (disposed) return; + disposed = true; + for (const itemId of openCalls.keys()) releaseCall(itemId); + const pendingBytes = pendingArguments.reduce((total, pending) => total + pending.retainedBytes, 0); + if (pendingBytes > 0) { + budget?.releaseRetained(pendingBytes, { kind: 'retained_collectors' }); + } + pendingArguments = []; + itemNames.clear(); + customExecItemNames.clear(); + repairItemNames.clear(); + ordinaryItemIds.clear(); + }; + + const retainPendingArgument = (block, itemId, outputIndex) => { + const retainedBytes = Buffer.byteLength(block, 'utf8'); + if (retainedBytes > 0) budget?.chargeRetained(retainedBytes, { kind: 'retained_collectors' }); + pendingArguments.push({ block, itemId, outputIndex, retainedBytes }); + }; + + const takePendingArguments = (itemId, outputIndex) => { + const matched = []; + const remaining = []; + for (const pending of pendingArguments) { + const matches = pending.itemId !== undefined + ? itemId !== undefined && pending.itemId === itemId + : outputIndex !== undefined && pending.outputIndex === outputIndex; + (matches ? matched : remaining).push(pending); + } + pendingArguments = remaining; + const retainedBytes = matched.reduce((total, pending) => total + pending.retainedBytes, 0); + if (retainedBytes > 0) { + budget?.releaseRetained(retainedBytes, { kind: 'retained_collectors' }); + } + return matched.map(pending => { + if (pending.itemId !== undefined || itemId === undefined) return pending.block; + const payload = sseDataPayload(pending.block); + if (payload === null) return pending.block; + try { + const parsed = JSON.parse(payload); + if (!isPlainObject(parsed)) return pending.block; + return replaceSseDataPayload(pending.block, JSON.stringify({ ...parsed, item_id: itemId })); + } catch { + return pending.block; + } + }); + }; + + const rewrite = (block) => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null || payload === '[DONE]') return [block]; + let parsed; + try { + parsed = JSON.parse(payload); + } catch { + return [block]; + } + if (!isPlainObject(parsed)) return [block]; + + const type = typeof parsed.type === 'string' ? parsed.type : ''; + const outputIndex = typeof parsed.output_index === 'number' + && Number.isInteger(parsed.output_index) + && parsed.output_index >= 0 + ? parsed.output_index + : undefined; + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'custom_tool_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const wireName = routedCustomToolWireName(parsed.item); + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const aliased = targetName !== undefined && targetName !== wireName; + const codeModeExec = targetName === 'exec' && parsed.item.name === 'exec' + && parsed.item.namespace === undefined && declaresCodeModeExec(declaredNames); + if (upstreamItemId && (aliased || codeModeExec)) { + customExecItemNames.set(upstreamItemId, parsed.item.name); + if (type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const repairable = wireName !== undefined && repairNames.has(wireName); + if (upstreamItemId && repairable) repairItemNames.set(upstreamItemId, parsed.item.name); + const restored = repairable || aliased || codeModeExec + ? restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames) + : { value: parsed, changed: false }; + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + } + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'function_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const routed = targetName !== undefined; + const wireName = routedCustomToolWireName(parsed.item); + if (upstreamItemId) { + if (routed) { + itemNames.set(upstreamItemId, { + name: parsed.item.name, + aliased: targetName !== wireName, + ...(typeof parsed.item.namespace === 'string' ? { namespace: parsed.item.namespace } : {}), + }); + ordinaryItemIds.delete(upstreamItemId); + } else { + ordinaryItemIds.add(upstreamItemId); + } + if (routed && type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const pending = takePendingArguments(upstreamItemId, outputIndex); + if (!routed) { + if (type === 'response.output_item.done' && upstreamItemId) ordinaryItemIds.delete(upstreamItemId); + return [...pending, block]; + } + if (upstreamItemId && pending.length > 0 && !openCalls.has(upstreamItemId)) { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const restoredBlock = restored.changed + ? replaceSseDataPayload(block, JSON.stringify(restored.value)) + : block; + const replayed = pending.flatMap(pendingBlock => rewrite(pendingBlock)); + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return type === 'response.output_item.added' + ? [restoredBlock, ...replayed] + : [...replayed, restoredBlock]; + } + + const upstreamItemId = typeof parsed.item_id === 'string' ? parsed.item_id : undefined; + if ( + type === 'response.custom_tool_call_input.delta' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (customExecItemNames.get(upstreamItemId) !== 'exec' + || mayBecomePatchEnvelope(open.argumentsText) + || open.argumentsText.trimStart() === '' + || open.argumentsText.trimStart().startsWith('{')) return []; + const inputDelta = open.argumentsText.slice(open.emittedInput.length); + open.emittedInput = open.argumentsText; + return inputDelta ? [replaceSseDataPayload(block, JSON.stringify({ ...parsed, delta: inputDelta }))] : []; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const source = typeof parsed.input === 'string' + ? parsed.input + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const name = customExecItemNames.get(upstreamItemId); + const helper = name === 'exec' + ? resolveCodeModeHelperName(undefined, name, source, undefined, declaredNames) + : name; + releaseCall(upstreamItemId); + return [replaceSseDataPayload(block, JSON.stringify({ + ...parsed, + input: helper ? compileCodeModeHelperInput(source, helper) : source, + }))]; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && repairItemNames.has(upstreamItemId) + && typeof parsed.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(parsed.input); + if (input !== parsed.input) { + return [replaceSseDataPayload(block, JSON.stringify({ ...parsed, input }))]; + } + } + const argumentEvent = type === 'response.function_call_arguments.delta' + || type === 'response.function_call_arguments.done'; + if (argumentEvent && (!upstreamItemId || (!itemNames.has(upstreamItemId) && !ordinaryItemIds.has(upstreamItemId)))) { + retainPendingArgument(block, upstreamItemId, outputIndex); + return []; + } + if ( + type === 'response.function_call_arguments.delta' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (itemNames.get(upstreamItemId)?.aliased) return []; + if (FREEFORM_WRAP_PREFIX.startsWith(open.argumentsText)) return []; + const fullInput = partialCustomToolInput(open.argumentsText); + if (fullInput === null) return []; + if ( + declaresCodeModeExec(declaredNames) + && itemNames.get(upstreamItemId)?.namespace === undefined + && itemNames.get(upstreamItemId)?.name === 'exec' + && mayBecomePatchEnvelope(fullInput) + ) return []; + if (!fullInput.startsWith(open.emittedInput) || fullInput.length === open.emittedInput.length) return []; + const inputDelta = fullInput.slice(open.emittedInput.length); + open.emittedInput = fullInput; + const nextType = 'response.custom_tool_call_input.delta'; + const next = { + ...parsed, + type: nextType, + item_id: customToolItemId(upstreamItemId), + delta: inputDelta, + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + if ( + type === 'response.function_call_arguments.done' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const nextType = 'response.custom_tool_call_input.done'; + const source = typeof parsed.arguments === 'string' + ? parsed.arguments + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const { arguments: _arguments, ...rest } = parsed; + const itemName = itemNames.get(upstreamItemId); + const helper = itemName?.aliased + ? itemName.name + : resolveCodeModeHelperName(undefined, itemName?.name ?? '', source, itemName?.namespace, declaredNames); + const next = { + ...rest, + type: nextType, + item_id: customToolItemId(upstreamItemId), + input: helper + ? compileCodeModeHelperInput(source, helper) + : unwrapRoutedCustomToolArguments(source, itemName?.name ?? '', itemName?.namespace), + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const terminal = type === 'response.completed' || type === 'response.failed' || type === 'response.incomplete'; + if (terminal) releaseAll(); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + }; + rewrite.dispose = releaseAll; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-function-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-function-tool-repair.mjs new file mode 100644 index 0000000..ae8dabf --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses-function-tool-repair.mjs @@ -0,0 +1,165 @@ +import { + TRANSLATOR_MAX_TURN_BYTES, + TranslatorBudgetExceededError, +} from './translator-budget.mjs'; +import { repairFunctionCalls } from './function-call-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const ENTRY_OVERHEAD_BYTES = 64; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function outputIndexOf(value) { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +export function createResponsesFunctionToolRepairBlockRewrite(schemas, budget) { + if (schemas.size === 0) return block => [block]; + const byId = new Map(); + const byIndex = new Map(); + let pending = []; + let retainedBytes = 0; + let disposed = false; + + const retain = (bytes) => { + if (retainedBytes + bytes > TRANSLATOR_MAX_TURN_BYTES) { + throw new TranslatorBudgetExceededError('retained_collectors', TRANSLATOR_MAX_TURN_BYTES); + } + budget?.chargeRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes += bytes; + }; + const release = (bytes) => { + budget?.releaseRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes -= bytes; + }; + const releaseIdentity = (identity) => { + if (identity.itemId !== undefined) byId.delete(identity.itemId); + if (identity.outputIndex !== undefined) byIndex.delete(identity.outputIndex); + release(identity.bytes); + }; + const dispose = () => { + if (disposed) return; + disposed = true; + release(retainedBytes); + byId.clear(); + byIndex.clear(); + pending = []; + }; + const lookup = (itemId, index) => { + const identity = itemId === undefined ? undefined : byId.get(itemId); + if (identity) return index === undefined || identity.outputIndex === undefined || identity.outputIndex === index ? identity : undefined; + const indexed = index === undefined ? undefined : byIndex.get(index); + return indexed && (itemId === undefined || indexed.itemId === undefined || indexed.itemId === itemId) ? indexed : undefined; + }; + const register = (item, index) => { + const itemId = typeof item.id === 'string' && item.id ? item.id : undefined; + if (itemId === undefined && index === undefined) return undefined; + const previous = new Set(); + if (itemId !== undefined && byId.has(itemId)) previous.add(byId.get(itemId)); + if (index !== undefined && byIndex.has(index)) previous.add(byIndex.get(index)); + for (const identity of previous) releaseIdentity(identity); + const metadata = { + type: item.type, + name: item.name, + ...('namespace' in item ? { namespace: item.namespace } : {}), + ...(item.status !== undefined && item.status !== 'in_progress' && item.status !== 'completed' ? { status: item.status } : {}), + }; + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(JSON.stringify([itemId, index, metadata]), 'utf8'); + retain(bytes); + const identity = { itemId, outputIndex: index, item: metadata, bytes }; + if (itemId !== undefined) byId.set(itemId, identity); + if (index !== undefined) byIndex.set(index, identity); + return identity; + }; + const repairCompletion = (block, event, identity) => { + if (typeof event.arguments !== 'string') return block; + const resolved = (typeof event.item_id !== 'string' || event.item_id === '') && identity.itemId !== undefined + ? { ...event, item_id: identity.itemId } + : event; + const repaired = repairFunctionCalls({ ...identity.item, status: identity.item.status ?? 'completed', arguments: event.arguments }, schemas); + if (repaired.changed && isObject(repaired.value)) { + return replaceSseDataPayload(block, JSON.stringify({ ...resolved, arguments: repaired.value.arguments })); + } + return resolved === event ? block : replaceSseDataPayload(block, JSON.stringify(resolved)); + }; + const flushPending = (identity) => { + const output = []; + const remaining = []; + for (const completion of pending) { + const matches = completion.itemId !== undefined + ? completion.itemId === identity.itemId + && (completion.outputIndex === undefined || identity.outputIndex === undefined || completion.outputIndex === identity.outputIndex) + : completion.outputIndex !== undefined && completion.outputIndex === identity.outputIndex; + if (!matches) { remaining.push(completion); continue; } + release(completion.bytes); + const payload = sseDataPayload(completion.block); + const event = payload === null ? undefined : JSON.parse(payload); + output.push(isObject(event) ? repairCompletion(completion.block, event, identity) : completion.block); + } + pending = remaining; + return output; + }; + + const rewrite = block => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null) return [block]; + if (payload === '[DONE]') { + const unfinished = pending.map(entry => entry.block); + dispose(); + return [...unfinished, block]; + } + let event; + try { event = JSON.parse(payload); } catch { return [block]; } + if (!isObject(event)) return [block]; + const index = outputIndexOf(event.output_index); + const itemId = typeof event.item_id === 'string' && event.item_id ? event.item_id : undefined; + try { + if ((event.type === 'response.output_item.added' || event.type === 'response.output_item.done') && isObject(event.item)) { + const identity = register(event.item, index); + const replayed = identity ? flushPending(identity) : []; + const repaired = repairFunctionCalls(event, schemas); + const output = repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block; + if (identity && (event.type === 'response.output_item.done' || replayed.length > 0)) releaseIdentity(identity); + return event.type === 'response.output_item.added' ? [output, ...replayed] : [...replayed, output]; + } + if (event.type === 'response.function_call_arguments.done' && typeof event.arguments === 'string') { + const identity = lookup(itemId, index); + if (identity) { + const output = repairCompletion(block, event, identity); + releaseIdentity(identity); + return [output]; + } + if (itemId !== undefined || index !== undefined) { + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(block, 'utf8'); + retain(bytes); + pending.push({ block, itemId, outputIndex: index, bytes }); + return []; + } + } + if (typeof event.type === 'string' && ['response.completed', 'response.failed', 'response.incomplete', 'response.cancelled'].includes(event.type)) { + const replayed = []; + if (event.type === 'response.completed' && isObject(event.response) && Array.isArray(event.response.output) + && (event.response.status === undefined || event.response.status === 'completed')) { + for (const [slot, item] of event.response.output.entries()) { + if (!isObject(item)) continue; + const identity = register(item, slot); + if (identity) replayed.push(...flushPending(identity)); + } + } + replayed.push(...pending.map(entry => entry.block)); + const repaired = repairFunctionCalls(event, schemas); + dispose(); + return [...replayed, repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block]; + } + return [block]; + } catch (error) { + dispose(); + throw error; + } + }; + rewrite.dispose = dispose; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses.mjs new file mode 100644 index 0000000..b0155d5 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/responses.mjs @@ -0,0 +1,159 @@ +import { Transform } from 'node:stream'; +import { StringDecoder } from 'node:string_decoder'; +import { stripCanonicalOnlyToolFields } from './tool-groups.mjs'; +import { + collectSelfNamedNamespaceScrubAuthorization, + createSelfNamedToolCallNamespaceScrubRewrite, + scrubSelfNamedToolCallNamespaceInJson, +} from './self-named-namespace-scrub.mjs'; +import { rewriteRoutedCustomToolsForUpstream, restoreRoutedCustomCallsInJson } from './custom-tool-compat.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream, restoreRoutedNamespaceCallsInJson } from './namespace-tool-compat.mjs'; +import { collectFunctionCallRepairSchemas, repairFunctionCallsInJson } from './function-call-compat.mjs'; +import { createRoutedCustomToolRestoreBlockRewrite } from './responses-custom-tool-repair.mjs'; +import { createResponsesFunctionToolRepairBlockRewrite } from './responses-function-tool-repair.mjs'; +import { createTranslatorBudget } from './translator-budget.mjs'; +import { collectDeclaredWireToolNames } from './undeclared-tool-guard.mjs'; +import { composeSseBlockRewrites, payloadRewriteAsBlockRewrite, nextSseBlock } from './sse-payload-rewrite.mjs'; + +/** Partial fix control: disambiguates colliding wire names, but omits dotted/qualified custom alias restoration, logical-name guards, and selected-only self-named scrub. */ +export function prepareResponsesCompatibility(body, policy = {}) { + const namespace = policy.namespaceTools === 'functions' + ? rewriteRoutedNamespaceToolsForUpstream(body, undefined, true) + : { body, aliases: new Map(), declarations: new Map() }; + const passthroughNames = new Set(['apply_patch']); + for (const [wireName, identity] of namespace.declarations) { + if (identity.kind === 'custom' && identity.name === 'apply_patch') passthroughNames.add(wireName); + } + const custom = policy.customTools && policy.customTools !== 'native' + ? rewriteRoutedCustomToolsForUpstream(namespace.body, policy.customTools === 'functions' ? false : undefined, passthroughNames) + : { body: namespace.body, names: new Set(), repairNames: new Set() }; + const schemas = policy.repairFunctionArguments ? collectFunctionCallRepairSchemas(body) : new Map(); + // Incomplete: only inspects lowered namespace.body, dropping original logical conflict guards. + const declared = collectDeclaredWireToolNames(namespace.body); + const functionWireNames = new Set(); + for (const schema of schemas.values()) { + if (!schema.namespace) functionWireNames.add(schema.name); + else for (const [wireName, identity] of namespace.aliases) { + if (identity.namespace === schema.namespace && identity.name === schema.name) functionWireNames.add(wireName); + } + } + const scrubAuthorization = collectSelfNamedNamespaceScrubAuthorization( + namespace.body, + new Set([...custom.names, ...custom.repairNames]), + functionWireNames, + ); + const restoreNamespace = (text) => restoreRoutedNamespaceCallsInJson(text, namespace.aliases); + return { + body: policy.namespaceTools === 'functions' ? stripCanonicalOnlyToolFields(custom.body, false) : custom.body, + needsResponseTransform: custom.names.size > 0 || custom.repairNames.size > 0 || namespace.aliases.size > 0 || schemas.size > 0, + restoreJson(text) { + let next = scrubSelfNamedToolCallNamespaceInJson(text, scrubAuthorization); + next = restoreRoutedCustomCallsInJson(next, custom.names, custom.repairNames, declared); + next = restoreNamespace(next); + next = repairFunctionCallsInJson(next, schemas); + return next; + }, + createStreamRewrite() { + const budget = createTranslatorBudget(); + const stages = [ + payloadRewriteAsBlockRewrite(createSelfNamedToolCallNamespaceScrubRewrite(scrubAuthorization)), + createRoutedCustomToolRestoreBlockRewrite(custom.names, budget, custom.repairNames, declared), + payloadRewriteAsBlockRewrite(restoreNamespace), + createResponsesFunctionToolRepairBlockRewrite(schemas, budget), + ]; + const rewrite = composeSseBlockRewrites(...stages); + const dispose = rewrite.dispose; + rewrite.dispose = () => { dispose?.(); budget.dispose(); }; + return rewrite; + }, + }; +} + +const MAX_RESPONSE_BYTES = 32 * 1024 * 1024; + +class CompatibilityResponseTransform extends Transform { + constructor(prepared, sse) { + super(); + this.prepared = prepared; + this.sse = sse; + this.decoder = new StringDecoder('utf8'); + this.buffer = ''; + this.rewrite = sse ? prepared.createStreamRewrite() : undefined; + } + + drain(final = false) { + if (this.sse) { + let frame; + while ((frame = nextSseBlock(this.buffer))) { + if (Buffer.byteLength(frame.block) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.buffer = frame.rest; + for (const block of this.rewrite(frame.block)) this.push(block + frame.delimiter); + } + if (final && this.buffer) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + for (const block of this.rewrite(this.buffer)) this.push(block + '\n\n'); + this.buffer = ''; + } + } else if (final) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.push(this.prepared.restoreJson(this.buffer)); + this.buffer = ''; + } + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + } + + _transform(chunk, _encoding, callback) { + try { + this.buffer += this.decoder.write(chunk); + this.drain(); + callback(); + } catch (error) { + callback(error); + } + } + + _flush(callback) { + try { + this.buffer += this.decoder.end(); + this.drain(true); + callback(); + } catch (error) { + callback(error); + } + } + + _destroy(error, callback) { + this.buffer = ''; + this.rewrite?.dispose?.(); + callback(error); + } +} + +export function createResponsesCompatibilityAdapter(policy = {}) { + const pending = new Map(); + return { + adaptRequest(body, requestId, overrides = {}) { + pending.delete(requestId); + const now = Date.now(); + for (const [id, entry] of pending) if (now - entry.at >= 15 * 60_000) pending.delete(id); + if (!pending.has(requestId) && pending.size >= 256) throw new Error('too many in-flight compatibility requests'); + const prepared = prepareResponsesCompatibility(body, { ...policy, ...overrides }); + if (prepared.needsResponseTransform) pending.set(requestId, { prepared, at: now }); + return prepared.body === body ? null : prepared.body; + }, + releaseResponse(requestId) { + pending.delete(requestId); + }, + createResponseTransform(requestId, response) { + const entry = pending.get(requestId); + pending.delete(requestId); + if (!entry) return null; + const encoding = (response.contentEncoding ?? '').trim().toLowerCase(); + if (encoding && encoding !== 'identity') throw new Error('compressed compatibility response cannot be rewritten'); + const type = (response.contentType ?? '').toLowerCase(); + const sse = type.startsWith('text/event-stream'); + if (!sse && !type.includes('application/json')) throw new Error('unsupported compatibility response content type'); + return new CompatibilityResponseTransform(entry.prepared, sse); + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/self-named-namespace-scrub.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/self-named-namespace-scrub.mjs new file mode 100644 index 0000000..d4c7800 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/self-named-namespace-scrub.mjs @@ -0,0 +1,149 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + specs, +) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) { + if (!isPlainObject(inner) || typeof inner.name !== 'string') continue; + if (namespace !== 'functions' && namespace === inner.name) { + if (inner.type === 'custom') sameNameNamespacedCustomNames.add(inner.name); + else if (inner.type === 'function') sameNameNamespacedFunctionNames.add(inner.name); + } + if (namespace === 'functions') { + if (inner.type === 'custom') bareCustomNames.add(inner.name); + else if (inner.type === 'function') bareFunctionNames.add(inner.name); + } + } + continue; + } + const nestedFunction = spec.type === 'function' && isPlainObject(spec.function) ? spec.function : undefined; + const name = typeof spec.name === 'string' && spec.name.length > 0 + ? spec.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; + if (!name) continue; + const namespace = typeof spec.namespace === 'string' ? spec.namespace : undefined; + if (namespace !== 'functions' && namespace === name) { + if (spec.type === 'custom') sameNameNamespacedCustomNames.add(name); + else if (spec.type === 'function') sameNameNamespacedFunctionNames.add(name); + } + if (!namespace || namespace === 'functions') { + if (spec.type === 'custom') bareCustomNames.add(name); + else if (spec.type === 'function') bareFunctionNames.add(name); + } + } +} + +export function collectSelfNamedNamespaceScrubAuthorization( + body, + authorizedBareCustomToolNames, + authorizedBareFunctionToolNames, +) { + const bareCustomNames = new Set(); + const bareFunctionNames = new Set(); + const sameNameNamespacedCustomNames = new Set(); + const sameNameNamespacedFunctionNames = new Set(); + if (isPlainObject(body)) { + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + body.tools, + ); + if (Array.isArray(body.input)) { + for (const item of body.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) { + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + item.tools, + ); + } + } + } + } + const authorizedCustomNames = [...bareCustomNames] + .filter(name => authorizedBareCustomToolNames.has(name)); + const authorizedFunctionNames = new Set([ + ...authorizedCustomNames, + ...[...bareFunctionNames].filter(name => authorizedBareFunctionToolNames.has(name)), + ]); + return { + customToolCallNames: new Set( + authorizedCustomNames.filter(name => !sameNameNamespacedCustomNames.has(name)), + ), + functionCallNames: new Set( + [...authorizedFunctionNames].filter(name => !sameNameNamespacedFunctionNames.has(name)), + ), + }; +} + +export function scrubSelfNamedToolCallNamespace(value, authorization) { + if (Array.isArray(value)) { + let changed = false; + const out = value.map(entry => { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: out, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + let changed = false; + const out = {}; + for (const [key, entry] of Object.entries(value)) { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + out[key] = result.value; + changed ||= result.changed; + } + const authorizedNames = value.type === 'custom_tool_call' + ? authorization.customToolCallNames + : value.type === 'function_call' + ? authorization.functionCallNames + : undefined; + if ( + authorizedNames + && typeof value.name === 'string' + && value.name.length > 0 + && value.namespace === value.name + && authorizedNames.has(value.name) + ) { + delete out.namespace; + changed = true; + } + return changed ? { value: out, changed: true } : { value, changed: false }; +} + +export function scrubSelfNamedToolCallNamespaceInJson(text, authorization) { + if (!text.includes('"namespace"')) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const result = scrubSelfNamedToolCallNamespace(payload, authorization); + return result.changed ? JSON.stringify(result.value) : text; +} + +export function createSelfNamedToolCallNamespaceScrubRewrite(authorization) { + return payload => scrubSelfNamedToolCallNamespaceInJson(payload, authorization); +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/sse-payload-rewrite.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/sse-payload-rewrite.mjs new file mode 100644 index 0000000..4798585 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/sse-payload-rewrite.mjs @@ -0,0 +1,74 @@ +/** Adapt a payload rewrite to the block contract (replace only on change). */ +export function payloadRewriteAsBlockRewrite(rewrite) { + return (block) => { + const payload = sseDataPayload(block); + if (payload === null) return [block]; + const rewritten = rewrite(payload); + return rewritten !== payload ? [replaceSseDataPayload(block, rewritten)] : [block]; + }; +} + +/** Chain block rewrites: every block stage N emits feeds stage N+1. */ +export function composeSseBlockRewrites(...rewrites) { + const active = rewrites.filter(Boolean); + if (active.length === 0) return Object.assign((block) => [block], {}); + const composed = (block) => { + let blocks = [block]; + for (const rewrite of active) { + const next = []; + for (const current of blocks) next.push(...rewrite(current)); + blocks = next; + } + return blocks; + }; + let disposed = false; + composed.dispose = () => { + if (disposed) return; + disposed = true; + for (const rewrite of active) { + try { rewrite.dispose?.(); } catch { /* teardown must not throw */ } + } + }; + return composed; +} + +/** Split one complete SSE event block while retaining its original blank-line delimiter. */ +export function nextSseBlock(buffer) { + const match = buffer.match(/\r?\n\r?\n/); + if (!match || match.index === undefined) return null; + return { + block: buffer.slice(0, match.index), + delimiter: match[0], + rest: buffer.slice(match.index + match[0].length), + }; +} + +/** Join all data lines from one SSE event according to the event-stream field rules. */ +export function sseDataPayload(block) { + const data = []; + for (const line of block.split(/\r?\n/)) { + if (!line.startsWith('data:')) continue; + const value = line.slice(5); + data.push(value.startsWith(' ') ? value.slice(1) : value); + } + return data.length > 0 ? data.join('\n') : null; +} + +/** Replace an SSE event's data field while preserving non-data fields and newline style. */ +export function replaceSseDataPayload(block, payload) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + const rewritten = []; + let replaced = false; + for (const line of lines) { + if (!line.startsWith('data:')) { + rewritten.push(line); + continue; + } + if (!replaced) { + rewritten.push(`data: ${payload}`); + replaced = true; + } + } + return replaced ? rewritten.join(newline) : block; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-argument-integers.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-argument-integers.mjs new file mode 100644 index 0000000..9164255 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-argument-integers.mjs @@ -0,0 +1,130 @@ +function asSchema(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined; +} + +function declaresInteger(schema) { + const type = schema.type; + if (type === 'integer') return true; + return Array.isArray(type) && type.includes('integer'); +} + +function declaresString(schema) { + const type = schema.type; + if (type === 'string') return true; + return Array.isArray(type) && type.includes('string'); +} + +const U64_NUMBER_FIELDS = new Set(['timeout_ms']); +const U64_NUMBER_FIELDS_BY_TOOL = new Map([ + ['wait', new Set(['yield_time_ms', 'max_tokens'])], +]); + +function declaresNumeric(schema) { + const type = schema.type; + if (type === 'integer' || type === 'number') return true; + return Array.isArray(type) && (type.includes('integer') || type.includes('number')); +} + +function resolveRef(schema, root, seen) { + const ref = schema.$ref; + if (typeof ref !== 'string' || !ref.startsWith('#/')) return schema; + if (seen.has(ref)) return undefined; + seen.add(ref); + let node = root; + for (const rawSegment of ref.slice(2).split('/')) { + const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~'); + const current = asSchema(node); + if (!current) return undefined; + node = current[segment]; + } + const resolved = asSchema(node); + return resolved ? resolveRef(resolved, root, seen) : undefined; +} + +const COMPOSITION_KEYS = ['anyOf', 'oneOf', 'allOf']; + +function compositionBranches(schema) { + const branches = []; + for (const key of COMPOSITION_KEYS) { + const value = schema[key]; + if (!Array.isArray(value)) continue; + for (const branch of value) { + const node = asSchema(branch); + if (node) branches.push(node); + } + } + return branches; +} + +function safelyIntegral(value) { + return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; +} + +function coerceValue(value, schema, root, depth, toolName, propertyName) { + if (depth > 64) return { value, changed: false }; + const resolved = schema ? resolveRef(schema, root, new Set()) : undefined; + + if (typeof value === 'number') { + if (!resolved) return { value, changed: false }; + const branches = compositionBranches(resolved); + const nativeU64Field = propertyName !== undefined + && ( + U64_NUMBER_FIELDS.has(propertyName) + || U64_NUMBER_FIELDS_BY_TOOL.get(toolName ?? '')?.has(propertyName) === true + ); + const nativeU64Declared = nativeU64Field + && (declaresNumeric(resolved) || branches.some(declaresNumeric)); + const integerDeclared = declaresInteger(resolved) + || branches.some(declaresInteger) + || nativeU64Declared; + if (!integerDeclared && safelyIntegral(value)) { + const stringDeclared = declaresString(resolved) || branches.some(declaresString); + const numericDeclared = declaresNumeric(resolved) || branches.some(declaresNumeric); + if (stringDeclared && !numericDeclared) { + return { value: String(value), changed: true }; + } + } + if (!integerDeclared || !safelyIntegral(value)) return { value, changed: false }; + return { value, changed: true }; + } + + if (Array.isArray(value)) { + const itemSchema = resolved ? asSchema(resolved.items) : undefined; + let changed = false; + const next = value.map(entry => { + const result = coerceValue(entry, itemSchema, root, depth + 1, toolName); + if (result.changed) changed = true; + return result.value; + }); + return changed ? { value: next, changed: true } : { value, changed: false }; + } + + const object = asSchema(value); + if (!object) return { value, changed: false }; + + const properties = resolved ? asSchema(resolved.properties) : undefined; + const additional = resolved ? asSchema(resolved.additionalProperties) : undefined; + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(object)) { + const childSchema = asSchema(properties?.[key]) ?? additional; + const result = coerceValue(entry, childSchema, root, depth + 1, toolName, key); + if (result.changed) changed = true; + next[key] = result.value; + } + return changed ? { value: next, changed: true } : { value, changed: false }; +} + +export function coerceIntegerToolArguments(args, parameters, toolName) { + if (!parameters || !args) return args; + if (!/\d/.test(args)) return args; + let parsed; + try { + parsed = JSON.parse(args); + } catch { + return args; + } + const result = coerceValue(parsed, parameters, parameters, 0, toolName); + if (!result.changed) return args; + return JSON.stringify(result.value); +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-groups.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-groups.mjs new file mode 100644 index 0000000..5b62304 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-groups.mjs @@ -0,0 +1,65 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** Collect top-level and Responses Lite tool containers without altering their order. */ +export function collectResponsesToolGroups(body) { + if (!isPlainObject(body)) return []; + + const groups = []; + if (Array.isArray(body.tools)) groups.push(body.tools); + if (!Array.isArray(body.input)) return groups; + + for (const item of body.input) { + if (isPlainObject(item) && item.type === 'additional_tools' && Array.isArray(item.tools)) { + groups.push(item.tools); + } + } + return groups; +} + +export const CANONICAL_ONLY_TOOL_FIELDS = [ + { field: 'external_web_access', toolTypes: new Set(['web_search', 'web_search_preview']), capabilityGated: true }, + { field: 'defer_loading' }, +]; + +export function stripCanonicalOnlyToolFields(body, includeCapabilityGated) { + if (!isPlainObject(body)) return body; + + const rewriteTools = (tools) => { + let changed = false; + const rewritten = tools.map(tool => { + if (!isPlainObject(tool)) return tool; + let next = tool; + for (const { field, toolTypes, capabilityGated } of CANONICAL_ONLY_TOOL_FIELDS) { + if (capabilityGated && !includeCapabilityGated) continue; + if (!Object.hasOwn(next, field)) continue; + if (toolTypes && (typeof next.type !== 'string' || !toolTypes.has(next.type))) continue; + const { [field]: _private, ...rest } = next; + next = rest; + } + if (next === tool) return tool; + changed = true; + return next; + }); + return changed ? rewritten : tools; + }; + + let rewrittenBody = body; + if (Array.isArray(body.tools)) { + const tools = rewriteTools(body.tools); + if (tools !== body.tools) rewrittenBody = { ...rewrittenBody, tools }; + } + if (!Array.isArray(body.input)) return rewrittenBody; + + let input; + for (let index = 0; index < body.input.length; index += 1) { + const item = body.input[index]; + if (!isPlainObject(item) || item.type !== 'additional_tools' || !Array.isArray(item.tools)) continue; + const tools = rewriteTools(item.tools); + if (tools === item.tools) continue; + input ??= [...body.input]; + input[index] = { ...item, tools }; + } + return input ? { ...rewrittenBody, input } : rewrittenBody; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-name-aliases.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-name-aliases.mjs new file mode 100644 index 0000000..587befb --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tool-name-aliases.mjs @@ -0,0 +1,68 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** + * A dotted spelling is a safe alias only when it cannot ALSO be read as some other identity's + * canonical `ns__name`. + */ +export function dottedAliasIsUnambiguous(namespace, name) { + return !namespace.includes('__') && !name.includes('__'); +} + +export function wireToolInnerName(tool) { + if (!isPlainObject(tool)) return undefined; + const nestedFunction = tool.type === 'function' && isPlainObject(tool.function) + ? tool.function + : undefined; + return typeof tool.name === 'string' && tool.name.length > 0 + ? tool.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; +} + +/** + * Dotted aliases that more than one declared identity would claim, plus dotted aliases that + * collide with a canonical or bare declared name. + */ +export function collectAmbiguousDottedAliases(specGroups) { + const owners = new Map(); + const claim = (alias, identity) => { + const owner = owners.get(alias); + if (owner === undefined) owners.set(alias, identity); + else if (owner !== identity) owners.set(alias, null); + }; + for (const specs of specGroups) { + if (!Array.isArray(specs)) continue; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + if (!namespace) continue; + for (const inner of spec.tools) { + const name = wireToolInnerName(inner); + if (!name) continue; + if (namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + claim(name, JSON.stringify([undefined, name])); + continue; + } + const identity = JSON.stringify([namespace, name]); + claim(dottedToolName(namespace, name), identity); + claim(namespacedToolName(namespace, name), identity); + claim(name, identity); + } + continue; + } + const name = wireToolInnerName(spec); + if (name) claim(name, JSON.stringify([undefined, name])); + } + } + const ambiguous = new Set(); + for (const [alias, owner] of owners) if (owner === null) ambiguous.add(alias); + return ambiguous; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tools.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tools.mjs new file mode 100644 index 0000000..203b692 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/tools.mjs @@ -0,0 +1,33 @@ +export function namespacedToolName(namespace, name) { + return namespace ? `${namespace}__${name}` : name; +} + +export function dottedToolName(namespace, name) { + return namespace ? `${namespace}.${name}` : name; +} + +const LEGACY_SHELL_BRIDGE_TOOL_NAMES = ['exec_command', 'shell_command']; +const CODE_MODE_HELPER_TOOL_NAMES = [ + ...LEGACY_SHELL_BRIDGE_TOOL_NAMES, + 'write_stdin', + 'apply_patch', +]; + +export const CODE_MODE_EXEC_TOOL_NAME = 'exec'; + +export function normalizeDeclaredToolName(name, declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return name; + if (declared.has(name)) return name; + if (name === 'apply_patch') return CODE_MODE_EXEC_TOOL_NAME; + if (LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy))) { + return name; + } + return CODE_MODE_HELPER_TOOL_NAMES.includes(name) + ? CODE_MODE_EXEC_TOOL_NAME + : name; +} + +export function declaresCodeModeExec(declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return false; + return !LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy)); +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/translator-budget.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/translator-budget.mjs new file mode 100644 index 0000000..1f11b9f --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/translator-budget.mjs @@ -0,0 +1,34 @@ +export const TRANSLATOR_MAX_TURN_BYTES = 16 * 1024 * 1024; +export const TRANSLATOR_MAX_CALL_ARGUMENT_BYTES = 8 * 1024 * 1024; + +export class TranslatorBudgetExceededError extends Error { + constructor(kind, limit) { + super(`translator buffer limit exceeded (${kind}: ${limit} bytes)`); + this.name = 'TranslatorBudgetExceededError'; + this.kind = kind; + this.limit = limit; + } +} + +export function createTranslatorBudget(options = {}) { + const maxTurnBytes = options.maxTurnBytes ?? TRANSLATOR_MAX_TURN_BYTES; + let charged = 0; + let disposed = false; + return { + chargeRetained(bytes, scope = { kind: 'retained_collectors' }) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + if (charged + bytes > maxTurnBytes) { + throw new TranslatorBudgetExceededError(scope.kind ?? 'retained_collectors', maxTurnBytes); + } + charged += bytes; + }, + releaseRetained(bytes) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + charged = Math.max(0, charged - bytes); + }, + dispose() { + disposed = true; + charged = 0; + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/undeclared-tool-guard.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/undeclared-tool-guard.mjs new file mode 100644 index 0000000..0cea492 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/src/undeclared-tool-guard.mjs @@ -0,0 +1,59 @@ +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from './tool-name-aliases.mjs'; +import { + CODE_MODE_EXEC_TOOL_NAME, + dottedToolName, + namespacedToolName, +} from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function addWireToolName(names, tool, namespace, ambiguousDottedAliases) { + if (!isPlainObject(tool)) return; + const name = wireToolInnerName(tool); + if (!name) return; + if (!namespace || namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + names.add(name); + return; + } + names.add(namespacedToolName(namespace, name)); + const dotted = dottedToolName(namespace, name); + if (dottedAliasIsUnambiguous(namespace, name) && !ambiguousDottedAliases?.has(dotted)) { + names.add(dotted); + } + if (name !== CODE_MODE_EXEC_TOOL_NAME) names.add(name); +} + +function addWireToolSpecs(names, specs, ambiguousDottedAliases) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases); + continue; + } + addWireToolName(names, spec, undefined, ambiguousDottedAliases); + } +} + +/** Tool names the outbound Responses body actually declared. */ +export function collectDeclaredWireToolNames(body) { + const names = new Set(); + if (!isPlainObject(body)) return names; + const specGroups = [body.tools]; + if (Array.isArray(body.input)) { + for (const item of body.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) specGroups.push(item.tools); + } + } + const ambiguousDottedAliases = collectAmbiguousDottedAliases(specGroups); + for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases); + return names; +} diff --git a/questions/codex-namespace-tool-collision/v1/controls/incomplete/tests/smoke.test.mjs b/questions/codex-namespace-tool-collision/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..bcf1887 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,121 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + createResponsesCompatibilityAdapter, + prepareResponsesCompatibility, +} from '../src/responses.mjs'; + +async function runTransform(transform, input) { + let out = ''; + transform.setEncoding('utf8'); + transform.on('data', (chunk) => { out += chunk; }); + const done = new Promise((resolve, reject) => { + transform.on('end', () => resolve(out)); + transform.on('error', reject); + }); + transform.end(input); + return done; +} + +test('lowers and restores ordinary non-colliding namespace function tools (JSON & SSE)', async () => { + const adapter = createResponsesCompatibilityAdapter({ + customTools: 'preserve-apply-patch', + namespaceTools: 'functions', + repairFunctionArguments: true, + }); + const body = { + tools: [ + { + type: 'namespace', + name: 'weather', + tools: [ + { + type: 'function', + name: 'forecast', + defer_loading: true, + parameters: { type: 'object', properties: { days: { type: 'integer' } } }, + }, + ], + }, + ], + tool_choice: { type: 'function', namespace: 'weather', name: 'forecast' }, + }; + const adapted = adapter.adaptRequest(body, 1); + assert.equal(adapted.tools.length, 1); + assert.equal(adapted.tools[0].name, 'weather__forecast'); + assert.equal('defer_loading' in adapted.tools[0], false); + assert.deepEqual(adapted.tool_choice, { type: 'function', name: 'weather__forecast' }); + + const jsonWire = JSON.stringify({ + status: 'completed', + output: [{ type: 'function_call', name: 'weather__forecast', call_id: 'c1', arguments: '{"days":3.0}' }], + }); + const restoredJson = JSON.parse(await runTransform( + adapter.createResponseTransform(1, { contentType: 'application/json', contentEncoding: '' }), + jsonWire, + )); + assert.deepEqual(restoredJson.output[0], { + type: 'function_call', + namespace: 'weather', + name: 'forecast', + call_id: 'c1', + arguments: '{"days":3}', + }); +}); + +test('lowers and restores ordinary custom tools and preserves apply_patch passthrough', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { type: 'custom', name: 'apply_patch', description: 'Patch files' }, + { type: 'custom', name: 'run_script', description: 'Run script' }, + ], + }, + { customTools: 'preserve-apply-patch', namespaceTools: 'functions', repairFunctionArguments: true }, + ); + assert.equal(prepared.body.tools[0].type, 'custom'); + assert.equal(prepared.body.tools[1].type, 'function'); + + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + output: [ + { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'run_script', arguments: '{"input":"echo hi"}' }, + ], + }))); + assert.deepEqual(restored.output[0], { + type: 'custom_tool_call', + id: 'ctc_1', + call_id: 'call_1', + name: 'run_script', + input: 'echo hi', + }); +}); + +test('repairs ordinary integer-float and bare-integer-to-string arguments without altering non-integral floats', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { + type: 'function', + name: 'cell_read', + parameters: { + type: 'object', + properties: { + cell_id: { type: 'string' }, + limit: { type: 'integer' }, + ratio: { type: 'integer' }, + }, + }, + }, + ], + }, + { repairFunctionArguments: true }, + ); + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + status: 'completed', + output: [ + { type: 'function_call', name: 'cell_read', arguments: '{"cell_id":4,"limit":10.0,"ratio":1.5}' }, + ], + }))); + assert.equal(restored.output[0].arguments, '{"cell_id":"4","limit":10,"ratio":1.5}'); +}); diff --git a/questions/codex-namespace-tool-collision/v1/question.json b/questions/codex-namespace-tool-collision/v1/question.json new file mode 100644 index 0000000..d90f309 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/question.json @@ -0,0 +1,70 @@ +{ + "id": "codex-namespace-tool-collision", + "revision": "v1", + "scoringVersion": "capability-ratio-v1", + "title": "Codex Namespace 工具重名消解与响应还原兼容", + "status": "calibrated", + "changeNote": "Eval Bank v2 complex root-cause question extracted from makecindy/cindy PR #14563 (793ac48b27b5).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "793ac48b27b5ca2bf648c7bf4d6f3158db324d7b", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "collision_disambiguation", + "weight": "3/10", + "mode": "ratio", + "items": [ + "collide_roundtrip_json_sse", + "collide_selector_kind_and_apply_patch", + "collide_reservations_and_order", + "collide_native_schema_repair" + ] + }, + { + "id": "dotted_custom_alias", + "weight": "1/4", + "mode": "ratio", + "items": [ + "dotted_custom_restoration", + "qualified_custom_alias_restoration", + "sse_incremental_custom_aliases", + "explicit_coordinate_precedence" + ] + }, + { + "id": "logical_name_guard", + "weight": "1/5", + "mode": "ratio", + "items": [ + "logical_apply_patch_conflict_guard", + "lowered_custom_self_named_conflict" + ] + }, + { + "id": "selected_self_named_scrub", + "weight": "3/20", + "mode": "ratio", + "items": [ + "selected_only_scrub_scope", + "inline_namespace_conservative_guard" + ] + }, + { + "id": "baseline_regression_guard", + "weight": "1/10", + "mode": "all", + "items": [ + "baseline_non_colliding_namespace", + "baseline_function_arg_repair" + ] + } + ] +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/CONTRACT.md b/questions/codex-namespace-tool-collision/v1/reference/CONTRACT.md new file mode 100644 index 0000000..85b9d28 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/CONTRACT.md @@ -0,0 +1,37 @@ +# Product & Protocol Contract + +## 1. Public Entrypoints (`src/responses.mjs`) + +- `prepareResponsesCompatibility(body, policy)`: + - `policy`: `{ namespaceTools?: 'native' | 'functions', customTools?: 'native' | 'functions' | 'preserve-apply-patch', repairFunctionArguments?: boolean }`. + - Returns `{ body, needsResponseTransform, restoreJson(text), createStreamRewrite() }`. +- `createResponsesCompatibilityAdapter(policy)`: + - Returns `{ adaptRequest(body, requestId, overrides?), releaseResponse(requestId), createResponseTransform(requestId, { contentType, contentEncoding }) }` supporting `application/json` and `text/event-stream`. + +## 2. Namespace Lowering & Collision Disambiguation (`namespaceTools: 'functions'`) + +- Top-level declarations (both flat `{ type, name }` and Chat-shaped nested `{ type: 'function', function: { name } }`) and children of the reserved `functions` namespace own their literal bare wire names regardless of declaration order across `tools` and `input[].additional_tools`. Duplicate declarations of the same logical tool deduplicate cleanly. +- Non-`functions` namespace children `(ns, name)` default to wire name `__`. When a wire name collides with a distinct logical tool, `prepareResponsesCompatibility` disambiguates deterministically (`_2`, `_3`, … capped at 64 chars: `prefix.slice(0, 64 - tail.length) + tail`) without hijacking any declared bare name, namespace child's logical name, or default flattened name across `tools` and `additional_tools`. +- Direct calls to `rewriteRoutedNamespaceToolsForUpstream(body)` default to `disambiguate = false` (throwing `NamespaceToolCollisionError` on collisions); passing `disambiguate = true` enables disambiguation. +- `tool_choice` (direct `{ type, name, namespace? }` and `allowed_tools`) and replayed `input` tool calls rewrite consistently to allocated wire names and drop private `namespace` fields. Authorization strictly matches original declared kinds (`function` vs `custom`). +- Under `customTools: 'preserve-apply-patch'`, any custom tool whose original logical name is `apply_patch` (even if namespaced and disambiguated) remains `type: 'custom'`; under `customTools: 'functions'`, all custom tools convert to `type: 'function'`. +- Canonical-only fields (`defer_loading`) are stripped from `tools` and `input[].additional_tools` when lowering. + +## 3. Round-Trip Restoration (JSON & Incremental SSE Parity) + +- Converted custom tools restore from `function_call` to `custom_tool_call` (`fc_` → `ctc_`, `{ "input": "..." }` unwrapped; incremental SSE emits `custom_tool_call` + `custom_tool_call_input` without leaking raw `function_call_arguments` deltas) across: + - the allocated wire name, + - unambiguous authorized dotted aliases (`.` when neither segment contains `__`, non-ambiguous across the catalog, and not declared as a bare tool), and + - provider echoes retaining matching `namespace` alongside original name, allocated wire name, or dotted alias. +- Calls with a non-matching `namespace` or unrelated bare names (e.g. `a__a__b_2`) remain untouched. +- If a call carries an explicit `(namespace, name)` matching an authorized declared namespace tool, that explicit declared identity takes precedence over another tool's alias spelling. + +## 4. Conflict Guards & Native-Namespace Repair + +- **Code Mode helper guard**: Helper rerouting toward bare custom `exec` must respect declared logical names (both unlowered and lowered, across `tools` and `additional_tools`) so declaring a namespaced `apply_patch` protects bare `apply_patch` from being rerouted to `exec`. +- **Self-named namespace scrubbing**: Strips redundant `namespace: x` from `{ name: x, namespace: x }` when bare `x` is authorized and no active same-name namespace conflict `(x, x)` exists. + - Must account for both original and lowered catalogs, including same-name namespaced `custom` tools that arrive upstream as `function_call`. + - Under `namespaceTools: 'functions'`, a same-name `type: 'namespace'` group declaration blocks scrubbing ONLY if authorized/selected by the turn's `tool_choice`; inline `spec.namespace` declarations retain the conservative guard. +- **Native-namespace argument repair (`namespaceTools: 'native'`, `repairFunctionArguments: true`)**: + - Request declarations pass through unchanged. + - Argument repair applies each tool's own schema keyed by exact `(namespace, name)` identity so bare `ns__name` and namespaced `(ns, name)` never cross-contaminate. Integral floats coerce to integers for `integer` fields; safe integers coerce to strings for `string`-only fields; non-integral floats stay untouched. diff --git a/questions/codex-namespace-tool-collision/v1/reference/ENVIRONMENT.md b/questions/codex-namespace-tool-collision/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..531abf3 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering non-colliding tool lowering, restoration, and argument repair diff --git a/questions/codex-namespace-tool-collision/v1/reference/TASK.md b/questions/codex-namespace-tool-collision/v1/reference/TASK.md new file mode 100644 index 0000000..7b45802 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/TASK.md @@ -0,0 +1,15 @@ +# Task + +Production Codex sessions are hitting Responses API tool compatibility failures whenever bare tools, `functions` tools, MCP/namespaced tools, and `custom` tools interact or share wire spellings—across both JSON responses and incremental SSE streams. + +Reported issues include: +- Requests failing when bare and namespaced tools flatten to the same wire name. +- Converted namespaced `custom` tools failing to round-trip back to `custom_tool_call` across valid provider echo spellings, or colliding with other declared tools. +- Self-named namespace echo repair, Code Mode helper routing, and native-namespace argument repair misbehaving around colliding, converted, or unselected tools. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable protocol compatibility defects while preserving behavior for ordinary non-colliding requests. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/codex-namespace-tool-collision/v1/reference/package.json b/questions/codex-namespace-tool-collision/v1/reference/package.json new file mode 100644 index 0000000..4fe1fc6 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-codex-namespace-tool-collision", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/apply-patch-envelope.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/apply-patch-envelope.mjs new file mode 100644 index 0000000..74a315a --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/apply-patch-envelope.mjs @@ -0,0 +1,45 @@ +const PATCH_BEGIN = '*** Begin Patch'; +const PATCH_END = '*** End Patch'; +const TOP_LEVEL_PATCH_ENVELOPE = /^(\*\*\* Begin Patch(?: \*\*\*)?)(\r?\n)([\s\S]*)(\r?\n)(\*\*\* End Patch(?: \*\*\*)?)(\r?\n)?$/; +const PATCH_OPERATION_LINE = /^\*\*\* (?:Add|Update|Delete) File: .+$/m; + +export function unwrapFreeformToolInput(argumentsText) { + if (typeof argumentsText !== 'string') return ''; + try { + const parsed = JSON.parse(argumentsText); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + } + } catch { + // The string is the freeform body, not nested JSON. + } + return argumentsText; +} + +export function normalizeApplyPatchDelimiters(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return text; + const [, begin, beginBreak, body, endBreak, end, trailingBreak = ''] = match; + if (!PATCH_OPERATION_LINE.test(body)) return text; + if (begin === PATCH_BEGIN && end === PATCH_END) return text; + return `${PATCH_BEGIN}${beginBreak}${body}${endBreak}${PATCH_END}${trailingBreak}`; +} + +export function isCompletePatchEnvelope(text) { + const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text); + if (!match) return false; + return PATCH_OPERATION_LINE.test(match[3] ?? ''); +} + +export function mayBecomePatchEnvelope(text) { + if (text === '') return false; + return text.startsWith(PATCH_BEGIN) || PATCH_BEGIN.startsWith(text); +} + +export function repairFreeformToolInput(argumentsText, toolName = '', namespace) { + const unwrapped = unwrapFreeformToolInput(argumentsText); + const ownsApplyPatchGrammar = namespace === undefined || namespace === 'functions'; + return ownsApplyPatchGrammar && toolName === 'apply_patch' + ? normalizeApplyPatchDelimiters(unwrapped) + : unwrapped; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/code-mode-helper-compat.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/code-mode-helper-compat.mjs new file mode 100644 index 0000000..0597745 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/code-mode-helper-compat.mjs @@ -0,0 +1,65 @@ +import { + isCompletePatchEnvelope, + normalizeApplyPatchDelimiters, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function unwrapPatchInput(value) { + try { + const parsed = JSON.parse(value); + if (isPlainObject(parsed)) { + if (typeof parsed.input === 'string') return parsed.input; + if (typeof parsed.patch === 'string') return parsed.patch; + } + } catch { + // Native custom calls carry the patch body directly. + } + return value; +} + +export function compileCodeModeHelperInput(argumentsText, toolName) { + if (typeof argumentsText !== 'string') return ''; + if (toolName === 'apply_patch') { + const patch = normalizeApplyPatchDelimiters(unwrapPatchInput(argumentsText)); + return `const result = await tools.apply_patch(${JSON.stringify(patch)});\ntext(result);`; + } + let parsed = argumentsText; + try { + parsed = JSON.parse(argumentsText); + } catch { + // Keep malformed provider text as data rather than executable source. + } + const args = isPlainObject(parsed) ? { ...parsed } : parsed; + if ( + toolName === 'shell_command' + && isPlainObject(args) + && typeof args.command === 'string' + && args.cmd === undefined + ) { + args.cmd = args.command; + delete args.command; + } + if (toolName === 'write_stdin') { + return `const result = await tools.write_stdin(${JSON.stringify(args)});\ntext(result);`; + } + return `const result = await tools.exec_command(${JSON.stringify(args)});\ntext(result);`; +} + +export function resolveCodeModeHelperName( + codeModeHelperName, + toolName, + argumentsText, + namespace, + declaredNames, +) { + if (codeModeHelperName) return codeModeHelperName; + if (toolName !== 'exec' || namespace !== undefined) return undefined; + if (!declaresCodeModeExec(declaredNames)) return undefined; + if (typeof argumentsText !== 'string' || argumentsText === '') return undefined; + return isCompletePatchEnvelope(unwrapFreeformToolInput(argumentsText)) ? 'apply_patch' : undefined; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/custom-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/custom-tool-compat.mjs new file mode 100644 index 0000000..7b7cef5 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/custom-tool-compat.mjs @@ -0,0 +1,349 @@ +import { namespacedToolName, normalizeDeclaredToolName } from './tools.mjs'; +import { + normalizeApplyPatchDelimiters, + repairFreeformToolInput, + unwrapFreeformToolInput, +} from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +const ROUTED_CUSTOM_TOOL_PASSTHROUGH = new Set(['apply_patch']); +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function routedCustomToolPassesThrough( + name, + supportsResponsesCustomTools, + passthroughNames = ROUTED_CUSTOM_TOOL_PASSTHROUGH, +) { + return supportsResponsesCustomTools !== false && passthroughNames.has(name); +} + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function customToolWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function toolChoiceAllowsRoutedCustomTool(body, wireName, candidateNames) { + if (!isPlainObject(body)) return true; + const choice = body.tool_choice; + if (choice === undefined || choice === null || choice === 'auto' || choice === 'required') { + return true; + } + if (choice === 'none') return false; + if (!isPlainObject(choice)) return true; + + const selectorAllows = (selector) => { + if (!isPlainObject(selector) || typeof selector.name !== 'string') return false; + if (selector.type !== 'custom') return false; + if (typeof selector.namespace === 'string') { + return customToolWireName(selector.namespace, selector.name) === wireName; + } + if (selector.name === wireName) return true; + const suffix = `__${selector.name}`; + const candidates = [...candidateNames].filter(name => name.endsWith(suffix)); + return candidates.length === 1 && candidates[0] === wireName; + }; + + if (choice.type === 'function' || choice.type === 'custom') return selectorAllows(choice); + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + return choice.tools.some(selectorAllows); + } + return false; +} + +export function routedCustomToolWireName(value) { + if (!isPlainObject(value) || typeof value.name !== 'string') return undefined; + return customToolWireName( + typeof value.namespace === 'string' ? value.namespace : undefined, + value.name, + ); +} + +export function routedCustomToolTargetName(value, names, declaredNames) { + const wireName = routedCustomToolWireName(value); + if (wireName === undefined) return undefined; + if (names.has(wireName)) return wireName; + if (!isPlainObject(value) || typeof value.namespace === 'string') return undefined; + const normalized = normalizeDeclaredToolName(wireName, declaredNames); + return normalized !== wireName && names.has(normalized) ? normalized : undefined; +} + +function collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, passthrough = false, passthroughNames) { + const names = new Set(); + const groups = collectResponsesToolGroups(body); + const bareWireNames = new Set(); + for (const group of groups) { + for (const tool of group) { + if ( + isPlainObject(tool) + && tool.type !== 'namespace' + && typeof tool.name === 'string' + ) bareWireNames.add(tool.name); + } + } + + for (const group of groups) { + for (const tool of group) { + if (!isPlainObject(tool)) continue; + if ( + tool.type === 'custom' + && typeof tool.name === 'string' + && routedCustomToolPassesThrough(tool.name, supportsResponsesCustomTools, passthroughNames) === passthrough + ) { + names.add(tool.name); + continue; + } + if (tool.type !== 'namespace' || typeof tool.name !== 'string' || !Array.isArray(tool.tools)) { + continue; + } + for (const child of tool.tools) { + if ( + isPlainObject(child) + && child.type === 'custom' + && typeof child.name === 'string' + && routedCustomToolPassesThrough(child.name, supportsResponsesCustomTools, passthroughNames) === passthrough + && (!passthrough || tool.name === BUILTIN_FUNCTIONS_NAMESPACE) + && !(tool.name === BUILTIN_FUNCTIONS_NAMESPACE && bareWireNames.has(child.name)) + ) names.add(customToolWireName(tool.name, child.name)); + } + } + } + return names; +} + +export function customToolItemId(id) { + if (typeof id !== 'string') return id; + return id.startsWith('fc_') ? `ctc_${id.slice(3)}` : id; +} + +export function collectRoutedCustomToolNames(body, supportsResponsesCustomTools, passthroughNames) { + const names = new Set(); + const visit = (value) => { + if (Array.isArray(value)) { + for (const entry of value) visit(entry); + return; + } + if (!isPlainObject(value)) return; + if ( + value.type === 'custom' + && typeof value.name === 'string' + && !routedCustomToolPassesThrough(value.name, supportsResponsesCustomTools, passthroughNames) + ) { + names.add(value.name); + } + for (const key of ['tools', 'input', 'tool_choice']) visit(value[key]); + }; + visit(body); + return names; +} + +function collectConvertedCallIds(value, names, out) { + if (Array.isArray(value)) { + for (const entry of value) collectConvertedCallIds(entry, names, out); + return; + } + if (!isPlainObject(value)) return; + if ( + (value.type === 'custom_tool_call' || value.type === 'function_call') + && typeof value.name === 'string' + && names.has(value.name) + && typeof value.call_id === 'string' + ) { + out.add(value.call_id); + } + if (Array.isArray(value.input)) collectConvertedCallIds(value.input, names, out); +} + +function rewriteForUpstream(value, names, callIds) { + if (Array.isArray(value)) return value.map(entry => rewriteForUpstream(entry, names, callIds)); + if (!isPlainObject(value)) return value; + + if (value.type === 'custom' && typeof value.name === 'string' && names.has(value.name)) { + const { format: _format, ...rest } = value; + const isDefinition = typeof value.description === 'string' + || isPlainObject(value.format) + || isPlainObject(value.parameters); + if (!isDefinition) return { ...rest, type: 'function' }; + const inputDescription = value.name === 'exec' + ? 'JavaScript source for unified exec. Use await tools.exec_command(...) for shell commands and text(...) to return textual output; do not provide a bare shell command.' + : 'Raw input for this client-executed custom tool.'; + return { + ...rest, + type: 'function', + parameters: { + type: 'object', + properties: { + input: { + type: 'string', + description: inputDescription, + }, + }, + required: ['input'], + additionalProperties: false, + }, + }; + } + + if ( + value.type === 'custom_tool_call' + && typeof value.name === 'string' + && names.has(value.name) + ) { + const { input, id: _id, ...rest } = value; + return { + ...rest, + type: 'function_call', + arguments: JSON.stringify({ input: typeof input === 'string' ? input : '' }), + }; + } + + if ( + value.type === 'custom_tool_call_output' + && typeof value.call_id === 'string' + && callIds.has(value.call_id) + ) { + return { ...value, type: 'function_call_output' }; + } + + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(value)) { + const rewritten = ['tools', 'input', 'tool_choice'].includes(key) + ? rewriteForUpstream(entry, names, callIds) : entry; + next[key] = rewritten; + changed ||= rewritten !== entry; + } + return changed ? next : value; +} + +export function rewriteRoutedCustomToolsForUpstream(body, supportsResponsesCustomTools, passthroughNames) { + const conversionNames = collectRoutedCustomToolNames(body, supportsResponsesCustomTools, passthroughNames); + const names = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, false, passthroughNames); + const repairNames = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, true); + for (const name of repairNames) { + if (!toolChoiceAllowsRoutedCustomTool(body, name, repairNames)) repairNames.delete(name); + } + if (conversionNames.size === 0) return { body, names, repairNames }; + const callIds = new Set(); + collectConvertedCallIds(body, conversionNames, callIds); + return { body: rewriteForUpstream(body, conversionNames, callIds), names, repairNames }; +} + +export function restoreRoutedCustomCalls(value, names, repairNames = new Set(), declaredNames) { + if (!isPlainObject(value)) return { value, changed: false }; + + const restoreItem = (item) => { + if (!isPlainObject(item)) return { value: item, changed: false }; + const wireName = routedCustomToolWireName(item); + const targetName = routedCustomToolTargetName(item, names, declaredNames); + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + && wireName !== undefined + && targetName !== undefined + ) { + const sourceInput = item.type === 'function_call' ? item.arguments : item.input; + const aliased = targetName !== wireName; + const itemNamespace = typeof item.namespace === 'string' ? item.namespace : undefined; + const helper = aliased && sourceInput !== '' + ? item.name + : resolveCodeModeHelperName(undefined, targetName, sourceInput, itemNamespace, declaredNames); + if (item.type === 'custom_tool_call' && !aliased && !helper) { + const input = repairNames.has(wireName) && typeof sourceInput === 'string' + ? normalizeApplyPatchDelimiters(sourceInput) + : sourceInput; + return input !== sourceInput + ? { value: { ...item, input }, changed: true } + : { value: item, changed: false }; + } + const restored = { + ...item, + type: 'custom_tool_call', + id: customToolItemId(item.id), + name: aliased ? targetName : item.name, + input: helper + ? compileCodeModeHelperInput(sourceInput, helper) + : repairFreeformToolInput(sourceInput, targetName, itemNamespace), + }; + delete restored.arguments; + if (aliased) delete restored.namespace; + return { value: restored, changed: true }; + } + if ( + item.type === 'custom_tool_call' + && typeof item.name === 'string' + && wireName !== undefined + && repairNames.has(wireName) + && typeof item.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(item.input); + if (input !== item.input) return { value: { ...item, input }, changed: true }; + } + return { value: item, changed: false }; + }; + + const restoreOutput = (output) => { + if (!Array.isArray(output)) return { value: output, changed: false }; + let changed = false; + const restored = output.map(item => { + const result = restoreItem(item); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value: output, changed: false }; + }; + + let changed = false; + const restored = { ...value }; + const output = restoreOutput(value.output); + if (output.changed) { + restored.output = output.value; + changed = true; + } + + if ( + (value.type === 'response.output_item.added' || value.type === 'response.output_item.done') + && isPlainObject(value.item) + ) { + const item = restoreItem(value.item); + if (item.changed) { + restored.item = item.value; + changed = true; + } + } + + if ( + typeof value.type === 'string' + && value.type.startsWith('response.') + && isPlainObject(value.response) + ) { + const response = restoreRoutedCustomCalls(value.response, names, repairNames, declaredNames); + if (response.changed) { + restored.response = response.value; + changed = true; + } + } + + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedCustomCallsInJson(text, names, repairNames = new Set(), declaredNames) { + if (names.size === 0 && repairNames.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedCustomCalls(payload, names, repairNames, declaredNames); + return restored.changed ? JSON.stringify(restored.value) : text; +} + +export function unwrapRoutedCustomToolArguments(argumentsText, toolName = '', namespace) { + return toolName + ? repairFreeformToolInput(argumentsText, toolName, namespace) + : unwrapFreeformToolInput(argumentsText); +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/function-call-compat.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/function-call-compat.mjs new file mode 100644 index 0000000..cfb6461 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/function-call-compat.mjs @@ -0,0 +1,154 @@ +import { coerceIntegerToolArguments } from './tool-argument-integers.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream } from './namespace-tool-compat.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function sameSchemaValue(left, right) { + if (left === right) return true; + if (Array.isArray(left) || Array.isArray(right)) { + return Array.isArray(left) && Array.isArray(right) && left.length === right.length + && left.every((value, index) => sameSchemaValue(value, right[index])); + } + if (!isObject(left) || !isObject(right)) return false; + const keys = Object.keys(left); + return keys.length === Object.keys(right).length + && keys.every(key => Object.hasOwn(right, key) && sameSchemaValue(left[key], right[key])); +} + +function namespaceOf(value) { + return typeof value === 'string' && value !== 'functions' ? value : undefined; +} + +function schemaKey(namespace, name) { + return JSON.stringify([namespace ?? '', name]); +} + +function selectorAllows(selector, lowered, wireName, identity) { + if (!isObject(selector) || selector.type !== 'function' || typeof selector.name !== 'string') return false; + if ('namespace' in selector) { + if (typeof selector.namespace !== 'string' || selector.namespace.length === 0) return false; + return namespaceOf(selector.namespace) === identity.namespace && selector.name === identity.name; + } + return isObject(lowered) && lowered.type === 'function' && lowered.name === wireName; +} + +export function collectFunctionCallRepairSchemas(body) { + const schemas = new Map(); + if (!isObject(body)) return schemas; + const groups = collectResponsesToolGroups(body); + if (Array.isArray(body.input)) { + for (const entry of body.input) { + if (isObject(entry) && entry.type === 'tool_search_output' && Array.isArray(entry.tools)) groups.push(entry.tools); + } + } + const namespacePlan = rewriteRoutedNamespaceToolsForUpstream({ ...body, tools: groups.flat(), input: [] }, undefined, true); + const lowered = namespacePlan.body; + const choice = body.tool_choice; + const loweredChoice = isObject(lowered) ? lowered.tool_choice : undefined; + const occupied = new Map(); + const register = (tool, namespace) => { + if (!isObject(tool) || typeof tool.name !== 'string' || tool.name.length === 0) return; + const identity = { + name: tool.name, + ...(namespace ? { namespace } : {}), + ...(isObject(tool.parameters) ? { parameters: tool.parameters } : {}), + }; + const key = schemaKey(namespace, tool.name); + if (occupied.has(key)) { + const previous = occupied.get(key); + if (!previous || previous.kind !== tool.type + || previous.identity.namespace !== namespace + || previous.identity.name !== tool.name + || !sameSchemaValue(previous.identity.parameters, identity.parameters)) { + occupied.set(key, null); + } + } else occupied.set(key, { kind: tool.type, identity }); + }; + for (const group of groups) { + for (const tool of group) { + if (!isObject(tool)) continue; + if (tool.type === 'namespace') { + if (typeof tool.name !== 'string' || !tool.name || !Array.isArray(tool.tools)) continue; + for (const child of tool.tools) register(child, namespaceOf(tool.name)); + } else if (tool.type === 'function' && isObject(tool.function)) { + register({ ...tool.function, type: 'function' }); + } else register(tool); + } + } + for (const [key, entry] of occupied) { + if (!entry || entry.kind !== 'function') continue; + let allowed = choice === undefined || choice === 'auto' || choice === 'required'; + if (isObject(choice)) { + const wireName = entry.identity.namespace + ? [...namespacePlan.aliases].find(([, identity]) => identity.namespace === entry.identity.namespace && identity.name === entry.identity.name)?.[0] + : entry.identity.name; + if (choice.type === 'allowed_tools' && Array.isArray(choice.tools)) { + const selectors = isObject(loweredChoice) && Array.isArray(loweredChoice.tools) ? loweredChoice.tools : []; + allowed = choice.tools.some((selector, index) => selectorAllows(selector, selectors[index], wireName, entry.identity)); + } else allowed = selectorAllows(choice, loweredChoice, wireName, entry.identity); + } + if (allowed) schemas.set(key, entry.identity); + } + return schemas; +} + +function repairItem(item, schemas, completed) { + if (!isObject(item) || item.type !== 'function_call' || typeof item.name !== 'string' + || typeof item.arguments !== 'string') return item; + if (item.status !== 'completed' && !(item.status === undefined && completed)) return item; + if ('namespace' in item && (typeof item.namespace !== 'string' || !item.namespace)) return item; + const namespace = namespaceOf(item.namespace); + const schema = schemas.get(schemaKey(namespace, item.name)); + if (!schema) return item; + if ('namespace' in item && (schema.namespace !== namespace || schema.name !== item.name)) return item; + const raw = item.arguments; + if (raw !== '') { + try { + let unsafe = false; + JSON.parse(raw, (_key, value) => { + if (typeof value === 'number' && (!Number.isFinite(value) + || (Number.isInteger(value) && !Number.isSafeInteger(value)))) unsafe = true; + return value; + }); + if (unsafe) return item; + } catch { return item; } + } + const argumentsText = coerceIntegerToolArguments(raw || '{}', schema.parameters, schema.namespace ? undefined : schema.name); + return argumentsText === raw ? item : { ...item, arguments: argumentsText }; +} + +export function repairFunctionCalls(value, schemas) { + if (schemas.size === 0 || !isObject(value)) return { value, changed: false }; + if (typeof value.status === 'string' && ['failed', 'incomplete', 'cancelled', 'in_progress', 'queued'].includes(value.status)) return { value, changed: false }; + let next = value; + if (value.type === 'function_call') next = repairItem(value, schemas, false); + else if (value.type === 'response.output_item.done') { + const item = repairItem(value.item, schemas, true); + if (item !== value.item) next = { ...value, item }; + } else if (value.type === 'response.completed' && isObject(value.response)) { + const response = value.response; + if ((response.status === undefined || response.status === 'completed') && Array.isArray(response.output)) { + const original = response.output; + const output = original.map(item => repairItem(item, schemas, true)); + if (output.some((item, index) => item !== original[index])) next = { ...value, response: { ...response, output } }; + } + } else if (typeof value.type !== 'string' || !value.type.startsWith('response.')) { + if (Array.isArray(value.output)) { + const original = value.output; + const output = original.map(item => repairItem(item, schemas, value.status === 'completed')); + if (output.some((item, index) => item !== original[index])) next = { ...value, output }; + } + } + return { value: next, changed: next !== value }; +} + +export function repairFunctionCallsInJson(text, schemas) { + if (schemas.size === 0) return text; + let payload; + try { payload = JSON.parse(text); } catch { return text; } + const repaired = repairFunctionCalls(payload, schemas); + return repaired.changed ? JSON.stringify(repaired.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/namespace-tool-compat.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/namespace-tool-compat.mjs new file mode 100644 index 0000000..3e60383 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/namespace-tool-compat.mjs @@ -0,0 +1,352 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; +import { collectResponsesToolGroups } from './tool-groups.mjs'; +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from './tool-name-aliases.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function namespaceIdentity(namespace, name) { + return `${namespace}\u0000${name}`; +} + +function isRepresentableName(name) { + if (typeof name !== 'string' || name.length === 0) return false; + for (let index = 0; index < name.length; index += 1) { + const code = name.charCodeAt(index); + if (code <= 0x1f || code === 0x7f) return false; + } + return true; +} + +function parseNamespaceGroup(tool) { + if ( + !isPlainObject(tool) + || tool.type !== 'namespace' + || !isRepresentableName(tool.name) + || !Array.isArray(tool.tools) + ) return undefined; + const children = []; + for (const child of tool.tools) { + if (!isPlainObject(child) || child.type === 'namespace' || !isRepresentableName(child.name)) continue; + children.push(child); + } + return { namespace: tool.name, children }; +} + +function loweredIdentity(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE + ? namespaceIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name) + : namespaceIdentity(namespace, name); +} + +function loweredWireName(namespace, name) { + return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name); +} + +function addSelector(selectors, selector, wireName) { + const current = selectors.get(selector); + if (current === undefined) selectors.set(selector, wireName); + else if (current !== wireName) selectors.set(selector, null); +} + +/** Two distinct logical tools would occupy one wire name; the caller maps this to a 400. */ +export class NamespaceToolCollisionError extends Error {} + +function buildRewritePlan(groups, disambiguate) { + const aliases = new Map(); + const bareWireNames = new Set(); + const canonicalWireNames = new Set(); + const identities = new Map(); + const selectors = new Map(); + const wireOwners = new Map(); + const reserved = new Set(); + + // Reserve every natural spelling before allocating aliases, including declarations in + // later additional_tools groups. An alias must not steal another tool's ordinary name. + for (const group of groups) for (const tool of group) { + const name = wireToolInnerName(tool); + if (isPlainObject(tool) && tool.type !== 'namespace' && isRepresentableName(name)) reserved.add(name); + const parsed = parseNamespaceGroup(tool); + if (parsed) for (const child of parsed.children) { + // Bare tool_choice references can name a child by its original logical name. + reserved.add(child.name); + reserved.add(loweredWireName(parsed.namespace, child.name)); + } + } + + for (const group of groups) { + for (const tool of group) { + const name = wireToolInnerName(tool); + if (isPlainObject(tool) && tool.type !== 'namespace' && isRepresentableName(name)) { + wireOwners.set(name, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name)); + bareWireNames.add(name); + canonicalWireNames.add(name); + addSelector(selectors, name, name); + } + // Codex's reserved group is another representation of bare tools. Claim its + // names before ordinary namespaces, but do not mark its declarations emitted. + const parsed = disambiguate ? parseNamespaceGroup(tool) : undefined; + if (parsed?.namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + for (const child of parsed.children) { + const childName = child.name; + wireOwners.set(childName, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, childName)); + canonicalWireNames.add(childName); + addSelector(selectors, childName, childName); + } + } + } + } + + for (const group of groups) { + for (const tool of group) { + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const childName = child.name; + const identity = loweredIdentity(parsed.namespace, childName); + let wireName = identities.get(identity) ?? loweredWireName(parsed.namespace, childName); + const owner = wireOwners.get(wireName); + if (owner !== undefined && owner !== identity) { + if (!disambiguate) { + throw new NamespaceToolCollisionError( + `namespace tool wire-name collision for "${wireName}"; rename one of the colliding tools`, + ); + } + const prefix = wireName; + let suffix = 2; + do { + const tail = `_${suffix++}`; + wireName = `${prefix.slice(0, 64 - tail.length)}${tail}`; + } while (reserved.has(wireName)); + reserved.add(wireName); + } + wireOwners.set(wireName, identity); + identities.set(identity, wireName); + // A bare declaration owns its literal selector even if a namespace child's + // original flattened spelling collides with it. + addSelector(selectors, wireName, wireName); + addSelector(selectors, `${parsed.namespace}.${childName}`, wireName); + if (!disambiguate || !canonicalWireNames.has(childName)) addSelector(selectors, childName, wireName); + if (parsed.namespace !== BUILTIN_FUNCTIONS_NAMESPACE) { + const kind = child.type === 'custom' ? 'custom' : 'function'; + aliases.set(wireName, { namespace: parsed.namespace, name: childName, kind }); + } + } + } + } + + return { aliases, bareWireNames, identities, selectors }; +} + +function rewriteToolList(tools, plan, emitted) { + let changed = false; + const rewritten = []; + for (const tool of tools) { + if (isPlainObject(tool) && tool.type === 'namespace') { + changed = true; + const parsed = parseNamespaceGroup(tool); + if (!parsed) continue; + for (const child of parsed.children) { + const wireName = plan.identities.get(loweredIdentity(parsed.namespace, child.name)); + if ( + wireName === undefined + || (parsed.namespace === BUILTIN_FUNCTIONS_NAMESPACE && plan.bareWireNames.has(wireName)) + || emitted.has(wireName) + ) continue; + emitted.add(wireName); + rewritten.push(wireName === child.name ? child : { ...child, name: wireName }); + } + continue; + } + const name = wireToolInnerName(tool); + if (isRepresentableName(name)) { + if (emitted.has(name)) { + changed = true; + continue; + } + emitted.add(name); + } + rewritten.push(tool); + } + return changed ? rewritten : tools; +} + +function hasMalformedNamespace(value) { + return 'namespace' in value && typeof value.namespace !== 'string'; +} + +function rewriteNamedSelector(value, plan, bareFallback) { + if (!isPlainObject(value) || typeof value.name !== 'string') return value; + if (hasMalformedNamespace(value)) return value; + const namespace = value.namespace; + if (typeof namespace !== 'string') { + if (!bareFallback) return value; + const wireName = plan.selectors.get(value.name) ?? undefined; + return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName }; + } + const { namespace: _dropped, ...rest } = value; + const wireName = plan.identities.get(loweredIdentity(namespace, value.name)) + ?? loweredWireName(namespace, value.name); + return { ...rest, name: wireName }; +} + +function rewriteToolChoice(value, plan) { + if (!isPlainObject(value)) return value; + if ((value.type === 'function' || value.type === 'custom') && typeof value.name === 'string') { + return rewriteNamedSelector(value, plan, true); + } + if (value.type !== 'allowed_tools' || !Array.isArray(value.tools)) return value; + let changed = false; + const tools = value.tools.map(tool => { + if (!isPlainObject(tool) || typeof tool.name !== 'string') return tool; + const rewritten = rewriteNamedSelector(tool, plan, true); + changed ||= rewritten !== tool; + return rewritten; + }); + return changed ? { ...value, tools } : value; +} + +function authorizedAliases(aliases, toolChoice) { + if (toolChoice === undefined || toolChoice === 'auto' || toolChoice === 'required') return aliases; + if (toolChoice === 'none' || !isPlainObject(toolChoice)) return new Map(); + + let authorized; + if ( + (toolChoice.type === 'function' || toolChoice.type === 'custom') + && typeof toolChoice.name === 'string' + ) { + if (hasMalformedNamespace(toolChoice)) return new Map(); + authorized = new Map([[toolChoice.name, toolChoice.type]]); + } else if (toolChoice.type === 'allowed_tools' && Array.isArray(toolChoice.tools)) { + authorized = new Map(); + for (const tool of toolChoice.tools) { + if (!isPlainObject(tool)) continue; + if (tool.type !== 'function' && tool.type !== 'custom') continue; + if (typeof tool.name !== 'string') continue; + if (hasMalformedNamespace(tool)) continue; + authorized.set(tool.name, tool.type); + } + } else { + return new Map(); + } + + return new Map( + [...aliases].filter(([wireName, identity]) => authorized.get(wireName) === identity.kind), + ); +} + +function rewriteInputItem(item, plan, emitted) { + if (!isPlainObject(item)) return item; + if (item.type === 'additional_tools' && Array.isArray(item.tools)) { + const tools = rewriteToolList(item.tools, plan, emitted); + return tools === item.tools ? item : { ...item, tools }; + } + if ( + (item.type === 'function_call' || item.type === 'custom_tool_call') + && typeof item.name === 'string' + ) return rewriteNamedSelector(item, plan, false); + return item; +} + +export function rewriteRoutedNamespaceToolsForUpstream(body, convertedCustomToolNames, disambiguate = false) { + if (!isPlainObject(body)) return { body, aliases: new Map(), declarations: new Map() }; + const groups = collectResponsesToolGroups(body); + const plan = buildRewritePlan(groups, disambiguate); + const declarations = new Map(plan.aliases); + + const emitted = new Set(); + const tools = Array.isArray(body.tools) ? rewriteToolList(body.tools, plan, emitted) : body.tools; + + let input = body.input; + if (Array.isArray(body.input)) { + let inputChanged = false; + const rewrittenInput = body.input.map(item => { + const next = rewriteInputItem(item, plan, emitted); + if (next !== item) inputChanged = true; + return next; + }); + if (inputChanged) input = rewrittenInput; + } + + const toolChoice = rewriteToolChoice(body.tool_choice, plan); + const aliases = authorizedAliases(plan.aliases, toolChoice); + const ambiguousDotted = collectAmbiguousDottedAliases(groups); + for (const identity of [...aliases.values()]) { + const dotted = dottedToolName(identity.namespace, identity.name); + if (dottedAliasIsUnambiguous(identity.namespace, identity.name) + && !ambiguousDotted.has(dotted) && !plan.bareWireNames.has(dotted) + && !aliases.has(dotted)) aliases.set(dotted, identity); + } + for (const identity of aliases.values()) { + if (convertedCustomToolNames?.has(namespacedToolName(identity.namespace, identity.name))) identity.kind = 'custom'; + } + return { + body: { + ...body, + ...(tools !== body.tools ? { tools } : {}), + ...(input !== body.input ? { input } : {}), + ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}), + }, + aliases, + declarations, + }; +} + +export function restoreRoutedNamespaceCalls( + value, + aliases, + originalCoordinates = new Set([...aliases.values()].map(identity => + namespaceIdentity(identity.namespace, identity.name))), +) { + if (Array.isArray(value)) { + let changed = false; + const restored = value.map(entry => { + const result = restoreRoutedNamespaceCalls(entry, aliases, originalCoordinates); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: restored, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + + let changed = false; + const restored = {}; + for (const [key, entry] of Object.entries(value)) { + const result = restoreRoutedNamespaceCalls(entry, aliases, originalCoordinates); + restored[key] = result.value; + changed ||= result.changed; + } + + if ( + (value.type === 'function_call' || value.type === 'custom_tool_call') + && typeof value.name === 'string' + // An explicit declared coordinate wins over another tool's alias spelling. + && !(typeof value.namespace === 'string' + && originalCoordinates.has(namespaceIdentity(value.namespace, value.name))) + ) { + const identity = aliases.get(value.name); + if (identity + && (value.type !== 'custom_tool_call' || identity.kind === 'custom') + && (!Object.hasOwn(value, 'namespace') || value.namespace === identity.namespace)) { + restored.name = identity.name; + restored.namespace = identity.namespace; + changed = true; + } + } + return changed ? { value: restored, changed: true } : { value, changed: false }; +} + +export function restoreRoutedNamespaceCallsInJson(text, aliases) { + if (aliases.size === 0) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const restored = restoreRoutedNamespaceCalls(payload, aliases); + return restored.changed ? JSON.stringify(restored.value) : text; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/responses-custom-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/responses-custom-tool-repair.mjs new file mode 100644 index 0000000..6afa922 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/responses-custom-tool-repair.mjs @@ -0,0 +1,351 @@ +import { mayBecomePatchEnvelope, normalizeApplyPatchDelimiters } from './apply-patch-envelope.mjs'; +import { compileCodeModeHelperInput, resolveCodeModeHelperName } from './code-mode-helper-compat.mjs'; +import { declaresCodeModeExec } from './tools.mjs'; +import { + customToolItemId, + restoreRoutedCustomCalls, + routedCustomToolTargetName, + routedCustomToolWireName, + unwrapRoutedCustomToolArguments, +} from './custom-tool-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const FREEFORM_WRAP_PREFIX = '{"input":"'; +const FREEFORM_WRAP_PREFIX_RE = /^\s*\{\s*"input"\s*:\s*"/; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function partialCustomToolInput(argumentsText) { + const match = FREEFORM_WRAP_PREFIX_RE.exec(argumentsText); + if (!match) return null; + const body = argumentsText.slice(match[0].length); + let output = ''; + for (let index = 0; index < body.length; index++) { + const char = body[index]; + if (char === '"') break; + if (char !== '\\') { + output += char; + continue; + } + const escaped = body[index + 1]; + if (escaped === undefined) break; + index += 1; + if (escaped === 'n') output += '\n'; + else if (escaped === 't') output += '\t'; + else if (escaped === 'r') output += '\r'; + else if (escaped === 'b') output += '\b'; + else if (escaped === 'f') output += '\f'; + else if (escaped === 'u') { + const hex = body.slice(index + 1, index + 5); + if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break; + output += String.fromCharCode(Number.parseInt(hex, 16)); + index += 4; + } else output += escaped; + } + return output; +} + +function replaceSseEventName(block, type) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + let replaced = false; + const next = lines.map(line => { + if (!replaced && line.startsWith('event:')) { + replaced = true; + return `event: ${type}`; + } + return line; + }); + return next.join(newline); +} + +export function createRoutedCustomToolRestoreBlockRewrite( + names, + budget, + repairNames = new Set(), + declaredNames, +) { + const itemNames = new Map(); + const customExecItemNames = new Map(); + const repairItemNames = new Map(); + const ordinaryItemIds = new Set(); + const openCalls = new Map(); + let pendingArguments = []; + let disposed = false; + + const releaseCall = (itemId) => { + const open = openCalls.get(itemId); + if (!open) return; + if (open.retainedBytes > 0) { + budget?.releaseRetained(open.retainedBytes, { kind: 'retained_collectors' }); + } + openCalls.delete(itemId); + }; + + const releaseAll = () => { + if (disposed) return; + disposed = true; + for (const itemId of openCalls.keys()) releaseCall(itemId); + const pendingBytes = pendingArguments.reduce((total, pending) => total + pending.retainedBytes, 0); + if (pendingBytes > 0) { + budget?.releaseRetained(pendingBytes, { kind: 'retained_collectors' }); + } + pendingArguments = []; + itemNames.clear(); + customExecItemNames.clear(); + repairItemNames.clear(); + ordinaryItemIds.clear(); + }; + + const retainPendingArgument = (block, itemId, outputIndex) => { + const retainedBytes = Buffer.byteLength(block, 'utf8'); + if (retainedBytes > 0) budget?.chargeRetained(retainedBytes, { kind: 'retained_collectors' }); + pendingArguments.push({ block, itemId, outputIndex, retainedBytes }); + }; + + const takePendingArguments = (itemId, outputIndex) => { + const matched = []; + const remaining = []; + for (const pending of pendingArguments) { + const matches = pending.itemId !== undefined + ? itemId !== undefined && pending.itemId === itemId + : outputIndex !== undefined && pending.outputIndex === outputIndex; + (matches ? matched : remaining).push(pending); + } + pendingArguments = remaining; + const retainedBytes = matched.reduce((total, pending) => total + pending.retainedBytes, 0); + if (retainedBytes > 0) { + budget?.releaseRetained(retainedBytes, { kind: 'retained_collectors' }); + } + return matched.map(pending => { + if (pending.itemId !== undefined || itemId === undefined) return pending.block; + const payload = sseDataPayload(pending.block); + if (payload === null) return pending.block; + try { + const parsed = JSON.parse(payload); + if (!isPlainObject(parsed)) return pending.block; + return replaceSseDataPayload(pending.block, JSON.stringify({ ...parsed, item_id: itemId })); + } catch { + return pending.block; + } + }); + }; + + const rewrite = (block) => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null || payload === '[DONE]') return [block]; + let parsed; + try { + parsed = JSON.parse(payload); + } catch { + return [block]; + } + if (!isPlainObject(parsed)) return [block]; + + const type = typeof parsed.type === 'string' ? parsed.type : ''; + const outputIndex = typeof parsed.output_index === 'number' + && Number.isInteger(parsed.output_index) + && parsed.output_index >= 0 + ? parsed.output_index + : undefined; + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'custom_tool_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const wireName = routedCustomToolWireName(parsed.item); + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const aliased = targetName !== undefined && targetName !== wireName; + const codeModeExec = targetName === 'exec' && parsed.item.name === 'exec' + && parsed.item.namespace === undefined && declaresCodeModeExec(declaredNames); + if (upstreamItemId && (aliased || codeModeExec)) { + customExecItemNames.set(upstreamItemId, parsed.item.name); + if (type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const repairable = wireName !== undefined && repairNames.has(wireName); + if (upstreamItemId && repairable) repairItemNames.set(upstreamItemId, parsed.item.name); + const restored = repairable || aliased || codeModeExec + ? restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames) + : { value: parsed, changed: false }; + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + } + if ( + (type === 'response.output_item.added' || type === 'response.output_item.done') + && isPlainObject(parsed.item) + && parsed.item.type === 'function_call' + && typeof parsed.item.name === 'string' + ) { + const upstreamItemId = typeof parsed.item.id === 'string' ? parsed.item.id : undefined; + const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames); + const routed = targetName !== undefined; + const wireName = routedCustomToolWireName(parsed.item); + if (upstreamItemId) { + if (routed) { + itemNames.set(upstreamItemId, { + name: parsed.item.name, + aliased: targetName !== wireName, + ...(typeof parsed.item.namespace === 'string' ? { namespace: parsed.item.namespace } : {}), + }); + ordinaryItemIds.delete(upstreamItemId); + } else { + ordinaryItemIds.add(upstreamItemId); + } + if (routed && type === 'response.output_item.added') { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + } + const pending = takePendingArguments(upstreamItemId, outputIndex); + if (!routed) { + if (type === 'response.output_item.done' && upstreamItemId) ordinaryItemIds.delete(upstreamItemId); + return [...pending, block]; + } + if (upstreamItemId && pending.length > 0 && !openCalls.has(upstreamItemId)) { + openCalls.set(upstreamItemId, { argumentsText: '', emittedInput: '', retainedBytes: 0 }); + } + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const restoredBlock = restored.changed + ? replaceSseDataPayload(block, JSON.stringify(restored.value)) + : block; + const replayed = pending.flatMap(pendingBlock => rewrite(pendingBlock)); + if (type === 'response.output_item.done' && upstreamItemId) releaseCall(upstreamItemId); + return type === 'response.output_item.added' + ? [restoredBlock, ...replayed] + : [...replayed, restoredBlock]; + } + + const upstreamItemId = typeof parsed.item_id === 'string' ? parsed.item_id : undefined; + if ( + type === 'response.custom_tool_call_input.delta' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (customExecItemNames.get(upstreamItemId) !== 'exec' + || mayBecomePatchEnvelope(open.argumentsText) + || open.argumentsText.trimStart() === '' + || open.argumentsText.trimStart().startsWith('{')) return []; + const inputDelta = open.argumentsText.slice(open.emittedInput.length); + open.emittedInput = open.argumentsText; + return inputDelta ? [replaceSseDataPayload(block, JSON.stringify({ ...parsed, delta: inputDelta }))] : []; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && customExecItemNames.has(upstreamItemId) + ) { + const source = typeof parsed.input === 'string' + ? parsed.input + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const name = customExecItemNames.get(upstreamItemId); + const helper = name === 'exec' + ? resolveCodeModeHelperName(undefined, name, source, undefined, declaredNames) + : name; + releaseCall(upstreamItemId); + return [replaceSseDataPayload(block, JSON.stringify({ + ...parsed, + input: helper ? compileCodeModeHelperInput(source, helper) : source, + }))]; + } + if ( + type === 'response.custom_tool_call_input.done' + && upstreamItemId + && repairItemNames.has(upstreamItemId) + && typeof parsed.input === 'string' + ) { + const input = normalizeApplyPatchDelimiters(parsed.input); + if (input !== parsed.input) { + return [replaceSseDataPayload(block, JSON.stringify({ ...parsed, input }))]; + } + } + const argumentEvent = type === 'response.function_call_arguments.delta' + || type === 'response.function_call_arguments.done'; + if (argumentEvent && (!upstreamItemId || (!itemNames.has(upstreamItemId) && !ordinaryItemIds.has(upstreamItemId)))) { + retainPendingArgument(block, upstreamItemId, outputIndex); + return []; + } + if ( + type === 'response.function_call_arguments.delta' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const open = openCalls.get(upstreamItemId) ?? { argumentsText: '', emittedInput: '', retainedBytes: 0 }; + const delta = typeof parsed.delta === 'string' ? parsed.delta : ''; + const deltaBytes = Buffer.byteLength(delta, 'utf8'); + if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: 'retained_collectors' }); + open.argumentsText += delta; + open.retainedBytes += deltaBytes; + openCalls.set(upstreamItemId, open); + if (itemNames.get(upstreamItemId)?.aliased) return []; + if (FREEFORM_WRAP_PREFIX.startsWith(open.argumentsText)) return []; + const fullInput = partialCustomToolInput(open.argumentsText); + if (fullInput === null) return []; + if ( + declaresCodeModeExec(declaredNames) + && itemNames.get(upstreamItemId)?.namespace === undefined + && itemNames.get(upstreamItemId)?.name === 'exec' + && mayBecomePatchEnvelope(fullInput) + ) return []; + if (!fullInput.startsWith(open.emittedInput) || fullInput.length === open.emittedInput.length) return []; + const inputDelta = fullInput.slice(open.emittedInput.length); + open.emittedInput = fullInput; + const nextType = 'response.custom_tool_call_input.delta'; + const next = { + ...parsed, + type: nextType, + item_id: customToolItemId(upstreamItemId), + delta: inputDelta, + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + if ( + type === 'response.function_call_arguments.done' + && upstreamItemId + && itemNames.has(upstreamItemId) + ) { + const nextType = 'response.custom_tool_call_input.done'; + const source = typeof parsed.arguments === 'string' + ? parsed.arguments + : openCalls.get(upstreamItemId)?.argumentsText ?? ''; + const { arguments: _arguments, ...rest } = parsed; + const itemName = itemNames.get(upstreamItemId); + const helper = itemName?.aliased + ? itemName.name + : resolveCodeModeHelperName(undefined, itemName?.name ?? '', source, itemName?.namespace, declaredNames); + const next = { + ...rest, + type: nextType, + item_id: customToolItemId(upstreamItemId), + input: helper + ? compileCodeModeHelperInput(source, helper) + : unwrapRoutedCustomToolArguments(source, itemName?.name ?? '', itemName?.namespace), + }; + return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))]; + } + + const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames); + const terminal = type === 'response.completed' || type === 'response.failed' || type === 'response.incomplete'; + if (terminal) releaseAll(); + return restored.changed + ? [replaceSseDataPayload(block, JSON.stringify(restored.value))] + : [block]; + }; + rewrite.dispose = releaseAll; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/responses-function-tool-repair.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/responses-function-tool-repair.mjs new file mode 100644 index 0000000..ae8dabf --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/responses-function-tool-repair.mjs @@ -0,0 +1,165 @@ +import { + TRANSLATOR_MAX_TURN_BYTES, + TranslatorBudgetExceededError, +} from './translator-budget.mjs'; +import { repairFunctionCalls } from './function-call-compat.mjs'; +import { replaceSseDataPayload, sseDataPayload } from './sse-payload-rewrite.mjs'; + +const ENTRY_OVERHEAD_BYTES = 64; + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function outputIndexOf(value) { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined; +} + +export function createResponsesFunctionToolRepairBlockRewrite(schemas, budget) { + if (schemas.size === 0) return block => [block]; + const byId = new Map(); + const byIndex = new Map(); + let pending = []; + let retainedBytes = 0; + let disposed = false; + + const retain = (bytes) => { + if (retainedBytes + bytes > TRANSLATOR_MAX_TURN_BYTES) { + throw new TranslatorBudgetExceededError('retained_collectors', TRANSLATOR_MAX_TURN_BYTES); + } + budget?.chargeRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes += bytes; + }; + const release = (bytes) => { + budget?.releaseRetained(bytes, { kind: 'retained_collectors' }); + retainedBytes -= bytes; + }; + const releaseIdentity = (identity) => { + if (identity.itemId !== undefined) byId.delete(identity.itemId); + if (identity.outputIndex !== undefined) byIndex.delete(identity.outputIndex); + release(identity.bytes); + }; + const dispose = () => { + if (disposed) return; + disposed = true; + release(retainedBytes); + byId.clear(); + byIndex.clear(); + pending = []; + }; + const lookup = (itemId, index) => { + const identity = itemId === undefined ? undefined : byId.get(itemId); + if (identity) return index === undefined || identity.outputIndex === undefined || identity.outputIndex === index ? identity : undefined; + const indexed = index === undefined ? undefined : byIndex.get(index); + return indexed && (itemId === undefined || indexed.itemId === undefined || indexed.itemId === itemId) ? indexed : undefined; + }; + const register = (item, index) => { + const itemId = typeof item.id === 'string' && item.id ? item.id : undefined; + if (itemId === undefined && index === undefined) return undefined; + const previous = new Set(); + if (itemId !== undefined && byId.has(itemId)) previous.add(byId.get(itemId)); + if (index !== undefined && byIndex.has(index)) previous.add(byIndex.get(index)); + for (const identity of previous) releaseIdentity(identity); + const metadata = { + type: item.type, + name: item.name, + ...('namespace' in item ? { namespace: item.namespace } : {}), + ...(item.status !== undefined && item.status !== 'in_progress' && item.status !== 'completed' ? { status: item.status } : {}), + }; + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(JSON.stringify([itemId, index, metadata]), 'utf8'); + retain(bytes); + const identity = { itemId, outputIndex: index, item: metadata, bytes }; + if (itemId !== undefined) byId.set(itemId, identity); + if (index !== undefined) byIndex.set(index, identity); + return identity; + }; + const repairCompletion = (block, event, identity) => { + if (typeof event.arguments !== 'string') return block; + const resolved = (typeof event.item_id !== 'string' || event.item_id === '') && identity.itemId !== undefined + ? { ...event, item_id: identity.itemId } + : event; + const repaired = repairFunctionCalls({ ...identity.item, status: identity.item.status ?? 'completed', arguments: event.arguments }, schemas); + if (repaired.changed && isObject(repaired.value)) { + return replaceSseDataPayload(block, JSON.stringify({ ...resolved, arguments: repaired.value.arguments })); + } + return resolved === event ? block : replaceSseDataPayload(block, JSON.stringify(resolved)); + }; + const flushPending = (identity) => { + const output = []; + const remaining = []; + for (const completion of pending) { + const matches = completion.itemId !== undefined + ? completion.itemId === identity.itemId + && (completion.outputIndex === undefined || identity.outputIndex === undefined || completion.outputIndex === identity.outputIndex) + : completion.outputIndex !== undefined && completion.outputIndex === identity.outputIndex; + if (!matches) { remaining.push(completion); continue; } + release(completion.bytes); + const payload = sseDataPayload(completion.block); + const event = payload === null ? undefined : JSON.parse(payload); + output.push(isObject(event) ? repairCompletion(completion.block, event, identity) : completion.block); + } + pending = remaining; + return output; + }; + + const rewrite = block => { + if (disposed) return [block]; + const payload = sseDataPayload(block); + if (payload === null) return [block]; + if (payload === '[DONE]') { + const unfinished = pending.map(entry => entry.block); + dispose(); + return [...unfinished, block]; + } + let event; + try { event = JSON.parse(payload); } catch { return [block]; } + if (!isObject(event)) return [block]; + const index = outputIndexOf(event.output_index); + const itemId = typeof event.item_id === 'string' && event.item_id ? event.item_id : undefined; + try { + if ((event.type === 'response.output_item.added' || event.type === 'response.output_item.done') && isObject(event.item)) { + const identity = register(event.item, index); + const replayed = identity ? flushPending(identity) : []; + const repaired = repairFunctionCalls(event, schemas); + const output = repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block; + if (identity && (event.type === 'response.output_item.done' || replayed.length > 0)) releaseIdentity(identity); + return event.type === 'response.output_item.added' ? [output, ...replayed] : [...replayed, output]; + } + if (event.type === 'response.function_call_arguments.done' && typeof event.arguments === 'string') { + const identity = lookup(itemId, index); + if (identity) { + const output = repairCompletion(block, event, identity); + releaseIdentity(identity); + return [output]; + } + if (itemId !== undefined || index !== undefined) { + const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(block, 'utf8'); + retain(bytes); + pending.push({ block, itemId, outputIndex: index, bytes }); + return []; + } + } + if (typeof event.type === 'string' && ['response.completed', 'response.failed', 'response.incomplete', 'response.cancelled'].includes(event.type)) { + const replayed = []; + if (event.type === 'response.completed' && isObject(event.response) && Array.isArray(event.response.output) + && (event.response.status === undefined || event.response.status === 'completed')) { + for (const [slot, item] of event.response.output.entries()) { + if (!isObject(item)) continue; + const identity = register(item, slot); + if (identity) replayed.push(...flushPending(identity)); + } + } + replayed.push(...pending.map(entry => entry.block)); + const repaired = repairFunctionCalls(event, schemas); + dispose(); + return [...replayed, repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block]; + } + return [block]; + } catch (error) { + dispose(); + throw error; + } + }; + rewrite.dispose = dispose; + return rewrite; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/responses.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/responses.mjs new file mode 100644 index 0000000..d4f3364 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/responses.mjs @@ -0,0 +1,223 @@ +import { Transform } from 'node:stream'; +import { StringDecoder } from 'node:string_decoder'; +import { stripCanonicalOnlyToolFields } from './tool-groups.mjs'; +import { + collectSelfNamedNamespaceScrubAuthorization, + createSelfNamedToolCallNamespaceScrubRewrite, + scrubSelfNamedToolCallNamespaceInJson, +} from './self-named-namespace-scrub.mjs'; +import { rewriteRoutedCustomToolsForUpstream, restoreRoutedCustomCallsInJson } from './custom-tool-compat.mjs'; +import { rewriteRoutedNamespaceToolsForUpstream, restoreRoutedNamespaceCallsInJson } from './namespace-tool-compat.mjs'; +import { collectFunctionCallRepairSchemas, repairFunctionCallsInJson } from './function-call-compat.mjs'; +import { createRoutedCustomToolRestoreBlockRewrite } from './responses-custom-tool-repair.mjs'; +import { createResponsesFunctionToolRepairBlockRewrite } from './responses-function-tool-repair.mjs'; +import { createTranslatorBudget } from './translator-budget.mjs'; +import { collectDeclaredWireToolNames } from './undeclared-tool-guard.mjs'; +import { composeSseBlockRewrites, payloadRewriteAsBlockRewrite, nextSseBlock } from './sse-payload-rewrite.mjs'; + +/** One request owns both forward conversion and reverse tool identities. */ +export function prepareResponsesCompatibility(body, policy = {}) { + // Allocate wire identities while original declaration/selector kinds are still intact. + // Custom conversion then sees unique names rather than ambiguous namespace spellings. + const namespace = policy.namespaceTools === 'functions' + ? rewriteRoutedNamespaceToolsForUpstream(body, undefined, true) + : { body, aliases: new Map(), declarations: new Map() }; + // Preserve the route's apply_patch exception by original name, even after alias allocation. + const passthroughNames = new Set(['apply_patch']); + for (const [wireName, identity] of namespace.declarations) { + if (identity.kind === 'custom' && identity.name === 'apply_patch') passthroughNames.add(wireName); + } + const custom = policy.customTools && policy.customTools !== 'native' + ? rewriteRoutedCustomToolsForUpstream(namespace.body, policy.customTools === 'functions' ? false : undefined, passthroughNames) + : { body: namespace.body, names: new Set(), repairNames: new Set() }; + // Custom restoration runs before namespace restoration, so it must recognize the + // same authorized aliases, without treating native passthrough tools as converted. + const convertedCustomIdentities = new Map(); + const convertedCustomAliases = new Map(); + const selectedNamespaceCoordinates = new Set([...namespace.aliases.values()].map(identity => + JSON.stringify([identity.namespace, identity.name]))); + for (const [wireName, identity] of namespace.declarations) { + if (identity.kind === 'custom' && custom.names.has(wireName)) { + convertedCustomIdentities.set(JSON.stringify([identity.namespace, identity.name]), wireName); + } + } + for (const [alias, identity] of namespace.aliases) { + if (identity.kind === 'custom' && convertedCustomIdentities.has(JSON.stringify([identity.namespace, identity.name]))) { + custom.names.add(alias); + convertedCustomAliases.set(alias, identity.namespace); + } + } + // Resolve original coordinates and matching qualified aliases to the allocated + // custom identity before conversion. Do not broaden the bare-name authority: + // concatenated qualified spellings can belong to unrelated ordinary functions. + const normalizeCustomCallIdentity = (text) => { + if (convertedCustomAliases.size === 0) return text; + let changed = false; + let payload; + try { + payload = JSON.parse(text, (_key, value) => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + const item = value; + if (item.type === 'function_call' && typeof item.name === 'string' + && typeof item.namespace === 'string') { + const coordinate = JSON.stringify([item.namespace, item.name]); + const wireName = selectedNamespaceCoordinates.has(coordinate) + ? convertedCustomIdentities.get(coordinate) + : convertedCustomAliases.get(item.name) === item.namespace ? item.name : undefined; + if (wireName !== undefined) { + const { namespace: _namespace, ...rest } = item; + changed = true; + return { ...rest, name: wireName }; + } + } + } + return value; + }); + } catch { return text; } + return changed ? JSON.stringify(payload) : text; + }; + const schemas = policy.repairFunctionArguments ? collectFunctionCallRepairSchemas(body) : new Map(); + // Logical names remain conflict guards even after allocating distinct wire names. + const declared = new Set([...collectDeclaredWireToolNames(body), ...collectDeclaredWireToolNames(namespace.body)]); + const functionWireNames = new Set(); + for (const schema of schemas.values()) { + if (!schema.namespace) functionWireNames.add(schema.name); + else for (const [wireName, identity] of namespace.aliases) { + if (identity.namespace === schema.namespace && identity.name === schema.name) functionWireNames.add(wireName); + } + } + // Only selected namespace identities can disambiguate a self-named provider echo. + // Reuse the namespace plan's kind-aware selector decision instead of reinterpreting it. + const selectedNamespaceTools = new Set([...namespace.aliases.values()].map(identity => + JSON.stringify([identity.namespace, identity.name, identity.kind]))); + const loweredNamespaceTools = new Set([...namespace.declarations.values()].map(identity => + JSON.stringify([identity.namespace, identity.name, identity.kind]))); + const scrubAuthorization = collectSelfNamedNamespaceScrubAuthorization( + namespace.body, + new Set([...custom.names, ...custom.repairNames]), + functionWireNames, + body, + policy.namespaceTools === 'functions' + ? (ns, name, kind) => { + const key = JSON.stringify([ns, name, kind]); + return !loweredNamespaceTools.has(key) || selectedNamespaceTools.has(key); + } + : undefined, + ); + const restoreNamespace = (text) => restoreRoutedNamespaceCallsInJson(text, namespace.aliases); + return { + body: policy.namespaceTools === 'functions' ? stripCanonicalOnlyToolFields(custom.body, false) : custom.body, + needsResponseTransform: custom.names.size > 0 || custom.repairNames.size > 0 || namespace.aliases.size > 0 || schemas.size > 0, + restoreJson(text) { + let next = scrubSelfNamedToolCallNamespaceInJson(text, scrubAuthorization); + next = normalizeCustomCallIdentity(next); + next = restoreRoutedCustomCallsInJson(next, custom.names, custom.repairNames, declared); + next = restoreNamespace(next); + next = repairFunctionCallsInJson(next, schemas); + return next; + }, + createStreamRewrite() { + const budget = createTranslatorBudget(); + const stages = [ + payloadRewriteAsBlockRewrite(createSelfNamedToolCallNamespaceScrubRewrite(scrubAuthorization)), + payloadRewriteAsBlockRewrite(normalizeCustomCallIdentity), + createRoutedCustomToolRestoreBlockRewrite(custom.names, budget, custom.repairNames, declared), + payloadRewriteAsBlockRewrite(restoreNamespace), + createResponsesFunctionToolRepairBlockRewrite(schemas, budget), + ]; + const rewrite = composeSseBlockRewrites(...stages); + const dispose = rewrite.dispose; + rewrite.dispose = () => { dispose?.(); budget.dispose(); }; + return rewrite; + }, + }; +} + +const MAX_RESPONSE_BYTES = 32 * 1024 * 1024; + +class CompatibilityResponseTransform extends Transform { + constructor(prepared, sse) { + super(); + this.prepared = prepared; + this.sse = sse; + this.decoder = new StringDecoder('utf8'); + this.buffer = ''; + this.rewrite = sse ? prepared.createStreamRewrite() : undefined; + } + + drain(final = false) { + if (this.sse) { + let frame; + while ((frame = nextSseBlock(this.buffer))) { + if (Buffer.byteLength(frame.block) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.buffer = frame.rest; + for (const block of this.rewrite(frame.block)) this.push(block + frame.delimiter); + } + if (final && this.buffer) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + for (const block of this.rewrite(this.buffer)) this.push(block + '\n\n'); + this.buffer = ''; + } + } else if (final) { + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + this.push(this.prepared.restoreJson(this.buffer)); + this.buffer = ''; + } + if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded'); + } + + _transform(chunk, _encoding, callback) { + try { + this.buffer += this.decoder.write(chunk); + this.drain(); + callback(); + } catch (error) { + callback(error); + } + } + + _flush(callback) { + try { + this.buffer += this.decoder.end(); + this.drain(true); + callback(); + } catch (error) { + callback(error); + } + } + + _destroy(error, callback) { + this.buffer = ''; + this.rewrite?.dispose?.(); + callback(error); + } +} + +export function createResponsesCompatibilityAdapter(policy = {}) { + const pending = new Map(); + return { + adaptRequest(body, requestId, overrides = {}) { + pending.delete(requestId); + const now = Date.now(); + for (const [id, entry] of pending) if (now - entry.at >= 15 * 60_000) pending.delete(id); + if (!pending.has(requestId) && pending.size >= 256) throw new Error('too many in-flight compatibility requests'); + const prepared = prepareResponsesCompatibility(body, { ...policy, ...overrides }); + if (prepared.needsResponseTransform) pending.set(requestId, { prepared, at: now }); + return prepared.body === body ? null : prepared.body; + }, + releaseResponse(requestId) { + pending.delete(requestId); + }, + createResponseTransform(requestId, response) { + const entry = pending.get(requestId); + pending.delete(requestId); + if (!entry) return null; + const encoding = (response.contentEncoding ?? '').trim().toLowerCase(); + if (encoding && encoding !== 'identity') throw new Error('compressed compatibility response cannot be rewritten'); + const type = (response.contentType ?? '').toLowerCase(); + const sse = type.startsWith('text/event-stream'); + if (!sse && !type.includes('application/json')) throw new Error('unsupported compatibility response content type'); + return new CompatibilityResponseTransform(entry.prepared, sse); + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/self-named-namespace-scrub.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/self-named-namespace-scrub.mjs new file mode 100644 index 0000000..48bdd63 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/self-named-namespace-scrub.mjs @@ -0,0 +1,160 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + specs, + namespaceToolAllowed, +) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) { + if (!isPlainObject(inner) || typeof inner.name !== 'string') continue; + if (namespace !== 'functions' && namespace === inner.name + && (!namespaceToolAllowed || namespaceToolAllowed(namespace, inner.name, String(inner.type)))) { + if (inner.type === 'custom') sameNameNamespacedCustomNames.add(inner.name); + else if (inner.type === 'function') sameNameNamespacedFunctionNames.add(inner.name); + } + if (namespace === 'functions') { + if (inner.type === 'custom') bareCustomNames.add(inner.name); + else if (inner.type === 'function') bareFunctionNames.add(inner.name); + } + } + continue; + } + const nestedFunction = spec.type === 'function' && isPlainObject(spec.function) ? spec.function : undefined; + const name = typeof spec.name === 'string' && spec.name.length > 0 + ? spec.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; + if (!name) continue; + const namespace = typeof spec.namespace === 'string' ? spec.namespace : undefined; + if (namespace !== 'functions' && namespace === name + && (!namespaceToolAllowed || namespaceToolAllowed(namespace, name, String(spec.type)))) { + if (spec.type === 'custom') sameNameNamespacedCustomNames.add(name); + else if (spec.type === 'function') sameNameNamespacedFunctionNames.add(name); + } + if (!namespace || namespace === 'functions') { + if (spec.type === 'custom') bareCustomNames.add(name); + else if (spec.type === 'function') bareFunctionNames.add(name); + } + } +} + +export function collectSelfNamedNamespaceScrubAuthorization( + body, + authorizedBareCustomToolNames, + authorizedBareFunctionToolNames, + originalBody, + namespaceToolAllowed, +) { + const bareCustomNames = new Set(); + const bareFunctionNames = new Set(); + const sameNameNamespacedCustomNames = new Set(); + const sameNameNamespacedFunctionNames = new Set(); + // Lowered catalogs authorize wire spellings; original catalogs retain genuine + // same-name namespace collisions that must never be scrubbed into bare calls. + for (const catalog of [body, originalBody]) { + if (!isPlainObject(catalog)) continue; + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + catalog.tools, + namespaceToolAllowed, + ); + if (Array.isArray(catalog.input)) { + for (const item of catalog.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) { + collectBareToolSpecs( + bareCustomNames, + bareFunctionNames, + sameNameNamespacedCustomNames, + sameNameNamespacedFunctionNames, + item.tools, + namespaceToolAllowed, + ); + } + } + } + } + const authorizedCustomNames = [...bareCustomNames] + .filter(name => authorizedBareCustomToolNames.has(name)); + const authorizedFunctionNames = new Set([ + ...authorizedCustomNames, + ...[...bareFunctionNames].filter(name => authorizedBareFunctionToolNames.has(name)), + ]); + return { + customToolCallNames: new Set( + authorizedCustomNames.filter(name => !sameNameNamespacedCustomNames.has(name)), + ), + functionCallNames: new Set( + [...authorizedFunctionNames].filter(name => + !sameNameNamespacedFunctionNames.has(name) && !sameNameNamespacedCustomNames.has(name)), + ), + }; +} + +export function scrubSelfNamedToolCallNamespace(value, authorization) { + if (Array.isArray(value)) { + let changed = false; + const out = value.map(entry => { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + changed ||= result.changed; + return result.value; + }); + return changed ? { value: out, changed: true } : { value, changed: false }; + } + if (!isPlainObject(value)) return { value, changed: false }; + let changed = false; + const out = {}; + for (const [key, entry] of Object.entries(value)) { + const result = scrubSelfNamedToolCallNamespace(entry, authorization); + out[key] = result.value; + changed ||= result.changed; + } + const authorizedNames = value.type === 'custom_tool_call' + ? authorization.customToolCallNames + : value.type === 'function_call' + ? authorization.functionCallNames + : undefined; + if ( + authorizedNames + && typeof value.name === 'string' + && value.name.length > 0 + && value.namespace === value.name + && authorizedNames.has(value.name) + ) { + delete out.namespace; + changed = true; + } + return changed ? { value: out, changed: true } : { value, changed: false }; +} + +export function scrubSelfNamedToolCallNamespaceInJson(text, authorization) { + if (!text.includes('"namespace"')) return text; + let payload; + try { + payload = JSON.parse(text); + } catch { + return text; + } + const result = scrubSelfNamedToolCallNamespace(payload, authorization); + return result.changed ? JSON.stringify(result.value) : text; +} + +export function createSelfNamedToolCallNamespaceScrubRewrite(authorization) { + return payload => scrubSelfNamedToolCallNamespaceInJson(payload, authorization); +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/sse-payload-rewrite.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/sse-payload-rewrite.mjs new file mode 100644 index 0000000..4798585 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/sse-payload-rewrite.mjs @@ -0,0 +1,74 @@ +/** Adapt a payload rewrite to the block contract (replace only on change). */ +export function payloadRewriteAsBlockRewrite(rewrite) { + return (block) => { + const payload = sseDataPayload(block); + if (payload === null) return [block]; + const rewritten = rewrite(payload); + return rewritten !== payload ? [replaceSseDataPayload(block, rewritten)] : [block]; + }; +} + +/** Chain block rewrites: every block stage N emits feeds stage N+1. */ +export function composeSseBlockRewrites(...rewrites) { + const active = rewrites.filter(Boolean); + if (active.length === 0) return Object.assign((block) => [block], {}); + const composed = (block) => { + let blocks = [block]; + for (const rewrite of active) { + const next = []; + for (const current of blocks) next.push(...rewrite(current)); + blocks = next; + } + return blocks; + }; + let disposed = false; + composed.dispose = () => { + if (disposed) return; + disposed = true; + for (const rewrite of active) { + try { rewrite.dispose?.(); } catch { /* teardown must not throw */ } + } + }; + return composed; +} + +/** Split one complete SSE event block while retaining its original blank-line delimiter. */ +export function nextSseBlock(buffer) { + const match = buffer.match(/\r?\n\r?\n/); + if (!match || match.index === undefined) return null; + return { + block: buffer.slice(0, match.index), + delimiter: match[0], + rest: buffer.slice(match.index + match[0].length), + }; +} + +/** Join all data lines from one SSE event according to the event-stream field rules. */ +export function sseDataPayload(block) { + const data = []; + for (const line of block.split(/\r?\n/)) { + if (!line.startsWith('data:')) continue; + const value = line.slice(5); + data.push(value.startsWith(' ') ? value.slice(1) : value); + } + return data.length > 0 ? data.join('\n') : null; +} + +/** Replace an SSE event's data field while preserving non-data fields and newline style. */ +export function replaceSseDataPayload(block, payload) { + const newline = block.includes('\r\n') ? '\r\n' : '\n'; + const lines = block.split(/\r?\n/); + const rewritten = []; + let replaced = false; + for (const line of lines) { + if (!line.startsWith('data:')) { + rewritten.push(line); + continue; + } + if (!replaced) { + rewritten.push(`data: ${payload}`); + replaced = true; + } + } + return replaced ? rewritten.join(newline) : block; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/tool-argument-integers.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/tool-argument-integers.mjs new file mode 100644 index 0000000..9164255 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/tool-argument-integers.mjs @@ -0,0 +1,130 @@ +function asSchema(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined; +} + +function declaresInteger(schema) { + const type = schema.type; + if (type === 'integer') return true; + return Array.isArray(type) && type.includes('integer'); +} + +function declaresString(schema) { + const type = schema.type; + if (type === 'string') return true; + return Array.isArray(type) && type.includes('string'); +} + +const U64_NUMBER_FIELDS = new Set(['timeout_ms']); +const U64_NUMBER_FIELDS_BY_TOOL = new Map([ + ['wait', new Set(['yield_time_ms', 'max_tokens'])], +]); + +function declaresNumeric(schema) { + const type = schema.type; + if (type === 'integer' || type === 'number') return true; + return Array.isArray(type) && (type.includes('integer') || type.includes('number')); +} + +function resolveRef(schema, root, seen) { + const ref = schema.$ref; + if (typeof ref !== 'string' || !ref.startsWith('#/')) return schema; + if (seen.has(ref)) return undefined; + seen.add(ref); + let node = root; + for (const rawSegment of ref.slice(2).split('/')) { + const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~'); + const current = asSchema(node); + if (!current) return undefined; + node = current[segment]; + } + const resolved = asSchema(node); + return resolved ? resolveRef(resolved, root, seen) : undefined; +} + +const COMPOSITION_KEYS = ['anyOf', 'oneOf', 'allOf']; + +function compositionBranches(schema) { + const branches = []; + for (const key of COMPOSITION_KEYS) { + const value = schema[key]; + if (!Array.isArray(value)) continue; + for (const branch of value) { + const node = asSchema(branch); + if (node) branches.push(node); + } + } + return branches; +} + +function safelyIntegral(value) { + return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; +} + +function coerceValue(value, schema, root, depth, toolName, propertyName) { + if (depth > 64) return { value, changed: false }; + const resolved = schema ? resolveRef(schema, root, new Set()) : undefined; + + if (typeof value === 'number') { + if (!resolved) return { value, changed: false }; + const branches = compositionBranches(resolved); + const nativeU64Field = propertyName !== undefined + && ( + U64_NUMBER_FIELDS.has(propertyName) + || U64_NUMBER_FIELDS_BY_TOOL.get(toolName ?? '')?.has(propertyName) === true + ); + const nativeU64Declared = nativeU64Field + && (declaresNumeric(resolved) || branches.some(declaresNumeric)); + const integerDeclared = declaresInteger(resolved) + || branches.some(declaresInteger) + || nativeU64Declared; + if (!integerDeclared && safelyIntegral(value)) { + const stringDeclared = declaresString(resolved) || branches.some(declaresString); + const numericDeclared = declaresNumeric(resolved) || branches.some(declaresNumeric); + if (stringDeclared && !numericDeclared) { + return { value: String(value), changed: true }; + } + } + if (!integerDeclared || !safelyIntegral(value)) return { value, changed: false }; + return { value, changed: true }; + } + + if (Array.isArray(value)) { + const itemSchema = resolved ? asSchema(resolved.items) : undefined; + let changed = false; + const next = value.map(entry => { + const result = coerceValue(entry, itemSchema, root, depth + 1, toolName); + if (result.changed) changed = true; + return result.value; + }); + return changed ? { value: next, changed: true } : { value, changed: false }; + } + + const object = asSchema(value); + if (!object) return { value, changed: false }; + + const properties = resolved ? asSchema(resolved.properties) : undefined; + const additional = resolved ? asSchema(resolved.additionalProperties) : undefined; + let changed = false; + const next = {}; + for (const [key, entry] of Object.entries(object)) { + const childSchema = asSchema(properties?.[key]) ?? additional; + const result = coerceValue(entry, childSchema, root, depth + 1, toolName, key); + if (result.changed) changed = true; + next[key] = result.value; + } + return changed ? { value: next, changed: true } : { value, changed: false }; +} + +export function coerceIntegerToolArguments(args, parameters, toolName) { + if (!parameters || !args) return args; + if (!/\d/.test(args)) return args; + let parsed; + try { + parsed = JSON.parse(args); + } catch { + return args; + } + const result = coerceValue(parsed, parameters, parameters, 0, toolName); + if (!result.changed) return args; + return JSON.stringify(result.value); +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/tool-groups.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/tool-groups.mjs new file mode 100644 index 0000000..5b62304 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/tool-groups.mjs @@ -0,0 +1,65 @@ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** Collect top-level and Responses Lite tool containers without altering their order. */ +export function collectResponsesToolGroups(body) { + if (!isPlainObject(body)) return []; + + const groups = []; + if (Array.isArray(body.tools)) groups.push(body.tools); + if (!Array.isArray(body.input)) return groups; + + for (const item of body.input) { + if (isPlainObject(item) && item.type === 'additional_tools' && Array.isArray(item.tools)) { + groups.push(item.tools); + } + } + return groups; +} + +export const CANONICAL_ONLY_TOOL_FIELDS = [ + { field: 'external_web_access', toolTypes: new Set(['web_search', 'web_search_preview']), capabilityGated: true }, + { field: 'defer_loading' }, +]; + +export function stripCanonicalOnlyToolFields(body, includeCapabilityGated) { + if (!isPlainObject(body)) return body; + + const rewriteTools = (tools) => { + let changed = false; + const rewritten = tools.map(tool => { + if (!isPlainObject(tool)) return tool; + let next = tool; + for (const { field, toolTypes, capabilityGated } of CANONICAL_ONLY_TOOL_FIELDS) { + if (capabilityGated && !includeCapabilityGated) continue; + if (!Object.hasOwn(next, field)) continue; + if (toolTypes && (typeof next.type !== 'string' || !toolTypes.has(next.type))) continue; + const { [field]: _private, ...rest } = next; + next = rest; + } + if (next === tool) return tool; + changed = true; + return next; + }); + return changed ? rewritten : tools; + }; + + let rewrittenBody = body; + if (Array.isArray(body.tools)) { + const tools = rewriteTools(body.tools); + if (tools !== body.tools) rewrittenBody = { ...rewrittenBody, tools }; + } + if (!Array.isArray(body.input)) return rewrittenBody; + + let input; + for (let index = 0; index < body.input.length; index += 1) { + const item = body.input[index]; + if (!isPlainObject(item) || item.type !== 'additional_tools' || !Array.isArray(item.tools)) continue; + const tools = rewriteTools(item.tools); + if (tools === item.tools) continue; + input ??= [...body.input]; + input[index] = { ...item, tools }; + } + return input ? { ...rewrittenBody, input } : rewrittenBody; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/tool-name-aliases.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/tool-name-aliases.mjs new file mode 100644 index 0000000..587befb --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/tool-name-aliases.mjs @@ -0,0 +1,68 @@ +import { dottedToolName, namespacedToolName } from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** + * A dotted spelling is a safe alias only when it cannot ALSO be read as some other identity's + * canonical `ns__name`. + */ +export function dottedAliasIsUnambiguous(namespace, name) { + return !namespace.includes('__') && !name.includes('__'); +} + +export function wireToolInnerName(tool) { + if (!isPlainObject(tool)) return undefined; + const nestedFunction = tool.type === 'function' && isPlainObject(tool.function) + ? tool.function + : undefined; + return typeof tool.name === 'string' && tool.name.length > 0 + ? tool.name + : typeof nestedFunction?.name === 'string' && nestedFunction.name.length > 0 + ? nestedFunction.name + : undefined; +} + +/** + * Dotted aliases that more than one declared identity would claim, plus dotted aliases that + * collide with a canonical or bare declared name. + */ +export function collectAmbiguousDottedAliases(specGroups) { + const owners = new Map(); + const claim = (alias, identity) => { + const owner = owners.get(alias); + if (owner === undefined) owners.set(alias, identity); + else if (owner !== identity) owners.set(alias, null); + }; + for (const specs of specGroups) { + if (!Array.isArray(specs)) continue; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + if (!namespace) continue; + for (const inner of spec.tools) { + const name = wireToolInnerName(inner); + if (!name) continue; + if (namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + claim(name, JSON.stringify([undefined, name])); + continue; + } + const identity = JSON.stringify([namespace, name]); + claim(dottedToolName(namespace, name), identity); + claim(namespacedToolName(namespace, name), identity); + claim(name, identity); + } + continue; + } + const name = wireToolInnerName(spec); + if (name) claim(name, JSON.stringify([undefined, name])); + } + } + const ambiguous = new Set(); + for (const [alias, owner] of owners) if (owner === null) ambiguous.add(alias); + return ambiguous; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/tools.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/tools.mjs new file mode 100644 index 0000000..203b692 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/tools.mjs @@ -0,0 +1,33 @@ +export function namespacedToolName(namespace, name) { + return namespace ? `${namespace}__${name}` : name; +} + +export function dottedToolName(namespace, name) { + return namespace ? `${namespace}.${name}` : name; +} + +const LEGACY_SHELL_BRIDGE_TOOL_NAMES = ['exec_command', 'shell_command']; +const CODE_MODE_HELPER_TOOL_NAMES = [ + ...LEGACY_SHELL_BRIDGE_TOOL_NAMES, + 'write_stdin', + 'apply_patch', +]; + +export const CODE_MODE_EXEC_TOOL_NAME = 'exec'; + +export function normalizeDeclaredToolName(name, declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return name; + if (declared.has(name)) return name; + if (name === 'apply_patch') return CODE_MODE_EXEC_TOOL_NAME; + if (LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy))) { + return name; + } + return CODE_MODE_HELPER_TOOL_NAMES.includes(name) + ? CODE_MODE_EXEC_TOOL_NAME + : name; +} + +export function declaresCodeModeExec(declared) { + if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return false; + return !LEGACY_SHELL_BRIDGE_TOOL_NAMES.some(legacy => declared.has(legacy)); +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/translator-budget.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/translator-budget.mjs new file mode 100644 index 0000000..1f11b9f --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/translator-budget.mjs @@ -0,0 +1,34 @@ +export const TRANSLATOR_MAX_TURN_BYTES = 16 * 1024 * 1024; +export const TRANSLATOR_MAX_CALL_ARGUMENT_BYTES = 8 * 1024 * 1024; + +export class TranslatorBudgetExceededError extends Error { + constructor(kind, limit) { + super(`translator buffer limit exceeded (${kind}: ${limit} bytes)`); + this.name = 'TranslatorBudgetExceededError'; + this.kind = kind; + this.limit = limit; + } +} + +export function createTranslatorBudget(options = {}) { + const maxTurnBytes = options.maxTurnBytes ?? TRANSLATOR_MAX_TURN_BYTES; + let charged = 0; + let disposed = false; + return { + chargeRetained(bytes, scope = { kind: 'retained_collectors' }) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + if (charged + bytes > maxTurnBytes) { + throw new TranslatorBudgetExceededError(scope.kind ?? 'retained_collectors', maxTurnBytes); + } + charged += bytes; + }, + releaseRetained(bytes) { + if (disposed || !Number.isFinite(bytes) || bytes <= 0) return; + charged = Math.max(0, charged - bytes); + }, + dispose() { + disposed = true; + charged = 0; + }, + }; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/src/undeclared-tool-guard.mjs b/questions/codex-namespace-tool-collision/v1/reference/src/undeclared-tool-guard.mjs new file mode 100644 index 0000000..0cea492 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/src/undeclared-tool-guard.mjs @@ -0,0 +1,59 @@ +import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from './tool-name-aliases.mjs'; +import { + CODE_MODE_EXEC_TOOL_NAME, + dottedToolName, + namespacedToolName, +} from './tools.mjs'; + +const BUILTIN_FUNCTIONS_NAMESPACE = 'functions'; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function addWireToolName(names, tool, namespace, ambiguousDottedAliases) { + if (!isPlainObject(tool)) return; + const name = wireToolInnerName(tool); + if (!name) return; + if (!namespace || namespace === BUILTIN_FUNCTIONS_NAMESPACE) { + names.add(name); + return; + } + names.add(namespacedToolName(namespace, name)); + const dotted = dottedToolName(namespace, name); + if (dottedAliasIsUnambiguous(namespace, name) && !ambiguousDottedAliases?.has(dotted)) { + names.add(dotted); + } + if (name !== CODE_MODE_EXEC_TOOL_NAME) names.add(name); +} + +function addWireToolSpecs(names, specs, ambiguousDottedAliases) { + if (!Array.isArray(specs)) return; + for (const spec of specs) { + if (!isPlainObject(spec)) continue; + if (spec.type === 'namespace' && Array.isArray(spec.tools)) { + const namespace = typeof spec.name === 'string' ? spec.name : undefined; + for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases); + continue; + } + addWireToolName(names, spec, undefined, ambiguousDottedAliases); + } +} + +/** Tool names the outbound Responses body actually declared. */ +export function collectDeclaredWireToolNames(body) { + const names = new Set(); + if (!isPlainObject(body)) return names; + const specGroups = [body.tools]; + if (Array.isArray(body.input)) { + for (const item of body.input) { + if ( + isPlainObject(item) + && (item.type === 'additional_tools' || item.type === 'tool_search_output') + ) specGroups.push(item.tools); + } + } + const ambiguousDottedAliases = collectAmbiguousDottedAliases(specGroups); + for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases); + return names; +} diff --git a/questions/codex-namespace-tool-collision/v1/reference/tests/smoke.test.mjs b/questions/codex-namespace-tool-collision/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..bcf1887 --- /dev/null +++ b/questions/codex-namespace-tool-collision/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,121 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + createResponsesCompatibilityAdapter, + prepareResponsesCompatibility, +} from '../src/responses.mjs'; + +async function runTransform(transform, input) { + let out = ''; + transform.setEncoding('utf8'); + transform.on('data', (chunk) => { out += chunk; }); + const done = new Promise((resolve, reject) => { + transform.on('end', () => resolve(out)); + transform.on('error', reject); + }); + transform.end(input); + return done; +} + +test('lowers and restores ordinary non-colliding namespace function tools (JSON & SSE)', async () => { + const adapter = createResponsesCompatibilityAdapter({ + customTools: 'preserve-apply-patch', + namespaceTools: 'functions', + repairFunctionArguments: true, + }); + const body = { + tools: [ + { + type: 'namespace', + name: 'weather', + tools: [ + { + type: 'function', + name: 'forecast', + defer_loading: true, + parameters: { type: 'object', properties: { days: { type: 'integer' } } }, + }, + ], + }, + ], + tool_choice: { type: 'function', namespace: 'weather', name: 'forecast' }, + }; + const adapted = adapter.adaptRequest(body, 1); + assert.equal(adapted.tools.length, 1); + assert.equal(adapted.tools[0].name, 'weather__forecast'); + assert.equal('defer_loading' in adapted.tools[0], false); + assert.deepEqual(adapted.tool_choice, { type: 'function', name: 'weather__forecast' }); + + const jsonWire = JSON.stringify({ + status: 'completed', + output: [{ type: 'function_call', name: 'weather__forecast', call_id: 'c1', arguments: '{"days":3.0}' }], + }); + const restoredJson = JSON.parse(await runTransform( + adapter.createResponseTransform(1, { contentType: 'application/json', contentEncoding: '' }), + jsonWire, + )); + assert.deepEqual(restoredJson.output[0], { + type: 'function_call', + namespace: 'weather', + name: 'forecast', + call_id: 'c1', + arguments: '{"days":3}', + }); +}); + +test('lowers and restores ordinary custom tools and preserves apply_patch passthrough', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { type: 'custom', name: 'apply_patch', description: 'Patch files' }, + { type: 'custom', name: 'run_script', description: 'Run script' }, + ], + }, + { customTools: 'preserve-apply-patch', namespaceTools: 'functions', repairFunctionArguments: true }, + ); + assert.equal(prepared.body.tools[0].type, 'custom'); + assert.equal(prepared.body.tools[1].type, 'function'); + + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + output: [ + { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'run_script', arguments: '{"input":"echo hi"}' }, + ], + }))); + assert.deepEqual(restored.output[0], { + type: 'custom_tool_call', + id: 'ctc_1', + call_id: 'call_1', + name: 'run_script', + input: 'echo hi', + }); +}); + +test('repairs ordinary integer-float and bare-integer-to-string arguments without altering non-integral floats', () => { + const prepared = prepareResponsesCompatibility( + { + tools: [ + { + type: 'function', + name: 'cell_read', + parameters: { + type: 'object', + properties: { + cell_id: { type: 'string' }, + limit: { type: 'integer' }, + ratio: { type: 'integer' }, + }, + }, + }, + ], + }, + { repairFunctionArguments: true }, + ); + const restored = JSON.parse(prepared.restoreJson(JSON.stringify({ + status: 'completed', + output: [ + { type: 'function_call', name: 'cell_read', arguments: '{"cell_id":4,"limit":10.0,"ratio":1.5}' }, + ], + }))); + assert.equal(restored.output[0].arguments, '{"cell_id":"4","limit":10,"ratio":1.5}'); +}); diff --git a/questions/mcp-apps-exact-origin/v1/author/editable.json b/questions/mcp-apps-exact-origin/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/mcp-apps-exact-origin/v1/author/evaluator.mjs b/questions/mcp-apps-exact-origin/v1/author/evaluator.mjs new file mode 100644 index 0000000..6535266 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/author/evaluator.mjs @@ -0,0 +1,351 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir] = process.argv.slice(2); +const [appCsp, networkHosts, toolUi] = await Promise.all([ + import(pathToFileURL(path.join(subDir, 'app-csp.mjs')).href), + import(pathToFileURL(path.join(subDir, 'network-hosts.mjs')).href), + import(pathToFileURL(path.join(subDir, 'tool-ui.mjs')).href), +]); + +const { validateCspDomains } = appCsp; +const { isValidGhostNetworkHostPattern, ghostNetworkTargetMatches } = networkHosts; +const { + getPluginToolUi, + pluginHasToolUi, + pluginToolVisible, + pluginUiDomains, + pluginUiPermissionsExpand, + validateGhostManifest, +} = toolUi; + +function makeManifest({ hosts, connectDomains, resourceDomains, frameDomains, baseUriDomains, file = 'ui/planner.html', initialHeight }) { + const csp = {}; + if (connectDomains !== undefined) csp.connectDomains = connectDomains; + if (resourceDomains !== undefined) csp.resourceDomains = resourceDomains; + if (frameDomains !== undefined) csp.frameDomains = frameDomains; + if (baseUriDomains !== undefined) csp.baseUriDomains = baseUriDomains; + const resource = { + uri: 'ui://planner', + file, + ...(Object.keys(csp).length ? { csp } : {}), + ...(initialHeight !== undefined ? { initialHeight } : {}), + }; + return { + schemaVersion: 3, + id: 'acme-planner', + name: 'Acme Planner', + version: '1.0.0', + tools: [{ name: 'help', description: 'Open planner' }], + network: { hosts }, + mcpApps: { + ui: { + resources: [resource], + tools: { help: { resourceUri: 'ui://planner', visibility: ['model', 'app'] } }, + }, + }, + }; +} + +function check(fn, errors, name) { + try { + fn(); + return true; + } catch (err) { + errors.push(`${name}: ${err.message}`); + return false; + } +} + +const errors = []; + +const exact_loopback_http_ws = check(() => { + const raw = makeManifest({ + hosts: ['http://127.0.0.1:48731', 'ws://127.0.0.1:48731'], + connectDomains: ['ws://127.0.0.1:48731'], + resourceDomains: ['http://127.0.0.1:48731'], + }); + const res = validateGhostManifest(raw); + assert.equal(res.ok, true); + assert.deepEqual(getPluginToolUi(res.manifest)?.resources, raw.mcpApps.ui.resources); + assert.deepEqual(pluginUiDomains(res.manifest), ['ws://127.0.0.1:48731', 'http://127.0.0.1:48731']); +}, errors, 'exact_loopback_http_ws'); + +const exact_default_port_and_case = check(() => { + const wssRaw = makeManifest({ + hosts: ['wss://stream.example.com'], + connectDomains: ['wss://stream.example.com', 'wss://stream.example.com:443', 'wss://STREAM.example.com/'], + }); + assert.equal(validateGhostManifest(wssRaw).ok, true); + + const httpRaw = makeManifest({ + hosts: ['http://127.0.0.1'], + resourceDomains: ['http://127.0.0.1', 'http://127.0.0.1:80', 'http://127.0.0.1/'], + }); + assert.equal(validateGhostManifest(httpRaw).ok, true); + + const httpsRaw = makeManifest({ + hosts: ['https://api.example.com'], + frameDomains: ['https://API.example.com:443/'], + }); + assert.equal(validateGhostManifest(httpsRaw).ok, true); +}, errors, 'exact_default_port_and_case'); + +const exact_scheme_host_isolation = check(() => { + // Positive anchor so a trivial reject-all implementation cannot pass. + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['ws://127.0.0.1:48731'] })).ok, + true, + ); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://api.example.com'] })).ok, + true, + ); + + // Scheme mismatch: ws vs http, https vs wss + for (const bad of [ + makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['http://127.0.0.1:48731'] }), + makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['wss://api.example.com'] }), + makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['ws://localhost:48731'] }), + makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://*.example.com'] }), + makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://sub.api.example.com'] }), + ]) { + const res = validateGhostManifest(bad); + assert.equal(res.ok, false); + assert.ok(res.reason.includes('页面域名必须在 network.hosts 内')); + } +}, errors, 'exact_scheme_host_isolation'); + +const exact_consent_diff_preserved = check(() => { + const origin = 'ws://127.0.0.1:48731'; + const previous = makeManifest({ hosts: [origin] }); + const next = makeManifest({ hosts: [origin], connectDomains: [origin] }); + assert.equal(validateGhostManifest(previous).ok, true); + assert.equal(validateGhostManifest(next).ok, true); + assert.equal(pluginHasToolUi(next), true); + assert.deepEqual(pluginUiDomains(next), [origin]); + // Network grant already approved; adding it to page CSP still expands page authority. + assert.equal(pluginUiPermissionsExpand(previous, next), true); + assert.equal(pluginUiPermissionsExpand(next, next), false); +}, errors, 'exact_consent_diff_preserved'); + +const reject_wildcard_port_default_scheme = check(() => { + // Positive anchors + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['wss://stream.example.com'], connectDomains: ['wss://stream.example.com'] })).ok, + true, + ); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://api.example.com'] })).ok, + true, + ); + // Classic :443 placeholder bypass attempts MUST be rejected. + for (const bad of [ + makeManifest({ hosts: ['wss://stream.example.com'], connectDomains: ['wss://stream.example.com:*'] }), + makeManifest({ hosts: ['wss://stream.example.com'], connectDomains: ['wss://stream.example.com:*/'] }), + makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://api.example.com:*'] }), + makeManifest({ hosts: ['https://api.example.com'], resourceDomains: ['https://api.example.com:*/'] }), + ]) { + const res = validateGhostManifest(bad); + assert.equal(res.ok, false); + assert.ok(res.reason.includes('页面域名必须在 network.hosts 内')); + } +}, errors, 'reject_wildcard_port_default_scheme'); + +const reject_wildcard_port_explicit_port = check(() => { + // Positive anchors + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['ws://127.0.0.1:48731'] })).ok, + true, + ); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['http://127.0.0.1:443'], resourceDomains: ['http://127.0.0.1:443'] })).ok, + true, + ); + // Wildcard port against explicit port (especially :443 on http://!) MUST be rejected. + for (const bad of [ + makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['ws://127.0.0.1:*'] }), + makeManifest({ hosts: ['http://127.0.0.1:443'], resourceDomains: ['http://127.0.0.1:*'] }), + makeManifest({ hosts: ['http://[::1]:8080'], connectDomains: ['http://[::1]:*'] }), + ]) { + const res = validateGhostManifest(bad); + assert.equal(res.ok, false); + assert.ok(res.reason.includes('页面域名必须在 network.hosts 内')); + } +}, errors, 'reject_wildcard_port_explicit_port'); + +const allow_exact_non_standard_port = check(() => { + for (const good of [ + makeManifest({ hosts: ['https://api.example.com:8443'], connectDomains: ['https://api.example.com:8443'] }), + makeManifest({ hosts: ['http://[::1]:8080'], connectDomains: ['http://[::1]:8080'] }), + makeManifest({ hosts: ['http://[::1]:8080'], connectDomains: ['http://[0:0:0:0:0:0:0:1]:8080'] }), + makeManifest({ hosts: ['ws://127.0.0.1:48731'], baseUriDomains: ['ws://127.0.0.1:48731/'] }), + ]) { + assert.equal(validateGhostManifest(good).ok, true); + } +}, errors, 'allow_exact_non_standard_port'); + +const reject_mismatched_non_standard_port = check(() => { + // Positive anchor + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['https://api.example.com:8443'], connectDomains: ['https://api.example.com:8443'] })).ok, + true, + ); + for (const bad of [ + makeManifest({ hosts: ['ws://127.0.0.1:48731'], connectDomains: ['ws://127.0.0.1:48732'] }), + makeManifest({ hosts: ['http://[::1]:8080'], connectDomains: ['http://[::1]:8081'] }), + makeManifest({ hosts: ['https://api.example.com:8443'], connectDomains: ['https://api.example.com'] }), + makeManifest({ hosts: ['https://api.example.com:8443'], connectDomains: ['https://api.example.com:443'] }), + makeManifest({ hosts: ['https://api.example.com'], connectDomains: ['https://api.example.com:8443'] }), + ]) { + const res = validateGhostManifest(bad); + assert.equal(res.ok, false); + assert.ok(res.reason.includes('页面域名必须在 network.hosts 内')); + } +}, errors, 'reject_mismatched_non_standard_port'); + +const legacy_bare_domain_compat = check(() => { + assert.equal( + validateGhostManifest( + makeManifest({ + hosts: ['api.example.com'], + connectDomains: ['https://api.example.com', 'wss://api.example.com:9999', 'https://api.example.com:*'], + }), + ).ok, + true, + ); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['api.example.com'], connectDomains: ['https://other.example.com'] })).ok, + false, + ); +}, errors, 'legacy_bare_domain_compat'); + +const legacy_wildcard_subdomain_compat = check(() => { + assert.equal( + validateGhostManifest( + makeManifest({ + hosts: ['*.example.com'], + connectDomains: ['https://a.example.com', 'https://deep.sub.example.com', 'https://*.example.com'], + }), + ).ok, + true, + ); + // Apex domain and suffix spoof must be rejected. + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['*.example.com'], connectDomains: ['https://example.com'] })).ok, + false, + ); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['*.example.com'], connectDomains: ['https://evil-example.com'] })).ok, + false, + ); +}, errors, 'legacy_wildcard_subdomain_compat'); + +const strict_csp_syntax_rejection = check(() => { + const badSources = [ + 'javascript:alert(1)', + 'data:text/html,hi', + 'ftp://files.example.com', + 'file:///etc/passwd', + 'https://api.example.com/v1', + 'https://api.example.com?q=1', + 'https://api.example.com#frag', + 'https://user:pass@api.example.com', + "https://api.example.com; script-src 'unsafe-inline'", + 'https://api.example.com ', + 'https://api.example.com:65536', + 'https://a.*.example.com', + 'https://*', + ]; + for (const s of badSources) { + assert.throws(() => validateCspDomains([s]), `Expected throw for ${s}`); + assert.equal( + validateGhostManifest(makeManifest({ hosts: ['api.example.com'], connectDomains: [s] })).ok, + false, + `Expected manifest rejection for ${s}`, + ); + } + const tooMany = Array.from({ length: 101 }, (_, i) => `https://s${i}.example.com`); + assert.throws(() => validateCspDomains(tooMany)); +}, errors, 'strict_csp_syntax_rejection'); + +const strict_network_hosts_validation = check(() => { + for (const valid of [ + 'api.example.com', + '*.example.com', + 'http://127.0.0.1:48731', + 'ws://127.0.0.1:48731', + 'https://api.example.com:8443', + 'wss://stream.example.com', + 'http://[::1]:8080', + ]) { + assert.equal(isValidGhostNetworkHostPattern(valid), true, `Expected valid host pattern: ${valid}`); + } + for (const invalid of [ + 'localhost', + '*.com', + '127.0.0.1', + 'API.example.com', + 'https://api.example.com:443', + 'http://127.0.0.1:80', + 'https://api.example.com/', + 'https://api.example.com/path', + 'https://user:pass@api.example.com', + 'https://*.example.com', + 'https://api.example.com:*', + 'ftp://files.example.com', + ]) { + assert.equal(isValidGhostNetworkHostPattern(invalid), false, `Expected invalid host pattern: ${invalid}`); + } + assert.equal(ghostNetworkTargetMatches('ws://127.0.0.1:48731', new URL('ws://127.0.0.1:48731/socket')), true); + assert.equal(ghostNetworkTargetMatches('ws://127.0.0.1:48731', new URL('ws://127.0.0.1:48732/socket')), false); + assert.equal(ghostNetworkTargetMatches('api.example.com', new URL('https://api.example.com/v1')), true); + assert.equal(ghostNetworkTargetMatches('api.example.com', new URL('https://api.example.com:8443/v1')), false); +}, errors, 'strict_network_hosts_validation'); + +const manifest_ui_invariants = check(() => { + // Invalid initialHeight fails package validation, dropped on installed reads. + for (const badHeight of ['240', NaN, Infinity, -Infinity, {}, null]) { + const raw = makeManifest({ hosts: ['api.example.com'], connectDomains: ['https://api.example.com'], initialHeight: badHeight }); + const res = validateGhostManifest(raw); + assert.equal(res.ok, false); + assert.ok(res.reason.includes('initialHeight')); + const installed = getPluginToolUi(raw); + assert.ok(installed); + assert.equal('initialHeight' in installed.resources[0], false); + } + // Unsafe historical paths grant zero page authority. + for (const badFile of ['../page.html', '/page.html', 'ui/../page.html', 'ui\\page.html', 'con.html']) { + const raw = makeManifest({ hosts: ['api.example.com'], connectDomains: ['https://api.example.com'], file: badFile }); + assert.equal(validateGhostManifest(raw).ok, false); + assert.equal(getPluginToolUi(raw), undefined); + assert.equal(pluginHasToolUi(raw), false); + assert.equal(pluginToolVisible(raw, 'help', 'app'), false); + assert.deepEqual(pluginUiDomains(raw), []); + } +}, errors, 'manifest_ui_invariants'); + +trusted.emit(({ + status: 'graded', + items: { + exact_loopback_http_ws, + exact_default_port_and_case, + exact_scheme_host_isolation, + exact_consent_diff_preserved, + reject_wildcard_port_default_scheme, + reject_wildcard_port_explicit_port, + allow_exact_non_standard_port, + reject_mismatched_non_standard_port, + legacy_bare_domain_compat, + legacy_wildcard_subdomain_compat, + strict_csp_syntax_rejection, + strict_network_hosts_validation, + manifest_ui_invariants, + }, + details: { errors }, +})); diff --git a/questions/mcp-apps-exact-origin/v1/author/grade.py b/questions/mcp-apps-exact-origin/v1/author/grade.py new file mode 100644 index 0000000..4f6d478 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=180 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/mcp-apps-exact-origin/v1/author/grade_impl.py b/questions/mcp-apps-exact-origin/v1/author/grade_impl.py new file mode 100644 index 0000000..a084ae5 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/author/grade_impl.py @@ -0,0 +1,39 @@ +"""Isolated pure-Node security/protocol grader for MCP Apps exact-origin validation.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-mcp-origin-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=60 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/mcp-apps-exact-origin/v1/author/result-channel.mjs b/questions/mcp-apps-exact-origin/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/mcp-apps-exact-origin/v1/candidate/CONTRACT.md b/questions/mcp-apps-exact-origin/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..e61993a --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/CONTRACT.md @@ -0,0 +1,28 @@ +# Product & Protocol Contract + +## 1. CSP Domain Sanitization (`src/app-csp.mjs`) + +- Exports `validateCspDomains(domains)`. +- Accepts `undefined` or an array of at most `100` valid origin-shaped CSP source strings; throws `Error('MCP_APP_INVALID_CSP_DOMAIN')` on any invalid input (wrong type, length > 100, disallowed scheme, invalid host/IPv6, out-of-range port, path, query, fragment, userinfo, whitespace, or directive separator). +- Allowed schemes: `http://`, `https://`, `ws://`, `wss://`. +- Host may be an ASCII hostname (with optional leftmost `*.` subdomain wildcard) or bracketed IPv6 literal; port may be `:<0-65535>` or `:*`; a single trailing `/` is allowed. +- Returns the validated array unchanged. + +## 2. Network Host Patterns & Path Safety (`src/network-hosts.mjs`) + +- Exports `GHOST_NETWORK_MAX_HOSTS` (`8`), `isSafeGhostRelativePath`, `isValidGhostNetworkHostPattern`, `ghostNetworkHostMatches`, and `ghostNetworkTargetMatches`. +- `isValidGhostNetworkHostPattern(pattern)`: non-empty string `<= 253` chars. + - **Exact origin** (`://`): canonical HTTP(S)/WS(S) `URL.origin` (`url.origin === pattern`) with no wildcards, userinfo, path, trailing slash, uppercase, or explicit default port. + - **Legacy domain**: lowercase `>= 2` DNS labels with optional leftmost `*.` (`*.example.com`); rejects single-label hosts (`localhost`, `*.com`) and bare IPv4 literals. +- `ghostNetworkTargetMatches(pattern, url)`: exact origins grant only that exact scheme/host/port; legacy domain declarations retain HTTPS default-port (`443`) matching. +- `isSafeGhostRelativePath(p)`: non-empty string `<= 256` chars, forward slashes only, safe path segments, rejects `.`, `..`, and Windows reserved device names (`con`, `prn`, `aux`, `nul`, `com1`–`com9`, `lpt1`–`lpt9`, with or without extension). + +## 3. MCP Apps UI Validation & Authorization (`src/tool-ui.mjs`) + +- Exports `PLUGIN_UI_MIN_CINDY_VERSION`, `GHOST_TOOLS_MAX`, `CSP_KEYS`, `ghostMcpAppsValidationError`, `parseGhostUi`, `validateGhostManifest`, `getPluginToolUi`, `pluginHasToolUi`, `pluginToolVisible`, `pluginUiDomains`, and `pluginUiPermissionsExpand`. +- Every CSP source across `connectDomains`, `resourceDomains`, `frameDomains`, and `baseUriDomains` must pass `validateCspDomains` and be authorized by at least one valid entry in `network.hosts`: + - **Exact origin entries** authorize only sources whose canonical origin matches identically (exact scheme, exact host/IPv6, exact non-standard port; default ports, hostname case, and trailing `/` normalize equivalently). Wildcard ports (`:*`) and wildcard hostnames (`*`) must never match an exact origin grant. + - **Legacy domain / `*.domain` entries** retain historical hostname-only matching across schemes and ports (`*.example.com` matches any subdomain depth, never the apex or suffix spoofs). +- `validateGhostManifest(raw)`: validates `network.hosts` (max 8 entries) and `mcpApps.ui` in `'package'` mode. Non-finite `initialHeight` fails with reason containing `mcpApps.ui.resources[i].initialHeight 必须是有限数字(CSS px)`; uncovered/invalid CSP fails with reason containing `页面域名必须在 network.hosts 内`. +- `getPluginToolUi(manifest)`: parses in `'installed'` mode (drops invalid `initialHeight` without discarding valid pages; refuses unsafe HTML paths and uncovered/invalid CSP origins). +- `pluginUiDomains(manifest)` lists deduplicated CSP origins across valid UI resources; `pluginUiPermissionsExpand(previous, next)` returns `true` when adding pages, expanding tool visibility to `'app'`, or adding any new CSP domain or exact origin. diff --git a/questions/mcp-apps-exact-origin/v1/candidate/ENVIRONMENT.md b/questions/mcp-apps-exact-origin/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..d5bfdc2 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke tests covering baseline domain validation and MCP Apps manifest parsing diff --git a/questions/mcp-apps-exact-origin/v1/candidate/TASK.md b/questions/mcp-apps-exact-origin/v1/candidate/TASK.md new file mode 100644 index 0000000..4db1fa1 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/TASK.md @@ -0,0 +1,10 @@ +# Task + +Plugin manifests that declare exact HTTP(S)/WS(S) origins in `network.hosts` (for example `http://127.0.0.1:48731`, `ws://127.0.0.1:48731`, `https://api.example.com:8443`, `wss://stream.example.com`, or `http://[::1]:8080`) are failing MCP Apps UI validation at install and runtime, and installation consent diffing fails to detect new exact-origin UI permissions. + +Inspect the codebase (`src/`), read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable defects across manifest validation, CSP domain sanitization, exact-origin authorization, and consent diffing while preserving all security boundaries and legacy domain compatibility. + +- Run `npm test` and add thorough verification tests as needed. +- Document your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/mcp-apps-exact-origin/v1/candidate/package.json b/questions/mcp-apps-exact-origin/v1/candidate/package.json new file mode 100644 index 0000000..788602d --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-mcp-apps-exact-origin", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/mcp-apps-exact-origin/v1/candidate/src/app-csp.mjs b/questions/mcp-apps-exact-origin/v1/candidate/src/app-csp.mjs new file mode 100644 index 0000000..4430bdc --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/src/app-csp.mjs @@ -0,0 +1,23 @@ +/** No schemes, directives, quotes, whitespace, credentials or paths from a CSP source. */ +export function validateCspDomains(domains) { + if (domains && (!Array.isArray(domains) || domains.length > 100)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return (domains ?? []).map((source) => { + if ( + typeof source !== 'string' || + !/^(https?|wss?):\/\/(?:\*\.)?(?:[a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(?::(?:[0-9]{1,5}|\*))?\/?$/.test( + source, + ) + ) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + const url = new URL( + source.replace('://*.', '://wildcard.').replace(/:\*(\/?)$/, ':443$1'), + ); + if (!url.hostname || (url.port && Number(url.port) > 65535)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return source; + }); +} diff --git a/questions/mcp-apps-exact-origin/v1/candidate/src/network-hosts.mjs b/questions/mcp-apps-exact-origin/v1/candidate/src/network-hosts.mjs new file mode 100644 index 0000000..3111ee9 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/src/network-hosts.mjs @@ -0,0 +1,60 @@ +export const GHOST_NETWORK_MAX_HOSTS = 8; + +const GHOST_PATH_SEGMENT_RE = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,63}$/; +const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i; +const GHOST_NETWORK_LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; + +export function isSafeGhostRelativePath(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 256) return false; + if (p.includes('\\')) return false; + const segments = p.split('/'); + return segments.every( + (seg) => + GHOST_PATH_SEGMENT_RE.test(seg) && + seg !== '.' && + seg !== '..' && + !WINDOWS_RESERVED_NAME_RE.test(seg), + ); +} + +/** + * Valid network.hosts entry: + * - Legacy domain: lowercase >=2 DNS labels, optional leftmost `*.` (`*.example.com`), no bare IPs. + * - Exact origin: canonical HTTP(S)/WS(S) `URL.origin` without wildcards, userinfo, path, or trailing slash. + */ +export function isValidGhostNetworkHostPattern(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 253) return false; + if (p.includes('://')) { + try { + const url = new URL(p); + return ( + ['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol) && + url.origin === p && + !url.hostname.includes('*') && + !url.username && + !url.password + ); + } catch { + return false; + } + } + const bare = p.startsWith('*.') ? p.slice(2) : p; + const labels = bare.split('.'); + if (labels.length < 2) return false; + if (labels.every((l) => /^\d+$/.test(l))) return false; + return labels.every((l) => GHOST_NETWORK_LABEL_RE.test(l)); +} + +export function ghostNetworkHostMatches(pattern, hostname) { + if (pattern.startsWith('*.')) { + return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1; + } + return hostname === pattern; +} + +/** Existing domain declarations retain HTTPS:443; an origin grants exactly one protocol/host/port. */ +export function ghostNetworkTargetMatches(pattern, url) { + return pattern.includes('://') + ? pattern === url.origin + : url.protocol === 'https:' && url.port === '' && ghostNetworkHostMatches(pattern, url.hostname); +} diff --git a/questions/mcp-apps-exact-origin/v1/candidate/src/tool-ui.mjs b/questions/mcp-apps-exact-origin/v1/candidate/src/tool-ui.mjs new file mode 100644 index 0000000..2fdda20 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/src/tool-ui.mjs @@ -0,0 +1,233 @@ +import { validateCspDomains } from './app-csp.mjs'; +import { + GHOST_NETWORK_MAX_HOSTS, + isSafeGhostRelativePath, + isValidGhostNetworkHostPattern, +} from './network-hosts.mjs'; + +export const PLUGIN_UI_MIN_CINDY_VERSION = '0.1.122-beta'; +export const GHOST_TOOLS_MAX = 64; +export const CSP_KEYS = ['connectDomains', 'resourceDomains', 'frameDomains', 'baseUriDomains']; + +const object = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v); +const safeKey = (key) => + /^[a-z][a-z0-9_-]{0,63}$/.test(key) && !['__proto__', 'constructor', 'prototype'].includes(key); +const invalidInitialHeight = (value) => value !== undefined && !Number.isFinite(value); + +export function ghostMcpAppsValidationError(raw) { + if (object(raw) && object(raw.ui) && Array.isArray(raw.ui.resources) && raw.ui.resources.length <= 16) { + const index = raw.ui.resources.findIndex( + (resource) => object(resource) && invalidInitialHeight(resource.initialHeight), + ); + if (index >= 0) return `mcpApps.ui.resources[${index}].initialHeight 必须是有限数字(CSS px)`; + } + return 'mcpApps.ui 页面或工具声明无效,页面域名必须在 network.hosts 内'; +} + +export function parseGhostUi( + raw, + tools, + hosts, + safePath = isSafeGhostRelativePath, + source = 'package', +) { + if ( + !object(raw) || + !Array.isArray(raw.resources) || + !object(raw.tools) || + (!raw.resources.length && !Object.keys(raw.tools).length) || + raw.resources.length > 16 || + Object.keys(raw.tools).length > GHOST_TOOLS_MAX + ) { + return null; + } + + const uris = new Set(); + let resources = raw.resources; + + for (const [index, resource] of raw.resources.entries()) { + if ( + !object(resource) || + typeof resource.uri !== 'string' || + !resource.uri.startsWith('ui://') || + resource.uri.length <= 5 || + /[\s\x00-\x1f\x7f]/.test(resource.uri) || + uris.has(resource.uri) || + !safePath(resource.file) || + typeof resource.file !== 'string' || + !/\.html?$/i.test(resource.file) || + (resource.prefersBorder !== undefined && typeof resource.prefersBorder !== 'boolean') || + (resource.hostFullscreenButton !== undefined && + typeof resource.hostFullscreenButton !== 'boolean') || + (resource.domain !== undefined && typeof resource.domain !== 'string') + ) { + return null; + } + + if (invalidInitialHeight(resource.initialHeight)) { + if (source === 'package') return null; + if (resources === raw.resources) resources = raw.resources.slice(); + const { initialHeight: _ignored, ...page } = resource; + resources[index] = page; + } + + uris.add(resource.uri); + + if ( + resource.permissions !== undefined && + (!object(resource.permissions) || + Object.entries(resource.permissions).some( + ([key, value]) => + !['camera', 'microphone', 'geolocation', 'clipboardWrite'].includes(key) || + !object(value) || + Object.keys(value).length > 0, + )) + ) { + return null; + } + + if (resource.csp !== undefined) { + if (!object(resource.csp)) return null; + for (const key of CSP_KEYS) { + const domains = resource.csp[key]; + if (domains !== undefined && (!Array.isArray(domains) || domains.some((v) => typeof v !== 'string'))) { + return null; + } + try { + const origins = validateCspDomains(domains); + for (const origin of origins) { + const hostname = new URL(origin.replace(/:\*(\/?)$/, ':443$1')).hostname.toLowerCase(); + if ( + !hosts.some( + (pattern) => + hostname === pattern || + (pattern.startsWith('*.') && + hostname.endsWith(pattern.slice(1)) && + hostname.length > pattern.length - 1), + ) + ) { + return null; + } + } + } catch { + return null; + } + } + } + } + + const names = new Set(tools.map((tool) => tool.name)); + for (const [name, link] of Object.entries(raw.tools)) { + if ( + !safeKey(name) || + !names.has(name) || + !object(link) || + (link.resourceUri !== undefined && + (typeof link.resourceUri !== 'string' || !uris.has(link.resourceUri))) || + (link.visibility !== undefined && + (!Array.isArray(link.visibility) || + !link.visibility.length || + link.visibility.some((v) => v !== 'model' && v !== 'app'))) + ) { + return null; + } + } + + return resources === raw.resources ? raw : { ...raw, resources }; +} + +export function validateGhostManifest(raw) { + if (!object(raw)) return { ok: false, reason: 'manifest 必须是对象' }; + if (raw.schemaVersion !== undefined && raw.schemaVersion !== 3) { + return { ok: false, reason: '仅支持 schemaVersion 3' }; + } + const tools = raw.tools ?? []; + if (!Array.isArray(tools) || tools.some((t) => !object(t) || typeof t.name !== 'string')) { + return { ok: false, reason: 'tools 声明无效' }; + } + let hosts = []; + if (raw.network !== undefined) { + if (!object(raw.network)) return { ok: false, reason: 'network 声明无效' }; + if (raw.network.hosts !== undefined) { + if ( + !Array.isArray(raw.network.hosts) || + raw.network.hosts.length > GHOST_NETWORK_MAX_HOSTS || + raw.network.hosts.some((h) => !isValidGhostNetworkHostPattern(h)) + ) { + return { ok: false, reason: 'network.hosts 包含无效域名或 origin' }; + } + hosts = raw.network.hosts; + } + } + if (raw.mcpApps !== undefined) { + if (!object(raw.mcpApps)) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + if (raw.mcpApps.ui !== undefined) { + const ui = parseGhostUi(raw.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'package'); + if (!ui) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + } + } + return { ok: true, manifest: raw }; +} + +/** Only valid declarations grant page authority, including on historical read paths. */ +export function getPluginToolUi(manifest) { + if (!object(manifest)) return undefined; + if ((manifest.schemaVersion !== undefined && manifest.schemaVersion !== 3) || !object(manifest.mcpApps)) { + return undefined; + } + const tools = manifest.tools ?? []; + const hosts = object(manifest.network) ? manifest.network.hosts ?? [] : []; + if ( + !Array.isArray(tools) || + tools.some((tool) => !object(tool) || typeof tool.name !== 'string') || + !Array.isArray(hosts) || + hosts.some((host) => typeof host !== 'string') + ) { + return undefined; + } + return parseGhostUi(manifest.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'installed') ?? undefined; +} + +export function pluginHasToolUi(manifest) { + return Boolean(getPluginToolUi(manifest)); +} + +export function pluginToolVisible(manifest, name, audience) { + const link = getPluginToolUi(manifest)?.tools[name]; + return link ? !link.visibility || link.visibility.includes(audience) : audience === 'model'; +} + +export function pluginUiDomains(manifest) { + return [ + ...new Set( + (getPluginToolUi(manifest)?.resources ?? []).flatMap((resource) => + CSP_KEYS.flatMap((key) => resource.csp?.[key] ?? []), + ), + ), + ]; +} + +export function pluginUiPermissionsExpand(previous, next) { + const previousUi = getPluginToolUi(previous); + const nextUi = getPluginToolUi(next); + const remaining = [...(previousUi?.resources ?? [])]; + for (const resource of [...(nextUi?.resources ?? [])].sort( + (a, b) => + Number(previousUi?.resources.some((old) => old.uri === b.uri)) - + Number(previousUi?.resources.some((old) => old.uri === a.uri)), + )) { + let index = remaining.findIndex((old) => old.uri === resource.uri); + if (index < 0) index = remaining.findIndex((old) => old.file === resource.file); + const before = remaining[index]; + if ( + !before || + CSP_KEYS.some((key) => resource.csp?.[key]?.some((domain) => !before.csp?.[key]?.includes(domain))) + ) { + return true; + } + remaining.splice(index, 1); + } + return Object.keys(nextUi?.tools ?? {}).some( + (name) => pluginToolVisible(next, name, 'app') && !pluginToolVisible(previous, name, 'app'), + ); +} diff --git a/questions/mcp-apps-exact-origin/v1/candidate/tests/smoke.test.mjs b/questions/mcp-apps-exact-origin/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..f2b741c --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,66 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { validateCspDomains } from '../src/app-csp.mjs'; +import { isValidGhostNetworkHostPattern } from '../src/network-hosts.mjs'; +import { + getPluginToolUi, + pluginUiDomains, + pluginUiPermissionsExpand, + validateGhostManifest, +} from '../src/tool-ui.mjs'; + +const baseManifest = { + schemaVersion: 3, + id: 'acme-planner', + name: 'Acme Planner', + version: '1.0.0', + tools: [{ name: 'help', description: 'Open planner' }], + network: { hosts: ['api.example.com', '*.cdn.example.com'] }, + mcpApps: { + ui: { + resources: [ + { + uri: 'ui://planner', + file: 'ui/planner.html', + csp: { + connectDomains: ['https://api.example.com'], + resourceDomains: ['https://static.cdn.example.com'], + }, + }, + ], + tools: { help: { resourceUri: 'ui://planner', visibility: ['model', 'app'] } }, + }, + }, +}; + +test('validates baseline domain and wildcard subdomain manifests', () => { + const res = validateGhostManifest(baseManifest); + assert.equal(res.ok, true); + assert.deepEqual(pluginUiDomains(res.manifest), [ + 'https://api.example.com', + 'https://static.cdn.example.com', + ]); + assert.equal(pluginUiPermissionsExpand(baseManifest, baseManifest), false); +}); + +test('validateCspDomains and isValidGhostNetworkHostPattern enforce strict syntax', () => { + assert.deepEqual(validateCspDomains(['https://api.example.com:8443']), ['https://api.example.com:8443']); + assert.throws(() => validateCspDomains(['javascript:alert(1)']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.throws(() => validateCspDomains(['https://user:pass@api.example.com']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.equal(isValidGhostNetworkHostPattern('ws://127.0.0.1:48731'), true); + assert.equal(isValidGhostNetworkHostPattern('https://api.example.com:443'), false); +}); + +test('getPluginToolUi strips invalid initialHeight on installed manifests while rejecting unsafe paths', () => { + const stored = structuredClone(baseManifest); + stored.mcpApps.ui.resources[0].initialHeight = NaN; + assert.equal(validateGhostManifest(stored).ok, false); + const installed = getPluginToolUi(stored); + assert.ok(installed); + assert.equal('initialHeight' in installed.resources[0], false); + + const traversal = structuredClone(baseManifest); + traversal.mcpApps.ui.resources[0].file = '../escape.html'; + assert.equal(getPluginToolUi(traversal), undefined); +}); diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/CONTRACT.md b/questions/mcp-apps-exact-origin/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..e61993a --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,28 @@ +# Product & Protocol Contract + +## 1. CSP Domain Sanitization (`src/app-csp.mjs`) + +- Exports `validateCspDomains(domains)`. +- Accepts `undefined` or an array of at most `100` valid origin-shaped CSP source strings; throws `Error('MCP_APP_INVALID_CSP_DOMAIN')` on any invalid input (wrong type, length > 100, disallowed scheme, invalid host/IPv6, out-of-range port, path, query, fragment, userinfo, whitespace, or directive separator). +- Allowed schemes: `http://`, `https://`, `ws://`, `wss://`. +- Host may be an ASCII hostname (with optional leftmost `*.` subdomain wildcard) or bracketed IPv6 literal; port may be `:<0-65535>` or `:*`; a single trailing `/` is allowed. +- Returns the validated array unchanged. + +## 2. Network Host Patterns & Path Safety (`src/network-hosts.mjs`) + +- Exports `GHOST_NETWORK_MAX_HOSTS` (`8`), `isSafeGhostRelativePath`, `isValidGhostNetworkHostPattern`, `ghostNetworkHostMatches`, and `ghostNetworkTargetMatches`. +- `isValidGhostNetworkHostPattern(pattern)`: non-empty string `<= 253` chars. + - **Exact origin** (`://`): canonical HTTP(S)/WS(S) `URL.origin` (`url.origin === pattern`) with no wildcards, userinfo, path, trailing slash, uppercase, or explicit default port. + - **Legacy domain**: lowercase `>= 2` DNS labels with optional leftmost `*.` (`*.example.com`); rejects single-label hosts (`localhost`, `*.com`) and bare IPv4 literals. +- `ghostNetworkTargetMatches(pattern, url)`: exact origins grant only that exact scheme/host/port; legacy domain declarations retain HTTPS default-port (`443`) matching. +- `isSafeGhostRelativePath(p)`: non-empty string `<= 256` chars, forward slashes only, safe path segments, rejects `.`, `..`, and Windows reserved device names (`con`, `prn`, `aux`, `nul`, `com1`–`com9`, `lpt1`–`lpt9`, with or without extension). + +## 3. MCP Apps UI Validation & Authorization (`src/tool-ui.mjs`) + +- Exports `PLUGIN_UI_MIN_CINDY_VERSION`, `GHOST_TOOLS_MAX`, `CSP_KEYS`, `ghostMcpAppsValidationError`, `parseGhostUi`, `validateGhostManifest`, `getPluginToolUi`, `pluginHasToolUi`, `pluginToolVisible`, `pluginUiDomains`, and `pluginUiPermissionsExpand`. +- Every CSP source across `connectDomains`, `resourceDomains`, `frameDomains`, and `baseUriDomains` must pass `validateCspDomains` and be authorized by at least one valid entry in `network.hosts`: + - **Exact origin entries** authorize only sources whose canonical origin matches identically (exact scheme, exact host/IPv6, exact non-standard port; default ports, hostname case, and trailing `/` normalize equivalently). Wildcard ports (`:*`) and wildcard hostnames (`*`) must never match an exact origin grant. + - **Legacy domain / `*.domain` entries** retain historical hostname-only matching across schemes and ports (`*.example.com` matches any subdomain depth, never the apex or suffix spoofs). +- `validateGhostManifest(raw)`: validates `network.hosts` (max 8 entries) and `mcpApps.ui` in `'package'` mode. Non-finite `initialHeight` fails with reason containing `mcpApps.ui.resources[i].initialHeight 必须是有限数字(CSS px)`; uncovered/invalid CSP fails with reason containing `页面域名必须在 network.hosts 内`. +- `getPluginToolUi(manifest)`: parses in `'installed'` mode (drops invalid `initialHeight` without discarding valid pages; refuses unsafe HTML paths and uncovered/invalid CSP origins). +- `pluginUiDomains(manifest)` lists deduplicated CSP origins across valid UI resources; `pluginUiPermissionsExpand(previous, next)` returns `true` when adding pages, expanding tool visibility to `'app'`, or adding any new CSP domain or exact origin. diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/ENVIRONMENT.md b/questions/mcp-apps-exact-origin/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..d5bfdc2 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke tests covering baseline domain validation and MCP Apps manifest parsing diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/TASK.md b/questions/mcp-apps-exact-origin/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..4db1fa1 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/TASK.md @@ -0,0 +1,10 @@ +# Task + +Plugin manifests that declare exact HTTP(S)/WS(S) origins in `network.hosts` (for example `http://127.0.0.1:48731`, `ws://127.0.0.1:48731`, `https://api.example.com:8443`, `wss://stream.example.com`, or `http://[::1]:8080`) are failing MCP Apps UI validation at install and runtime, and installation consent diffing fails to detect new exact-origin UI permissions. + +Inspect the codebase (`src/`), read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable defects across manifest validation, CSP domain sanitization, exact-origin authorization, and consent diffing while preserving all security boundaries and legacy domain compatibility. + +- Run `npm test` and add thorough verification tests as needed. +- Document your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/package.json b/questions/mcp-apps-exact-origin/v1/controls/incomplete/package.json new file mode 100644 index 0000000..788602d --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-mcp-apps-exact-origin", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/app-csp.mjs b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/app-csp.mjs new file mode 100644 index 0000000..4430bdc --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/app-csp.mjs @@ -0,0 +1,23 @@ +/** No schemes, directives, quotes, whitespace, credentials or paths from a CSP source. */ +export function validateCspDomains(domains) { + if (domains && (!Array.isArray(domains) || domains.length > 100)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return (domains ?? []).map((source) => { + if ( + typeof source !== 'string' || + !/^(https?|wss?):\/\/(?:\*\.)?(?:[a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(?::(?:[0-9]{1,5}|\*))?\/?$/.test( + source, + ) + ) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + const url = new URL( + source.replace('://*.', '://wildcard.').replace(/:\*(\/?)$/, ':443$1'), + ); + if (!url.hostname || (url.port && Number(url.port) > 65535)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return source; + }); +} diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/network-hosts.mjs b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/network-hosts.mjs new file mode 100644 index 0000000..3111ee9 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/network-hosts.mjs @@ -0,0 +1,60 @@ +export const GHOST_NETWORK_MAX_HOSTS = 8; + +const GHOST_PATH_SEGMENT_RE = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,63}$/; +const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i; +const GHOST_NETWORK_LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; + +export function isSafeGhostRelativePath(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 256) return false; + if (p.includes('\\')) return false; + const segments = p.split('/'); + return segments.every( + (seg) => + GHOST_PATH_SEGMENT_RE.test(seg) && + seg !== '.' && + seg !== '..' && + !WINDOWS_RESERVED_NAME_RE.test(seg), + ); +} + +/** + * Valid network.hosts entry: + * - Legacy domain: lowercase >=2 DNS labels, optional leftmost `*.` (`*.example.com`), no bare IPs. + * - Exact origin: canonical HTTP(S)/WS(S) `URL.origin` without wildcards, userinfo, path, or trailing slash. + */ +export function isValidGhostNetworkHostPattern(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 253) return false; + if (p.includes('://')) { + try { + const url = new URL(p); + return ( + ['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol) && + url.origin === p && + !url.hostname.includes('*') && + !url.username && + !url.password + ); + } catch { + return false; + } + } + const bare = p.startsWith('*.') ? p.slice(2) : p; + const labels = bare.split('.'); + if (labels.length < 2) return false; + if (labels.every((l) => /^\d+$/.test(l))) return false; + return labels.every((l) => GHOST_NETWORK_LABEL_RE.test(l)); +} + +export function ghostNetworkHostMatches(pattern, hostname) { + if (pattern.startsWith('*.')) { + return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1; + } + return hostname === pattern; +} + +/** Existing domain declarations retain HTTPS:443; an origin grants exactly one protocol/host/port. */ +export function ghostNetworkTargetMatches(pattern, url) { + return pattern.includes('://') + ? pattern === url.origin + : url.protocol === 'https:' && url.port === '' && ghostNetworkHostMatches(pattern, url.hostname); +} diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/tool-ui.mjs b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/tool-ui.mjs new file mode 100644 index 0000000..f45f239 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/src/tool-ui.mjs @@ -0,0 +1,236 @@ +import { validateCspDomains } from './app-csp.mjs'; +import { + GHOST_NETWORK_MAX_HOSTS, + isSafeGhostRelativePath, + isValidGhostNetworkHostPattern, +} from './network-hosts.mjs'; + +export const PLUGIN_UI_MIN_CINDY_VERSION = '0.1.122-beta'; +export const GHOST_TOOLS_MAX = 64; +export const CSP_KEYS = ['connectDomains', 'resourceDomains', 'frameDomains', 'baseUriDomains']; + +const object = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v); +const safeKey = (key) => + /^[a-z][a-z0-9_-]{0,63}$/.test(key) && !['__proto__', 'constructor', 'prototype'].includes(key); +const invalidInitialHeight = (value) => value !== undefined && !Number.isFinite(value); + +export function ghostMcpAppsValidationError(raw) { + if (object(raw) && object(raw.ui) && Array.isArray(raw.ui.resources) && raw.ui.resources.length <= 16) { + const index = raw.ui.resources.findIndex( + (resource) => object(resource) && invalidInitialHeight(resource.initialHeight), + ); + if (index >= 0) return `mcpApps.ui.resources[${index}].initialHeight 必须是有限数字(CSS px)`; + } + return 'mcpApps.ui 页面或工具声明无效,页面域名必须在 network.hosts 内'; +} + +export function parseGhostUi( + raw, + tools, + hosts, + safePath = isSafeGhostRelativePath, + source = 'package', +) { + if ( + !object(raw) || + !Array.isArray(raw.resources) || + !object(raw.tools) || + (!raw.resources.length && !Object.keys(raw.tools).length) || + raw.resources.length > 16 || + Object.keys(raw.tools).length > GHOST_TOOLS_MAX + ) { + return null; + } + + const uris = new Set(); + let resources = raw.resources; + + for (const [index, resource] of raw.resources.entries()) { + if ( + !object(resource) || + typeof resource.uri !== 'string' || + !resource.uri.startsWith('ui://') || + resource.uri.length <= 5 || + /[\s\x00-\x1f\x7f]/.test(resource.uri) || + uris.has(resource.uri) || + !safePath(resource.file) || + typeof resource.file !== 'string' || + !/\.html?$/i.test(resource.file) || + (resource.prefersBorder !== undefined && typeof resource.prefersBorder !== 'boolean') || + (resource.hostFullscreenButton !== undefined && + typeof resource.hostFullscreenButton !== 'boolean') || + (resource.domain !== undefined && typeof resource.domain !== 'string') + ) { + return null; + } + + if (invalidInitialHeight(resource.initialHeight)) { + if (source === 'package') return null; + if (resources === raw.resources) resources = raw.resources.slice(); + const { initialHeight: _ignored, ...page } = resource; + resources[index] = page; + } + + uris.add(resource.uri); + + if ( + resource.permissions !== undefined && + (!object(resource.permissions) || + Object.entries(resource.permissions).some( + ([key, value]) => + !['camera', 'microphone', 'geolocation', 'clipboardWrite'].includes(key) || + !object(value) || + Object.keys(value).length > 0, + )) + ) { + return null; + } + + if (resource.csp !== undefined) { + if (!object(resource.csp)) return null; + for (const key of CSP_KEYS) { + const domains = resource.csp[key]; + if (domains !== undefined && (!Array.isArray(domains) || domains.some((v) => typeof v !== 'string'))) { + return null; + } + try { + const origins = validateCspDomains(domains); + for (const origin of origins) { + const wildcardPort = /:\*\/?$/.test(origin); + const url = new URL(origin.replace(/:\*(\/?)$/, ':443$1')); + const hostname = url.hostname.toLowerCase(); + if ( + !hosts.some((pattern) => { + if (pattern.includes('://')) { + return !wildcardPort && !hostname.includes('*') && pattern === url.origin; + } + // Incomplete control: rejects :* on host-only patterns too AND breaks legacy *.domain wildcard matching. + if (wildcardPort) return false; + return hostname === pattern; + }) + ) { + return null; + } + } + } catch { + return null; + } + } + } + } + + const names = new Set(tools.map((tool) => tool.name)); + for (const [name, link] of Object.entries(raw.tools)) { + if ( + !safeKey(name) || + !names.has(name) || + !object(link) || + (link.resourceUri !== undefined && + (typeof link.resourceUri !== 'string' || !uris.has(link.resourceUri))) || + (link.visibility !== undefined && + (!Array.isArray(link.visibility) || + !link.visibility.length || + link.visibility.some((v) => v !== 'model' && v !== 'app'))) + ) { + return null; + } + } + + return resources === raw.resources ? raw : { ...raw, resources }; +} + +export function validateGhostManifest(raw) { + if (!object(raw)) return { ok: false, reason: 'manifest 必须是对象' }; + if (raw.schemaVersion !== undefined && raw.schemaVersion !== 3) { + return { ok: false, reason: '仅支持 schemaVersion 3' }; + } + const tools = raw.tools ?? []; + if (!Array.isArray(tools) || tools.some((t) => !object(t) || typeof t.name !== 'string')) { + return { ok: false, reason: 'tools 声明无效' }; + } + let hosts = []; + if (raw.network !== undefined) { + if (!object(raw.network)) return { ok: false, reason: 'network 声明无效' }; + if (raw.network.hosts !== undefined) { + if ( + !Array.isArray(raw.network.hosts) || + raw.network.hosts.length > GHOST_NETWORK_MAX_HOSTS || + raw.network.hosts.some((h) => !isValidGhostNetworkHostPattern(h)) + ) { + return { ok: false, reason: 'network.hosts 包含无效域名或 origin' }; + } + hosts = raw.network.hosts; + } + } + if (raw.mcpApps !== undefined) { + if (!object(raw.mcpApps)) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + if (raw.mcpApps.ui !== undefined) { + const ui = parseGhostUi(raw.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'package'); + if (!ui) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + } + } + return { ok: true, manifest: raw }; +} + +/** Only valid declarations grant page authority, including on historical read paths. */ +export function getPluginToolUi(manifest) { + if (!object(manifest)) return undefined; + if ((manifest.schemaVersion !== undefined && manifest.schemaVersion !== 3) || !object(manifest.mcpApps)) { + return undefined; + } + const tools = manifest.tools ?? []; + const hosts = object(manifest.network) ? manifest.network.hosts ?? [] : []; + if ( + !Array.isArray(tools) || + tools.some((tool) => !object(tool) || typeof tool.name !== 'string') || + !Array.isArray(hosts) || + hosts.some((host) => typeof host !== 'string') + ) { + return undefined; + } + return parseGhostUi(manifest.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'installed') ?? undefined; +} + +export function pluginHasToolUi(manifest) { + return Boolean(getPluginToolUi(manifest)); +} + +export function pluginToolVisible(manifest, name, audience) { + const link = getPluginToolUi(manifest)?.tools[name]; + return link ? !link.visibility || link.visibility.includes(audience) : audience === 'model'; +} + +export function pluginUiDomains(manifest) { + return [ + ...new Set( + (getPluginToolUi(manifest)?.resources ?? []).flatMap((resource) => + CSP_KEYS.flatMap((key) => resource.csp?.[key] ?? []), + ), + ), + ]; +} + +export function pluginUiPermissionsExpand(previous, next) { + const previousUi = getPluginToolUi(previous); + const nextUi = getPluginToolUi(next); + const remaining = [...(previousUi?.resources ?? [])]; + for (const resource of [...(nextUi?.resources ?? [])].sort( + (a, b) => + Number(previousUi?.resources.some((old) => old.uri === b.uri)) - + Number(previousUi?.resources.some((old) => old.uri === a.uri)), + )) { + let index = remaining.findIndex((old) => old.uri === resource.uri); + if (index < 0) index = remaining.findIndex((old) => old.file === resource.file); + const before = remaining[index]; + if ( + !before || + CSP_KEYS.some((key) => resource.csp?.[key]?.some((domain) => !before.csp?.[key]?.includes(domain))) + ) { + return true; + } + remaining.splice(index, 1); + } + return Object.keys(nextUi?.tools ?? {}).some( + (name) => pluginToolVisible(next, name, 'app') && !pluginToolVisible(previous, name, 'app'), + ); +} diff --git a/questions/mcp-apps-exact-origin/v1/controls/incomplete/tests/smoke.test.mjs b/questions/mcp-apps-exact-origin/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..f2b741c --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,66 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { validateCspDomains } from '../src/app-csp.mjs'; +import { isValidGhostNetworkHostPattern } from '../src/network-hosts.mjs'; +import { + getPluginToolUi, + pluginUiDomains, + pluginUiPermissionsExpand, + validateGhostManifest, +} from '../src/tool-ui.mjs'; + +const baseManifest = { + schemaVersion: 3, + id: 'acme-planner', + name: 'Acme Planner', + version: '1.0.0', + tools: [{ name: 'help', description: 'Open planner' }], + network: { hosts: ['api.example.com', '*.cdn.example.com'] }, + mcpApps: { + ui: { + resources: [ + { + uri: 'ui://planner', + file: 'ui/planner.html', + csp: { + connectDomains: ['https://api.example.com'], + resourceDomains: ['https://static.cdn.example.com'], + }, + }, + ], + tools: { help: { resourceUri: 'ui://planner', visibility: ['model', 'app'] } }, + }, + }, +}; + +test('validates baseline domain and wildcard subdomain manifests', () => { + const res = validateGhostManifest(baseManifest); + assert.equal(res.ok, true); + assert.deepEqual(pluginUiDomains(res.manifest), [ + 'https://api.example.com', + 'https://static.cdn.example.com', + ]); + assert.equal(pluginUiPermissionsExpand(baseManifest, baseManifest), false); +}); + +test('validateCspDomains and isValidGhostNetworkHostPattern enforce strict syntax', () => { + assert.deepEqual(validateCspDomains(['https://api.example.com:8443']), ['https://api.example.com:8443']); + assert.throws(() => validateCspDomains(['javascript:alert(1)']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.throws(() => validateCspDomains(['https://user:pass@api.example.com']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.equal(isValidGhostNetworkHostPattern('ws://127.0.0.1:48731'), true); + assert.equal(isValidGhostNetworkHostPattern('https://api.example.com:443'), false); +}); + +test('getPluginToolUi strips invalid initialHeight on installed manifests while rejecting unsafe paths', () => { + const stored = structuredClone(baseManifest); + stored.mcpApps.ui.resources[0].initialHeight = NaN; + assert.equal(validateGhostManifest(stored).ok, false); + const installed = getPluginToolUi(stored); + assert.ok(installed); + assert.equal('initialHeight' in installed.resources[0], false); + + const traversal = structuredClone(baseManifest); + traversal.mcpApps.ui.resources[0].file = '../escape.html'; + assert.equal(getPluginToolUi(traversal), undefined); +}); diff --git a/questions/mcp-apps-exact-origin/v1/question.json b/questions/mcp-apps-exact-origin/v1/question.json new file mode 100644 index 0000000..bfab2d6 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/question.json @@ -0,0 +1,69 @@ +{ + "id": "mcp-apps-exact-origin", + "revision": "v1", + "scoringVersion": "quality-composition-v1", + "title": "MCP Apps 精确 Origin CSP 清单校验与兼容保护", + "status": "calibrated", + "changeNote": "Eval Bank v2 security/protocol question extracted from makecindy/cindy PR #15220 (5b6d74c1).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "5b6d74c161421676ce5a3b2325fbeb7781b360f8", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "exact_origin_matching", + "weight": "1/4", + "mode": "ratio", + "items": [ + "exact_loopback_http_ws", + "exact_default_port_and_case", + "exact_scheme_host_isolation", + "exact_consent_diff_preserved" + ] + }, + { + "id": "wildcard_port_rejection", + "weight": "1/4", + "mode": "all", + "items": [ + "reject_wildcard_port_default_scheme", + "reject_wildcard_port_explicit_port" + ] + }, + { + "id": "non_standard_ports", + "weight": "1/6", + "mode": "all", + "items": [ + "allow_exact_non_standard_port", + "reject_mismatched_non_standard_port" + ] + }, + { + "id": "legacy_domain_compat", + "weight": "1/6", + "mode": "ratio", + "items": [ + "legacy_bare_domain_compat", + "legacy_wildcard_subdomain_compat" + ] + }, + { + "id": "regression_and_sanitization", + "weight": "1/6", + "mode": "all", + "items": [ + "strict_csp_syntax_rejection", + "strict_network_hosts_validation", + "manifest_ui_invariants" + ] + } + ] +} diff --git a/questions/mcp-apps-exact-origin/v1/reference/CONTRACT.md b/questions/mcp-apps-exact-origin/v1/reference/CONTRACT.md new file mode 100644 index 0000000..e61993a --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/CONTRACT.md @@ -0,0 +1,28 @@ +# Product & Protocol Contract + +## 1. CSP Domain Sanitization (`src/app-csp.mjs`) + +- Exports `validateCspDomains(domains)`. +- Accepts `undefined` or an array of at most `100` valid origin-shaped CSP source strings; throws `Error('MCP_APP_INVALID_CSP_DOMAIN')` on any invalid input (wrong type, length > 100, disallowed scheme, invalid host/IPv6, out-of-range port, path, query, fragment, userinfo, whitespace, or directive separator). +- Allowed schemes: `http://`, `https://`, `ws://`, `wss://`. +- Host may be an ASCII hostname (with optional leftmost `*.` subdomain wildcard) or bracketed IPv6 literal; port may be `:<0-65535>` or `:*`; a single trailing `/` is allowed. +- Returns the validated array unchanged. + +## 2. Network Host Patterns & Path Safety (`src/network-hosts.mjs`) + +- Exports `GHOST_NETWORK_MAX_HOSTS` (`8`), `isSafeGhostRelativePath`, `isValidGhostNetworkHostPattern`, `ghostNetworkHostMatches`, and `ghostNetworkTargetMatches`. +- `isValidGhostNetworkHostPattern(pattern)`: non-empty string `<= 253` chars. + - **Exact origin** (`://`): canonical HTTP(S)/WS(S) `URL.origin` (`url.origin === pattern`) with no wildcards, userinfo, path, trailing slash, uppercase, or explicit default port. + - **Legacy domain**: lowercase `>= 2` DNS labels with optional leftmost `*.` (`*.example.com`); rejects single-label hosts (`localhost`, `*.com`) and bare IPv4 literals. +- `ghostNetworkTargetMatches(pattern, url)`: exact origins grant only that exact scheme/host/port; legacy domain declarations retain HTTPS default-port (`443`) matching. +- `isSafeGhostRelativePath(p)`: non-empty string `<= 256` chars, forward slashes only, safe path segments, rejects `.`, `..`, and Windows reserved device names (`con`, `prn`, `aux`, `nul`, `com1`–`com9`, `lpt1`–`lpt9`, with or without extension). + +## 3. MCP Apps UI Validation & Authorization (`src/tool-ui.mjs`) + +- Exports `PLUGIN_UI_MIN_CINDY_VERSION`, `GHOST_TOOLS_MAX`, `CSP_KEYS`, `ghostMcpAppsValidationError`, `parseGhostUi`, `validateGhostManifest`, `getPluginToolUi`, `pluginHasToolUi`, `pluginToolVisible`, `pluginUiDomains`, and `pluginUiPermissionsExpand`. +- Every CSP source across `connectDomains`, `resourceDomains`, `frameDomains`, and `baseUriDomains` must pass `validateCspDomains` and be authorized by at least one valid entry in `network.hosts`: + - **Exact origin entries** authorize only sources whose canonical origin matches identically (exact scheme, exact host/IPv6, exact non-standard port; default ports, hostname case, and trailing `/` normalize equivalently). Wildcard ports (`:*`) and wildcard hostnames (`*`) must never match an exact origin grant. + - **Legacy domain / `*.domain` entries** retain historical hostname-only matching across schemes and ports (`*.example.com` matches any subdomain depth, never the apex or suffix spoofs). +- `validateGhostManifest(raw)`: validates `network.hosts` (max 8 entries) and `mcpApps.ui` in `'package'` mode. Non-finite `initialHeight` fails with reason containing `mcpApps.ui.resources[i].initialHeight 必须是有限数字(CSS px)`; uncovered/invalid CSP fails with reason containing `页面域名必须在 network.hosts 内`. +- `getPluginToolUi(manifest)`: parses in `'installed'` mode (drops invalid `initialHeight` without discarding valid pages; refuses unsafe HTML paths and uncovered/invalid CSP origins). +- `pluginUiDomains(manifest)` lists deduplicated CSP origins across valid UI resources; `pluginUiPermissionsExpand(previous, next)` returns `true` when adding pages, expanding tool visibility to `'app'`, or adding any new CSP domain or exact origin. diff --git a/questions/mcp-apps-exact-origin/v1/reference/ENVIRONMENT.md b/questions/mcp-apps-exact-origin/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..d5bfdc2 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke tests covering baseline domain validation and MCP Apps manifest parsing diff --git a/questions/mcp-apps-exact-origin/v1/reference/TASK.md b/questions/mcp-apps-exact-origin/v1/reference/TASK.md new file mode 100644 index 0000000..4db1fa1 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/TASK.md @@ -0,0 +1,10 @@ +# Task + +Plugin manifests that declare exact HTTP(S)/WS(S) origins in `network.hosts` (for example `http://127.0.0.1:48731`, `ws://127.0.0.1:48731`, `https://api.example.com:8443`, `wss://stream.example.com`, or `http://[::1]:8080`) are failing MCP Apps UI validation at install and runtime, and installation consent diffing fails to detect new exact-origin UI permissions. + +Inspect the codebase (`src/`), read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable defects across manifest validation, CSP domain sanitization, exact-origin authorization, and consent diffing while preserving all security boundaries and legacy domain compatibility. + +- Run `npm test` and add thorough verification tests as needed. +- Document your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/mcp-apps-exact-origin/v1/reference/package.json b/questions/mcp-apps-exact-origin/v1/reference/package.json new file mode 100644 index 0000000..788602d --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-mcp-apps-exact-origin", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/mcp-apps-exact-origin/v1/reference/src/app-csp.mjs b/questions/mcp-apps-exact-origin/v1/reference/src/app-csp.mjs new file mode 100644 index 0000000..4430bdc --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/src/app-csp.mjs @@ -0,0 +1,23 @@ +/** No schemes, directives, quotes, whitespace, credentials or paths from a CSP source. */ +export function validateCspDomains(domains) { + if (domains && (!Array.isArray(domains) || domains.length > 100)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return (domains ?? []).map((source) => { + if ( + typeof source !== 'string' || + !/^(https?|wss?):\/\/(?:\*\.)?(?:[a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(?::(?:[0-9]{1,5}|\*))?\/?$/.test( + source, + ) + ) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + const url = new URL( + source.replace('://*.', '://wildcard.').replace(/:\*(\/?)$/, ':443$1'), + ); + if (!url.hostname || (url.port && Number(url.port) > 65535)) { + throw new Error('MCP_APP_INVALID_CSP_DOMAIN'); + } + return source; + }); +} diff --git a/questions/mcp-apps-exact-origin/v1/reference/src/network-hosts.mjs b/questions/mcp-apps-exact-origin/v1/reference/src/network-hosts.mjs new file mode 100644 index 0000000..3111ee9 --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/src/network-hosts.mjs @@ -0,0 +1,60 @@ +export const GHOST_NETWORK_MAX_HOSTS = 8; + +const GHOST_PATH_SEGMENT_RE = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,63}$/; +const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i; +const GHOST_NETWORK_LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; + +export function isSafeGhostRelativePath(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 256) return false; + if (p.includes('\\')) return false; + const segments = p.split('/'); + return segments.every( + (seg) => + GHOST_PATH_SEGMENT_RE.test(seg) && + seg !== '.' && + seg !== '..' && + !WINDOWS_RESERVED_NAME_RE.test(seg), + ); +} + +/** + * Valid network.hosts entry: + * - Legacy domain: lowercase >=2 DNS labels, optional leftmost `*.` (`*.example.com`), no bare IPs. + * - Exact origin: canonical HTTP(S)/WS(S) `URL.origin` without wildcards, userinfo, path, or trailing slash. + */ +export function isValidGhostNetworkHostPattern(p) { + if (typeof p !== 'string' || p.length === 0 || p.length > 253) return false; + if (p.includes('://')) { + try { + const url = new URL(p); + return ( + ['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol) && + url.origin === p && + !url.hostname.includes('*') && + !url.username && + !url.password + ); + } catch { + return false; + } + } + const bare = p.startsWith('*.') ? p.slice(2) : p; + const labels = bare.split('.'); + if (labels.length < 2) return false; + if (labels.every((l) => /^\d+$/.test(l))) return false; + return labels.every((l) => GHOST_NETWORK_LABEL_RE.test(l)); +} + +export function ghostNetworkHostMatches(pattern, hostname) { + if (pattern.startsWith('*.')) { + return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1; + } + return hostname === pattern; +} + +/** Existing domain declarations retain HTTPS:443; an origin grants exactly one protocol/host/port. */ +export function ghostNetworkTargetMatches(pattern, url) { + return pattern.includes('://') + ? pattern === url.origin + : url.protocol === 'https:' && url.port === '' && ghostNetworkHostMatches(pattern, url.hostname); +} diff --git a/questions/mcp-apps-exact-origin/v1/reference/src/tool-ui.mjs b/questions/mcp-apps-exact-origin/v1/reference/src/tool-ui.mjs new file mode 100644 index 0000000..94ce95f --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/src/tool-ui.mjs @@ -0,0 +1,242 @@ +import { validateCspDomains } from './app-csp.mjs'; +import { + GHOST_NETWORK_MAX_HOSTS, + isSafeGhostRelativePath, + isValidGhostNetworkHostPattern, +} from './network-hosts.mjs'; + +export const PLUGIN_UI_MIN_CINDY_VERSION = '0.1.122-beta'; +export const GHOST_TOOLS_MAX = 64; +export const CSP_KEYS = ['connectDomains', 'resourceDomains', 'frameDomains', 'baseUriDomains']; + +const object = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v); +const safeKey = (key) => + /^[a-z][a-z0-9_-]{0,63}$/.test(key) && !['__proto__', 'constructor', 'prototype'].includes(key); +const invalidInitialHeight = (value) => value !== undefined && !Number.isFinite(value); + +export function ghostMcpAppsValidationError(raw) { + if (object(raw) && object(raw.ui) && Array.isArray(raw.ui.resources) && raw.ui.resources.length <= 16) { + const index = raw.ui.resources.findIndex( + (resource) => object(resource) && invalidInitialHeight(resource.initialHeight), + ); + if (index >= 0) return `mcpApps.ui.resources[${index}].initialHeight 必须是有限数字(CSS px)`; + } + return 'mcpApps.ui 页面或工具声明无效,页面域名必须在 network.hosts 内'; +} + +export function parseGhostUi( + raw, + tools, + hosts, + safePath = isSafeGhostRelativePath, + source = 'package', +) { + if ( + !object(raw) || + !Array.isArray(raw.resources) || + !object(raw.tools) || + (!raw.resources.length && !Object.keys(raw.tools).length) || + raw.resources.length > 16 || + Object.keys(raw.tools).length > GHOST_TOOLS_MAX + ) { + return null; + } + + const uris = new Set(); + let resources = raw.resources; + + for (const [index, resource] of raw.resources.entries()) { + if ( + !object(resource) || + typeof resource.uri !== 'string' || + !resource.uri.startsWith('ui://') || + resource.uri.length <= 5 || + /[\s\x00-\x1f\x7f]/.test(resource.uri) || + uris.has(resource.uri) || + !safePath(resource.file) || + typeof resource.file !== 'string' || + !/\.html?$/i.test(resource.file) || + (resource.prefersBorder !== undefined && typeof resource.prefersBorder !== 'boolean') || + (resource.hostFullscreenButton !== undefined && + typeof resource.hostFullscreenButton !== 'boolean') || + (resource.domain !== undefined && typeof resource.domain !== 'string') + ) { + return null; + } + + if (invalidInitialHeight(resource.initialHeight)) { + if (source === 'package') return null; + if (resources === raw.resources) resources = raw.resources.slice(); + const { initialHeight: _ignored, ...page } = resource; + resources[index] = page; + } + + uris.add(resource.uri); + + if ( + resource.permissions !== undefined && + (!object(resource.permissions) || + Object.entries(resource.permissions).some( + ([key, value]) => + !['camera', 'microphone', 'geolocation', 'clipboardWrite'].includes(key) || + !object(value) || + Object.keys(value).length > 0, + )) + ) { + return null; + } + + if (resource.csp !== undefined) { + if (!object(resource.csp)) return null; + for (const key of CSP_KEYS) { + const domains = resource.csp[key]; + if (domains !== undefined && (!Array.isArray(domains) || domains.some((v) => typeof v !== 'string'))) { + return null; + } + try { + const origins = validateCspDomains(domains); + for (const origin of origins) { + const wildcardPort = /:\*\/?$/.test(origin); + const url = new URL(origin.replace(/:\*(\/?)$/, ':443$1')); + const hostname = url.hostname.toLowerCase(); + if ( + !hosts.some((pattern) => { + // network.hosts validates exact origins in canonical URL.origin form. + // Do not let the wildcard-port placeholder match an exact grant. + if (pattern.includes('://')) { + return !wildcardPort && !hostname.includes('*') && pattern === url.origin; + } + // Keep historical hostname-only matching for domain declarations. + return ( + hostname === pattern || + (pattern.startsWith('*.') && + hostname.endsWith(pattern.slice(1)) && + hostname.length > pattern.length - 1) + ); + }) + ) { + return null; + } + } + } catch { + return null; + } + } + } + } + + const names = new Set(tools.map((tool) => tool.name)); + for (const [name, link] of Object.entries(raw.tools)) { + if ( + !safeKey(name) || + !names.has(name) || + !object(link) || + (link.resourceUri !== undefined && + (typeof link.resourceUri !== 'string' || !uris.has(link.resourceUri))) || + (link.visibility !== undefined && + (!Array.isArray(link.visibility) || + !link.visibility.length || + link.visibility.some((v) => v !== 'model' && v !== 'app'))) + ) { + return null; + } + } + + return resources === raw.resources ? raw : { ...raw, resources }; +} + +export function validateGhostManifest(raw) { + if (!object(raw)) return { ok: false, reason: 'manifest 必须是对象' }; + if (raw.schemaVersion !== undefined && raw.schemaVersion !== 3) { + return { ok: false, reason: '仅支持 schemaVersion 3' }; + } + const tools = raw.tools ?? []; + if (!Array.isArray(tools) || tools.some((t) => !object(t) || typeof t.name !== 'string')) { + return { ok: false, reason: 'tools 声明无效' }; + } + let hosts = []; + if (raw.network !== undefined) { + if (!object(raw.network)) return { ok: false, reason: 'network 声明无效' }; + if (raw.network.hosts !== undefined) { + if ( + !Array.isArray(raw.network.hosts) || + raw.network.hosts.length > GHOST_NETWORK_MAX_HOSTS || + raw.network.hosts.some((h) => !isValidGhostNetworkHostPattern(h)) + ) { + return { ok: false, reason: 'network.hosts 包含无效域名或 origin' }; + } + hosts = raw.network.hosts; + } + } + if (raw.mcpApps !== undefined) { + if (!object(raw.mcpApps)) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + if (raw.mcpApps.ui !== undefined) { + const ui = parseGhostUi(raw.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'package'); + if (!ui) return { ok: false, reason: ghostMcpAppsValidationError(raw.mcpApps) }; + } + } + return { ok: true, manifest: raw }; +} + +/** Only valid declarations grant page authority, including on historical read paths. */ +export function getPluginToolUi(manifest) { + if (!object(manifest)) return undefined; + if ((manifest.schemaVersion !== undefined && manifest.schemaVersion !== 3) || !object(manifest.mcpApps)) { + return undefined; + } + const tools = manifest.tools ?? []; + const hosts = object(manifest.network) ? manifest.network.hosts ?? [] : []; + if ( + !Array.isArray(tools) || + tools.some((tool) => !object(tool) || typeof tool.name !== 'string') || + !Array.isArray(hosts) || + hosts.some((host) => typeof host !== 'string') + ) { + return undefined; + } + return parseGhostUi(manifest.mcpApps.ui, tools, hosts, isSafeGhostRelativePath, 'installed') ?? undefined; +} + +export function pluginHasToolUi(manifest) { + return Boolean(getPluginToolUi(manifest)); +} + +export function pluginToolVisible(manifest, name, audience) { + const link = getPluginToolUi(manifest)?.tools[name]; + return link ? !link.visibility || link.visibility.includes(audience) : audience === 'model'; +} + +export function pluginUiDomains(manifest) { + return [ + ...new Set( + (getPluginToolUi(manifest)?.resources ?? []).flatMap((resource) => + CSP_KEYS.flatMap((key) => resource.csp?.[key] ?? []), + ), + ), + ]; +} + +export function pluginUiPermissionsExpand(previous, next) { + const previousUi = getPluginToolUi(previous); + const nextUi = getPluginToolUi(next); + const remaining = [...(previousUi?.resources ?? [])]; + for (const resource of [...(nextUi?.resources ?? [])].sort( + (a, b) => + Number(previousUi?.resources.some((old) => old.uri === b.uri)) - + Number(previousUi?.resources.some((old) => old.uri === a.uri)), + )) { + let index = remaining.findIndex((old) => old.uri === resource.uri); + if (index < 0) index = remaining.findIndex((old) => old.file === resource.file); + const before = remaining[index]; + if ( + !before || + CSP_KEYS.some((key) => resource.csp?.[key]?.some((domain) => !before.csp?.[key]?.includes(domain))) + ) { + return true; + } + remaining.splice(index, 1); + } + return Object.keys(nextUi?.tools ?? {}).some( + (name) => pluginToolVisible(next, name, 'app') && !pluginToolVisible(previous, name, 'app'), + ); +} diff --git a/questions/mcp-apps-exact-origin/v1/reference/tests/smoke.test.mjs b/questions/mcp-apps-exact-origin/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..f2b741c --- /dev/null +++ b/questions/mcp-apps-exact-origin/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,66 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { validateCspDomains } from '../src/app-csp.mjs'; +import { isValidGhostNetworkHostPattern } from '../src/network-hosts.mjs'; +import { + getPluginToolUi, + pluginUiDomains, + pluginUiPermissionsExpand, + validateGhostManifest, +} from '../src/tool-ui.mjs'; + +const baseManifest = { + schemaVersion: 3, + id: 'acme-planner', + name: 'Acme Planner', + version: '1.0.0', + tools: [{ name: 'help', description: 'Open planner' }], + network: { hosts: ['api.example.com', '*.cdn.example.com'] }, + mcpApps: { + ui: { + resources: [ + { + uri: 'ui://planner', + file: 'ui/planner.html', + csp: { + connectDomains: ['https://api.example.com'], + resourceDomains: ['https://static.cdn.example.com'], + }, + }, + ], + tools: { help: { resourceUri: 'ui://planner', visibility: ['model', 'app'] } }, + }, + }, +}; + +test('validates baseline domain and wildcard subdomain manifests', () => { + const res = validateGhostManifest(baseManifest); + assert.equal(res.ok, true); + assert.deepEqual(pluginUiDomains(res.manifest), [ + 'https://api.example.com', + 'https://static.cdn.example.com', + ]); + assert.equal(pluginUiPermissionsExpand(baseManifest, baseManifest), false); +}); + +test('validateCspDomains and isValidGhostNetworkHostPattern enforce strict syntax', () => { + assert.deepEqual(validateCspDomains(['https://api.example.com:8443']), ['https://api.example.com:8443']); + assert.throws(() => validateCspDomains(['javascript:alert(1)']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.throws(() => validateCspDomains(['https://user:pass@api.example.com']), /MCP_APP_INVALID_CSP_DOMAIN/); + assert.equal(isValidGhostNetworkHostPattern('ws://127.0.0.1:48731'), true); + assert.equal(isValidGhostNetworkHostPattern('https://api.example.com:443'), false); +}); + +test('getPluginToolUi strips invalid initialHeight on installed manifests while rejecting unsafe paths', () => { + const stored = structuredClone(baseManifest); + stored.mcpApps.ui.resources[0].initialHeight = NaN; + assert.equal(validateGhostManifest(stored).ok, false); + const installed = getPluginToolUi(stored); + assert.ok(installed); + assert.equal('initialHeight' in installed.resources[0], false); + + const traversal = structuredClone(baseManifest); + traversal.mcpApps.ui.resources[0].file = '../escape.html'; + assert.equal(getPluginToolUi(traversal), undefined); +}); diff --git a/questions/opt-cshare-compression/v1/author/editable.json b/questions/opt-cshare-compression/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-cshare-compression/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-cshare-compression/v1/author/evaluator.mjs b/questions/opt-cshare-compression/v1/author/evaluator.mjs new file mode 100644 index 0000000..25b4cd9 --- /dev/null +++ b/questions/opt-cshare-compression/v1/author/evaluator.mjs @@ -0,0 +1,550 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { performance } from 'node:perf_hooks'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +// Submission code runs in a child process under Node's permission model: `--permission` since +// Node 22.13 / 23.5, `--experimental-permission` on Node 20 before that, absent before Node 20. +// Without it the submission cannot be isolated, so the run is reported as an environment +// problem instead of being scored. +const PERMISSION_FLAG = ['--permission', '--experimental-permission'].find( + (flag) => spawnSync(process.execPath, [flag, '-e', ''], { stdio: 'ignore', timeout: 10_000 }).status === 0, +); +if (!PERMISSION_FLAG) { + trusted.emit({ + status: 'environment_invalid', + reason: `grading needs Node.js >= 20 for the permission model (found ${process.version})`, + }); + process.exit(0); +} +const bufferCompare = Buffer.compare; +const randomHex = (n) => crypto.randomBytes(n).toString('hex'); +const childNonce = randomHex(16); + +const [subSrcDir, corpusGeneratorPath] = process.argv.slice(2); +if (!subSrcDir || !corpusGeneratorPath) { + throw new Error('Usage: node evaluator.mjs '); +} + +const ENCODE_LIMIT_MS = 12_000; +const DECODE_LIMIT_MS = 5_000; +const FALLBACK_ARCHIVE_BYTES = 100_000_000; + +// Private held-out corpus configuration (unseen by candidates: distinct seed, language, +// project, file paths, identifiers, prose, models, timestamps, UUID space, PNG dims, counts). +const HELD_OUT_CONFIG = { + suiteName: 'held-out', + seed: 'cshare-heldout-unseen-v1-73918462', + bundleATurns: 1016, + bundleAMediaCopies: 18, + bundleBSharedTurns: 156, + bundleBTailTurns: 40, + bundleCWorkerTurns: 112, + bundleCWorkerShotsEach: 14, + theme: { + project: 'kestrel-ledger', + cwd: '/srv/builds/kestrel-ledger', + branch: 'refactor/settlement-quorum-engine', + appVersion: '3.2.1', + platform: 'linux', + baseEpochMs: Date.UTC(2026, 8, 23, 14, 42, 10), + lineNumWidth: 4, + pngWidth: 1024, + pngHeight: 576, + models: ['claude-opus-4-7', 'claude-sonnet-4-7'], + codexModel: 'gpt-5.4-codex', + providers: ['vertex-anthropic', 'azure-codex'], + workerRoles: ['architect', 'settlement', 'fuzzing', 'compliance'], + files: [ + 'crates/quorum/src/ballot_router.rs', + 'crates/ledger/src/merkle_vault.rs', + 'crates/clearing/src/batch_settler.rs', + 'crates/wire/src/envelope_codec.rs', + 'crates/audit/src/proof_verifier.rs', + 'crates/ops/src/clock_drift_guard.rs', + ], + identifiers: [ + 'BallotRouter', 'MerkleVault', 'BatchSettler', 'EnvelopeCodec', + 'ProofVerifier', 'ClockDriftGuard', 'QuorumEpoch', 'EscrowSlot', + 'ClearingWindow', 'WitnessLog', 'FinalitySeal', 'ShardRebalancer', + 'NonceRegistry', 'SlashingOracle', 'AnchorReceipt', 'RelayPipeline', + ], + zhNotes: [ + '排查清算批次在跨分片提交时出现的状态漂移与重复记账隐患。', + '重构了见证日志的序列化边界,确保重放阶段严格保持幂等性。', + '定位到时钟漂移守卫在突发网络抖动下误判租约过期的根因。', + '已将默克尔证明校验切换为流水线批量核验,并补全异常分支覆盖。', + '核对锚定回执与托管槽位映射关系,确认回滚路径不会遗留悬挂状态。', + '全量集成测试与确定性仿真通过,状态哈希前后一致。', + ], + enNotes: [ + 'Investigating cross-shard settlement drift and duplicate posting edge cases.', + 'Refactored witness log serialization boundaries to preserve strict replay idempotency.', + 'Isolated lease expiry false positives inside the clock drift guard during jitter spikes.', + 'Switched Merkle proof verification to pipelined batch checks with full fault coverage.', + 'Validated anchor receipt mapping against escrow slots to prevent orphaned rollback state.', + 'Deterministic ledger simulation and integration suite passed with exact digest parity.', + ], + toolNames: [ + 'open_source', 'patch_source', 'exec_shell', 'symbol_grep', + 'tree_scan', 'diff_apply', 'dump_telemetry', 'check_invariants', + ], + }, +}; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +async function snapshotDirHashes(dir) { + const result = {}; + async function walk(cur, relPrefix) { + const entries = await fs.readdir(cur, { withFileTypes: true }); + entries.sort((a, b) => a.name.localeCompare(b.name)); + for (const ent of entries) { + const full = path.join(cur, ent.name); + const rel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name; + if (ent.isDirectory()) { + await walk(full, rel); + } else if (ent.isFile()) { + const data = await fs.readFile(full); + result[rel] = sha256(data); + } + } + } + await walk(dir, ''); + return result; +} + +function fingerprintBundle(bundle) { + return bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); +} + +function verifyPlainHeader(encoded, label) { + assert.ok(encoded instanceof Uint8Array, `${label}: encoded output must be Uint8Array`); + assert.ok(encoded.byteLength >= 12, `${label}: encoded output shorter than 12 bytes`); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), 'XDTSHARE', `${label}: bad XDTSHARE magic`); + assert.equal(buf.readUInt8(8), 1, `${label}: headerVersion must be 1`); + assert.equal(buf.readUInt8(9), 0, `${label}: cipher must be 0`); + assert.equal(buf.readUInt16BE(10), 0, `${label}: reserved bytes must be 0`); +} + +function verifyDecodedMatches(decoded, expectedFingerprint, label) { + assert.ok(decoded && typeof decoded === 'object', `${label}: decodeArchive must return an object`); + assert.equal(decoded.headerVersion, 1, `${label}: decoded headerVersion must be 1`); + assert.ok(Array.isArray(decoded.entries), `${label}: decoded.entries must be an array`); + assert.equal( + decoded.entries.length, + expectedFingerprint.length, + `${label}: entry count mismatch (${decoded.entries.length} vs ${expectedFingerprint.length})`, + ); + for (let i = 0; i < expectedFingerprint.length; i++) { + const exp = expectedFingerprint[i]; + const got = decoded.entries[i]; + assert.ok(got && typeof got === 'object', `${label}[${i}]: entry missing`); + assert.equal(got.path, exp.path, `${label}[${i}]: path mismatch (${got.path} vs ${exp.path})`); + assert.ok(got.content instanceof Uint8Array, `${label}[${i}]: content must be Uint8Array`); + assert.equal(got.content.byteLength, exp.bytes, `${label}[${i}] (${exp.path}): byte length mismatch`); + assert.equal(sha256(got.content), exp.sha256, `${label}[${i}] (${exp.path}): SHA-256 mismatch`); + } +} + +function buildAdversarialBundles(createDeterministicRng) { + const rng = createDeterministicRng('cshare-adversarial-edges-v1'); + const all256 = new Uint8Array(256); + for (let i = 0; i < 256; i++) all256[i] = i; + + const highEntropy = new Uint8Array(rng.bytes(65_536)); + + // Create a non-zero byteOffset Uint8Array view into a larger backing buffer + const backing = Buffer.alloc(128, 0xaa); + const innerBytes = Buffer.from('offset-slice-\x00\x01\xff-中文🎉\r\n', 'utf8'); + innerBytes.copy(backing, 23); + const offsetView = new Uint8Array(backing.buffer, backing.byteOffset + 23, innerBytes.length); + + // PNG-like binary plus colliding base64 text & sentinel strings + const tinyPng = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + rng.bytes(512), + ]); + const tinyPngB64 = tinyPng.toString('base64'); + + const emptyBundle = { headerVersion: 1, entries: [] }; + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.jsonl', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: all256 }, + { path: 'binary-as.json', content: new Uint8Array(all256) }, + { path: 'binary-as.jsonl', content: new Uint8Array(all256) }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\u0000\uffff\r\nline2\nno-trailing-newline', 'utf8') }, + { path: 'crlf.jsonl', content: Buffer.from('{"a":1}\r\n{"a":2}\r\n', 'utf8') }, + { path: 'no-eol.jsonl', content: Buffer.from('{"a":1}\n{"a":2}', 'utf8') }, + { path: 'pretty4.json', content: Buffer.from('{\n "a": 1,\n "b": [1.0, -0]\n}\n', 'utf8') }, + { path: 'dup-keys.json', content: Buffer.from('{"k":1,"k":2}\n', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json line\n{broken json\r\n\x00\x01\x02\x1eB:0\x1f@@B64:0@@XDTSHARE\n', 'utf8') }, + { path: 'fake-media.png', content: Buffer.from('actually plain text, not a png\r\n', 'utf8') }, + { path: 'media/tiny.png', content: new Uint8Array(tinyPng) }, + { path: 'sentinel-collide.jsonl', content: Buffer.from(`{"sentinel":"\\u001eB:0\\u001f","raw":"\x1eB:0\x1f","b64":"${tinyPngB64}"}\n`, 'utf8') }, + { path: 'blobs/random-64k.bin', content: highEntropy }, + { path: 'dup/path.txt', content: Buffer.from('version A\n', 'utf8') }, + { path: 'dup/path.txt', content: Buffer.from('version B\r\n', 'utf8') }, + { path: 'dup/path.txt', content: Buffer.from('version A\n', 'utf8') }, + { path: 'views/nonzero-offset.bin', content: offsetView }, + ], + }; + + return [ + { name: 'edge-empty-archive', bundle: emptyBundle }, + { name: 'edge-adversarial-mix', bundle: edgeBundle }, + ]; +} + +const errors = []; +let gate_exact_lossless = false; +let gate_stateless_isolated_decode = false; +let gate_header_and_limits = false; +let archiveBytes = FALLBACK_ARCHIVE_BYTES; +let details = {}; + +const codecPath = path.join(subSrcDir, 'cshare-codec.mjs'); +const [codecMod, corpusMod] = await Promise.all([ + import(pathToFileURL(codecPath).href), + import(pathToFileURL(corpusGeneratorPath).href), +]); + +const { + encodeArchive, + decodeArchive, + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, +} = codecMod; +const { + createDeterministicRng, + generatePublicSuite, + generateCorpusSuite, + measureBundleRawBytes, +} = corpusMod; + +const srcHashesBefore = await snapshotDirHashes(subSrcDir); + +const publicSuite = generatePublicSuite(); +const heldOutSuite = generateCorpusSuite(HELD_OUT_CONFIG); +const adversarialCases = buildAdversarialBundles(createDeterministicRng); + +let headerApiOk = true; +try { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE', 'XDTSHARE_MAGIC export mismatch'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12, 'XDTSHARE_PLAIN_HEADER_LENGTH export mismatch'); + assert.equal(typeof encodeArchive, 'function', 'encodeArchive must be a function'); + assert.equal(typeof decodeArchive, 'function', 'decodeArchive must be a function'); + + // Invalid headers must throw + assert.throws(() => decodeArchive(new Uint8Array(0)), 'must reject 0-byte archive'); + assert.throws(() => decodeArchive(new Uint8Array(11)), 'must reject 11-byte archive'); + assert.throws(() => decodeArchive(Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1')), 'must reject bad magic'); + assert.throws(() => decodeArchive(Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1')), 'must reject headerVersion=2'); + assert.throws(() => decodeArchive(Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1')), 'must reject cipher=1'); +} catch (err) { + headerApiOk = false; + errors.push(`header_api: ${err.message}`); +} + +let losslessOk = true; +let allHeadersOk = headerApiOk; +let determinismOk = true; +let heldOutEncodeMs = 0; +let heldOutDecodeMs = 0; +let heldOutRawTotal = 0; +let heldOutEncodedTotal = 0; +const heldOutEncodedRecords = []; +const perBundleStats = []; + +// 1. Adversarial edge cases +for (const { name, bundle } of adversarialCases) { + try { + const fp = fingerprintBundle(bundle); + const encoded1 = encodeArchive(bundle); + verifyPlainHeader(encoded1, name); + // Input immutability check + assert.deepEqual(fingerprintBundle(bundle), fp, `${name}: encodeArchive mutated input buffers`); + + const encoded2 = encodeArchive(bundle); + if (sha256(encoded1) !== sha256(encoded2)) { + determinismOk = false; + errors.push(`determinism: ${name} produced different bytes across repeated encodes`); + } + + // Decode from a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded1.byteLength + 29); + padded.set(encoded1, 17); + const sliced = padded.subarray(17, 17 + encoded1.byteLength); + const decoded = decodeArchive(sliced); + verifyDecodedMatches(decoded, fp, name); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`edge(${name}): ${err.message}`); + } +} + +// 2. Public corpus round-trip verification +for (const bundle of publicSuite.bundles) { + try { + const fp = fingerprintBundle(bundle); + const encoded = encodeArchive(bundle); + verifyPlainHeader(encoded, `public/${bundle.name}`); + assert.deepEqual(fingerprintBundle(bundle), fp, `public/${bundle.name}: input mutated`); + const decoded = decodeArchive(encoded); + verifyDecodedMatches(decoded, fp, `public/${bundle.name}`); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`public(${bundle.name}): ${err.message}`); + } +} + +// 3. Held-out unseen corpus: measure archive_bytes + encode/decode timings + verify lossless +for (const bundle of heldOutSuite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + heldOutRawTotal += rawBytes; + try { + const fp = fingerprintBundle(bundle); + const t0 = trusted.now(); + const encoded = encodeArchive(bundle); + const encMs = trusted.now() - t0; + heldOutEncodeMs += encMs; + + verifyPlainHeader(encoded, `held-out/${bundle.name}`); + assert.deepEqual(fingerprintBundle(bundle), fp, `held-out/${bundle.name}: input mutated`); + + const t1 = trusted.now(); + const decoded = decodeArchive(encoded); + const decMs = trusted.now() - t1; + heldOutDecodeMs += decMs; + + verifyDecodedMatches(decoded, fp, `held-out/${bundle.name}`); + + heldOutEncodedTotal += encoded.byteLength; + heldOutEncodedRecords.push({ name: bundle.name, encoded, fp }); + perBundleStats.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + encode_ms: Number(encMs.toFixed(1)), + decode_ms: Number(decMs.toFixed(1)), + }); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`held-out(${bundle.name}): ${err.message}`); + } +} + +// Held-out determinism spot check on fork-chain-and-media (bundle index 1) +if (heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + try { + const b1 = heldOutSuite.bundles[1]; + const reEncoded = encodeArchive(b1); + if (sha256(reEncoded) !== sha256(heldOutEncodedRecords[1].encoded)) { + determinismOk = false; + errors.push('determinism: held-out bundle produced different bytes across repeated encodes'); + } + } catch (err) { + determinismOk = false; + errors.push(`determinism: ${err.message}`); + } +} + +// 4. Stateless isolated child-process decode gate +if (heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + // Real path: the permission model checks resolved paths (macOS temp dirs sit behind /var -> /private/var). + const isoRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cshare-iso-decode-'))); + try { + const archiveDir = path.join(isoRoot, 'archives'); + const childWorkDir = path.join(isoRoot, 'child-cwd'); + const childTmpDir = path.join(isoRoot, 'child-tmp'); + await Promise.all([ + fs.mkdir(archiveDir, { recursive: true }), + fs.mkdir(childWorkDir, { recursive: true }), + fs.mkdir(childTmpDir, { recursive: true }), + ]); + + const archivePaths = []; + for (let i = 0; i < heldOutEncodedRecords.length; i++) { + const p = path.join(archiveDir, `bundle-${i}.cshare`); + await fs.writeFile(p, heldOutEncodedRecords[i].encoded); + archivePaths.push(p); + } + const runnerDir = path.join(isoRoot, 'runner'); + const outDir = path.join(isoRoot, 'decoded'); + await Promise.all([fs.mkdir(runnerDir, { recursive: true }), fs.mkdir(outDir, { recursive: true })]); + + // The child only decodes and writes the bytes it produced; the parent compares them with the + // original entries. Under the permission model the child can read nothing but the runner, the + // codec and the archives, so decoding cannot fall back on the corpus files on disk. + const runnerScript = path.join(runnerDir, 'decode-runner.mjs'); + await fs.writeFile( + runnerScript, + [ + "import fs from 'node:fs';", + "import path from 'node:path';", + "import { performance } from 'node:perf_hooks';", + "import { pathToFileURL } from 'node:url';", + "const nonce = fs.readFileSync(0, 'utf8').trim();", + "const readFileSync = fs.readFileSync;", + "const writeFileSync = fs.writeFileSync;", + "const writeSync = fs.writeSync;", + "const join = path.join;", + "const now = performance.now.bind(performance);", + "const concat = Buffer.concat;", + "const stringify = JSON.stringify;", + "const [codecFile, outDir, ...files] = process.argv.slice(2);", + "const { decodeArchive } = await import(pathToFileURL(codecFile).href);", + "let totalDecodeMs = 0;", + "for (let i = 0; i < files.length; i++) {", + " const raw = readFileSync(files[i]);", + " const u8 = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);", + " const t0 = now();", + " const res = decodeArchive(u8);", + " totalDecodeMs += now() - t0;", + " if (!res || res.headerVersion !== 1 || !Array.isArray(res.entries)) {", + " throw new Error('Invalid decoded bundle structure');", + " }", + " const parts = [];", + " const index = res.entries.map((e) => {", + " if (!(e.content instanceof Uint8Array)) throw new Error('Entry content must be Uint8Array');", + " parts.push(e.content);", + " return { path: e.path, bytes: e.content.byteLength };", + " });", + " writeFileSync(join(outDir, `bundle-${i}.json`), stringify({ headerVersion: res.headerVersion, index }));", + " writeFileSync(join(outDir, `bundle-${i}.bin`), concat(parts));", + "}", + "writeSync(1, `EVAL-RESULT ${nonce} ${stringify({ totalDecodeMs })}\\n`);", + ].join('\n'), + 'utf8', + ); + + const realSubSrcDir = await fs.realpath(subSrcDir); + const realCodecPath = path.join(realSubSrcDir, path.relative(subSrcDir, codecPath)); + const sandboxFlags = [ + '--frozen-intrinsics', + PERMISSION_FLAG, + `--allow-fs-read=${runnerDir}`, + `--allow-fs-read=${realSubSrcDir}`, + `--allow-fs-read=${archiveDir}`, + `--allow-fs-write=${outDir}`, + ]; + const stdout = execFileSync(process.execPath, [...sandboxFlags, runnerScript, realCodecPath, outDir, ...archivePaths], { + cwd: childWorkDir, + env: { + PATH: process.env.PATH, + HOME: childTmpDir, + TMPDIR: childTmpDir, + TEMP: childTmpDir, + TMP: childTmpDir, + }, + input: `${childNonce}\n`, + encoding: 'utf8', + timeout: 30_000, + maxBuffer: 32 * 1024 * 1024, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + const tag = `EVAL-RESULT ${childNonce} `; + const tagged = stdout.split('\n').filter((line) => line.startsWith(tag)); + assert.equal(tagged.length, 1, 'isolated decode did not report exactly one authenticated result'); + const parsed = JSON.parse(tagged[0].slice(tag.length)); + for (let i = 0; i < heldOutEncodedRecords.length; i++) { + const name = heldOutEncodedRecords[i].name; + const meta = JSON.parse(await fs.readFile(path.join(outDir, `bundle-${i}.json`), 'utf8')); + const bin = await fs.readFile(path.join(outDir, `bundle-${i}.bin`)); + const original = heldOutSuite.bundles[i].entries; + assert.equal(meta.headerVersion, 1, `isolated decode header on ${name}`); + assert.equal(meta.index.length, original.length, `isolated decode entry count on ${name}`); + let off = 0; + for (let k = 0; k < original.length; k++) { + const want = original[k]; + const wantBytes = typeof want.content === 'string' ? Buffer.from(want.content, 'utf8') : Buffer.from(want.content); + const got = meta.index[k]; + assert.equal(got.path, want.path, `isolated decode path mismatch on ${name}#${k}`); + assert.equal(got.bytes, wantBytes.byteLength, `isolated decode size mismatch on ${name}#${k}`); + assert.equal(bufferCompare(bin.subarray(off, off + got.bytes), wantBytes), 0, `isolated decode content mismatch on ${name}#${k}`); + off += got.bytes; + } + assert.equal(off, bin.byteLength, `isolated decode trailing bytes on ${name}`); + } + + // Ensure subSrcDir was not modified as a side-channel during encode/decode + const srcHashesAfter = await snapshotDirHashes(subSrcDir); + assert.deepEqual(srcHashesAfter, srcHashesBefore, 'submission src/ was mutated during execution'); + + gate_stateless_isolated_decode = true; + details.isolatedDecodeMs = Number(parsed.totalDecodeMs.toFixed(1)); + } catch (err) { + gate_stateless_isolated_decode = false; + const stderrTail = typeof err.stderr === 'string' && err.stderr ? ` | stderr: ${err.stderr.slice(-600)}` : ''; + errors.push(`stateless_decode: ${err.message.split('\n')[0].slice(0, 200)}${stderrTail}`); + } finally { + await fs.rm(isoRoot, { recursive: true, force: true }); + } +} + +const limitsOk = + heldOutEncodedRecords.length === heldOutSuite.bundles.length && + heldOutEncodeMs <= ENCODE_LIMIT_MS && + heldOutDecodeMs <= DECODE_LIMIT_MS; + +if (!limitsOk && heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + errors.push( + `limits: encode=${heldOutEncodeMs.toFixed(1)}ms (limit ${ENCODE_LIMIT_MS}ms), decode=${heldOutDecodeMs.toFixed(1)}ms (limit ${DECODE_LIMIT_MS}ms)`, + ); +} + +gate_exact_lossless = losslessOk && heldOutEncodedRecords.length === heldOutSuite.bundles.length; +gate_header_and_limits = allHeadersOk && determinismOk && limitsOk; +archiveBytes = + heldOutEncodedRecords.length === heldOutSuite.bundles.length && Number.isInteger(heldOutEncodedTotal) && heldOutEncodedTotal > 0 + ? heldOutEncodedTotal + : FALLBACK_ARCHIVE_BYTES; + +details = { + ...details, + heldOutRawBytes: heldOutRawTotal, + heldOutArchiveBytes: archiveBytes, + heldOutEncodeMs: Number(heldOutEncodeMs.toFixed(1)), + heldOutDecodeMs: Number(heldOutDecodeMs.toFixed(1)), + bundles: perBundleStats, + errors, +}; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_lossless, + gate_stateless_isolated_decode, + gate_header_and_limits, + }, + metrics: { + archive_bytes: archiveBytes, + }, + details, +})); diff --git a/questions/opt-cshare-compression/v1/author/grade.py b/questions/opt-cshare-compression/v1/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/opt-cshare-compression/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-cshare-compression/v1/author/grade_impl.py b/questions/opt-cshare-compression/v1/author/grade_impl.py new file mode 100644 index 0000000..89a2775 --- /dev/null +++ b/questions/opt-cshare-compression/v1/author/grade_impl.py @@ -0,0 +1,45 @@ +"""Isolated pure-Node quantitative grader for opt-cshare-compression.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + src_dir = submission_root / 'src' + if not src_dir.is_dir(): + return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'} + + with tempfile.TemporaryDirectory(prefix='eval-cshare-opt-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(src_dir, sub_src) + corpus_gen = Q / 'candidate' / 'lib' / 'corpus-generator.mjs' + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src), str(corpus_gen)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-cshare-compression/v1/author/result-channel.mjs b/questions/opt-cshare-compression/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-cshare-compression/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-cshare-compression/v1/candidate/CONTRACT.md b/questions/opt-cshare-compression/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..b1b35f7 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/CONTRACT.md @@ -0,0 +1,54 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Performance limits (held-out corpus total across 3 bundles)**: + - Total `encodeArchive` time: `<= 12,000 ms` (12 seconds) + - Total `decodeArchive` time: `<= 5,000 ms` (5 seconds) diff --git a/questions/opt-cshare-compression/v1/candidate/ENVIRONMENT.md b/questions/opt-cshare-compression/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..1fee79d --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. For Node.js 18+ portability, `zlib.deflateRawSync`, `zlib.gzipSync`, and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` is present without checking availability first. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism & held-out evaluation: + - Public benchmark (`npm run bench`) runs on a deterministic 3-bundle public `.cshare` corpus generated by `lib/corpus-generator.mjs`. + - Official grading evaluates bit-exact lossless correctness, stateless child-process decoding, header/timing limits (`encode <= 12s`, `decode <= 5s`), and total `archive_bytes` on an **unseen held-out 3-bundle corpus** with different seeds, project domain, file paths, code identifiers, vocabulary, UUID spaces, timestamps, and media. +- Public checks: + - `npm test` — lossless round-trip, header validation, and adversarial edge-case smoke tests + - `npm run bench` — deterministic public corpus benchmark reporting raw size, `archive_bytes`, compression ratio, and encode/decode timings diff --git a/questions/opt-cshare-compression/v1/candidate/TASK.md b/questions/opt-cshare-compression/v1/candidate/TASK.md new file mode 100644 index 0000000..15239d3 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive lossless compression codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). + +## Observed Production Symptoms + +Cindy exports AI coding sessions—including single-agent sessions, Claude fork chains, media attachments, and Orca multi-worker team archives—into `.cshare` files using per-entry raw DEFLATE (level 6) with no cross-file solid compression, no content deduplication, and no structural preprocessing. As a result, realistic 10–14 MiB session exports still occupy multiple megabytes when shared or migrated across devices, despite containing massive structural and semantic redundancy across: +- Pretty-printed JSON metadata (`manifest.json`, `session.json`, `media-map.json`) +- Database `messages.jsonl` and native vendor transcripts (`transcripts/claude/*.jsonl`, `transcripts/codex/rollout.jsonl`) +- Structured JSONL telemetry, timestamps, IDs, and numeric usage counters +- Fork chains (`fork-0.jsonl`, `fork-1.jsonl`, `fork-2.jsonl`) and Orca worker subdirectories (`orca/workers/0..3/`) +- Evolving file snapshots and duplicated binary media attachments (`media/*.png`) + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header (`"XDTSHARE"` ASCII 8B + `headerVersion=1` u8 + `cipher=0` u8 + 2 zero reserved bytes). Everything from byte 12 onward is your open-ended lossless container and compression format. +- Guarantee **100% bit-exact lossless round-trip** (`headerVersion`, entry count, exact entry order, exact UTF-8 paths, and byte-exact contents) across all valid `.cshare` bundles and arbitrary binary/edge-case payloads. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must reconstruct every entry in a fresh isolated Node.js process given only the encoded archive bytes. +- **Open-ended optimization goal**: Minimize total encoded `archive_bytes` on the **unseen held-out evaluation suite** (which uses different seeds, project domains, file names, code identifiers, vocabulary, UUID spaces, timestamps, and media—hardcoded dictionaries will not generalize), while staying within Node.js built-ins (zero external npm packages) and the held-out runtime limits (`encode <= 12s`, `decode <= 5s`). +- Run `npm test` and `npm run bench` to verify correctness and compare public corpus sizes before and after your changes. +- Record your analysis, format design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料生成器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v1/candidate/bench/workload.mjs b/questions/opt-cshare-compression/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..4304604 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { generatePublicSuite, measureBundleRawBytes } from '../lib/corpus-generator.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = generatePublicSuite(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v1/candidate/lib/corpus-generator.mjs b/questions/opt-cshare-compression/v1/candidate/lib/corpus-generator.mjs new file mode 100644 index 0000000..db0f35a --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/lib/corpus-generator.mjs @@ -0,0 +1,1269 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic parameterized `.cshare` archive corpus generator. + * Pure Node.js >= 18 ESM, zero external dependencies, zero wall-clock or random nondeterminism. + */ + +function hashSeed(str) { + const h = crypto.createHash('sha256').update(String(str)).digest(); + return [h.readUInt32LE(0), h.readUInt32LE(4), h.readUInt32LE(8), h.readUInt32LE(12)]; +} + +export function createDeterministicRng(seed) { + let [a, b, c, d] = hashSeed(seed); + function nextU32() { + const t = b << 9; + let r = b * 5; + r = ((r << 7) | (r >>> 25)) * 9; + c ^= a; + d ^= b; + b ^= c; + a ^= d; + c ^= t; + d = (d << 11) | (d >>> 21); + return r >>> 0; + } + return { + u32: nextU32, + int(min, max) { + return min + (nextU32() % (max - min + 1)); + }, + pick(arr) { + return arr[nextU32() % arr.length]; + }, + bytes(len) { + const out = Buffer.allocUnsafe(len); + let i = 0; + while (i + 4 <= len) { + out.writeUInt32LE(nextU32(), i); + i += 4; + } + while (i < len) out[i++] = nextU32() & 0xff; + return out; + }, + uuid() { + const b16 = this.bytes(16); + b16[6] = (b16[6] & 0x0f) | 0x40; + b16[8] = (b16[8] & 0x3f) | 0x80; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + uuidv7(tsMs, seq, nodeBuf) { + const b16 = Buffer.alloc(16); + b16.writeUInt32BE(Math.floor(tsMs / 0x10000) >>> 0, 0); + b16.writeUInt16BE(tsMs & 0xffff, 4); + b16[6] = 0x70 | ((seq >>> 8) & 0x0f); + b16[7] = seq & 0xff; + b16[8] = 0x80 | (nodeBuf[0] & 0x3f); + b16[9] = nodeBuf[1]; + b16[10] = nodeBuf[2]; + b16[11] = nodeBuf[3]; + b16[12] = nodeBuf[4]; + const rnd = nextU32(); + b16[13] = (rnd >>> 16) & 0xff; + b16[14] = (rnd >>> 8) & 0xff; + b16[15] = rnd & 0xff; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + hex(nBytes) { + return this.bytes(nBytes).toString('hex'); + }, + }; +} + +// ---------- Valid PNG framing over deterministic incompressible payload ---------- +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function pngChunk(type, data) { + const typeBuf = Buffer.from(type, 'ascii'); + const lenBuf = Buffer.alloc(4); + lenBuf.writeUInt32BE(data.length, 0); + const crcBuf = Buffer.alloc(4); + crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0); + return Buffer.concat([lenBuf, typeBuf, data, crcBuf]); +} + +export function makeSyntheticPng(rng, payloadBytes, width = 800, height = 450) { + const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // RGBA + const raw = Buffer.concat([ + sig, + pngChunk('IHDR', ihdr), + pngChunk('IDAT', rng.bytes(payloadBytes)), + pngChunk('IEND', Buffer.alloc(0)), + ]); + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); +} + +// ---------- Default public theme ---------- +export const PUBLIC_SEED = 'cshare-public-suite-v1'; + +export const PUBLIC_THEME = { + project: 'nebula-sync', + cwd: '/Users/dev/workspace/nebula-sync', + branch: 'feat/incremental-snapshot-pipeline', + appVersion: '2.14.3', + platform: 'darwin', + baseEpochMs: Date.UTC(2026, 3, 12, 9, 15, 0), + lineNumWidth: 5, + pngWidth: 800, + pngHeight: 450, + models: ['claude-sonnet-4-6', 'claude-opus-4-6'], + codexModel: 'gpt-5.3-codex', + providers: ['anthropic-direct', 'openai-codex'], + workerRoles: ['implementer', 'verifier', 'profiler', 'auditor'], + files: [ + 'src/sync/snapshotScheduler.ts', + 'src/sync/deltaJournal.ts', + 'src/storage/walCompactor.ts', + 'src/network/chunkMuxer.ts', + 'src/protocol/frameValidator.ts', + 'src/metrics/backpressureProbe.ts', + ], + identifiers: [ + 'SnapshotScheduler', 'DeltaJournal', 'WalCompactor', 'ChunkMuxer', + 'FrameValidator', 'BackpressureProbe', 'EpochCursor', 'SegmentRing', + 'LeaseToken', 'CheckpointBarrier', 'FlushWindow', 'ReplayIndex', + 'MerkleBucket', 'PeerTransport', 'ThrottleGate', 'DigestCache', + ], + zhNotes: [ + '检查增量快照写入路径是否存在重复刷盘或锁竞争问题。', + '已完成核心调度器的边界修复,正在补齐回归测试并核对延迟分位数。', + '发现 WAL 压缩窗口在高并发下会触发多余的索引重建,已调整阈值。', + '对比了新旧分片多路复用逻辑,确认在断连重传时不再丢弃尾帧。', + '建议将校验和计算下沉到批量提交阶段,减少热路径上的内存拷贝。', + '已核验全部单元测试与冒烟基准,吞吐和内存峰值符合预期。', + ], + enNotes: [ + 'Auditing the incremental snapshot pipeline for redundant disk flushes and lock contention.', + 'Applied boundary guard to the scheduler queue and verified p99 latency under burst load.', + 'Detected redundant index rebuilds during WAL compaction under overlapping worker writes.', + 'Verified chunk multiplexer handles reconnect retries without dropping trailing frames.', + 'Moved digest verification into the batch commit stage to avoid extra buffer copies.', + 'All unit tests and deterministic regression checks passed with zero integrity warnings.', + ], + toolNames: [ + 'read_file', 'edit_file', 'run_command', 'grep_search', + 'list_dir', 'apply_patch', 'inspect_metrics', 'verify_checksum', + ], +}; + +function toUint8(str) { + const buf = Buffer.from(str, 'utf8'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); +} + +function generateSourceFile(rng, theme, fileIndex, lineCount) { + const filePath = theme.files[fileIndex % theme.files.length]; + const isRust = filePath.endsWith('.rs'); + const lines = []; + const primary = theme.identifiers[fileIndex % theme.identifiers.length]; + const secondary = theme.identifiers[(fileIndex + 5) % theme.identifiers.length]; + lines.push(isRust ? `//! Module ${primary} (${filePath})` : `/** Module ${primary} (${filePath}) */`); + lines.push( + isRust + ? `use crate::common::{${secondary}, MetricsSink, StateDigest};` + : `import { ${secondary}, MetricsSink, StateDigest } from './common.js';`, + ); + lines.push(''); + + const verbs = ['validate', 'reconcile', 'compact', 'dispatch', 'serialize', 'verify', 'hydrate', 'drain', 'snapshot', 'rotate', 'merge', 'evict']; + const nouns = ['header', 'segment', 'window', 'cursor', 'journal', 'envelope', 'bucket', 'frame', 'quorum', 'batch', 'receipt', 'checkpoint']; + + let fnIdx = 0; + while (lines.length < lineCount) { + const idA = theme.identifiers[(fileIndex * 3 + fnIdx) % theme.identifiers.length]; + const idB = theme.identifiers[(fileIndex + fnIdx * 5 + 2) % theme.identifiers.length]; + const verb = verbs[(fnIdx + fileIndex) % verbs.length]; + const noun = nouns[(fnIdx * 3 + fileIndex) % nouns.length]; + const limit = 16 + (rng.u32() % 4096); + const mask = (rng.u32() & 0xffff).toString(16).padStart(4, '0'); + const step = 3 + (rng.u32() % 29); + const errCode = `ERR_${idA.toUpperCase().slice(0, 6)}_${noun.toUpperCase()}_${fnIdx}`; + const mode = fnIdx % 3; + + if (isRust) { + lines.push(`/// ${verb} ${noun} state for ${idA} using ${idB} bounds (limit=${limit}).`); + lines.push(`pub fn ${verb}_${noun}_${fnIdx}(ctx: &mut ${primary}, input: &[u8], epoch: u64) -> Result {`); + if (mode === 0) { + lines.push(` if input.len() < ${step} { return Err(Error::new("${errCode}", epoch)); }`); + lines.push(` let mut acc: u64 = (epoch ^ 0x${mask}) + ${limit};`); + lines.push(` for (idx, chunk) in input.chunks(${step}).enumerate() {`); + lines.push(` let delta = ctx.estimate_${idB.toLowerCase()}(idx as u64, chunk.len());`); + lines.push(` acc = acc.wrapping_mul(${31 + (fnIdx % 7)}).wrapping_add(delta ^ (chunk[0] as u64));`); + lines.push(` if acc % ${step + 5} == 0 { ctx.record_checkpoint("${idA}:${noun}", idx, acc); }`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` let mut cursor = ctx.open_${noun}_cursor(epoch, ${limit})?;`); + lines.push(` while let Some(slice) = cursor.next_window(${step * 8}) {`); + lines.push(` let digest = StateDigest::fold(slice, 0x${mask});`); + lines.push(` if !ctx.accept_${idB.toLowerCase()}(&digest) { return Err(Error::mismatch("${errCode}")); }`); + lines.push(` }`); + lines.push(` let acc = cursor.finalize_epoch("${theme.project}:${fnIdx}");`); + } else { + lines.push(` let tag = format!("${theme.project}/${idA}/${noun}#{}", epoch + ${fnIdx});`); + lines.push(` let mut slots = Vec::with_capacity(${16 + (fnIdx % 64)});`); + lines.push(` for slot in 0..${8 + (fnIdx % 12)} { slots.push((slot as u64 * ${step}) ^ 0x${mask}); }`); + lines.push(` let acc = ctx.apply_${verb}(&tag, &slots, input.len());`); + } + lines.push(` ctx.commit_window(${fnIdx}, acc as usize, "${errCode}");`); + lines.push(` Ok((acc & 0x3fff) as usize)`); + lines.push(`}`); + lines.push(''); + } else { + lines.push(`/** ${verb} ${noun} state for ${idA} with ${idB} guard (limit=${limit}). */`); + lines.push(`export function ${verb}${idA}${fnIdx}(ctx: ${primary}, input: Uint8Array, epoch: number): number {`); + if (mode === 0) { + lines.push(` if (input.length < ${step}) throw new RangeError('${errCode}: short input');`); + lines.push(` let acc = ((epoch ^ 0x${mask}) + ${limit}) >>> 0;`); + lines.push(` for (let idx = 0; idx < input.length; idx += ${step}) {`); + lines.push(` const delta = ctx.estimate${idB}(idx, input.length - idx);`); + lines.push(` acc = (Math.imul(acc, ${31 + (fnIdx % 7)}) + (delta ^ input[idx])) >>> 0;`); + lines.push(` if (acc % ${step + 5} === 0) ctx.recordCheckpoint('${idA}:${noun}', idx, acc);`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` const cursor = ctx.open${idB}Cursor(epoch, ${limit});`); + lines.push(` for (const slice of cursor.windows(${step * 8})) {`); + lines.push(` const digest = StateDigest.fold(slice, 0x${mask});`); + lines.push(` if (!ctx.accept${idA}(digest)) throw new Error('${errCode}: digest mismatch');`); + lines.push(` }`); + lines.push(` const acc = cursor.finalizeEpoch('${theme.project}:${noun}#${fnIdx}');`); + } else { + lines.push(` const tag = '${theme.project}/${idA}/${noun}#' + (epoch + ${fnIdx});`); + lines.push(` const slots = new Uint32Array(${8 + (fnIdx % 12)});`); + lines.push(` for (let s = 0; s < slots.length; s++) slots[s] = (s * ${step}) ^ 0x${mask};`); + lines.push(` const acc = ctx.apply${idB}(tag, slots, input.length);`); + } + lines.push(` ctx.commitWindow(${fnIdx}, acc, '${errCode}');`); + lines.push(` return acc & 0x3fff;`); + lines.push(`}`); + lines.push(''); + } + fnIdx++; + } + return lines.slice(0, lineCount); +} + +function formatLineNumbered(lines, startLine = 1, width = 5) { + const out = new Array(lines.length); + for (let i = 0; i < lines.length; i++) { + out[i] = `${String(startLine + i).padStart(width, ' ')}: ${lines[i]}`; + } + return out.join('\n'); +} + +function mutateSourceLines(rng, theme, prevLines, versionIdx) { + const lines = prevLines.slice(); + const insertAt = 8 + (rng.u32() % 35); + const insertCount = 2 + (rng.u32() % 4); + const added = []; + for (let k = 0; k < insertCount; k++) { + added.push(` // rev-${versionIdx}.${k}: guard ${rng.pick(theme.identifiers)} invariant (mask=0x${rng.hex(2)})`); + } + lines.splice(insertAt, 0, ...added); + const edits = 4 + (rng.u32() % 5); + for (let e = 0; e < edits; e++) { + const pos = 70 + (rng.u32() % (lines.length - 90)); + lines[pos] = lines[pos] + ` /* rev_${versionIdx}_${e} */`; + } + return lines; +} + +function makeToolDefinitions(theme) { + const defs = []; + for (let i = 0; i < 42; i++) { + const name = `${theme.toolNames[i % theme.toolNames.length]}_v${Math.floor(i / theme.toolNames.length) + 1}`; + const idA = theme.identifiers[i % theme.identifiers.length]; + const idB = theme.identifiers[(i + 7) % theme.identifiers.length]; + defs.push({ + name, + description: `Execute ${name} against ${theme.project} workspace (${idA} -> ${idB}). Returns structured diagnostic records, byte offsets, checksums, and execution trace spans without mutating unrelated workspace segments.`, + input_schema: { + type: 'object', + additionalProperties: false, + required: ['targetPath', 'mode', 'budgetMs'], + properties: { + targetPath: { type: 'string', description: `Relative path under ${theme.cwd} for ${idA} inspection.` }, + mode: { type: 'string', enum: ['fast', 'strict', 'audit', 'replay'] }, + budgetMs: { type: 'integer', minimum: 50, maximum: 60000, default: 5000 }, + includeTrace: { type: 'boolean', default: true }, + maxLines: { type: 'integer', minimum: 1, maximum: 4000, default: 1200 }, + filters: { type: 'array', items: { type: 'string' }, description: `Filter tags for ${idB} collector.` }, + encoding: { type: 'string', enum: ['utf8', 'binary', 'jsonl'], default: 'utf8' }, + checksumAlg: { type: 'string', enum: ['sha256', 'crc32'], default: 'sha256' }, + }, + }, + }); + } + return defs; +} + +function buildManifest(meta, rawEntries) { + const manifestEntries = rawEntries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: crypto.createHash('sha256').update(e.content).digest('hex'), + })); + const manifest = { + formatVersion: 3, + minReaderVersion: meta.orca ? 2 : 1, + appVersion: meta.appVersion, + platform: meta.platform, + exportedAt: meta.exportedAt, + agentKind: meta.agentKind, + title: meta.title, + workspaceKind: 'project', + originalWorkingDir: meta.cwd, + sdkSessionIds: meta.sdkSessionIds, + activeSdkSessionId: meta.sdkSessionIds[meta.sdkSessionIds.length - 1] ?? null, + exportFidelity: 'full', + counts: { messages: meta.messageCount, media: meta.mediaCount }, + entries: manifestEntries, + transcripts: meta.transcripts, + ...(meta.orca ? { orca: meta.orca } : {}), + }; + return toUint8(JSON.stringify(manifest, null, 2) + '\n'); +} + +function generateBundleA(rng, theme, opts) { + const sessionId = rng.uuid(); + const sdkSessionId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const model = theme.models[0]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const turnCount = opts.bundleATurns ?? 1000; + const mediaCopies = opts.bundleAMediaCopies ?? 18; + const srcFiles = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 340)); + + // 1 unique 16 KiB PNG duplicated across repeated architecture diagram captures + const uniqA = makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450); + const uniqAB64 = Buffer.from(uniqA).toString('base64'); + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < mediaCopies; m++) { + const filename = `diag-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqA) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + const msgLines = []; + const transcriptLines = []; + const traceLines = []; + + let tsMs = theme.baseEpochMs; + let prevUuid = null; + let inputTokens = 8400; + let cacheReadTokens = 7200; + let cumulativeCost = 14200; + let heapKb = 96000; + let rssKb = 184000; + + for (let i = 0; i < turnCount; i++) { + const dt = 500 + (i % 7) * 180 + rng.int(10, 80); + tsMs += dt; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const requestId = `req_${theme.project.slice(0, 4)}_${String(Math.floor(i / 2)).padStart(5, '0')}`; + const seq = i + 1; + + const kind = i % 4; + let role, dbContent, claudeType, claudeMessage; + let toolUseId = null; + let toolUseResult; + + const deltaIn = 120 + (i % 13) * 35; + const outTok = kind === 1 || kind === 3 ? (110 + (i % 11) * 28) : 0; + const cacheCreate = i % 16 === 0 ? 640 : 0; + cacheReadTokens = Math.max(0, inputTokens - 160); + inputTokens += deltaIn; + const durationMs = 240 + (i % 9) * 140; + const ttftMs = 95 + (i % 5) * 35; + cumulativeCost += Math.round((deltaIn * 3 + outTok * 15) / 10); + + const spanTrace = [tsMs - durationMs, tsMs - durationMs + ttftMs, tsMs - Math.floor(durationMs / 3), tsMs]; + + if (i === 12) { + role = 'user'; + claudeType = 'user'; + const note = `Architecture diagram check: ${theme.zhNotes[0]}`; + dbContent = `${note}\n![diag](cindy-image://${sessionId}/diag-01.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniqAB64 } }, + ], + }; + } else if (kind === 0) { + role = 'user'; + claudeType = 'user'; + const text = `[Step ${seq}] ${theme.zhNotes[i % theme.zhNotes.length]}\nFile: ${theme.files[i % theme.files.length]}\nContext: ${theme.enNotes[(i * 3) % theme.enNotes.length]}`; + dbContent = text; + claudeMessage = { role: 'user', content: [{ type: 'text', text }] }; + } else if (kind === 1) { + role = 'assistant'; + claudeType = 'assistant'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq).padStart(5, '0')}`; + const toolName = theme.toolNames[i % theme.toolNames.length]; + const inputObj = { + path: `${theme.cwd}/${theme.files[i % theme.files.length]}`, + startLine: 1 + ((i * 17) % 140), + endLine: 120 + ((i * 17) % 140), + includeMetrics: true, + tag: `${theme.branch}#${seq}`, + }; + dbContent = JSON.stringify({ + type: 'tool_use', + id: toolUseId, + name: toolName, + input: inputObj, + thought: theme.enNotes[i % theme.enNotes.length], + }); + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [ + { type: 'thinking', thinking: theme.enNotes[i % theme.enNotes.length] }, + { type: 'tool_use', id: toolUseId, name: toolName, input: inputObj }, + ], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } else if (kind === 2) { + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq - 1).padStart(5, '0')}`; + const fileIdx = (i >> 2) % srcFiles.length; + const lines = srcFiles[fileIdx]; + let payloadText; + if (i % 16 === 2) { + const start = (i * 5) % 80; + payloadText = formatLineNumbered(lines.slice(start, start + 120), start + 1, lnWidth); + } else if (i % 16 === 6) { + const f = theme.files[fileIdx]; + const diffLines = [ + `diff --git a/${f} b/${f}`, + `--- a/${f}`, + `+++ b/${f}`, + `@@ -${20 + (i % 80)},14 +${20 + (i % 80)},16 @@`, + ]; + for (let k = 0; k < 20; k++) { + diffLines.push((k === 5 ? '-' : k === 6 ? '+' : ' ') + lines[(20 + (i % 80) + k) % lines.length]); + } + payloadText = diffLines.join('\n'); + } else { + const logLines = [`$ test-runner --filter ${theme.identifiers[i % theme.identifiers.length]} --seed ${seq}`]; + for (let k = 0; k < 10; k++) { + logLines.push( + `[${new Date(tsMs - 200 + k * 10).toISOString()}] PASS case_${k} (${theme.identifiers[(i + k) % theme.identifiers.length]}) elapsed=${15 + (k % 5) * 4}ms rss=${rssKb + k * 16}KB`, + ); + } + payloadText = logLines.join('\n'); + } + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + is_error: false, + content: payloadText, + }); + toolUseResult = { + status: 'ok', + bytes: Buffer.byteLength(payloadText, 'utf8'), + durationMs, + stdout: payloadText, + }; + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: payloadText }], + }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const text = `${theme.zhNotes[(i + 2) % theme.zhNotes.length]}\n\nSummary (${theme.identifiers[i % theme.identifiers.length]}):\n- ${theme.enNotes[(i + 1) % theme.enNotes.length]}\n- Verified checkpoint #${seq} (${inputTokens} in / ${outTok} out).`; + dbContent = text; + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } + + const agentMetaObj = { + uuid, + parentUuid: prevUuid, + sdkSessionId, + model, + providerId, + requestId, + turnUsageDetails: { + inputTokens, + cacheReadTokens, + cacheCreationTokens: cacheCreate, + outputTokens: outTok, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + }, + }; + msgLines.push(JSON.stringify({ + id: `msg-${String(seq).padStart(6, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify(agentMetaObj), + })); + transcriptLines.push(JSON.stringify({ + parentUuid: prevUuid, + isSidechain: false, + userType: 'external', + cwd: theme.cwd, + sessionId: sdkSessionId, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId, + providerId, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + message: claudeMessage, + ...(toolUseResult ? { toolUseResult } : {}), + })); + prevUuid = uuid; + + // Structured telemetry spans placed between messages.jsonl and transcripts/ (>2 MiB separation) + for (let s = 0; s < 5; s++) { + const spanTs = tsMs - durationMs + s * Math.max(15, Math.floor(durationMs / 5)); + heapKb += 4 + (s === 4 ? -12 : 3); + rssKb += 6 + (s === 4 ? -16 : 4); + traceLines.push(JSON.stringify({ + seq: i * 5 + s + 1, + sessionId, + turnSeq: seq, + requestId, + phase: ['dispatch', 'prompt_cache', 'tool_exec', 'post_hook', 'commit'][s], + timestamp: new Date(spanTs).toISOString(), + tsMs: spanTs, + elapsedMs: 18 + s * 24 + (i % 7) * 5, + inputTokens: inputTokens + s * 4, + cacheReadTokens, + outputTokens: s === 4 ? outTok : Math.floor(outTok * (s / 4)), + heapUsedKb: heapKb, + rssKb, + cumulativeCostMicroUsd: cumulativeCost, + status: 'ok', + model, + providerId, + })); + } + } + + const transcriptPath = `transcripts/claude/${sdkSessionId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: single-agent optimization audit`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId, + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(msgLines.join('\n') + '\n') }, + ...mediaEntries, + { path: 'telemetry/turn-spans.jsonl', content: toUint8(traceLines.join('\n') + '\n') }, + { path: transcriptPath, content: toUint8(transcriptLines.join('\n') + '\n') }, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 5000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: single-agent optimization audit`, + cwd: theme.cwd, + sdkSessionIds: [sdkSessionId], + messageCount: turnCount, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId, path: transcriptPath }], + }, bodyEntries); + + return { + name: 'single-agent-session', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleB(rng, theme, opts) { + const sessionId = rng.uuid(); + const forkSids = [rng.uuid(), rng.uuid(), rng.uuid()]; + const nodeBuf = rng.bytes(5); + const model = theme.models[1]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const sharedTurns = opts.bundleBSharedTurns ?? 152; + const tailTurns = opts.bundleBTailTurns ?? 38; + + // 12 binary PNGs built from 3 unique incompressible blobs (64 KiB unique total, 356 KiB raw) + const uniquePngs = [ + makeSyntheticPng(rng, 38 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniquePngB64 = uniquePngs.map((b) => Buffer.from(b).toString('base64')); + const imgAssign = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2]; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < 12; m++) { + const filename = `img-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniquePngs[imgAssign[m]]) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + let fileVersions = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 640)); + let tsMs = theme.baseEpochMs + 3600_000; + let prevUuid = null; + let inputTokens = 12000; + let cumulativeCost = 22000; + + const sharedPrefixTurns = []; + const dbMsgLines = []; + let snapshotIdx = 0; + + for (let t = 0; t < sharedTurns; t++) { + tsMs += 600 + (t % 7) * 210 + rng.int(5, 45); + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, t + 1, nodeBuf); + const seq = t + 1; + const reqId = `req_fork_${String(Math.floor(t / 2)).padStart(4, '0')}`; + const durationMs = 260 + (t % 9) * 180; + const outTok = t % 2 === 1 ? (140 + (t % 7) * 40) : 0; + const cacheRead = Math.max(0, inputTokens - 180); + inputTokens += 150 + (t % 11) * 45; + cumulativeCost += Math.round((inputTokens * 2 + outTok * 15) / 100); + + let role, claudeType, claudeMessage, dbContent; + let toolUseId = null; + + if (t === 5 || t === 55 || t === 105) { + const imgIdx = t === 5 ? 0 : t === 55 ? 1 : 2; + role = 'user'; + claudeType = 'user'; + const note = `Screenshot #${imgIdx + 1}: ${theme.zhNotes[imgIdx]} (${theme.enNotes[imgIdx]})`; + const imgNum = imgIdx === 0 ? 1 : imgIdx === 1 ? 9 : 11; + dbContent = `${note}\n![shot](cindy-image://${sessionId}/img-${String(imgNum).padStart(2, '0')}.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniquePngB64[imgIdx] } }, + ], + }; + } else if (t > 0 && t % 7 === 0 && snapshotIdx < 20) { + const fIdx = snapshotIdx % 4; + const rev = Math.floor(snapshotIdx / 4); + if (rev > 0) fileVersions[fIdx] = mutateSourceLines(rng, theme, fileVersions[fIdx], rev); + snapshotIdx++; + const numbered = formatLineNumbered(fileVersions[fIdx], 1, lnWidth); + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_snap_${String(snapshotIdx).padStart(3, '0')}`; + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + file: theme.files[fIdx], + revision: rev, + content: numbered, + }); + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: numbered }], + }; + } else if (t % 2 === 0) { + role = 'user'; + claudeType = 'user'; + const logLine = `[turn ${seq}] ${theme.zhNotes[t % theme.zhNotes.length]} | ${theme.enNotes[(t * 5) % theme.enNotes.length]} | metrics: latency=${durationMs}ms`; + dbContent = logLine; + claudeMessage = { role: 'user', content: [{ type: 'text', text: logLine }] }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const reply = `Analysis #${seq} (${theme.identifiers[t % theme.identifiers.length]}): ${theme.enNotes[(t + 2) % theme.enNotes.length]}\n${theme.zhNotes[(t + 1) % theme.zhNotes.length]}`; + dbContent = reply; + claudeMessage = { + id: `msg_f_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text: reply }], + usage: { input_tokens: inputTokens, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + + sharedPrefixTurns.push({ + parentUuid: prevUuid, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId: reqId, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + message: claudeMessage, + }); + dbMsgLines.push(JSON.stringify({ + id: `bmsg-${String(seq).padStart(5, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: prevUuid, + sdkSessionId: forkSids[2], + model, + providerId, + requestId: reqId, + inputTokens, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + }), + })); + prevUuid = uuid; + } + + const forkEntries = []; + const transcriptRefs = []; + for (let f = 0; f < 3; f++) { + const fSid = forkSids[f]; + const lines = sharedPrefixTurns.map((turn) => JSON.stringify({ ...turn, sessionId: fSid, forkBranch: `fork-${f}` })); + let fPrev = prevUuid; + let fTs = tsMs + f * 60_000; + let fIn = inputTokens; + let fCost = cumulativeCost; + for (let k = 0; k < tailTurns; k++) { + fTs += 500 + (k % 5) * 190 + rng.int(5, 35); + const iso = new Date(fTs).toISOString(); + const uuid = rng.uuidv7(fTs, 200 + f * 60 + k, nodeBuf); + const outTok = k % 2 === 1 ? (110 + (k % 7) * 35) : 0; + const cacheRead = Math.max(0, fIn - 140); + fIn += 130 + (k % 9) * 40; + fCost += Math.round((fIn * 2 + outTok * 15) / 100); + let msg; + if (f === 2 && k < 4) { + fileVersions[k] = mutateSourceLines(rng, theme, fileVersions[k], 5 + f); + const numbered = formatLineNumbered(fileVersions[k], 1, lnWidth); + msg = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: `toolu_tail_${f}_${k}`, is_error: false, content: numbered }], + }; + } else { + const text = `[fork-${f} tail ${k + 1}] ${theme.enNotes[(k + f * 2) % theme.enNotes.length]} | ${theme.zhNotes[(k + f) % theme.zhNotes.length]}`; + msg = k % 2 === 0 + ? { role: 'user', content: [{ type: 'text', text }] } + : { + id: `msg_f${f}_t${k}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { input_tokens: fIn, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + lines.push(JSON.stringify({ + parentUuid: fPrev, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: `${theme.branch}-f${f}`, + type: k % 2 === 0 ? 'user' : 'assistant', + uuid, + timestamp: iso, + requestId: `req_f${f}_${String(k).padStart(3, '0')}`, + durationMs: 220 + (k % 8) * 140, + cumulativeCostMicroUsd: fCost, + sessionId: fSid, + forkBranch: `fork-${f}`, + message: msg, + })); + fPrev = uuid; + } + const tp = `transcripts/claude/fork-${f}.jsonl`; + forkEntries.push({ path: tp, content: toUint8(lines.join('\n') + '\n') }); + transcriptRefs.push({ sdkSessionId: fSid, path: tp }); + } + + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: fork chain & evolving snapshots`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId: forkSids[2], + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs + 3600_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(dbMsgLines.join('\n') + '\n') }, + ...mediaEntries, + ...forkEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 90_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: fork chain & evolving snapshots`, + cwd: theme.cwd, + sdkSessionIds: forkSids, + messageCount: dbMsgLines.length, + mediaCount: mediaEntries.length, + transcripts: transcriptRefs, + }, bodyEntries); + + return { + name: 'fork-chain-and-media', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleC(rng, theme, opts) { + const leadSessionId = rng.uuid(); + const leadSdkId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const lnWidth = theme.lineNumWidth ?? 5; + const workerTurns = opts.bundleCWorkerTurns ?? 110; + const workerMediaEach = opts.bundleCWorkerShotsEach ?? 14; + const toolDefs = makeToolDefinitions(theme); + const systemPromptBase = [ + `You are an Orca autonomous engineering worker operating inside ${theme.cwd} (${theme.project}).`, + ...theme.enNotes, + ...theme.zhNotes, + 'Strict invariants: preserve exact wire compatibility, maintain deterministic ordering, never drop audit checksums, verify every edge case before reporting completion.', + ].join('\n'); + const sharedRepoFiles = [0, 1, 4, 5].map((i) => generateSourceFile(rng, theme, i, 420)); + + // 2 unique 16 KiB PNGs (32 KiB unique floor) duplicated across lead & 4 workers' verification screenshots + const uniqShots = [ + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniqShotsB64 = uniqShots.map((b) => Buffer.from(b).toString('base64')); + const totalShots = 4 + 4 * workerMediaEach; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < totalShots; m++) { + const filename = m < 4 + ? `lead-shot-${String(m + 1).padStart(2, '0')}.png` + : `worker-${Math.floor((m - 4) / workerMediaEach)}-shot-${String(((m - 4) % workerMediaEach) + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqShots[m % 2]) }); + mediaMap.push({ + url: `cindy-image://${leadSessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: leadSessionId, + filename, + }); + } + + let tsMs = theme.baseEpochMs + 7200_000; + const leadMsgs = []; + const leadTranscript = []; + let leadPrev = null; + for (let i = 0; i < 44; i++) { + tsMs += 800 + (i % 5) * 140; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const text = `[Lead #${i + 1}] Coordinate worker ${i % 4}: ${theme.zhNotes[i % theme.zhNotes.length]} (${theme.enNotes[i % theme.enNotes.length]})`; + leadMsgs.push(JSON.stringify({ + id: `lead-${String(i + 1).padStart(4, '0')}`, + sessionId: leadSessionId, + seq: i + 1, + role: i % 2 === 0 ? 'user' : 'assistant', + createdAt: iso, + createdAtMs: tsMs, + toolUseId: null, + content: text, + agentMeta: JSON.stringify({ uuid, parentUuid: leadPrev, sdkSessionId: leadSdkId, model: theme.models[0] }), + })); + leadTranscript.push(JSON.stringify({ + parentUuid: leadPrev, + sessionId: leadSdkId, + uuid, + timestamp: iso, + type: i % 2 === 0 ? 'user' : 'assistant', + message: { role: i % 2 === 0 ? 'user' : 'assistant', content: [{ type: 'text', text }] }, + })); + leadPrev = uuid; + } + + const workerEntries = []; + const workerManifests = []; + const roles = theme.workerRoles ?? ['implementer', 'verifier', 'profiler', 'auditor']; + + for (let w = 0; w < 4; w++) { + const wSessionId = rng.uuid(); + const wThreadId = rng.uuid(); + const wNode = rng.bytes(5); + const wDir = `${theme.cwd}/.worktrees/worker-${w}`; + const wMsgs = []; + const wRollout = []; + let wTs = theme.baseEpochMs + 7210_000 + w * 2500; + let wIn = 18000; + let wCost = 9500; + let wPrev = null; + + const workerTools = toolDefs.map((d) => ({ + ...d, + description: `[worker-${w}/${roles[w]}] ${d.description}`, + })); + wRollout.push(JSON.stringify({ + timestamp: new Date(wTs).toISOString(), + type: 'session_meta', + payload: { + id: wThreadId, + workerIndex: w, + workerRole: roles[w], + cwd: wDir, + model: theme.codexModel, + providerId: theme.providers[1], + systemPrompt: `${systemPromptBase}\nAssigned Role: ${roles[w]} (#${w})`, + tools: workerTools, + }, + })); + + for (let t = 0; t < workerTurns; t++) { + wTs += 500 + (t % 7) * 160 + rng.int(5, 30); + const iso = new Date(wTs).toISOString(); + const uuid = rng.uuidv7(wTs, t + 1, wNode); + const seq = t + 1; + const cacheRead = Math.max(0, wIn - 180); + const outTok = t % 2 === 1 ? (120 + (t % 9) * 32) : 0; + const dur = 180 + (t % 8) * 160; + wIn += 140 + (t % 11) * 45; + wCost += Math.round((wIn + outTok * 12) / 80); + + let role, dbContent, rolloutItem; + let toolUseId = null; + + if (t === 4 || t === 56) { + const sIdx = (w + (t === 4 ? 0 : 1)) % 2; + role = 'user'; + dbContent = JSON.stringify({ + type: 'screenshot_check', + worker: w, + image: `cindy-image://${leadSessionId}/worker-${w}-shot-0${sIdx + 1}.png`, + }); + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role: 'user', + content: [ + { type: 'input_text', text: `Verify UI screenshot #${sIdx + 1} for worker-${w}` }, + { type: 'input_image', image_url: `data:image/png;base64,${uniqShotsB64[sIdx]}` }, + ], + }, + }; + } else if (t % 20 === 6) { + const fIdx = Math.floor(t / 20) % sharedRepoFiles.length; + const lines = w === 0 ? sharedRepoFiles[fIdx] : mutateSourceLines(rng, theme, sharedRepoFiles[fIdx], w * 10 + t); + const numbered = formatLineNumbered(lines, 1, lnWidth); + role = 'tool'; + toolUseId = `call_w${w}_${String(seq).padStart(4, '0')}`; + dbContent = JSON.stringify({ + type: 'function_call_output', + call_id: toolUseId, + file: theme.files[fIdx], + output: numbered, + }); + rolloutItem = { + type: 'response_item', + payload: { type: 'function_call_output', call_id: toolUseId, output: numbered }, + }; + } else if (t % 10 === 0) { + role = 'assistant'; + const summary = `Worker ${w} (${roles[w]}) turn ${seq}: ${theme.enNotes[(t + w) % theme.enNotes.length]}`; + dbContent = JSON.stringify({ type: 'tool_context', worker: w, summary, toolCount: workerTools.length }); + rolloutItem = { + type: 'turn_context', + payload: { + turn: seq, + cwd: wDir, + model: theme.codexModel, + summary, + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + ...(t === 0 || t === 50 ? { tools: workerTools } : {}), + }, + }; + } else { + role = t % 2 === 0 ? 'user' : 'assistant'; + const text = `[worker-${w}/${roles[w]} #${seq}] ${theme.zhNotes[(t + w) % theme.zhNotes.length]}\n${theme.enNotes[(t * 3 + w) % theme.enNotes.length]} (tokens=${wIn}, dur=${dur}ms)`; + dbContent = text; + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role, + content: [{ type: role === 'user' ? 'input_text' : 'output_text', text }], + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + }, + }; + } + + wMsgs.push(JSON.stringify({ + id: `w${w}-msg-${String(seq).padStart(5, '0')}`, + sessionId: wSessionId, + seq, + role, + createdAt: iso, + createdAtMs: wTs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: wPrev, + sdkSessionId: wThreadId, + model: theme.codexModel, + providerId: theme.providers[1], + workerIndex: w, + turnUsageDetails: { + inputTokens: wIn, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs: dur, + cumulativeCostMicroUsd: wCost, + }, + }), + })); + wRollout.push(JSON.stringify({ + timestamp: iso, + tsMs: wTs, + uuid, + parentUuid: wPrev, + sessionId: wThreadId, + workerIndex: w, + ...rolloutItem, + })); + wPrev = uuid; + } + + const prefix = `orca/workers/${w}`; + const rolloutPath = `${prefix}/transcripts/codex/rollout.jsonl`; + workerEntries.push( + { + path: `${prefix}/session.json`, + content: toUint8(JSON.stringify({ + id: wSessionId, + title: `Worker ${w} (${roles[w]})`, + workingDir: wDir, + workspaceKind: 'project', + model: theme.codexModel, + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[1], + status: 'done', + sdkSessionId: wThreadId, + totalTokenUsage: wIn, + totalCostUsd: Number((wCost / 1e6).toFixed(6)), + agentKind: 'codex', + orcaRole: 'worker', + createdAt: theme.baseEpochMs + 7210_000, + updatedAt: wTs, + }, null, 2) + '\n'), + }, + { path: `${prefix}/messages.jsonl`, content: toUint8(wMsgs.join('\n') + '\n') }, + { path: rolloutPath, content: toUint8(wRollout.join('\n') + '\n') }, + ); + workerManifests.push({ + index: w, + agentKind: 'codex', + providerId: theme.providers[1], + title: `Worker ${w} (${roles[w]})`, + role: roles[w], + label: `worker-${w}`, + status: 'done', + focused: w === 0, + sdkSessionIds: [wThreadId], + activeSdkSessionId: wThreadId, + counts: { messages: wMsgs.length }, + transcripts: [{ sdkSessionId: wThreadId, path: rolloutPath }], + }); + } + + const leadTranscriptPath = `transcripts/claude/${leadSdkId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: leadSessionId, + title: `${theme.project}: Orca 4-worker team session`, + workingDir: theme.cwd, + workspaceKind: 'project', + model: theme.models[0], + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[0], + status: 'idle', + sdkSessionId: leadSdkId, + agentKind: 'cc', + orcaRole: 'lead', + createdAt: theme.baseEpochMs + 7200_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(leadMsgs.join('\n') + '\n') }, + { path: leadTranscriptPath, content: toUint8(leadTranscript.join('\n') + '\n') }, + ...mediaEntries, + ...workerEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 120_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: Orca 4-worker team session`, + cwd: theme.cwd, + sdkSessionIds: [leadSdkId], + messageCount: leadMsgs.length, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId: leadSdkId, path: leadTranscriptPath }], + orca: { teamStatus: 'completed', workers: workerManifests }, + }, bodyEntries); + + return { + name: 'orca-team-archive', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +export function generateCorpusSuite(options = {}) { + const seed = options.seed ?? PUBLIC_SEED; + const theme = options.theme ?? PUBLIC_THEME; + const rng = createDeterministicRng(seed); + return { + suiteName: options.suiteName ?? 'public', + bundles: [ + generateBundleA(rng, theme, options), + generateBundleB(rng, theme, options), + generateBundleC(rng, theme, options), + ], + }; +} + +export function generatePublicSuite() { + return generateCorpusSuite({ seed: PUBLIC_SEED, theme: PUBLIC_THEME, suiteName: 'public' }); +} + +export function measureBundleRawBytes(bundle) { + let total = 0; + for (const e of bundle.entries) total += e.content.byteLength; + return total; +} diff --git a/questions/opt-cshare-compression/v1/candidate/package.json b/questions/opt-cshare-compression/v1/candidate/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v1/candidate/src/container.mjs b/questions/opt-cshare-compression/v1/candidate/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v1/candidate/src/cshare-codec.mjs b/questions/opt-cshare-compression/v1/candidate/src/cshare-codec.mjs new file mode 100644 index 0000000..ae57561 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/src/cshare-codec.mjs @@ -0,0 +1,88 @@ +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +/** + * Baseline Cindy `.cshare` codec: + * Per-entry raw DEFLATE (level 6), no cross-file solid compression, + * no media deduplication, compresses binary media entries identically to text. + */ +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const headerVersion = bundle.headerVersion ?? XDTSHARE_HEADER_VERSION; + const header = encodePlainHeader(headerVersion); + + const countBuf = Buffer.alloc(4); + countBuf.writeUInt32LE(bundle.entries.length, 0); + + const chunks = [header, countBuf]; + for (const entry of bundle.entries) { + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const pathBuf = Buffer.from(entry.path, 'utf8'); + const rawBuf = toBufferView(entry.content); + const compressed = zlib.deflateRawSync(rawBuf, { level: 6 }); + + const meta = Buffer.alloc(12); + meta.writeUInt32LE(pathBuf.length, 0); + meta.writeUInt32LE(rawBuf.length, 4); + meta.writeUInt32LE(compressed.length, 8); + chunks.push(meta, pathBuf, compressed); + } + + const out = Buffer.concat(chunks); + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + if (payload.length < 4) { + throw new Error('Truncated archive payload'); + } + const entryCount = payload.readUInt32LE(0); + let offset = 4; + const entries = new Array(entryCount); + + for (let i = 0; i < entryCount; i++) { + if (offset + 12 > payload.length) { + throw new Error(`Truncated entry header at index ${i}`); + } + const pathLen = payload.readUInt32LE(offset); + const rawLen = payload.readUInt32LE(offset + 4); + const compLen = payload.readUInt32LE(offset + 8); + offset += 12; + + if (offset + pathLen + compLen > payload.length) { + throw new Error(`Truncated entry data at index ${i}`); + } + const entryPath = payload.toString('utf8', offset, offset + pathLen); + offset += pathLen; + const compSlice = payload.subarray(offset, offset + compLen); + offset += compLen; + + const inflated = zlib.inflateRawSync(compSlice); + if (inflated.length !== rawLen) { + throw new Error(`Size mismatch for ${entryPath}: expected ${rawLen}, got ${inflated.length}`); + } + entries[i] = { + path: entryPath, + content: new Uint8Array(inflated.buffer, inflated.byteOffset, inflated.byteLength), + }; + } + + if (offset !== payload.length) { + throw new Error(`Unexpected trailing bytes: ${payload.length - offset}`); + } + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v1/candidate/tests/smoke.test.mjs b/questions/opt-cshare-compression/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..4beed65 --- /dev/null +++ b/questions/opt-cshare-compression/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { generatePublicSuite } from '../lib/corpus-generator.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = generatePublicSuite(); + assert.equal(suite.bundles.length, 3); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/CONTRACT.md b/questions/opt-cshare-compression/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..b1b35f7 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,54 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Performance limits (held-out corpus total across 3 bundles)**: + - Total `encodeArchive` time: `<= 12,000 ms` (12 seconds) + - Total `decodeArchive` time: `<= 5,000 ms` (5 seconds) diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/ENVIRONMENT.md b/questions/opt-cshare-compression/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..1fee79d --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. For Node.js 18+ portability, `zlib.deflateRawSync`, `zlib.gzipSync`, and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` is present without checking availability first. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism & held-out evaluation: + - Public benchmark (`npm run bench`) runs on a deterministic 3-bundle public `.cshare` corpus generated by `lib/corpus-generator.mjs`. + - Official grading evaluates bit-exact lossless correctness, stateless child-process decoding, header/timing limits (`encode <= 12s`, `decode <= 5s`), and total `archive_bytes` on an **unseen held-out 3-bundle corpus** with different seeds, project domain, file paths, code identifiers, vocabulary, UUID spaces, timestamps, and media. +- Public checks: + - `npm test` — lossless round-trip, header validation, and adversarial edge-case smoke tests + - `npm run bench` — deterministic public corpus benchmark reporting raw size, `archive_bytes`, compression ratio, and encode/decode timings diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/TASK.md b/questions/opt-cshare-compression/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..15239d3 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive lossless compression codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). + +## Observed Production Symptoms + +Cindy exports AI coding sessions—including single-agent sessions, Claude fork chains, media attachments, and Orca multi-worker team archives—into `.cshare` files using per-entry raw DEFLATE (level 6) with no cross-file solid compression, no content deduplication, and no structural preprocessing. As a result, realistic 10–14 MiB session exports still occupy multiple megabytes when shared or migrated across devices, despite containing massive structural and semantic redundancy across: +- Pretty-printed JSON metadata (`manifest.json`, `session.json`, `media-map.json`) +- Database `messages.jsonl` and native vendor transcripts (`transcripts/claude/*.jsonl`, `transcripts/codex/rollout.jsonl`) +- Structured JSONL telemetry, timestamps, IDs, and numeric usage counters +- Fork chains (`fork-0.jsonl`, `fork-1.jsonl`, `fork-2.jsonl`) and Orca worker subdirectories (`orca/workers/0..3/`) +- Evolving file snapshots and duplicated binary media attachments (`media/*.png`) + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header (`"XDTSHARE"` ASCII 8B + `headerVersion=1` u8 + `cipher=0` u8 + 2 zero reserved bytes). Everything from byte 12 onward is your open-ended lossless container and compression format. +- Guarantee **100% bit-exact lossless round-trip** (`headerVersion`, entry count, exact entry order, exact UTF-8 paths, and byte-exact contents) across all valid `.cshare` bundles and arbitrary binary/edge-case payloads. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must reconstruct every entry in a fresh isolated Node.js process given only the encoded archive bytes. +- **Open-ended optimization goal**: Minimize total encoded `archive_bytes` on the **unseen held-out evaluation suite** (which uses different seeds, project domains, file names, code identifiers, vocabulary, UUID spaces, timestamps, and media—hardcoded dictionaries will not generalize), while staying within Node.js built-ins (zero external npm packages) and the held-out runtime limits (`encode <= 12s`, `decode <= 5s`). +- Run `npm test` and `npm run bench` to verify correctness and compare public corpus sizes before and after your changes. +- Record your analysis, format design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料生成器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/bench/workload.mjs b/questions/opt-cshare-compression/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..4304604 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { generatePublicSuite, measureBundleRawBytes } from '../lib/corpus-generator.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = generatePublicSuite(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/lib/corpus-generator.mjs b/questions/opt-cshare-compression/v1/controls/incomplete/lib/corpus-generator.mjs new file mode 100644 index 0000000..db0f35a --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/lib/corpus-generator.mjs @@ -0,0 +1,1269 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic parameterized `.cshare` archive corpus generator. + * Pure Node.js >= 18 ESM, zero external dependencies, zero wall-clock or random nondeterminism. + */ + +function hashSeed(str) { + const h = crypto.createHash('sha256').update(String(str)).digest(); + return [h.readUInt32LE(0), h.readUInt32LE(4), h.readUInt32LE(8), h.readUInt32LE(12)]; +} + +export function createDeterministicRng(seed) { + let [a, b, c, d] = hashSeed(seed); + function nextU32() { + const t = b << 9; + let r = b * 5; + r = ((r << 7) | (r >>> 25)) * 9; + c ^= a; + d ^= b; + b ^= c; + a ^= d; + c ^= t; + d = (d << 11) | (d >>> 21); + return r >>> 0; + } + return { + u32: nextU32, + int(min, max) { + return min + (nextU32() % (max - min + 1)); + }, + pick(arr) { + return arr[nextU32() % arr.length]; + }, + bytes(len) { + const out = Buffer.allocUnsafe(len); + let i = 0; + while (i + 4 <= len) { + out.writeUInt32LE(nextU32(), i); + i += 4; + } + while (i < len) out[i++] = nextU32() & 0xff; + return out; + }, + uuid() { + const b16 = this.bytes(16); + b16[6] = (b16[6] & 0x0f) | 0x40; + b16[8] = (b16[8] & 0x3f) | 0x80; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + uuidv7(tsMs, seq, nodeBuf) { + const b16 = Buffer.alloc(16); + b16.writeUInt32BE(Math.floor(tsMs / 0x10000) >>> 0, 0); + b16.writeUInt16BE(tsMs & 0xffff, 4); + b16[6] = 0x70 | ((seq >>> 8) & 0x0f); + b16[7] = seq & 0xff; + b16[8] = 0x80 | (nodeBuf[0] & 0x3f); + b16[9] = nodeBuf[1]; + b16[10] = nodeBuf[2]; + b16[11] = nodeBuf[3]; + b16[12] = nodeBuf[4]; + const rnd = nextU32(); + b16[13] = (rnd >>> 16) & 0xff; + b16[14] = (rnd >>> 8) & 0xff; + b16[15] = rnd & 0xff; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + hex(nBytes) { + return this.bytes(nBytes).toString('hex'); + }, + }; +} + +// ---------- Valid PNG framing over deterministic incompressible payload ---------- +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function pngChunk(type, data) { + const typeBuf = Buffer.from(type, 'ascii'); + const lenBuf = Buffer.alloc(4); + lenBuf.writeUInt32BE(data.length, 0); + const crcBuf = Buffer.alloc(4); + crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0); + return Buffer.concat([lenBuf, typeBuf, data, crcBuf]); +} + +export function makeSyntheticPng(rng, payloadBytes, width = 800, height = 450) { + const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // RGBA + const raw = Buffer.concat([ + sig, + pngChunk('IHDR', ihdr), + pngChunk('IDAT', rng.bytes(payloadBytes)), + pngChunk('IEND', Buffer.alloc(0)), + ]); + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); +} + +// ---------- Default public theme ---------- +export const PUBLIC_SEED = 'cshare-public-suite-v1'; + +export const PUBLIC_THEME = { + project: 'nebula-sync', + cwd: '/Users/dev/workspace/nebula-sync', + branch: 'feat/incremental-snapshot-pipeline', + appVersion: '2.14.3', + platform: 'darwin', + baseEpochMs: Date.UTC(2026, 3, 12, 9, 15, 0), + lineNumWidth: 5, + pngWidth: 800, + pngHeight: 450, + models: ['claude-sonnet-4-6', 'claude-opus-4-6'], + codexModel: 'gpt-5.3-codex', + providers: ['anthropic-direct', 'openai-codex'], + workerRoles: ['implementer', 'verifier', 'profiler', 'auditor'], + files: [ + 'src/sync/snapshotScheduler.ts', + 'src/sync/deltaJournal.ts', + 'src/storage/walCompactor.ts', + 'src/network/chunkMuxer.ts', + 'src/protocol/frameValidator.ts', + 'src/metrics/backpressureProbe.ts', + ], + identifiers: [ + 'SnapshotScheduler', 'DeltaJournal', 'WalCompactor', 'ChunkMuxer', + 'FrameValidator', 'BackpressureProbe', 'EpochCursor', 'SegmentRing', + 'LeaseToken', 'CheckpointBarrier', 'FlushWindow', 'ReplayIndex', + 'MerkleBucket', 'PeerTransport', 'ThrottleGate', 'DigestCache', + ], + zhNotes: [ + '检查增量快照写入路径是否存在重复刷盘或锁竞争问题。', + '已完成核心调度器的边界修复,正在补齐回归测试并核对延迟分位数。', + '发现 WAL 压缩窗口在高并发下会触发多余的索引重建,已调整阈值。', + '对比了新旧分片多路复用逻辑,确认在断连重传时不再丢弃尾帧。', + '建议将校验和计算下沉到批量提交阶段,减少热路径上的内存拷贝。', + '已核验全部单元测试与冒烟基准,吞吐和内存峰值符合预期。', + ], + enNotes: [ + 'Auditing the incremental snapshot pipeline for redundant disk flushes and lock contention.', + 'Applied boundary guard to the scheduler queue and verified p99 latency under burst load.', + 'Detected redundant index rebuilds during WAL compaction under overlapping worker writes.', + 'Verified chunk multiplexer handles reconnect retries without dropping trailing frames.', + 'Moved digest verification into the batch commit stage to avoid extra buffer copies.', + 'All unit tests and deterministic regression checks passed with zero integrity warnings.', + ], + toolNames: [ + 'read_file', 'edit_file', 'run_command', 'grep_search', + 'list_dir', 'apply_patch', 'inspect_metrics', 'verify_checksum', + ], +}; + +function toUint8(str) { + const buf = Buffer.from(str, 'utf8'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); +} + +function generateSourceFile(rng, theme, fileIndex, lineCount) { + const filePath = theme.files[fileIndex % theme.files.length]; + const isRust = filePath.endsWith('.rs'); + const lines = []; + const primary = theme.identifiers[fileIndex % theme.identifiers.length]; + const secondary = theme.identifiers[(fileIndex + 5) % theme.identifiers.length]; + lines.push(isRust ? `//! Module ${primary} (${filePath})` : `/** Module ${primary} (${filePath}) */`); + lines.push( + isRust + ? `use crate::common::{${secondary}, MetricsSink, StateDigest};` + : `import { ${secondary}, MetricsSink, StateDigest } from './common.js';`, + ); + lines.push(''); + + const verbs = ['validate', 'reconcile', 'compact', 'dispatch', 'serialize', 'verify', 'hydrate', 'drain', 'snapshot', 'rotate', 'merge', 'evict']; + const nouns = ['header', 'segment', 'window', 'cursor', 'journal', 'envelope', 'bucket', 'frame', 'quorum', 'batch', 'receipt', 'checkpoint']; + + let fnIdx = 0; + while (lines.length < lineCount) { + const idA = theme.identifiers[(fileIndex * 3 + fnIdx) % theme.identifiers.length]; + const idB = theme.identifiers[(fileIndex + fnIdx * 5 + 2) % theme.identifiers.length]; + const verb = verbs[(fnIdx + fileIndex) % verbs.length]; + const noun = nouns[(fnIdx * 3 + fileIndex) % nouns.length]; + const limit = 16 + (rng.u32() % 4096); + const mask = (rng.u32() & 0xffff).toString(16).padStart(4, '0'); + const step = 3 + (rng.u32() % 29); + const errCode = `ERR_${idA.toUpperCase().slice(0, 6)}_${noun.toUpperCase()}_${fnIdx}`; + const mode = fnIdx % 3; + + if (isRust) { + lines.push(`/// ${verb} ${noun} state for ${idA} using ${idB} bounds (limit=${limit}).`); + lines.push(`pub fn ${verb}_${noun}_${fnIdx}(ctx: &mut ${primary}, input: &[u8], epoch: u64) -> Result {`); + if (mode === 0) { + lines.push(` if input.len() < ${step} { return Err(Error::new("${errCode}", epoch)); }`); + lines.push(` let mut acc: u64 = (epoch ^ 0x${mask}) + ${limit};`); + lines.push(` for (idx, chunk) in input.chunks(${step}).enumerate() {`); + lines.push(` let delta = ctx.estimate_${idB.toLowerCase()}(idx as u64, chunk.len());`); + lines.push(` acc = acc.wrapping_mul(${31 + (fnIdx % 7)}).wrapping_add(delta ^ (chunk[0] as u64));`); + lines.push(` if acc % ${step + 5} == 0 { ctx.record_checkpoint("${idA}:${noun}", idx, acc); }`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` let mut cursor = ctx.open_${noun}_cursor(epoch, ${limit})?;`); + lines.push(` while let Some(slice) = cursor.next_window(${step * 8}) {`); + lines.push(` let digest = StateDigest::fold(slice, 0x${mask});`); + lines.push(` if !ctx.accept_${idB.toLowerCase()}(&digest) { return Err(Error::mismatch("${errCode}")); }`); + lines.push(` }`); + lines.push(` let acc = cursor.finalize_epoch("${theme.project}:${fnIdx}");`); + } else { + lines.push(` let tag = format!("${theme.project}/${idA}/${noun}#{}", epoch + ${fnIdx});`); + lines.push(` let mut slots = Vec::with_capacity(${16 + (fnIdx % 64)});`); + lines.push(` for slot in 0..${8 + (fnIdx % 12)} { slots.push((slot as u64 * ${step}) ^ 0x${mask}); }`); + lines.push(` let acc = ctx.apply_${verb}(&tag, &slots, input.len());`); + } + lines.push(` ctx.commit_window(${fnIdx}, acc as usize, "${errCode}");`); + lines.push(` Ok((acc & 0x3fff) as usize)`); + lines.push(`}`); + lines.push(''); + } else { + lines.push(`/** ${verb} ${noun} state for ${idA} with ${idB} guard (limit=${limit}). */`); + lines.push(`export function ${verb}${idA}${fnIdx}(ctx: ${primary}, input: Uint8Array, epoch: number): number {`); + if (mode === 0) { + lines.push(` if (input.length < ${step}) throw new RangeError('${errCode}: short input');`); + lines.push(` let acc = ((epoch ^ 0x${mask}) + ${limit}) >>> 0;`); + lines.push(` for (let idx = 0; idx < input.length; idx += ${step}) {`); + lines.push(` const delta = ctx.estimate${idB}(idx, input.length - idx);`); + lines.push(` acc = (Math.imul(acc, ${31 + (fnIdx % 7)}) + (delta ^ input[idx])) >>> 0;`); + lines.push(` if (acc % ${step + 5} === 0) ctx.recordCheckpoint('${idA}:${noun}', idx, acc);`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` const cursor = ctx.open${idB}Cursor(epoch, ${limit});`); + lines.push(` for (const slice of cursor.windows(${step * 8})) {`); + lines.push(` const digest = StateDigest.fold(slice, 0x${mask});`); + lines.push(` if (!ctx.accept${idA}(digest)) throw new Error('${errCode}: digest mismatch');`); + lines.push(` }`); + lines.push(` const acc = cursor.finalizeEpoch('${theme.project}:${noun}#${fnIdx}');`); + } else { + lines.push(` const tag = '${theme.project}/${idA}/${noun}#' + (epoch + ${fnIdx});`); + lines.push(` const slots = new Uint32Array(${8 + (fnIdx % 12)});`); + lines.push(` for (let s = 0; s < slots.length; s++) slots[s] = (s * ${step}) ^ 0x${mask};`); + lines.push(` const acc = ctx.apply${idB}(tag, slots, input.length);`); + } + lines.push(` ctx.commitWindow(${fnIdx}, acc, '${errCode}');`); + lines.push(` return acc & 0x3fff;`); + lines.push(`}`); + lines.push(''); + } + fnIdx++; + } + return lines.slice(0, lineCount); +} + +function formatLineNumbered(lines, startLine = 1, width = 5) { + const out = new Array(lines.length); + for (let i = 0; i < lines.length; i++) { + out[i] = `${String(startLine + i).padStart(width, ' ')}: ${lines[i]}`; + } + return out.join('\n'); +} + +function mutateSourceLines(rng, theme, prevLines, versionIdx) { + const lines = prevLines.slice(); + const insertAt = 8 + (rng.u32() % 35); + const insertCount = 2 + (rng.u32() % 4); + const added = []; + for (let k = 0; k < insertCount; k++) { + added.push(` // rev-${versionIdx}.${k}: guard ${rng.pick(theme.identifiers)} invariant (mask=0x${rng.hex(2)})`); + } + lines.splice(insertAt, 0, ...added); + const edits = 4 + (rng.u32() % 5); + for (let e = 0; e < edits; e++) { + const pos = 70 + (rng.u32() % (lines.length - 90)); + lines[pos] = lines[pos] + ` /* rev_${versionIdx}_${e} */`; + } + return lines; +} + +function makeToolDefinitions(theme) { + const defs = []; + for (let i = 0; i < 42; i++) { + const name = `${theme.toolNames[i % theme.toolNames.length]}_v${Math.floor(i / theme.toolNames.length) + 1}`; + const idA = theme.identifiers[i % theme.identifiers.length]; + const idB = theme.identifiers[(i + 7) % theme.identifiers.length]; + defs.push({ + name, + description: `Execute ${name} against ${theme.project} workspace (${idA} -> ${idB}). Returns structured diagnostic records, byte offsets, checksums, and execution trace spans without mutating unrelated workspace segments.`, + input_schema: { + type: 'object', + additionalProperties: false, + required: ['targetPath', 'mode', 'budgetMs'], + properties: { + targetPath: { type: 'string', description: `Relative path under ${theme.cwd} for ${idA} inspection.` }, + mode: { type: 'string', enum: ['fast', 'strict', 'audit', 'replay'] }, + budgetMs: { type: 'integer', minimum: 50, maximum: 60000, default: 5000 }, + includeTrace: { type: 'boolean', default: true }, + maxLines: { type: 'integer', minimum: 1, maximum: 4000, default: 1200 }, + filters: { type: 'array', items: { type: 'string' }, description: `Filter tags for ${idB} collector.` }, + encoding: { type: 'string', enum: ['utf8', 'binary', 'jsonl'], default: 'utf8' }, + checksumAlg: { type: 'string', enum: ['sha256', 'crc32'], default: 'sha256' }, + }, + }, + }); + } + return defs; +} + +function buildManifest(meta, rawEntries) { + const manifestEntries = rawEntries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: crypto.createHash('sha256').update(e.content).digest('hex'), + })); + const manifest = { + formatVersion: 3, + minReaderVersion: meta.orca ? 2 : 1, + appVersion: meta.appVersion, + platform: meta.platform, + exportedAt: meta.exportedAt, + agentKind: meta.agentKind, + title: meta.title, + workspaceKind: 'project', + originalWorkingDir: meta.cwd, + sdkSessionIds: meta.sdkSessionIds, + activeSdkSessionId: meta.sdkSessionIds[meta.sdkSessionIds.length - 1] ?? null, + exportFidelity: 'full', + counts: { messages: meta.messageCount, media: meta.mediaCount }, + entries: manifestEntries, + transcripts: meta.transcripts, + ...(meta.orca ? { orca: meta.orca } : {}), + }; + return toUint8(JSON.stringify(manifest, null, 2) + '\n'); +} + +function generateBundleA(rng, theme, opts) { + const sessionId = rng.uuid(); + const sdkSessionId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const model = theme.models[0]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const turnCount = opts.bundleATurns ?? 1000; + const mediaCopies = opts.bundleAMediaCopies ?? 18; + const srcFiles = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 340)); + + // 1 unique 16 KiB PNG duplicated across repeated architecture diagram captures + const uniqA = makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450); + const uniqAB64 = Buffer.from(uniqA).toString('base64'); + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < mediaCopies; m++) { + const filename = `diag-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqA) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + const msgLines = []; + const transcriptLines = []; + const traceLines = []; + + let tsMs = theme.baseEpochMs; + let prevUuid = null; + let inputTokens = 8400; + let cacheReadTokens = 7200; + let cumulativeCost = 14200; + let heapKb = 96000; + let rssKb = 184000; + + for (let i = 0; i < turnCount; i++) { + const dt = 500 + (i % 7) * 180 + rng.int(10, 80); + tsMs += dt; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const requestId = `req_${theme.project.slice(0, 4)}_${String(Math.floor(i / 2)).padStart(5, '0')}`; + const seq = i + 1; + + const kind = i % 4; + let role, dbContent, claudeType, claudeMessage; + let toolUseId = null; + let toolUseResult; + + const deltaIn = 120 + (i % 13) * 35; + const outTok = kind === 1 || kind === 3 ? (110 + (i % 11) * 28) : 0; + const cacheCreate = i % 16 === 0 ? 640 : 0; + cacheReadTokens = Math.max(0, inputTokens - 160); + inputTokens += deltaIn; + const durationMs = 240 + (i % 9) * 140; + const ttftMs = 95 + (i % 5) * 35; + cumulativeCost += Math.round((deltaIn * 3 + outTok * 15) / 10); + + const spanTrace = [tsMs - durationMs, tsMs - durationMs + ttftMs, tsMs - Math.floor(durationMs / 3), tsMs]; + + if (i === 12) { + role = 'user'; + claudeType = 'user'; + const note = `Architecture diagram check: ${theme.zhNotes[0]}`; + dbContent = `${note}\n![diag](cindy-image://${sessionId}/diag-01.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniqAB64 } }, + ], + }; + } else if (kind === 0) { + role = 'user'; + claudeType = 'user'; + const text = `[Step ${seq}] ${theme.zhNotes[i % theme.zhNotes.length]}\nFile: ${theme.files[i % theme.files.length]}\nContext: ${theme.enNotes[(i * 3) % theme.enNotes.length]}`; + dbContent = text; + claudeMessage = { role: 'user', content: [{ type: 'text', text }] }; + } else if (kind === 1) { + role = 'assistant'; + claudeType = 'assistant'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq).padStart(5, '0')}`; + const toolName = theme.toolNames[i % theme.toolNames.length]; + const inputObj = { + path: `${theme.cwd}/${theme.files[i % theme.files.length]}`, + startLine: 1 + ((i * 17) % 140), + endLine: 120 + ((i * 17) % 140), + includeMetrics: true, + tag: `${theme.branch}#${seq}`, + }; + dbContent = JSON.stringify({ + type: 'tool_use', + id: toolUseId, + name: toolName, + input: inputObj, + thought: theme.enNotes[i % theme.enNotes.length], + }); + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [ + { type: 'thinking', thinking: theme.enNotes[i % theme.enNotes.length] }, + { type: 'tool_use', id: toolUseId, name: toolName, input: inputObj }, + ], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } else if (kind === 2) { + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq - 1).padStart(5, '0')}`; + const fileIdx = (i >> 2) % srcFiles.length; + const lines = srcFiles[fileIdx]; + let payloadText; + if (i % 16 === 2) { + const start = (i * 5) % 80; + payloadText = formatLineNumbered(lines.slice(start, start + 120), start + 1, lnWidth); + } else if (i % 16 === 6) { + const f = theme.files[fileIdx]; + const diffLines = [ + `diff --git a/${f} b/${f}`, + `--- a/${f}`, + `+++ b/${f}`, + `@@ -${20 + (i % 80)},14 +${20 + (i % 80)},16 @@`, + ]; + for (let k = 0; k < 20; k++) { + diffLines.push((k === 5 ? '-' : k === 6 ? '+' : ' ') + lines[(20 + (i % 80) + k) % lines.length]); + } + payloadText = diffLines.join('\n'); + } else { + const logLines = [`$ test-runner --filter ${theme.identifiers[i % theme.identifiers.length]} --seed ${seq}`]; + for (let k = 0; k < 10; k++) { + logLines.push( + `[${new Date(tsMs - 200 + k * 10).toISOString()}] PASS case_${k} (${theme.identifiers[(i + k) % theme.identifiers.length]}) elapsed=${15 + (k % 5) * 4}ms rss=${rssKb + k * 16}KB`, + ); + } + payloadText = logLines.join('\n'); + } + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + is_error: false, + content: payloadText, + }); + toolUseResult = { + status: 'ok', + bytes: Buffer.byteLength(payloadText, 'utf8'), + durationMs, + stdout: payloadText, + }; + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: payloadText }], + }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const text = `${theme.zhNotes[(i + 2) % theme.zhNotes.length]}\n\nSummary (${theme.identifiers[i % theme.identifiers.length]}):\n- ${theme.enNotes[(i + 1) % theme.enNotes.length]}\n- Verified checkpoint #${seq} (${inputTokens} in / ${outTok} out).`; + dbContent = text; + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } + + const agentMetaObj = { + uuid, + parentUuid: prevUuid, + sdkSessionId, + model, + providerId, + requestId, + turnUsageDetails: { + inputTokens, + cacheReadTokens, + cacheCreationTokens: cacheCreate, + outputTokens: outTok, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + }, + }; + msgLines.push(JSON.stringify({ + id: `msg-${String(seq).padStart(6, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify(agentMetaObj), + })); + transcriptLines.push(JSON.stringify({ + parentUuid: prevUuid, + isSidechain: false, + userType: 'external', + cwd: theme.cwd, + sessionId: sdkSessionId, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId, + providerId, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + message: claudeMessage, + ...(toolUseResult ? { toolUseResult } : {}), + })); + prevUuid = uuid; + + // Structured telemetry spans placed between messages.jsonl and transcripts/ (>2 MiB separation) + for (let s = 0; s < 5; s++) { + const spanTs = tsMs - durationMs + s * Math.max(15, Math.floor(durationMs / 5)); + heapKb += 4 + (s === 4 ? -12 : 3); + rssKb += 6 + (s === 4 ? -16 : 4); + traceLines.push(JSON.stringify({ + seq: i * 5 + s + 1, + sessionId, + turnSeq: seq, + requestId, + phase: ['dispatch', 'prompt_cache', 'tool_exec', 'post_hook', 'commit'][s], + timestamp: new Date(spanTs).toISOString(), + tsMs: spanTs, + elapsedMs: 18 + s * 24 + (i % 7) * 5, + inputTokens: inputTokens + s * 4, + cacheReadTokens, + outputTokens: s === 4 ? outTok : Math.floor(outTok * (s / 4)), + heapUsedKb: heapKb, + rssKb, + cumulativeCostMicroUsd: cumulativeCost, + status: 'ok', + model, + providerId, + })); + } + } + + const transcriptPath = `transcripts/claude/${sdkSessionId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: single-agent optimization audit`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId, + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(msgLines.join('\n') + '\n') }, + ...mediaEntries, + { path: 'telemetry/turn-spans.jsonl', content: toUint8(traceLines.join('\n') + '\n') }, + { path: transcriptPath, content: toUint8(transcriptLines.join('\n') + '\n') }, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 5000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: single-agent optimization audit`, + cwd: theme.cwd, + sdkSessionIds: [sdkSessionId], + messageCount: turnCount, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId, path: transcriptPath }], + }, bodyEntries); + + return { + name: 'single-agent-session', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleB(rng, theme, opts) { + const sessionId = rng.uuid(); + const forkSids = [rng.uuid(), rng.uuid(), rng.uuid()]; + const nodeBuf = rng.bytes(5); + const model = theme.models[1]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const sharedTurns = opts.bundleBSharedTurns ?? 152; + const tailTurns = opts.bundleBTailTurns ?? 38; + + // 12 binary PNGs built from 3 unique incompressible blobs (64 KiB unique total, 356 KiB raw) + const uniquePngs = [ + makeSyntheticPng(rng, 38 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniquePngB64 = uniquePngs.map((b) => Buffer.from(b).toString('base64')); + const imgAssign = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2]; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < 12; m++) { + const filename = `img-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniquePngs[imgAssign[m]]) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + let fileVersions = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 640)); + let tsMs = theme.baseEpochMs + 3600_000; + let prevUuid = null; + let inputTokens = 12000; + let cumulativeCost = 22000; + + const sharedPrefixTurns = []; + const dbMsgLines = []; + let snapshotIdx = 0; + + for (let t = 0; t < sharedTurns; t++) { + tsMs += 600 + (t % 7) * 210 + rng.int(5, 45); + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, t + 1, nodeBuf); + const seq = t + 1; + const reqId = `req_fork_${String(Math.floor(t / 2)).padStart(4, '0')}`; + const durationMs = 260 + (t % 9) * 180; + const outTok = t % 2 === 1 ? (140 + (t % 7) * 40) : 0; + const cacheRead = Math.max(0, inputTokens - 180); + inputTokens += 150 + (t % 11) * 45; + cumulativeCost += Math.round((inputTokens * 2 + outTok * 15) / 100); + + let role, claudeType, claudeMessage, dbContent; + let toolUseId = null; + + if (t === 5 || t === 55 || t === 105) { + const imgIdx = t === 5 ? 0 : t === 55 ? 1 : 2; + role = 'user'; + claudeType = 'user'; + const note = `Screenshot #${imgIdx + 1}: ${theme.zhNotes[imgIdx]} (${theme.enNotes[imgIdx]})`; + const imgNum = imgIdx === 0 ? 1 : imgIdx === 1 ? 9 : 11; + dbContent = `${note}\n![shot](cindy-image://${sessionId}/img-${String(imgNum).padStart(2, '0')}.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniquePngB64[imgIdx] } }, + ], + }; + } else if (t > 0 && t % 7 === 0 && snapshotIdx < 20) { + const fIdx = snapshotIdx % 4; + const rev = Math.floor(snapshotIdx / 4); + if (rev > 0) fileVersions[fIdx] = mutateSourceLines(rng, theme, fileVersions[fIdx], rev); + snapshotIdx++; + const numbered = formatLineNumbered(fileVersions[fIdx], 1, lnWidth); + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_snap_${String(snapshotIdx).padStart(3, '0')}`; + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + file: theme.files[fIdx], + revision: rev, + content: numbered, + }); + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: numbered }], + }; + } else if (t % 2 === 0) { + role = 'user'; + claudeType = 'user'; + const logLine = `[turn ${seq}] ${theme.zhNotes[t % theme.zhNotes.length]} | ${theme.enNotes[(t * 5) % theme.enNotes.length]} | metrics: latency=${durationMs}ms`; + dbContent = logLine; + claudeMessage = { role: 'user', content: [{ type: 'text', text: logLine }] }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const reply = `Analysis #${seq} (${theme.identifiers[t % theme.identifiers.length]}): ${theme.enNotes[(t + 2) % theme.enNotes.length]}\n${theme.zhNotes[(t + 1) % theme.zhNotes.length]}`; + dbContent = reply; + claudeMessage = { + id: `msg_f_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text: reply }], + usage: { input_tokens: inputTokens, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + + sharedPrefixTurns.push({ + parentUuid: prevUuid, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId: reqId, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + message: claudeMessage, + }); + dbMsgLines.push(JSON.stringify({ + id: `bmsg-${String(seq).padStart(5, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: prevUuid, + sdkSessionId: forkSids[2], + model, + providerId, + requestId: reqId, + inputTokens, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + }), + })); + prevUuid = uuid; + } + + const forkEntries = []; + const transcriptRefs = []; + for (let f = 0; f < 3; f++) { + const fSid = forkSids[f]; + const lines = sharedPrefixTurns.map((turn) => JSON.stringify({ ...turn, sessionId: fSid, forkBranch: `fork-${f}` })); + let fPrev = prevUuid; + let fTs = tsMs + f * 60_000; + let fIn = inputTokens; + let fCost = cumulativeCost; + for (let k = 0; k < tailTurns; k++) { + fTs += 500 + (k % 5) * 190 + rng.int(5, 35); + const iso = new Date(fTs).toISOString(); + const uuid = rng.uuidv7(fTs, 200 + f * 60 + k, nodeBuf); + const outTok = k % 2 === 1 ? (110 + (k % 7) * 35) : 0; + const cacheRead = Math.max(0, fIn - 140); + fIn += 130 + (k % 9) * 40; + fCost += Math.round((fIn * 2 + outTok * 15) / 100); + let msg; + if (f === 2 && k < 4) { + fileVersions[k] = mutateSourceLines(rng, theme, fileVersions[k], 5 + f); + const numbered = formatLineNumbered(fileVersions[k], 1, lnWidth); + msg = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: `toolu_tail_${f}_${k}`, is_error: false, content: numbered }], + }; + } else { + const text = `[fork-${f} tail ${k + 1}] ${theme.enNotes[(k + f * 2) % theme.enNotes.length]} | ${theme.zhNotes[(k + f) % theme.zhNotes.length]}`; + msg = k % 2 === 0 + ? { role: 'user', content: [{ type: 'text', text }] } + : { + id: `msg_f${f}_t${k}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { input_tokens: fIn, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + lines.push(JSON.stringify({ + parentUuid: fPrev, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: `${theme.branch}-f${f}`, + type: k % 2 === 0 ? 'user' : 'assistant', + uuid, + timestamp: iso, + requestId: `req_f${f}_${String(k).padStart(3, '0')}`, + durationMs: 220 + (k % 8) * 140, + cumulativeCostMicroUsd: fCost, + sessionId: fSid, + forkBranch: `fork-${f}`, + message: msg, + })); + fPrev = uuid; + } + const tp = `transcripts/claude/fork-${f}.jsonl`; + forkEntries.push({ path: tp, content: toUint8(lines.join('\n') + '\n') }); + transcriptRefs.push({ sdkSessionId: fSid, path: tp }); + } + + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: fork chain & evolving snapshots`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId: forkSids[2], + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs + 3600_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(dbMsgLines.join('\n') + '\n') }, + ...mediaEntries, + ...forkEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 90_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: fork chain & evolving snapshots`, + cwd: theme.cwd, + sdkSessionIds: forkSids, + messageCount: dbMsgLines.length, + mediaCount: mediaEntries.length, + transcripts: transcriptRefs, + }, bodyEntries); + + return { + name: 'fork-chain-and-media', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleC(rng, theme, opts) { + const leadSessionId = rng.uuid(); + const leadSdkId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const lnWidth = theme.lineNumWidth ?? 5; + const workerTurns = opts.bundleCWorkerTurns ?? 110; + const workerMediaEach = opts.bundleCWorkerShotsEach ?? 14; + const toolDefs = makeToolDefinitions(theme); + const systemPromptBase = [ + `You are an Orca autonomous engineering worker operating inside ${theme.cwd} (${theme.project}).`, + ...theme.enNotes, + ...theme.zhNotes, + 'Strict invariants: preserve exact wire compatibility, maintain deterministic ordering, never drop audit checksums, verify every edge case before reporting completion.', + ].join('\n'); + const sharedRepoFiles = [0, 1, 4, 5].map((i) => generateSourceFile(rng, theme, i, 420)); + + // 2 unique 16 KiB PNGs (32 KiB unique floor) duplicated across lead & 4 workers' verification screenshots + const uniqShots = [ + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniqShotsB64 = uniqShots.map((b) => Buffer.from(b).toString('base64')); + const totalShots = 4 + 4 * workerMediaEach; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < totalShots; m++) { + const filename = m < 4 + ? `lead-shot-${String(m + 1).padStart(2, '0')}.png` + : `worker-${Math.floor((m - 4) / workerMediaEach)}-shot-${String(((m - 4) % workerMediaEach) + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqShots[m % 2]) }); + mediaMap.push({ + url: `cindy-image://${leadSessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: leadSessionId, + filename, + }); + } + + let tsMs = theme.baseEpochMs + 7200_000; + const leadMsgs = []; + const leadTranscript = []; + let leadPrev = null; + for (let i = 0; i < 44; i++) { + tsMs += 800 + (i % 5) * 140; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const text = `[Lead #${i + 1}] Coordinate worker ${i % 4}: ${theme.zhNotes[i % theme.zhNotes.length]} (${theme.enNotes[i % theme.enNotes.length]})`; + leadMsgs.push(JSON.stringify({ + id: `lead-${String(i + 1).padStart(4, '0')}`, + sessionId: leadSessionId, + seq: i + 1, + role: i % 2 === 0 ? 'user' : 'assistant', + createdAt: iso, + createdAtMs: tsMs, + toolUseId: null, + content: text, + agentMeta: JSON.stringify({ uuid, parentUuid: leadPrev, sdkSessionId: leadSdkId, model: theme.models[0] }), + })); + leadTranscript.push(JSON.stringify({ + parentUuid: leadPrev, + sessionId: leadSdkId, + uuid, + timestamp: iso, + type: i % 2 === 0 ? 'user' : 'assistant', + message: { role: i % 2 === 0 ? 'user' : 'assistant', content: [{ type: 'text', text }] }, + })); + leadPrev = uuid; + } + + const workerEntries = []; + const workerManifests = []; + const roles = theme.workerRoles ?? ['implementer', 'verifier', 'profiler', 'auditor']; + + for (let w = 0; w < 4; w++) { + const wSessionId = rng.uuid(); + const wThreadId = rng.uuid(); + const wNode = rng.bytes(5); + const wDir = `${theme.cwd}/.worktrees/worker-${w}`; + const wMsgs = []; + const wRollout = []; + let wTs = theme.baseEpochMs + 7210_000 + w * 2500; + let wIn = 18000; + let wCost = 9500; + let wPrev = null; + + const workerTools = toolDefs.map((d) => ({ + ...d, + description: `[worker-${w}/${roles[w]}] ${d.description}`, + })); + wRollout.push(JSON.stringify({ + timestamp: new Date(wTs).toISOString(), + type: 'session_meta', + payload: { + id: wThreadId, + workerIndex: w, + workerRole: roles[w], + cwd: wDir, + model: theme.codexModel, + providerId: theme.providers[1], + systemPrompt: `${systemPromptBase}\nAssigned Role: ${roles[w]} (#${w})`, + tools: workerTools, + }, + })); + + for (let t = 0; t < workerTurns; t++) { + wTs += 500 + (t % 7) * 160 + rng.int(5, 30); + const iso = new Date(wTs).toISOString(); + const uuid = rng.uuidv7(wTs, t + 1, wNode); + const seq = t + 1; + const cacheRead = Math.max(0, wIn - 180); + const outTok = t % 2 === 1 ? (120 + (t % 9) * 32) : 0; + const dur = 180 + (t % 8) * 160; + wIn += 140 + (t % 11) * 45; + wCost += Math.round((wIn + outTok * 12) / 80); + + let role, dbContent, rolloutItem; + let toolUseId = null; + + if (t === 4 || t === 56) { + const sIdx = (w + (t === 4 ? 0 : 1)) % 2; + role = 'user'; + dbContent = JSON.stringify({ + type: 'screenshot_check', + worker: w, + image: `cindy-image://${leadSessionId}/worker-${w}-shot-0${sIdx + 1}.png`, + }); + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role: 'user', + content: [ + { type: 'input_text', text: `Verify UI screenshot #${sIdx + 1} for worker-${w}` }, + { type: 'input_image', image_url: `data:image/png;base64,${uniqShotsB64[sIdx]}` }, + ], + }, + }; + } else if (t % 20 === 6) { + const fIdx = Math.floor(t / 20) % sharedRepoFiles.length; + const lines = w === 0 ? sharedRepoFiles[fIdx] : mutateSourceLines(rng, theme, sharedRepoFiles[fIdx], w * 10 + t); + const numbered = formatLineNumbered(lines, 1, lnWidth); + role = 'tool'; + toolUseId = `call_w${w}_${String(seq).padStart(4, '0')}`; + dbContent = JSON.stringify({ + type: 'function_call_output', + call_id: toolUseId, + file: theme.files[fIdx], + output: numbered, + }); + rolloutItem = { + type: 'response_item', + payload: { type: 'function_call_output', call_id: toolUseId, output: numbered }, + }; + } else if (t % 10 === 0) { + role = 'assistant'; + const summary = `Worker ${w} (${roles[w]}) turn ${seq}: ${theme.enNotes[(t + w) % theme.enNotes.length]}`; + dbContent = JSON.stringify({ type: 'tool_context', worker: w, summary, toolCount: workerTools.length }); + rolloutItem = { + type: 'turn_context', + payload: { + turn: seq, + cwd: wDir, + model: theme.codexModel, + summary, + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + ...(t === 0 || t === 50 ? { tools: workerTools } : {}), + }, + }; + } else { + role = t % 2 === 0 ? 'user' : 'assistant'; + const text = `[worker-${w}/${roles[w]} #${seq}] ${theme.zhNotes[(t + w) % theme.zhNotes.length]}\n${theme.enNotes[(t * 3 + w) % theme.enNotes.length]} (tokens=${wIn}, dur=${dur}ms)`; + dbContent = text; + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role, + content: [{ type: role === 'user' ? 'input_text' : 'output_text', text }], + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + }, + }; + } + + wMsgs.push(JSON.stringify({ + id: `w${w}-msg-${String(seq).padStart(5, '0')}`, + sessionId: wSessionId, + seq, + role, + createdAt: iso, + createdAtMs: wTs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: wPrev, + sdkSessionId: wThreadId, + model: theme.codexModel, + providerId: theme.providers[1], + workerIndex: w, + turnUsageDetails: { + inputTokens: wIn, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs: dur, + cumulativeCostMicroUsd: wCost, + }, + }), + })); + wRollout.push(JSON.stringify({ + timestamp: iso, + tsMs: wTs, + uuid, + parentUuid: wPrev, + sessionId: wThreadId, + workerIndex: w, + ...rolloutItem, + })); + wPrev = uuid; + } + + const prefix = `orca/workers/${w}`; + const rolloutPath = `${prefix}/transcripts/codex/rollout.jsonl`; + workerEntries.push( + { + path: `${prefix}/session.json`, + content: toUint8(JSON.stringify({ + id: wSessionId, + title: `Worker ${w} (${roles[w]})`, + workingDir: wDir, + workspaceKind: 'project', + model: theme.codexModel, + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[1], + status: 'done', + sdkSessionId: wThreadId, + totalTokenUsage: wIn, + totalCostUsd: Number((wCost / 1e6).toFixed(6)), + agentKind: 'codex', + orcaRole: 'worker', + createdAt: theme.baseEpochMs + 7210_000, + updatedAt: wTs, + }, null, 2) + '\n'), + }, + { path: `${prefix}/messages.jsonl`, content: toUint8(wMsgs.join('\n') + '\n') }, + { path: rolloutPath, content: toUint8(wRollout.join('\n') + '\n') }, + ); + workerManifests.push({ + index: w, + agentKind: 'codex', + providerId: theme.providers[1], + title: `Worker ${w} (${roles[w]})`, + role: roles[w], + label: `worker-${w}`, + status: 'done', + focused: w === 0, + sdkSessionIds: [wThreadId], + activeSdkSessionId: wThreadId, + counts: { messages: wMsgs.length }, + transcripts: [{ sdkSessionId: wThreadId, path: rolloutPath }], + }); + } + + const leadTranscriptPath = `transcripts/claude/${leadSdkId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: leadSessionId, + title: `${theme.project}: Orca 4-worker team session`, + workingDir: theme.cwd, + workspaceKind: 'project', + model: theme.models[0], + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[0], + status: 'idle', + sdkSessionId: leadSdkId, + agentKind: 'cc', + orcaRole: 'lead', + createdAt: theme.baseEpochMs + 7200_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(leadMsgs.join('\n') + '\n') }, + { path: leadTranscriptPath, content: toUint8(leadTranscript.join('\n') + '\n') }, + ...mediaEntries, + ...workerEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 120_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: Orca 4-worker team session`, + cwd: theme.cwd, + sdkSessionIds: [leadSdkId], + messageCount: leadMsgs.length, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId: leadSdkId, path: leadTranscriptPath }], + orca: { teamStatus: 'completed', workers: workerManifests }, + }, bodyEntries); + + return { + name: 'orca-team-archive', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +export function generateCorpusSuite(options = {}) { + const seed = options.seed ?? PUBLIC_SEED; + const theme = options.theme ?? PUBLIC_THEME; + const rng = createDeterministicRng(seed); + return { + suiteName: options.suiteName ?? 'public', + bundles: [ + generateBundleA(rng, theme, options), + generateBundleB(rng, theme, options), + generateBundleC(rng, theme, options), + ], + }; +} + +export function generatePublicSuite() { + return generateCorpusSuite({ seed: PUBLIC_SEED, theme: PUBLIC_THEME, suiteName: 'public' }); +} + +export function measureBundleRawBytes(bundle) { + let total = 0; + for (const e of bundle.entries) total += e.content.byteLength; + return total; +} diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/package.json b/questions/opt-cshare-compression/v1/controls/incomplete/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/src/container.mjs b/questions/opt-cshare-compression/v1/controls/incomplete/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/src/cshare-codec.mjs b/questions/opt-cshare-compression/v1/controls/incomplete/src/cshare-codec.mjs new file mode 100644 index 0000000..0449c33 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/src/cshare-codec.mjs @@ -0,0 +1,127 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +const MEDIA_EXT_RE = /\.(png|jpe?g|webp|gif|mp4|webm|pdf|zip)$/i; + +/** + * Incomplete optimization control: + * Adds media content-hash deduplication and store-only handling for incompressible + * media blobs, but still compresses every non-media entry independently with + * per-file raw DEFLATE (level 6) — missing solid cross-file compression and + * domain-aware structural transforms. + */ +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const headerVersion = bundle.headerVersion ?? XDTSHARE_HEADER_VERSION; + const header = encodePlainHeader(headerVersion); + + const blobs = []; + const mediaHashToIdx = new Map(); + const table = new Array(bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + const entry = bundle.entries[i]; + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const rawBuf = toBufferView(entry.content); + if (MEDIA_EXT_RE.test(entry.path)) { + const digest = crypto.createHash('sha256').update(rawBuf).digest('hex'); + let blobIdx = mediaHashToIdx.get(digest); + if (blobIdx === undefined) { + blobIdx = blobs.length; + mediaHashToIdx.set(digest, blobIdx); + blobs.push({ stored: true, rawLen: rawBuf.length, data: Buffer.from(rawBuf) }); + } + table[i] = [entry.path, blobIdx]; + } else { + const blobIdx = blobs.length; + const compressed = zlib.deflateRawSync(rawBuf, { level: 6 }); + blobs.push({ stored: false, rawLen: rawBuf.length, data: compressed }); + table[i] = [entry.path, blobIdx]; + } + } + + const tocComp = zlib.deflateRawSync(Buffer.from(JSON.stringify(table), 'utf8'), { level: 6 }); + const sectionHdr = Buffer.alloc(8); + sectionHdr.writeUInt32LE(tocComp.length, 0); + sectionHdr.writeUInt32LE(blobs.length, 4); + + const parts = [header, sectionHdr, tocComp]; + for (const blob of blobs) { + const bh = Buffer.alloc(9); + bh.writeUInt8(blob.stored ? 1 : 0, 0); + bh.writeUInt32LE(blob.rawLen, 1); + bh.writeUInt32LE(blob.data.length, 5); + parts.push(bh, blob.data); + } + + const out = Buffer.concat(parts); + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + if (payload.length < 8) { + throw new Error('Truncated archive payload'); + } + const tocCompLen = payload.readUInt32LE(0); + const blobCount = payload.readUInt32LE(4); + let offset = 8; + + if (offset + tocCompLen > payload.length) { + throw new Error('Truncated TOC section'); + } + const table = JSON.parse(zlib.inflateRawSync(payload.subarray(offset, offset + tocCompLen)).toString('utf8')); + offset += tocCompLen; + + const decodedBlobs = new Array(blobCount); + for (let i = 0; i < blobCount; i++) { + if (offset + 9 > payload.length) { + throw new Error(`Truncated blob header at index ${i}`); + } + const stored = payload.readUInt8(offset) === 1; + const rawLen = payload.readUInt32LE(offset + 1); + const dataLen = payload.readUInt32LE(offset + 5); + offset += 9; + if (offset + dataLen > payload.length) { + throw new Error(`Truncated blob body at index ${i}`); + } + const slice = payload.subarray(offset, offset + dataLen); + offset += dataLen; + + const raw = stored ? Buffer.from(slice) : zlib.inflateRawSync(slice); + if (raw.length !== rawLen) { + throw new Error(`Decoded blob length mismatch at index ${i}`); + } + decodedBlobs[i] = raw; + } + + if (offset !== payload.length) { + throw new Error(`Unexpected trailing bytes: ${payload.length - offset}`); + } + + const entries = table.map(([entryPath, blobIdx]) => { + const blob = decodedBlobs[blobIdx]; + if (!blob) throw new Error(`Invalid blob index ${blobIdx} for ${entryPath}`); + const copy = Buffer.from(blob); + return { + path: entryPath, + content: new Uint8Array(copy.buffer, copy.byteOffset, copy.byteLength), + }; + }); + + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v1/controls/incomplete/tests/smoke.test.mjs b/questions/opt-cshare-compression/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..4beed65 --- /dev/null +++ b/questions/opt-cshare-compression/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { generatePublicSuite } from '../lib/corpus-generator.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = generatePublicSuite(); + assert.equal(suite.bundles.length, 3); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-cshare-compression/v1/question.json b/questions/opt-cshare-compression/v1/question.json new file mode 100644 index 0000000..3348bc8 --- /dev/null +++ b/questions/opt-cshare-compression/v1/question.json @@ -0,0 +1,40 @@ +{ + "id": "opt-cshare-compression", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": ".cshare 会话归档极限无损压缩优化", + "status": "calibrated", + "changeNote": "Eval Bank v2 high-ceiling deterministic compression question extracted from makecindy/cindy session-share export pipeline (b61c43049a9c).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "b61c43049a9c2977e2bc64f2a4a12d6d344924bd", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "compression_ratio", + "weight": "1", + "mode": "metric", + "gate": [ + "gate_exact_lossless", + "gate_stateless_isolated_decode", + "gate_header_and_limits" + ], + "metric": { + "id": "archive_bytes", + "label": "Held-out .cshare total size", + "unit": "B", + "direction": "lower", + "baseline": 3500000, + "target": 160000, + "scale": "log" + } + } + ] +} diff --git a/questions/opt-cshare-compression/v1/reference/CONTRACT.md b/questions/opt-cshare-compression/v1/reference/CONTRACT.md new file mode 100644 index 0000000..b1b35f7 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/CONTRACT.md @@ -0,0 +1,54 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Performance limits (held-out corpus total across 3 bundles)**: + - Total `encodeArchive` time: `<= 12,000 ms` (12 seconds) + - Total `decodeArchive` time: `<= 5,000 ms` (5 seconds) diff --git a/questions/opt-cshare-compression/v1/reference/ENVIRONMENT.md b/questions/opt-cshare-compression/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..1fee79d --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. For Node.js 18+ portability, `zlib.deflateRawSync`, `zlib.gzipSync`, and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` is present without checking availability first. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism & held-out evaluation: + - Public benchmark (`npm run bench`) runs on a deterministic 3-bundle public `.cshare` corpus generated by `lib/corpus-generator.mjs`. + - Official grading evaluates bit-exact lossless correctness, stateless child-process decoding, header/timing limits (`encode <= 12s`, `decode <= 5s`), and total `archive_bytes` on an **unseen held-out 3-bundle corpus** with different seeds, project domain, file paths, code identifiers, vocabulary, UUID spaces, timestamps, and media. +- Public checks: + - `npm test` — lossless round-trip, header validation, and adversarial edge-case smoke tests + - `npm run bench` — deterministic public corpus benchmark reporting raw size, `archive_bytes`, compression ratio, and encode/decode timings diff --git a/questions/opt-cshare-compression/v1/reference/TASK.md b/questions/opt-cshare-compression/v1/reference/TASK.md new file mode 100644 index 0000000..15239d3 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive lossless compression codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). + +## Observed Production Symptoms + +Cindy exports AI coding sessions—including single-agent sessions, Claude fork chains, media attachments, and Orca multi-worker team archives—into `.cshare` files using per-entry raw DEFLATE (level 6) with no cross-file solid compression, no content deduplication, and no structural preprocessing. As a result, realistic 10–14 MiB session exports still occupy multiple megabytes when shared or migrated across devices, despite containing massive structural and semantic redundancy across: +- Pretty-printed JSON metadata (`manifest.json`, `session.json`, `media-map.json`) +- Database `messages.jsonl` and native vendor transcripts (`transcripts/claude/*.jsonl`, `transcripts/codex/rollout.jsonl`) +- Structured JSONL telemetry, timestamps, IDs, and numeric usage counters +- Fork chains (`fork-0.jsonl`, `fork-1.jsonl`, `fork-2.jsonl`) and Orca worker subdirectories (`orca/workers/0..3/`) +- Evolving file snapshots and duplicated binary media attachments (`media/*.png`) + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header (`"XDTSHARE"` ASCII 8B + `headerVersion=1` u8 + `cipher=0` u8 + 2 zero reserved bytes). Everything from byte 12 onward is your open-ended lossless container and compression format. +- Guarantee **100% bit-exact lossless round-trip** (`headerVersion`, entry count, exact entry order, exact UTF-8 paths, and byte-exact contents) across all valid `.cshare` bundles and arbitrary binary/edge-case payloads. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must reconstruct every entry in a fresh isolated Node.js process given only the encoded archive bytes. +- **Open-ended optimization goal**: Minimize total encoded `archive_bytes` on the **unseen held-out evaluation suite** (which uses different seeds, project domains, file names, code identifiers, vocabulary, UUID spaces, timestamps, and media—hardcoded dictionaries will not generalize), while staying within Node.js built-ins (zero external npm packages) and the held-out runtime limits (`encode <= 12s`, `decode <= 5s`). +- Run `npm test` and `npm run bench` to verify correctness and compare public corpus sizes before and after your changes. +- Record your analysis, format design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料生成器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v1/reference/bench/workload.mjs b/questions/opt-cshare-compression/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..4304604 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { generatePublicSuite, measureBundleRawBytes } from '../lib/corpus-generator.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = generatePublicSuite(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v1/reference/lib/corpus-generator.mjs b/questions/opt-cshare-compression/v1/reference/lib/corpus-generator.mjs new file mode 100644 index 0000000..db0f35a --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/lib/corpus-generator.mjs @@ -0,0 +1,1269 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic parameterized `.cshare` archive corpus generator. + * Pure Node.js >= 18 ESM, zero external dependencies, zero wall-clock or random nondeterminism. + */ + +function hashSeed(str) { + const h = crypto.createHash('sha256').update(String(str)).digest(); + return [h.readUInt32LE(0), h.readUInt32LE(4), h.readUInt32LE(8), h.readUInt32LE(12)]; +} + +export function createDeterministicRng(seed) { + let [a, b, c, d] = hashSeed(seed); + function nextU32() { + const t = b << 9; + let r = b * 5; + r = ((r << 7) | (r >>> 25)) * 9; + c ^= a; + d ^= b; + b ^= c; + a ^= d; + c ^= t; + d = (d << 11) | (d >>> 21); + return r >>> 0; + } + return { + u32: nextU32, + int(min, max) { + return min + (nextU32() % (max - min + 1)); + }, + pick(arr) { + return arr[nextU32() % arr.length]; + }, + bytes(len) { + const out = Buffer.allocUnsafe(len); + let i = 0; + while (i + 4 <= len) { + out.writeUInt32LE(nextU32(), i); + i += 4; + } + while (i < len) out[i++] = nextU32() & 0xff; + return out; + }, + uuid() { + const b16 = this.bytes(16); + b16[6] = (b16[6] & 0x0f) | 0x40; + b16[8] = (b16[8] & 0x3f) | 0x80; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + uuidv7(tsMs, seq, nodeBuf) { + const b16 = Buffer.alloc(16); + b16.writeUInt32BE(Math.floor(tsMs / 0x10000) >>> 0, 0); + b16.writeUInt16BE(tsMs & 0xffff, 4); + b16[6] = 0x70 | ((seq >>> 8) & 0x0f); + b16[7] = seq & 0xff; + b16[8] = 0x80 | (nodeBuf[0] & 0x3f); + b16[9] = nodeBuf[1]; + b16[10] = nodeBuf[2]; + b16[11] = nodeBuf[3]; + b16[12] = nodeBuf[4]; + const rnd = nextU32(); + b16[13] = (rnd >>> 16) & 0xff; + b16[14] = (rnd >>> 8) & 0xff; + b16[15] = rnd & 0xff; + const h = b16.toString('hex'); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; + }, + hex(nBytes) { + return this.bytes(nBytes).toString('hex'); + }, + }; +} + +// ---------- Valid PNG framing over deterministic incompressible payload ---------- +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function pngChunk(type, data) { + const typeBuf = Buffer.from(type, 'ascii'); + const lenBuf = Buffer.alloc(4); + lenBuf.writeUInt32BE(data.length, 0); + const crcBuf = Buffer.alloc(4); + crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0); + return Buffer.concat([lenBuf, typeBuf, data, crcBuf]); +} + +export function makeSyntheticPng(rng, payloadBytes, width = 800, height = 450) { + const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // RGBA + const raw = Buffer.concat([ + sig, + pngChunk('IHDR', ihdr), + pngChunk('IDAT', rng.bytes(payloadBytes)), + pngChunk('IEND', Buffer.alloc(0)), + ]); + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); +} + +// ---------- Default public theme ---------- +export const PUBLIC_SEED = 'cshare-public-suite-v1'; + +export const PUBLIC_THEME = { + project: 'nebula-sync', + cwd: '/Users/dev/workspace/nebula-sync', + branch: 'feat/incremental-snapshot-pipeline', + appVersion: '2.14.3', + platform: 'darwin', + baseEpochMs: Date.UTC(2026, 3, 12, 9, 15, 0), + lineNumWidth: 5, + pngWidth: 800, + pngHeight: 450, + models: ['claude-sonnet-4-6', 'claude-opus-4-6'], + codexModel: 'gpt-5.3-codex', + providers: ['anthropic-direct', 'openai-codex'], + workerRoles: ['implementer', 'verifier', 'profiler', 'auditor'], + files: [ + 'src/sync/snapshotScheduler.ts', + 'src/sync/deltaJournal.ts', + 'src/storage/walCompactor.ts', + 'src/network/chunkMuxer.ts', + 'src/protocol/frameValidator.ts', + 'src/metrics/backpressureProbe.ts', + ], + identifiers: [ + 'SnapshotScheduler', 'DeltaJournal', 'WalCompactor', 'ChunkMuxer', + 'FrameValidator', 'BackpressureProbe', 'EpochCursor', 'SegmentRing', + 'LeaseToken', 'CheckpointBarrier', 'FlushWindow', 'ReplayIndex', + 'MerkleBucket', 'PeerTransport', 'ThrottleGate', 'DigestCache', + ], + zhNotes: [ + '检查增量快照写入路径是否存在重复刷盘或锁竞争问题。', + '已完成核心调度器的边界修复,正在补齐回归测试并核对延迟分位数。', + '发现 WAL 压缩窗口在高并发下会触发多余的索引重建,已调整阈值。', + '对比了新旧分片多路复用逻辑,确认在断连重传时不再丢弃尾帧。', + '建议将校验和计算下沉到批量提交阶段,减少热路径上的内存拷贝。', + '已核验全部单元测试与冒烟基准,吞吐和内存峰值符合预期。', + ], + enNotes: [ + 'Auditing the incremental snapshot pipeline for redundant disk flushes and lock contention.', + 'Applied boundary guard to the scheduler queue and verified p99 latency under burst load.', + 'Detected redundant index rebuilds during WAL compaction under overlapping worker writes.', + 'Verified chunk multiplexer handles reconnect retries without dropping trailing frames.', + 'Moved digest verification into the batch commit stage to avoid extra buffer copies.', + 'All unit tests and deterministic regression checks passed with zero integrity warnings.', + ], + toolNames: [ + 'read_file', 'edit_file', 'run_command', 'grep_search', + 'list_dir', 'apply_patch', 'inspect_metrics', 'verify_checksum', + ], +}; + +function toUint8(str) { + const buf = Buffer.from(str, 'utf8'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); +} + +function generateSourceFile(rng, theme, fileIndex, lineCount) { + const filePath = theme.files[fileIndex % theme.files.length]; + const isRust = filePath.endsWith('.rs'); + const lines = []; + const primary = theme.identifiers[fileIndex % theme.identifiers.length]; + const secondary = theme.identifiers[(fileIndex + 5) % theme.identifiers.length]; + lines.push(isRust ? `//! Module ${primary} (${filePath})` : `/** Module ${primary} (${filePath}) */`); + lines.push( + isRust + ? `use crate::common::{${secondary}, MetricsSink, StateDigest};` + : `import { ${secondary}, MetricsSink, StateDigest } from './common.js';`, + ); + lines.push(''); + + const verbs = ['validate', 'reconcile', 'compact', 'dispatch', 'serialize', 'verify', 'hydrate', 'drain', 'snapshot', 'rotate', 'merge', 'evict']; + const nouns = ['header', 'segment', 'window', 'cursor', 'journal', 'envelope', 'bucket', 'frame', 'quorum', 'batch', 'receipt', 'checkpoint']; + + let fnIdx = 0; + while (lines.length < lineCount) { + const idA = theme.identifiers[(fileIndex * 3 + fnIdx) % theme.identifiers.length]; + const idB = theme.identifiers[(fileIndex + fnIdx * 5 + 2) % theme.identifiers.length]; + const verb = verbs[(fnIdx + fileIndex) % verbs.length]; + const noun = nouns[(fnIdx * 3 + fileIndex) % nouns.length]; + const limit = 16 + (rng.u32() % 4096); + const mask = (rng.u32() & 0xffff).toString(16).padStart(4, '0'); + const step = 3 + (rng.u32() % 29); + const errCode = `ERR_${idA.toUpperCase().slice(0, 6)}_${noun.toUpperCase()}_${fnIdx}`; + const mode = fnIdx % 3; + + if (isRust) { + lines.push(`/// ${verb} ${noun} state for ${idA} using ${idB} bounds (limit=${limit}).`); + lines.push(`pub fn ${verb}_${noun}_${fnIdx}(ctx: &mut ${primary}, input: &[u8], epoch: u64) -> Result {`); + if (mode === 0) { + lines.push(` if input.len() < ${step} { return Err(Error::new("${errCode}", epoch)); }`); + lines.push(` let mut acc: u64 = (epoch ^ 0x${mask}) + ${limit};`); + lines.push(` for (idx, chunk) in input.chunks(${step}).enumerate() {`); + lines.push(` let delta = ctx.estimate_${idB.toLowerCase()}(idx as u64, chunk.len());`); + lines.push(` acc = acc.wrapping_mul(${31 + (fnIdx % 7)}).wrapping_add(delta ^ (chunk[0] as u64));`); + lines.push(` if acc % ${step + 5} == 0 { ctx.record_checkpoint("${idA}:${noun}", idx, acc); }`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` let mut cursor = ctx.open_${noun}_cursor(epoch, ${limit})?;`); + lines.push(` while let Some(slice) = cursor.next_window(${step * 8}) {`); + lines.push(` let digest = StateDigest::fold(slice, 0x${mask});`); + lines.push(` if !ctx.accept_${idB.toLowerCase()}(&digest) { return Err(Error::mismatch("${errCode}")); }`); + lines.push(` }`); + lines.push(` let acc = cursor.finalize_epoch("${theme.project}:${fnIdx}");`); + } else { + lines.push(` let tag = format!("${theme.project}/${idA}/${noun}#{}", epoch + ${fnIdx});`); + lines.push(` let mut slots = Vec::with_capacity(${16 + (fnIdx % 64)});`); + lines.push(` for slot in 0..${8 + (fnIdx % 12)} { slots.push((slot as u64 * ${step}) ^ 0x${mask}); }`); + lines.push(` let acc = ctx.apply_${verb}(&tag, &slots, input.len());`); + } + lines.push(` ctx.commit_window(${fnIdx}, acc as usize, "${errCode}");`); + lines.push(` Ok((acc & 0x3fff) as usize)`); + lines.push(`}`); + lines.push(''); + } else { + lines.push(`/** ${verb} ${noun} state for ${idA} with ${idB} guard (limit=${limit}). */`); + lines.push(`export function ${verb}${idA}${fnIdx}(ctx: ${primary}, input: Uint8Array, epoch: number): number {`); + if (mode === 0) { + lines.push(` if (input.length < ${step}) throw new RangeError('${errCode}: short input');`); + lines.push(` let acc = ((epoch ^ 0x${mask}) + ${limit}) >>> 0;`); + lines.push(` for (let idx = 0; idx < input.length; idx += ${step}) {`); + lines.push(` const delta = ctx.estimate${idB}(idx, input.length - idx);`); + lines.push(` acc = (Math.imul(acc, ${31 + (fnIdx % 7)}) + (delta ^ input[idx])) >>> 0;`); + lines.push(` if (acc % ${step + 5} === 0) ctx.recordCheckpoint('${idA}:${noun}', idx, acc);`); + lines.push(` }`); + } else if (mode === 1) { + lines.push(` const cursor = ctx.open${idB}Cursor(epoch, ${limit});`); + lines.push(` for (const slice of cursor.windows(${step * 8})) {`); + lines.push(` const digest = StateDigest.fold(slice, 0x${mask});`); + lines.push(` if (!ctx.accept${idA}(digest)) throw new Error('${errCode}: digest mismatch');`); + lines.push(` }`); + lines.push(` const acc = cursor.finalizeEpoch('${theme.project}:${noun}#${fnIdx}');`); + } else { + lines.push(` const tag = '${theme.project}/${idA}/${noun}#' + (epoch + ${fnIdx});`); + lines.push(` const slots = new Uint32Array(${8 + (fnIdx % 12)});`); + lines.push(` for (let s = 0; s < slots.length; s++) slots[s] = (s * ${step}) ^ 0x${mask};`); + lines.push(` const acc = ctx.apply${idB}(tag, slots, input.length);`); + } + lines.push(` ctx.commitWindow(${fnIdx}, acc, '${errCode}');`); + lines.push(` return acc & 0x3fff;`); + lines.push(`}`); + lines.push(''); + } + fnIdx++; + } + return lines.slice(0, lineCount); +} + +function formatLineNumbered(lines, startLine = 1, width = 5) { + const out = new Array(lines.length); + for (let i = 0; i < lines.length; i++) { + out[i] = `${String(startLine + i).padStart(width, ' ')}: ${lines[i]}`; + } + return out.join('\n'); +} + +function mutateSourceLines(rng, theme, prevLines, versionIdx) { + const lines = prevLines.slice(); + const insertAt = 8 + (rng.u32() % 35); + const insertCount = 2 + (rng.u32() % 4); + const added = []; + for (let k = 0; k < insertCount; k++) { + added.push(` // rev-${versionIdx}.${k}: guard ${rng.pick(theme.identifiers)} invariant (mask=0x${rng.hex(2)})`); + } + lines.splice(insertAt, 0, ...added); + const edits = 4 + (rng.u32() % 5); + for (let e = 0; e < edits; e++) { + const pos = 70 + (rng.u32() % (lines.length - 90)); + lines[pos] = lines[pos] + ` /* rev_${versionIdx}_${e} */`; + } + return lines; +} + +function makeToolDefinitions(theme) { + const defs = []; + for (let i = 0; i < 42; i++) { + const name = `${theme.toolNames[i % theme.toolNames.length]}_v${Math.floor(i / theme.toolNames.length) + 1}`; + const idA = theme.identifiers[i % theme.identifiers.length]; + const idB = theme.identifiers[(i + 7) % theme.identifiers.length]; + defs.push({ + name, + description: `Execute ${name} against ${theme.project} workspace (${idA} -> ${idB}). Returns structured diagnostic records, byte offsets, checksums, and execution trace spans without mutating unrelated workspace segments.`, + input_schema: { + type: 'object', + additionalProperties: false, + required: ['targetPath', 'mode', 'budgetMs'], + properties: { + targetPath: { type: 'string', description: `Relative path under ${theme.cwd} for ${idA} inspection.` }, + mode: { type: 'string', enum: ['fast', 'strict', 'audit', 'replay'] }, + budgetMs: { type: 'integer', minimum: 50, maximum: 60000, default: 5000 }, + includeTrace: { type: 'boolean', default: true }, + maxLines: { type: 'integer', minimum: 1, maximum: 4000, default: 1200 }, + filters: { type: 'array', items: { type: 'string' }, description: `Filter tags for ${idB} collector.` }, + encoding: { type: 'string', enum: ['utf8', 'binary', 'jsonl'], default: 'utf8' }, + checksumAlg: { type: 'string', enum: ['sha256', 'crc32'], default: 'sha256' }, + }, + }, + }); + } + return defs; +} + +function buildManifest(meta, rawEntries) { + const manifestEntries = rawEntries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: crypto.createHash('sha256').update(e.content).digest('hex'), + })); + const manifest = { + formatVersion: 3, + minReaderVersion: meta.orca ? 2 : 1, + appVersion: meta.appVersion, + platform: meta.platform, + exportedAt: meta.exportedAt, + agentKind: meta.agentKind, + title: meta.title, + workspaceKind: 'project', + originalWorkingDir: meta.cwd, + sdkSessionIds: meta.sdkSessionIds, + activeSdkSessionId: meta.sdkSessionIds[meta.sdkSessionIds.length - 1] ?? null, + exportFidelity: 'full', + counts: { messages: meta.messageCount, media: meta.mediaCount }, + entries: manifestEntries, + transcripts: meta.transcripts, + ...(meta.orca ? { orca: meta.orca } : {}), + }; + return toUint8(JSON.stringify(manifest, null, 2) + '\n'); +} + +function generateBundleA(rng, theme, opts) { + const sessionId = rng.uuid(); + const sdkSessionId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const model = theme.models[0]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const turnCount = opts.bundleATurns ?? 1000; + const mediaCopies = opts.bundleAMediaCopies ?? 18; + const srcFiles = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 340)); + + // 1 unique 16 KiB PNG duplicated across repeated architecture diagram captures + const uniqA = makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450); + const uniqAB64 = Buffer.from(uniqA).toString('base64'); + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < mediaCopies; m++) { + const filename = `diag-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqA) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + const msgLines = []; + const transcriptLines = []; + const traceLines = []; + + let tsMs = theme.baseEpochMs; + let prevUuid = null; + let inputTokens = 8400; + let cacheReadTokens = 7200; + let cumulativeCost = 14200; + let heapKb = 96000; + let rssKb = 184000; + + for (let i = 0; i < turnCount; i++) { + const dt = 500 + (i % 7) * 180 + rng.int(10, 80); + tsMs += dt; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const requestId = `req_${theme.project.slice(0, 4)}_${String(Math.floor(i / 2)).padStart(5, '0')}`; + const seq = i + 1; + + const kind = i % 4; + let role, dbContent, claudeType, claudeMessage; + let toolUseId = null; + let toolUseResult; + + const deltaIn = 120 + (i % 13) * 35; + const outTok = kind === 1 || kind === 3 ? (110 + (i % 11) * 28) : 0; + const cacheCreate = i % 16 === 0 ? 640 : 0; + cacheReadTokens = Math.max(0, inputTokens - 160); + inputTokens += deltaIn; + const durationMs = 240 + (i % 9) * 140; + const ttftMs = 95 + (i % 5) * 35; + cumulativeCost += Math.round((deltaIn * 3 + outTok * 15) / 10); + + const spanTrace = [tsMs - durationMs, tsMs - durationMs + ttftMs, tsMs - Math.floor(durationMs / 3), tsMs]; + + if (i === 12) { + role = 'user'; + claudeType = 'user'; + const note = `Architecture diagram check: ${theme.zhNotes[0]}`; + dbContent = `${note}\n![diag](cindy-image://${sessionId}/diag-01.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniqAB64 } }, + ], + }; + } else if (kind === 0) { + role = 'user'; + claudeType = 'user'; + const text = `[Step ${seq}] ${theme.zhNotes[i % theme.zhNotes.length]}\nFile: ${theme.files[i % theme.files.length]}\nContext: ${theme.enNotes[(i * 3) % theme.enNotes.length]}`; + dbContent = text; + claudeMessage = { role: 'user', content: [{ type: 'text', text }] }; + } else if (kind === 1) { + role = 'assistant'; + claudeType = 'assistant'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq).padStart(5, '0')}`; + const toolName = theme.toolNames[i % theme.toolNames.length]; + const inputObj = { + path: `${theme.cwd}/${theme.files[i % theme.files.length]}`, + startLine: 1 + ((i * 17) % 140), + endLine: 120 + ((i * 17) % 140), + includeMetrics: true, + tag: `${theme.branch}#${seq}`, + }; + dbContent = JSON.stringify({ + type: 'tool_use', + id: toolUseId, + name: toolName, + input: inputObj, + thought: theme.enNotes[i % theme.enNotes.length], + }); + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [ + { type: 'thinking', thinking: theme.enNotes[i % theme.enNotes.length] }, + { type: 'tool_use', id: toolUseId, name: toolName, input: inputObj }, + ], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } else if (kind === 2) { + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_${sdkSessionId.slice(0, 8)}_${String(seq - 1).padStart(5, '0')}`; + const fileIdx = (i >> 2) % srcFiles.length; + const lines = srcFiles[fileIdx]; + let payloadText; + if (i % 16 === 2) { + const start = (i * 5) % 80; + payloadText = formatLineNumbered(lines.slice(start, start + 120), start + 1, lnWidth); + } else if (i % 16 === 6) { + const f = theme.files[fileIdx]; + const diffLines = [ + `diff --git a/${f} b/${f}`, + `--- a/${f}`, + `+++ b/${f}`, + `@@ -${20 + (i % 80)},14 +${20 + (i % 80)},16 @@`, + ]; + for (let k = 0; k < 20; k++) { + diffLines.push((k === 5 ? '-' : k === 6 ? '+' : ' ') + lines[(20 + (i % 80) + k) % lines.length]); + } + payloadText = diffLines.join('\n'); + } else { + const logLines = [`$ test-runner --filter ${theme.identifiers[i % theme.identifiers.length]} --seed ${seq}`]; + for (let k = 0; k < 10; k++) { + logLines.push( + `[${new Date(tsMs - 200 + k * 10).toISOString()}] PASS case_${k} (${theme.identifiers[(i + k) % theme.identifiers.length]}) elapsed=${15 + (k % 5) * 4}ms rss=${rssKb + k * 16}KB`, + ); + } + payloadText = logLines.join('\n'); + } + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + is_error: false, + content: payloadText, + }); + toolUseResult = { + status: 'ok', + bytes: Buffer.byteLength(payloadText, 'utf8'), + durationMs, + stdout: payloadText, + }; + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: payloadText }], + }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const text = `${theme.zhNotes[(i + 2) % theme.zhNotes.length]}\n\nSummary (${theme.identifiers[i % theme.identifiers.length]}):\n- ${theme.enNotes[(i + 1) % theme.enNotes.length]}\n- Verified checkpoint #${seq} (${inputTokens} in / ${outTok} out).`; + dbContent = text; + claudeMessage = { + id: `msg_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { + input_tokens: inputTokens, + cache_read_input_tokens: cacheReadTokens, + cache_creation_input_tokens: cacheCreate, + output_tokens: outTok, + }, + }; + } + + const agentMetaObj = { + uuid, + parentUuid: prevUuid, + sdkSessionId, + model, + providerId, + requestId, + turnUsageDetails: { + inputTokens, + cacheReadTokens, + cacheCreationTokens: cacheCreate, + outputTokens: outTok, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + }, + }; + msgLines.push(JSON.stringify({ + id: `msg-${String(seq).padStart(6, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify(agentMetaObj), + })); + transcriptLines.push(JSON.stringify({ + parentUuid: prevUuid, + isSidechain: false, + userType: 'external', + cwd: theme.cwd, + sessionId: sdkSessionId, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId, + providerId, + durationMs, + ttftMs, + cumulativeCostMicroUsd: cumulativeCost, + spanTrace, + message: claudeMessage, + ...(toolUseResult ? { toolUseResult } : {}), + })); + prevUuid = uuid; + + // Structured telemetry spans placed between messages.jsonl and transcripts/ (>2 MiB separation) + for (let s = 0; s < 5; s++) { + const spanTs = tsMs - durationMs + s * Math.max(15, Math.floor(durationMs / 5)); + heapKb += 4 + (s === 4 ? -12 : 3); + rssKb += 6 + (s === 4 ? -16 : 4); + traceLines.push(JSON.stringify({ + seq: i * 5 + s + 1, + sessionId, + turnSeq: seq, + requestId, + phase: ['dispatch', 'prompt_cache', 'tool_exec', 'post_hook', 'commit'][s], + timestamp: new Date(spanTs).toISOString(), + tsMs: spanTs, + elapsedMs: 18 + s * 24 + (i % 7) * 5, + inputTokens: inputTokens + s * 4, + cacheReadTokens, + outputTokens: s === 4 ? outTok : Math.floor(outTok * (s / 4)), + heapUsedKb: heapKb, + rssKb, + cumulativeCostMicroUsd: cumulativeCost, + status: 'ok', + model, + providerId, + })); + } + } + + const transcriptPath = `transcripts/claude/${sdkSessionId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: single-agent optimization audit`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId, + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(msgLines.join('\n') + '\n') }, + ...mediaEntries, + { path: 'telemetry/turn-spans.jsonl', content: toUint8(traceLines.join('\n') + '\n') }, + { path: transcriptPath, content: toUint8(transcriptLines.join('\n') + '\n') }, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 5000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: single-agent optimization audit`, + cwd: theme.cwd, + sdkSessionIds: [sdkSessionId], + messageCount: turnCount, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId, path: transcriptPath }], + }, bodyEntries); + + return { + name: 'single-agent-session', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleB(rng, theme, opts) { + const sessionId = rng.uuid(); + const forkSids = [rng.uuid(), rng.uuid(), rng.uuid()]; + const nodeBuf = rng.bytes(5); + const model = theme.models[1]; + const providerId = theme.providers[0]; + const lnWidth = theme.lineNumWidth ?? 5; + const sharedTurns = opts.bundleBSharedTurns ?? 152; + const tailTurns = opts.bundleBTailTurns ?? 38; + + // 12 binary PNGs built from 3 unique incompressible blobs (64 KiB unique total, 356 KiB raw) + const uniquePngs = [ + makeSyntheticPng(rng, 38 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 13 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniquePngB64 = uniquePngs.map((b) => Buffer.from(b).toString('base64')); + const imgAssign = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2]; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < 12; m++) { + const filename = `img-${String(m + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniquePngs[imgAssign[m]]) }); + mediaMap.push({ + url: `cindy-image://${sessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: sessionId, + filename, + }); + } + + let fileVersions = [0, 1, 2, 3].map((i) => generateSourceFile(rng, theme, i, 640)); + let tsMs = theme.baseEpochMs + 3600_000; + let prevUuid = null; + let inputTokens = 12000; + let cumulativeCost = 22000; + + const sharedPrefixTurns = []; + const dbMsgLines = []; + let snapshotIdx = 0; + + for (let t = 0; t < sharedTurns; t++) { + tsMs += 600 + (t % 7) * 210 + rng.int(5, 45); + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, t + 1, nodeBuf); + const seq = t + 1; + const reqId = `req_fork_${String(Math.floor(t / 2)).padStart(4, '0')}`; + const durationMs = 260 + (t % 9) * 180; + const outTok = t % 2 === 1 ? (140 + (t % 7) * 40) : 0; + const cacheRead = Math.max(0, inputTokens - 180); + inputTokens += 150 + (t % 11) * 45; + cumulativeCost += Math.round((inputTokens * 2 + outTok * 15) / 100); + + let role, claudeType, claudeMessage, dbContent; + let toolUseId = null; + + if (t === 5 || t === 55 || t === 105) { + const imgIdx = t === 5 ? 0 : t === 55 ? 1 : 2; + role = 'user'; + claudeType = 'user'; + const note = `Screenshot #${imgIdx + 1}: ${theme.zhNotes[imgIdx]} (${theme.enNotes[imgIdx]})`; + const imgNum = imgIdx === 0 ? 1 : imgIdx === 1 ? 9 : 11; + dbContent = `${note}\n![shot](cindy-image://${sessionId}/img-${String(imgNum).padStart(2, '0')}.png)`; + claudeMessage = { + role: 'user', + content: [ + { type: 'text', text: note }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: uniquePngB64[imgIdx] } }, + ], + }; + } else if (t > 0 && t % 7 === 0 && snapshotIdx < 20) { + const fIdx = snapshotIdx % 4; + const rev = Math.floor(snapshotIdx / 4); + if (rev > 0) fileVersions[fIdx] = mutateSourceLines(rng, theme, fileVersions[fIdx], rev); + snapshotIdx++; + const numbered = formatLineNumbered(fileVersions[fIdx], 1, lnWidth); + role = 'tool'; + claudeType = 'user'; + toolUseId = `toolu_snap_${String(snapshotIdx).padStart(3, '0')}`; + dbContent = JSON.stringify({ + type: 'tool_result', + tool_use_id: toolUseId, + file: theme.files[fIdx], + revision: rev, + content: numbered, + }); + claudeMessage = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: toolUseId, is_error: false, content: numbered }], + }; + } else if (t % 2 === 0) { + role = 'user'; + claudeType = 'user'; + const logLine = `[turn ${seq}] ${theme.zhNotes[t % theme.zhNotes.length]} | ${theme.enNotes[(t * 5) % theme.enNotes.length]} | metrics: latency=${durationMs}ms`; + dbContent = logLine; + claudeMessage = { role: 'user', content: [{ type: 'text', text: logLine }] }; + } else { + role = 'assistant'; + claudeType = 'assistant'; + const reply = `Analysis #${seq} (${theme.identifiers[t % theme.identifiers.length]}): ${theme.enNotes[(t + 2) % theme.enNotes.length]}\n${theme.zhNotes[(t + 1) % theme.zhNotes.length]}`; + dbContent = reply; + claudeMessage = { + id: `msg_f_${seq}`, + role: 'assistant', + model, + content: [{ type: 'text', text: reply }], + usage: { input_tokens: inputTokens, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + + sharedPrefixTurns.push({ + parentUuid: prevUuid, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: theme.branch, + type: claudeType, + uuid, + timestamp: iso, + requestId: reqId, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + message: claudeMessage, + }); + dbMsgLines.push(JSON.stringify({ + id: `bmsg-${String(seq).padStart(5, '0')}`, + sessionId, + seq, + role, + createdAt: iso, + createdAtMs: tsMs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: prevUuid, + sdkSessionId: forkSids[2], + model, + providerId, + requestId: reqId, + inputTokens, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs, + cumulativeCostMicroUsd: cumulativeCost, + }), + })); + prevUuid = uuid; + } + + const forkEntries = []; + const transcriptRefs = []; + for (let f = 0; f < 3; f++) { + const fSid = forkSids[f]; + const lines = sharedPrefixTurns.map((turn) => JSON.stringify({ ...turn, sessionId: fSid, forkBranch: `fork-${f}` })); + let fPrev = prevUuid; + let fTs = tsMs + f * 60_000; + let fIn = inputTokens; + let fCost = cumulativeCost; + for (let k = 0; k < tailTurns; k++) { + fTs += 500 + (k % 5) * 190 + rng.int(5, 35); + const iso = new Date(fTs).toISOString(); + const uuid = rng.uuidv7(fTs, 200 + f * 60 + k, nodeBuf); + const outTok = k % 2 === 1 ? (110 + (k % 7) * 35) : 0; + const cacheRead = Math.max(0, fIn - 140); + fIn += 130 + (k % 9) * 40; + fCost += Math.round((fIn * 2 + outTok * 15) / 100); + let msg; + if (f === 2 && k < 4) { + fileVersions[k] = mutateSourceLines(rng, theme, fileVersions[k], 5 + f); + const numbered = formatLineNumbered(fileVersions[k], 1, lnWidth); + msg = { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: `toolu_tail_${f}_${k}`, is_error: false, content: numbered }], + }; + } else { + const text = `[fork-${f} tail ${k + 1}] ${theme.enNotes[(k + f * 2) % theme.enNotes.length]} | ${theme.zhNotes[(k + f) % theme.zhNotes.length]}`; + msg = k % 2 === 0 + ? { role: 'user', content: [{ type: 'text', text }] } + : { + id: `msg_f${f}_t${k}`, + role: 'assistant', + model, + content: [{ type: 'text', text }], + usage: { input_tokens: fIn, cache_read_input_tokens: cacheRead, output_tokens: outTok }, + }; + } + lines.push(JSON.stringify({ + parentUuid: fPrev, + isSidechain: false, + cwd: theme.cwd, + version: theme.appVersion, + gitBranch: `${theme.branch}-f${f}`, + type: k % 2 === 0 ? 'user' : 'assistant', + uuid, + timestamp: iso, + requestId: `req_f${f}_${String(k).padStart(3, '0')}`, + durationMs: 220 + (k % 8) * 140, + cumulativeCostMicroUsd: fCost, + sessionId: fSid, + forkBranch: `fork-${f}`, + message: msg, + })); + fPrev = uuid; + } + const tp = `transcripts/claude/fork-${f}.jsonl`; + forkEntries.push({ path: tp, content: toUint8(lines.join('\n') + '\n') }); + transcriptRefs.push({ sdkSessionId: fSid, path: tp }); + } + + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: sessionId, + title: `${theme.project}: fork chain & evolving snapshots`, + workingDir: theme.cwd, + workspaceKind: 'project', + model, + effort: 'high', + permissionMode: 'auto', + providerId, + status: 'idle', + sdkSessionId: forkSids[2], + totalTokenUsage: inputTokens, + totalCostUsd: Number((cumulativeCost / 1e6).toFixed(6)), + contextTokens: inputTokens, + contextWindow: 200000, + agentKind: 'cc', + createdAt: theme.baseEpochMs + 3600_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(dbMsgLines.join('\n') + '\n') }, + ...mediaEntries, + ...forkEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 90_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: fork chain & evolving snapshots`, + cwd: theme.cwd, + sdkSessionIds: forkSids, + messageCount: dbMsgLines.length, + mediaCount: mediaEntries.length, + transcripts: transcriptRefs, + }, bodyEntries); + + return { + name: 'fork-chain-and-media', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +function generateBundleC(rng, theme, opts) { + const leadSessionId = rng.uuid(); + const leadSdkId = rng.uuid(); + const nodeBuf = rng.bytes(5); + const lnWidth = theme.lineNumWidth ?? 5; + const workerTurns = opts.bundleCWorkerTurns ?? 110; + const workerMediaEach = opts.bundleCWorkerShotsEach ?? 14; + const toolDefs = makeToolDefinitions(theme); + const systemPromptBase = [ + `You are an Orca autonomous engineering worker operating inside ${theme.cwd} (${theme.project}).`, + ...theme.enNotes, + ...theme.zhNotes, + 'Strict invariants: preserve exact wire compatibility, maintain deterministic ordering, never drop audit checksums, verify every edge case before reporting completion.', + ].join('\n'); + const sharedRepoFiles = [0, 1, 4, 5].map((i) => generateSourceFile(rng, theme, i, 420)); + + // 2 unique 16 KiB PNGs (32 KiB unique floor) duplicated across lead & 4 workers' verification screenshots + const uniqShots = [ + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + makeSyntheticPng(rng, 16 * 1024, theme.pngWidth ?? 800, theme.pngHeight ?? 450), + ]; + const uniqShotsB64 = uniqShots.map((b) => Buffer.from(b).toString('base64')); + const totalShots = 4 + 4 * workerMediaEach; + const mediaEntries = []; + const mediaMap = []; + for (let m = 0; m < totalShots; m++) { + const filename = m < 4 + ? `lead-shot-${String(m + 1).padStart(2, '0')}.png` + : `worker-${Math.floor((m - 4) / workerMediaEach)}-shot-${String(((m - 4) % workerMediaEach) + 1).padStart(2, '0')}.png`; + const zipPath = `media/${filename}`; + mediaEntries.push({ path: zipPath, content: new Uint8Array(uniqShots[m % 2]) }); + mediaMap.push({ + url: `cindy-image://${leadSessionId}/${filename}`, + scheme: 'cindy-image', + kind: 'image', + zipPath, + imageHost: leadSessionId, + filename, + }); + } + + let tsMs = theme.baseEpochMs + 7200_000; + const leadMsgs = []; + const leadTranscript = []; + let leadPrev = null; + for (let i = 0; i < 44; i++) { + tsMs += 800 + (i % 5) * 140; + const iso = new Date(tsMs).toISOString(); + const uuid = rng.uuidv7(tsMs, i + 1, nodeBuf); + const text = `[Lead #${i + 1}] Coordinate worker ${i % 4}: ${theme.zhNotes[i % theme.zhNotes.length]} (${theme.enNotes[i % theme.enNotes.length]})`; + leadMsgs.push(JSON.stringify({ + id: `lead-${String(i + 1).padStart(4, '0')}`, + sessionId: leadSessionId, + seq: i + 1, + role: i % 2 === 0 ? 'user' : 'assistant', + createdAt: iso, + createdAtMs: tsMs, + toolUseId: null, + content: text, + agentMeta: JSON.stringify({ uuid, parentUuid: leadPrev, sdkSessionId: leadSdkId, model: theme.models[0] }), + })); + leadTranscript.push(JSON.stringify({ + parentUuid: leadPrev, + sessionId: leadSdkId, + uuid, + timestamp: iso, + type: i % 2 === 0 ? 'user' : 'assistant', + message: { role: i % 2 === 0 ? 'user' : 'assistant', content: [{ type: 'text', text }] }, + })); + leadPrev = uuid; + } + + const workerEntries = []; + const workerManifests = []; + const roles = theme.workerRoles ?? ['implementer', 'verifier', 'profiler', 'auditor']; + + for (let w = 0; w < 4; w++) { + const wSessionId = rng.uuid(); + const wThreadId = rng.uuid(); + const wNode = rng.bytes(5); + const wDir = `${theme.cwd}/.worktrees/worker-${w}`; + const wMsgs = []; + const wRollout = []; + let wTs = theme.baseEpochMs + 7210_000 + w * 2500; + let wIn = 18000; + let wCost = 9500; + let wPrev = null; + + const workerTools = toolDefs.map((d) => ({ + ...d, + description: `[worker-${w}/${roles[w]}] ${d.description}`, + })); + wRollout.push(JSON.stringify({ + timestamp: new Date(wTs).toISOString(), + type: 'session_meta', + payload: { + id: wThreadId, + workerIndex: w, + workerRole: roles[w], + cwd: wDir, + model: theme.codexModel, + providerId: theme.providers[1], + systemPrompt: `${systemPromptBase}\nAssigned Role: ${roles[w]} (#${w})`, + tools: workerTools, + }, + })); + + for (let t = 0; t < workerTurns; t++) { + wTs += 500 + (t % 7) * 160 + rng.int(5, 30); + const iso = new Date(wTs).toISOString(); + const uuid = rng.uuidv7(wTs, t + 1, wNode); + const seq = t + 1; + const cacheRead = Math.max(0, wIn - 180); + const outTok = t % 2 === 1 ? (120 + (t % 9) * 32) : 0; + const dur = 180 + (t % 8) * 160; + wIn += 140 + (t % 11) * 45; + wCost += Math.round((wIn + outTok * 12) / 80); + + let role, dbContent, rolloutItem; + let toolUseId = null; + + if (t === 4 || t === 56) { + const sIdx = (w + (t === 4 ? 0 : 1)) % 2; + role = 'user'; + dbContent = JSON.stringify({ + type: 'screenshot_check', + worker: w, + image: `cindy-image://${leadSessionId}/worker-${w}-shot-0${sIdx + 1}.png`, + }); + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role: 'user', + content: [ + { type: 'input_text', text: `Verify UI screenshot #${sIdx + 1} for worker-${w}` }, + { type: 'input_image', image_url: `data:image/png;base64,${uniqShotsB64[sIdx]}` }, + ], + }, + }; + } else if (t % 20 === 6) { + const fIdx = Math.floor(t / 20) % sharedRepoFiles.length; + const lines = w === 0 ? sharedRepoFiles[fIdx] : mutateSourceLines(rng, theme, sharedRepoFiles[fIdx], w * 10 + t); + const numbered = formatLineNumbered(lines, 1, lnWidth); + role = 'tool'; + toolUseId = `call_w${w}_${String(seq).padStart(4, '0')}`; + dbContent = JSON.stringify({ + type: 'function_call_output', + call_id: toolUseId, + file: theme.files[fIdx], + output: numbered, + }); + rolloutItem = { + type: 'response_item', + payload: { type: 'function_call_output', call_id: toolUseId, output: numbered }, + }; + } else if (t % 10 === 0) { + role = 'assistant'; + const summary = `Worker ${w} (${roles[w]}) turn ${seq}: ${theme.enNotes[(t + w) % theme.enNotes.length]}`; + dbContent = JSON.stringify({ type: 'tool_context', worker: w, summary, toolCount: workerTools.length }); + rolloutItem = { + type: 'turn_context', + payload: { + turn: seq, + cwd: wDir, + model: theme.codexModel, + summary, + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + ...(t === 0 || t === 50 ? { tools: workerTools } : {}), + }, + }; + } else { + role = t % 2 === 0 ? 'user' : 'assistant'; + const text = `[worker-${w}/${roles[w]} #${seq}] ${theme.zhNotes[(t + w) % theme.zhNotes.length]}\n${theme.enNotes[(t * 3 + w) % theme.enNotes.length]} (tokens=${wIn}, dur=${dur}ms)`; + dbContent = text; + rolloutItem = { + type: 'response_item', + payload: { + type: 'message', + role, + content: [{ type: role === 'user' ? 'input_text' : 'output_text', text }], + usage: { + input_tokens: wIn, + cached_input_tokens: cacheRead, + output_tokens: outTok, + duration_ms: dur, + cumulative_cost_microusd: wCost, + }, + }, + }; + } + + wMsgs.push(JSON.stringify({ + id: `w${w}-msg-${String(seq).padStart(5, '0')}`, + sessionId: wSessionId, + seq, + role, + createdAt: iso, + createdAtMs: wTs, + toolUseId, + content: dbContent, + agentMeta: JSON.stringify({ + uuid, + parentUuid: wPrev, + sdkSessionId: wThreadId, + model: theme.codexModel, + providerId: theme.providers[1], + workerIndex: w, + turnUsageDetails: { + inputTokens: wIn, + cacheReadTokens: cacheRead, + outputTokens: outTok, + durationMs: dur, + cumulativeCostMicroUsd: wCost, + }, + }), + })); + wRollout.push(JSON.stringify({ + timestamp: iso, + tsMs: wTs, + uuid, + parentUuid: wPrev, + sessionId: wThreadId, + workerIndex: w, + ...rolloutItem, + })); + wPrev = uuid; + } + + const prefix = `orca/workers/${w}`; + const rolloutPath = `${prefix}/transcripts/codex/rollout.jsonl`; + workerEntries.push( + { + path: `${prefix}/session.json`, + content: toUint8(JSON.stringify({ + id: wSessionId, + title: `Worker ${w} (${roles[w]})`, + workingDir: wDir, + workspaceKind: 'project', + model: theme.codexModel, + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[1], + status: 'done', + sdkSessionId: wThreadId, + totalTokenUsage: wIn, + totalCostUsd: Number((wCost / 1e6).toFixed(6)), + agentKind: 'codex', + orcaRole: 'worker', + createdAt: theme.baseEpochMs + 7210_000, + updatedAt: wTs, + }, null, 2) + '\n'), + }, + { path: `${prefix}/messages.jsonl`, content: toUint8(wMsgs.join('\n') + '\n') }, + { path: rolloutPath, content: toUint8(wRollout.join('\n') + '\n') }, + ); + workerManifests.push({ + index: w, + agentKind: 'codex', + providerId: theme.providers[1], + title: `Worker ${w} (${roles[w]})`, + role: roles[w], + label: `worker-${w}`, + status: 'done', + focused: w === 0, + sdkSessionIds: [wThreadId], + activeSdkSessionId: wThreadId, + counts: { messages: wMsgs.length }, + transcripts: [{ sdkSessionId: wThreadId, path: rolloutPath }], + }); + } + + const leadTranscriptPath = `transcripts/claude/${leadSdkId}.jsonl`; + const bodyEntries = [ + { + path: 'session.json', + content: toUint8(JSON.stringify({ + id: leadSessionId, + title: `${theme.project}: Orca 4-worker team session`, + workingDir: theme.cwd, + workspaceKind: 'project', + model: theme.models[0], + effort: 'high', + permissionMode: 'auto', + providerId: theme.providers[0], + status: 'idle', + sdkSessionId: leadSdkId, + agentKind: 'cc', + orcaRole: 'lead', + createdAt: theme.baseEpochMs + 7200_000, + updatedAt: tsMs, + }, null, 2) + '\n'), + }, + { path: 'media-map.json', content: toUint8(JSON.stringify(mediaMap, null, 2) + '\n') }, + { path: 'messages.jsonl', content: toUint8(leadMsgs.join('\n') + '\n') }, + { path: leadTranscriptPath, content: toUint8(leadTranscript.join('\n') + '\n') }, + ...mediaEntries, + ...workerEntries, + ]; + const manifestBuf = buildManifest({ + appVersion: theme.appVersion, + platform: theme.platform, + exportedAt: new Date(tsMs + 120_000).toISOString(), + agentKind: 'cc', + title: `${theme.project}: Orca 4-worker team session`, + cwd: theme.cwd, + sdkSessionIds: [leadSdkId], + messageCount: leadMsgs.length, + mediaCount: mediaEntries.length, + transcripts: [{ sdkSessionId: leadSdkId, path: leadTranscriptPath }], + orca: { teamStatus: 'completed', workers: workerManifests }, + }, bodyEntries); + + return { + name: 'orca-team-archive', + headerVersion: 1, + entries: [{ path: 'manifest.json', content: manifestBuf }, ...bodyEntries], + }; +} + +export function generateCorpusSuite(options = {}) { + const seed = options.seed ?? PUBLIC_SEED; + const theme = options.theme ?? PUBLIC_THEME; + const rng = createDeterministicRng(seed); + return { + suiteName: options.suiteName ?? 'public', + bundles: [ + generateBundleA(rng, theme, options), + generateBundleB(rng, theme, options), + generateBundleC(rng, theme, options), + ], + }; +} + +export function generatePublicSuite() { + return generateCorpusSuite({ seed: PUBLIC_SEED, theme: PUBLIC_THEME, suiteName: 'public' }); +} + +export function measureBundleRawBytes(bundle) { + let total = 0; + for (const e of bundle.entries) total += e.content.byteLength; + return total; +} diff --git a/questions/opt-cshare-compression/v1/reference/package.json b/questions/opt-cshare-compression/v1/reference/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v1/reference/src/container.mjs b/questions/opt-cshare-compression/v1/reference/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v1/reference/src/cshare-codec.mjs b/questions/opt-cshare-compression/v1/reference/src/cshare-codec.mjs new file mode 100644 index 0000000..87143e3 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/src/cshare-codec.mjs @@ -0,0 +1,253 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +const MEDIA_EXT_RE = /\.(png|jpe?g|webp|gif|mp4|webm)$/i; +const B64_TOKEN_PREFIX = '\x1eB:'; +const B64_TOKEN_SUFFIX = '\x1f'; +const B64_TOKEN_RE = /\x1eB:(\d+)\x1f/g; + +// Entry encoding modes: +// 0 = raw bytes inside solid Brotli stream +// 1 = deduplicated store-only media blob (index into media table) +// 2 = canonical compact JSON (restored via JSON.stringify(obj, null, 2) + '\n') +// 3 = UTF-8 text with inline Base64 media tokens referencing media table +const MODE_RAW = 0; +const MODE_MEDIA_STORE = 1; +const MODE_PRETTY_JSON2 = 2; +const MODE_INLINE_B64_REF = 3; + +function isExactUtf8(buf, str) { + return Buffer.byteLength(str, 'utf8') === buf.length && Buffer.from(str, 'utf8').equals(buf); +} + +/** + * Reference `.cshare` codec: + * - Content-hash deduplication + store-only storage for binary media blobs + * - Inline Base64-to-media deduplication inside JSONL transcripts + * - Lossless pretty-printed JSON compaction (verified bit-exact) + * - Solid cross-file Brotli compression (quality 5, lgwin 24) + */ +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const headerVersion = bundle.headerVersion ?? XDTSHARE_HEADER_VERSION; + const header = encodePlainHeader(headerVersion); + + // Pass 1: deduplicate store-only binary media blobs and build Base64 lookup list + const mediaBlobs = []; + const mediaHashToIdx = new Map(); + const entryMediaIdx = new Array(bundle.entries.length).fill(-1); + const b64Refs = []; + + for (let i = 0; i < bundle.entries.length; i++) { + const entry = bundle.entries[i]; + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const rawBuf = toBufferView(entry.content); + if (MEDIA_EXT_RE.test(entry.path)) { + const digest = crypto.createHash('sha256').update(rawBuf).digest('hex'); + let idx = mediaHashToIdx.get(digest); + if (idx === undefined) { + idx = mediaBlobs.length; + mediaHashToIdx.set(digest, idx); + const copy = Buffer.from(rawBuf); + mediaBlobs.push(copy); + if (copy.length >= 256) { + b64Refs.push([copy.toString('base64'), idx]); + } + } + entryMediaIdx[i] = idx; + } + } + + // Pass 2: build ordered TOC + solid stream chunks + const toc = new Array(bundle.entries.length); + const solidChunks = []; + + for (let i = 0; i < bundle.entries.length; i++) { + const entry = bundle.entries[i]; + const mediaIdx = entryMediaIdx[i]; + if (mediaIdx >= 0) { + toc[i] = [entry.path, MODE_MEDIA_STORE, mediaIdx]; + continue; + } + + const rawBuf = toBufferView(entry.content); + let outBuf = rawBuf; + let mode = MODE_RAW; + + if (entry.path.endsWith('.json') && rawBuf.length > 0) { + const str = rawBuf.toString('utf8'); + if (isExactUtf8(rawBuf, str)) { + try { + const parsed = JSON.parse(str); + if (JSON.stringify(parsed, null, 2) + '\n' === str) { + outBuf = Buffer.from(JSON.stringify(parsed), 'utf8'); + mode = MODE_PRETTY_JSON2; + } + } catch { + // Malformed JSON: fall back to raw binary mode + } + } + } else if (entry.path.endsWith('.jsonl') && b64Refs.length > 0 && rawBuf.length >= 256) { + const str = rawBuf.toString('utf8'); + if (isExactUtf8(rawBuf, str) && !str.includes(B64_TOKEN_PREFIX)) { + let transformed = str; + let changed = false; + for (const [b64, idx] of b64Refs) { + if (transformed.includes(b64)) { + transformed = transformed.split(b64).join(`${B64_TOKEN_PREFIX}${idx}${B64_TOKEN_SUFFIX}`); + changed = true; + } + } + if (changed) { + outBuf = Buffer.from(transformed, 'utf8'); + mode = MODE_INLINE_B64_REF; + } + } + } + + toc[i] = [entry.path, mode, outBuf.length]; + solidChunks.push(outBuf); + } + + const tocBuf = Buffer.from(JSON.stringify(toc), 'utf8'); + const tocLenBuf = Buffer.alloc(4); + tocLenBuf.writeUInt32LE(tocBuf.length, 0); + const solidInput = Buffer.concat([tocLenBuf, tocBuf, ...solidChunks]); + + const solidCompressed = zlib.brotliCompressSync(solidInput, { + params: { + [zlib.constants.BROTLI_PARAM_QUALITY]: 5, + [zlib.constants.BROTLI_PARAM_LGWIN]: 24, + }, + }); + + const sectionHdr = Buffer.alloc(8); + sectionHdr.writeUInt32LE(solidCompressed.length, 0); + sectionHdr.writeUInt32LE(mediaBlobs.length, 4); + + const parts = [header, sectionHdr, solidCompressed]; + for (const blob of mediaBlobs) { + const lenBuf = Buffer.alloc(4); + lenBuf.writeUInt32LE(blob.length, 0); + parts.push(lenBuf, blob); + } + + const out = Buffer.concat(parts); + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + if (payload.length < 8) { + throw new Error('Truncated archive payload'); + } + const solidLen = payload.readUInt32LE(0); + const mediaCount = payload.readUInt32LE(4); + let offset = 8; + + if (offset + solidLen > payload.length) { + throw new Error('Truncated solid Brotli payload'); + } + const solidRaw = zlib.brotliDecompressSync(payload.subarray(offset, offset + solidLen)); + offset += solidLen; + + const mediaBlobs = new Array(mediaCount); + for (let i = 0; i < mediaCount; i++) { + if (offset + 4 > payload.length) { + throw new Error(`Truncated media header at index ${i}`); + } + const len = payload.readUInt32LE(offset); + offset += 4; + if (offset + len > payload.length) { + throw new Error(`Truncated media body at index ${i}`); + } + mediaBlobs[i] = Buffer.from(payload.subarray(offset, offset + len)); + offset += len; + } + + if (offset !== payload.length) { + throw new Error(`Unexpected trailing bytes: ${payload.length - offset}`); + } + if (solidRaw.length < 4) { + throw new Error('Truncated solid TOC length'); + } + + const tocLen = solidRaw.readUInt32LE(0); + let solidPos = 4; + if (solidPos + tocLen > solidRaw.length) { + throw new Error('Truncated solid TOC'); + } + const toc = JSON.parse(solidRaw.toString('utf8', solidPos, solidPos + tocLen)); + solidPos += tocLen; + + const mediaB64Cache = new Map(); + const getMediaB64 = (idx) => { + let cached = mediaB64Cache.get(idx); + if (cached === undefined) { + const blob = mediaBlobs[idx]; + if (!blob) throw new Error(`Invalid media reference index ${idx}`); + cached = blob.toString('base64'); + mediaB64Cache.set(idx, cached); + } + return cached; + }; + + const entries = new Array(toc.length); + for (let i = 0; i < toc.length; i++) { + const [entryPath, mode, arg] = toc[i]; + if (mode === MODE_MEDIA_STORE) { + const blob = mediaBlobs[arg]; + if (!blob) throw new Error(`Invalid media blob index ${arg} for ${entryPath}`); + const copy = Buffer.from(blob); + entries[i] = { + path: entryPath, + content: new Uint8Array(copy.buffer, copy.byteOffset, copy.byteLength), + }; + continue; + } + + if (solidPos + arg > solidRaw.length) { + throw new Error(`Truncated solid entry data for ${entryPath}`); + } + const slice = solidRaw.subarray(solidPos, solidPos + arg); + solidPos += arg; + + let restored; + if (mode === MODE_RAW) { + restored = Buffer.from(slice); + } else if (mode === MODE_PRETTY_JSON2) { + const parsed = JSON.parse(slice.toString('utf8')); + restored = Buffer.from(JSON.stringify(parsed, null, 2) + '\n', 'utf8'); + } else if (mode === MODE_INLINE_B64_REF) { + const expanded = slice.toString('utf8').replace(B64_TOKEN_RE, (_, idxStr) => getMediaB64(Number(idxStr))); + restored = Buffer.from(expanded, 'utf8'); + } else { + throw new Error(`Unknown entry encoding mode ${mode} for ${entryPath}`); + } + + entries[i] = { + path: entryPath, + content: new Uint8Array(restored.buffer, restored.byteOffset, restored.byteLength), + }; + } + + if (solidPos !== solidRaw.length) { + throw new Error(`Unexpected trailing solid bytes: ${solidRaw.length - solidPos}`); + } + + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v1/reference/tests/smoke.test.mjs b/questions/opt-cshare-compression/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..4beed65 --- /dev/null +++ b/questions/opt-cshare-compression/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { generatePublicSuite } from '../lib/corpus-generator.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = generatePublicSuite(); + assert.equal(suite.bundles.length, 3); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-cshare-compression/v2/author/editable.json b/questions/opt-cshare-compression/v2/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-cshare-compression/v2/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-cshare-compression/v2/author/evaluator.mjs b/questions/opt-cshare-compression/v2/author/evaluator.mjs new file mode 100644 index 0000000..48e4c0e --- /dev/null +++ b/questions/opt-cshare-compression/v2/author/evaluator.mjs @@ -0,0 +1,507 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { performance } from 'node:perf_hooks'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +// Submission code runs in a child process under Node's permission model: `--permission` since +// Node 22.13 / 23.5, `--experimental-permission` on Node 20 before that, absent before Node 20. +// Without it the submission cannot be isolated, so the run is reported as an environment +// problem instead of being scored. +const PERMISSION_FLAG = ['--permission', '--experimental-permission'].find( + (flag) => spawnSync(process.execPath, [flag, '-e', ''], { stdio: 'ignore', timeout: 10_000 }).status === 0, +); +if (!PERMISSION_FLAG) { + trusted.emit({ + status: 'environment_invalid', + reason: `grading needs Node.js >= 20 for the permission model (found ${process.version})`, + }); + process.exit(0); +} +const bufferCompare = Buffer.compare; +const randomHex = (n) => crypto.randomBytes(n).toString('hex'); +const childNonce = randomHex(16); + +const [subSrcDir, corpusLoaderPath, publicCorpusPath, heldOutCorpusPath] = process.argv.slice(2); +if (!subSrcDir || !corpusLoaderPath || !publicCorpusPath || !heldOutCorpusPath) { + throw new Error('Usage: node evaluator.mjs '); +} + +// Product budget: exporting ~1 MB of session data within ~2 s and importing it within ~1 s +// on the grading machine (held-out corpus is ~12 MB raw). +const ENCODE_LIMIT_MS = 24_000; +const DECODE_LIMIT_MS = 12_000; +const FALLBACK_ARCHIVE_BYTES = 100_000_000; + +// Held-out corpus: real de-identified session exports from different tasks than the public +// corpus, scrubbed with a different surrogate key (so public-corpus dictionaries do not transfer). + +function createDeterministicRng(seed) { + let state = crypto.createHash('sha256').update(String(seed)).digest(); + let pool = Buffer.alloc(0); + return { + bytes(n) { + while (pool.length < n) { + state = crypto.createHash('sha256').update(state).digest(); + pool = Buffer.concat([pool, state]); + } + const out = pool.subarray(0, n); + pool = pool.subarray(n); + return Buffer.from(out); + }, + }; +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +async function snapshotDirHashes(dir) { + const result = {}; + async function walk(cur, relPrefix) { + const entries = await fs.readdir(cur, { withFileTypes: true }); + entries.sort((a, b) => a.name.localeCompare(b.name)); + for (const ent of entries) { + const full = path.join(cur, ent.name); + const rel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name; + if (ent.isDirectory()) { + await walk(full, rel); + } else if (ent.isFile()) { + const data = await fs.readFile(full); + result[rel] = sha256(data); + } + } + } + await walk(dir, ''); + return result; +} + +function fingerprintBundle(bundle) { + return bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); +} + +function verifyPlainHeader(encoded, label) { + assert.ok(encoded instanceof Uint8Array, `${label}: encoded output must be Uint8Array`); + assert.ok(encoded.byteLength >= 12, `${label}: encoded output shorter than 12 bytes`); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), 'XDTSHARE', `${label}: bad XDTSHARE magic`); + assert.equal(buf.readUInt8(8), 1, `${label}: headerVersion must be 1`); + assert.equal(buf.readUInt8(9), 0, `${label}: cipher must be 0`); + assert.equal(buf.readUInt16BE(10), 0, `${label}: reserved bytes must be 0`); +} + +function verifyDecodedMatches(decoded, expectedFingerprint, label) { + assert.ok(decoded && typeof decoded === 'object', `${label}: decodeArchive must return an object`); + assert.equal(decoded.headerVersion, 1, `${label}: decoded headerVersion must be 1`); + assert.ok(Array.isArray(decoded.entries), `${label}: decoded.entries must be an array`); + assert.equal( + decoded.entries.length, + expectedFingerprint.length, + `${label}: entry count mismatch (${decoded.entries.length} vs ${expectedFingerprint.length})`, + ); + for (let i = 0; i < expectedFingerprint.length; i++) { + const exp = expectedFingerprint[i]; + const got = decoded.entries[i]; + assert.ok(got && typeof got === 'object', `${label}[${i}]: entry missing`); + assert.equal(got.path, exp.path, `${label}[${i}]: path mismatch (${got.path} vs ${exp.path})`); + assert.ok(got.content instanceof Uint8Array, `${label}[${i}]: content must be Uint8Array`); + assert.equal(got.content.byteLength, exp.bytes, `${label}[${i}] (${exp.path}): byte length mismatch`); + assert.equal(sha256(got.content), exp.sha256, `${label}[${i}] (${exp.path}): SHA-256 mismatch`); + } +} + +function buildAdversarialBundles(createDeterministicRng) { + const rng = createDeterministicRng('cshare-adversarial-edges-v1'); + const all256 = new Uint8Array(256); + for (let i = 0; i < 256; i++) all256[i] = i; + + const highEntropy = new Uint8Array(rng.bytes(65_536)); + + // Create a non-zero byteOffset Uint8Array view into a larger backing buffer + const backing = Buffer.alloc(128, 0xaa); + const innerBytes = Buffer.from('offset-slice-\x00\x01\xff-中文🎉\r\n', 'utf8'); + innerBytes.copy(backing, 23); + const offsetView = new Uint8Array(backing.buffer, backing.byteOffset + 23, innerBytes.length); + + // PNG-like binary plus colliding base64 text & sentinel strings + const tinyPng = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + rng.bytes(512), + ]); + const tinyPngB64 = tinyPng.toString('base64'); + + const emptyBundle = { headerVersion: 1, entries: [] }; + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.jsonl', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: all256 }, + { path: 'binary-as.json', content: new Uint8Array(all256) }, + { path: 'binary-as.jsonl', content: new Uint8Array(all256) }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\u0000\uffff\r\nline2\nno-trailing-newline', 'utf8') }, + { path: 'crlf.jsonl', content: Buffer.from('{"a":1}\r\n{"a":2}\r\n', 'utf8') }, + { path: 'no-eol.jsonl', content: Buffer.from('{"a":1}\n{"a":2}', 'utf8') }, + { path: 'pretty4.json', content: Buffer.from('{\n "a": 1,\n "b": [1.0, -0]\n}\n', 'utf8') }, + { path: 'dup-keys.json', content: Buffer.from('{"k":1,"k":2}\n', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json line\n{broken json\r\n\x00\x01\x02\x1eB:0\x1f@@B64:0@@XDTSHARE\n', 'utf8') }, + { path: 'fake-media.png', content: Buffer.from('actually plain text, not a png\r\n', 'utf8') }, + { path: 'media/tiny.png', content: new Uint8Array(tinyPng) }, + { path: 'sentinel-collide.jsonl', content: Buffer.from(`{"sentinel":"\\u001eB:0\\u001f","raw":"\x1eB:0\x1f","b64":"${tinyPngB64}"}\n`, 'utf8') }, + { path: 'blobs/random-64k.bin', content: highEntropy }, + { path: 'dup/path.txt', content: Buffer.from('version A\n', 'utf8') }, + { path: 'dup/path.txt', content: Buffer.from('version B\r\n', 'utf8') }, + { path: 'dup/path.txt', content: Buffer.from('version A\n', 'utf8') }, + { path: 'views/nonzero-offset.bin', content: offsetView }, + ], + }; + + return [ + { name: 'edge-empty-archive', bundle: emptyBundle }, + { name: 'edge-adversarial-mix', bundle: edgeBundle }, + ]; +} + +const errors = []; +let gate_exact_lossless = false; +let gate_stateless_isolated_decode = false; +let gate_header_and_limits = false; +let archiveBytes = FALLBACK_ARCHIVE_BYTES; +let details = {}; + +const codecPath = path.join(subSrcDir, 'cshare-codec.mjs'); +const [codecMod, corpusMod] = await Promise.all([ + import(pathToFileURL(codecPath).href), + import(pathToFileURL(corpusLoaderPath).href), +]); + +const { + encodeArchive, + decodeArchive, + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, +} = codecMod; +const { + loadCorpus, + measureBundleRawBytes, +} = corpusMod; + +const srcHashesBefore = await snapshotDirHashes(subSrcDir); + +const publicSuite = loadCorpus(publicCorpusPath); +const heldOutSuite = loadCorpus(heldOutCorpusPath); +const adversarialCases = buildAdversarialBundles(createDeterministicRng); + +let headerApiOk = true; +try { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE', 'XDTSHARE_MAGIC export mismatch'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12, 'XDTSHARE_PLAIN_HEADER_LENGTH export mismatch'); + assert.equal(typeof encodeArchive, 'function', 'encodeArchive must be a function'); + assert.equal(typeof decodeArchive, 'function', 'decodeArchive must be a function'); + + // Invalid headers must throw + assert.throws(() => decodeArchive(new Uint8Array(0)), 'must reject 0-byte archive'); + assert.throws(() => decodeArchive(new Uint8Array(11)), 'must reject 11-byte archive'); + assert.throws(() => decodeArchive(Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1')), 'must reject bad magic'); + assert.throws(() => decodeArchive(Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1')), 'must reject headerVersion=2'); + assert.throws(() => decodeArchive(Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1')), 'must reject cipher=1'); +} catch (err) { + headerApiOk = false; + errors.push(`header_api: ${err.message}`); +} + +let losslessOk = true; +let allHeadersOk = headerApiOk; +let determinismOk = true; +let heldOutEncodeMs = 0; +let heldOutDecodeMs = 0; +let heldOutRawTotal = 0; +let heldOutEncodedTotal = 0; +const heldOutEncodedRecords = []; +const perBundleStats = []; + +// 1. Adversarial edge cases +for (const { name, bundle } of adversarialCases) { + try { + const fp = fingerprintBundle(bundle); + const encoded1 = encodeArchive(bundle); + verifyPlainHeader(encoded1, name); + // Input immutability check + assert.deepEqual(fingerprintBundle(bundle), fp, `${name}: encodeArchive mutated input buffers`); + + const encoded2 = encodeArchive(bundle); + if (sha256(encoded1) !== sha256(encoded2)) { + determinismOk = false; + errors.push(`determinism: ${name} produced different bytes across repeated encodes`); + } + + // Decode from a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded1.byteLength + 29); + padded.set(encoded1, 17); + const sliced = padded.subarray(17, 17 + encoded1.byteLength); + const decoded = decodeArchive(sliced); + verifyDecodedMatches(decoded, fp, name); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`edge(${name}): ${err.message}`); + } +} + +// 2. Public corpus round-trip verification +for (const bundle of publicSuite.bundles) { + try { + const fp = fingerprintBundle(bundle); + const encoded = encodeArchive(bundle); + verifyPlainHeader(encoded, `public/${bundle.name}`); + assert.deepEqual(fingerprintBundle(bundle), fp, `public/${bundle.name}: input mutated`); + const decoded = decodeArchive(encoded); + verifyDecodedMatches(decoded, fp, `public/${bundle.name}`); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`public(${bundle.name}): ${err.message}`); + } +} + +// 3. Held-out unseen corpus: measure archive_bytes + encode/decode timings + verify lossless +for (const bundle of heldOutSuite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + heldOutRawTotal += rawBytes; + try { + const fp = fingerprintBundle(bundle); + const t0 = trusted.now(); + const encoded = encodeArchive(bundle); + const encMs = trusted.now() - t0; + heldOutEncodeMs += encMs; + + verifyPlainHeader(encoded, `held-out/${bundle.name}`); + assert.deepEqual(fingerprintBundle(bundle), fp, `held-out/${bundle.name}: input mutated`); + + const t1 = trusted.now(); + const decoded = decodeArchive(encoded); + const decMs = trusted.now() - t1; + heldOutDecodeMs += decMs; + + verifyDecodedMatches(decoded, fp, `held-out/${bundle.name}`); + + heldOutEncodedTotal += encoded.byteLength; + heldOutEncodedRecords.push({ name: bundle.name, encoded, fp }); + perBundleStats.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + encode_ms: Number(encMs.toFixed(1)), + decode_ms: Number(decMs.toFixed(1)), + }); + } catch (err) { + losslessOk = false; + if (/header|magic|cipher|version|Uint8Array/i.test(err.message)) allHeadersOk = false; + errors.push(`held-out(${bundle.name}): ${err.message}`); + } +} + +// Held-out determinism spot check on fork-chain-and-media (bundle index 1) +if (heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + try { + const b1 = heldOutSuite.bundles[1]; + const reEncoded = encodeArchive(b1); + if (sha256(reEncoded) !== sha256(heldOutEncodedRecords[1].encoded)) { + determinismOk = false; + errors.push('determinism: held-out bundle produced different bytes across repeated encodes'); + } + } catch (err) { + determinismOk = false; + errors.push(`determinism: ${err.message}`); + } +} + +// 4. Stateless isolated child-process decode gate +if (heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + // Real path: the permission model checks resolved paths (macOS temp dirs sit behind /var -> /private/var). + const isoRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cshare-iso-decode-'))); + try { + const archiveDir = path.join(isoRoot, 'archives'); + const childWorkDir = path.join(isoRoot, 'child-cwd'); + const childTmpDir = path.join(isoRoot, 'child-tmp'); + await Promise.all([ + fs.mkdir(archiveDir, { recursive: true }), + fs.mkdir(childWorkDir, { recursive: true }), + fs.mkdir(childTmpDir, { recursive: true }), + ]); + + const archivePaths = []; + for (let i = 0; i < heldOutEncodedRecords.length; i++) { + const p = path.join(archiveDir, `bundle-${i}.cshare`); + await fs.writeFile(p, heldOutEncodedRecords[i].encoded); + archivePaths.push(p); + } + const runnerDir = path.join(isoRoot, 'runner'); + const outDir = path.join(isoRoot, 'decoded'); + await Promise.all([fs.mkdir(runnerDir, { recursive: true }), fs.mkdir(outDir, { recursive: true })]); + + // The child only decodes and writes the bytes it produced; the parent compares them with the + // original entries. Under the permission model the child can read nothing but the runner, the + // codec and the archives, so decoding cannot fall back on the corpus files on disk. + const runnerScript = path.join(runnerDir, 'decode-runner.mjs'); + await fs.writeFile( + runnerScript, + [ + "import fs from 'node:fs';", + "import path from 'node:path';", + "import { performance } from 'node:perf_hooks';", + "import { pathToFileURL } from 'node:url';", + "const nonce = fs.readFileSync(0, 'utf8').trim();", + "const readFileSync = fs.readFileSync;", + "const writeFileSync = fs.writeFileSync;", + "const writeSync = fs.writeSync;", + "const join = path.join;", + "const now = performance.now.bind(performance);", + "const concat = Buffer.concat;", + "const stringify = JSON.stringify;", + "const [codecFile, outDir, ...files] = process.argv.slice(2);", + "const { decodeArchive } = await import(pathToFileURL(codecFile).href);", + "let totalDecodeMs = 0;", + "for (let i = 0; i < files.length; i++) {", + " const raw = readFileSync(files[i]);", + " const u8 = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);", + " const t0 = now();", + " const res = decodeArchive(u8);", + " totalDecodeMs += now() - t0;", + " if (!res || res.headerVersion !== 1 || !Array.isArray(res.entries)) {", + " throw new Error('Invalid decoded bundle structure');", + " }", + " const parts = [];", + " const index = res.entries.map((e) => {", + " if (!(e.content instanceof Uint8Array)) throw new Error('Entry content must be Uint8Array');", + " parts.push(e.content);", + " return { path: e.path, bytes: e.content.byteLength };", + " });", + " writeFileSync(join(outDir, `bundle-${i}.json`), stringify({ headerVersion: res.headerVersion, index }));", + " writeFileSync(join(outDir, `bundle-${i}.bin`), concat(parts));", + "}", + "writeSync(1, `EVAL-RESULT ${nonce} ${stringify({ totalDecodeMs })}\\n`);", + ].join('\n'), + 'utf8', + ); + + const realSubSrcDir = await fs.realpath(subSrcDir); + const realCodecPath = path.join(realSubSrcDir, path.relative(subSrcDir, codecPath)); + const sandboxFlags = [ + '--frozen-intrinsics', + PERMISSION_FLAG, + `--allow-fs-read=${runnerDir}`, + `--allow-fs-read=${realSubSrcDir}`, + `--allow-fs-read=${archiveDir}`, + `--allow-fs-write=${outDir}`, + ]; + const stdout = execFileSync(process.execPath, [...sandboxFlags, runnerScript, realCodecPath, outDir, ...archivePaths], { + cwd: childWorkDir, + env: { + PATH: process.env.PATH, + HOME: childTmpDir, + TMPDIR: childTmpDir, + TEMP: childTmpDir, + TMP: childTmpDir, + }, + input: `${childNonce}\n`, + encoding: 'utf8', + timeout: 30_000, + maxBuffer: 32 * 1024 * 1024, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + const tag = `EVAL-RESULT ${childNonce} `; + const tagged = stdout.split('\n').filter((line) => line.startsWith(tag)); + assert.equal(tagged.length, 1, 'isolated decode did not report exactly one authenticated result'); + const parsed = JSON.parse(tagged[0].slice(tag.length)); + for (let i = 0; i < heldOutEncodedRecords.length; i++) { + const name = heldOutEncodedRecords[i].name; + const meta = JSON.parse(await fs.readFile(path.join(outDir, `bundle-${i}.json`), 'utf8')); + const bin = await fs.readFile(path.join(outDir, `bundle-${i}.bin`)); + const original = heldOutSuite.bundles[i].entries; + assert.equal(meta.headerVersion, 1, `isolated decode header on ${name}`); + assert.equal(meta.index.length, original.length, `isolated decode entry count on ${name}`); + let off = 0; + for (let k = 0; k < original.length; k++) { + const want = original[k]; + const wantBytes = typeof want.content === 'string' ? Buffer.from(want.content, 'utf8') : Buffer.from(want.content); + const got = meta.index[k]; + assert.equal(got.path, want.path, `isolated decode path mismatch on ${name}#${k}`); + assert.equal(got.bytes, wantBytes.byteLength, `isolated decode size mismatch on ${name}#${k}`); + assert.equal(bufferCompare(bin.subarray(off, off + got.bytes), wantBytes), 0, `isolated decode content mismatch on ${name}#${k}`); + off += got.bytes; + } + assert.equal(off, bin.byteLength, `isolated decode trailing bytes on ${name}`); + } + + // Ensure subSrcDir was not modified as a side-channel during encode/decode + const srcHashesAfter = await snapshotDirHashes(subSrcDir); + assert.deepEqual(srcHashesAfter, srcHashesBefore, 'submission src/ was mutated during execution'); + + gate_stateless_isolated_decode = true; + details.isolatedDecodeMs = Number(parsed.totalDecodeMs.toFixed(1)); + } catch (err) { + gate_stateless_isolated_decode = false; + const stderrTail = typeof err.stderr === 'string' && err.stderr ? ` | stderr: ${err.stderr.slice(-600)}` : ''; + errors.push(`stateless_decode: ${err.message.split('\n')[0].slice(0, 200)}${stderrTail}`); + } finally { + await fs.rm(isoRoot, { recursive: true, force: true }); + } +} + +const limitsOk = + heldOutEncodedRecords.length === heldOutSuite.bundles.length && + heldOutEncodeMs <= ENCODE_LIMIT_MS && + heldOutDecodeMs <= DECODE_LIMIT_MS; + +if (!limitsOk && heldOutEncodedRecords.length === heldOutSuite.bundles.length) { + errors.push( + `limits: encode=${heldOutEncodeMs.toFixed(1)}ms (limit ${ENCODE_LIMIT_MS}ms), decode=${heldOutDecodeMs.toFixed(1)}ms (limit ${DECODE_LIMIT_MS}ms)`, + ); +} + +gate_exact_lossless = losslessOk && heldOutEncodedRecords.length === heldOutSuite.bundles.length; +gate_header_and_limits = allHeadersOk && determinismOk && limitsOk; +archiveBytes = + heldOutEncodedRecords.length === heldOutSuite.bundles.length && Number.isInteger(heldOutEncodedTotal) && heldOutEncodedTotal > 0 + ? heldOutEncodedTotal + : FALLBACK_ARCHIVE_BYTES; + +details = { + ...details, + heldOutRawBytes: heldOutRawTotal, + heldOutArchiveBytes: archiveBytes, + heldOutEncodeMs: Number(heldOutEncodeMs.toFixed(1)), + heldOutDecodeMs: Number(heldOutDecodeMs.toFixed(1)), + bundles: perBundleStats, + errors, +}; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_lossless, + gate_stateless_isolated_decode, + gate_header_and_limits, + }, + metrics: { + archive_bytes: archiveBytes, + }, + details, +})); diff --git a/questions/opt-cshare-compression/v2/author/grade.py b/questions/opt-cshare-compression/v2/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/opt-cshare-compression/v2/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-cshare-compression/v2/author/grade_impl.py b/questions/opt-cshare-compression/v2/author/grade_impl.py new file mode 100644 index 0000000..e5519b1 --- /dev/null +++ b/questions/opt-cshare-compression/v2/author/grade_impl.py @@ -0,0 +1,47 @@ +"""Isolated pure-Node quantitative grader for opt-cshare-compression.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + src_dir = submission_root / 'src' + if not src_dir.is_dir(): + return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'} + + with tempfile.TemporaryDirectory(prefix='eval-cshare-opt-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(src_dir, sub_src) + loader = Q / 'candidate' / 'lib' / 'corpus.mjs' + public = Q / 'candidate' / 'corpus' / 'public.json.br' + heldout = HERE / 'heldout' / 'heldout.json.br' + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src), str(loader), str(public), str(heldout)], + input=nonce + '\n', capture_output=True, text=True, timeout=270 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-cshare-compression/v2/author/heldout/heldout.json.br b/questions/opt-cshare-compression/v2/author/heldout/heldout.json.br new file mode 100644 index 0000000..cfeb887 Binary files /dev/null and b/questions/opt-cshare-compression/v2/author/heldout/heldout.json.br differ diff --git a/questions/opt-cshare-compression/v2/author/result-channel.mjs b/questions/opt-cshare-compression/v2/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-cshare-compression/v2/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-cshare-compression/v2/candidate/CONTRACT.md b/questions/opt-cshare-compression/v2/candidate/CONTRACT.md new file mode 100644 index 0000000..48f0349 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/CONTRACT.md @@ -0,0 +1,64 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Time budget (held-out total: 13 bundles, about 12 MB raw)**, measured on the grading machine. It reflects the product budget of exporting about 1 MB of session data in roughly 2 seconds and importing it in roughly 1 second: + - Total `encodeArchive` time: `<= 24,000 ms` + - Total `decodeArchive` time: `<= 12,000 ms` + +## 5. Corpus Provenance and De-identification + +Both the public and the held-out corpus are real exports rebuilt from the exporter's layout (`scripts/build-real-cshare-corpus.py` in the question bank) and de-identified (`scripts/scrub-real-cshare-corpus.py`) before publication: + +- Harness-injected instruction text (system and developer prompts, tool, skill and agent listings, injected session and environment context) is replaced line by line with surrogate text of the same shape: same length, whitespace, punctuation and script, seeded by a keyed hash of the whole line, so identical lines stay identical within a corpus. Every non-empty line of an injected block is replaced, short ones included; a short value that stands alone (under 16 characters, such as a JSON Schema type, an enum value or a tool name) is kept so the record structure stays real. Model output, tool calls and results and task prompts are real. +- Local paths, the OS user name, e-mail addresses and account identifiers are rewritten to neutral values of the same shape; the time zone is set to UTC. +- The public and held-out corpora use different keys, and come from different tasks. + +The corpus is the measured workload; it is not something to special-case. Decoding must not depend on any data outside the archive bytes. diff --git a/questions/opt-cshare-compression/v2/candidate/ENVIRONMENT.md b/questions/opt-cshare-compression/v2/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..2ee83cf --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. `zlib.deflateRawSync`, `zlib.gzipSync` and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` exists without checking first. +- Platform: cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Corpus and evaluation: + - `npm run bench` measures the 13 public real exports in `corpus/public.json.br` (loaded by `lib/corpus.mjs`). + - Official grading checks bit-exact lossless round-trips (public corpus, held-out corpus and adversarial edge cases), stateless decoding in an isolated child process, header handling, determinism and the time budget, then reports total `archive_bytes` over the **unseen held-out set of 13 real exports** from different tasks. +- Public checks: + - `npm test` — header validation, adversarial edge cases and lossless round-trip of the public corpus + - `npm run bench` — raw size, `archive_bytes`, compression ratio and encode/decode timings on the public corpus diff --git a/questions/opt-cshare-compression/v2/candidate/TASK.md b/questions/opt-cshare-compression/v2/candidate/TASK.md new file mode 100644 index 0000000..6b1fd51 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/TASK.md @@ -0,0 +1,34 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). Users export a task to share it or to move it to another device; smaller archives upload, sync and import faster. + +## What the real archives look like + +`corpus/public.json.br` holds 13 real session exports (13.4 MB raw), rebuilt with the exporter's exact entry layout from real Cindy sessions in which Claude Code, Codex and a plugin engine (Gemini) worked on open-source code. Each bundle contains, in the exporter's order: + +- `session.json` — pretty-printed session snapshot. +- `messages.jsonl` — Cindy's own database rows for the task (user prompts, tool calls with results, assistant text, per-turn usage metadata). Much of it repeats what the native transcript already holds, in a different JSON shape. +- `transcripts/claude/.jsonl` (Claude Code) or `transcripts/codex/rollout-*.jsonl` plus `codex-state/thread.json` (Codex) — the engine's native log: every message, tool call and result, periodic prompt and tool-listing snapshots, API request records, usage counters. Plugin-engine tasks have no native log (database rows only). +- `media-map.json` and `manifest.json` (entry sizes and SHA-256 digests). + +Assistant thinking blocks carry vendor-encrypted signatures (long base64 strings); they must survive byte-exactly. + +The current exporter writes a zip with per-entry DEFLATE level 6, reproduced by the baseline codec here. Nothing is shared across entries, so the long-range redundancy between `messages.jsonl` and the native transcript, and the repeated prompt snapshots inside a transcript, are paid for again and again. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header. Everything from byte 12 onward is your own lossless format. +- Guarantee **bit-exact lossless round-trip** (`headerVersion`, entry count, entry order, UTF-8 paths and contents) for every valid bundle and for arbitrary binary / malformed edge cases. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must work in a fresh isolated Node.js process given only the archive bytes. +- **Open-ended goal**: minimize the total encoded `archive_bytes` on an **unseen held-out set of real exports** from different tasks, using only Node.js built-ins, within the time budget in `CONTRACT.md` §4. +- The held-out exports were de-identified with a different key, so harness text and pseudonymous identifiers differ from the public corpus: dictionaries copied from the public corpus will not transfer. General techniques will. +- Run `npm test` and `npm run bench` to verify correctness and compare sizes before and after your changes. +- Record your analysis, format design, trade-offs and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v2/candidate/bench/workload.mjs b/questions/opt-cshare-compression/v2/candidate/bench/workload.mjs new file mode 100644 index 0000000..a391ed6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { loadPublicCorpus, measureBundleRawBytes } from '../lib/corpus.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = loadPublicCorpus(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v2/candidate/corpus/public.json.br b/questions/opt-cshare-compression/v2/candidate/corpus/public.json.br new file mode 100644 index 0000000..586e04b Binary files /dev/null and b/questions/opt-cshare-compression/v2/candidate/corpus/public.json.br differ diff --git a/questions/opt-cshare-compression/v2/candidate/lib/corpus.mjs b/questions/opt-cshare-compression/v2/candidate/lib/corpus.mjs new file mode 100644 index 0000000..f26d840 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/lib/corpus.mjs @@ -0,0 +1,37 @@ +import fs from 'node:fs'; +import zlib from 'node:zlib'; + +/** + * Loads a packed corpus of real `.cshare` bundles. + * + * Each bundle is the exact entry list that Cindy's desktop exporter writes into one session + * archive (session.json, messages.jsonl, native transcripts, codex-state, media-map.json, + * manifest.json), rebuilt from real sessions and de-identified (see CONTRACT.md §5). + * + * Returns { suiteName, bundles: [{ name, agentKind, model, headerVersion: 1, + * entries: [{ path, content: Uint8Array }] }] }. + */ +export function loadCorpus(file) { + const json = JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); + return { + suiteName: json.suite, + bundles: json.bundles.map((b) => ({ + name: b.name, + agentKind: b.agentKind, + model: b.model, + headerVersion: 1, + entries: b.entries.map((e) => { + const buf = Buffer.from(e.text, 'utf8'); + return { path: e.path, content: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) }; + }), + })), + }; +} + +export function loadPublicCorpus() { + return loadCorpus(new URL('../corpus/public.json.br', import.meta.url)); +} + +export function measureBundleRawBytes(bundle) { + return bundle.entries.reduce((sum, e) => sum + e.content.byteLength, 0); +} diff --git a/questions/opt-cshare-compression/v2/candidate/package.json b/questions/opt-cshare-compression/v2/candidate/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v2/candidate/src/container.mjs b/questions/opt-cshare-compression/v2/candidate/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v2/candidate/src/cshare-codec.mjs b/questions/opt-cshare-compression/v2/candidate/src/cshare-codec.mjs new file mode 100644 index 0000000..ae57561 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/src/cshare-codec.mjs @@ -0,0 +1,88 @@ +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +/** + * Baseline Cindy `.cshare` codec: + * Per-entry raw DEFLATE (level 6), no cross-file solid compression, + * no media deduplication, compresses binary media entries identically to text. + */ +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const headerVersion = bundle.headerVersion ?? XDTSHARE_HEADER_VERSION; + const header = encodePlainHeader(headerVersion); + + const countBuf = Buffer.alloc(4); + countBuf.writeUInt32LE(bundle.entries.length, 0); + + const chunks = [header, countBuf]; + for (const entry of bundle.entries) { + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const pathBuf = Buffer.from(entry.path, 'utf8'); + const rawBuf = toBufferView(entry.content); + const compressed = zlib.deflateRawSync(rawBuf, { level: 6 }); + + const meta = Buffer.alloc(12); + meta.writeUInt32LE(pathBuf.length, 0); + meta.writeUInt32LE(rawBuf.length, 4); + meta.writeUInt32LE(compressed.length, 8); + chunks.push(meta, pathBuf, compressed); + } + + const out = Buffer.concat(chunks); + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + if (payload.length < 4) { + throw new Error('Truncated archive payload'); + } + const entryCount = payload.readUInt32LE(0); + let offset = 4; + const entries = new Array(entryCount); + + for (let i = 0; i < entryCount; i++) { + if (offset + 12 > payload.length) { + throw new Error(`Truncated entry header at index ${i}`); + } + const pathLen = payload.readUInt32LE(offset); + const rawLen = payload.readUInt32LE(offset + 4); + const compLen = payload.readUInt32LE(offset + 8); + offset += 12; + + if (offset + pathLen + compLen > payload.length) { + throw new Error(`Truncated entry data at index ${i}`); + } + const entryPath = payload.toString('utf8', offset, offset + pathLen); + offset += pathLen; + const compSlice = payload.subarray(offset, offset + compLen); + offset += compLen; + + const inflated = zlib.inflateRawSync(compSlice); + if (inflated.length !== rawLen) { + throw new Error(`Size mismatch for ${entryPath}: expected ${rawLen}, got ${inflated.length}`); + } + entries[i] = { + path: entryPath, + content: new Uint8Array(inflated.buffer, inflated.byteOffset, inflated.byteLength), + }; + } + + if (offset !== payload.length) { + throw new Error(`Unexpected trailing bytes: ${payload.length - offset}`); + } + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v2/candidate/tests/smoke.test.mjs b/questions/opt-cshare-compression/v2/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..e8f6708 --- /dev/null +++ b/questions/opt-cshare-compression/v2/candidate/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { loadPublicCorpus } from '../lib/corpus.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = loadPublicCorpus(); + assert.equal(suite.bundles.length, 13); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/CONTRACT.md b/questions/opt-cshare-compression/v2/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..48f0349 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/CONTRACT.md @@ -0,0 +1,64 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Time budget (held-out total: 13 bundles, about 12 MB raw)**, measured on the grading machine. It reflects the product budget of exporting about 1 MB of session data in roughly 2 seconds and importing it in roughly 1 second: + - Total `encodeArchive` time: `<= 24,000 ms` + - Total `decodeArchive` time: `<= 12,000 ms` + +## 5. Corpus Provenance and De-identification + +Both the public and the held-out corpus are real exports rebuilt from the exporter's layout (`scripts/build-real-cshare-corpus.py` in the question bank) and de-identified (`scripts/scrub-real-cshare-corpus.py`) before publication: + +- Harness-injected instruction text (system and developer prompts, tool, skill and agent listings, injected session and environment context) is replaced line by line with surrogate text of the same shape: same length, whitespace, punctuation and script, seeded by a keyed hash of the whole line, so identical lines stay identical within a corpus. Every non-empty line of an injected block is replaced, short ones included; a short value that stands alone (under 16 characters, such as a JSON Schema type, an enum value or a tool name) is kept so the record structure stays real. Model output, tool calls and results and task prompts are real. +- Local paths, the OS user name, e-mail addresses and account identifiers are rewritten to neutral values of the same shape; the time zone is set to UTC. +- The public and held-out corpora use different keys, and come from different tasks. + +The corpus is the measured workload; it is not something to special-case. Decoding must not depend on any data outside the archive bytes. diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/ENVIRONMENT.md b/questions/opt-cshare-compression/v2/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..2ee83cf --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. `zlib.deflateRawSync`, `zlib.gzipSync` and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` exists without checking first. +- Platform: cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Corpus and evaluation: + - `npm run bench` measures the 13 public real exports in `corpus/public.json.br` (loaded by `lib/corpus.mjs`). + - Official grading checks bit-exact lossless round-trips (public corpus, held-out corpus and adversarial edge cases), stateless decoding in an isolated child process, header handling, determinism and the time budget, then reports total `archive_bytes` over the **unseen held-out set of 13 real exports** from different tasks. +- Public checks: + - `npm test` — header validation, adversarial edge cases and lossless round-trip of the public corpus + - `npm run bench` — raw size, `archive_bytes`, compression ratio and encode/decode timings on the public corpus diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/TASK.md b/questions/opt-cshare-compression/v2/controls/incomplete/TASK.md new file mode 100644 index 0000000..6b1fd51 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/TASK.md @@ -0,0 +1,34 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). Users export a task to share it or to move it to another device; smaller archives upload, sync and import faster. + +## What the real archives look like + +`corpus/public.json.br` holds 13 real session exports (13.4 MB raw), rebuilt with the exporter's exact entry layout from real Cindy sessions in which Claude Code, Codex and a plugin engine (Gemini) worked on open-source code. Each bundle contains, in the exporter's order: + +- `session.json` — pretty-printed session snapshot. +- `messages.jsonl` — Cindy's own database rows for the task (user prompts, tool calls with results, assistant text, per-turn usage metadata). Much of it repeats what the native transcript already holds, in a different JSON shape. +- `transcripts/claude/.jsonl` (Claude Code) or `transcripts/codex/rollout-*.jsonl` plus `codex-state/thread.json` (Codex) — the engine's native log: every message, tool call and result, periodic prompt and tool-listing snapshots, API request records, usage counters. Plugin-engine tasks have no native log (database rows only). +- `media-map.json` and `manifest.json` (entry sizes and SHA-256 digests). + +Assistant thinking blocks carry vendor-encrypted signatures (long base64 strings); they must survive byte-exactly. + +The current exporter writes a zip with per-entry DEFLATE level 6, reproduced by the baseline codec here. Nothing is shared across entries, so the long-range redundancy between `messages.jsonl` and the native transcript, and the repeated prompt snapshots inside a transcript, are paid for again and again. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header. Everything from byte 12 onward is your own lossless format. +- Guarantee **bit-exact lossless round-trip** (`headerVersion`, entry count, entry order, UTF-8 paths and contents) for every valid bundle and for arbitrary binary / malformed edge cases. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must work in a fresh isolated Node.js process given only the archive bytes. +- **Open-ended goal**: minimize the total encoded `archive_bytes` on an **unseen held-out set of real exports** from different tasks, using only Node.js built-ins, within the time budget in `CONTRACT.md` §4. +- The held-out exports were de-identified with a different key, so harness text and pseudonymous identifiers differ from the public corpus: dictionaries copied from the public corpus will not transfer. General techniques will. +- Run `npm test` and `npm run bench` to verify correctness and compare sizes before and after your changes. +- Record your analysis, format design, trade-offs and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/bench/workload.mjs b/questions/opt-cshare-compression/v2/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..a391ed6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { loadPublicCorpus, measureBundleRawBytes } from '../lib/corpus.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = loadPublicCorpus(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/corpus/public.json.br b/questions/opt-cshare-compression/v2/controls/incomplete/corpus/public.json.br new file mode 100644 index 0000000..586e04b Binary files /dev/null and b/questions/opt-cshare-compression/v2/controls/incomplete/corpus/public.json.br differ diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/lib/corpus.mjs b/questions/opt-cshare-compression/v2/controls/incomplete/lib/corpus.mjs new file mode 100644 index 0000000..f26d840 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/lib/corpus.mjs @@ -0,0 +1,37 @@ +import fs from 'node:fs'; +import zlib from 'node:zlib'; + +/** + * Loads a packed corpus of real `.cshare` bundles. + * + * Each bundle is the exact entry list that Cindy's desktop exporter writes into one session + * archive (session.json, messages.jsonl, native transcripts, codex-state, media-map.json, + * manifest.json), rebuilt from real sessions and de-identified (see CONTRACT.md §5). + * + * Returns { suiteName, bundles: [{ name, agentKind, model, headerVersion: 1, + * entries: [{ path, content: Uint8Array }] }] }. + */ +export function loadCorpus(file) { + const json = JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); + return { + suiteName: json.suite, + bundles: json.bundles.map((b) => ({ + name: b.name, + agentKind: b.agentKind, + model: b.model, + headerVersion: 1, + entries: b.entries.map((e) => { + const buf = Buffer.from(e.text, 'utf8'); + return { path: e.path, content: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) }; + }), + })), + }; +} + +export function loadPublicCorpus() { + return loadCorpus(new URL('../corpus/public.json.br', import.meta.url)); +} + +export function measureBundleRawBytes(bundle) { + return bundle.entries.reduce((sum, e) => sum + e.content.byteLength, 0); +} diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/package.json b/questions/opt-cshare-compression/v2/controls/incomplete/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/src/container.mjs b/questions/opt-cshare-compression/v2/controls/incomplete/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/src/cshare-codec.mjs b/questions/opt-cshare-compression/v2/controls/incomplete/src/cshare-codec.mjs new file mode 100644 index 0000000..c2b5c1b --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/src/cshare-codec.mjs @@ -0,0 +1,87 @@ +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +/** + * Partial improvement: per-entry Brotli instead of DEFLATE, still no cross-file + * solid compression, so redundancy between entries is not exploited. + */ +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const headerVersion = bundle.headerVersion ?? XDTSHARE_HEADER_VERSION; + const header = encodePlainHeader(headerVersion); + + const countBuf = Buffer.alloc(4); + countBuf.writeUInt32LE(bundle.entries.length, 0); + + const chunks = [header, countBuf]; + for (const entry of bundle.entries) { + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const pathBuf = Buffer.from(entry.path, 'utf8'); + const rawBuf = toBufferView(entry.content); + const compressed = zlib.brotliCompressSync(rawBuf, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 9, [zlib.constants.BROTLI_PARAM_LGWIN]: 22, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: rawBuf.length } }); + + const meta = Buffer.alloc(12); + meta.writeUInt32LE(pathBuf.length, 0); + meta.writeUInt32LE(rawBuf.length, 4); + meta.writeUInt32LE(compressed.length, 8); + chunks.push(meta, pathBuf, compressed); + } + + const out = Buffer.concat(chunks); + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + if (payload.length < 4) { + throw new Error('Truncated archive payload'); + } + const entryCount = payload.readUInt32LE(0); + let offset = 4; + const entries = new Array(entryCount); + + for (let i = 0; i < entryCount; i++) { + if (offset + 12 > payload.length) { + throw new Error(`Truncated entry header at index ${i}`); + } + const pathLen = payload.readUInt32LE(offset); + const rawLen = payload.readUInt32LE(offset + 4); + const compLen = payload.readUInt32LE(offset + 8); + offset += 12; + + if (offset + pathLen + compLen > payload.length) { + throw new Error(`Truncated entry data at index ${i}`); + } + const entryPath = payload.toString('utf8', offset, offset + pathLen); + offset += pathLen; + const compSlice = payload.subarray(offset, offset + compLen); + offset += compLen; + + const inflated = zlib.brotliDecompressSync(compSlice); + if (inflated.length !== rawLen) { + throw new Error(`Size mismatch for ${entryPath}: expected ${rawLen}, got ${inflated.length}`); + } + entries[i] = { + path: entryPath, + content: new Uint8Array(inflated.buffer, inflated.byteOffset, inflated.byteLength), + }; + } + + if (offset !== payload.length) { + throw new Error(`Unexpected trailing bytes: ${payload.length - offset}`); + } + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v2/controls/incomplete/tests/smoke.test.mjs b/questions/opt-cshare-compression/v2/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..e8f6708 --- /dev/null +++ b/questions/opt-cshare-compression/v2/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { loadPublicCorpus } from '../lib/corpus.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = loadPublicCorpus(); + assert.equal(suite.bundles.length, 13); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-cshare-compression/v2/question.json b/questions/opt-cshare-compression/v2/question.json new file mode 100644 index 0000000..0107a25 --- /dev/null +++ b/questions/opt-cshare-compression/v2/question.json @@ -0,0 +1,40 @@ +{ + "id": "opt-cshare-compression", + "revision": "v2", + "scoringVersion": "metric-v1", + "title": ".cshare 会话归档极限无损压缩优化", + "status": "calibrated", + "changeNote": "v2: replaces the synthetic generator with real exports. 26 real Cindy sessions (Claude Code, Codex and a plugin engine working on open-source code) are rebuilt with the desktop exporter's entry layout and de-identified (harness prompt text replaced line by line with same-shape surrogate text; paths, user name, e-mail and account ids pseudonymized). 13 public / 13 held-out from different tasks and surrogate keys. Baseline = per-entry DEFLATE-6 on the held-out set; target = vendor-encrypted signatures as raw binary (unique, incompressible) plus the rest 25% below solid Brotli-11. Time budget 24 s encode / 12 s decode for ~12 MB.", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "compression_ratio", + "weight": "1", + "mode": "metric", + "gate": [ + "gate_exact_lossless", + "gate_stateless_isolated_decode", + "gate_header_and_limits" + ], + "metric": { + "id": "archive_bytes", + "label": "Held-out real .cshare total size", + "unit": "B", + "direction": "lower", + "baseline": 3398503, + "target": 1670000, + "scale": "log" + } + } + ] +} diff --git a/questions/opt-cshare-compression/v2/reference/CONTRACT.md b/questions/opt-cshare-compression/v2/reference/CONTRACT.md new file mode 100644 index 0000000..48f0349 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/CONTRACT.md @@ -0,0 +1,64 @@ +# Codec & Container Contract + +This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold. + +## 1. Public Module Interface (`src/cshare-codec.mjs`) + +Must export: +- `XDTSHARE_MAGIC = 'XDTSHARE'` +- `XDTSHARE_PLAIN_HEADER_LENGTH = 12` +- `encodeArchive(bundle)`: + - Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`). + - Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header. + - Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers. + - Must be deterministic: encoding the same bundle twice must produce identical archive bytes. +- `decodeArchive(bytes)`: + - Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`. + - Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`. + - Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`. + +## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes) + +| Offset | Length | Field | Required Value | +| --- | --- | --- | --- | +| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) | +| `8` | `1` | `headerVersion` | `1` (`u8`) | +| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) | +| `10` | `2` | `reserved` | `0x00, 0x00` | +| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format | + +## 3. Bit-Exact Lossless Correctness Invariants + +For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve: +1. `headerVersion === 1` +2. Exact entry count (`decoded.entries.length === bundle.entries.length`) +3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`) +4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`) + +This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs: +- Empty archives (`entries: []`) +- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`) +- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl` +- UTF-8 CJK and emoji characters in both `path` and `content` +- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters) +- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png` +- High-entropy incompressible random buffers +- Duplicate entry paths (both with identical contents and with distinct contents) in their original order + +## 4. Stateless Isolated Decode & Runtime Bounds + +- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode. +- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback. +- **Time budget (held-out total: 13 bundles, about 12 MB raw)**, measured on the grading machine. It reflects the product budget of exporting about 1 MB of session data in roughly 2 seconds and importing it in roughly 1 second: + - Total `encodeArchive` time: `<= 24,000 ms` + - Total `decodeArchive` time: `<= 12,000 ms` + +## 5. Corpus Provenance and De-identification + +Both the public and the held-out corpus are real exports rebuilt from the exporter's layout (`scripts/build-real-cshare-corpus.py` in the question bank) and de-identified (`scripts/scrub-real-cshare-corpus.py`) before publication: + +- Harness-injected instruction text (system and developer prompts, tool, skill and agent listings, injected session and environment context) is replaced line by line with surrogate text of the same shape: same length, whitespace, punctuation and script, seeded by a keyed hash of the whole line, so identical lines stay identical within a corpus. Every non-empty line of an injected block is replaced, short ones included; a short value that stands alone (under 16 characters, such as a JSON Schema type, an enum value or a tool name) is kept so the record structure stays real. Model output, tool calls and results and task prompts are real. +- Local paths, the OS user name, e-mail addresses and account identifiers are rewritten to neutral values of the same shape; the time zone is set to UTC. +- The public and held-out corpora use different keys, and come from different tasks. + +The corpus is the measured workload; it is not something to special-case. Decoding must not depend on any data outside the archive bytes. diff --git a/questions/opt-cshare-compression/v2/reference/ENVIRONMENT.md b/questions/opt-cshare-compression/v2/reference/ENVIRONMENT.md new file mode 100644 index 0000000..2ee83cf --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/ENVIRONMENT.md @@ -0,0 +1,12 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. `zlib.deflateRawSync`, `zlib.gzipSync` and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` exists without checking first. +- Platform: cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Corpus and evaluation: + - `npm run bench` measures the 13 public real exports in `corpus/public.json.br` (loaded by `lib/corpus.mjs`). + - Official grading checks bit-exact lossless round-trips (public corpus, held-out corpus and adversarial edge cases), stateless decoding in an isolated child process, header handling, determinism and the time budget, then reports total `archive_bytes` over the **unseen held-out set of 13 real exports** from different tasks. +- Public checks: + - `npm test` — header validation, adversarial edge cases and lossless round-trip of the public corpus + - `npm run bench` — raw size, `archive_bytes`, compression ratio and encode/decode timings on the public corpus diff --git a/questions/opt-cshare-compression/v2/reference/TASK.md b/questions/opt-cshare-compression/v2/reference/TASK.md new file mode 100644 index 0000000..6b1fd51 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/TASK.md @@ -0,0 +1,34 @@ +# Task + +You are optimizing Cindy's `.cshare` session-archive codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`). Users export a task to share it or to move it to another device; smaller archives upload, sync and import faster. + +## What the real archives look like + +`corpus/public.json.br` holds 13 real session exports (13.4 MB raw), rebuilt with the exporter's exact entry layout from real Cindy sessions in which Claude Code, Codex and a plugin engine (Gemini) worked on open-source code. Each bundle contains, in the exporter's order: + +- `session.json` — pretty-printed session snapshot. +- `messages.jsonl` — Cindy's own database rows for the task (user prompts, tool calls with results, assistant text, per-turn usage metadata). Much of it repeats what the native transcript already holds, in a different JSON shape. +- `transcripts/claude/.jsonl` (Claude Code) or `transcripts/codex/rollout-*.jsonl` plus `codex-state/thread.json` (Codex) — the engine's native log: every message, tool call and result, periodic prompt and tool-listing snapshots, API request records, usage counters. Plugin-engine tasks have no native log (database rows only). +- `media-map.json` and `manifest.json` (entry sizes and SHA-256 digests). + +Assistant thinking blocks carry vendor-encrypted signatures (long base64 strings); they must survive byte-exactly. + +The current exporter writes a zip with per-entry DEFLATE level 6, reproduced by the baseline codec here. Nothing is shared across entries, so the long-range redundancy between `messages.jsonl` and the native transcript, and the repeated prompt snapshots inside a transcript, are paid for again and again. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve the required public API in `src/cshare-codec.mjs`: + - `XDTSHARE_MAGIC` (`'XDTSHARE'`) + - `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`) + - `encodeArchive(bundle)` → `Uint8Array` + - `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }` +- Preserve the exact 12-byte outer `XDTSHARE` plain header. Everything from byte 12 onward is your own lossless format. +- Guarantee **bit-exact lossless round-trip** (`headerVersion`, entry count, entry order, UTF-8 paths and contents) for every valid bundle and for arbitrary binary / malformed edge cases. +- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must work in a fresh isolated Node.js process given only the archive bytes. +- **Open-ended goal**: minimize the total encoded `archive_bytes` on an **unseen held-out set of real exports** from different tasks, using only Node.js built-ins, within the time budget in `CONTRACT.md` §4. +- The held-out exports were de-identified with a different key, so harness text and pseudonymous identifiers differ from the public corpus: dictionaries copied from the public corpus will not transfer. General techniques will. +- Run `npm test` and `npm run bench` to verify correctness and compare sizes before and after your changes. +- Record your analysis, format design, trade-offs and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-cshare-compression/v2/reference/bench/workload.mjs b/questions/opt-cshare-compression/v2/reference/bench/workload.mjs new file mode 100644 index 0000000..a391ed6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/bench/workload.mjs @@ -0,0 +1,80 @@ +import crypto from 'node:crypto'; +import { performance } from 'node:perf_hooks'; + +import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs'; +import { loadPublicCorpus, measureBundleRawBytes } from '../lib/corpus.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +export function runPublicBenchmark() { + const suite = loadPublicCorpus(); + const perBundle = []; + let totalRawBytes = 0; + let totalArchiveBytes = 0; + let totalEncodeMs = 0; + let totalDecodeMs = 0; + + for (const bundle of suite.bundles) { + const rawBytes = measureBundleRawBytes(bundle); + const t0 = performance.now(); + const encoded = encodeArchive(bundle); + const encodeMs = performance.now() - t0; + + const t1 = performance.now(); + const decoded = decodeArchive(encoded); + const decodeMs = performance.now() - t1; + + if (decoded.entries.length !== bundle.entries.length) { + throw new Error(`Entry count mismatch on ${bundle.name}`); + } + for (let i = 0; i < bundle.entries.length; i++) { + if (decoded.entries[i].path !== bundle.entries[i].path) { + throw new Error(`Path mismatch at ${bundle.name}[${i}]`); + } + if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) { + throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`); + } + } + + totalRawBytes += rawBytes; + totalArchiveBytes += encoded.byteLength; + totalEncodeMs += encodeMs; + totalDecodeMs += decodeMs; + + perBundle.push({ + name: bundle.name, + entries: bundle.entries.length, + raw_bytes: rawBytes, + archive_bytes: encoded.byteLength, + ratio: Number((rawBytes / encoded.byteLength).toFixed(2)), + encode_ms: Number(encodeMs.toFixed(1)), + decode_ms: Number(decodeMs.toFixed(1)), + }); + } + + return { + suite: suite.suiteName, + raw_bytes: totalRawBytes, + archive_bytes: totalArchiveBytes, + compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)), + encode_ms: Number(totalEncodeMs.toFixed(1)), + decode_ms: Number(totalDecodeMs.toFixed(1)), + bundles: perBundle, + }; +} + +if (isMainModule()) { + console.log(JSON.stringify(runPublicBenchmark(), null, 2)); +} diff --git a/questions/opt-cshare-compression/v2/reference/corpus/public.json.br b/questions/opt-cshare-compression/v2/reference/corpus/public.json.br new file mode 100644 index 0000000..586e04b Binary files /dev/null and b/questions/opt-cshare-compression/v2/reference/corpus/public.json.br differ diff --git a/questions/opt-cshare-compression/v2/reference/lib/corpus.mjs b/questions/opt-cshare-compression/v2/reference/lib/corpus.mjs new file mode 100644 index 0000000..f26d840 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/lib/corpus.mjs @@ -0,0 +1,37 @@ +import fs from 'node:fs'; +import zlib from 'node:zlib'; + +/** + * Loads a packed corpus of real `.cshare` bundles. + * + * Each bundle is the exact entry list that Cindy's desktop exporter writes into one session + * archive (session.json, messages.jsonl, native transcripts, codex-state, media-map.json, + * manifest.json), rebuilt from real sessions and de-identified (see CONTRACT.md §5). + * + * Returns { suiteName, bundles: [{ name, agentKind, model, headerVersion: 1, + * entries: [{ path, content: Uint8Array }] }] }. + */ +export function loadCorpus(file) { + const json = JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); + return { + suiteName: json.suite, + bundles: json.bundles.map((b) => ({ + name: b.name, + agentKind: b.agentKind, + model: b.model, + headerVersion: 1, + entries: b.entries.map((e) => { + const buf = Buffer.from(e.text, 'utf8'); + return { path: e.path, content: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) }; + }), + })), + }; +} + +export function loadPublicCorpus() { + return loadCorpus(new URL('../corpus/public.json.br', import.meta.url)); +} + +export function measureBundleRawBytes(bundle) { + return bundle.entries.reduce((sum, e) => sum + e.content.byteLength, 0); +} diff --git a/questions/opt-cshare-compression/v2/reference/package.json b/questions/opt-cshare-compression/v2/reference/package.json new file mode 100644 index 0000000..3ddc7e4 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-cshare-compression", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-cshare-compression/v2/reference/src/container.mjs b/questions/opt-cshare-compression/v2/reference/src/container.mjs new file mode 100644 index 0000000..9df1af6 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/src/container.mjs @@ -0,0 +1,55 @@ +/** + * Outer XDTSHARE plain header framing (pure helpers, zero IO). + * + * Layout (12 bytes): + * 0..7 ASCII "XDTSHARE" + * 8 headerVersion = 1 (uint8) + * 9 cipher = 0 (uint8, plaintext) + * 10..11 reserved = 0x0000 (uint16) + */ + +export const XDTSHARE_MAGIC = 'XDTSHARE'; +export const XDTSHARE_HEADER_VERSION = 1; +export const XDTSHARE_PLAIN_HEADER_LENGTH = 12; + +export function toBufferView(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array or Buffer'); + } + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +export function encodePlainHeader(headerVersion = XDTSHARE_HEADER_VERSION) { + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported headerVersion: ${headerVersion}`); + } + const header = Buffer.alloc(XDTSHARE_PLAIN_HEADER_LENGTH); + header.write(XDTSHARE_MAGIC, 0, 'ascii'); + header.writeUInt8(headerVersion, 8); + header.writeUInt8(0, 9); + header.writeUInt16BE(0, 10); + return header; +} + +export function parsePlainHeader(bytes) { + const buf = toBufferView(bytes); + if (buf.length < XDTSHARE_PLAIN_HEADER_LENGTH) { + throw new Error('Archive too short for XDTSHARE header'); + } + if (buf.toString('ascii', 0, 8) !== XDTSHARE_MAGIC) { + throw new Error('Invalid XDTSHARE magic'); + } + const headerVersion = buf.readUInt8(8); + if (headerVersion !== XDTSHARE_HEADER_VERSION) { + throw new Error(`Unsupported XDTSHARE headerVersion: ${headerVersion}`); + } + const cipher = buf.readUInt8(9); + if (cipher !== 0) { + throw new Error(`Unsupported XDTSHARE cipher: ${cipher}`); + } + return { + headerVersion, + cipher, + payload: buf.subarray(XDTSHARE_PLAIN_HEADER_LENGTH), + }; +} diff --git a/questions/opt-cshare-compression/v2/reference/src/cshare-codec.mjs b/questions/opt-cshare-compression/v2/reference/src/cshare-codec.mjs new file mode 100644 index 0000000..f6a5e19 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/src/cshare-codec.mjs @@ -0,0 +1,83 @@ +import zlib from 'node:zlib'; +import { + XDTSHARE_MAGIC, + XDTSHARE_HEADER_VERSION, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodePlainHeader, + parsePlainHeader, + toBufferView, +} from './container.mjs'; + +export { XDTSHARE_MAGIC, XDTSHARE_PLAIN_HEADER_LENGTH }; + +/** + * Reference codec: one solid Brotli stream (quality 11, large window) over a small entry + * table followed by every entry's bytes in archive order. Cross-file redundancy (the same + * tool output in messages.jsonl and in the native transcript, repeated prompt blocks) is + * found by the long window; vendor-encrypted thinking signatures stay near-incompressible. + */ +const BROTLI_ENCODE = { + params: { + [zlib.constants.BROTLI_PARAM_QUALITY]: 11, + [zlib.constants.BROTLI_PARAM_LGWIN]: 26, + [zlib.constants.BROTLI_PARAM_LARGE_WINDOW]: true, + [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, + }, +}; +const BROTLI_DECODE = { params: { [zlib.constants.BROTLI_DECODER_PARAM_LARGE_WINDOW]: true } }; + +export function encodeArchive(bundle) { + if (!bundle || !Array.isArray(bundle.entries)) { + throw new TypeError('bundle.entries must be an array'); + } + const header = encodePlainHeader(bundle.headerVersion ?? XDTSHARE_HEADER_VERSION); + const table = []; + const bodies = []; + let total = 0; + for (const entry of bundle.entries) { + if (!entry || typeof entry.path !== 'string') { + throw new TypeError('Each entry must have a string path'); + } + const body = toBufferView(entry.content); + const pathBuf = Buffer.from(entry.path, 'utf8'); + const meta = Buffer.alloc(8); + meta.writeUInt32LE(pathBuf.length, 0); + meta.writeUInt32LE(body.length, 4); + table.push(meta, pathBuf); + bodies.push(body); + total += body.length; + } + const count = Buffer.alloc(4); + count.writeUInt32LE(bundle.entries.length, 0); + const solid = Buffer.concat([count, ...table, ...bodies]); + const opts = { params: { ...BROTLI_ENCODE.params, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: solid.length } }; + const out = Buffer.concat([header, zlib.brotliCompressSync(solid, opts)]); + void total; + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); +} + +export function decodeArchive(bytes) { + const { headerVersion, payload } = parsePlainHeader(bytes); + const solid = zlib.brotliDecompressSync(payload, BROTLI_DECODE); + if (solid.length < 4) throw new Error('Truncated archive payload'); + const count = solid.readUInt32LE(0); + let offset = 4; + const metas = []; + for (let i = 0; i < count; i++) { + if (offset + 8 > solid.length) throw new Error(`Truncated entry table at ${i}`); + const pathLen = solid.readUInt32LE(offset); + const size = solid.readUInt32LE(offset + 4); + offset += 8; + if (offset + pathLen > solid.length) throw new Error(`Truncated path at ${i}`); + metas.push({ path: solid.toString('utf8', offset, offset + pathLen), size }); + offset += pathLen; + } + const entries = metas.map((m) => { + if (offset + m.size > solid.length) throw new Error(`Truncated body for ${m.path}`); + const copy = Buffer.from(solid.subarray(offset, offset + m.size)); + offset += m.size; + return { path: m.path, content: new Uint8Array(copy.buffer, copy.byteOffset, copy.byteLength) }; + }); + if (offset !== solid.length) throw new Error(`Unexpected trailing bytes: ${solid.length - offset}`); + return { headerVersion, entries }; +} diff --git a/questions/opt-cshare-compression/v2/reference/tests/smoke.test.mjs b/questions/opt-cshare-compression/v2/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..e8f6708 --- /dev/null +++ b/questions/opt-cshare-compression/v2/reference/tests/smoke.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; + +import { + XDTSHARE_MAGIC, + XDTSHARE_PLAIN_HEADER_LENGTH, + encodeArchive, + decodeArchive, +} from '../src/cshare-codec.mjs'; +import { loadPublicCorpus } from '../lib/corpus.mjs'; + +function sha256(u8) { + return crypto.createHash('sha256').update(u8).digest('hex'); +} + +function assertHeader(encoded) { + assert.ok(encoded instanceof Uint8Array, 'encodeArchive must return Uint8Array'); + assert.ok(encoded.byteLength >= XDTSHARE_PLAIN_HEADER_LENGTH, 'archive shorter than 12-byte header'); + const buf = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); + assert.equal(buf.toString('ascii', 0, 8), XDTSHARE_MAGIC); + assert.equal(buf.readUInt8(8), 1, 'headerVersion must be 1'); + assert.equal(buf.readUInt8(9), 0, 'cipher must be 0'); + assert.equal(buf.readUInt16BE(10), 0, 'reserved bytes must be 0'); +} + +function assertRoundTrip(bundle) { + const originalHashes = bundle.entries.map((e) => ({ + path: e.path, + bytes: e.content.byteLength, + sha256: sha256(e.content), + })); + + const encoded = encodeArchive(bundle); + assertHeader(encoded); + + // Verify caller buffers were not mutated. + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(sha256(bundle.entries[i].content), originalHashes[i].sha256, `input mutated at ${bundle.entries[i].path}`); + } + + const decoded = decodeArchive(encoded); + assert.equal(decoded.headerVersion, 1); + assert.equal(decoded.entries.length, bundle.entries.length); + + for (let i = 0; i < bundle.entries.length; i++) { + assert.equal(decoded.entries[i].path, originalHashes[i].path, `path mismatch at index ${i}`); + assert.ok(decoded.entries[i].content instanceof Uint8Array, `content must be Uint8Array at ${originalHashes[i].path}`); + assert.equal(decoded.entries[i].content.byteLength, originalHashes[i].bytes, `length mismatch at ${originalHashes[i].path}`); + assert.equal(sha256(decoded.entries[i].content), originalHashes[i].sha256, `content hash mismatch at ${originalHashes[i].path}`); + } + return encoded; +} + +test('XDTSHARE header validation rejects malformed or unsupported headers', () => { + assert.equal(XDTSHARE_MAGIC, 'XDTSHARE'); + assert.equal(XDTSHARE_PLAIN_HEADER_LENGTH, 12); + + assert.throws(() => decodeArchive(new Uint8Array(4)), /short|invalid|header/i); + + const badMagic = Buffer.from('BADMAGIC\x01\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badMagic)); + + const badVersion = Buffer.from('XDTSHARE\x02\x00\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badVersion)); + + const badCipher = Buffer.from('XDTSHARE\x01\x01\x00\x00', 'latin1'); + assert.throws(() => decodeArchive(badCipher)); +}); + +test('lossless round-trip on adversarial edge cases and non-zero byteOffset views', () => { + const allBytes = new Uint8Array(256); + for (let i = 0; i < 256; i++) allBytes[i] = i; + + const emptyBundle = { headerVersion: 1, entries: [] }; + assertRoundTrip(emptyBundle); + + const backing = Buffer.alloc(64); + Buffer.from('offset-view-payload-\x00\xff-你好🚀', 'utf8').copy(backing, 11); + const slicedView = new Uint8Array(backing.buffer, backing.byteOffset + 11, 30); + + const edgeBundle = { + headerVersion: 1, + entries: [ + { path: 'empty.txt', content: new Uint8Array(0) }, + { path: 'empty.json', content: new Uint8Array(0) }, + { path: 'empty.png', content: new Uint8Array(0) }, + { path: 'all-bytes.bin', content: allBytes }, + { path: 'notes/会话-日志-🚀.txt', content: Buffer.from('你好世界 🚀👨‍👩‍👧‍👦 café\r\nline2\nno-eol', 'utf8') }, + { path: 'malformed.jsonl', content: Buffer.from('not-json\r\n{broken\n\x00\x01\x02\x1e\x1f@@B64:0@@', 'latin1') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('second version\r\n', 'utf8') }, + { path: 'dup.txt', content: Buffer.from('first version\n', 'utf8') }, + { path: 'sliced-view.bin', content: slicedView }, + ], + }; + + const encoded = assertRoundTrip(edgeBundle); + const encoded2 = encodeArchive(edgeBundle); + assert.equal(sha256(encoded), sha256(encoded2), 'encodeArchive must be deterministic'); + + // Decode via a non-zero byteOffset Uint8Array view + const padded = new Uint8Array(encoded.byteLength + 19); + padded.set(encoded, 13); + const view = padded.subarray(13, 13 + encoded.byteLength); + const decodedFromView = decodeArchive(view); + assert.equal(decodedFromView.entries.length, edgeBundle.entries.length); + assert.equal(sha256(decodedFromView.entries[3].content), sha256(allBytes)); +}); + +test('lossless round-trip on the full public .cshare corpus', () => { + const suite = loadPublicCorpus(); + assert.equal(suite.bundles.length, 13); + for (const bundle of suite.bundles) { + assertRoundTrip(bundle); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/author/editable.json b/questions/opt-device-link-delta-sync/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-device-link-delta-sync/v1/author/evaluator.mjs b/questions/opt-device-link-delta-sync/v1/author/evaluator.mjs new file mode 100644 index 0000000..6c39c32 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/evaluator.mjs @@ -0,0 +1,674 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { generateTrace } from '../candidate/lib/trace-generator.mjs'; +import { generateHeldoutTrace } from './heldout-trace.mjs'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +// Submission code runs in a child process under Node's permission model: `--permission` since +// Node 22.13 / 23.5, `--experimental-permission` on Node 20 before that, absent before Node 20. +// Without it the submission cannot be isolated, so the run is reported as an environment +// problem instead of being scored. +const PERMISSION_FLAG = ['--permission', '--experimental-permission'].find( + (flag) => spawnSync(process.execPath, [flag, '-e', ''], { stdio: 'ignore', timeout: 10_000 }).status === 0, +); +if (!PERMISSION_FLAG) { + trusted.emit({ + status: 'environment_invalid', + reason: `grading needs Node.js >= 20 for the permission model (found ${process.version})`, + }); + process.exit(0); +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const MAX_ROUNDS = 4; +const MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +const MAX_TRACE_RUNTIME_MS = 8000; + +const [rawSubDir] = process.argv.slice(2); +if (!rawSubDir) { + console.error('Usage: node evaluator.mjs '); + process.exit(2); +} + +const subDir = await fs.realpath(rawSubDir); +const authorDir = await fs.realpath(HERE); + +const FORBIDDEN_MODULES = [ + 'fs', 'fs/promises', 'net', 'http', 'https', 'http2', 'dgram', 'tls', 'dns', + 'child_process', 'worker_threads', 'cluster', 'inspector', 'inspector/promises', + 'vm', 'os', 'v8', 'module', 'perf_hooks', +]; + +async function auditSubmissionSource(dir) { + const stack = [dir]; + const forbiddenImportRe = new RegExp( + `(?:from\\s*|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:node:)?(${FORBIDDEN_MODULES.map((m) => m.replace('/', '\\/')).join('|')})['"]`, + ); + const forbiddenRuntimeRe = /\bprocess\s*\.\s*(?:getBuiltinModule|binding|dlopen)\b/; + + while (stack.length > 0) { + const cur = stack.pop(); + const entries = await fs.readdir(cur, { withFileTypes: true }); + for (const entry of entries) { + const full = path.join(cur, entry.name); + const st = await fs.lstat(full); + if (st.isSymbolicLink()) { + throw new Error(`Symlink forbidden in src/: ${entry.name}`); + } + if (st.isDirectory()) { + stack.push(full); + continue; + } + if (!st.isFile()) { + throw new Error(`Non-regular file forbidden in src/: ${entry.name}`); + } + if (entry.name.endsWith('.node')) { + throw new Error(`Native addon forbidden in src/: ${entry.name}`); + } + if (/\.(mjs|js|cjs)$/.test(entry.name)) { + const text = await fs.readFile(full, 'utf8'); + const m1 = forbiddenImportRe.exec(text); + if (m1) { + throw new Error(`Forbidden side-channel module import '${m1[1]}' in ${entry.name}`); + } + const m2 = forbiddenRuntimeRe.exec(text); + if (m2) { + throw new Error(`Forbidden process escape '${m2[0]}' in ${entry.name}`); + } + } + } + } +} + +class SandboxedWorker { + constructor(scriptPath, args, sandboxDir) { + const nodeFlags = [PERMISSION_FLAG, `--allow-fs-read=${subDir}`, `--allow-fs-read=${scriptPath}`]; + this.child = spawn(process.execPath, [...nodeFlags, scriptPath, ...args], { + cwd: sandboxDir, + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: sandboxDir, + TMPDIR: sandboxDir, + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker output: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) throw new Error(res.error || `Worker error: ${this.stderr}`); + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { /* ignore */ } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +async function runSandboxedTrace(trace, { verifyImmutable = false } = {}) { + const hostTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-sync-host-')); + const clientTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-sync-client-')); + const hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }; + const clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }; + + let hostWorker = null; + let clientWorker = null; + const hostPids = new Set(); + const clientPids = new Set(); + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new SandboxedWorker( + path.join(authorDir, 'worker-host.mjs'), + [subDir, JSON.stringify(hostOptions)], + hostTmp, + ); + const ping = await hostWorker.call({ op: 'ping' }); + hostPids.add(ping.pid); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new SandboxedWorker( + path.join(authorDir, 'worker-client.mjs'), + [subDir, JSON.stringify(clientOptions)], + clientTmp, + ); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + clientPids.add(init.pid); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + perChannel: {}, + elapsedMs: 0, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + verifyImmutable, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + const t0 = trusted.now(); + try { + await spawnHost(); + await spawnClient(null); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > MAX_PERSISTENT_BYTES) { + throw new Error(`exportPersistentState exceeded 2 MiB (${exported.byteLength} > ${MAX_PERSISTENT_BYTES})`); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'host_evict') { + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + verifyImmutable, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + verifyImmutable, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + verifyImmutable, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown step type: ${step.type}`); + } + } + + stats.elapsedMs = Math.round(trusted.now() - t0); + // Confirm zero PID overlap between host and client processes + for (const p of hostPids) { + assert.ok(!clientPids.has(p), 'Host and Client shared a PID'); + } + return { stats, hostSpawnCount: hostPids.size, clientSpawnCount: clientPids.size }; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + await Promise.all([ + fs.rm(hostTmp, { recursive: true, force: true }), + fs.rm(clientTmp, { recursive: true, force: true }), + ]); + } +} + +function buildAdversarialEdgeTrace() { + const largeStrBase = 'A'.repeat(20_000) + '日本語テスト🚀'; + const largeStrNext = largeStrBase + 'APPENDED_STREAM_CHUNK_' + '中'.repeat(600); + const payloads = [ + { ch: 'edge:prim', args: '{}', val: null }, + { ch: 'edge:prim', args: '{}', val: true }, + { ch: 'edge:prim', args: '{}', val: false }, + { ch: 'edge:prim', args: '{}', val: 0 }, + { ch: 'edge:prim', args: '{}', val: -123456.789 }, + { ch: 'edge:prim', args: '{}', val: '' }, + { ch: 'edge:prim', args: '{}', val: 'Hello 🌍 你好世界\n\t\r"quotes"\\backslash' }, + { ch: 'edge:prim', args: '{}', val: [] }, + { ch: 'edge:prim', args: '{}', val: {} }, + { + ch: 'edge:proto-keys', + args: '{"k":1}', + val: { + constructor: 'ctor-val-1', + toString: 'toString-val-1', + valueOf: 42, + hasOwnProperty: { a: [1, 2, null], b: {} }, + $ref: 'literal-dollar-ref', + $d: 1, + nested: { emptyArr: [], emptyObj: {}, large: largeStrBase }, + list: [ + { id: 'k1', $ref: 'keep-me', val: 1, tags: ['a', 'b'] }, + { id: 'k2', val: null, tags: [] }, + ], + }, + }, + { + ch: 'edge:proto-keys', + args: '{"k":1}', + val: { + constructor: 'ctor-val-2', + // toString deleted + valueOf: [false, true, 0], + hasOwnProperty: { a: [1, 3], c: 'added' }, + $ref: 'literal-dollar-ref-2', + nested: { emptyArr: [null], emptyObj: { x: '' }, large: largeStrNext }, + list: [ + { id: 'k2', val: { becameObj: true }, tags: ['new'] }, + { id: 'k1', $ref: 'keep-me', val: 1, tags: ['a', 'b', 'c'] }, + { id: 'k3', val: 'emoji-🎉-end', tags: [] }, + ], + }, + }, + // Adversarial revisionSuffix mismatch inside messages:view shape + { + ch: 'local-db:messages:view', + args: '{"sessionId":"adv-s1","limit":10}', + val: { + sessionId: 'adv-s1', + revisionSuffix: ':r9', + items: [ + { key: 'work:1', type: 'work', summary: { revision: 'no-matching-suffix', title: 'raw' } }, + { key: 'msg:1', type: 'messages', messages: [{ id: 'm1', role: 'assistant', content: { text: largeStrBase }, remoteBodyVersion: 'not-a-sha' }] }, + ], + }, + }, + { + ch: 'local-db:messages:view', + args: '{"sessionId":"adv-s1","limit":10}', + val: { + sessionId: 'adv-s1', + revisionSuffix: ':r10', + items: [ + { key: 'work:1', type: 'work', summary: { revision: 'no-matching-suffix', title: 'raw-updated' } }, + { key: 'msg:1', type: 'messages', messages: [{ id: 'm1', role: 'assistant', content: { text: largeStrNext }, remoteBodyVersion: 'not-a-sha' }] }, + ], + }, + }, + ]; + + const steps = payloads.map((p, idx) => ({ + type: 'rpc', + id: `edge-${idx + 1}`, + channel: p.ch, + argsKey: p.args, + groundTruthValue: p.val, + })); + // Add a cold reconnect and re-read to verify edge shapes survive reconnect + steps.push({ type: 'cold_reconnect', label: 'edge-cold-reconnect' }); + steps.push({ + type: 'rpc', + id: 'edge-post-cold', + channel: 'edge:proto-keys', + argsKey: '{"k":1}', + groundTruthValue: payloads[10].val, + }); + return { steps }; +} + +async function checkInProcessDriftAndExports() { + const mod = await import(pathToFileURL(path.join(subDir, 'sync-protocol.mjs')).href); + assert.equal(mod.PROTOCOL_MAX_ROUNDS, 4); + assert.equal(typeof mod.createHostSyncEndpoint, 'function'); + assert.equal(typeof mod.createClientSyncEndpoint, 'function'); + + const host = mod.createHostSyncEndpoint(); + const client = mod.createClientSyncEndpoint(); + assert.equal(typeof host.handleFrame, 'function'); + assert.equal(typeof host.evictVolatileBases, 'function'); + assert.equal(typeof client.beginRead, 'function'); + assert.equal(typeof client.receiveResponse, 'function'); + assert.equal(typeof client.exportPersistentState, 'function'); + assert.equal(typeof client.simulateColdReconnect, 'function'); + + const runOne = (readId, channel, argsKey, val) => { + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + while (true) { + assert.ok(req instanceof Uint8Array); + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue: val, round }); + assert.ok(res instanceof Uint8Array); + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean'); + if (step.done) { + assert.deepStrictEqual(step.value, val); + return; + } + round += 1; + assert.ok(round < MAX_ROUNDS); + req = step.nextRequestBytes; + } + }; + + runOne('u1', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 1 }] }); + host.evictVolatileBases(); + runOne('u2', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 2 }] }); + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + runOne('u3', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 3 }] }); +} + +async function checkEntropyIsolation() { + // 2048 bytes of true cryptographic randomness encoded as 4096 hex chars -> >= 2048 bytes entropy. + // Any physically isolated protocol without a side-channel MUST transmit >= 1800 wire bytes! + const randomPayload = { + nonceId: 'entropy-check-1', + hexBlob: crypto.randomBytes(2048).toString('hex'), + }; + const trace = { + steps: [ + { + type: 'rpc', + id: 'entropy-1', + channel: 'isolation:entropy', + argsKey: '{"k":"nonce"}', + groundTruthValue: randomPayload, + }, + ], + }; + const { stats } = await runSandboxedTrace(trace, { verifyImmutable: true }); + assert.ok( + stats.totalWireBytes >= 1800, + `Entropy lower-bound violation: 2048B random nonce transferred in only ${stats.totalWireBytes}B`, + ); + return stats.totalWireBytes; +} + +const errors = []; +let gate_wire_sanity = false; +let gate_process_isolation = false; +let gate_reconnect_and_drift = false; +let gate_exact_json_parity = false; + +let auditOk = false; +try { + await auditSubmissionSource(subDir); + auditOk = true; +} catch (err) { + errors.push(`audit: ${err.message}`); +} + +let exportsAndInProcOk = false; +if (auditOk) { + try { + await checkInProcessDriftAndExports(); + exportsAndInProcOk = true; + } catch (err) { + errors.push(`exports/inproc: ${err.message}`); + } +} + +let entropyBytes = 0; +let isolationOk = false; +if (auditOk) { + try { + entropyBytes = await checkEntropyIsolation(); + isolationOk = true; + } catch (err) { + errors.push(`isolation: ${err.message}`); + } +} + +let edgeOk = false; +if (auditOk) { + try { + const edgeRes = await runSandboxedTrace(buildAdversarialEdgeTrace(), { verifyImmutable: true }); + assert.ok(edgeRes.stats.maxRoundsUsed <= MAX_ROUNDS); + edgeOk = true; + } catch (err) { + errors.push(`edgeParity: ${err.message}`); + } +} + +let publicOk = false; +let publicStats = null; +if (auditOk) { + try { + const pubTrace = generateTrace({ seed: 20260501 }); + const pubRes = await runSandboxedTrace(pubTrace, { verifyImmutable: false }); + publicStats = pubRes.stats; + assert.equal(pubRes.stats.rpcCount, pubTrace.meta.totalRpcs); + assert.ok(pubRes.stats.maxRoundsUsed <= MAX_ROUNDS); + assert.ok(pubRes.stats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES); + publicOk = true; + } catch (err) { + errors.push(`publicTrace: ${err.message}`); + } +} + +let heldoutOk = false; +let heldoutStats = null; +let heldoutMeta = null; +let heldoutHostSpawns = 0; +let heldoutClientSpawns = 0; +if (auditOk) { + try { + const hoTrace = generateHeldoutTrace(); + heldoutMeta = hoTrace.meta; + const hoRes = await runSandboxedTrace(hoTrace, { verifyImmutable: false }); + heldoutStats = hoRes.stats; + heldoutHostSpawns = hoRes.hostSpawnCount; + heldoutClientSpawns = hoRes.clientSpawnCount; + assert.equal(hoRes.stats.rpcCount, hoTrace.meta.totalRpcs); + assert.ok(hoRes.stats.maxRoundsUsed <= MAX_ROUNDS); + assert.ok(hoRes.stats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES); + heldoutOk = true; + } catch (err) { + errors.push(`heldoutTrace: ${err.message}`); + } +} + +const runtimeOk = heldoutStats !== null && heldoutStats.elapsedMs <= MAX_TRACE_RUNTIME_MS; +if (heldoutStats && !runtimeOk) { + errors.push(`runtime: held-out trace took ${heldoutStats.elapsedMs}ms > ${MAX_TRACE_RUNTIME_MS}ms`); +} + +gate_wire_sanity = auditOk && exportsAndInProcOk && edgeOk && heldoutOk + && heldoutStats.maxRoundsUsed <= MAX_ROUNDS && heldoutStats.totalWireBytes > 0; +gate_process_isolation = auditOk && isolationOk && heldoutOk + && heldoutHostSpawns >= 10 && heldoutClientSpawns >= 7; +gate_reconnect_and_drift = auditOk && exportsAndInProcOk && publicOk && heldoutOk && runtimeOk + && heldoutStats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES; +gate_exact_json_parity = auditOk && edgeOk && publicOk && heldoutOk; + +const total_wire_bytes = heldoutOk ? heldoutStats.totalWireBytes : 100_000_000; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_json_parity, + gate_process_isolation, + gate_reconnect_and_drift, + gate_wire_sanity, + }, + metrics: { + total_wire_bytes, + }, + details: { + errors, + entropyCheckWireBytes: entropyBytes, + publicWireBytes: publicStats?.totalWireBytes ?? null, + heldout: heldoutStats + ? { + totalWireBytes: heldoutStats.totalWireBytes, + upstreamBytes: heldoutStats.upstreamBytes, + downstreamBytes: heldoutStats.downstreamBytes, + rawJsonBytes: heldoutMeta?.rawJsonBytes ?? null, + rpcCount: heldoutStats.rpcCount, + totalRounds: heldoutStats.totalRounds, + maxRoundsUsed: heldoutStats.maxRoundsUsed, + maxPersistentBytesSeen: heldoutStats.maxPersistentBytesSeen, + elapsedMs: heldoutStats.elapsedMs, + perChannel: heldoutStats.perChannel, + } + : null, + }, +})); diff --git a/questions/opt-device-link-delta-sync/v1/author/grade.py b/questions/opt-device-link-delta-sync/v1/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-device-link-delta-sync/v1/author/grade_impl.py b/questions/opt-device-link-delta-sync/v1/author/grade_impl.py new file mode 100644 index 0000000..b70cbb8 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/grade_impl.py @@ -0,0 +1,47 @@ +"""Isolated pure-Node quantitative grader: runs correctness, isolation, drift gates + unseen held-out wire benchmark.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + src_dir = submission_root / 'src' + if not src_dir.is_dir(): + return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'} + with tempfile.TemporaryDirectory(prefix='eval-delta-sync-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(src_dir, sub_src, symlinks=True) + # Ensure ESM semantics if submission adds .js helper files inside src/ + pkg_file = sub_src / 'package.json' + if not pkg_file.exists(): + pkg_file.write_text('{"type":"module"}\n') + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-device-link-delta-sync/v1/author/heldout-trace.mjs b/questions/opt-device-link-delta-sync/v1/author/heldout-trace.mjs new file mode 100644 index 0000000..373ba89 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/heldout-trace.mjs @@ -0,0 +1,168 @@ +import { generateTrace } from '../candidate/lib/trace-generator.mjs'; + +export const HELDOUT_SEED = 918273645; + +export const HELDOUT_CORPUS = { + idPrefix: 'ho2', + devices: [ + 'node-tokyo-macmini-09', + 'node-frankfurt-epyc-14', + 'node-seattle-thinkpad-22', + 'node-singapore-arm-07', + ], + workingDirs: [ + '/srv/builds/aurora-gateway', + '/srv/builds/nebula-indexer', + '/srv/builds/kestrel-mobile-app', + '/srv/builds/polaris-sync-engine', + '/srv/builds/solstice-telemetry', + '/srv/builds/horizon-cli', + ], + subdirs: [ + 'modules/transport/src', + 'modules/reconciler/src', + 'clients/ios-bridge/src', + 'clients/desktop-host/src', + 'edge/relay-router/src', + 'core/wire-codec/src', + 'spec/conformance', + 'tools/replay', + ], + fileStems: [ + 'frameMux', 'stateDiffer', 'pageDelta', 'bodyVault', + 'peerChannel', 'batchReader', 'outboxQueue', 'dictPush', + 'zlibAdapter', 'hostWorker', 'sessionIndex', 'coldResume', + 'driftProbe', 'retryScheduler', 'memoryCap', 'tokenStream', + 'varintPack', 'hashTree', 'journalSync', 'limitLedger', + ], + symbolVerbs: [ + 'align', 'diff', 'unpack', 'pack', 'sweep', 'strip', 'squash', + 'audit', 'route', 'dedupe', 'restore', 'marshal', 'decompress', 'trim', + 'splice', 'verify', 'flush', 'sanitize', + ], + symbolNouns: [ + 'BaseSlot', 'TranscriptPage', 'ContentBlock', 'PacketFrame', 'VersionRing', + 'OutlineTag', 'DigestList', 'ThreadRow', 'RateWindow', 'JobHistory', + 'MerkleChain', 'EditInstr', 'LeafHash', 'ClientState', 'SyncEnvelope', + 'StringPool', 'StreamTail', 'DiskRecord', + ], + cjkTopics: [ + '蜂窝网络高抖动下同步流量激增', '全局设备状态变更触发补丁中止', '后台重启后历史正文清单体积过大', + '助手流式输出尾部追加导致全文重发', '页级修订后缀污染未修改工作节点', '双请求并行读取造成旧基准失配', + '持久化落盘空间逼近双兆字节红线', '多模型供应商目录静态字段反复传输', '预置字典未对齐导致压缩率偏低', + '历史分页游标切换引发重复拉取', '跨进程隔离通道帧长度与轮次审计', '结构化数组重排与字段名冗余', + '宿主进程重启后的冷缓存集合核对', '中日韩与表情混合文本无损还原', '高频状态栏轮询带宽预算控制', + '定时巡检运行记录窗口移位压缩', + ], + enObservations: [ + 'Captured downstream burst when 65 percent of session rows flipped online flag', + 'Found streaming assistant output retransmitting unchanged 3 KiB markdown bodies', + 'Logged 22 KiB upstream manifest upload immediately after iOS cold relaunch', + 'Verified ring buffer retains prior snapshots across overlapping in-flight polls', + 'Measured raw deflate savings when seeded with previous synchronized base bytes', + 'Checked strict deep-equality across nested nulls, empty lists, and Unicode text', + 'Isolated page-wide outline suffix churn from actual work item payload edits', + 'Compared recursive keyed object patching against depth-limited row replacement', + 'Tracked compressed persistent cache footprint across six suspend-resume cycles', + 'Observed paginated history fetches sharing immutable blocks with latest page', + 'Evaluated multi-round Merkle prefix exchange for append-only transcript sync', + 'Measured binary varint field encoding on catalog and schedule index updates', + ], + cjkActions: [ + '应按唯一标识匹配条目并深入字段级差分,避免单字段变动拖累整行重传', + '宿主丢失易失基准时可通过紧凑内容摘要或双轮哈希调和跳过已落盘条目', + '对流式增长的长字符串采用公共前缀加尾部增量编码,可消除九成以上重复载荷', + '在宿主侧为每个请求键保留有界多基准环,确保并发旧基准请求依然命中增量路径', + '以双方共享的旧快照作为压缩预置字典,可显著压缩重复路径与固定枚举标签', + '严格保留空对象、空数组、数字类型、特殊普通键及多字节字符的逐字段一致性', + '冷重连握手改用分桶哈希或前缀摘要树,将上行字节从数万字节降至百字节级', + '剥离页级后缀前必须核验全部子节点格式匹配,确保任意异常输入均可无损还原', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-opus-4-6', + 'gpt-5.4-high', + 'gemini-3.1-pro', + 'deepseek-v3.2', + 'qwen3.5-max', + 'kimi-k2-thinking', + ], + tagsPool: [ + 'wan', 'delta', 'reconcile', 'ios', 'android', 'critical', 'backlog', + 'codec', 'storage', 'framing', 'metrics', 'release', 'hardening', 'latency', + ], + sessionTitles: [ + '调试弱网蜂窝环境下跨端状态漂移与重连风暴', + 'Reduce upstream digest bloat on iOS cold resume', + '设计通用结构化二进制差分与前缀字典编码器', + 'Analyze multi-region gateway quota refresh spikes', + '修复定时巡检面板历史记录滑动窗口重复序列化', + 'Benchmark Merkle bucket reconciliation under packet loss', + '处理流式思维链增量追加导致的下行带宽放大', + 'Verify strict process isolation between host and peer', + '排查并发只读请求基准淘汰引发的全量回退', + 'Optimize persistent disk cache eviction under 2 MiB cap', + '验证日文与表情符号混合长日志精确还原一致', + 'Stress-test pagination boundary transitions across reconnects', + ], + toolNames: ['inspect_trace', 'verify_hash', 'run_bench', 'diff_snapshot', 'profile_codec'], + workTitles: [ + 'Audit cold-start manifest overhead', + 'Replay held-out cellular trace', + 'Validate binary varint decoder bounds', + 'Strip volatile outline revision suffixes', + 'Check concurrent stale-base ring hits', + 'Measure preset-dictionary compression ratio', + ], + providers: [ + { id: 'claude-prod', name: 'Claude Enterprise Hub', kind: 'anthropic', baseUrl: 'https://claude-gw.aurora.example/v1', region: 'us-east-2', tier: 'dedicated' }, + { id: 'openai-prod', name: 'OpenAI Dedicated Pool', kind: 'openai', baseUrl: 'https://oai-gw.aurora.example/v1', region: 'us-west-1', tier: 'dedicated' }, + { id: 'gemini-cloud', name: 'Gemini Global Cloud', kind: 'gemini', baseUrl: 'https://gemini-gw.aurora.example/v1beta', region: 'europe-west4', tier: 'enterprise' }, + { id: 'vertex-eu', name: 'Vertex EU Frankfurt', kind: 'vertex', baseUrl: 'https://eu-vertex.aurora.example/v1', region: 'europe-west3', tier: 'enterprise' }, + { id: 'bedrock-ap', name: 'Bedrock Tokyo Relay', kind: 'bedrock', baseUrl: 'https://ap-bedrock.aurora.example', region: 'ap-northeast-1', tier: 'enterprise' }, + { id: 'deepseek-hk', name: 'DeepSeek HK Cluster', kind: 'openai-compat', baseUrl: 'https://ds-hk.aurora.example/v1', region: 'ap-east-1', tier: 'scale' }, + { id: 'router-edge', name: 'Edge Multi-Model Router', kind: 'openai-compat', baseUrl: 'https://edge-router.aurora.example/v1', region: 'global', tier: 'prepaid' }, + { id: 'grok-fast', name: 'Grok Inference Mesh', kind: 'openai-compat', baseUrl: 'https://grok-mesh.aurora.example/v1', region: 'us-central1', tier: 'pro' }, + { id: 'qwen-sh', name: 'Qwen Shanghai Cloud', kind: 'openai-compat', baseUrl: 'https://qwen-sh.aurora.example/v1', region: 'cn-shanghai', tier: 'enterprise' }, + { id: 'kimi-bj', name: 'Kimi Beijing Gateway', kind: 'openai-compat', baseUrl: 'https://kimi-bj.aurora.example/v1', region: 'cn-beijing', tier: 'pro' }, + { id: 'glm-hz', name: 'GLM Hangzhou Endpoint', kind: 'openai-compat', baseUrl: 'https://glm-hz.aurora.example/v4', region: 'cn-hangzhou', tier: 'pro' }, + { id: 'minimax-sg', name: 'MiniMax Singapore Pool', kind: 'anthropic-compat', baseUrl: 'https://mm-sg.aurora.example/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'vllm-lab', name: 'On-Prem vLLM H100 Rack', kind: 'openai-compat', baseUrl: 'http://10.24.0.18:8000/v1', region: 'on-prem', tier: 'internal' }, + { id: 'fallback-eu', name: 'EU Failover Proxy', kind: 'openai-compat', baseUrl: 'https://failover-eu.aurora.example/v1', region: 'eu-west-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Hourly cellular sync telemetry rollup', + '每两小时巡检跨区域中继断连率', + 'Nightly binary codec fuzz verification', + 'Automated database compaction & vacuum', + '检查高流量会话持久化缓存命中率', + 'Daily provider quota burn forecast', + 'Weekly cold-reconnect regression sweep', + '定期归档过期远控诊断快照', + ], + schedulePrompts: [ + 'Aggregate wire-byte telemetry across all relay POPs and alert on regressions exceeding 10%.', + '扫描过去两小时内出现增量基准失配的会话,汇总失败原因并输出修复建议。', + 'Run fuzzing corpus against binary patch decoders and confirm zero parity mismatches.', + 'Analyze provider quota burn trajectories and recommend fallback routing weights.', + ], +}; + +export const HELDOUT_SCHEDULE_PROFILE = { + coldReconnectTicks: [28, 66, 102, 142, 178, 210], + hostEvictTicks: [46, 120, 192], + concurrentSpecs: [ + { tick: 19, channel: 'local-db:sessions:list' }, + { tick: 86, channel: 'local-db:messages:view' }, + { tick: 156, channel: 'local-db:sessions:list' }, + { tick: 202, channel: 'maker:provider:list' }, + ], +}; + +export function generateHeldoutTrace() { + return generateTrace({ + seed: HELDOUT_SEED, + corpus: HELDOUT_CORPUS, + scheduleProfile: HELDOUT_SCHEDULE_PROFILE, + }); +} diff --git a/questions/opt-device-link-delta-sync/v1/author/result-channel.mjs b/questions/opt-device-link-delta-sync/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/author/worker-client.mjs b/questions/opt-device-link-delta-sync/v1/author/worker-client.mjs new file mode 100644 index 0000000..46a66ad --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/worker-client.mjs @@ -0,0 +1,152 @@ +import module from 'node:module'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const allowedRoot = path.resolve(srcDir); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const ALLOWED_BUILTINS = new Set([ + 'node:zlib', 'zlib', + 'node:crypto', 'crypto', + 'node:buffer', 'buffer', + 'node:util', 'util', + 'node:string_decoder', 'string_decoder', + 'node:assert', 'assert', 'node:assert/strict', +]); + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('file://')) { + const resolved = nextResolve(specifier, context); + if (resolved?.url?.startsWith('file://')) { + const targetPath = path.resolve(fileURLToPath(resolved.url)); + if (targetPath !== allowedRoot && !targetPath.startsWith(allowedRoot + path.sep)) { + throw new Error(`Forbidden import outside src/: ${specifier}`); + } + } + return resolved; + } + if (!ALLOWED_BUILTINS.has(specifier)) { + throw new Error(`Forbidden built-in or external import: ${specifier}`); + } + return nextResolve(specifier, context); + }, + }); +} + +for (const key of ['fetch', 'WebSocket', 'XMLHttpRequest']) { + try { delete globalThis[key]; } catch { /* ignore */ } +} +for (const key of ['getBuiltinModule', 'dlopen', 'binding']) { + try { + Object.defineProperty(process, key, { + value: () => { throw new Error(`Forbidden process.${key}`); }, + configurable: false, + writable: false, + }); + } catch { /* ignore */ } +} + +const modUrl = pathToFileURL(path.join(allowedRoot, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/author/worker-host.mjs b/questions/opt-device-link-delta-sync/v1/author/worker-host.mjs new file mode 100644 index 0000000..6a4dd40 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/author/worker-host.mjs @@ -0,0 +1,107 @@ +import module from 'node:module'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const allowedRoot = path.resolve(srcDir); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const ALLOWED_BUILTINS = new Set([ + 'node:zlib', 'zlib', + 'node:crypto', 'crypto', + 'node:buffer', 'buffer', + 'node:util', 'util', + 'node:string_decoder', 'string_decoder', + 'node:assert', 'assert', 'node:assert/strict', +]); + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('file://')) { + const resolved = nextResolve(specifier, context); + if (resolved?.url?.startsWith('file://')) { + const targetPath = path.resolve(fileURLToPath(resolved.url)); + if (targetPath !== allowedRoot && !targetPath.startsWith(allowedRoot + path.sep)) { + throw new Error(`Forbidden import outside src/: ${specifier}`); + } + } + return resolved; + } + if (!ALLOWED_BUILTINS.has(specifier)) { + throw new Error(`Forbidden built-in or external import: ${specifier}`); + } + return nextResolve(specifier, context); + }, + }); +} + +// Neutralize global network / dynamic builtin escape hatches before loading submission code. +for (const key of ['fetch', 'WebSocket', 'XMLHttpRequest']) { + try { delete globalThis[key]; } catch { /* ignore */ } +} +for (const key of ['getBuiltinModule', 'dlopen', 'binding']) { + try { + Object.defineProperty(process, key, { + value: () => { throw new Error(`Forbidden process.${key}`); }, + configurable: false, + writable: false, + }); + } catch { /* ignore */ } +} + +const modUrl = pathToFileURL(path.join(allowedRoot, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const beforeJson = req.verifyImmutable ? JSON.stringify(req.groundTruthValue) : null; + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + if (beforeJson !== null && JSON.stringify(req.groundTruthValue) !== beforeJson) { + throw new Error('host.handleFrame mutated groundTruthValue'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/candidate/CONTRACT.md b/questions/opt-device-link-delta-sync/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..34b1c2a --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/CONTRACT.md @@ -0,0 +1,93 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (may be one of the 4 Cindy channels or any arbitrary test channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 8s` for a full 240-RPC trace). +4. **Generalization**: Evaluation runs on unseen held-out seeds, corpora, channel payloads, and event timings. Do not hardcode trace strings or schema assumptions that break on unseen payloads. diff --git a/questions/opt-device-link-delta-sync/v1/candidate/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..8e0ce3f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,10 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic 240-RPC two-process benchmark across all 4 Cindy channels reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, and compression ratio vs raw JSON diff --git a/questions/opt-device-link-delta-sync/v1/candidate/TASK.md b/questions/opt-device-link-delta-sync/v1/candidate/TASK.md new file mode 100644 index 0000000..4ce97c8 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/TASK.md @@ -0,0 +1,25 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC delta synchronization and cold-cache reconciliation protocol (`src/sync-protocol.mjs`), extracted from production desktop-to-mobile remote sessions (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). + +## Observed Production Bottlenecks + +In a typical mobile-over-cellular session polling 4 read-heavy RPC channels across ~240 reads (~20 MiB of raw JSON), the current baseline protocol burns over **2.0 MiB** of metered wire traffic (upstream + downstream combined) due to compounding architectural limits: + +1. **Channel silo**: `invokeDelta` is enabled ONLY on `local-db:sessions:list`; structured catalogs (`maker:provider:list`, ~45 KiB/poll) and schedule indices (`maker:schedule:list-sidebar-index-runs`, ~28 KiB/poll) resend full gzipped JSON on every single poll even when only quota numbers or 1–3 run entries changed. +2. **Coarse row-level diff & abort cliffs**: `invokeDelta` stops at `MAX_DEPTH = 2` (replacing entire session rows whenever a single field changes), aborts to a full snapshot whenever the uncompressed JSON patch exceeds `MAX_DELTA_RATIO = 0.5` (triggered during bulk device/tag refreshes where >55% of rows change 1 field), and resets to a full snapshot every `MAX_UNVERIFIED_DELTAS = 8` incremental reads. +3. **Expensive streaming appends & suffix churn in `local-db:messages:view`**: `historyViewDelta` only deduplicates completely identical items; appending 100–400 characters of streaming assistant text/thinking forces the entire multi-kilobyte message item to be re-sent on every poll, while page-wide `revisionSuffix` updates touch every `work` item. +4. **Bloated cold-cache manifests & weak cold reconciliation**: After mobile background-kill & cold reconnect (or host volatile-base eviction), `SessionMessageReuse` uploads up to 256 `[id, 64-hex-sha256]` pairs (~15–25 KiB upstream per read) only for `messages:view` and resends full gzipped snapshots for the other channels. +5. **Single/brittle base tracking & generic compression**: Concurrent in-flight reads with a slightly stale base fall back to full snapshots, and JSON patches carry heavy structural/key overhead without leveraging the already-synchronized base state. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every RPC read across all channels, pagination queries, streaming updates, arbitrary edge-case JSON shapes, mobile cold reconnects, host volatile-base evictions, and concurrent in-flight stale-base reads. +- Respect **strict two-process isolation**: Host and Client run in completely separate Node.js child processes communicating **only** via `Uint8Array` wire frames. No shared memory, filesystem, network, or side channels are permitted. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return a `Uint8Array` within `maxPersistentBytes` (default `2 MiB`), and every RPC must complete in at most `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended optimization goal**: Design any clean, general, deterministic two-party sync protocol inside `src/` to drive `total_wire_bytes` (sum of **all** upstream `requestBytes` and downstream `responseBytes` across **all** rounds and **all** RPCs) as low as possible — both on public benchmarks and on unseen held-out workloads with different seeds, payloads, vocabularies, and reconnect timings. +- Run `npm test` and `npm run bench` to verify exact parity and measure your wire-byte reduction. +- Record your analysis, protocol design, trade-offs, and verified benchmark results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v1/candidate/bench/workload.mjs b/questions/opt-device-link-delta-sync/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..5eaab10 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark(seed = 20260501) { + const trace = generateTrace({ seed }); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + seed, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + host_evictions: trace.meta.hostEvictCount, + concurrent_pairs: trace.meta.concurrentPairCount, + bulk_storms: trace.meta.bulkStormCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v1/candidate/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v1/candidate/lib/rpc-harness.mjs new file mode 100644 index 0000000..03d2824 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/lib/rpc-harness.mjs @@ -0,0 +1,293 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v1/candidate/lib/trace-generator.mjs b/questions/opt-device-link-delta-sync/v1/candidate/lib/trace-generator.mjs new file mode 100644 index 0000000..3621bc5 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/lib/trace-generator.mjs @@ -0,0 +1,936 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic Mulberry32 PRNG. + */ +export function createRng(seed) { + let state = (seed >>> 0) || 1; + return { + next() { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }, + int(min, max) { + return min + Math.floor(this.next() * (max - min + 1)); + }, + pick(arr) { + return arr[Math.floor(this.next() * arr.length)]; + }, + bool(p = 0.5) { + return this.next() < p; + }, + hex(len) { + const chars = '0123456789abcdef'; + let out = ''; + for (let i = 0; i < len; i += 1) { + out += chars[Math.floor(this.next() * 16)]; + } + return out; + }, + shuffle(arr) { + const out = arr.slice(); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = Math.floor(this.next() * (i + 1)); + const tmp = out[i]; + out[i] = out[j]; + out[j] = tmp; + } + return out; + }, + }; +} + +function sha256Hex(str) { + return crypto.createHash('sha256').update(str, 'utf8').digest('hex'); +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +export const DEFAULT_CORPUS = { + idPrefix: 'pub', + devices: [ + 'dev-mac-studio-01', + 'dev-mbp-m4-02', + 'dev-linux-build-03', + 'dev-wsl-workstation-04', + ], + workingDirs: [ + '/Users/dev/workspace/cindy-core', + '/Users/dev/workspace/cindy-mobile', + '/Users/dev/workspace/cindy-relay', + '/Users/dev/workspace/eval-bank', + '/Users/dev/workspace/agent-sdk', + '/Users/dev/workspace/docs-site', + ], + subdirs: [ + 'packages/device-link/src', + 'packages/maker-shared/src', + 'apps/mobile/src/sync', + 'apps/desktop/src/main', + 'services/relay-edge/src', + 'crates/protocol/src', + 'tests/integration', + 'scripts/bench', + ], + fileStems: [ + 'invokeDelta', 'invokeTransfer', 'historyViewDelta', 'sessionMessageReuse', + 'routedClient', 'listingReadCoalescer', 'transportBacklog', 'pushTransfer', + 'nodeCompression', 'remoteAgent', 'metadataContinuity', 'setupSnapshot', + 'stallDiagnostics', 'peerRecovery', 'cacheBudget', 'streamAssembler', + 'frameCodec', 'merkleIndex', 'walCheckpoint', 'quotaTracker', + ], + symbolVerbs: [ + 'reconcile', 'compute', 'decode', 'encode', 'evict', 'normalize', 'compact', + 'verify', 'dispatch', 'coalesce', 'hydrate', 'serialize', 'inflate', 'prune', + 'merge', 'replay', 'checkpoint', 'validate', + ], + symbolNouns: [ + 'DeltaBase', 'HistoryPage', 'MessageBody', 'WireFrame', 'SnapshotRing', + 'RevisionSuffix', 'ColdManifest', 'SessionRow', 'QuotaBucket', 'RunWindow', + 'PrefixLadder', 'PatchOp', 'ChunkDigest', 'PeerCursor', 'TransferHeader', + 'KeyTable', 'StreamBuffer', 'CacheEntry', + ], + cjkTopics: [ + '跨设备弱网同步延迟', '批量行刷新触发阈值回退', '移动端冷重连摘要上行膨胀', + '流式文本追加导致整条消息重传', '工作摘要版本号后缀高频抖动', '并发读取基准淘汰错位', + '本地持久化缓存体积上限控制', '多通道结构化目录轮询冗余', '字典压缩窗口命中率下降', + '分页历史回溯与最新页缓存复用', '异步队列背压与帧边界对齐', '索引重排与键表编码开销', + '断连恢复后的冷缓存集合调和', '长日志代码块与多语言字符集校验', '任务状态栏高频更新节流', + '定时任务滑动窗口增量裁剪', + ], + enObservations: [ + 'Observed wire amplification during bulk metadata refresh across active peers', + 'Detected redundant retransmission of unchanged markdown prefixes while streaming', + 'Measured upstream handshake spike when uploading full 64-hex SHA-256 manifests', + 'Confirmed multi-snapshot ring avoids full-page fallback under pipelined reads', + 'Profiled deflate dictionary match ratio against prior synchronized base payload', + 'Validated exact JSON parity for empty containers, floats, null fields, and emoji', + 'Traced revision suffix propagation across nested work summary child nodes', + 'Benchmarked recursive keyed array diff against coarse depth-2 row replacement', + 'Audited persistent cache serialization size under mobile background termination', + 'Inspected pagination cursor overlap when scrolling older transcript segments', + 'Evaluated 2-RTT set reconciliation bandwidth on partial state divergence', + 'Checked varint length framing and key-table interning on structured provider lists', + ], + cjkActions: [ + '建议改为按主键递归比对字段,仅下发变动属性与紧凑索引序列', + '排查发现未命中易失基准时会直接回退整页快照,应结合持久化摘要跳过未变正文', + '实测在流式输出阶段采用前缀复用加尾部追加指令,可将单次下行体积压缩至原来的十分之一', + '需要同时保留最近多个已确认与在途基准,防止并发轮询携带旧标签时反复触发全量同步', + '对比普通压缩与基于旧快照预置字典的原始流压缩,重复路径和模型标识几乎不再占用字节', + '核对边界用例:空数组、空对象、中文标点、表情符号及原型同名普通键均须严格等价', + '对冷启动重连场景,采用分层前缀哈希或紧凑摘要握手可避免每次上传数十千字节清单', + '注意在 diff 前先校验所有 work 节点确实携带统一页级后缀,避免误改异常数据', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-sonnet-4-5', + 'claude-opus-4-1', + 'gpt-5.3-codex', + 'gemini-2.5-pro', + 'deepseek-r1-0528', + 'qwen3-coder-480b', + ], + tagsPool: [ + 'device-link', 'perf', 'sync', 'mobile', 'relay', 'p0', 'p1', + 'refactor', 'sqlite', 'rpc', 'telemetry', 'ci', 'security', 'ux', + ], + sessionTitles: [ + '重构 device-link 跨设备增量同步协议', + 'Fix mobile cold-reconnect history delta miss', + '优化弱网 JSON 压缩与字典复用策略', + 'Investigate provider quota sidebar polling lag', + '排查 schedule 侧栏索引高频刷新流量消耗', + 'Implement binary patch encoder for sessions list', + '修复并发 stale-base 读取回退全文问题', + 'Audit SessionMessageReuse cache eviction bounds', + '支持多轮 Merkle 集合调和协议实验', + 'Optimize SQLite WAL checkpoint during streaming', + '解决 CJK 长文本流式追加重复传输瓶颈', + 'Verify deterministic replay across macOS & Linux', + ], + toolNames: ['read_file', 'run_command', 'edit_file', 'grep_search', 'list_dir'], + workTitles: [ + 'Inspect device-link delta protocol', + 'Run unit test suite', + 'Measure wire bytes on mobile trace', + 'Patch revision suffix normalization', + 'Verify cold-reconnect cache parity', + 'Profile streaming message append cost', + ], + providers: [ + { id: 'anthropic', name: 'Anthropic Direct', kind: 'anthropic', baseUrl: 'https://api.anthropic.com/v1', region: 'us-east-1', tier: 'enterprise' }, + { id: 'openai', name: 'OpenAI Platform', kind: 'openai', baseUrl: 'https://api.openai.com/v1', region: 'us-west-2', tier: 'tier-5' }, + { id: 'google', name: 'Google AI Studio', kind: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', region: 'us-central1', tier: 'paid' }, + { id: 'vertex', name: 'Google Cloud Vertex AI', kind: 'vertex', baseUrl: 'https://us-central1-aiplatform.googleapis.com/v1', region: 'us-central1', tier: 'enterprise' }, + { id: 'bedrock', name: 'AWS Bedrock', kind: 'bedrock', baseUrl: 'https://bedrock-runtime.us-west-2.amazonaws.com', region: 'us-west-2', tier: 'enterprise' }, + { id: 'deepseek', name: 'DeepSeek API', kind: 'openai-compat', baseUrl: 'https://api.deepseek.com/v1', region: 'ap-east-1', tier: 'pro' }, + { id: 'openrouter', name: 'OpenRouter Gateway', kind: 'openai-compat', baseUrl: 'https://openrouter.ai/api/v1', region: 'global', tier: 'credits' }, + { id: 'xai', name: 'xAI Grok API', kind: 'openai-compat', baseUrl: 'https://api.x.ai/v1', region: 'us-west-1', tier: 'pro' }, + { id: 'qwen', name: 'Alibaba DashScope Qwen', kind: 'openai-compat', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', region: 'cn-beijing', tier: 'enterprise' }, + { id: 'moonshot', name: 'Moonshot Kimi API', kind: 'openai-compat', baseUrl: 'https://api.moonshot.cn/v1', region: 'cn-north-1', tier: 'pro' }, + { id: 'zhipu', name: 'Zhipu GLM OpenPlatform', kind: 'openai-compat', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', region: 'cn-east-1', tier: 'pro' }, + { id: 'minimax', name: 'MiniMax Coding Plan', kind: 'anthropic-compat', baseUrl: 'https://api.minimaxi.com/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'ollama-local', name: 'Local Ollama Studio', kind: 'ollama', baseUrl: 'http://127.0.0.1:11434/v1', region: 'local', tier: 'free' }, + { id: 'team-proxy', name: 'Internal LiteLLM Proxy', kind: 'openai-compat', baseUrl: 'https://llm-gateway.internal.example/v1', region: 'eu-central-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Nightly PR triage & CI digest', + '每小时同步上游安全通告', + 'Release branch changelog builder', + 'Mobile relay latency watchdog', + '清理过期工作区缓存与临时构建', + 'Weekly dependency vulnerability audit', + 'Eval Bank regression tracker', + '数据库 WAL 体积巡检任务', + ], + schedulePrompts: [ + 'Inspect open pull requests with failing checks, summarize root causes, and draft minimal fixes.', + '检查过去 1 小时内 relay 节点的 P95 延迟与断线重连日志,如异常则生成排查摘要。', + 'Collect merged commits since the last tag and prepare structured release notes grouped by subsystem.', + 'Audit disk usage of local session archives and flag workspaces exceeding 500 MiB.', + ], +}; + +function makeSymbol(rng, corpus) { + return `${rng.pick(corpus.symbolVerbs)}${rng.pick(corpus.symbolNouns)}`; +} + +function makeFilePath(rng, corpus) { + return `${rng.pick(corpus.subdirs)}/${rng.pick(corpus.fileStems)}.ts`; +} + +/** + * Generates realistic, high-entropy technical paragraphs combining unique identifiers, + * paths, line ranges, commit hashes, metrics, code fragments, and CJK+English prose. + */ +function makeUniqueParagraph(rng, corpus, seq) { + const kind = rng.int(0, 4); + const file = makeFilePath(rng, corpus); + const symA = makeSymbol(rng, corpus); + const symB = makeSymbol(rng, corpus); + const line = rng.int(18, 640); + const commit = rng.hex(10); + const bytesBefore = rng.int(12_000, 195_000); + const bytesAfter = Math.max(240, Math.floor(bytesBefore * (0.04 + rng.next() * 0.28))); + const ms = rng.int(4, 380); + + if (kind === 0) { + return `[${commit}] ${rng.pick(corpus.enObservations)} in \`${file}:${line}\` (\`${symA}\` -> \`${symB}\`): payload=${bytesBefore}B -> ${bytesAfter}B (${ms}ms, seq=${seq}). ${rng.pick(corpus.cjkTopics)}:${rng.pick(corpus.cjkActions)}。`; + } + if (kind === 1) { + const varA = `${rng.pick(corpus.symbolNouns).toLowerCase()}_${rng.hex(4)}`; + const varB = `tag_${rng.hex(6)}`; + return `\`\`\`ts\n// ${file}:${line} (${commit})\nexport function ${symA}(${varA}: Uint8Array, ${varB}: string) {\n const limit = ${rng.int(64, 4096)};\n return ${symB}(${varA}.subarray(0, Math.min(${varA}.byteLength, limit)), ${varB});\n}\n\`\`\`\n分析结论(#${seq}):针对「${rng.pick(corpus.cjkTopics)}」,${rng.pick(corpus.cjkActions)}(实测耗时 ${ms}ms,压缩后 ${bytesAfter}B)。`; + } + if (kind === 2) { + const reqId = `req-${rng.hex(8)}`; + const peerId = `peer-${rng.hex(6)}`; + return `Trace ${reqId} (${peerId}): ${rng.pick(corpus.enObservations)}. Checked \`${symA}\` at \`${file}:${line}-${line + rng.int(8, 45)}\` against commit \`${commit}\` (delta=${bytesAfter}B vs raw=${bytesBefore}B, ratio=${((bytesAfter / bytesBefore) * 100).toFixed(2)}%). 备注:${rng.pick(corpus.cjkTopics)} ✅`; + } + if (kind === 3) { + return `在排查 \`${file}\` 第 ${line} 行 \`${symA}\`(提交 \`${commit}\`)时观测到「${rng.pick(corpus.cjkTopics)}」,单次同步帧达到 ${bytesBefore} 字节。${rng.pick(corpus.cjkActions)},验证通过 ${rng.int(12, 96)} 组用例(${ms}ms,目标 ${bytesAfter}B)。`; + } + const errCode = `ERR_${rng.pick(corpus.symbolNouns).toUpperCase()}_${rng.int(100, 999)}`; + return `Diagnostic ${errCode} @ \`${file}:${line}\` [rev=${seq}, hash=${commit}]: \`${symA}\` returned ${bytesAfter}B after calling \`${symB}\`. ${rng.pick(corpus.enObservations)}; verified fallback parity without data drift (${ms}ms).`; +} + +function makeStreamAppendChunk(rng, corpus, seq) { + const file = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(8); + const line = rng.int(10, 580); + const val = rng.int(120, 98000); + if (rng.bool(0.5)) { + return `[chunk-${commit}] \`${file}:${line}\` \`${sym}()\`: ${rng.pick(corpus.enObservations)} (measured=${val}B, step=${seq}). ${rng.pick(corpus.cjkTopics)}。`; + } + return `(片段 ${commit})检查 \`${file}:${line}\` 中的 \`${sym}\`:${rng.pick(corpus.cjkActions)}(指标=${val},序号=${seq})。`; +} + +function makeThinkingChunk(rng, corpus, seq) { + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(6); + const n = rng.int(16, 4096); + if (rng.bool(0.5)) { + return `Checking \`${sym}\` (#${seq}, id=${commit}, budget=${n}B): ${rng.pick(corpus.enObservations)}. `; + } + return `思考(${commit}/#${seq}):关于「${rng.pick(corpus.cjkTopics)}」与 \`${sym}\`(${n}B),${rng.pick(corpus.cjkActions)}。`; +} + +function makeToolOutput(rng, corpus, seq) { + const f1 = makeFilePath(rng, corpus); + const f2 = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const h = rng.hex(10); + return [ + `${f1}:${rng.int(10, 400)}: export function ${sym}(ctx_${seq}) { /* ${h} */ }`, + `${f2}:${rng.int(10, 400)}: assert.equal(checksum, "${rng.hex(16)}");`, + `PASS ${rng.int(14, 68)}/${rng.int(68, 72)} assertions (${rng.int(42, 890)}ms, rss=${rng.int(34, 128)}MB)`, + ].join('\n'); +} + +function makeMessageText(rng, corpus, seq, paragraphs) { + const parts = []; + for (let i = 0; i < paragraphs; i += 1) { + parts.push(makeUniqueParagraph(rng, corpus, seq * 10 + i)); + } + return parts.join('\n\n'); +} + +function createInitialSessions(rng, corpus, baseTime) { + const sessions = []; + for (let i = 0; i < 160; i += 1) { + const id = `${corpus.idPrefix}-sess-${String(i + 1).padStart(4, '0')}-${rng.hex(4)}`; + const tagCount = rng.int(1, 3); + const tags = []; + for (let t = 0; t < tagCount; t += 1) { + const tag = rng.pick(corpus.tagsPool); + if (!tags.includes(tag)) tags.push(tag); + } + const input = rng.int(4000, 180000); + const output = rng.int(800, 42000); + const cacheRead = rng.int(10000, 600000); + const sym = makeSymbol(rng, corpus); + sessions.push({ + id, + title: `${rng.pick(corpus.sessionTitles)} [${sym} #${i + 1}]`, + workingDir: `${rng.pick(corpus.workingDirs)}/${rng.pick(corpus.fileStems)}`, + agentKind: rng.pick(corpus.agentKinds), + phase: i < 8 ? 'running' : rng.pick(['idle', 'idle', 'idle', 'waiting_approval', 'error']), + updatedAt: baseTime - i * rng.int(45_000, 300_000), + lastMessagePreview: `${rng.pick(corpus.cjkTopics)} · ${sym} (${rng.hex(8)}): ${rng.pick(corpus.enObservations).slice(0, 68)}`, + tokenUsage: { + input, + output, + cacheRead, + costUsd: Math.round((input * 0.000003 + output * 0.000015 + cacheRead * 0.0000003) * 10000) / 10000, + }, + tags, + unreadCount: i < 12 ? rng.int(0, 5) : 0, + pinned: i < 24, + modelLabel: rng.pick(corpus.modelLabels), + deviceId: rng.pick(corpus.devices), + deviceOnline: true, + }); + } + return sessions; +} + +function makeMessageItem(rng, corpus, sessionId, seq, timestamp, revSuffix) { + const isWork = seq % 5 === 4; + if (isWork) { + const workId = `${corpus.idPrefix}-${sessionId}-w${String(seq).padStart(4, '0')}`; + const sym = makeSymbol(rng, corpus); + return { + key: `work:${workId}`, + type: 'work', + summary: { + title: `${rng.pick(corpus.workTitles)} · ${sym} (#${seq})`, + status: 'done', + revision: `${workId}-r1${revSuffix}`, + durationMs: rng.int(180, 9400), + }, + children: [ + { + key: `work:${workId}:c1`, + type: 'work', + summary: { + title: `Step 1: ${rng.pick(corpus.toolNames)} ${makeFilePath(rng, corpus)}`, + status: 'done', + revision: `${workId}-c1-r1${revSuffix}`, + durationMs: rng.int(60, 2400), + }, + }, + ], + }; + } + const msgId = `${corpus.idPrefix}-${sessionId}-m${String(seq).padStart(4, '0')}`; + const role = seq % 2 === 0 ? 'user' : 'assistant'; + const paragraphs = role === 'user' ? rng.int(1, 2) : rng.int(3, 5); + const text = `[#${seq}] ${makeMessageText(rng, corpus, seq, paragraphs)}`; + const content = { text }; + const row = { + id: msgId, + role, + createdAt: timestamp, + remoteBodyVersion: sha256Hex(JSON.stringify(content)), + content, + }; + if (role === 'assistant') { + row.thinking = makeThinkingChunk(rng, corpus, seq) + makeThinkingChunk(rng, corpus, seq + 1); + if (seq % 3 === 1) { + row.toolCalls = [ + { + id: `tc-${seq}-${rng.hex(4)}`, + name: rng.pick(corpus.toolNames), + args: { + path: `${rng.pick(corpus.workingDirs)}/${makeFilePath(rng, corpus)}`, + limit: rng.int(50, 200), + }, + status: 'done', + output: makeToolOutput(rng, corpus, seq), + }, + ]; + } + } + return { + key: `msg:${msgId}`, + type: 'messages', + messages: [row], + }; +} + +function applyRevisionSuffix(items, oldSuffix, newSuffix) { + for (const item of items) { + if (item.type === 'work') { + if (item.summary && typeof item.summary.revision === 'string' && item.summary.revision.endsWith(oldSuffix)) { + item.summary.revision = item.summary.revision.slice(0, -oldSuffix.length) + newSuffix; + } + if (Array.isArray(item.children)) { + applyRevisionSuffix(item.children, oldSuffix, newSuffix); + } + } + } +} + +function createInitialSessionHistory(rng, corpus, sessionId, baseTime) { + const rev = 1; + const revSuffix = `:rev-${rev}`; + const items = []; + for (let seq = 1; seq <= 35; seq += 1) { + items.push(makeMessageItem(rng, corpus, sessionId, seq, baseTime - (36 - seq) * 18_000, revSuffix)); + } + return { + sessionId, + nextSeq: 36, + rev, + revSuffix, + streamingTicksLeft: 0, + runningWorkSummary: { + status: 'running', + activeTool: rng.pick(corpus.toolNames), + elapsedMs: 1200, + stepCount: 1, + lines: [`Initialized trace session ${sessionId} (${rng.hex(8)})`], + }, + items, + }; +} + +function createInitialProviders(rng, corpus, baseTime) { + const capabilityPool = ['tools', 'vision', 'reasoning', 'caching', 'streaming', 'json-schema']; + const providers = corpus.providers.map((p, idx) => { + const modelCount = 7 + (idx % 4); + const models = []; + for (let m = 0; m < modelCount; m += 1) { + const tier = m === 0 ? 'flagship' : m < 3 ? 'balanced' : m < 6 ? 'fast' : 'mini'; + const capCount = 3 + (m % 4); + models.push({ + id: `${p.id}/${tier}-v${(m % 5) + 1}.${idx % 3}-${rng.hex(3)}`, + label: `${p.name} ${tier.toUpperCase()} ${(m % 5) + 1}.${idx % 3}`, + description: `${p.name} ${tier} profile (${p.region}, ${makeSymbol(rng, corpus)}, rev-${rng.hex(6)}): ${rng.pick(corpus.enObservations)}`, + contextWindow: m < 3 ? 200_000 : m < 6 ? 128_000 : 64_000, + maxOutputTokens: m < 2 ? 32_768 : 16_384, + pricing: { + inputPerM: Math.round((0.15 + (modelCount - m) * 0.85) * 100) / 100, + outputPerM: Math.round((0.6 + (modelCount - m) * 3.1) * 100) / 100, + cacheReadPerM: Math.round((0.03 + (modelCount - m) * 0.12) * 100) / 100, + }, + capabilities: capabilityPool.slice(0, capCount), + deprecated: false, + defaultEffort: m < 2 ? 'high' : 'medium', + }); + } + const dailyLimit = 5_000_000 + idx * 1_500_000; + const usedPercent = Math.round(rng.next() * 450) / 10; + return { + id: p.id, + name: p.name, + kind: p.kind, + enabled: true, + status: 'healthy', + baseUrl: p.baseUrl, + region: p.region, + latencyMs: rng.int(110, 620), + checkedAt: baseTime, + quota: { + usedPercent, + remainingTokens: Math.round(dailyLimit * (1 - usedPercent / 100)), + dailyLimit, + resetAt: baseTime + 6 * 3600_000, + tier: p.tier, + }, + models, + }; + }); + return { + catalogVersion: 4, + generatedAt: baseTime, + activeProviderId: providers[0].id, + providers, + }; +} + +function createInitialSchedules(rng, corpus, baseTime) { + const crons = ['*/15 * * * *', '0 * * * *', '0 */4 * * *', '0 9 * * 1-5', '30 2 * * *']; + const jobs = []; + for (let i = 0; i < 40; i += 1) { + const recentRuns = []; + for (let r = 0; r < 6; r += 1) { + const startedAt = baseTime - (6 - r) * 3600_000 - i * 17_000; + const durationMs = rng.int(2400, 48000); + recentRuns.push({ + runId: `${corpus.idPrefix}-run-${i + 1}-${r + 1}-${rng.hex(4)}`, + startedAt, + finishedAt: startedAt + durationMs, + status: r === 4 && i % 9 === 0 ? 'failed' : 'succeeded', + durationMs, + summary: `${rng.pick(corpus.scheduleNames)} [${rng.hex(6)}] (${rng.int(1, 24)} items, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1200, 36000), + }); + } + jobs.push({ + id: `${corpus.idPrefix}-sched-${String(i + 1).padStart(3, '0')}`, + name: `${rng.pick(corpus.scheduleNames)} #${i + 1}`, + cron: rng.pick(crons), + prompt: `${rng.pick(corpus.schedulePrompts)} (${makeFilePath(rng, corpus)})`, + targetSessionId: `${corpus.idPrefix}-sess-${String((i % 30) + 1).padStart(4, '0')}`, + workspaceDir: rng.pick(corpus.workingDirs), + enabled: i % 11 !== 10, + nextRunAt: baseTime + rng.int(120_000, 7200_000), + lastStatus: recentRuns[recentRuns.length - 1].status, + recentRuns, + runSeq: 7, + }); + } + return { + indexVersion: 3, + updatedAt: baseTime, + totalJobs: jobs.length, + jobs, + }; +} + +export const DEFAULT_SCHEDULE_PROFILE = { + coldReconnectTicks: [34, 72, 110, 148, 184, 214], + hostEvictTicks: [52, 128, 198], + concurrentSpecs: [ + { tick: 24, channel: 'local-db:sessions:list' }, + { tick: 92, channel: 'local-db:messages:view' }, + { tick: 162, channel: 'local-db:sessions:list' }, + { tick: 204, channel: 'maker:provider:list' }, + ], +}; + +/** + * Generate a deterministic 240-RPC multi-channel Cindy sync trace. + */ +export function generateTrace({ + seed = 20260501, + corpus = DEFAULT_CORPUS, + scheduleProfile = DEFAULT_SCHEDULE_PROFILE, +} = {}) { + const rng = createRng(seed); + let clock = 1_765_000_000_000 + (seed % 1000) * 60_000; + + const sessions = createInitialSessions(rng, corpus, clock); + const histA = createInitialSessionHistory(rng, corpus, 'active-A', clock); + const histB = createInitialSessionHistory(rng, corpus, 'active-B', clock); + const providerCatalog = createInitialProviders(rng, corpus, clock); + const scheduleIndex = createInitialSchedules(rng, corpus, clock); + + let sessionsPollCount = 0; + let bulkStormCount = 0; + let deviceOnlineFlip = false; + + function mutateSessions(bulkOverride = false) { + sessionsPollCount += 1; + clock += rng.int(1500, 4500); + const isBulkStorm = bulkOverride || (sessionsPollCount > 2 && sessionsPollCount % 10 === 0); + if (isBulkStorm) { + bulkStormCount += 1; + deviceOnlineFlip = !deviceOnlineFlip; + const ratio = 0.60 + rng.next() * 0.15; + const count = Math.floor(sessions.length * ratio); + const indices = rng.shuffle(Array.from({ length: sessions.length }, (_, i) => i)).slice(0, count); + for (const idx of indices) { + const s = sessions[idx]; + s.deviceOnline = deviceOnlineFlip; + s.tokenUsage.cacheRead += rng.int(50, 900); + if (idx % 5 === 0) s.updatedAt = clock; + } + } + const mutateCount = rng.int(4, 12); + const picked = []; + for (let i = 0; i < mutateCount; i += 1) { + const idx = rng.int(0, Math.min(sessions.length - 1, 45)); + if (!picked.includes(idx)) picked.push(idx); + } + for (const idx of picked) { + const s = sessions[idx]; + s.updatedAt = clock - rng.int(0, 900); + s.phase = rng.pick(['running', 'idle', 'waiting_approval']); + s.tokenUsage.input += rng.int(200, 4500); + s.tokenUsage.output += rng.int(80, 1200); + s.tokenUsage.costUsd = Math.round( + (s.tokenUsage.input * 0.000003 + s.tokenUsage.output * 0.000015 + s.tokenUsage.cacheRead * 0.0000003) * 10000, + ) / 10000; + s.unreadCount = s.phase === 'running' ? s.unreadCount + 1 : 0; + if (rng.bool(0.5)) { + s.lastMessagePreview = `${rng.pick(corpus.cjkTopics)} · ${makeSymbol(rng, corpus)} (${rng.hex(6)}): ${rng.pick(corpus.enObservations).slice(0, 56)}`; + } + } + const moveCount = Math.min(picked.length, rng.int(2, 5)); + for (let m = 0; m < moveCount; m += 1) { + const idx = picked[m]; + if (idx > 0 && idx < sessions.length) { + const [row] = sessions.splice(idx, 1); + const dest = rng.int(0, Math.min(8, sessions.length)); + sessions.splice(dest, 0, row); + } + } + } + + function snapshotSessions(scope) { + if (scope === 'pinned') { + const pinned = sessions.filter((s) => s.pinned).slice(0, 40); + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'pinned', + totalCount: pinned.length, + activeDeviceId: corpus.devices[0], + sessions: pinned, + }); + } + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'all', + totalCount: sessions.length, + activeDeviceId: corpus.devices[0], + sessions, + }); + } + + function mutateHistory(hist, steps = 1) { + for (let s = 0; s < steps; s += 1) { + clock += rng.int(900, 2800); + const oldSuffix = hist.revSuffix; + hist.rev += 1; + const newSuffix = `:rev-${hist.rev}`; + applyRevisionSuffix(hist.items, oldSuffix, newSuffix); + hist.revSuffix = newSuffix; + + hist.runningWorkSummary.elapsedMs += rng.int(800, 3200); + hist.runningWorkSummary.stepCount += 1; + hist.runningWorkSummary.activeTool = rng.pick(corpus.toolNames); + hist.runningWorkSummary.lines.push( + `[rev ${hist.rev}] ${hist.runningWorkSummary.activeTool} ${makeSymbol(rng, corpus)} (${rng.hex(6)})`, + ); + if (hist.runningWorkSummary.lines.length > 6) { + hist.runningWorkSummary.lines.shift(); + } + + const lastItem = hist.items[hist.items.length - 1]; + const canStreamAppend = + hist.streamingTicksLeft > 0 + && lastItem + && lastItem.type === 'messages' + && lastItem.messages[0]?.role === 'assistant'; + + if (canStreamAppend) { + // Streaming text/thinking append (120–380 chars appended onto the last message!) + const msg = lastItem.messages[0]; + const appended = makeStreamAppendChunk(rng, corpus, hist.rev); + msg.content.text += `\n${appended}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + if (rng.bool(0.65) && typeof msg.thinking === 'string') { + msg.thinking += makeThinkingChunk(rng, corpus, hist.rev); + } + hist.streamingTicksLeft -= 1; + } else if (hist.items.length < 140) { + // Advance a conversation turn (user message + optional work step + new streaming assistant message) + const burst = rng.int(2, 4); + let lastAdded = null; + for (let b = 0; b < burst && hist.items.length < 140; b += 1) { + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + b * 250, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + lastAdded = item; + } + if (lastAdded && lastAdded.type === 'messages' && lastAdded.messages[0].role === 'assistant') { + hist.streamingTicksLeft = rng.int(3, 5); + } else if (hist.items.length < 140) { + // Ensure next item starts a streaming assistant turn + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + 900, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + hist.streamingTicksLeft = + item.type === 'messages' && item.messages[0].role === 'assistant' ? rng.int(3, 5) : 0; + } else { + hist.streamingTicksLeft = 0; + } + } else { + for (let i = hist.items.length - 1; i >= 0; i -= 1) { + const cand = hist.items[i]; + if (cand.type === 'messages' && cand.messages[0].role === 'assistant') { + const msg = cand.messages[0]; + msg.content.text += `\n${makeStreamAppendChunk(rng, corpus, hist.rev)}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + break; + } + } + } + } + } + + function snapshotHistory(hist, beforeIndex = null) { + if (beforeIndex !== null) { + const start = Math.max(0, beforeIndex - 28); + const slice = hist.items.slice(start, beforeIndex); + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: start > 0, + nextBefore: slice[0]?.key ?? null, + before: hist.items[beforeIndex]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: slice, + }); + } + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: true, + nextBefore: hist.items[0]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: hist.items, + }); + } + + function mutateProviders() { + clock += rng.int(1200, 3500); + providerCatalog.generatedAt = clock; + const statusChoices = ['healthy', 'healthy', 'healthy', 'degraded', 'rate_limited']; + const changedStatus = new Set([ + rng.int(0, providerCatalog.providers.length - 1), + rng.int(0, providerCatalog.providers.length - 1), + ]); + for (let i = 0; i < providerCatalog.providers.length; i += 1) { + const p = providerCatalog.providers[i]; + if (rng.bool(0.5) || changedStatus.has(i)) { + p.checkedAt = clock; + p.latencyMs = Math.max(45, p.latencyMs + rng.int(-35, 45)); + const nextPct = Math.min(99.9, Math.round((p.quota.usedPercent + rng.next() * 1.4) * 10) / 10); + p.quota.usedPercent = nextPct; + p.quota.remainingTokens = Math.max(0, Math.round(p.quota.dailyLimit * (1 - nextPct / 100))); + if (rng.bool(0.2)) { + p.quota.resetAt = clock + 6 * 3600_000; + } + } + if (changedStatus.has(i)) { + p.status = rng.pick(statusChoices); + } + } + } + + function mutateSchedules() { + clock += rng.int(1500, 4000); + scheduleIndex.updatedAt = clock; + const mutateCount = rng.int(1, 3); + const chosen = new Set(); + while (chosen.size < mutateCount) { + chosen.add(rng.int(0, scheduleIndex.jobs.length - 1)); + } + for (const idx of chosen) { + const job = scheduleIndex.jobs[idx]; + const durationMs = rng.int(1800, 42000); + const status = rng.bool(0.88) ? 'succeeded' : 'failed'; + const runEntry = { + runId: `${corpus.idPrefix}-run-${idx + 1}-${job.runSeq}-${rng.hex(4)}`, + startedAt: clock - durationMs, + finishedAt: clock, + status, + durationMs, + summary: `${job.name} [${rng.hex(6)}] (${rng.int(1, 20)} records, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1400, 29000), + }; + job.runSeq += 1; + job.lastStatus = status; + job.nextRunAt = clock + rng.int(900_000, 7200_000); + job.recentRuns.push(runEntry); + if (job.recentRuns.length > 6) { + job.recentRuns.shift(); + } + } + } + + const concurrentByTick = new Map(scheduleProfile.concurrentSpecs.map((c) => [c.tick, c.channel])); + const coldReconnectSet = new Set(scheduleProfile.coldReconnectTicks); + const hostEvictSet = new Set(scheduleProfile.hostEvictTicks); + + const targets = { + 'local-db:sessions:list': 76, + 'local-db:messages:view': 98, + 'maker:provider:list': 28, + 'maker:schedule:list-sidebar-index-runs': 30, + }; + const emitted = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + const channelOrder = [ + 'local-db:messages:view', + 'local-db:sessions:list', + 'maker:provider:list', + 'maker:schedule:list-sidebar-index-runs', + ]; + const totalNonConcurrent = 232; + const tickChannels = []; + for (let i = 0; i < totalNonConcurrent; i += 1) { + let bestChannel = null; + let bestDeficit = -Infinity; + for (const ch of channelOrder) { + if (emitted[ch] >= targets[ch]) continue; + const expected = ((i + 1) * targets[ch]) / totalNonConcurrent; + const deficit = expected - emitted[ch]; + if (deficit > bestDeficit) { + bestDeficit = deficit; + bestChannel = ch; + } + } + emitted[bestChannel] += 1; + tickChannels.push(bestChannel); + } + + const steps = []; + let rpcCounter = 0; + let nonConcurrentIdx = 0; + let sessionReadSeq = 0; + let msgReadSeq = 0; + let rawJsonBytes = 0; + const channelCounts = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + + function makeRpcRead(channel, forcePrimary = false, forceSession = null) { + rpcCounter += 1; + channelCounts[channel] += 1; + const id = `rpc-${String(rpcCounter).padStart(4, '0')}`; + let argsKey; + let groundTruthValue; + + if (channel === 'local-db:sessions:list') { + sessionReadSeq += 1; + mutateSessions(false); + const isPinned = !forcePrimary && sessionReadSeq % 5 === 0; + const scope = isPinned ? 'pinned' : 'all'; + argsKey = JSON.stringify({ scope, limit: isPinned ? 40 : 160 }); + groundTruthValue = snapshotSessions(scope); + } else if (channel === 'local-db:messages:view') { + msgReadSeq += 1; + const useA = forceSession !== null ? forceSession === 'A' : (msgReadSeq % 2 === 1); + const hist = useA ? histA : histB; + mutateHistory(hist, 1); + const isPaginated = !forcePrimary && msgReadSeq >= 10 && msgReadSeq % 8 === 2 && hist.items.length > 35; + if (isPaginated) { + const beforeIndex = Math.min(hist.items.length - 5, 30 + (msgReadSeq % 3) * 10); + const beforeKey = hist.items[beforeIndex].key; + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, before: beforeKey, limit: 28 }); + groundTruthValue = snapshotHistory(hist, beforeIndex); + } else { + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, limit: 140 }); + groundTruthValue = snapshotHistory(hist, null); + } + } else if (channel === 'maker:provider:list') { + mutateProviders(); + argsKey = JSON.stringify({ includeModels: true, includeQuotas: true }); + groundTruthValue = cloneJson(providerCatalog); + } else if (channel === 'maker:schedule:list-sidebar-index-runs') { + mutateSchedules(); + argsKey = JSON.stringify({ limit: 40, recentRuns: 6 }); + groundTruthValue = cloneJson({ + indexVersion: scheduleIndex.indexVersion, + updatedAt: scheduleIndex.updatedAt, + totalJobs: scheduleIndex.totalJobs, + jobs: scheduleIndex.jobs.map(({ runSeq: _r, ...rest }) => rest), + }); + } else { + throw new Error(`Unknown channel: ${channel}`); + } + + rawJsonBytes += Buffer.byteLength(JSON.stringify(groundTruthValue), 'utf8'); + return { id, channel, argsKey, groundTruthValue }; + } + + let reconnectNum = 0; + let evictNum = 0; + + for (let tick = 0; tick < 236; tick += 1) { + if (coldReconnectSet.has(tick)) { + reconnectNum += 1; + mutateSessions(false); + mutateHistory(histA, rng.int(2, 4)); + mutateHistory(histB, rng.int(2, 3)); + mutateProviders(); + mutateSchedules(); + steps.push({ + type: 'cold_reconnect', + label: `mobile-cold-reconnect-${reconnectNum}`, + }); + } + if (hostEvictSet.has(tick)) { + evictNum += 1; + mutateSessions(false); + mutateHistory(histA, 1); + steps.push({ + type: 'host_evict', + label: `host-volatile-evict-${evictNum}`, + }); + } + + if (concurrentByTick.has(tick)) { + const ch = concurrentByTick.get(tick); + const forcedSess = ch === 'local-db:messages:view' ? 'A' : null; + const r1 = makeRpcRead(ch, true, forcedSess); + const r2 = makeRpcRead(ch, true, forcedSess); + steps.push({ + type: 'concurrent_rpc', + reads: [r1, r2], + }); + } else { + const ch = tickChannels[nonConcurrentIdx]; + nonConcurrentIdx += 1; + steps.push({ + type: 'rpc', + ...makeRpcRead(ch, false, null), + }); + } + } + + return { + seed, + meta: { + totalRpcs: rpcCounter, + channelCounts, + coldReconnectCount: reconnectNum, + hostEvictCount: evictNum, + concurrentPairCount: scheduleProfile.concurrentSpecs.length, + bulkStormCount, + finalHistoryLengthA: histA.items.length, + finalHistoryLengthB: histB.items.length, + rawJsonBytes, + }, + steps, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/candidate/package.json b/questions/opt-device-link-delta-sync/v1/candidate/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v1/candidate/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v1/candidate/src/sync-protocol.mjs new file mode 100644 index 0000000..9a56c1c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/src/sync-protocol.mjs @@ -0,0 +1,708 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Authentic Cindy device-link baseline: + * - invokeDelta enabled ONLY on `local-db:sessions:list` with MAX_DEPTH = 2, + * MAX_DELTA_RATIO = 0.5 abort cliff, MAX_UNVERIFIED_DELTAS = 8 reset cliff, + * and single-slot base tracking. + * - historyViewDelta item-level replacement + SessionMessageReuse 64-hex SHA-256 + * manifest on `local-db:messages:view`. + * - Plain ifNoneMatch + gzipBase64 JSON on all other channels. + */ + +const INVOKE_DELTA_CHANNELS = new Set(['local-db:sessions:list']); +const MESSAGES_VIEW_CHANNEL = 'local-db:messages:view'; +const MAX_DEPTH = 2; +const MAX_DELTA_RATIO = 0.5; +const MAX_UNVERIFIED_DELTAS = 8; +const INVOKE_TRANSFER_MIN_GZIP_BYTES = 1024; +const MAX_REUSE_MANIFEST_ENTRIES = 256; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function sha256Hex(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex'); +} + +function encodeJsonBytes(obj) { + return encoder.encode(JSON.stringify(obj)); +} + +function decodeJsonBytes(bytes) { + return JSON.parse(decoder.decode(bytes)); +} + +function gzipBase64(text) { + return zlib.gzipSync(Buffer.from(text, 'utf8')).toString('base64'); +} + +function gunzipBase64(b64) { + return zlib.gunzipSync(Buffer.from(b64, 'base64')).toString('utf8'); +} + +function samePlainKeys(a, b) { + const left = Object.keys(a); + const right = Object.keys(b); + return left.length === right.length && left.every((k, i) => k === right[i]); +} + +function invokeDiff(base, next, depth) { + if (depth < MAX_DEPTH && Array.isArray(base) && Array.isArray(next)) { + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + let reused = 0; + let inPlace = base.length === next.length; + const a = next.map((element, pos) => { + const idx = byText.get(JSON.stringify(element)); + if (idx === undefined) { + inPlace = false; + return [element]; + } + reused += 1; + if (idx !== pos) inPlace = false; + return idx; + }); + if (inPlace) return undefined; + return reused > 0 ? { a } : { s: next }; + } + if (depth < MAX_DEPTH && isPlainObject(base) && isPlainObject(next) && samePlainKeys(base, next)) { + const o = {}; + let changed = false; + for (const key of Object.keys(next)) { + const child = invokeDiff(base[key], next[key], depth + 1); + if (child !== undefined) { + o[key] = child; + changed = true; + } + } + return changed ? { o } : undefined; + } + return JSON.stringify(base) === JSON.stringify(next) ? undefined : { s: next }; +} + +function invokeApply(base, patch, depth) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if (depth >= MAX_DEPTH) throw new Error('delta patch too deep'); + if ('a' in patch) { + return patch.a.map((entry) => (typeof entry === 'number' ? base[entry] : entry[0])); + } + if ('o' in patch) { + const result = {}; + for (const key of Object.keys(base)) { + const child = Object.prototype.hasOwnProperty.call(patch.o, key) ? patch.o[key] : undefined; + result[key] = invokeApply(base[key], child, depth + 1); + } + return result; + } + throw new Error('invalid delta patch'); +} + +function computeInvokePatch(baseText, nextText) { + const base = JSON.parse(baseText); + const next = JSON.parse(nextText); + const patch = invokeDiff(base, next, 0); + if (!patch || 's' in patch) return null; + if (JSON.stringify(patch).length > nextText.length * MAX_DELTA_RATIO) return null; + return patch; +} + +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function stripSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => + typeof rev === 'string' && rev.endsWith(suffix) ? rev.slice(0, -suffix.length) : rev, + ); +} + +function appendSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)); +} + +function isReusableMessage(row) { + return ( + isPlainObject(row) + && typeof row.id === 'string' + && row.id.length > 0 + && (row.role === 'assistant' || row.role === 'user') + && typeof row.remoteBodyVersion === 'string' + && /^[a-f0-9]{64}$/.test(row.remoteBodyVersion) + && isPlainObject(row.content) + && typeof row.content.text === 'string' + ); +} + +function mapMessageRows(value, fn) { + if (!isPlainObject(value) || !Array.isArray(value.items)) return value; + return { + ...value, + items: value.items.map((item) => { + if (isPlainObject(item) && item.type === 'messages' && Array.isArray(item.messages)) { + return { + ...item, + messages: item.messages.map((row) => (isPlainObject(row) ? fn(row) : row)), + }; + } + return item; + }), + }; +} + +function parseSessionArgs(argsKey) { + try { + const parsed = JSON.parse(argsKey); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +export function createHostSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // Single latest base per (channel, argsKey) for invokeDelta + const invokeBases = new Map(); + let invokeBaseBytes = 0; + + // Volatile historyViewDelta bases keyed by token + const historyBases = new Map(); + let historyBaseBytes = 0; + let tokenSeq = 0; + + function evictVolatileBases() { + invokeBases.clear(); + invokeBaseBytes = 0; + historyBases.clear(); + historyBaseBytes = 0; + } + + function rememberInvokeBase(key, tag, text) { + const prev = invokeBases.get(key); + if (prev) { + invokeBaseBytes -= prev.text.length; + invokeBases.delete(key); + } + if (text.length > maxCacheBytes / 2) return; + invokeBases.set(key, { tag, text }); + invokeBaseBytes += text.length; + while (invokeBases.size > 32 || invokeBaseBytes > maxCacheBytes / 2) { + const oldestKey = invokeBases.keys().next().value; + const oldest = invokeBases.get(oldestKey); + invokeBaseBytes -= oldest.text.length; + invokeBases.delete(oldestKey); + } + } + + function rememberHistoryBase(token, itemsJson) { + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + if (bytes > maxCacheBytes / 2) return false; + historyBases.set(token, { itemsJson, bytes }); + historyBaseBytes += bytes; + while (historyBases.size > 16 || historyBaseBytes > maxCacheBytes / 2) { + const oldestKey = historyBases.keys().next().value; + const oldest = historyBases.get(oldestKey); + historyBaseBytes -= oldest.bytes; + historyBases.delete(oldestKey); + } + return true; + } + + function encodeTransferEnvelope(value, ifNoneMatch, allowGzip) { + const text = JSON.stringify(value); + const tag = sha256Hex(text); + if (ifNoneMatch && ifNoneMatch === tag) { + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, notModified: true } }); + } + const utf8Bytes = Buffer.byteLength(text, 'utf8'); + if (allowGzip && utf8Bytes >= INVOKE_TRANSFER_MIN_GZIP_BYTES) { + const b64 = gzipBase64(text); + if (b64.length + 48 < utf8Bytes * 0.9) { + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, gzipBase64: b64 } }); + } + } + return encodeJsonBytes({ ok: true, result: value, transfer: { tag } }); + } + + function handleHistoryView(argsKey, req, groundTruthValue) { + const parsedArgs = parseSessionArgs(argsKey); + const isLatestPage = parsedArgs.before == null; + let payloadValue = groundTruthValue; + + // 1. Apply historyViewDelta if latest page and client opted in + if ( + isLatestPage + && req.historyDelta?.version === 1 + && isPlainObject(groundTruthValue) + && Array.isArray(groundTruthValue.items) + ) { + const suffix = + typeof groundTruthValue.revisionSuffix === 'string' + && groundTruthValue.revisionSuffix + && allWorkRevisionsEndWith(groundTruthValue.items, groundTruthValue.revisionSuffix) + ? groundTruthValue.revisionSuffix + : undefined; + const strippedJson = groundTruthValue.items.map((item) => JSON.stringify(stripSuffix(item, suffix))); + const baseEntry = req.historyDelta.base ? historyBases.get(req.historyDelta.base) : undefined; + let outItems = groundTruthValue.items; + let matchedBase; + + if (baseEntry) { + matchedBase = req.historyDelta.base; + const baseMap = new Map(); + for (let i = 0; i < baseEntry.itemsJson.length; i += 1) { + if (!baseMap.has(baseEntry.itemsJson[i])) baseMap.set(baseEntry.itemsJson[i], i); + } + const compressedItems = []; + let runStart = -1; + let runCount = 0; + const flushRun = () => { + if (runCount > 0) { + compressedItems.push({ type: 'same', from: runStart, count: runCount }); + runStart = -1; + runCount = 0; + } + }; + for (let i = 0; i < strippedJson.length; i += 1) { + const baseIdx = baseMap.get(strippedJson[i]); + if (baseIdx !== undefined) { + if (runCount > 0 && baseIdx === runStart + runCount) { + runCount += 1; + } else { + flushRun(); + runStart = baseIdx; + runCount = 1; + } + } else { + flushRun(); + compressedItems.push(groundTruthValue.items[i]); + } + } + flushRun(); + outItems = compressedItems; + } + + tokenSeq += 1; + const token = `hvd-${tokenSeq}`; + const stored = rememberHistoryBase(token, strippedJson); + payloadValue = { + ...groundTruthValue, + items: outItems, + historyDelta: { + version: 1, + ...(stored ? { token } : {}), + ...(matchedBase ? { base: matchedBase } : {}), + ...(suffix ? { revisionSuffix: suffix } : {}), + }, + }; + } + + // 2. Apply SessionMessageReuse body omission if client advertised known [id, sha256] pairs + if (req.messageBodies?.version === 1 && Array.isArray(req.messageBodies.known) && req.messageBodies.known.length > 0) { + const known = new Map(); + for (const pair of req.messageBodies.known) { + if (Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string') { + known.set(pair[0], pair[1]); + } + } + let strippedAny = false; + const strippedVal = mapMessageRows(payloadValue, (row) => { + if (isReusableMessage(row) && known.get(row.id) === row.remoteBodyVersion) { + strippedAny = true; + const { content: _c, ...rest } = row; + return rest; + } + return row; + }); + if (strippedAny) { + payloadValue = { format: 'message-bodies-v1', value: strippedVal }; + } + } + + return encodeTransferEnvelope(payloadValue, req.transfer?.ifNoneMatch, req.transfer?.gzip === 1); + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue }) { + const req = decodeJsonBytes(requestBytes); + + if (channel === MESSAGES_VIEW_CHANNEL) { + return handleHistoryView(argsKey, req, groundTruthValue); + } + + const text = JSON.stringify(groundTruthValue); + const tag = sha256Hex(text); + const transfer = req.transfer || {}; + + if (transfer.ifNoneMatch && transfer.ifNoneMatch === tag) { + if (transfer.delta === 1 && INVOKE_DELTA_CHANNELS.has(channel)) { + rememberInvokeBase(`${channel}\u0000${argsKey}`, tag, text); + } + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, notModified: true } }); + } + + if (transfer.delta === 1 && INVOKE_DELTA_CHANNELS.has(channel)) { + const key = `${channel}\u0000${argsKey}`; + const base = invokeBases.get(key); + rememberInvokeBase(key, tag, text); + if (base && transfer.ifNoneMatch && base.tag === transfer.ifNoneMatch) { + const patch = computeInvokePatch(base.text, text); + if (patch) { + const patchText = JSON.stringify(patch); + const patchBytes = Buffer.byteLength(patchText, 'utf8'); + if (transfer.gzip === 1 && patchBytes >= INVOKE_TRANSFER_MIN_GZIP_BYTES) { + const b64 = gzipBase64(patchText); + if (b64.length + 16 < patchBytes * 0.9) { + return encodeJsonBytes({ + ok: true, + result: null, + transfer: { tag, delta: { base: base.tag, length: text.length, gzipBase64: b64 } }, + }); + } + } + return encodeJsonBytes({ + ok: true, + result: null, + transfer: { tag, delta: { base: base.tag, length: text.length, patch } }, + }); + } + } + } + + return encodeTransferEnvelope(groundTruthValue, transfer.ifNoneMatch, transfer.gzip === 1); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + const maxPersistentBodyEntries = options.maxPersistentBodyEntries ?? DEFAULT_MAX_PERSISTENT_BODY_ENTRIES; + + // Volatile caches (cleared on cold reconnect) + const invokeCache = new Map(); + let invokeCacheBytes = 0; + const historyCache = new Map(); + let historyCacheBytes = 0; + const inflight = new Map(); + + // Persistent immutable message body cache (SessionMessageReuse) + // key: `${sessionId}\u0000${msgId}` -> { sessionId, id, version, contentJson } + const persistentBodies = new Map(); + let persistentBodyBytes = 0; + + function loadPersistentState(bytes) { + persistentBodies.clear(); + persistentBodyBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const json = zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8'); + const rows = JSON.parse(json); + if (!Array.isArray(rows)) return; + for (const entry of rows) { + if (!entry || typeof entry.sessionId !== 'string' || typeof entry.id !== 'string') continue; + rememberPersistentBody(entry.sessionId, entry.id, entry.version, entry.contentJson); + } + } catch { + // Ignore corrupt persistent blob + } + } + + function rememberPersistentBody(sessionId, id, version, contentJson) { + const key = `${sessionId}\u0000${id}`; + const prev = persistentBodies.get(key); + if (prev) { + persistentBodyBytes -= prev.contentJson.length; + persistentBodies.delete(key); + } + if (contentJson.length > maxPersistentBytes / 2) return; + persistentBodies.set(key, { sessionId, id, version, contentJson }); + persistentBodyBytes += contentJson.length; + while (persistentBodies.size > maxPersistentBodyEntries || persistentBodyBytes > maxPersistentBytes) { + const oldestKey = persistentBodies.keys().next().value; + const oldest = persistentBodies.get(oldestKey); + persistentBodyBytes -= oldest.contentJson.length; + persistentBodies.delete(oldestKey); + } + } + + function exportPersistentState() { + const rows = Array.from(persistentBodies.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.shift(); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snapshot = exportPersistentState(); + invokeCache.clear(); + invokeCacheBytes = 0; + historyCache.clear(); + historyCacheBytes = 0; + inflight.clear(); + loadPersistentState(snapshot); + } + + function rememberInvokeCache(key, entry) { + const prev = invokeCache.get(key); + if (prev) { + invokeCacheBytes -= prev.text.length; + invokeCache.delete(key); + } + if (entry.text.length > maxCacheBytes / 2) return; + invokeCache.set(key, entry); + invokeCacheBytes += entry.text.length; + while (invokeCache.size > 32 || invokeCacheBytes > maxCacheBytes / 2) { + const oldestKey = invokeCache.keys().next().value; + const oldest = invokeCache.get(oldestKey); + invokeCacheBytes -= oldest.text.length; + invokeCache.delete(oldestKey); + } + } + + function rememberHistoryCache(key, entry) { + const prev = historyCache.get(key); + if (prev) { + historyCacheBytes -= prev.bytes; + historyCache.delete(key); + } + if (entry.bytes > maxCacheBytes / 2) return; + historyCache.set(key, entry); + historyCacheBytes += entry.bytes; + while (historyCache.size > 16 || historyCacheBytes > maxCacheBytes / 2) { + const oldestKey = historyCache.keys().next().value; + const oldest = historyCache.get(oldestKey); + historyCacheBytes -= oldest.bytes; + historyCache.delete(oldestKey); + } + } + + if (options.persistentState) { + loadPersistentState(options.persistentState); + } + + function beginRead({ readId, channel, argsKey }) { + const cacheKey = `${channel}\u0000${argsKey}`; + + if (channel === MESSAGES_VIEW_CHANNEL) { + const parsedArgs = parseSessionArgs(argsKey); + const sessionId = typeof parsedArgs.sessionId === 'string' ? parsedArgs.sessionId : ''; + const isLatestPage = parsedArgs.before == null; + const hvdKey = `${sessionId}\u0000latest`; + const hvdSnap = isLatestPage ? historyCache.get(hvdKey) : undefined; + + // Snapshot known bodies from persistent cache when no volatile historyDelta base exists + const bodySnap = new Map(); + const knownPairs = []; + if (!hvdSnap && sessionId) { + const allForSession = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) allForSession.push(entry); + } + const recent = allForSession.slice(-MAX_REUSE_MANIFEST_ENTRIES); + for (const entry of recent) { + bodySnap.set(entry.id, entry); + knownPairs.push([entry.id, entry.version]); + } + } + + const reqObj = { + transfer: { + gzip: 1, + }, + ...(isLatestPage + ? { historyDelta: { version: 1, ...(hvdSnap ? { base: hvdSnap.token } : {}) } } + : {}), + ...(knownPairs.length > 0 ? { messageBodies: { version: 1, known: knownPairs } } : {}), + }; + inflight.set(readId, { + channel, + cacheKey, + sessionId, + hvdKey, + hvdSnap, + bodySnap, + cachedTransfer: undefined, + }); + return encodeJsonBytes(reqObj); + } + + const cached = invokeCache.get(cacheKey); + const transfer = { gzip: 1 }; + // Simulate Cindy Mobile's MAX_UNVERIFIED_DELTAS = 8 reset cliff + if (cached && (cached.unverified ?? 0) < MAX_UNVERIFIED_DELTAS) { + transfer.ifNoneMatch = cached.tag; + } + if (INVOKE_DELTA_CHANNELS.has(channel)) { + transfer.delta = 1; + } + inflight.set(readId, { channel, cacheKey, cached }); + return encodeJsonBytes({ transfer }); + } + + function decodeTransfer(resp, cached, cacheKey) { + const transfer = resp.transfer || {}; + if (transfer.notModified) { + if (!cached || cached.tag !== transfer.tag) throw new Error('unexpected notModified'); + const val = JSON.parse(cached.text); + rememberInvokeCache(cacheKey, { tag: transfer.tag, text: cached.text, unverified: cached.unverified }); + return val; + } + if (transfer.delta) { + const delta = transfer.delta; + if (!cached || cached.tag !== delta.base) throw new Error('unexpected delta base'); + const patch = typeof delta.gzipBase64 === 'string' ? JSON.parse(gunzipBase64(delta.gzipBase64)) : delta.patch; + const value = invokeApply(JSON.parse(cached.text), patch, 0); + const text = JSON.stringify(value); + rememberInvokeCache(cacheKey, { + tag: transfer.tag, + text, + unverified: (cached.unverified ?? 0) + 1, + }); + return value; + } + let text; + let value; + if (typeof transfer.gzipBase64 === 'string') { + text = gunzipBase64(transfer.gzipBase64); + value = JSON.parse(text); + } else { + value = resp.result; + text = JSON.stringify(value); + } + if (transfer.tag) { + rememberInvokeCache(cacheKey, { tag: transfer.tag, text, unverified: 0 }); + } + return value; + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + inflight.delete(readId); + const resp = decodeJsonBytes(responseBytes); + + if (state.channel === MESSAGES_VIEW_CHANNEL) { + let decoded = decodeTransfer(resp, state.cachedTransfer, state.cacheKey); + + // 1. Restore SessionMessageReuse omitted message bodies + const packed = isPlainObject(decoded) && decoded.format === 'message-bodies-v1'; + const inner = packed ? decoded.value : decoded; + decoded = mapMessageRows(inner, (row) => { + let restored = row; + if (packed && !Object.prototype.hasOwnProperty.call(row, 'content')) { + const hit = state.bodySnap.get(row.id); + if (!hit || hit.version !== row.remoteBodyVersion) { + throw new Error(`Missing persistent body for ${row.id}`); + } + restored = { ...row, content: JSON.parse(hit.contentJson) }; + } + if (state.sessionId && isReusableMessage(restored)) { + rememberPersistentBody( + state.sessionId, + restored.id, + restored.remoteBodyVersion, + JSON.stringify(restored.content), + ); + } + return restored; + }); + + // 2. Restore historyViewDelta `same` runs + if (isPlainObject(decoded) && Array.isArray(decoded.items) && decoded.historyDelta?.version === 1) { + const { historyDelta: delta, ...page } = decoded; + const suffix = typeof delta.revisionSuffix === 'string' && delta.revisionSuffix ? delta.revisionSuffix : undefined; + const items = []; + for (const item of decoded.items) { + if (isPlainObject(item) && item.type === 'same') { + if (!state.hvdSnap || delta.base !== state.hvdSnap.token) { + throw new Error('historyViewDelta base mismatch'); + } + for (let i = item.from; i < item.from + item.count; i += 1) { + items.push(appendSuffix(JSON.parse(state.hvdSnap.itemsJson[i]), suffix)); + } + } else { + items.push(item); + } + } + const restoredPage = { ...page, items }; + if (typeof delta.token === 'string') { + const itemsJson = items.map((it) => JSON.stringify(stripSuffix(it, suffix))); + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + rememberHistoryCache(state.hvdKey, { token: delta.token, itemsJson, bytes }); + } + return { done: true, value: restoredPage }; + } + return { done: true, value: decoded }; + } + + const value = decodeTransfer(resp, state.cached, state.cacheKey); + return { done: true, value }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/candidate/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..3795c0f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated trace parity check on public seed', async () => { + const fullTrace = generateTrace({ seed: 20260501 }); + // Run the first 60 steps (covers all 4 channels, a concurrent pair, cold reconnect, and host evict) + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/CONTRACT.md b/questions/opt-device-link-delta-sync/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..34b1c2a --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,93 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (may be one of the 4 Cindy channels or any arbitrary test channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 8s` for a full 240-RPC trace). +4. **Generalization**: Evaluation runs on unseen held-out seeds, corpora, channel payloads, and event timings. Do not hardcode trace strings or schema assumptions that break on unseen payloads. diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..8e0ce3f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,10 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic 240-RPC two-process benchmark across all 4 Cindy channels reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, and compression ratio vs raw JSON diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/TASK.md b/questions/opt-device-link-delta-sync/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..4ce97c8 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/TASK.md @@ -0,0 +1,25 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC delta synchronization and cold-cache reconciliation protocol (`src/sync-protocol.mjs`), extracted from production desktop-to-mobile remote sessions (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). + +## Observed Production Bottlenecks + +In a typical mobile-over-cellular session polling 4 read-heavy RPC channels across ~240 reads (~20 MiB of raw JSON), the current baseline protocol burns over **2.0 MiB** of metered wire traffic (upstream + downstream combined) due to compounding architectural limits: + +1. **Channel silo**: `invokeDelta` is enabled ONLY on `local-db:sessions:list`; structured catalogs (`maker:provider:list`, ~45 KiB/poll) and schedule indices (`maker:schedule:list-sidebar-index-runs`, ~28 KiB/poll) resend full gzipped JSON on every single poll even when only quota numbers or 1–3 run entries changed. +2. **Coarse row-level diff & abort cliffs**: `invokeDelta` stops at `MAX_DEPTH = 2` (replacing entire session rows whenever a single field changes), aborts to a full snapshot whenever the uncompressed JSON patch exceeds `MAX_DELTA_RATIO = 0.5` (triggered during bulk device/tag refreshes where >55% of rows change 1 field), and resets to a full snapshot every `MAX_UNVERIFIED_DELTAS = 8` incremental reads. +3. **Expensive streaming appends & suffix churn in `local-db:messages:view`**: `historyViewDelta` only deduplicates completely identical items; appending 100–400 characters of streaming assistant text/thinking forces the entire multi-kilobyte message item to be re-sent on every poll, while page-wide `revisionSuffix` updates touch every `work` item. +4. **Bloated cold-cache manifests & weak cold reconciliation**: After mobile background-kill & cold reconnect (or host volatile-base eviction), `SessionMessageReuse` uploads up to 256 `[id, 64-hex-sha256]` pairs (~15–25 KiB upstream per read) only for `messages:view` and resends full gzipped snapshots for the other channels. +5. **Single/brittle base tracking & generic compression**: Concurrent in-flight reads with a slightly stale base fall back to full snapshots, and JSON patches carry heavy structural/key overhead without leveraging the already-synchronized base state. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every RPC read across all channels, pagination queries, streaming updates, arbitrary edge-case JSON shapes, mobile cold reconnects, host volatile-base evictions, and concurrent in-flight stale-base reads. +- Respect **strict two-process isolation**: Host and Client run in completely separate Node.js child processes communicating **only** via `Uint8Array` wire frames. No shared memory, filesystem, network, or side channels are permitted. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return a `Uint8Array` within `maxPersistentBytes` (default `2 MiB`), and every RPC must complete in at most `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended optimization goal**: Design any clean, general, deterministic two-party sync protocol inside `src/` to drive `total_wire_bytes` (sum of **all** upstream `requestBytes` and downstream `responseBytes` across **all** rounds and **all** RPCs) as low as possible — both on public benchmarks and on unseen held-out workloads with different seeds, payloads, vocabularies, and reconnect timings. +- Run `npm test` and `npm run bench` to verify exact parity and measure your wire-byte reduction. +- Record your analysis, protocol design, trade-offs, and verified benchmark results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/bench/workload.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..5eaab10 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark(seed = 20260501) { + const trace = generateTrace({ seed }); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + seed, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + host_evictions: trace.meta.hostEvictCount, + concurrent_pairs: trace.meta.concurrentPairCount, + bulk_storms: trace.meta.bulkStormCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/rpc-harness.mjs new file mode 100644 index 0000000..03d2824 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/rpc-harness.mjs @@ -0,0 +1,293 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/trace-generator.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/trace-generator.mjs new file mode 100644 index 0000000..3621bc5 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/trace-generator.mjs @@ -0,0 +1,936 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic Mulberry32 PRNG. + */ +export function createRng(seed) { + let state = (seed >>> 0) || 1; + return { + next() { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }, + int(min, max) { + return min + Math.floor(this.next() * (max - min + 1)); + }, + pick(arr) { + return arr[Math.floor(this.next() * arr.length)]; + }, + bool(p = 0.5) { + return this.next() < p; + }, + hex(len) { + const chars = '0123456789abcdef'; + let out = ''; + for (let i = 0; i < len; i += 1) { + out += chars[Math.floor(this.next() * 16)]; + } + return out; + }, + shuffle(arr) { + const out = arr.slice(); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = Math.floor(this.next() * (i + 1)); + const tmp = out[i]; + out[i] = out[j]; + out[j] = tmp; + } + return out; + }, + }; +} + +function sha256Hex(str) { + return crypto.createHash('sha256').update(str, 'utf8').digest('hex'); +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +export const DEFAULT_CORPUS = { + idPrefix: 'pub', + devices: [ + 'dev-mac-studio-01', + 'dev-mbp-m4-02', + 'dev-linux-build-03', + 'dev-wsl-workstation-04', + ], + workingDirs: [ + '/Users/dev/workspace/cindy-core', + '/Users/dev/workspace/cindy-mobile', + '/Users/dev/workspace/cindy-relay', + '/Users/dev/workspace/eval-bank', + '/Users/dev/workspace/agent-sdk', + '/Users/dev/workspace/docs-site', + ], + subdirs: [ + 'packages/device-link/src', + 'packages/maker-shared/src', + 'apps/mobile/src/sync', + 'apps/desktop/src/main', + 'services/relay-edge/src', + 'crates/protocol/src', + 'tests/integration', + 'scripts/bench', + ], + fileStems: [ + 'invokeDelta', 'invokeTransfer', 'historyViewDelta', 'sessionMessageReuse', + 'routedClient', 'listingReadCoalescer', 'transportBacklog', 'pushTransfer', + 'nodeCompression', 'remoteAgent', 'metadataContinuity', 'setupSnapshot', + 'stallDiagnostics', 'peerRecovery', 'cacheBudget', 'streamAssembler', + 'frameCodec', 'merkleIndex', 'walCheckpoint', 'quotaTracker', + ], + symbolVerbs: [ + 'reconcile', 'compute', 'decode', 'encode', 'evict', 'normalize', 'compact', + 'verify', 'dispatch', 'coalesce', 'hydrate', 'serialize', 'inflate', 'prune', + 'merge', 'replay', 'checkpoint', 'validate', + ], + symbolNouns: [ + 'DeltaBase', 'HistoryPage', 'MessageBody', 'WireFrame', 'SnapshotRing', + 'RevisionSuffix', 'ColdManifest', 'SessionRow', 'QuotaBucket', 'RunWindow', + 'PrefixLadder', 'PatchOp', 'ChunkDigest', 'PeerCursor', 'TransferHeader', + 'KeyTable', 'StreamBuffer', 'CacheEntry', + ], + cjkTopics: [ + '跨设备弱网同步延迟', '批量行刷新触发阈值回退', '移动端冷重连摘要上行膨胀', + '流式文本追加导致整条消息重传', '工作摘要版本号后缀高频抖动', '并发读取基准淘汰错位', + '本地持久化缓存体积上限控制', '多通道结构化目录轮询冗余', '字典压缩窗口命中率下降', + '分页历史回溯与最新页缓存复用', '异步队列背压与帧边界对齐', '索引重排与键表编码开销', + '断连恢复后的冷缓存集合调和', '长日志代码块与多语言字符集校验', '任务状态栏高频更新节流', + '定时任务滑动窗口增量裁剪', + ], + enObservations: [ + 'Observed wire amplification during bulk metadata refresh across active peers', + 'Detected redundant retransmission of unchanged markdown prefixes while streaming', + 'Measured upstream handshake spike when uploading full 64-hex SHA-256 manifests', + 'Confirmed multi-snapshot ring avoids full-page fallback under pipelined reads', + 'Profiled deflate dictionary match ratio against prior synchronized base payload', + 'Validated exact JSON parity for empty containers, floats, null fields, and emoji', + 'Traced revision suffix propagation across nested work summary child nodes', + 'Benchmarked recursive keyed array diff against coarse depth-2 row replacement', + 'Audited persistent cache serialization size under mobile background termination', + 'Inspected pagination cursor overlap when scrolling older transcript segments', + 'Evaluated 2-RTT set reconciliation bandwidth on partial state divergence', + 'Checked varint length framing and key-table interning on structured provider lists', + ], + cjkActions: [ + '建议改为按主键递归比对字段,仅下发变动属性与紧凑索引序列', + '排查发现未命中易失基准时会直接回退整页快照,应结合持久化摘要跳过未变正文', + '实测在流式输出阶段采用前缀复用加尾部追加指令,可将单次下行体积压缩至原来的十分之一', + '需要同时保留最近多个已确认与在途基准,防止并发轮询携带旧标签时反复触发全量同步', + '对比普通压缩与基于旧快照预置字典的原始流压缩,重复路径和模型标识几乎不再占用字节', + '核对边界用例:空数组、空对象、中文标点、表情符号及原型同名普通键均须严格等价', + '对冷启动重连场景,采用分层前缀哈希或紧凑摘要握手可避免每次上传数十千字节清单', + '注意在 diff 前先校验所有 work 节点确实携带统一页级后缀,避免误改异常数据', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-sonnet-4-5', + 'claude-opus-4-1', + 'gpt-5.3-codex', + 'gemini-2.5-pro', + 'deepseek-r1-0528', + 'qwen3-coder-480b', + ], + tagsPool: [ + 'device-link', 'perf', 'sync', 'mobile', 'relay', 'p0', 'p1', + 'refactor', 'sqlite', 'rpc', 'telemetry', 'ci', 'security', 'ux', + ], + sessionTitles: [ + '重构 device-link 跨设备增量同步协议', + 'Fix mobile cold-reconnect history delta miss', + '优化弱网 JSON 压缩与字典复用策略', + 'Investigate provider quota sidebar polling lag', + '排查 schedule 侧栏索引高频刷新流量消耗', + 'Implement binary patch encoder for sessions list', + '修复并发 stale-base 读取回退全文问题', + 'Audit SessionMessageReuse cache eviction bounds', + '支持多轮 Merkle 集合调和协议实验', + 'Optimize SQLite WAL checkpoint during streaming', + '解决 CJK 长文本流式追加重复传输瓶颈', + 'Verify deterministic replay across macOS & Linux', + ], + toolNames: ['read_file', 'run_command', 'edit_file', 'grep_search', 'list_dir'], + workTitles: [ + 'Inspect device-link delta protocol', + 'Run unit test suite', + 'Measure wire bytes on mobile trace', + 'Patch revision suffix normalization', + 'Verify cold-reconnect cache parity', + 'Profile streaming message append cost', + ], + providers: [ + { id: 'anthropic', name: 'Anthropic Direct', kind: 'anthropic', baseUrl: 'https://api.anthropic.com/v1', region: 'us-east-1', tier: 'enterprise' }, + { id: 'openai', name: 'OpenAI Platform', kind: 'openai', baseUrl: 'https://api.openai.com/v1', region: 'us-west-2', tier: 'tier-5' }, + { id: 'google', name: 'Google AI Studio', kind: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', region: 'us-central1', tier: 'paid' }, + { id: 'vertex', name: 'Google Cloud Vertex AI', kind: 'vertex', baseUrl: 'https://us-central1-aiplatform.googleapis.com/v1', region: 'us-central1', tier: 'enterprise' }, + { id: 'bedrock', name: 'AWS Bedrock', kind: 'bedrock', baseUrl: 'https://bedrock-runtime.us-west-2.amazonaws.com', region: 'us-west-2', tier: 'enterprise' }, + { id: 'deepseek', name: 'DeepSeek API', kind: 'openai-compat', baseUrl: 'https://api.deepseek.com/v1', region: 'ap-east-1', tier: 'pro' }, + { id: 'openrouter', name: 'OpenRouter Gateway', kind: 'openai-compat', baseUrl: 'https://openrouter.ai/api/v1', region: 'global', tier: 'credits' }, + { id: 'xai', name: 'xAI Grok API', kind: 'openai-compat', baseUrl: 'https://api.x.ai/v1', region: 'us-west-1', tier: 'pro' }, + { id: 'qwen', name: 'Alibaba DashScope Qwen', kind: 'openai-compat', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', region: 'cn-beijing', tier: 'enterprise' }, + { id: 'moonshot', name: 'Moonshot Kimi API', kind: 'openai-compat', baseUrl: 'https://api.moonshot.cn/v1', region: 'cn-north-1', tier: 'pro' }, + { id: 'zhipu', name: 'Zhipu GLM OpenPlatform', kind: 'openai-compat', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', region: 'cn-east-1', tier: 'pro' }, + { id: 'minimax', name: 'MiniMax Coding Plan', kind: 'anthropic-compat', baseUrl: 'https://api.minimaxi.com/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'ollama-local', name: 'Local Ollama Studio', kind: 'ollama', baseUrl: 'http://127.0.0.1:11434/v1', region: 'local', tier: 'free' }, + { id: 'team-proxy', name: 'Internal LiteLLM Proxy', kind: 'openai-compat', baseUrl: 'https://llm-gateway.internal.example/v1', region: 'eu-central-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Nightly PR triage & CI digest', + '每小时同步上游安全通告', + 'Release branch changelog builder', + 'Mobile relay latency watchdog', + '清理过期工作区缓存与临时构建', + 'Weekly dependency vulnerability audit', + 'Eval Bank regression tracker', + '数据库 WAL 体积巡检任务', + ], + schedulePrompts: [ + 'Inspect open pull requests with failing checks, summarize root causes, and draft minimal fixes.', + '检查过去 1 小时内 relay 节点的 P95 延迟与断线重连日志,如异常则生成排查摘要。', + 'Collect merged commits since the last tag and prepare structured release notes grouped by subsystem.', + 'Audit disk usage of local session archives and flag workspaces exceeding 500 MiB.', + ], +}; + +function makeSymbol(rng, corpus) { + return `${rng.pick(corpus.symbolVerbs)}${rng.pick(corpus.symbolNouns)}`; +} + +function makeFilePath(rng, corpus) { + return `${rng.pick(corpus.subdirs)}/${rng.pick(corpus.fileStems)}.ts`; +} + +/** + * Generates realistic, high-entropy technical paragraphs combining unique identifiers, + * paths, line ranges, commit hashes, metrics, code fragments, and CJK+English prose. + */ +function makeUniqueParagraph(rng, corpus, seq) { + const kind = rng.int(0, 4); + const file = makeFilePath(rng, corpus); + const symA = makeSymbol(rng, corpus); + const symB = makeSymbol(rng, corpus); + const line = rng.int(18, 640); + const commit = rng.hex(10); + const bytesBefore = rng.int(12_000, 195_000); + const bytesAfter = Math.max(240, Math.floor(bytesBefore * (0.04 + rng.next() * 0.28))); + const ms = rng.int(4, 380); + + if (kind === 0) { + return `[${commit}] ${rng.pick(corpus.enObservations)} in \`${file}:${line}\` (\`${symA}\` -> \`${symB}\`): payload=${bytesBefore}B -> ${bytesAfter}B (${ms}ms, seq=${seq}). ${rng.pick(corpus.cjkTopics)}:${rng.pick(corpus.cjkActions)}。`; + } + if (kind === 1) { + const varA = `${rng.pick(corpus.symbolNouns).toLowerCase()}_${rng.hex(4)}`; + const varB = `tag_${rng.hex(6)}`; + return `\`\`\`ts\n// ${file}:${line} (${commit})\nexport function ${symA}(${varA}: Uint8Array, ${varB}: string) {\n const limit = ${rng.int(64, 4096)};\n return ${symB}(${varA}.subarray(0, Math.min(${varA}.byteLength, limit)), ${varB});\n}\n\`\`\`\n分析结论(#${seq}):针对「${rng.pick(corpus.cjkTopics)}」,${rng.pick(corpus.cjkActions)}(实测耗时 ${ms}ms,压缩后 ${bytesAfter}B)。`; + } + if (kind === 2) { + const reqId = `req-${rng.hex(8)}`; + const peerId = `peer-${rng.hex(6)}`; + return `Trace ${reqId} (${peerId}): ${rng.pick(corpus.enObservations)}. Checked \`${symA}\` at \`${file}:${line}-${line + rng.int(8, 45)}\` against commit \`${commit}\` (delta=${bytesAfter}B vs raw=${bytesBefore}B, ratio=${((bytesAfter / bytesBefore) * 100).toFixed(2)}%). 备注:${rng.pick(corpus.cjkTopics)} ✅`; + } + if (kind === 3) { + return `在排查 \`${file}\` 第 ${line} 行 \`${symA}\`(提交 \`${commit}\`)时观测到「${rng.pick(corpus.cjkTopics)}」,单次同步帧达到 ${bytesBefore} 字节。${rng.pick(corpus.cjkActions)},验证通过 ${rng.int(12, 96)} 组用例(${ms}ms,目标 ${bytesAfter}B)。`; + } + const errCode = `ERR_${rng.pick(corpus.symbolNouns).toUpperCase()}_${rng.int(100, 999)}`; + return `Diagnostic ${errCode} @ \`${file}:${line}\` [rev=${seq}, hash=${commit}]: \`${symA}\` returned ${bytesAfter}B after calling \`${symB}\`. ${rng.pick(corpus.enObservations)}; verified fallback parity without data drift (${ms}ms).`; +} + +function makeStreamAppendChunk(rng, corpus, seq) { + const file = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(8); + const line = rng.int(10, 580); + const val = rng.int(120, 98000); + if (rng.bool(0.5)) { + return `[chunk-${commit}] \`${file}:${line}\` \`${sym}()\`: ${rng.pick(corpus.enObservations)} (measured=${val}B, step=${seq}). ${rng.pick(corpus.cjkTopics)}。`; + } + return `(片段 ${commit})检查 \`${file}:${line}\` 中的 \`${sym}\`:${rng.pick(corpus.cjkActions)}(指标=${val},序号=${seq})。`; +} + +function makeThinkingChunk(rng, corpus, seq) { + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(6); + const n = rng.int(16, 4096); + if (rng.bool(0.5)) { + return `Checking \`${sym}\` (#${seq}, id=${commit}, budget=${n}B): ${rng.pick(corpus.enObservations)}. `; + } + return `思考(${commit}/#${seq}):关于「${rng.pick(corpus.cjkTopics)}」与 \`${sym}\`(${n}B),${rng.pick(corpus.cjkActions)}。`; +} + +function makeToolOutput(rng, corpus, seq) { + const f1 = makeFilePath(rng, corpus); + const f2 = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const h = rng.hex(10); + return [ + `${f1}:${rng.int(10, 400)}: export function ${sym}(ctx_${seq}) { /* ${h} */ }`, + `${f2}:${rng.int(10, 400)}: assert.equal(checksum, "${rng.hex(16)}");`, + `PASS ${rng.int(14, 68)}/${rng.int(68, 72)} assertions (${rng.int(42, 890)}ms, rss=${rng.int(34, 128)}MB)`, + ].join('\n'); +} + +function makeMessageText(rng, corpus, seq, paragraphs) { + const parts = []; + for (let i = 0; i < paragraphs; i += 1) { + parts.push(makeUniqueParagraph(rng, corpus, seq * 10 + i)); + } + return parts.join('\n\n'); +} + +function createInitialSessions(rng, corpus, baseTime) { + const sessions = []; + for (let i = 0; i < 160; i += 1) { + const id = `${corpus.idPrefix}-sess-${String(i + 1).padStart(4, '0')}-${rng.hex(4)}`; + const tagCount = rng.int(1, 3); + const tags = []; + for (let t = 0; t < tagCount; t += 1) { + const tag = rng.pick(corpus.tagsPool); + if (!tags.includes(tag)) tags.push(tag); + } + const input = rng.int(4000, 180000); + const output = rng.int(800, 42000); + const cacheRead = rng.int(10000, 600000); + const sym = makeSymbol(rng, corpus); + sessions.push({ + id, + title: `${rng.pick(corpus.sessionTitles)} [${sym} #${i + 1}]`, + workingDir: `${rng.pick(corpus.workingDirs)}/${rng.pick(corpus.fileStems)}`, + agentKind: rng.pick(corpus.agentKinds), + phase: i < 8 ? 'running' : rng.pick(['idle', 'idle', 'idle', 'waiting_approval', 'error']), + updatedAt: baseTime - i * rng.int(45_000, 300_000), + lastMessagePreview: `${rng.pick(corpus.cjkTopics)} · ${sym} (${rng.hex(8)}): ${rng.pick(corpus.enObservations).slice(0, 68)}`, + tokenUsage: { + input, + output, + cacheRead, + costUsd: Math.round((input * 0.000003 + output * 0.000015 + cacheRead * 0.0000003) * 10000) / 10000, + }, + tags, + unreadCount: i < 12 ? rng.int(0, 5) : 0, + pinned: i < 24, + modelLabel: rng.pick(corpus.modelLabels), + deviceId: rng.pick(corpus.devices), + deviceOnline: true, + }); + } + return sessions; +} + +function makeMessageItem(rng, corpus, sessionId, seq, timestamp, revSuffix) { + const isWork = seq % 5 === 4; + if (isWork) { + const workId = `${corpus.idPrefix}-${sessionId}-w${String(seq).padStart(4, '0')}`; + const sym = makeSymbol(rng, corpus); + return { + key: `work:${workId}`, + type: 'work', + summary: { + title: `${rng.pick(corpus.workTitles)} · ${sym} (#${seq})`, + status: 'done', + revision: `${workId}-r1${revSuffix}`, + durationMs: rng.int(180, 9400), + }, + children: [ + { + key: `work:${workId}:c1`, + type: 'work', + summary: { + title: `Step 1: ${rng.pick(corpus.toolNames)} ${makeFilePath(rng, corpus)}`, + status: 'done', + revision: `${workId}-c1-r1${revSuffix}`, + durationMs: rng.int(60, 2400), + }, + }, + ], + }; + } + const msgId = `${corpus.idPrefix}-${sessionId}-m${String(seq).padStart(4, '0')}`; + const role = seq % 2 === 0 ? 'user' : 'assistant'; + const paragraphs = role === 'user' ? rng.int(1, 2) : rng.int(3, 5); + const text = `[#${seq}] ${makeMessageText(rng, corpus, seq, paragraphs)}`; + const content = { text }; + const row = { + id: msgId, + role, + createdAt: timestamp, + remoteBodyVersion: sha256Hex(JSON.stringify(content)), + content, + }; + if (role === 'assistant') { + row.thinking = makeThinkingChunk(rng, corpus, seq) + makeThinkingChunk(rng, corpus, seq + 1); + if (seq % 3 === 1) { + row.toolCalls = [ + { + id: `tc-${seq}-${rng.hex(4)}`, + name: rng.pick(corpus.toolNames), + args: { + path: `${rng.pick(corpus.workingDirs)}/${makeFilePath(rng, corpus)}`, + limit: rng.int(50, 200), + }, + status: 'done', + output: makeToolOutput(rng, corpus, seq), + }, + ]; + } + } + return { + key: `msg:${msgId}`, + type: 'messages', + messages: [row], + }; +} + +function applyRevisionSuffix(items, oldSuffix, newSuffix) { + for (const item of items) { + if (item.type === 'work') { + if (item.summary && typeof item.summary.revision === 'string' && item.summary.revision.endsWith(oldSuffix)) { + item.summary.revision = item.summary.revision.slice(0, -oldSuffix.length) + newSuffix; + } + if (Array.isArray(item.children)) { + applyRevisionSuffix(item.children, oldSuffix, newSuffix); + } + } + } +} + +function createInitialSessionHistory(rng, corpus, sessionId, baseTime) { + const rev = 1; + const revSuffix = `:rev-${rev}`; + const items = []; + for (let seq = 1; seq <= 35; seq += 1) { + items.push(makeMessageItem(rng, corpus, sessionId, seq, baseTime - (36 - seq) * 18_000, revSuffix)); + } + return { + sessionId, + nextSeq: 36, + rev, + revSuffix, + streamingTicksLeft: 0, + runningWorkSummary: { + status: 'running', + activeTool: rng.pick(corpus.toolNames), + elapsedMs: 1200, + stepCount: 1, + lines: [`Initialized trace session ${sessionId} (${rng.hex(8)})`], + }, + items, + }; +} + +function createInitialProviders(rng, corpus, baseTime) { + const capabilityPool = ['tools', 'vision', 'reasoning', 'caching', 'streaming', 'json-schema']; + const providers = corpus.providers.map((p, idx) => { + const modelCount = 7 + (idx % 4); + const models = []; + for (let m = 0; m < modelCount; m += 1) { + const tier = m === 0 ? 'flagship' : m < 3 ? 'balanced' : m < 6 ? 'fast' : 'mini'; + const capCount = 3 + (m % 4); + models.push({ + id: `${p.id}/${tier}-v${(m % 5) + 1}.${idx % 3}-${rng.hex(3)}`, + label: `${p.name} ${tier.toUpperCase()} ${(m % 5) + 1}.${idx % 3}`, + description: `${p.name} ${tier} profile (${p.region}, ${makeSymbol(rng, corpus)}, rev-${rng.hex(6)}): ${rng.pick(corpus.enObservations)}`, + contextWindow: m < 3 ? 200_000 : m < 6 ? 128_000 : 64_000, + maxOutputTokens: m < 2 ? 32_768 : 16_384, + pricing: { + inputPerM: Math.round((0.15 + (modelCount - m) * 0.85) * 100) / 100, + outputPerM: Math.round((0.6 + (modelCount - m) * 3.1) * 100) / 100, + cacheReadPerM: Math.round((0.03 + (modelCount - m) * 0.12) * 100) / 100, + }, + capabilities: capabilityPool.slice(0, capCount), + deprecated: false, + defaultEffort: m < 2 ? 'high' : 'medium', + }); + } + const dailyLimit = 5_000_000 + idx * 1_500_000; + const usedPercent = Math.round(rng.next() * 450) / 10; + return { + id: p.id, + name: p.name, + kind: p.kind, + enabled: true, + status: 'healthy', + baseUrl: p.baseUrl, + region: p.region, + latencyMs: rng.int(110, 620), + checkedAt: baseTime, + quota: { + usedPercent, + remainingTokens: Math.round(dailyLimit * (1 - usedPercent / 100)), + dailyLimit, + resetAt: baseTime + 6 * 3600_000, + tier: p.tier, + }, + models, + }; + }); + return { + catalogVersion: 4, + generatedAt: baseTime, + activeProviderId: providers[0].id, + providers, + }; +} + +function createInitialSchedules(rng, corpus, baseTime) { + const crons = ['*/15 * * * *', '0 * * * *', '0 */4 * * *', '0 9 * * 1-5', '30 2 * * *']; + const jobs = []; + for (let i = 0; i < 40; i += 1) { + const recentRuns = []; + for (let r = 0; r < 6; r += 1) { + const startedAt = baseTime - (6 - r) * 3600_000 - i * 17_000; + const durationMs = rng.int(2400, 48000); + recentRuns.push({ + runId: `${corpus.idPrefix}-run-${i + 1}-${r + 1}-${rng.hex(4)}`, + startedAt, + finishedAt: startedAt + durationMs, + status: r === 4 && i % 9 === 0 ? 'failed' : 'succeeded', + durationMs, + summary: `${rng.pick(corpus.scheduleNames)} [${rng.hex(6)}] (${rng.int(1, 24)} items, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1200, 36000), + }); + } + jobs.push({ + id: `${corpus.idPrefix}-sched-${String(i + 1).padStart(3, '0')}`, + name: `${rng.pick(corpus.scheduleNames)} #${i + 1}`, + cron: rng.pick(crons), + prompt: `${rng.pick(corpus.schedulePrompts)} (${makeFilePath(rng, corpus)})`, + targetSessionId: `${corpus.idPrefix}-sess-${String((i % 30) + 1).padStart(4, '0')}`, + workspaceDir: rng.pick(corpus.workingDirs), + enabled: i % 11 !== 10, + nextRunAt: baseTime + rng.int(120_000, 7200_000), + lastStatus: recentRuns[recentRuns.length - 1].status, + recentRuns, + runSeq: 7, + }); + } + return { + indexVersion: 3, + updatedAt: baseTime, + totalJobs: jobs.length, + jobs, + }; +} + +export const DEFAULT_SCHEDULE_PROFILE = { + coldReconnectTicks: [34, 72, 110, 148, 184, 214], + hostEvictTicks: [52, 128, 198], + concurrentSpecs: [ + { tick: 24, channel: 'local-db:sessions:list' }, + { tick: 92, channel: 'local-db:messages:view' }, + { tick: 162, channel: 'local-db:sessions:list' }, + { tick: 204, channel: 'maker:provider:list' }, + ], +}; + +/** + * Generate a deterministic 240-RPC multi-channel Cindy sync trace. + */ +export function generateTrace({ + seed = 20260501, + corpus = DEFAULT_CORPUS, + scheduleProfile = DEFAULT_SCHEDULE_PROFILE, +} = {}) { + const rng = createRng(seed); + let clock = 1_765_000_000_000 + (seed % 1000) * 60_000; + + const sessions = createInitialSessions(rng, corpus, clock); + const histA = createInitialSessionHistory(rng, corpus, 'active-A', clock); + const histB = createInitialSessionHistory(rng, corpus, 'active-B', clock); + const providerCatalog = createInitialProviders(rng, corpus, clock); + const scheduleIndex = createInitialSchedules(rng, corpus, clock); + + let sessionsPollCount = 0; + let bulkStormCount = 0; + let deviceOnlineFlip = false; + + function mutateSessions(bulkOverride = false) { + sessionsPollCount += 1; + clock += rng.int(1500, 4500); + const isBulkStorm = bulkOverride || (sessionsPollCount > 2 && sessionsPollCount % 10 === 0); + if (isBulkStorm) { + bulkStormCount += 1; + deviceOnlineFlip = !deviceOnlineFlip; + const ratio = 0.60 + rng.next() * 0.15; + const count = Math.floor(sessions.length * ratio); + const indices = rng.shuffle(Array.from({ length: sessions.length }, (_, i) => i)).slice(0, count); + for (const idx of indices) { + const s = sessions[idx]; + s.deviceOnline = deviceOnlineFlip; + s.tokenUsage.cacheRead += rng.int(50, 900); + if (idx % 5 === 0) s.updatedAt = clock; + } + } + const mutateCount = rng.int(4, 12); + const picked = []; + for (let i = 0; i < mutateCount; i += 1) { + const idx = rng.int(0, Math.min(sessions.length - 1, 45)); + if (!picked.includes(idx)) picked.push(idx); + } + for (const idx of picked) { + const s = sessions[idx]; + s.updatedAt = clock - rng.int(0, 900); + s.phase = rng.pick(['running', 'idle', 'waiting_approval']); + s.tokenUsage.input += rng.int(200, 4500); + s.tokenUsage.output += rng.int(80, 1200); + s.tokenUsage.costUsd = Math.round( + (s.tokenUsage.input * 0.000003 + s.tokenUsage.output * 0.000015 + s.tokenUsage.cacheRead * 0.0000003) * 10000, + ) / 10000; + s.unreadCount = s.phase === 'running' ? s.unreadCount + 1 : 0; + if (rng.bool(0.5)) { + s.lastMessagePreview = `${rng.pick(corpus.cjkTopics)} · ${makeSymbol(rng, corpus)} (${rng.hex(6)}): ${rng.pick(corpus.enObservations).slice(0, 56)}`; + } + } + const moveCount = Math.min(picked.length, rng.int(2, 5)); + for (let m = 0; m < moveCount; m += 1) { + const idx = picked[m]; + if (idx > 0 && idx < sessions.length) { + const [row] = sessions.splice(idx, 1); + const dest = rng.int(0, Math.min(8, sessions.length)); + sessions.splice(dest, 0, row); + } + } + } + + function snapshotSessions(scope) { + if (scope === 'pinned') { + const pinned = sessions.filter((s) => s.pinned).slice(0, 40); + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'pinned', + totalCount: pinned.length, + activeDeviceId: corpus.devices[0], + sessions: pinned, + }); + } + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'all', + totalCount: sessions.length, + activeDeviceId: corpus.devices[0], + sessions, + }); + } + + function mutateHistory(hist, steps = 1) { + for (let s = 0; s < steps; s += 1) { + clock += rng.int(900, 2800); + const oldSuffix = hist.revSuffix; + hist.rev += 1; + const newSuffix = `:rev-${hist.rev}`; + applyRevisionSuffix(hist.items, oldSuffix, newSuffix); + hist.revSuffix = newSuffix; + + hist.runningWorkSummary.elapsedMs += rng.int(800, 3200); + hist.runningWorkSummary.stepCount += 1; + hist.runningWorkSummary.activeTool = rng.pick(corpus.toolNames); + hist.runningWorkSummary.lines.push( + `[rev ${hist.rev}] ${hist.runningWorkSummary.activeTool} ${makeSymbol(rng, corpus)} (${rng.hex(6)})`, + ); + if (hist.runningWorkSummary.lines.length > 6) { + hist.runningWorkSummary.lines.shift(); + } + + const lastItem = hist.items[hist.items.length - 1]; + const canStreamAppend = + hist.streamingTicksLeft > 0 + && lastItem + && lastItem.type === 'messages' + && lastItem.messages[0]?.role === 'assistant'; + + if (canStreamAppend) { + // Streaming text/thinking append (120–380 chars appended onto the last message!) + const msg = lastItem.messages[0]; + const appended = makeStreamAppendChunk(rng, corpus, hist.rev); + msg.content.text += `\n${appended}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + if (rng.bool(0.65) && typeof msg.thinking === 'string') { + msg.thinking += makeThinkingChunk(rng, corpus, hist.rev); + } + hist.streamingTicksLeft -= 1; + } else if (hist.items.length < 140) { + // Advance a conversation turn (user message + optional work step + new streaming assistant message) + const burst = rng.int(2, 4); + let lastAdded = null; + for (let b = 0; b < burst && hist.items.length < 140; b += 1) { + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + b * 250, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + lastAdded = item; + } + if (lastAdded && lastAdded.type === 'messages' && lastAdded.messages[0].role === 'assistant') { + hist.streamingTicksLeft = rng.int(3, 5); + } else if (hist.items.length < 140) { + // Ensure next item starts a streaming assistant turn + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + 900, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + hist.streamingTicksLeft = + item.type === 'messages' && item.messages[0].role === 'assistant' ? rng.int(3, 5) : 0; + } else { + hist.streamingTicksLeft = 0; + } + } else { + for (let i = hist.items.length - 1; i >= 0; i -= 1) { + const cand = hist.items[i]; + if (cand.type === 'messages' && cand.messages[0].role === 'assistant') { + const msg = cand.messages[0]; + msg.content.text += `\n${makeStreamAppendChunk(rng, corpus, hist.rev)}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + break; + } + } + } + } + } + + function snapshotHistory(hist, beforeIndex = null) { + if (beforeIndex !== null) { + const start = Math.max(0, beforeIndex - 28); + const slice = hist.items.slice(start, beforeIndex); + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: start > 0, + nextBefore: slice[0]?.key ?? null, + before: hist.items[beforeIndex]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: slice, + }); + } + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: true, + nextBefore: hist.items[0]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: hist.items, + }); + } + + function mutateProviders() { + clock += rng.int(1200, 3500); + providerCatalog.generatedAt = clock; + const statusChoices = ['healthy', 'healthy', 'healthy', 'degraded', 'rate_limited']; + const changedStatus = new Set([ + rng.int(0, providerCatalog.providers.length - 1), + rng.int(0, providerCatalog.providers.length - 1), + ]); + for (let i = 0; i < providerCatalog.providers.length; i += 1) { + const p = providerCatalog.providers[i]; + if (rng.bool(0.5) || changedStatus.has(i)) { + p.checkedAt = clock; + p.latencyMs = Math.max(45, p.latencyMs + rng.int(-35, 45)); + const nextPct = Math.min(99.9, Math.round((p.quota.usedPercent + rng.next() * 1.4) * 10) / 10); + p.quota.usedPercent = nextPct; + p.quota.remainingTokens = Math.max(0, Math.round(p.quota.dailyLimit * (1 - nextPct / 100))); + if (rng.bool(0.2)) { + p.quota.resetAt = clock + 6 * 3600_000; + } + } + if (changedStatus.has(i)) { + p.status = rng.pick(statusChoices); + } + } + } + + function mutateSchedules() { + clock += rng.int(1500, 4000); + scheduleIndex.updatedAt = clock; + const mutateCount = rng.int(1, 3); + const chosen = new Set(); + while (chosen.size < mutateCount) { + chosen.add(rng.int(0, scheduleIndex.jobs.length - 1)); + } + for (const idx of chosen) { + const job = scheduleIndex.jobs[idx]; + const durationMs = rng.int(1800, 42000); + const status = rng.bool(0.88) ? 'succeeded' : 'failed'; + const runEntry = { + runId: `${corpus.idPrefix}-run-${idx + 1}-${job.runSeq}-${rng.hex(4)}`, + startedAt: clock - durationMs, + finishedAt: clock, + status, + durationMs, + summary: `${job.name} [${rng.hex(6)}] (${rng.int(1, 20)} records, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1400, 29000), + }; + job.runSeq += 1; + job.lastStatus = status; + job.nextRunAt = clock + rng.int(900_000, 7200_000); + job.recentRuns.push(runEntry); + if (job.recentRuns.length > 6) { + job.recentRuns.shift(); + } + } + } + + const concurrentByTick = new Map(scheduleProfile.concurrentSpecs.map((c) => [c.tick, c.channel])); + const coldReconnectSet = new Set(scheduleProfile.coldReconnectTicks); + const hostEvictSet = new Set(scheduleProfile.hostEvictTicks); + + const targets = { + 'local-db:sessions:list': 76, + 'local-db:messages:view': 98, + 'maker:provider:list': 28, + 'maker:schedule:list-sidebar-index-runs': 30, + }; + const emitted = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + const channelOrder = [ + 'local-db:messages:view', + 'local-db:sessions:list', + 'maker:provider:list', + 'maker:schedule:list-sidebar-index-runs', + ]; + const totalNonConcurrent = 232; + const tickChannels = []; + for (let i = 0; i < totalNonConcurrent; i += 1) { + let bestChannel = null; + let bestDeficit = -Infinity; + for (const ch of channelOrder) { + if (emitted[ch] >= targets[ch]) continue; + const expected = ((i + 1) * targets[ch]) / totalNonConcurrent; + const deficit = expected - emitted[ch]; + if (deficit > bestDeficit) { + bestDeficit = deficit; + bestChannel = ch; + } + } + emitted[bestChannel] += 1; + tickChannels.push(bestChannel); + } + + const steps = []; + let rpcCounter = 0; + let nonConcurrentIdx = 0; + let sessionReadSeq = 0; + let msgReadSeq = 0; + let rawJsonBytes = 0; + const channelCounts = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + + function makeRpcRead(channel, forcePrimary = false, forceSession = null) { + rpcCounter += 1; + channelCounts[channel] += 1; + const id = `rpc-${String(rpcCounter).padStart(4, '0')}`; + let argsKey; + let groundTruthValue; + + if (channel === 'local-db:sessions:list') { + sessionReadSeq += 1; + mutateSessions(false); + const isPinned = !forcePrimary && sessionReadSeq % 5 === 0; + const scope = isPinned ? 'pinned' : 'all'; + argsKey = JSON.stringify({ scope, limit: isPinned ? 40 : 160 }); + groundTruthValue = snapshotSessions(scope); + } else if (channel === 'local-db:messages:view') { + msgReadSeq += 1; + const useA = forceSession !== null ? forceSession === 'A' : (msgReadSeq % 2 === 1); + const hist = useA ? histA : histB; + mutateHistory(hist, 1); + const isPaginated = !forcePrimary && msgReadSeq >= 10 && msgReadSeq % 8 === 2 && hist.items.length > 35; + if (isPaginated) { + const beforeIndex = Math.min(hist.items.length - 5, 30 + (msgReadSeq % 3) * 10); + const beforeKey = hist.items[beforeIndex].key; + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, before: beforeKey, limit: 28 }); + groundTruthValue = snapshotHistory(hist, beforeIndex); + } else { + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, limit: 140 }); + groundTruthValue = snapshotHistory(hist, null); + } + } else if (channel === 'maker:provider:list') { + mutateProviders(); + argsKey = JSON.stringify({ includeModels: true, includeQuotas: true }); + groundTruthValue = cloneJson(providerCatalog); + } else if (channel === 'maker:schedule:list-sidebar-index-runs') { + mutateSchedules(); + argsKey = JSON.stringify({ limit: 40, recentRuns: 6 }); + groundTruthValue = cloneJson({ + indexVersion: scheduleIndex.indexVersion, + updatedAt: scheduleIndex.updatedAt, + totalJobs: scheduleIndex.totalJobs, + jobs: scheduleIndex.jobs.map(({ runSeq: _r, ...rest }) => rest), + }); + } else { + throw new Error(`Unknown channel: ${channel}`); + } + + rawJsonBytes += Buffer.byteLength(JSON.stringify(groundTruthValue), 'utf8'); + return { id, channel, argsKey, groundTruthValue }; + } + + let reconnectNum = 0; + let evictNum = 0; + + for (let tick = 0; tick < 236; tick += 1) { + if (coldReconnectSet.has(tick)) { + reconnectNum += 1; + mutateSessions(false); + mutateHistory(histA, rng.int(2, 4)); + mutateHistory(histB, rng.int(2, 3)); + mutateProviders(); + mutateSchedules(); + steps.push({ + type: 'cold_reconnect', + label: `mobile-cold-reconnect-${reconnectNum}`, + }); + } + if (hostEvictSet.has(tick)) { + evictNum += 1; + mutateSessions(false); + mutateHistory(histA, 1); + steps.push({ + type: 'host_evict', + label: `host-volatile-evict-${evictNum}`, + }); + } + + if (concurrentByTick.has(tick)) { + const ch = concurrentByTick.get(tick); + const forcedSess = ch === 'local-db:messages:view' ? 'A' : null; + const r1 = makeRpcRead(ch, true, forcedSess); + const r2 = makeRpcRead(ch, true, forcedSess); + steps.push({ + type: 'concurrent_rpc', + reads: [r1, r2], + }); + } else { + const ch = tickChannels[nonConcurrentIdx]; + nonConcurrentIdx += 1; + steps.push({ + type: 'rpc', + ...makeRpcRead(ch, false, null), + }); + } + } + + return { + seed, + meta: { + totalRpcs: rpcCounter, + channelCounts, + coldReconnectCount: reconnectNum, + hostEvictCount: evictNum, + concurrentPairCount: scheduleProfile.concurrentSpecs.length, + bulkStormCount, + finalHistoryLengthA: histA.items.length, + finalHistoryLengthB: histB.items.length, + rawJsonBytes, + }, + steps, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/package.json b/questions/opt-device-link-delta-sync/v1/controls/incomplete/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/src/sync-protocol.mjs new file mode 100644 index 0000000..c12dc5b --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/src/sync-protocol.mjs @@ -0,0 +1,645 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Incomplete optimization control: + * - Extends invokeDelta (MAX_DEPTH = 2, row-level replacement) across ALL channels. + * - Removes MAX_UNVERIFIED_DELTAS = 8 reset cliff and raises MAX_DELTA_RATIO to 0.85. + * - Uses binary gzip framing instead of gzipBase64 inside JSON. + * Still misses: + * - Recursive field-level diff (replaces whole session/provider/schedule/message rows). + * - String-append / streaming text diff. + * - Multi-base host snapshot retention (falls back to full on concurrent stale-base reads). + * - Compact cold-cache reconciliation (still sends 64-hex SHA-256 manifest on messages:view, + * no cold reuse on other channels). + */ + +const MESSAGES_VIEW_CHANNEL = 'local-db:messages:view'; +const MAX_DEPTH = 2; +const MAX_DELTA_RATIO = 0.85; +const MAX_REUSE_MANIFEST_ENTRIES = 256; + +const FRAME_PLAIN = 0; +const FRAME_GZIP = 1; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function sha256Hex(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex'); +} + +function packFrame(obj) { + const raw = Buffer.from(JSON.stringify(obj), 'utf8'); + if (raw.byteLength >= 128) { + const gz = zlib.gzipSync(raw, { level: 9 }); + if (gz.byteLength + 1 < raw.byteLength) { + const out = new Uint8Array(gz.byteLength + 1); + out[0] = FRAME_GZIP; + out.set(gz, 1); + return out; + } + } + const out = new Uint8Array(raw.byteLength + 1); + out[0] = FRAME_PLAIN; + out.set(raw, 1); + return out; +} + +function unpackFrame(bytes) { + const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const tag = buf[0]; + const body = buf.subarray(1); + const raw = tag === FRAME_GZIP ? zlib.gunzipSync(body) : body; + return JSON.parse(raw.toString('utf8')); +} + +function samePlainKeys(a, b) { + const left = Object.keys(a); + const right = Object.keys(b); + return left.length === right.length && left.every((k, i) => k === right[i]); +} + +function shallowDiff(base, next, depth) { + if (depth < MAX_DEPTH && Array.isArray(base) && Array.isArray(next)) { + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + let reused = 0; + let inPlace = base.length === next.length; + const a = next.map((el, pos) => { + const idx = byText.get(JSON.stringify(el)); + if (idx === undefined) { + inPlace = false; + return [el]; + } + reused += 1; + if (idx !== pos) inPlace = false; + return idx; + }); + if (inPlace) return undefined; + return reused > 0 ? { a } : { s: next }; + } + if (depth < MAX_DEPTH && isPlainObject(base) && isPlainObject(next) && samePlainKeys(base, next)) { + const o = {}; + let changed = false; + for (const key of Object.keys(next)) { + const child = shallowDiff(base[key], next[key], depth + 1); + if (child !== undefined) { + o[key] = child; + changed = true; + } + } + return changed ? { o } : undefined; + } + return JSON.stringify(base) === JSON.stringify(next) ? undefined : { s: next }; +} + +function shallowApply(base, patch, depth) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if (depth >= MAX_DEPTH) throw new Error('patch too deep'); + if ('a' in patch) { + return patch.a.map((entry) => (typeof entry === 'number' ? base[entry] : entry[0])); + } + if ('o' in patch) { + const out = {}; + for (const key of Object.keys(base)) { + const child = Object.prototype.hasOwnProperty.call(patch.o, key) ? patch.o[key] : undefined; + out[key] = shallowApply(base[key], child, depth + 1); + } + return out; + } + throw new Error('invalid patch'); +} + +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function stripSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => + typeof rev === 'string' && rev.endsWith(suffix) ? rev.slice(0, -suffix.length) : rev, + ); +} + +function appendSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)); +} + +function isReusableMessage(row) { + return ( + isPlainObject(row) + && typeof row.id === 'string' + && row.id.length > 0 + && (row.role === 'assistant' || row.role === 'user') + && typeof row.remoteBodyVersion === 'string' + && /^[a-f0-9]{64}$/.test(row.remoteBodyVersion) + && isPlainObject(row.content) + && typeof row.content.text === 'string' + ); +} + +function mapMessageRows(value, fn) { + if (!isPlainObject(value) || !Array.isArray(value.items)) return value; + return { + ...value, + items: value.items.map((item) => { + if (isPlainObject(item) && item.type === 'messages' && Array.isArray(item.messages)) { + return { + ...item, + messages: item.messages.map((row) => (isPlainObject(row) ? fn(row) : row)), + }; + } + return item; + }), + }; +} + +function parseArgs(argsKey) { + try { + const parsed = JSON.parse(argsKey); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +export function createHostSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // Keep last 2 snapshots per (channel, argsKey) (still MAX_DEPTH=2 row replacement, gzip, 64-hex cold manifest) + const bases = new Map(); + let baseBytes = 0; + const historyBases = new Map(); + let historyBytes = 0; + let tokenSeq = 0; + + function evictVolatileBases() { + bases.clear(); + baseBytes = 0; + historyBases.clear(); + historyBytes = 0; + } + + function rememberBase(key, tag, text) { + if (text.length > maxCacheBytes / 2) return; + let list = bases.get(key); + if (!list) { + list = []; + bases.set(key, list); + } else { + bases.delete(key); + bases.set(key, list); + } + const existing = list.findIndex((e) => e.tag === tag); + if (existing >= 0) { + const [e] = list.splice(existing, 1); + list.push(e); + return; + } + list.push({ tag, text }); + baseBytes += text.length; + while (list.length > 2) { + const dropped = list.shift(); + baseBytes -= dropped.text.length; + } + while (bases.size > 32 || baseBytes > maxCacheBytes / 2) { + const oldestKey = bases.keys().next().value; + const oldestList = bases.get(oldestKey); + for (const e of oldestList) baseBytes -= e.text.length; + bases.delete(oldestKey); + } + } + + function findBase(key, tag) { + const list = bases.get(key); + if (!list) return undefined; + for (let i = list.length - 1; i >= 0; i -= 1) { + if (list[i].tag === tag) return list[i]; + } + return undefined; + } + + function rememberHistoryBase(token, itemsJson) { + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + if (bytes > maxCacheBytes / 2) return false; + historyBases.set(token, { itemsJson, bytes }); + historyBytes += bytes; + while (historyBases.size > 16 || historyBytes > maxCacheBytes / 2) { + const oldestKey = historyBases.keys().next().value; + const oldest = historyBases.get(oldestKey); + historyBytes -= oldest.bytes; + historyBases.delete(oldestKey); + } + return true; + } + + function handleHistoryView(argsKey, req, groundTruthValue) { + const parsedArgs = parseArgs(argsKey); + const isLatestPage = parsedArgs.before == null; + let payloadValue = groundTruthValue; + + if ( + isLatestPage + && req.hvd + && isPlainObject(groundTruthValue) + && Array.isArray(groundTruthValue.items) + ) { + const suffix = + typeof groundTruthValue.revisionSuffix === 'string' + && groundTruthValue.revisionSuffix + && allWorkRevisionsEndWith(groundTruthValue.items, groundTruthValue.revisionSuffix) + ? groundTruthValue.revisionSuffix + : undefined; + const strippedJson = groundTruthValue.items.map((item) => JSON.stringify(stripSuffix(item, suffix))); + const baseEntry = req.hvd.base ? historyBases.get(req.hvd.base) : undefined; + let outItems = groundTruthValue.items; + let matchedBase; + + if (baseEntry) { + matchedBase = req.hvd.base; + const baseMap = new Map(); + for (let i = 0; i < baseEntry.itemsJson.length; i += 1) { + if (!baseMap.has(baseEntry.itemsJson[i])) baseMap.set(baseEntry.itemsJson[i], i); + } + const compressedItems = []; + let runStart = -1; + let runCount = 0; + const flush = () => { + if (runCount > 0) { + compressedItems.push({ type: 'same', from: runStart, count: runCount }); + runStart = -1; + runCount = 0; + } + }; + for (let i = 0; i < strippedJson.length; i += 1) { + const baseIdx = baseMap.get(strippedJson[i]); + if (baseIdx !== undefined) { + if (runCount > 0 && baseIdx === runStart + runCount) runCount += 1; + else { + flush(); + runStart = baseIdx; + runCount = 1; + } + } else { + flush(); + compressedItems.push(groundTruthValue.items[i]); + } + } + flush(); + outItems = compressedItems; + } else if (req.hvd.base && req.hasBodies) { + return packFrame({ kind: 'hvd-miss' }); + } + + tokenSeq += 1; + const token = `h-${tokenSeq}`; + const stored = rememberHistoryBase(token, strippedJson); + payloadValue = { + ...groundTruthValue, + items: outItems, + _hvd: { + ...(stored ? { token } : {}), + ...(matchedBase ? { base: matchedBase } : {}), + ...(suffix ? { suffix } : {}), + }, + }; + } + + if (Array.isArray(req.knownBodies) && req.knownBodies.length > 0) { + const known = new Map(req.knownBodies); + let strippedAny = false; + const strippedVal = mapMessageRows(payloadValue, (row) => { + if (isReusableMessage(row) && known.get(row.id) === row.remoteBodyVersion) { + strippedAny = true; + const { content: _c, ...rest } = row; + return rest; + } + return row; + }); + if (strippedAny) { + return packFrame({ kind: 'hvd-bodies', value: strippedVal }); + } + } + + return packFrame({ kind: 'hvd', value: payloadValue }); + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue }) { + const req = unpackFrame(requestBytes); + + if (channel === MESSAGES_VIEW_CHANNEL) { + return handleHistoryView(argsKey, req, groundTruthValue); + } + + const text = JSON.stringify(groundTruthValue); + const tag = sha256Hex(text).slice(0, 24); + const key = `${channel}\u0000${argsKey}`; + const base = req.base ? findBase(key, req.base) : undefined; + rememberBase(key, tag, text); + + if (req.base && req.base === tag) { + return packFrame({ kind: 'same', tag }); + } + + if (base && req.base && base.tag === req.base) { + const patch = shallowDiff(JSON.parse(base.text), groundTruthValue, 0); + if (patch && !('s' in patch)) { + const deltaFrame = packFrame({ kind: 'delta', tag, base: base.tag, patch }); + const fullFrame = packFrame({ kind: 'full', tag, value: groundTruthValue }); + return deltaFrame.byteLength <= fullFrame.byteLength ? deltaFrame : fullFrame; + } + } + + return packFrame({ kind: 'full', tag, value: groundTruthValue }); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + const maxPersistentBodyEntries = options.maxPersistentBodyEntries ?? DEFAULT_MAX_PERSISTENT_BODY_ENTRIES; + + const cache = new Map(); + let cacheBytes = 0; + const historyCache = new Map(); + let historyBytes = 0; + const inflight = new Map(); + + const persistentBodies = new Map(); + let persistentBodyBytes = 0; + + function loadPersistentState(bytes) { + persistentBodies.clear(); + persistentBodyBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const rows = JSON.parse(zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8')); + if (!Array.isArray(rows)) return; + for (const e of rows) { + if (e && typeof e.sessionId === 'string' && typeof e.id === 'string') { + rememberBody(e.sessionId, e.id, e.version, e.contentJson); + } + } + } catch { + // ignore + } + } + + function rememberBody(sessionId, id, version, contentJson) { + const key = `${sessionId}\u0000${id}`; + const prev = persistentBodies.get(key); + if (prev) { + persistentBodyBytes -= prev.contentJson.length; + persistentBodies.delete(key); + } + if (contentJson.length > maxPersistentBytes / 2) return; + persistentBodies.set(key, { sessionId, id, version, contentJson }); + persistentBodyBytes += contentJson.length; + while (persistentBodies.size > maxPersistentBodyEntries || persistentBodyBytes > maxPersistentBytes) { + const oldestKey = persistentBodies.keys().next().value; + const oldest = persistentBodies.get(oldestKey); + persistentBodyBytes -= oldest.contentJson.length; + persistentBodies.delete(oldestKey); + } + } + + function exportPersistentState() { + const rows = Array.from(persistentBodies.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.shift(); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snap = exportPersistentState(); + cache.clear(); + cacheBytes = 0; + historyCache.clear(); + historyBytes = 0; + inflight.clear(); + loadPersistentState(snap); + } + + function rememberCache(key, tag, text) { + const prev = cache.get(key); + if (prev) { + cacheBytes -= prev.text.length; + cache.delete(key); + } + if (text.length > maxCacheBytes / 2) return; + cache.set(key, { tag, text }); + cacheBytes += text.length; + while (cache.size > 32 || cacheBytes > maxCacheBytes / 2) { + const oldestKey = cache.keys().next().value; + const oldest = cache.get(oldestKey); + cacheBytes -= oldest.text.length; + cache.delete(oldestKey); + } + } + + function rememberHistory(key, entry) { + const prev = historyCache.get(key); + if (prev) { + historyBytes -= prev.bytes; + historyCache.delete(key); + } + if (entry.bytes > maxCacheBytes / 2) return; + historyCache.set(key, entry); + historyBytes += entry.bytes; + while (historyCache.size > 16 || historyBytes > maxCacheBytes / 2) { + const oldestKey = historyCache.keys().next().value; + const oldest = historyCache.get(oldestKey); + historyBytes -= oldest.bytes; + historyCache.delete(oldestKey); + } + } + + if (options.persistentState) loadPersistentState(options.persistentState); + + function beginRead({ readId, channel, argsKey }) { + const key = `${channel}\u0000${argsKey}`; + if (channel === MESSAGES_VIEW_CHANNEL) { + const parsedArgs = parseArgs(argsKey); + const sessionId = typeof parsedArgs.sessionId === 'string' ? parsedArgs.sessionId : ''; + const isLatestPage = parsedArgs.before == null; + const hvdKey = `${sessionId}\u0000latest`; + const hvdSnap = isLatestPage ? historyCache.get(hvdKey) : undefined; + const bodySnap = new Map(); + const knownBodies = []; + if (!hvdSnap && sessionId) { + const list = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) list.push(entry); + } + for (const entry of list.slice(-MAX_REUSE_MANIFEST_ENTRIES)) { + bodySnap.set(entry.id, entry); + knownBodies.push([entry.id, entry.version]); + } + } + inflight.set(readId, { channel, key, sessionId, hvdKey, hvdSnap, bodySnap, isLatestPage }); + let hasBodies = false; + if (hvdSnap && sessionId) { + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) { hasBodies = true; break; } + } + } + return packFrame({ + ...(isLatestPage ? { hvd: hvdSnap ? { base: hvdSnap.token } : {} } : {}), + ...(hasBodies ? { hasBodies: 1 } : {}), + ...(knownBodies.length > 0 ? { knownBodies } : {}), + }); + } + + const cached = cache.get(key); + inflight.set(readId, { channel, key, cached }); + return packFrame(cached ? { base: cached.tag } : {}); + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + const resp = unpackFrame(responseBytes); + + if (resp.kind === 'hvd-miss') { + const bodySnap = new Map(); + const knownBodies = []; + const list = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === state.sessionId) list.push(entry); + } + for (const entry of list.slice(-MAX_REUSE_MANIFEST_ENTRIES)) { + bodySnap.set(entry.id, entry); + knownBodies.push([entry.id, entry.version]); + } + state.hvdSnap = undefined; + state.bodySnap = bodySnap; + return { + done: false, + nextRequestBytes: packFrame({ + ...(state.isLatestPage ? { hvd: {} } : {}), + ...(knownBodies.length > 0 ? { knownBodies } : {}), + }), + }; + } + + inflight.delete(readId); + + if (state.channel === MESSAGES_VIEW_CHANNEL) { + const packed = resp.kind === 'hvd-bodies'; + let decoded = mapMessageRows(resp.value, (row) => { + let restored = row; + if (packed && !Object.prototype.hasOwnProperty.call(row, 'content')) { + const hit = state.bodySnap.get(row.id); + if (!hit || hit.version !== row.remoteBodyVersion) { + throw new Error(`Missing body for ${row.id}`); + } + restored = { ...row, content: JSON.parse(hit.contentJson) }; + } + if (state.sessionId && isReusableMessage(restored)) { + rememberBody(state.sessionId, restored.id, restored.remoteBodyVersion, JSON.stringify(restored.content)); + } + return restored; + }); + + if (isPlainObject(decoded) && Array.isArray(decoded.items) && decoded._hvd) { + const { _hvd: delta, ...page } = decoded; + const suffix = typeof delta.suffix === 'string' && delta.suffix ? delta.suffix : undefined; + const items = []; + for (const item of decoded.items) { + if (isPlainObject(item) && item.type === 'same') { + if (!state.hvdSnap || delta.base !== state.hvdSnap.token) throw new Error('hvd base mismatch'); + for (let i = item.from; i < item.from + item.count; i += 1) { + items.push(appendSuffix(JSON.parse(state.hvdSnap.itemsJson[i]), suffix)); + } + } else { + items.push(item); + } + } + const restoredPage = { ...page, items }; + if (typeof delta.token === 'string') { + const itemsJson = items.map((it) => JSON.stringify(stripSuffix(it, suffix))); + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + rememberHistory(state.hvdKey, { token: delta.token, itemsJson, bytes }); + } + return { done: true, value: restoredPage }; + } + return { done: true, value: decoded }; + } + + if (resp.kind === 'same') { + const val = JSON.parse(state.cached.text); + rememberCache(state.key, resp.tag, state.cached.text); + return { done: true, value: val }; + } + if (resp.kind === 'delta') { + const val = shallowApply(JSON.parse(state.cached.text), resp.patch, 0); + rememberCache(state.key, resp.tag, JSON.stringify(val)); + return { done: true, value: val }; + } + rememberCache(state.key, resp.tag, JSON.stringify(resp.value)); + return { done: true, value: resp.value }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/controls/incomplete/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..3795c0f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated trace parity check on public seed', async () => { + const fullTrace = generateTrace({ seed: 20260501 }); + // Run the first 60 steps (covers all 4 channels, a concurrent pair, cold reconnect, and host evict) + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-device-link-delta-sync/v1/question.json b/questions/opt-device-link-delta-sync/v1/question.json new file mode 100644 index 0000000..43e4a07 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/question.json @@ -0,0 +1,41 @@ +{ + "id": "opt-device-link-delta-sync", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "跨设备 RPC 结构化增量同步与冷缓存调和优化", + "status": "calibrated", + "changeNote": "Eval Bank high-ceiling deterministic optimization question extracted from makecindy/cindy packages/device-link (28492cd24393).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "wire_efficiency", + "weight": "1", + "mode": "metric", + "gate": [ + "gate_exact_json_parity", + "gate_process_isolation", + "gate_reconnect_and_drift", + "gate_wire_sanity" + ], + "metric": { + "id": "total_wire_bytes", + "label": "Held-out 240-RPC wire bytes", + "unit": "B", + "direction": "lower", + "baseline": 2300000, + "target": 175000, + "scale": "log" + } + } + ] +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/CONTRACT.md b/questions/opt-device-link-delta-sync/v1/reference/CONTRACT.md new file mode 100644 index 0000000..34b1c2a --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/CONTRACT.md @@ -0,0 +1,93 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (may be one of the 4 Cindy channels or any arbitrary test channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 8s` for a full 240-RPC trace). +4. **Generalization**: Evaluation runs on unseen held-out seeds, corpora, channel payloads, and event timings. Do not hardcode trace strings or schema assumptions that break on unseen payloads. diff --git a/questions/opt-device-link-delta-sync/v1/reference/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..8e0ce3f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/ENVIRONMENT.md @@ -0,0 +1,10 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic 240-RPC two-process benchmark across all 4 Cindy channels reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, and compression ratio vs raw JSON diff --git a/questions/opt-device-link-delta-sync/v1/reference/TASK.md b/questions/opt-device-link-delta-sync/v1/reference/TASK.md new file mode 100644 index 0000000..4ce97c8 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/TASK.md @@ -0,0 +1,25 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC delta synchronization and cold-cache reconciliation protocol (`src/sync-protocol.mjs`), extracted from production desktop-to-mobile remote sessions (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). + +## Observed Production Bottlenecks + +In a typical mobile-over-cellular session polling 4 read-heavy RPC channels across ~240 reads (~20 MiB of raw JSON), the current baseline protocol burns over **2.0 MiB** of metered wire traffic (upstream + downstream combined) due to compounding architectural limits: + +1. **Channel silo**: `invokeDelta` is enabled ONLY on `local-db:sessions:list`; structured catalogs (`maker:provider:list`, ~45 KiB/poll) and schedule indices (`maker:schedule:list-sidebar-index-runs`, ~28 KiB/poll) resend full gzipped JSON on every single poll even when only quota numbers or 1–3 run entries changed. +2. **Coarse row-level diff & abort cliffs**: `invokeDelta` stops at `MAX_DEPTH = 2` (replacing entire session rows whenever a single field changes), aborts to a full snapshot whenever the uncompressed JSON patch exceeds `MAX_DELTA_RATIO = 0.5` (triggered during bulk device/tag refreshes where >55% of rows change 1 field), and resets to a full snapshot every `MAX_UNVERIFIED_DELTAS = 8` incremental reads. +3. **Expensive streaming appends & suffix churn in `local-db:messages:view`**: `historyViewDelta` only deduplicates completely identical items; appending 100–400 characters of streaming assistant text/thinking forces the entire multi-kilobyte message item to be re-sent on every poll, while page-wide `revisionSuffix` updates touch every `work` item. +4. **Bloated cold-cache manifests & weak cold reconciliation**: After mobile background-kill & cold reconnect (or host volatile-base eviction), `SessionMessageReuse` uploads up to 256 `[id, 64-hex-sha256]` pairs (~15–25 KiB upstream per read) only for `messages:view` and resends full gzipped snapshots for the other channels. +5. **Single/brittle base tracking & generic compression**: Concurrent in-flight reads with a slightly stale base fall back to full snapshots, and JSON patches carry heavy structural/key overhead without leveraging the already-synchronized base state. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every RPC read across all channels, pagination queries, streaming updates, arbitrary edge-case JSON shapes, mobile cold reconnects, host volatile-base evictions, and concurrent in-flight stale-base reads. +- Respect **strict two-process isolation**: Host and Client run in completely separate Node.js child processes communicating **only** via `Uint8Array` wire frames. No shared memory, filesystem, network, or side channels are permitted. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return a `Uint8Array` within `maxPersistentBytes` (default `2 MiB`), and every RPC must complete in at most `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended optimization goal**: Design any clean, general, deterministic two-party sync protocol inside `src/` to drive `total_wire_bytes` (sum of **all** upstream `requestBytes` and downstream `responseBytes` across **all** rounds and **all** RPCs) as low as possible — both on public benchmarks and on unseen held-out workloads with different seeds, payloads, vocabularies, and reconnect timings. +- Run `npm test` and `npm run bench` to verify exact parity and measure your wire-byte reduction. +- Record your analysis, protocol design, trade-offs, and verified benchmark results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v1/reference/bench/workload.mjs b/questions/opt-device-link-delta-sync/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..5eaab10 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark(seed = 20260501) { + const trace = generateTrace({ seed }); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + seed, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + host_evictions: trace.meta.hostEvictCount, + concurrent_pairs: trace.meta.concurrentPairCount, + bulk_storms: trace.meta.bulkStormCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v1/reference/lib/rpc-harness.mjs new file mode 100644 index 0000000..03d2824 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/lib/rpc-harness.mjs @@ -0,0 +1,293 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/lib/trace-generator.mjs b/questions/opt-device-link-delta-sync/v1/reference/lib/trace-generator.mjs new file mode 100644 index 0000000..3621bc5 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/lib/trace-generator.mjs @@ -0,0 +1,936 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic Mulberry32 PRNG. + */ +export function createRng(seed) { + let state = (seed >>> 0) || 1; + return { + next() { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }, + int(min, max) { + return min + Math.floor(this.next() * (max - min + 1)); + }, + pick(arr) { + return arr[Math.floor(this.next() * arr.length)]; + }, + bool(p = 0.5) { + return this.next() < p; + }, + hex(len) { + const chars = '0123456789abcdef'; + let out = ''; + for (let i = 0; i < len; i += 1) { + out += chars[Math.floor(this.next() * 16)]; + } + return out; + }, + shuffle(arr) { + const out = arr.slice(); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = Math.floor(this.next() * (i + 1)); + const tmp = out[i]; + out[i] = out[j]; + out[j] = tmp; + } + return out; + }, + }; +} + +function sha256Hex(str) { + return crypto.createHash('sha256').update(str, 'utf8').digest('hex'); +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +export const DEFAULT_CORPUS = { + idPrefix: 'pub', + devices: [ + 'dev-mac-studio-01', + 'dev-mbp-m4-02', + 'dev-linux-build-03', + 'dev-wsl-workstation-04', + ], + workingDirs: [ + '/Users/dev/workspace/cindy-core', + '/Users/dev/workspace/cindy-mobile', + '/Users/dev/workspace/cindy-relay', + '/Users/dev/workspace/eval-bank', + '/Users/dev/workspace/agent-sdk', + '/Users/dev/workspace/docs-site', + ], + subdirs: [ + 'packages/device-link/src', + 'packages/maker-shared/src', + 'apps/mobile/src/sync', + 'apps/desktop/src/main', + 'services/relay-edge/src', + 'crates/protocol/src', + 'tests/integration', + 'scripts/bench', + ], + fileStems: [ + 'invokeDelta', 'invokeTransfer', 'historyViewDelta', 'sessionMessageReuse', + 'routedClient', 'listingReadCoalescer', 'transportBacklog', 'pushTransfer', + 'nodeCompression', 'remoteAgent', 'metadataContinuity', 'setupSnapshot', + 'stallDiagnostics', 'peerRecovery', 'cacheBudget', 'streamAssembler', + 'frameCodec', 'merkleIndex', 'walCheckpoint', 'quotaTracker', + ], + symbolVerbs: [ + 'reconcile', 'compute', 'decode', 'encode', 'evict', 'normalize', 'compact', + 'verify', 'dispatch', 'coalesce', 'hydrate', 'serialize', 'inflate', 'prune', + 'merge', 'replay', 'checkpoint', 'validate', + ], + symbolNouns: [ + 'DeltaBase', 'HistoryPage', 'MessageBody', 'WireFrame', 'SnapshotRing', + 'RevisionSuffix', 'ColdManifest', 'SessionRow', 'QuotaBucket', 'RunWindow', + 'PrefixLadder', 'PatchOp', 'ChunkDigest', 'PeerCursor', 'TransferHeader', + 'KeyTable', 'StreamBuffer', 'CacheEntry', + ], + cjkTopics: [ + '跨设备弱网同步延迟', '批量行刷新触发阈值回退', '移动端冷重连摘要上行膨胀', + '流式文本追加导致整条消息重传', '工作摘要版本号后缀高频抖动', '并发读取基准淘汰错位', + '本地持久化缓存体积上限控制', '多通道结构化目录轮询冗余', '字典压缩窗口命中率下降', + '分页历史回溯与最新页缓存复用', '异步队列背压与帧边界对齐', '索引重排与键表编码开销', + '断连恢复后的冷缓存集合调和', '长日志代码块与多语言字符集校验', '任务状态栏高频更新节流', + '定时任务滑动窗口增量裁剪', + ], + enObservations: [ + 'Observed wire amplification during bulk metadata refresh across active peers', + 'Detected redundant retransmission of unchanged markdown prefixes while streaming', + 'Measured upstream handshake spike when uploading full 64-hex SHA-256 manifests', + 'Confirmed multi-snapshot ring avoids full-page fallback under pipelined reads', + 'Profiled deflate dictionary match ratio against prior synchronized base payload', + 'Validated exact JSON parity for empty containers, floats, null fields, and emoji', + 'Traced revision suffix propagation across nested work summary child nodes', + 'Benchmarked recursive keyed array diff against coarse depth-2 row replacement', + 'Audited persistent cache serialization size under mobile background termination', + 'Inspected pagination cursor overlap when scrolling older transcript segments', + 'Evaluated 2-RTT set reconciliation bandwidth on partial state divergence', + 'Checked varint length framing and key-table interning on structured provider lists', + ], + cjkActions: [ + '建议改为按主键递归比对字段,仅下发变动属性与紧凑索引序列', + '排查发现未命中易失基准时会直接回退整页快照,应结合持久化摘要跳过未变正文', + '实测在流式输出阶段采用前缀复用加尾部追加指令,可将单次下行体积压缩至原来的十分之一', + '需要同时保留最近多个已确认与在途基准,防止并发轮询携带旧标签时反复触发全量同步', + '对比普通压缩与基于旧快照预置字典的原始流压缩,重复路径和模型标识几乎不再占用字节', + '核对边界用例:空数组、空对象、中文标点、表情符号及原型同名普通键均须严格等价', + '对冷启动重连场景,采用分层前缀哈希或紧凑摘要握手可避免每次上传数十千字节清单', + '注意在 diff 前先校验所有 work 节点确实携带统一页级后缀,避免误改异常数据', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-sonnet-4-5', + 'claude-opus-4-1', + 'gpt-5.3-codex', + 'gemini-2.5-pro', + 'deepseek-r1-0528', + 'qwen3-coder-480b', + ], + tagsPool: [ + 'device-link', 'perf', 'sync', 'mobile', 'relay', 'p0', 'p1', + 'refactor', 'sqlite', 'rpc', 'telemetry', 'ci', 'security', 'ux', + ], + sessionTitles: [ + '重构 device-link 跨设备增量同步协议', + 'Fix mobile cold-reconnect history delta miss', + '优化弱网 JSON 压缩与字典复用策略', + 'Investigate provider quota sidebar polling lag', + '排查 schedule 侧栏索引高频刷新流量消耗', + 'Implement binary patch encoder for sessions list', + '修复并发 stale-base 读取回退全文问题', + 'Audit SessionMessageReuse cache eviction bounds', + '支持多轮 Merkle 集合调和协议实验', + 'Optimize SQLite WAL checkpoint during streaming', + '解决 CJK 长文本流式追加重复传输瓶颈', + 'Verify deterministic replay across macOS & Linux', + ], + toolNames: ['read_file', 'run_command', 'edit_file', 'grep_search', 'list_dir'], + workTitles: [ + 'Inspect device-link delta protocol', + 'Run unit test suite', + 'Measure wire bytes on mobile trace', + 'Patch revision suffix normalization', + 'Verify cold-reconnect cache parity', + 'Profile streaming message append cost', + ], + providers: [ + { id: 'anthropic', name: 'Anthropic Direct', kind: 'anthropic', baseUrl: 'https://api.anthropic.com/v1', region: 'us-east-1', tier: 'enterprise' }, + { id: 'openai', name: 'OpenAI Platform', kind: 'openai', baseUrl: 'https://api.openai.com/v1', region: 'us-west-2', tier: 'tier-5' }, + { id: 'google', name: 'Google AI Studio', kind: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', region: 'us-central1', tier: 'paid' }, + { id: 'vertex', name: 'Google Cloud Vertex AI', kind: 'vertex', baseUrl: 'https://us-central1-aiplatform.googleapis.com/v1', region: 'us-central1', tier: 'enterprise' }, + { id: 'bedrock', name: 'AWS Bedrock', kind: 'bedrock', baseUrl: 'https://bedrock-runtime.us-west-2.amazonaws.com', region: 'us-west-2', tier: 'enterprise' }, + { id: 'deepseek', name: 'DeepSeek API', kind: 'openai-compat', baseUrl: 'https://api.deepseek.com/v1', region: 'ap-east-1', tier: 'pro' }, + { id: 'openrouter', name: 'OpenRouter Gateway', kind: 'openai-compat', baseUrl: 'https://openrouter.ai/api/v1', region: 'global', tier: 'credits' }, + { id: 'xai', name: 'xAI Grok API', kind: 'openai-compat', baseUrl: 'https://api.x.ai/v1', region: 'us-west-1', tier: 'pro' }, + { id: 'qwen', name: 'Alibaba DashScope Qwen', kind: 'openai-compat', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', region: 'cn-beijing', tier: 'enterprise' }, + { id: 'moonshot', name: 'Moonshot Kimi API', kind: 'openai-compat', baseUrl: 'https://api.moonshot.cn/v1', region: 'cn-north-1', tier: 'pro' }, + { id: 'zhipu', name: 'Zhipu GLM OpenPlatform', kind: 'openai-compat', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', region: 'cn-east-1', tier: 'pro' }, + { id: 'minimax', name: 'MiniMax Coding Plan', kind: 'anthropic-compat', baseUrl: 'https://api.minimaxi.com/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'ollama-local', name: 'Local Ollama Studio', kind: 'ollama', baseUrl: 'http://127.0.0.1:11434/v1', region: 'local', tier: 'free' }, + { id: 'team-proxy', name: 'Internal LiteLLM Proxy', kind: 'openai-compat', baseUrl: 'https://llm-gateway.internal.example/v1', region: 'eu-central-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Nightly PR triage & CI digest', + '每小时同步上游安全通告', + 'Release branch changelog builder', + 'Mobile relay latency watchdog', + '清理过期工作区缓存与临时构建', + 'Weekly dependency vulnerability audit', + 'Eval Bank regression tracker', + '数据库 WAL 体积巡检任务', + ], + schedulePrompts: [ + 'Inspect open pull requests with failing checks, summarize root causes, and draft minimal fixes.', + '检查过去 1 小时内 relay 节点的 P95 延迟与断线重连日志,如异常则生成排查摘要。', + 'Collect merged commits since the last tag and prepare structured release notes grouped by subsystem.', + 'Audit disk usage of local session archives and flag workspaces exceeding 500 MiB.', + ], +}; + +function makeSymbol(rng, corpus) { + return `${rng.pick(corpus.symbolVerbs)}${rng.pick(corpus.symbolNouns)}`; +} + +function makeFilePath(rng, corpus) { + return `${rng.pick(corpus.subdirs)}/${rng.pick(corpus.fileStems)}.ts`; +} + +/** + * Generates realistic, high-entropy technical paragraphs combining unique identifiers, + * paths, line ranges, commit hashes, metrics, code fragments, and CJK+English prose. + */ +function makeUniqueParagraph(rng, corpus, seq) { + const kind = rng.int(0, 4); + const file = makeFilePath(rng, corpus); + const symA = makeSymbol(rng, corpus); + const symB = makeSymbol(rng, corpus); + const line = rng.int(18, 640); + const commit = rng.hex(10); + const bytesBefore = rng.int(12_000, 195_000); + const bytesAfter = Math.max(240, Math.floor(bytesBefore * (0.04 + rng.next() * 0.28))); + const ms = rng.int(4, 380); + + if (kind === 0) { + return `[${commit}] ${rng.pick(corpus.enObservations)} in \`${file}:${line}\` (\`${symA}\` -> \`${symB}\`): payload=${bytesBefore}B -> ${bytesAfter}B (${ms}ms, seq=${seq}). ${rng.pick(corpus.cjkTopics)}:${rng.pick(corpus.cjkActions)}。`; + } + if (kind === 1) { + const varA = `${rng.pick(corpus.symbolNouns).toLowerCase()}_${rng.hex(4)}`; + const varB = `tag_${rng.hex(6)}`; + return `\`\`\`ts\n// ${file}:${line} (${commit})\nexport function ${symA}(${varA}: Uint8Array, ${varB}: string) {\n const limit = ${rng.int(64, 4096)};\n return ${symB}(${varA}.subarray(0, Math.min(${varA}.byteLength, limit)), ${varB});\n}\n\`\`\`\n分析结论(#${seq}):针对「${rng.pick(corpus.cjkTopics)}」,${rng.pick(corpus.cjkActions)}(实测耗时 ${ms}ms,压缩后 ${bytesAfter}B)。`; + } + if (kind === 2) { + const reqId = `req-${rng.hex(8)}`; + const peerId = `peer-${rng.hex(6)}`; + return `Trace ${reqId} (${peerId}): ${rng.pick(corpus.enObservations)}. Checked \`${symA}\` at \`${file}:${line}-${line + rng.int(8, 45)}\` against commit \`${commit}\` (delta=${bytesAfter}B vs raw=${bytesBefore}B, ratio=${((bytesAfter / bytesBefore) * 100).toFixed(2)}%). 备注:${rng.pick(corpus.cjkTopics)} ✅`; + } + if (kind === 3) { + return `在排查 \`${file}\` 第 ${line} 行 \`${symA}\`(提交 \`${commit}\`)时观测到「${rng.pick(corpus.cjkTopics)}」,单次同步帧达到 ${bytesBefore} 字节。${rng.pick(corpus.cjkActions)},验证通过 ${rng.int(12, 96)} 组用例(${ms}ms,目标 ${bytesAfter}B)。`; + } + const errCode = `ERR_${rng.pick(corpus.symbolNouns).toUpperCase()}_${rng.int(100, 999)}`; + return `Diagnostic ${errCode} @ \`${file}:${line}\` [rev=${seq}, hash=${commit}]: \`${symA}\` returned ${bytesAfter}B after calling \`${symB}\`. ${rng.pick(corpus.enObservations)}; verified fallback parity without data drift (${ms}ms).`; +} + +function makeStreamAppendChunk(rng, corpus, seq) { + const file = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(8); + const line = rng.int(10, 580); + const val = rng.int(120, 98000); + if (rng.bool(0.5)) { + return `[chunk-${commit}] \`${file}:${line}\` \`${sym}()\`: ${rng.pick(corpus.enObservations)} (measured=${val}B, step=${seq}). ${rng.pick(corpus.cjkTopics)}。`; + } + return `(片段 ${commit})检查 \`${file}:${line}\` 中的 \`${sym}\`:${rng.pick(corpus.cjkActions)}(指标=${val},序号=${seq})。`; +} + +function makeThinkingChunk(rng, corpus, seq) { + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(6); + const n = rng.int(16, 4096); + if (rng.bool(0.5)) { + return `Checking \`${sym}\` (#${seq}, id=${commit}, budget=${n}B): ${rng.pick(corpus.enObservations)}. `; + } + return `思考(${commit}/#${seq}):关于「${rng.pick(corpus.cjkTopics)}」与 \`${sym}\`(${n}B),${rng.pick(corpus.cjkActions)}。`; +} + +function makeToolOutput(rng, corpus, seq) { + const f1 = makeFilePath(rng, corpus); + const f2 = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const h = rng.hex(10); + return [ + `${f1}:${rng.int(10, 400)}: export function ${sym}(ctx_${seq}) { /* ${h} */ }`, + `${f2}:${rng.int(10, 400)}: assert.equal(checksum, "${rng.hex(16)}");`, + `PASS ${rng.int(14, 68)}/${rng.int(68, 72)} assertions (${rng.int(42, 890)}ms, rss=${rng.int(34, 128)}MB)`, + ].join('\n'); +} + +function makeMessageText(rng, corpus, seq, paragraphs) { + const parts = []; + for (let i = 0; i < paragraphs; i += 1) { + parts.push(makeUniqueParagraph(rng, corpus, seq * 10 + i)); + } + return parts.join('\n\n'); +} + +function createInitialSessions(rng, corpus, baseTime) { + const sessions = []; + for (let i = 0; i < 160; i += 1) { + const id = `${corpus.idPrefix}-sess-${String(i + 1).padStart(4, '0')}-${rng.hex(4)}`; + const tagCount = rng.int(1, 3); + const tags = []; + for (let t = 0; t < tagCount; t += 1) { + const tag = rng.pick(corpus.tagsPool); + if (!tags.includes(tag)) tags.push(tag); + } + const input = rng.int(4000, 180000); + const output = rng.int(800, 42000); + const cacheRead = rng.int(10000, 600000); + const sym = makeSymbol(rng, corpus); + sessions.push({ + id, + title: `${rng.pick(corpus.sessionTitles)} [${sym} #${i + 1}]`, + workingDir: `${rng.pick(corpus.workingDirs)}/${rng.pick(corpus.fileStems)}`, + agentKind: rng.pick(corpus.agentKinds), + phase: i < 8 ? 'running' : rng.pick(['idle', 'idle', 'idle', 'waiting_approval', 'error']), + updatedAt: baseTime - i * rng.int(45_000, 300_000), + lastMessagePreview: `${rng.pick(corpus.cjkTopics)} · ${sym} (${rng.hex(8)}): ${rng.pick(corpus.enObservations).slice(0, 68)}`, + tokenUsage: { + input, + output, + cacheRead, + costUsd: Math.round((input * 0.000003 + output * 0.000015 + cacheRead * 0.0000003) * 10000) / 10000, + }, + tags, + unreadCount: i < 12 ? rng.int(0, 5) : 0, + pinned: i < 24, + modelLabel: rng.pick(corpus.modelLabels), + deviceId: rng.pick(corpus.devices), + deviceOnline: true, + }); + } + return sessions; +} + +function makeMessageItem(rng, corpus, sessionId, seq, timestamp, revSuffix) { + const isWork = seq % 5 === 4; + if (isWork) { + const workId = `${corpus.idPrefix}-${sessionId}-w${String(seq).padStart(4, '0')}`; + const sym = makeSymbol(rng, corpus); + return { + key: `work:${workId}`, + type: 'work', + summary: { + title: `${rng.pick(corpus.workTitles)} · ${sym} (#${seq})`, + status: 'done', + revision: `${workId}-r1${revSuffix}`, + durationMs: rng.int(180, 9400), + }, + children: [ + { + key: `work:${workId}:c1`, + type: 'work', + summary: { + title: `Step 1: ${rng.pick(corpus.toolNames)} ${makeFilePath(rng, corpus)}`, + status: 'done', + revision: `${workId}-c1-r1${revSuffix}`, + durationMs: rng.int(60, 2400), + }, + }, + ], + }; + } + const msgId = `${corpus.idPrefix}-${sessionId}-m${String(seq).padStart(4, '0')}`; + const role = seq % 2 === 0 ? 'user' : 'assistant'; + const paragraphs = role === 'user' ? rng.int(1, 2) : rng.int(3, 5); + const text = `[#${seq}] ${makeMessageText(rng, corpus, seq, paragraphs)}`; + const content = { text }; + const row = { + id: msgId, + role, + createdAt: timestamp, + remoteBodyVersion: sha256Hex(JSON.stringify(content)), + content, + }; + if (role === 'assistant') { + row.thinking = makeThinkingChunk(rng, corpus, seq) + makeThinkingChunk(rng, corpus, seq + 1); + if (seq % 3 === 1) { + row.toolCalls = [ + { + id: `tc-${seq}-${rng.hex(4)}`, + name: rng.pick(corpus.toolNames), + args: { + path: `${rng.pick(corpus.workingDirs)}/${makeFilePath(rng, corpus)}`, + limit: rng.int(50, 200), + }, + status: 'done', + output: makeToolOutput(rng, corpus, seq), + }, + ]; + } + } + return { + key: `msg:${msgId}`, + type: 'messages', + messages: [row], + }; +} + +function applyRevisionSuffix(items, oldSuffix, newSuffix) { + for (const item of items) { + if (item.type === 'work') { + if (item.summary && typeof item.summary.revision === 'string' && item.summary.revision.endsWith(oldSuffix)) { + item.summary.revision = item.summary.revision.slice(0, -oldSuffix.length) + newSuffix; + } + if (Array.isArray(item.children)) { + applyRevisionSuffix(item.children, oldSuffix, newSuffix); + } + } + } +} + +function createInitialSessionHistory(rng, corpus, sessionId, baseTime) { + const rev = 1; + const revSuffix = `:rev-${rev}`; + const items = []; + for (let seq = 1; seq <= 35; seq += 1) { + items.push(makeMessageItem(rng, corpus, sessionId, seq, baseTime - (36 - seq) * 18_000, revSuffix)); + } + return { + sessionId, + nextSeq: 36, + rev, + revSuffix, + streamingTicksLeft: 0, + runningWorkSummary: { + status: 'running', + activeTool: rng.pick(corpus.toolNames), + elapsedMs: 1200, + stepCount: 1, + lines: [`Initialized trace session ${sessionId} (${rng.hex(8)})`], + }, + items, + }; +} + +function createInitialProviders(rng, corpus, baseTime) { + const capabilityPool = ['tools', 'vision', 'reasoning', 'caching', 'streaming', 'json-schema']; + const providers = corpus.providers.map((p, idx) => { + const modelCount = 7 + (idx % 4); + const models = []; + for (let m = 0; m < modelCount; m += 1) { + const tier = m === 0 ? 'flagship' : m < 3 ? 'balanced' : m < 6 ? 'fast' : 'mini'; + const capCount = 3 + (m % 4); + models.push({ + id: `${p.id}/${tier}-v${(m % 5) + 1}.${idx % 3}-${rng.hex(3)}`, + label: `${p.name} ${tier.toUpperCase()} ${(m % 5) + 1}.${idx % 3}`, + description: `${p.name} ${tier} profile (${p.region}, ${makeSymbol(rng, corpus)}, rev-${rng.hex(6)}): ${rng.pick(corpus.enObservations)}`, + contextWindow: m < 3 ? 200_000 : m < 6 ? 128_000 : 64_000, + maxOutputTokens: m < 2 ? 32_768 : 16_384, + pricing: { + inputPerM: Math.round((0.15 + (modelCount - m) * 0.85) * 100) / 100, + outputPerM: Math.round((0.6 + (modelCount - m) * 3.1) * 100) / 100, + cacheReadPerM: Math.round((0.03 + (modelCount - m) * 0.12) * 100) / 100, + }, + capabilities: capabilityPool.slice(0, capCount), + deprecated: false, + defaultEffort: m < 2 ? 'high' : 'medium', + }); + } + const dailyLimit = 5_000_000 + idx * 1_500_000; + const usedPercent = Math.round(rng.next() * 450) / 10; + return { + id: p.id, + name: p.name, + kind: p.kind, + enabled: true, + status: 'healthy', + baseUrl: p.baseUrl, + region: p.region, + latencyMs: rng.int(110, 620), + checkedAt: baseTime, + quota: { + usedPercent, + remainingTokens: Math.round(dailyLimit * (1 - usedPercent / 100)), + dailyLimit, + resetAt: baseTime + 6 * 3600_000, + tier: p.tier, + }, + models, + }; + }); + return { + catalogVersion: 4, + generatedAt: baseTime, + activeProviderId: providers[0].id, + providers, + }; +} + +function createInitialSchedules(rng, corpus, baseTime) { + const crons = ['*/15 * * * *', '0 * * * *', '0 */4 * * *', '0 9 * * 1-5', '30 2 * * *']; + const jobs = []; + for (let i = 0; i < 40; i += 1) { + const recentRuns = []; + for (let r = 0; r < 6; r += 1) { + const startedAt = baseTime - (6 - r) * 3600_000 - i * 17_000; + const durationMs = rng.int(2400, 48000); + recentRuns.push({ + runId: `${corpus.idPrefix}-run-${i + 1}-${r + 1}-${rng.hex(4)}`, + startedAt, + finishedAt: startedAt + durationMs, + status: r === 4 && i % 9 === 0 ? 'failed' : 'succeeded', + durationMs, + summary: `${rng.pick(corpus.scheduleNames)} [${rng.hex(6)}] (${rng.int(1, 24)} items, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1200, 36000), + }); + } + jobs.push({ + id: `${corpus.idPrefix}-sched-${String(i + 1).padStart(3, '0')}`, + name: `${rng.pick(corpus.scheduleNames)} #${i + 1}`, + cron: rng.pick(crons), + prompt: `${rng.pick(corpus.schedulePrompts)} (${makeFilePath(rng, corpus)})`, + targetSessionId: `${corpus.idPrefix}-sess-${String((i % 30) + 1).padStart(4, '0')}`, + workspaceDir: rng.pick(corpus.workingDirs), + enabled: i % 11 !== 10, + nextRunAt: baseTime + rng.int(120_000, 7200_000), + lastStatus: recentRuns[recentRuns.length - 1].status, + recentRuns, + runSeq: 7, + }); + } + return { + indexVersion: 3, + updatedAt: baseTime, + totalJobs: jobs.length, + jobs, + }; +} + +export const DEFAULT_SCHEDULE_PROFILE = { + coldReconnectTicks: [34, 72, 110, 148, 184, 214], + hostEvictTicks: [52, 128, 198], + concurrentSpecs: [ + { tick: 24, channel: 'local-db:sessions:list' }, + { tick: 92, channel: 'local-db:messages:view' }, + { tick: 162, channel: 'local-db:sessions:list' }, + { tick: 204, channel: 'maker:provider:list' }, + ], +}; + +/** + * Generate a deterministic 240-RPC multi-channel Cindy sync trace. + */ +export function generateTrace({ + seed = 20260501, + corpus = DEFAULT_CORPUS, + scheduleProfile = DEFAULT_SCHEDULE_PROFILE, +} = {}) { + const rng = createRng(seed); + let clock = 1_765_000_000_000 + (seed % 1000) * 60_000; + + const sessions = createInitialSessions(rng, corpus, clock); + const histA = createInitialSessionHistory(rng, corpus, 'active-A', clock); + const histB = createInitialSessionHistory(rng, corpus, 'active-B', clock); + const providerCatalog = createInitialProviders(rng, corpus, clock); + const scheduleIndex = createInitialSchedules(rng, corpus, clock); + + let sessionsPollCount = 0; + let bulkStormCount = 0; + let deviceOnlineFlip = false; + + function mutateSessions(bulkOverride = false) { + sessionsPollCount += 1; + clock += rng.int(1500, 4500); + const isBulkStorm = bulkOverride || (sessionsPollCount > 2 && sessionsPollCount % 10 === 0); + if (isBulkStorm) { + bulkStormCount += 1; + deviceOnlineFlip = !deviceOnlineFlip; + const ratio = 0.60 + rng.next() * 0.15; + const count = Math.floor(sessions.length * ratio); + const indices = rng.shuffle(Array.from({ length: sessions.length }, (_, i) => i)).slice(0, count); + for (const idx of indices) { + const s = sessions[idx]; + s.deviceOnline = deviceOnlineFlip; + s.tokenUsage.cacheRead += rng.int(50, 900); + if (idx % 5 === 0) s.updatedAt = clock; + } + } + const mutateCount = rng.int(4, 12); + const picked = []; + for (let i = 0; i < mutateCount; i += 1) { + const idx = rng.int(0, Math.min(sessions.length - 1, 45)); + if (!picked.includes(idx)) picked.push(idx); + } + for (const idx of picked) { + const s = sessions[idx]; + s.updatedAt = clock - rng.int(0, 900); + s.phase = rng.pick(['running', 'idle', 'waiting_approval']); + s.tokenUsage.input += rng.int(200, 4500); + s.tokenUsage.output += rng.int(80, 1200); + s.tokenUsage.costUsd = Math.round( + (s.tokenUsage.input * 0.000003 + s.tokenUsage.output * 0.000015 + s.tokenUsage.cacheRead * 0.0000003) * 10000, + ) / 10000; + s.unreadCount = s.phase === 'running' ? s.unreadCount + 1 : 0; + if (rng.bool(0.5)) { + s.lastMessagePreview = `${rng.pick(corpus.cjkTopics)} · ${makeSymbol(rng, corpus)} (${rng.hex(6)}): ${rng.pick(corpus.enObservations).slice(0, 56)}`; + } + } + const moveCount = Math.min(picked.length, rng.int(2, 5)); + for (let m = 0; m < moveCount; m += 1) { + const idx = picked[m]; + if (idx > 0 && idx < sessions.length) { + const [row] = sessions.splice(idx, 1); + const dest = rng.int(0, Math.min(8, sessions.length)); + sessions.splice(dest, 0, row); + } + } + } + + function snapshotSessions(scope) { + if (scope === 'pinned') { + const pinned = sessions.filter((s) => s.pinned).slice(0, 40); + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'pinned', + totalCount: pinned.length, + activeDeviceId: corpus.devices[0], + sessions: pinned, + }); + } + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'all', + totalCount: sessions.length, + activeDeviceId: corpus.devices[0], + sessions, + }); + } + + function mutateHistory(hist, steps = 1) { + for (let s = 0; s < steps; s += 1) { + clock += rng.int(900, 2800); + const oldSuffix = hist.revSuffix; + hist.rev += 1; + const newSuffix = `:rev-${hist.rev}`; + applyRevisionSuffix(hist.items, oldSuffix, newSuffix); + hist.revSuffix = newSuffix; + + hist.runningWorkSummary.elapsedMs += rng.int(800, 3200); + hist.runningWorkSummary.stepCount += 1; + hist.runningWorkSummary.activeTool = rng.pick(corpus.toolNames); + hist.runningWorkSummary.lines.push( + `[rev ${hist.rev}] ${hist.runningWorkSummary.activeTool} ${makeSymbol(rng, corpus)} (${rng.hex(6)})`, + ); + if (hist.runningWorkSummary.lines.length > 6) { + hist.runningWorkSummary.lines.shift(); + } + + const lastItem = hist.items[hist.items.length - 1]; + const canStreamAppend = + hist.streamingTicksLeft > 0 + && lastItem + && lastItem.type === 'messages' + && lastItem.messages[0]?.role === 'assistant'; + + if (canStreamAppend) { + // Streaming text/thinking append (120–380 chars appended onto the last message!) + const msg = lastItem.messages[0]; + const appended = makeStreamAppendChunk(rng, corpus, hist.rev); + msg.content.text += `\n${appended}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + if (rng.bool(0.65) && typeof msg.thinking === 'string') { + msg.thinking += makeThinkingChunk(rng, corpus, hist.rev); + } + hist.streamingTicksLeft -= 1; + } else if (hist.items.length < 140) { + // Advance a conversation turn (user message + optional work step + new streaming assistant message) + const burst = rng.int(2, 4); + let lastAdded = null; + for (let b = 0; b < burst && hist.items.length < 140; b += 1) { + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + b * 250, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + lastAdded = item; + } + if (lastAdded && lastAdded.type === 'messages' && lastAdded.messages[0].role === 'assistant') { + hist.streamingTicksLeft = rng.int(3, 5); + } else if (hist.items.length < 140) { + // Ensure next item starts a streaming assistant turn + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + 900, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + hist.streamingTicksLeft = + item.type === 'messages' && item.messages[0].role === 'assistant' ? rng.int(3, 5) : 0; + } else { + hist.streamingTicksLeft = 0; + } + } else { + for (let i = hist.items.length - 1; i >= 0; i -= 1) { + const cand = hist.items[i]; + if (cand.type === 'messages' && cand.messages[0].role === 'assistant') { + const msg = cand.messages[0]; + msg.content.text += `\n${makeStreamAppendChunk(rng, corpus, hist.rev)}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + break; + } + } + } + } + } + + function snapshotHistory(hist, beforeIndex = null) { + if (beforeIndex !== null) { + const start = Math.max(0, beforeIndex - 28); + const slice = hist.items.slice(start, beforeIndex); + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: start > 0, + nextBefore: slice[0]?.key ?? null, + before: hist.items[beforeIndex]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: slice, + }); + } + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: true, + nextBefore: hist.items[0]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: hist.items, + }); + } + + function mutateProviders() { + clock += rng.int(1200, 3500); + providerCatalog.generatedAt = clock; + const statusChoices = ['healthy', 'healthy', 'healthy', 'degraded', 'rate_limited']; + const changedStatus = new Set([ + rng.int(0, providerCatalog.providers.length - 1), + rng.int(0, providerCatalog.providers.length - 1), + ]); + for (let i = 0; i < providerCatalog.providers.length; i += 1) { + const p = providerCatalog.providers[i]; + if (rng.bool(0.5) || changedStatus.has(i)) { + p.checkedAt = clock; + p.latencyMs = Math.max(45, p.latencyMs + rng.int(-35, 45)); + const nextPct = Math.min(99.9, Math.round((p.quota.usedPercent + rng.next() * 1.4) * 10) / 10); + p.quota.usedPercent = nextPct; + p.quota.remainingTokens = Math.max(0, Math.round(p.quota.dailyLimit * (1 - nextPct / 100))); + if (rng.bool(0.2)) { + p.quota.resetAt = clock + 6 * 3600_000; + } + } + if (changedStatus.has(i)) { + p.status = rng.pick(statusChoices); + } + } + } + + function mutateSchedules() { + clock += rng.int(1500, 4000); + scheduleIndex.updatedAt = clock; + const mutateCount = rng.int(1, 3); + const chosen = new Set(); + while (chosen.size < mutateCount) { + chosen.add(rng.int(0, scheduleIndex.jobs.length - 1)); + } + for (const idx of chosen) { + const job = scheduleIndex.jobs[idx]; + const durationMs = rng.int(1800, 42000); + const status = rng.bool(0.88) ? 'succeeded' : 'failed'; + const runEntry = { + runId: `${corpus.idPrefix}-run-${idx + 1}-${job.runSeq}-${rng.hex(4)}`, + startedAt: clock - durationMs, + finishedAt: clock, + status, + durationMs, + summary: `${job.name} [${rng.hex(6)}] (${rng.int(1, 20)} records, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1400, 29000), + }; + job.runSeq += 1; + job.lastStatus = status; + job.nextRunAt = clock + rng.int(900_000, 7200_000); + job.recentRuns.push(runEntry); + if (job.recentRuns.length > 6) { + job.recentRuns.shift(); + } + } + } + + const concurrentByTick = new Map(scheduleProfile.concurrentSpecs.map((c) => [c.tick, c.channel])); + const coldReconnectSet = new Set(scheduleProfile.coldReconnectTicks); + const hostEvictSet = new Set(scheduleProfile.hostEvictTicks); + + const targets = { + 'local-db:sessions:list': 76, + 'local-db:messages:view': 98, + 'maker:provider:list': 28, + 'maker:schedule:list-sidebar-index-runs': 30, + }; + const emitted = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + const channelOrder = [ + 'local-db:messages:view', + 'local-db:sessions:list', + 'maker:provider:list', + 'maker:schedule:list-sidebar-index-runs', + ]; + const totalNonConcurrent = 232; + const tickChannels = []; + for (let i = 0; i < totalNonConcurrent; i += 1) { + let bestChannel = null; + let bestDeficit = -Infinity; + for (const ch of channelOrder) { + if (emitted[ch] >= targets[ch]) continue; + const expected = ((i + 1) * targets[ch]) / totalNonConcurrent; + const deficit = expected - emitted[ch]; + if (deficit > bestDeficit) { + bestDeficit = deficit; + bestChannel = ch; + } + } + emitted[bestChannel] += 1; + tickChannels.push(bestChannel); + } + + const steps = []; + let rpcCounter = 0; + let nonConcurrentIdx = 0; + let sessionReadSeq = 0; + let msgReadSeq = 0; + let rawJsonBytes = 0; + const channelCounts = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + + function makeRpcRead(channel, forcePrimary = false, forceSession = null) { + rpcCounter += 1; + channelCounts[channel] += 1; + const id = `rpc-${String(rpcCounter).padStart(4, '0')}`; + let argsKey; + let groundTruthValue; + + if (channel === 'local-db:sessions:list') { + sessionReadSeq += 1; + mutateSessions(false); + const isPinned = !forcePrimary && sessionReadSeq % 5 === 0; + const scope = isPinned ? 'pinned' : 'all'; + argsKey = JSON.stringify({ scope, limit: isPinned ? 40 : 160 }); + groundTruthValue = snapshotSessions(scope); + } else if (channel === 'local-db:messages:view') { + msgReadSeq += 1; + const useA = forceSession !== null ? forceSession === 'A' : (msgReadSeq % 2 === 1); + const hist = useA ? histA : histB; + mutateHistory(hist, 1); + const isPaginated = !forcePrimary && msgReadSeq >= 10 && msgReadSeq % 8 === 2 && hist.items.length > 35; + if (isPaginated) { + const beforeIndex = Math.min(hist.items.length - 5, 30 + (msgReadSeq % 3) * 10); + const beforeKey = hist.items[beforeIndex].key; + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, before: beforeKey, limit: 28 }); + groundTruthValue = snapshotHistory(hist, beforeIndex); + } else { + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, limit: 140 }); + groundTruthValue = snapshotHistory(hist, null); + } + } else if (channel === 'maker:provider:list') { + mutateProviders(); + argsKey = JSON.stringify({ includeModels: true, includeQuotas: true }); + groundTruthValue = cloneJson(providerCatalog); + } else if (channel === 'maker:schedule:list-sidebar-index-runs') { + mutateSchedules(); + argsKey = JSON.stringify({ limit: 40, recentRuns: 6 }); + groundTruthValue = cloneJson({ + indexVersion: scheduleIndex.indexVersion, + updatedAt: scheduleIndex.updatedAt, + totalJobs: scheduleIndex.totalJobs, + jobs: scheduleIndex.jobs.map(({ runSeq: _r, ...rest }) => rest), + }); + } else { + throw new Error(`Unknown channel: ${channel}`); + } + + rawJsonBytes += Buffer.byteLength(JSON.stringify(groundTruthValue), 'utf8'); + return { id, channel, argsKey, groundTruthValue }; + } + + let reconnectNum = 0; + let evictNum = 0; + + for (let tick = 0; tick < 236; tick += 1) { + if (coldReconnectSet.has(tick)) { + reconnectNum += 1; + mutateSessions(false); + mutateHistory(histA, rng.int(2, 4)); + mutateHistory(histB, rng.int(2, 3)); + mutateProviders(); + mutateSchedules(); + steps.push({ + type: 'cold_reconnect', + label: `mobile-cold-reconnect-${reconnectNum}`, + }); + } + if (hostEvictSet.has(tick)) { + evictNum += 1; + mutateSessions(false); + mutateHistory(histA, 1); + steps.push({ + type: 'host_evict', + label: `host-volatile-evict-${evictNum}`, + }); + } + + if (concurrentByTick.has(tick)) { + const ch = concurrentByTick.get(tick); + const forcedSess = ch === 'local-db:messages:view' ? 'A' : null; + const r1 = makeRpcRead(ch, true, forcedSess); + const r2 = makeRpcRead(ch, true, forcedSess); + steps.push({ + type: 'concurrent_rpc', + reads: [r1, r2], + }); + } else { + const ch = tickChannels[nonConcurrentIdx]; + nonConcurrentIdx += 1; + steps.push({ + type: 'rpc', + ...makeRpcRead(ch, false, null), + }); + } + } + + return { + seed, + meta: { + totalRpcs: rpcCounter, + channelCounts, + coldReconnectCount: reconnectNum, + hostEvictCount: evictNum, + concurrentPairCount: scheduleProfile.concurrentSpecs.length, + bulkStormCount, + finalHistoryLengthA: histA.items.length, + finalHistoryLengthB: histB.items.length, + rawJsonBytes, + }, + steps, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v1/reference/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/reference/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v1/reference/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v1/reference/package.json b/questions/opt-device-link-delta-sync/v1/reference/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v1/reference/src/sync-protocol.mjs new file mode 100644 index 0000000..a2e4637 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/src/sync-protocol.mjs @@ -0,0 +1,796 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Reference human optimization: + * - Cross-channel keyed recursive field-level JSON patch (handles arbitrary nesting, + * object key additions/deletions/edits, keyed record arrays matched by id/key with + * per-record field patches, and revisionSuffix normalization). + * - Multi-base snapshot ring on Host (up to maxBaseSnapshotsPerKey = 8) so concurrent + * in-flight stale-base reads stay incremental. + * - Eliminates MAX_DELTA_RATIO = 0.5 abort cliff and MAX_UNVERIFIED_DELTAS = 8 reset cliff. + * - Compact 8-byte (16-hex) cold-cache digests for messages:view bodies & keyed rows + * persisted across mobile cold reconnects. + * - Raw DEFLATE framing (`deflateRawSync`). + * + * Intentionally does NOT implement: + * - String append / prefix-suffix / line-delta ops (streaming appends still replace the text field). + * - Binary / varint / key-interning patch encoding (uses JSON patch objects). + * - Base-seeded preset-dictionary DEFLATE (`{ dictionary: baseBuf }`). + * - Compact Merkle prefix hashes / Golomb-coded sets / Bloom + 2-RTT cold reconciliation. + */ + +const FLAG_RAW = 0; +const FLAG_DEFLATE = 1; +const DELETE_SENTINEL = { $d: 1 }; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function hash16(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 12); +} + +function packFrame(obj) { + const raw = Buffer.from(JSON.stringify(obj), 'utf8'); + if (raw.byteLength >= 96) { + const compressed = zlib.deflateRawSync(raw, { level: 9 }); + if (compressed.byteLength + 1 < raw.byteLength) { + const out = new Uint8Array(compressed.byteLength + 1); + out[0] = FLAG_DEFLATE; + out.set(compressed, 1); + return out; + } + } + const out = new Uint8Array(raw.byteLength + 1); + out[0] = FLAG_RAW; + out.set(raw, 1); + return out; +} + +function unpackFrame(bytes) { + const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const body = buf.subarray(1); + const raw = buf[0] === FLAG_DEFLATE ? zlib.inflateRawSync(body) : body; + return JSON.parse(raw.toString('utf8')); +} + +// --- revisionSuffix normalization for history pages (like historyViewDelta.ts) --- +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function normalizePageForDiff(value) { + if ( + !isPlainObject(value) + || typeof value.revisionSuffix !== 'string' + || !value.revisionSuffix + || !Array.isArray(value.items) + || !allWorkRevisionsEndWith(value.items, value.revisionSuffix) + ) { + return { normalized: value, suffixed: false }; + } + const suffix = value.revisionSuffix; + const items = value.items.map((item) => + swapHistoryItem(item, (rev) => rev.slice(0, -suffix.length)), + ); + return { normalized: { ...value, items }, suffixed: true }; +} + +function denormalizePageAfterApply(value, suffixed) { + if (!suffixed || !isPlainObject(value) || typeof value.revisionSuffix !== 'string' || !value.revisionSuffix || !Array.isArray(value.items)) { + return value; + } + const suffix = value.revisionSuffix; + const items = value.items.map((item) => + swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)), + ); + return { ...value, items }; +} + +// --- Recursive keyed JSON patch --- +function detectArrayKeyField(arr) { + if (!Array.isArray(arr) || arr.length === 0) return null; + for (const candidate of ['id', 'key', 'runId']) { + const seen = new Set(); + let ok = true; + for (let i = 0; i < arr.length; i += 1) { + const el = arr[i]; + if (!isPlainObject(el) || typeof el[candidate] !== 'string' || el[candidate].length === 0 || seen.has(el[candidate])) { + ok = false; + break; + } + seen.add(el[candidate]); + } + if (ok) return candidate; + } + return null; +} + +function deepEqual(a, b) { + if (Object.is(a, b)) return true; + if (typeof a !== typeof b || a === null || b === null) return false; + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let i = 0; i < a.length; i += 1) { + if (!deepEqual(a[i], b[i])) return false; + } + return true; + } + if (Array.isArray(b)) return false; + if (typeof a === 'object') { + const ka = Object.keys(a); + const kb = Object.keys(b); + if (ka.length !== kb.length) return false; + for (let i = 0; i < ka.length; i += 1) { + const k = ka[i]; + if (!Object.prototype.hasOwnProperty.call(b, k)) return false; + if (!deepEqual(a[k], b[k])) return false; + } + return true; + } + return false; +} + +/** + * Patch representation: + * - undefined: unchanged + * - { s: value }: full replacement + * - { o: [[key, childPatch | DELETE_SENTINEL], ...] }: object field patch (safe for prototype keys!) + * - { k: ops }: keyed/indexed array patch where each op is: + * - integer `idx` -> reuse base[idx] + * - [startIdx, count] -> reuse base[startIdx .. startIdx+count-1] + * - [idx, patch, 1] -> apply recursive patch to base[idx] + * - { v: literal } -> new literal element + */ +function diffValue(base, next) { + if (Object.is(base, next)) return undefined; + if (base === null || next === null || typeof base !== 'object' || typeof next !== 'object') { + return { s: next }; + } + if (Array.isArray(base) !== Array.isArray(next)) { + return { s: next }; + } + + if (Array.isArray(base)) { + if (deepEqual(base, next)) return undefined; + if (base.length === 0 || next.length === 0) return { s: next }; + + const keyField = detectArrayKeyField(base); + const nextKeyField = detectArrayKeyField(next); + if (keyField && keyField === nextKeyField) { + const baseByKey = new Map(); + for (let i = 0; i < base.length; i += 1) { + baseByKey.set(base[i][keyField], i); + } + const ops = []; + let runStart = -1; + let runLen = 0; + const flushRun = () => { + if (runLen === 1) ops.push(runStart); + else if (runLen > 1) ops.push([runStart, runLen]); + runStart = -1; + runLen = 0; + }; + let matchedAny = false; + for (let i = 0; i < next.length; i += 1) { + const el = next[i]; + const bi = baseByKey.get(el[keyField]); + if (bi === undefined) { + flushRun(); + ops.push({ v: el }); + } else { + matchedAny = true; + const childPatch = diffValue(base[bi], el); + if (childPatch === undefined) { + if (runLen > 0 && bi === runStart + runLen) { + runLen += 1; + } else { + flushRun(); + runStart = bi; + runLen = 1; + } + } else { + flushRun(); + ops.push([bi, childPatch, 1]); + } + } + } + flushRun(); + return matchedAny ? { k: ops } : { s: next }; + } + + // Unkeyed array: match identical elements by JSON text + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + const ops = []; + let reused = 0; + for (let i = 0; i < next.length; i += 1) { + const idx = byText.get(JSON.stringify(next[i])); + if (idx !== undefined) { + reused += 1; + ops.push(idx); + } else { + ops.push({ v: next[i] }); + } + } + return reused > 0 ? { k: ops } : { s: next }; + } + + // Plain object diff using entries array so keys like "constructor"/"toString" are 100% safe + const entries = []; + const nextKeys = Object.keys(next); + const baseKeys = Object.keys(base); + for (let i = 0; i < baseKeys.length; i += 1) { + const k = baseKeys[i]; + if (!Object.prototype.hasOwnProperty.call(next, k)) { + entries.push([k, DELETE_SENTINEL]); + } + } + for (let i = 0; i < nextKeys.length; i += 1) { + const k = nextKeys[i]; + if (!Object.prototype.hasOwnProperty.call(base, k)) { + entries.push([k, { s: next[k] }]); + } else { + const child = diffValue(base[k], next[k]); + if (child !== undefined) { + entries.push([k, child]); + } + } + } + if (entries.length === 0) return undefined; + return { o: entries }; +} + +function applyPatch(base, patch) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if ('k' in patch) { + const out = []; + for (let i = 0; i < patch.k.length; i += 1) { + const op = patch.k[i]; + if (typeof op === 'number') { + out.push(base[op]); + } else if (Array.isArray(op)) { + if (op.length === 2) { + for (let j = op[0]; j < op[0] + op[1]; j += 1) out.push(base[j]); + } else { + out.push(applyPatch(base[op[0]], op[1])); + } + } else { + out.push(op.v); + } + } + return out; + } + if ('o' in patch) { + const out = {}; + const deletes = new Set(); + const updates = new Map(); + for (let i = 0; i < patch.o.length; i += 1) { + const [k, p] = patch.o[i]; + if (isPlainObject(p) && p.$d === 1) deletes.add(k); + else updates.set(k, p); + } + for (const k of Object.keys(base)) { + if (deletes.has(k)) continue; + if (updates.has(k)) { + out[k] = applyPatch(base[k], updates.get(k)); + updates.delete(k); + } else { + out[k] = base[k]; + } + } + for (const [k, p] of updates.entries()) { + out[k] = applyPatch(undefined, p); + } + return out; + } + throw new Error('Invalid reference patch node'); +} + +// --- Cold-cache reusable item extraction & substitution (8-byte / 16-hex digests) --- +function extractColdItems(channel, value) { + const out = []; + if (!isPlainObject(value)) return out; + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const suffix = typeof value.revisionSuffix === 'string' ? value.revisionSuffix : ''; + for (const item of value.items) { + if (!isPlainObject(item) || typeof item.key !== 'string') continue; + const stripped = suffix ? swapHistoryItem(item, (r) => (typeof r === 'string' && r.endsWith(suffix) ? r.slice(0, -suffix.length) : r)) : item; + const json = JSON.stringify(stripped); + out.push({ scope: `msg:${value.sessionId || ''}`, id: item.key, hash: hash16(json), json }); + } + } else if (channel === 'local-db:sessions:list' && Array.isArray(value.sessions)) { + for (const row of value.sessions) { + if (isPlainObject(row) && typeof row.id === 'string') { + const json = JSON.stringify(row); + out.push({ scope: 'sess', id: row.id, hash: hash16(json), json }); + } + } + } else if (channel === 'maker:provider:list' && Array.isArray(value.providers)) { + for (const p of value.providers) { + if (isPlainObject(p) && typeof p.id === 'string') { + const json = JSON.stringify(p); + out.push({ scope: 'prov', id: p.id, hash: hash16(json), json }); + if (Array.isArray(p.models)) { + const mj = JSON.stringify(p.models); + out.push({ scope: 'prov', id: `${p.id}#models`, hash: hash16(mj), json: mj }); + } + } + } + } else if (channel === 'maker:schedule:list-sidebar-index-runs' && Array.isArray(value.jobs)) { + for (const j of value.jobs) { + if (isPlainObject(j) && typeof j.id === 'string') { + const json = JSON.stringify(j); + out.push({ scope: 'sched', id: j.id, hash: hash16(json), json }); + } + } + } + return out; +} + +function coldScopeFor(channel, argsKey) { + if (channel === 'local-db:messages:view') { + try { + const parsed = JSON.parse(argsKey); + return `msg:${parsed?.sessionId || ''}`; + } catch { + return 'msg:'; + } + } + if (channel === 'local-db:sessions:list') return 'sess'; + if (channel === 'maker:provider:list') return 'prov'; + if (channel === 'maker:schedule:list-sidebar-index-runs') return 'sched'; + return null; +} + +function substituteColdKnown(channel, value, knownPairs) { + if (!isPlainObject(value) || !Array.isArray(knownPairs) || knownPairs.length === 0) return { value, refs: null }; + // Map id -> { hash, cIdx } where cIdx is the integer index in client's knownPairs array + const knownMap = new Map(); + for (let i = 0; i < knownPairs.length; i += 1) { + const pair = knownPairs[i]; + if (Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string') { + knownMap.set(pair[0], { hash: pair[1], cIdx: i }); + } + } + const refs = []; + + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const suffix = typeof value.revisionSuffix === 'string' && allWorkRevisionsEndWith(value.items, value.revisionSuffix) + ? value.revisionSuffix + : ''; + const items = value.items.map((item, idx) => { + if (isPlainObject(item) && typeof item.key === 'string') { + const hit = knownMap.get(item.key); + if (hit) { + const stripped = suffix ? swapHistoryItem(item, (r) => r.slice(0, -suffix.length)) : item; + if (hash16(JSON.stringify(stripped)) === hit.hash) { + refs.push([idx, hit.cIdx]); + return null; + } + } + } + return item; + }); + return refs.length > 0 ? { value: { ...value, items }, refs, suffix } : { value, refs: null }; + } + + const field = + channel === 'local-db:sessions:list' ? 'sessions' + : channel === 'maker:provider:list' ? 'providers' + : channel === 'maker:schedule:list-sidebar-index-runs' ? 'jobs' + : null; + if (field && Array.isArray(value[field])) { + const modelRefs = []; + const nextArr = value[field].map((row, idx) => { + if (isPlainObject(row) && typeof row.id === 'string') { + const hit = knownMap.get(row.id); + if (hit && hash16(JSON.stringify(row)) === hit.hash) { + refs.push([idx, hit.cIdx]); + return null; + } + if (field === 'providers' && Array.isArray(row.models)) { + const mHit = knownMap.get(`${row.id}#models`); + if (mHit && hash16(JSON.stringify(row.models)) === mHit.hash) { + modelRefs.push([idx, mHit.cIdx]); + return { ...row, models: null }; + } + } + } + return row; + }); + return (refs.length > 0 || modelRefs.length > 0) + ? { value: { ...value, [field]: nextArr }, refs, modelRefs, suffix: '' } + : { value, refs: null }; + } + return { value, refs: null }; +} + +function restoreColdKnown(channel, value, refs, modelRefs, suffix, coldList) { + if (!isPlainObject(value) || !Array.isArray(refs)) return value; + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const items = value.items.slice(); + for (let i = 0; i < refs.length; i += 1) { + const [idx, cIdx] = refs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache item index ${cIdx}`); + const parsed = JSON.parse(stored.json); + items[idx] = suffix ? swapHistoryItem(parsed, (r) => (typeof r === 'string' ? r + suffix : r)) : parsed; + } + return { ...value, items }; + } + + const field = + channel === 'local-db:sessions:list' ? 'sessions' + : channel === 'maker:provider:list' ? 'providers' + : channel === 'maker:schedule:list-sidebar-index-runs' ? 'jobs' + : null; + if (field && Array.isArray(value[field])) { + const arr = value[field].slice(); + for (let i = 0; i < refs.length; i += 1) { + const [idx, cIdx] = refs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache row index ${cIdx}`); + arr[idx] = JSON.parse(stored.json); + } + if (Array.isArray(modelRefs)) { + for (let i = 0; i < modelRefs.length; i += 1) { + const [idx, cIdx] = modelRefs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache models index ${cIdx}`); + arr[idx] = { ...arr[idx], models: JSON.parse(stored.json) }; + } + } + return { ...value, [field]: arr }; + } + return value; +} + +export function createHostSyncEndpoint(options = {}) { + const maxBaseSnapshotsPerKey = options.maxBaseSnapshotsPerKey ?? DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY; + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // key -> Array<{ id, normalized, bytes }> + const rings = new Map(); + let totalBytes = 0; + + function evictVolatileBases() { + rings.clear(); + totalBytes = 0; + } + + function evictOneOldest() { + for (const [k, ring] of rings.entries()) { + const removed = ring.shift(); + if (removed) totalBytes -= removed.bytes; + if (ring.length === 0) rings.delete(k); + return; + } + } + + function rememberSnapshot(key, id, normalized, bytes, suffixed) { + if (bytes > maxCacheBytes / 2) return; + let ring = rings.get(key); + if (!ring) { + ring = []; + rings.set(key, ring); + } else { + // Refresh LRU order of the key + rings.delete(key); + rings.set(key, ring); + } + const existingIdx = ring.findIndex((s) => s.id === id); + if (existingIdx >= 0) { + const [existing] = ring.splice(existingIdx, 1); + ring.push(existing); + return; + } + ring.push({ id, normalized, bytes, suffixed }); + totalBytes += bytes; + while (ring.length > maxBaseSnapshotsPerKey) { + const dropped = ring.shift(); + totalBytes -= dropped.bytes; + } + while (totalBytes > maxCacheBytes && rings.size > 0) { + evictOneOldest(); + } + } + + function findBase(key, baseId) { + const ring = rings.get(key); + if (!ring) return undefined; + for (let i = ring.length - 1; i >= 0; i -= 1) { + if (ring[i].id === baseId) return ring[i]; + } + return undefined; + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round = 0 }) { + const req = unpackFrame(requestBytes); + const key = `${channel}\u0000${argsKey}`; + const { normalized, suffixed } = normalizePageForDiff(groundTruthValue); + const normJson = JSON.stringify(normalized); + const nextId = hash16(`${suffixed ? '1' : '0'}:${normJson}`); + + const baseSnap = req.base ? findBase(key, req.base) : undefined; + rememberSnapshot(key, nextId, normalized, normJson.length, suffixed); + + if (req.base && req.base === nextId) { + return packFrame({ t: 'same', id: nextId, sx: suffixed ? 1 : 0 }); + } + + if (baseSnap && baseSnap.suffixed === suffixed) { + const patch = diffValue(baseSnap.normalized, normalized); + if (patch === undefined) { + return packFrame({ t: 'same', id: nextId, sx: suffixed ? 1 : 0 }); + } + const deltaFrame = packFrame({ t: 'delta', id: nextId, base: baseSnap.id, p: patch, sx: suffixed ? 1 : 0 }); + const fullFrame = packFrame({ t: 'full', id: nextId, v: groundTruthValue, sx: suffixed ? 1 : 0 }); + return deltaFrame.byteLength <= fullFrame.byteLength ? deltaFrame : fullFrame; + } + + // If client advertised a warm base that was evicted on the Host, request a Round-1 cold-digest retry. + if (req.base && req.hasCold && round < PROTOCOL_MAX_ROUNDS - 1 && normJson.length >= 2048) { + return packFrame({ t: 'miss' }); + } + + // Cold path: substitute any items matching client's compact digest manifest + if (Array.isArray(req.cold) && req.cold.length > 0) { + const { value: subVal, refs, modelRefs, suffix } = substituteColdKnown(channel, groundTruthValue, req.cold); + if (refs) { + return packFrame({ + t: 'cold', + id: nextId, + v: subVal, + r: refs, + ...(modelRefs && modelRefs.length > 0 ? { mr: modelRefs } : {}), + sf: suffix, + sx: suffixed ? 1 : 0, + }); + } + } + + return packFrame({ t: 'full', id: nextId, v: groundTruthValue, sx: suffixed ? 1 : 0 }); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + + // Volatile state: key -> { id, normalized, bytes } + const cache = new Map(); + let cacheBytes = 0; + const inflight = new Map(); + + // Persistent cold-cache store: `${scope}\u0000${id}` -> { scope, id, hash, json } + const persistent = new Map(); + let persistentRawBytes = 0; + + function rememberPersistent(scope, id, hash, json) { + const k = `${scope}\u0000${id}`; + const prev = persistent.get(k); + if (prev) { + persistentRawBytes -= prev.json.length; + persistent.delete(k); + } + if (json.length > maxPersistentBytes / 2) return; + persistent.set(k, { scope, id, hash, json }); + persistentRawBytes += json.length; + // Cap raw stored JSON at ~4 MiB (compresses well under 2 MiB; enforced tightly on export) + while (persistent.size > 1200 || persistentRawBytes > maxPersistentBytes * 2) { + const oldestKey = persistent.keys().next().value; + const oldest = persistent.get(oldestKey); + persistentRawBytes -= oldest.json.length; + persistent.delete(oldestKey); + } + } + + function loadPersistentState(bytes) { + persistent.clear(); + persistentRawBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const rows = JSON.parse(zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8')); + if (!Array.isArray(rows)) return; + for (const r of rows) { + if (r && typeof r.scope === 'string' && typeof r.id === 'string' && typeof r.hash === 'string' && typeof r.json === 'string') { + rememberPersistent(r.scope, r.id, r.hash, r.json); + } + } + } catch { + // ignore corrupt blob + } + } + + function exportPersistentState() { + const rows = Array.from(persistent.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8'), { level: 6 }); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.splice(0, Math.max(1, Math.floor(rows.length * 0.15))); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8'), { level: 6 }); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snap = exportPersistentState(); + cache.clear(); + cacheBytes = 0; + inflight.clear(); + loadPersistentState(snap); + } + + function rememberCache(key, id, normalized, bytes) { + const prev = cache.get(key); + if (prev) { + cacheBytes -= prev.bytes; + cache.delete(key); + } + if (bytes > maxCacheBytes / 2) return; + cache.set(key, { id, normalized, bytes }); + cacheBytes += bytes; + while (cache.size > 32 || cacheBytes > maxCacheBytes) { + const oldestKey = cache.keys().next().value; + const oldest = cache.get(oldestKey); + cacheBytes -= oldest.bytes; + cache.delete(oldestKey); + } + } + + function recordPersistentFromValue(channel, value) { + const items = extractColdItems(channel, value); + for (let i = 0; i < items.length; i += 1) { + const it = items[i]; + rememberPersistent(it.scope, it.id, it.hash, it.json); + } + } + + if (options.persistentState) { + loadPersistentState(options.persistentState); + } + + function buildColdManifest(channel, argsKey) { + const scope = coldScopeFor(channel, argsKey); + const coldList = []; + const coldPairs = []; + let pinnedOnly = false; + if (channel === 'local-db:sessions:list') { + try { pinnedOnly = JSON.parse(argsKey)?.scope === 'pinned'; } catch { /* ignore */ } + } + if (scope) { + for (const entry of persistent.values()) { + if (entry.scope !== scope) continue; + if (pinnedOnly && !entry.json.includes('"pinned":true')) continue; + coldList.push(entry); + coldPairs.push([entry.id, entry.hash]); + } + } + return { coldList, coldPairs }; + } + + function beginRead({ readId, channel, argsKey }) { + const key = `${channel}\u0000${argsKey}`; + const cached = cache.get(key); + + if (cached) { + const scope = coldScopeFor(channel, argsKey); + let hasCold = false; + if (scope) { + for (const entry of persistent.values()) { + if (entry.scope === scope) { + hasCold = true; + break; + } + } + } + inflight.set(readId, { channel, argsKey, key, cached, coldList: null }); + return packFrame(hasCold ? { base: cached.id, hasCold: 1 } : { base: cached.id }); + } + + const { coldList, coldPairs } = buildColdManifest(channel, argsKey); + inflight.set(readId, { channel, argsKey, key, cached: null, coldList }); + return packFrame(coldPairs.length > 0 ? { cold: coldPairs } : {}); + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + const resp = unpackFrame(responseBytes); + + if (resp.t === 'miss') { + const { coldList, coldPairs } = buildColdManifest(state.channel, state.argsKey); + state.coldList = coldList; + return { done: false, nextRequestBytes: packFrame(coldPairs.length > 0 ? { cold: coldPairs } : {}) }; + } + + inflight.delete(readId); + + let finalValue; + let normalized; + const suffixed = resp.sx === 1; + + if (resp.t === 'same') { + if (!state.cached) throw new Error('Unexpected same without cached base'); + normalized = JSON.parse(JSON.stringify(state.cached.normalized)); + finalValue = denormalizePageAfterApply(normalized, suffixed); + } else if (resp.t === 'delta') { + if (!state.cached || state.cached.id !== resp.base) { + throw new Error(`Delta base mismatch: expected ${state.cached?.id}, got ${resp.base}`); + } + const baseClone = JSON.parse(JSON.stringify(state.cached.normalized)); + normalized = applyPatch(baseClone, resp.p); + finalValue = denormalizePageAfterApply(normalized, suffixed); + } else if (resp.t === 'cold') { + finalValue = restoreColdKnown(state.channel, resp.v, resp.r, resp.mr, resp.sf || '', state.coldList); + normalized = normalizePageForDiff(finalValue).normalized; + } else if (resp.t === 'full') { + finalValue = resp.v; + normalized = normalizePageForDiff(finalValue).normalized; + } else { + throw new Error(`Unknown response kind: ${resp.t}`); + } + + const normJson = JSON.stringify(normalized); + rememberCache(state.key, resp.id, normalized, normJson.length); + recordPersistentFromValue(state.channel, finalValue); + return { done: true, value: finalValue }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v1/reference/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..3795c0f --- /dev/null +++ b/questions/opt-device-link-delta-sync/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { generateTrace } from '../lib/trace-generator.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated trace parity check on public seed', async () => { + const fullTrace = generateTrace({ seed: 20260501 }); + // Run the first 60 steps (covers all 4 channels, a concurrent pair, cold reconnect, and host evict) + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-device-link-delta-sync/v2/author/editable.json b/questions/opt-device-link-delta-sync/v2/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-device-link-delta-sync/v2/author/evaluator.mjs b/questions/opt-device-link-delta-sync/v2/author/evaluator.mjs new file mode 100644 index 0000000..c719c68 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/evaluator.mjs @@ -0,0 +1,704 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { loadTrace } from '../candidate/lib/trace-loader.mjs'; +import { generateHeldoutTrace as generateStressTrace } from './stress-trace.mjs'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +// Submission code runs in a child process under Node's permission model: `--permission` since +// Node 22.13 / 23.5, `--experimental-permission` on Node 20 before that, absent before Node 20. +// Without it the submission cannot be isolated, so the run is reported as an environment +// problem instead of being scored. +const PERMISSION_FLAG = ['--permission', '--experimental-permission'].find( + (flag) => spawnSync(process.execPath, [flag, '-e', ''], { stdio: 'ignore', timeout: 10_000 }).status === 0, +); +if (!PERMISSION_FLAG) { + trusted.emit({ + status: 'environment_invalid', + reason: `grading needs Node.js >= 20 for the permission model (found ${process.version})`, + }); + process.exit(0); +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const MAX_ROUNDS = 4; +const MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +const MAX_TRACE_RUNTIME_MS = 20000; +const PUBLIC_TRACE_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../candidate/corpus/public-trace.json.br'); +const HELDOUT_TRACE_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'heldout/heldout-trace.json.br'); + +const [rawSubDir] = process.argv.slice(2); +if (!rawSubDir) { + console.error('Usage: node evaluator.mjs '); + process.exit(2); +} + +const subDir = await fs.realpath(rawSubDir); +const authorDir = await fs.realpath(HERE); + +const FORBIDDEN_MODULES = [ + 'fs', 'fs/promises', 'net', 'http', 'https', 'http2', 'dgram', 'tls', 'dns', + 'child_process', 'worker_threads', 'cluster', 'inspector', 'inspector/promises', + 'vm', 'os', 'v8', 'module', 'perf_hooks', +]; + +async function auditSubmissionSource(dir) { + const stack = [dir]; + const forbiddenImportRe = new RegExp( + `(?:from\\s*|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:node:)?(${FORBIDDEN_MODULES.map((m) => m.replace('/', '\\/')).join('|')})['"]`, + ); + const forbiddenRuntimeRe = /\bprocess\s*\.\s*(?:getBuiltinModule|binding|dlopen)\b/; + + while (stack.length > 0) { + const cur = stack.pop(); + const entries = await fs.readdir(cur, { withFileTypes: true }); + for (const entry of entries) { + const full = path.join(cur, entry.name); + const st = await fs.lstat(full); + if (st.isSymbolicLink()) { + throw new Error(`Symlink forbidden in src/: ${entry.name}`); + } + if (st.isDirectory()) { + stack.push(full); + continue; + } + if (!st.isFile()) { + throw new Error(`Non-regular file forbidden in src/: ${entry.name}`); + } + if (entry.name.endsWith('.node')) { + throw new Error(`Native addon forbidden in src/: ${entry.name}`); + } + if (/\.(mjs|js|cjs)$/.test(entry.name)) { + const text = await fs.readFile(full, 'utf8'); + const m1 = forbiddenImportRe.exec(text); + if (m1) { + throw new Error(`Forbidden side-channel module import '${m1[1]}' in ${entry.name}`); + } + const m2 = forbiddenRuntimeRe.exec(text); + if (m2) { + throw new Error(`Forbidden process escape '${m2[0]}' in ${entry.name}`); + } + } + } + } +} + +class SandboxedWorker { + constructor(scriptPath, args, sandboxDir) { + const nodeFlags = [PERMISSION_FLAG, `--allow-fs-read=${subDir}`, `--allow-fs-read=${scriptPath}`]; + this.child = spawn(process.execPath, [...nodeFlags, scriptPath, ...args], { + cwd: sandboxDir, + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: sandboxDir, + TMPDIR: sandboxDir, + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker output: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) throw new Error(res.error || `Worker error: ${this.stderr}`); + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { /* ignore */ } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +async function runSandboxedTrace(trace, { verifyImmutable = false } = {}) { + const hostTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-sync-host-')); + const clientTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-sync-client-')); + const hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }; + const clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }; + + let hostWorker = null; + let clientWorker = null; + const hostPids = new Set(); + const clientPids = new Set(); + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new SandboxedWorker( + path.join(authorDir, 'worker-host.mjs'), + [subDir, JSON.stringify(hostOptions)], + hostTmp, + ); + const ping = await hostWorker.call({ op: 'ping' }); + hostPids.add(ping.pid); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new SandboxedWorker( + path.join(authorDir, 'worker-client.mjs'), + [subDir, JSON.stringify(clientOptions)], + clientTmp, + ); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + clientPids.add(init.pid); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + perChannel: {}, + elapsedMs: 0, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + verifyImmutable, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + const t0 = trusted.now(); + try { + await spawnHost(); + await spawnClient(null); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > MAX_PERSISTENT_BYTES) { + throw new Error(`exportPersistentState exceeded 2 MiB (${exported.byteLength} > ${MAX_PERSISTENT_BYTES})`); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'client_restart') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > MAX_PERSISTENT_BYTES) { + throw new Error(`exportPersistentState exceeded 2 MiB (${exported.byteLength} > ${MAX_PERSISTENT_BYTES})`); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + } else if (step.type === 'host_evict') { + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + verifyImmutable, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + verifyImmutable, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + verifyImmutable, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown step type: ${step.type}`); + } + } + + stats.elapsedMs = Math.round(trusted.now() - t0); + // Confirm zero PID overlap between host and client processes + for (const p of hostPids) { + assert.ok(!clientPids.has(p), 'Host and Client shared a PID'); + } + return { stats, hostSpawnCount: hostPids.size, clientSpawnCount: clientPids.size }; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + await Promise.all([ + fs.rm(hostTmp, { recursive: true, force: true }), + fs.rm(clientTmp, { recursive: true, force: true }), + ]); + } +} + +function buildAdversarialEdgeTrace() { + const largeStrBase = 'A'.repeat(20_000) + '日本語テスト🚀'; + const largeStrNext = largeStrBase + 'APPENDED_STREAM_CHUNK_' + '中'.repeat(600); + const payloads = [ + { ch: 'edge:prim', args: '{}', val: null }, + { ch: 'edge:prim', args: '{}', val: true }, + { ch: 'edge:prim', args: '{}', val: false }, + { ch: 'edge:prim', args: '{}', val: 0 }, + { ch: 'edge:prim', args: '{}', val: -123456.789 }, + { ch: 'edge:prim', args: '{}', val: '' }, + { ch: 'edge:prim', args: '{}', val: 'Hello 🌍 你好世界\n\t\r"quotes"\\backslash' }, + { ch: 'edge:prim', args: '{}', val: [] }, + { ch: 'edge:prim', args: '{}', val: {} }, + { + ch: 'edge:proto-keys', + args: '{"k":1}', + val: { + constructor: 'ctor-val-1', + toString: 'toString-val-1', + valueOf: 42, + hasOwnProperty: { a: [1, 2, null], b: {} }, + $ref: 'literal-dollar-ref', + $d: 1, + nested: { emptyArr: [], emptyObj: {}, large: largeStrBase }, + list: [ + { id: 'k1', $ref: 'keep-me', val: 1, tags: ['a', 'b'] }, + { id: 'k2', val: null, tags: [] }, + ], + }, + }, + { + ch: 'edge:proto-keys', + args: '{"k":1}', + val: { + constructor: 'ctor-val-2', + // toString deleted + valueOf: [false, true, 0], + hasOwnProperty: { a: [1, 3], c: 'added' }, + $ref: 'literal-dollar-ref-2', + nested: { emptyArr: [null], emptyObj: { x: '' }, large: largeStrNext }, + list: [ + { id: 'k2', val: { becameObj: true }, tags: ['new'] }, + { id: 'k1', $ref: 'keep-me', val: 1, tags: ['a', 'b', 'c'] }, + { id: 'k3', val: 'emoji-🎉-end', tags: [] }, + ], + }, + }, + // Adversarial revisionSuffix mismatch inside messages:view shape + { + ch: 'local-db:messages:view', + args: '{"sessionId":"adv-s1","limit":10}', + val: { + sessionId: 'adv-s1', + revisionSuffix: ':r9', + items: [ + { key: 'work:1', type: 'work', summary: { revision: 'no-matching-suffix', title: 'raw' } }, + { key: 'msg:1', type: 'messages', messages: [{ id: 'm1', role: 'assistant', content: { text: largeStrBase }, remoteBodyVersion: 'not-a-sha' }] }, + ], + }, + }, + { + ch: 'local-db:messages:view', + args: '{"sessionId":"adv-s1","limit":10}', + val: { + sessionId: 'adv-s1', + revisionSuffix: ':r10', + items: [ + { key: 'work:1', type: 'work', summary: { revision: 'no-matching-suffix', title: 'raw-updated' } }, + { key: 'msg:1', type: 'messages', messages: [{ id: 'm1', role: 'assistant', content: { text: largeStrNext }, remoteBodyVersion: 'not-a-sha' }] }, + ], + }, + }, + ]; + + const steps = payloads.map((p, idx) => ({ + type: 'rpc', + id: `edge-${idx + 1}`, + channel: p.ch, + argsKey: p.args, + groundTruthValue: p.val, + })); + // Add a cold reconnect and re-read to verify edge shapes survive reconnect + steps.push({ type: 'cold_reconnect', label: 'edge-cold-reconnect' }); + steps.push({ + type: 'rpc', + id: 'edge-post-cold', + channel: 'edge:proto-keys', + argsKey: '{"k":1}', + groundTruthValue: payloads[10].val, + }); + return { steps }; +} + +async function checkInProcessDriftAndExports() { + const mod = await import(pathToFileURL(path.join(subDir, 'sync-protocol.mjs')).href); + assert.equal(mod.PROTOCOL_MAX_ROUNDS, 4); + assert.equal(typeof mod.createHostSyncEndpoint, 'function'); + assert.equal(typeof mod.createClientSyncEndpoint, 'function'); + + const host = mod.createHostSyncEndpoint(); + const client = mod.createClientSyncEndpoint(); + assert.equal(typeof host.handleFrame, 'function'); + assert.equal(typeof host.evictVolatileBases, 'function'); + assert.equal(typeof client.beginRead, 'function'); + assert.equal(typeof client.receiveResponse, 'function'); + assert.equal(typeof client.exportPersistentState, 'function'); + assert.equal(typeof client.simulateColdReconnect, 'function'); + + const runOne = (readId, channel, argsKey, val) => { + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + while (true) { + assert.ok(req instanceof Uint8Array); + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue: val, round }); + assert.ok(res instanceof Uint8Array); + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean'); + if (step.done) { + assert.deepStrictEqual(step.value, val); + return; + } + round += 1; + assert.ok(round < MAX_ROUNDS); + req = step.nextRequestBytes; + } + }; + + runOne('u1', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 1 }] }); + host.evictVolatileBases(); + runOne('u2', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 2 }] }); + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + runOne('u3', 'local-db:sessions:list', '{"scope":"all"}', { sessions: [{ id: 'a', v: 3 }] }); +} + +async function checkEntropyIsolation() { + // 2048 bytes of true cryptographic randomness encoded as 4096 hex chars -> >= 2048 bytes entropy. + // Any physically isolated protocol without a side-channel MUST transmit >= 1800 wire bytes! + const randomPayload = { + nonceId: 'entropy-check-1', + hexBlob: crypto.randomBytes(2048).toString('hex'), + }; + const trace = { + steps: [ + { + type: 'rpc', + id: 'entropy-1', + channel: 'isolation:entropy', + argsKey: '{"k":"nonce"}', + groundTruthValue: randomPayload, + }, + ], + }; + const { stats } = await runSandboxedTrace(trace, { verifyImmutable: true }); + assert.ok( + stats.totalWireBytes >= 1800, + `Entropy lower-bound violation: 2048B random nonce transferred in only ${stats.totalWireBytes}B`, + ); + return stats.totalWireBytes; +} + +const errors = []; +let gate_wire_sanity = false; +let gate_process_isolation = false; +let gate_reconnect_and_drift = false; +let gate_exact_json_parity = false; + +let auditOk = false; +try { + await auditSubmissionSource(subDir); + auditOk = true; +} catch (err) { + errors.push(`audit: ${err.message}`); +} + +let exportsAndInProcOk = false; +if (auditOk) { + try { + await checkInProcessDriftAndExports(); + exportsAndInProcOk = true; + } catch (err) { + errors.push(`exports/inproc: ${err.message}`); + } +} + +let entropyBytes = 0; +let isolationOk = false; +if (auditOk) { + try { + entropyBytes = await checkEntropyIsolation(); + isolationOk = true; + } catch (err) { + errors.push(`isolation: ${err.message}`); + } +} + +let edgeOk = false; +if (auditOk) { + try { + const edgeRes = await runSandboxedTrace(buildAdversarialEdgeTrace(), { verifyImmutable: true }); + assert.ok(edgeRes.stats.maxRoundsUsed <= MAX_ROUNDS); + edgeOk = true; + } catch (err) { + errors.push(`edgeParity: ${err.message}`); + } +} + +let publicOk = false; +let publicStats = null; +if (auditOk) { + try { + const pubTrace = loadTrace(PUBLIC_TRACE_FILE); + const pubRes = await runSandboxedTrace(pubTrace, { verifyImmutable: false }); + publicStats = pubRes.stats; + assert.equal(pubRes.stats.rpcCount, pubTrace.meta.totalRpcs); + assert.ok(pubRes.stats.maxRoundsUsed <= MAX_ROUNDS); + assert.ok(pubRes.stats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES); + publicOk = true; + } catch (err) { + errors.push(`publicTrace: ${err.message}`); + } +} + +// Robustness stress run (gate only, not scored): a synthetic trace with many cold reconnects, +// host volatile-base evictions, bulk row churn and concurrent stale-base reads. +let stressOk = false; +let stressHostSpawns = 0; +let stressClientSpawns = 0; +let stressMaxPersistent = 0; +if (auditOk) { + try { + const stressTrace = generateStressTrace(); + const stressRes = await runSandboxedTrace(stressTrace, { verifyImmutable: false }); + stressHostSpawns = stressRes.hostSpawnCount; + stressClientSpawns = stressRes.clientSpawnCount; + stressMaxPersistent = stressRes.stats.maxPersistentBytesSeen; + assert.equal(stressRes.stats.rpcCount, stressTrace.meta.totalRpcs); + assert.ok(stressRes.stats.maxRoundsUsed <= MAX_ROUNDS); + assert.ok(stressRes.stats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES); + stressOk = true; + } catch (err) { + errors.push(`stressTrace: ${err.message}`); + } +} + +// Scored run: the held-out real workload (different real tasks, different de-identification key). +let heldoutOk = false; +let heldoutStats = null; +let heldoutMeta = null; +if (auditOk) { + try { + const hoTrace = loadTrace(HELDOUT_TRACE_FILE); + heldoutMeta = hoTrace.meta; + const hoRes = await runSandboxedTrace(hoTrace, { verifyImmutable: false }); + heldoutStats = hoRes.stats; + assert.equal(hoRes.stats.rpcCount, hoTrace.meta.totalRpcs); + assert.ok(hoRes.stats.maxRoundsUsed <= MAX_ROUNDS); + assert.ok(hoRes.stats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES); + heldoutOk = true; + } catch (err) { + errors.push(`heldoutTrace: ${err.message}`); + } +} + +const runtimeOk = heldoutStats !== null && heldoutStats.elapsedMs <= MAX_TRACE_RUNTIME_MS; +if (heldoutStats && !runtimeOk) { + errors.push(`runtime: held-out trace took ${heldoutStats.elapsedMs}ms > ${MAX_TRACE_RUNTIME_MS}ms`); +} + +gate_wire_sanity = auditOk && exportsAndInProcOk && edgeOk && heldoutOk + && heldoutStats.maxRoundsUsed <= MAX_ROUNDS && heldoutStats.totalWireBytes > 0; +gate_process_isolation = auditOk && isolationOk && heldoutOk && stressOk + && stressHostSpawns >= 10 && stressClientSpawns >= 7; +gate_reconnect_and_drift = auditOk && exportsAndInProcOk && publicOk && heldoutOk && stressOk && runtimeOk + && heldoutStats.maxPersistentBytesSeen <= MAX_PERSISTENT_BYTES && stressMaxPersistent <= MAX_PERSISTENT_BYTES; +gate_exact_json_parity = auditOk && edgeOk && publicOk && heldoutOk; + +const total_wire_bytes = heldoutOk ? heldoutStats.totalWireBytes : 100_000_000; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_json_parity, + gate_process_isolation, + gate_reconnect_and_drift, + gate_wire_sanity, + }, + metrics: { + total_wire_bytes, + }, + details: { + errors, + entropyCheckWireBytes: entropyBytes, + publicWireBytes: publicStats?.totalWireBytes ?? null, + heldout: heldoutStats + ? { + totalWireBytes: heldoutStats.totalWireBytes, + upstreamBytes: heldoutStats.upstreamBytes, + downstreamBytes: heldoutStats.downstreamBytes, + rawJsonBytes: heldoutMeta?.rawJsonBytes ?? null, + rpcCount: heldoutStats.rpcCount, + totalRounds: heldoutStats.totalRounds, + maxRoundsUsed: heldoutStats.maxRoundsUsed, + maxPersistentBytesSeen: heldoutStats.maxPersistentBytesSeen, + elapsedMs: heldoutStats.elapsedMs, + perChannel: heldoutStats.perChannel, + } + : null, + }, +})); diff --git a/questions/opt-device-link-delta-sync/v2/author/grade.py b/questions/opt-device-link-delta-sync/v2/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-device-link-delta-sync/v2/author/grade_impl.py b/questions/opt-device-link-delta-sync/v2/author/grade_impl.py new file mode 100644 index 0000000..b70cbb8 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/grade_impl.py @@ -0,0 +1,47 @@ +"""Isolated pure-Node quantitative grader: runs correctness, isolation, drift gates + unseen held-out wire benchmark.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + src_dir = submission_root / 'src' + if not src_dir.is_dir(): + return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'} + with tempfile.TemporaryDirectory(prefix='eval-delta-sync-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(src_dir, sub_src, symlinks=True) + # Ensure ESM semantics if submission adds .js helper files inside src/ + pkg_file = sub_src / 'package.json' + if not pkg_file.exists(): + pkg_file.write_text('{"type":"module"}\n') + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-device-link-delta-sync/v2/author/heldout/heldout-trace.json.br b/questions/opt-device-link-delta-sync/v2/author/heldout/heldout-trace.json.br new file mode 100644 index 0000000..c37e660 Binary files /dev/null and b/questions/opt-device-link-delta-sync/v2/author/heldout/heldout-trace.json.br differ diff --git a/questions/opt-device-link-delta-sync/v2/author/result-channel.mjs b/questions/opt-device-link-delta-sync/v2/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-device-link-delta-sync/v2/author/stress-trace-generator.mjs b/questions/opt-device-link-delta-sync/v2/author/stress-trace-generator.mjs new file mode 100644 index 0000000..3621bc5 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/stress-trace-generator.mjs @@ -0,0 +1,936 @@ +import crypto from 'node:crypto'; + +/** + * Deterministic Mulberry32 PRNG. + */ +export function createRng(seed) { + let state = (seed >>> 0) || 1; + return { + next() { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }, + int(min, max) { + return min + Math.floor(this.next() * (max - min + 1)); + }, + pick(arr) { + return arr[Math.floor(this.next() * arr.length)]; + }, + bool(p = 0.5) { + return this.next() < p; + }, + hex(len) { + const chars = '0123456789abcdef'; + let out = ''; + for (let i = 0; i < len; i += 1) { + out += chars[Math.floor(this.next() * 16)]; + } + return out; + }, + shuffle(arr) { + const out = arr.slice(); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = Math.floor(this.next() * (i + 1)); + const tmp = out[i]; + out[i] = out[j]; + out[j] = tmp; + } + return out; + }, + }; +} + +function sha256Hex(str) { + return crypto.createHash('sha256').update(str, 'utf8').digest('hex'); +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +export const DEFAULT_CORPUS = { + idPrefix: 'pub', + devices: [ + 'dev-mac-studio-01', + 'dev-mbp-m4-02', + 'dev-linux-build-03', + 'dev-wsl-workstation-04', + ], + workingDirs: [ + '/Users/dev/workspace/cindy-core', + '/Users/dev/workspace/cindy-mobile', + '/Users/dev/workspace/cindy-relay', + '/Users/dev/workspace/eval-bank', + '/Users/dev/workspace/agent-sdk', + '/Users/dev/workspace/docs-site', + ], + subdirs: [ + 'packages/device-link/src', + 'packages/maker-shared/src', + 'apps/mobile/src/sync', + 'apps/desktop/src/main', + 'services/relay-edge/src', + 'crates/protocol/src', + 'tests/integration', + 'scripts/bench', + ], + fileStems: [ + 'invokeDelta', 'invokeTransfer', 'historyViewDelta', 'sessionMessageReuse', + 'routedClient', 'listingReadCoalescer', 'transportBacklog', 'pushTransfer', + 'nodeCompression', 'remoteAgent', 'metadataContinuity', 'setupSnapshot', + 'stallDiagnostics', 'peerRecovery', 'cacheBudget', 'streamAssembler', + 'frameCodec', 'merkleIndex', 'walCheckpoint', 'quotaTracker', + ], + symbolVerbs: [ + 'reconcile', 'compute', 'decode', 'encode', 'evict', 'normalize', 'compact', + 'verify', 'dispatch', 'coalesce', 'hydrate', 'serialize', 'inflate', 'prune', + 'merge', 'replay', 'checkpoint', 'validate', + ], + symbolNouns: [ + 'DeltaBase', 'HistoryPage', 'MessageBody', 'WireFrame', 'SnapshotRing', + 'RevisionSuffix', 'ColdManifest', 'SessionRow', 'QuotaBucket', 'RunWindow', + 'PrefixLadder', 'PatchOp', 'ChunkDigest', 'PeerCursor', 'TransferHeader', + 'KeyTable', 'StreamBuffer', 'CacheEntry', + ], + cjkTopics: [ + '跨设备弱网同步延迟', '批量行刷新触发阈值回退', '移动端冷重连摘要上行膨胀', + '流式文本追加导致整条消息重传', '工作摘要版本号后缀高频抖动', '并发读取基准淘汰错位', + '本地持久化缓存体积上限控制', '多通道结构化目录轮询冗余', '字典压缩窗口命中率下降', + '分页历史回溯与最新页缓存复用', '异步队列背压与帧边界对齐', '索引重排与键表编码开销', + '断连恢复后的冷缓存集合调和', '长日志代码块与多语言字符集校验', '任务状态栏高频更新节流', + '定时任务滑动窗口增量裁剪', + ], + enObservations: [ + 'Observed wire amplification during bulk metadata refresh across active peers', + 'Detected redundant retransmission of unchanged markdown prefixes while streaming', + 'Measured upstream handshake spike when uploading full 64-hex SHA-256 manifests', + 'Confirmed multi-snapshot ring avoids full-page fallback under pipelined reads', + 'Profiled deflate dictionary match ratio against prior synchronized base payload', + 'Validated exact JSON parity for empty containers, floats, null fields, and emoji', + 'Traced revision suffix propagation across nested work summary child nodes', + 'Benchmarked recursive keyed array diff against coarse depth-2 row replacement', + 'Audited persistent cache serialization size under mobile background termination', + 'Inspected pagination cursor overlap when scrolling older transcript segments', + 'Evaluated 2-RTT set reconciliation bandwidth on partial state divergence', + 'Checked varint length framing and key-table interning on structured provider lists', + ], + cjkActions: [ + '建议改为按主键递归比对字段,仅下发变动属性与紧凑索引序列', + '排查发现未命中易失基准时会直接回退整页快照,应结合持久化摘要跳过未变正文', + '实测在流式输出阶段采用前缀复用加尾部追加指令,可将单次下行体积压缩至原来的十分之一', + '需要同时保留最近多个已确认与在途基准,防止并发轮询携带旧标签时反复触发全量同步', + '对比普通压缩与基于旧快照预置字典的原始流压缩,重复路径和模型标识几乎不再占用字节', + '核对边界用例:空数组、空对象、中文标点、表情符号及原型同名普通键均须严格等价', + '对冷启动重连场景,采用分层前缀哈希或紧凑摘要握手可避免每次上传数十千字节清单', + '注意在 diff 前先校验所有 work 节点确实携带统一页级后缀,避免误改异常数据', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-sonnet-4-5', + 'claude-opus-4-1', + 'gpt-5.3-codex', + 'gemini-2.5-pro', + 'deepseek-r1-0528', + 'qwen3-coder-480b', + ], + tagsPool: [ + 'device-link', 'perf', 'sync', 'mobile', 'relay', 'p0', 'p1', + 'refactor', 'sqlite', 'rpc', 'telemetry', 'ci', 'security', 'ux', + ], + sessionTitles: [ + '重构 device-link 跨设备增量同步协议', + 'Fix mobile cold-reconnect history delta miss', + '优化弱网 JSON 压缩与字典复用策略', + 'Investigate provider quota sidebar polling lag', + '排查 schedule 侧栏索引高频刷新流量消耗', + 'Implement binary patch encoder for sessions list', + '修复并发 stale-base 读取回退全文问题', + 'Audit SessionMessageReuse cache eviction bounds', + '支持多轮 Merkle 集合调和协议实验', + 'Optimize SQLite WAL checkpoint during streaming', + '解决 CJK 长文本流式追加重复传输瓶颈', + 'Verify deterministic replay across macOS & Linux', + ], + toolNames: ['read_file', 'run_command', 'edit_file', 'grep_search', 'list_dir'], + workTitles: [ + 'Inspect device-link delta protocol', + 'Run unit test suite', + 'Measure wire bytes on mobile trace', + 'Patch revision suffix normalization', + 'Verify cold-reconnect cache parity', + 'Profile streaming message append cost', + ], + providers: [ + { id: 'anthropic', name: 'Anthropic Direct', kind: 'anthropic', baseUrl: 'https://api.anthropic.com/v1', region: 'us-east-1', tier: 'enterprise' }, + { id: 'openai', name: 'OpenAI Platform', kind: 'openai', baseUrl: 'https://api.openai.com/v1', region: 'us-west-2', tier: 'tier-5' }, + { id: 'google', name: 'Google AI Studio', kind: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', region: 'us-central1', tier: 'paid' }, + { id: 'vertex', name: 'Google Cloud Vertex AI', kind: 'vertex', baseUrl: 'https://us-central1-aiplatform.googleapis.com/v1', region: 'us-central1', tier: 'enterprise' }, + { id: 'bedrock', name: 'AWS Bedrock', kind: 'bedrock', baseUrl: 'https://bedrock-runtime.us-west-2.amazonaws.com', region: 'us-west-2', tier: 'enterprise' }, + { id: 'deepseek', name: 'DeepSeek API', kind: 'openai-compat', baseUrl: 'https://api.deepseek.com/v1', region: 'ap-east-1', tier: 'pro' }, + { id: 'openrouter', name: 'OpenRouter Gateway', kind: 'openai-compat', baseUrl: 'https://openrouter.ai/api/v1', region: 'global', tier: 'credits' }, + { id: 'xai', name: 'xAI Grok API', kind: 'openai-compat', baseUrl: 'https://api.x.ai/v1', region: 'us-west-1', tier: 'pro' }, + { id: 'qwen', name: 'Alibaba DashScope Qwen', kind: 'openai-compat', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', region: 'cn-beijing', tier: 'enterprise' }, + { id: 'moonshot', name: 'Moonshot Kimi API', kind: 'openai-compat', baseUrl: 'https://api.moonshot.cn/v1', region: 'cn-north-1', tier: 'pro' }, + { id: 'zhipu', name: 'Zhipu GLM OpenPlatform', kind: 'openai-compat', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', region: 'cn-east-1', tier: 'pro' }, + { id: 'minimax', name: 'MiniMax Coding Plan', kind: 'anthropic-compat', baseUrl: 'https://api.minimaxi.com/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'ollama-local', name: 'Local Ollama Studio', kind: 'ollama', baseUrl: 'http://127.0.0.1:11434/v1', region: 'local', tier: 'free' }, + { id: 'team-proxy', name: 'Internal LiteLLM Proxy', kind: 'openai-compat', baseUrl: 'https://llm-gateway.internal.example/v1', region: 'eu-central-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Nightly PR triage & CI digest', + '每小时同步上游安全通告', + 'Release branch changelog builder', + 'Mobile relay latency watchdog', + '清理过期工作区缓存与临时构建', + 'Weekly dependency vulnerability audit', + 'Eval Bank regression tracker', + '数据库 WAL 体积巡检任务', + ], + schedulePrompts: [ + 'Inspect open pull requests with failing checks, summarize root causes, and draft minimal fixes.', + '检查过去 1 小时内 relay 节点的 P95 延迟与断线重连日志,如异常则生成排查摘要。', + 'Collect merged commits since the last tag and prepare structured release notes grouped by subsystem.', + 'Audit disk usage of local session archives and flag workspaces exceeding 500 MiB.', + ], +}; + +function makeSymbol(rng, corpus) { + return `${rng.pick(corpus.symbolVerbs)}${rng.pick(corpus.symbolNouns)}`; +} + +function makeFilePath(rng, corpus) { + return `${rng.pick(corpus.subdirs)}/${rng.pick(corpus.fileStems)}.ts`; +} + +/** + * Generates realistic, high-entropy technical paragraphs combining unique identifiers, + * paths, line ranges, commit hashes, metrics, code fragments, and CJK+English prose. + */ +function makeUniqueParagraph(rng, corpus, seq) { + const kind = rng.int(0, 4); + const file = makeFilePath(rng, corpus); + const symA = makeSymbol(rng, corpus); + const symB = makeSymbol(rng, corpus); + const line = rng.int(18, 640); + const commit = rng.hex(10); + const bytesBefore = rng.int(12_000, 195_000); + const bytesAfter = Math.max(240, Math.floor(bytesBefore * (0.04 + rng.next() * 0.28))); + const ms = rng.int(4, 380); + + if (kind === 0) { + return `[${commit}] ${rng.pick(corpus.enObservations)} in \`${file}:${line}\` (\`${symA}\` -> \`${symB}\`): payload=${bytesBefore}B -> ${bytesAfter}B (${ms}ms, seq=${seq}). ${rng.pick(corpus.cjkTopics)}:${rng.pick(corpus.cjkActions)}。`; + } + if (kind === 1) { + const varA = `${rng.pick(corpus.symbolNouns).toLowerCase()}_${rng.hex(4)}`; + const varB = `tag_${rng.hex(6)}`; + return `\`\`\`ts\n// ${file}:${line} (${commit})\nexport function ${symA}(${varA}: Uint8Array, ${varB}: string) {\n const limit = ${rng.int(64, 4096)};\n return ${symB}(${varA}.subarray(0, Math.min(${varA}.byteLength, limit)), ${varB});\n}\n\`\`\`\n分析结论(#${seq}):针对「${rng.pick(corpus.cjkTopics)}」,${rng.pick(corpus.cjkActions)}(实测耗时 ${ms}ms,压缩后 ${bytesAfter}B)。`; + } + if (kind === 2) { + const reqId = `req-${rng.hex(8)}`; + const peerId = `peer-${rng.hex(6)}`; + return `Trace ${reqId} (${peerId}): ${rng.pick(corpus.enObservations)}. Checked \`${symA}\` at \`${file}:${line}-${line + rng.int(8, 45)}\` against commit \`${commit}\` (delta=${bytesAfter}B vs raw=${bytesBefore}B, ratio=${((bytesAfter / bytesBefore) * 100).toFixed(2)}%). 备注:${rng.pick(corpus.cjkTopics)} ✅`; + } + if (kind === 3) { + return `在排查 \`${file}\` 第 ${line} 行 \`${symA}\`(提交 \`${commit}\`)时观测到「${rng.pick(corpus.cjkTopics)}」,单次同步帧达到 ${bytesBefore} 字节。${rng.pick(corpus.cjkActions)},验证通过 ${rng.int(12, 96)} 组用例(${ms}ms,目标 ${bytesAfter}B)。`; + } + const errCode = `ERR_${rng.pick(corpus.symbolNouns).toUpperCase()}_${rng.int(100, 999)}`; + return `Diagnostic ${errCode} @ \`${file}:${line}\` [rev=${seq}, hash=${commit}]: \`${symA}\` returned ${bytesAfter}B after calling \`${symB}\`. ${rng.pick(corpus.enObservations)}; verified fallback parity without data drift (${ms}ms).`; +} + +function makeStreamAppendChunk(rng, corpus, seq) { + const file = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(8); + const line = rng.int(10, 580); + const val = rng.int(120, 98000); + if (rng.bool(0.5)) { + return `[chunk-${commit}] \`${file}:${line}\` \`${sym}()\`: ${rng.pick(corpus.enObservations)} (measured=${val}B, step=${seq}). ${rng.pick(corpus.cjkTopics)}。`; + } + return `(片段 ${commit})检查 \`${file}:${line}\` 中的 \`${sym}\`:${rng.pick(corpus.cjkActions)}(指标=${val},序号=${seq})。`; +} + +function makeThinkingChunk(rng, corpus, seq) { + const sym = makeSymbol(rng, corpus); + const commit = rng.hex(6); + const n = rng.int(16, 4096); + if (rng.bool(0.5)) { + return `Checking \`${sym}\` (#${seq}, id=${commit}, budget=${n}B): ${rng.pick(corpus.enObservations)}. `; + } + return `思考(${commit}/#${seq}):关于「${rng.pick(corpus.cjkTopics)}」与 \`${sym}\`(${n}B),${rng.pick(corpus.cjkActions)}。`; +} + +function makeToolOutput(rng, corpus, seq) { + const f1 = makeFilePath(rng, corpus); + const f2 = makeFilePath(rng, corpus); + const sym = makeSymbol(rng, corpus); + const h = rng.hex(10); + return [ + `${f1}:${rng.int(10, 400)}: export function ${sym}(ctx_${seq}) { /* ${h} */ }`, + `${f2}:${rng.int(10, 400)}: assert.equal(checksum, "${rng.hex(16)}");`, + `PASS ${rng.int(14, 68)}/${rng.int(68, 72)} assertions (${rng.int(42, 890)}ms, rss=${rng.int(34, 128)}MB)`, + ].join('\n'); +} + +function makeMessageText(rng, corpus, seq, paragraphs) { + const parts = []; + for (let i = 0; i < paragraphs; i += 1) { + parts.push(makeUniqueParagraph(rng, corpus, seq * 10 + i)); + } + return parts.join('\n\n'); +} + +function createInitialSessions(rng, corpus, baseTime) { + const sessions = []; + for (let i = 0; i < 160; i += 1) { + const id = `${corpus.idPrefix}-sess-${String(i + 1).padStart(4, '0')}-${rng.hex(4)}`; + const tagCount = rng.int(1, 3); + const tags = []; + for (let t = 0; t < tagCount; t += 1) { + const tag = rng.pick(corpus.tagsPool); + if (!tags.includes(tag)) tags.push(tag); + } + const input = rng.int(4000, 180000); + const output = rng.int(800, 42000); + const cacheRead = rng.int(10000, 600000); + const sym = makeSymbol(rng, corpus); + sessions.push({ + id, + title: `${rng.pick(corpus.sessionTitles)} [${sym} #${i + 1}]`, + workingDir: `${rng.pick(corpus.workingDirs)}/${rng.pick(corpus.fileStems)}`, + agentKind: rng.pick(corpus.agentKinds), + phase: i < 8 ? 'running' : rng.pick(['idle', 'idle', 'idle', 'waiting_approval', 'error']), + updatedAt: baseTime - i * rng.int(45_000, 300_000), + lastMessagePreview: `${rng.pick(corpus.cjkTopics)} · ${sym} (${rng.hex(8)}): ${rng.pick(corpus.enObservations).slice(0, 68)}`, + tokenUsage: { + input, + output, + cacheRead, + costUsd: Math.round((input * 0.000003 + output * 0.000015 + cacheRead * 0.0000003) * 10000) / 10000, + }, + tags, + unreadCount: i < 12 ? rng.int(0, 5) : 0, + pinned: i < 24, + modelLabel: rng.pick(corpus.modelLabels), + deviceId: rng.pick(corpus.devices), + deviceOnline: true, + }); + } + return sessions; +} + +function makeMessageItem(rng, corpus, sessionId, seq, timestamp, revSuffix) { + const isWork = seq % 5 === 4; + if (isWork) { + const workId = `${corpus.idPrefix}-${sessionId}-w${String(seq).padStart(4, '0')}`; + const sym = makeSymbol(rng, corpus); + return { + key: `work:${workId}`, + type: 'work', + summary: { + title: `${rng.pick(corpus.workTitles)} · ${sym} (#${seq})`, + status: 'done', + revision: `${workId}-r1${revSuffix}`, + durationMs: rng.int(180, 9400), + }, + children: [ + { + key: `work:${workId}:c1`, + type: 'work', + summary: { + title: `Step 1: ${rng.pick(corpus.toolNames)} ${makeFilePath(rng, corpus)}`, + status: 'done', + revision: `${workId}-c1-r1${revSuffix}`, + durationMs: rng.int(60, 2400), + }, + }, + ], + }; + } + const msgId = `${corpus.idPrefix}-${sessionId}-m${String(seq).padStart(4, '0')}`; + const role = seq % 2 === 0 ? 'user' : 'assistant'; + const paragraphs = role === 'user' ? rng.int(1, 2) : rng.int(3, 5); + const text = `[#${seq}] ${makeMessageText(rng, corpus, seq, paragraphs)}`; + const content = { text }; + const row = { + id: msgId, + role, + createdAt: timestamp, + remoteBodyVersion: sha256Hex(JSON.stringify(content)), + content, + }; + if (role === 'assistant') { + row.thinking = makeThinkingChunk(rng, corpus, seq) + makeThinkingChunk(rng, corpus, seq + 1); + if (seq % 3 === 1) { + row.toolCalls = [ + { + id: `tc-${seq}-${rng.hex(4)}`, + name: rng.pick(corpus.toolNames), + args: { + path: `${rng.pick(corpus.workingDirs)}/${makeFilePath(rng, corpus)}`, + limit: rng.int(50, 200), + }, + status: 'done', + output: makeToolOutput(rng, corpus, seq), + }, + ]; + } + } + return { + key: `msg:${msgId}`, + type: 'messages', + messages: [row], + }; +} + +function applyRevisionSuffix(items, oldSuffix, newSuffix) { + for (const item of items) { + if (item.type === 'work') { + if (item.summary && typeof item.summary.revision === 'string' && item.summary.revision.endsWith(oldSuffix)) { + item.summary.revision = item.summary.revision.slice(0, -oldSuffix.length) + newSuffix; + } + if (Array.isArray(item.children)) { + applyRevisionSuffix(item.children, oldSuffix, newSuffix); + } + } + } +} + +function createInitialSessionHistory(rng, corpus, sessionId, baseTime) { + const rev = 1; + const revSuffix = `:rev-${rev}`; + const items = []; + for (let seq = 1; seq <= 35; seq += 1) { + items.push(makeMessageItem(rng, corpus, sessionId, seq, baseTime - (36 - seq) * 18_000, revSuffix)); + } + return { + sessionId, + nextSeq: 36, + rev, + revSuffix, + streamingTicksLeft: 0, + runningWorkSummary: { + status: 'running', + activeTool: rng.pick(corpus.toolNames), + elapsedMs: 1200, + stepCount: 1, + lines: [`Initialized trace session ${sessionId} (${rng.hex(8)})`], + }, + items, + }; +} + +function createInitialProviders(rng, corpus, baseTime) { + const capabilityPool = ['tools', 'vision', 'reasoning', 'caching', 'streaming', 'json-schema']; + const providers = corpus.providers.map((p, idx) => { + const modelCount = 7 + (idx % 4); + const models = []; + for (let m = 0; m < modelCount; m += 1) { + const tier = m === 0 ? 'flagship' : m < 3 ? 'balanced' : m < 6 ? 'fast' : 'mini'; + const capCount = 3 + (m % 4); + models.push({ + id: `${p.id}/${tier}-v${(m % 5) + 1}.${idx % 3}-${rng.hex(3)}`, + label: `${p.name} ${tier.toUpperCase()} ${(m % 5) + 1}.${idx % 3}`, + description: `${p.name} ${tier} profile (${p.region}, ${makeSymbol(rng, corpus)}, rev-${rng.hex(6)}): ${rng.pick(corpus.enObservations)}`, + contextWindow: m < 3 ? 200_000 : m < 6 ? 128_000 : 64_000, + maxOutputTokens: m < 2 ? 32_768 : 16_384, + pricing: { + inputPerM: Math.round((0.15 + (modelCount - m) * 0.85) * 100) / 100, + outputPerM: Math.round((0.6 + (modelCount - m) * 3.1) * 100) / 100, + cacheReadPerM: Math.round((0.03 + (modelCount - m) * 0.12) * 100) / 100, + }, + capabilities: capabilityPool.slice(0, capCount), + deprecated: false, + defaultEffort: m < 2 ? 'high' : 'medium', + }); + } + const dailyLimit = 5_000_000 + idx * 1_500_000; + const usedPercent = Math.round(rng.next() * 450) / 10; + return { + id: p.id, + name: p.name, + kind: p.kind, + enabled: true, + status: 'healthy', + baseUrl: p.baseUrl, + region: p.region, + latencyMs: rng.int(110, 620), + checkedAt: baseTime, + quota: { + usedPercent, + remainingTokens: Math.round(dailyLimit * (1 - usedPercent / 100)), + dailyLimit, + resetAt: baseTime + 6 * 3600_000, + tier: p.tier, + }, + models, + }; + }); + return { + catalogVersion: 4, + generatedAt: baseTime, + activeProviderId: providers[0].id, + providers, + }; +} + +function createInitialSchedules(rng, corpus, baseTime) { + const crons = ['*/15 * * * *', '0 * * * *', '0 */4 * * *', '0 9 * * 1-5', '30 2 * * *']; + const jobs = []; + for (let i = 0; i < 40; i += 1) { + const recentRuns = []; + for (let r = 0; r < 6; r += 1) { + const startedAt = baseTime - (6 - r) * 3600_000 - i * 17_000; + const durationMs = rng.int(2400, 48000); + recentRuns.push({ + runId: `${corpus.idPrefix}-run-${i + 1}-${r + 1}-${rng.hex(4)}`, + startedAt, + finishedAt: startedAt + durationMs, + status: r === 4 && i % 9 === 0 ? 'failed' : 'succeeded', + durationMs, + summary: `${rng.pick(corpus.scheduleNames)} [${rng.hex(6)}] (${rng.int(1, 24)} items, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1200, 36000), + }); + } + jobs.push({ + id: `${corpus.idPrefix}-sched-${String(i + 1).padStart(3, '0')}`, + name: `${rng.pick(corpus.scheduleNames)} #${i + 1}`, + cron: rng.pick(crons), + prompt: `${rng.pick(corpus.schedulePrompts)} (${makeFilePath(rng, corpus)})`, + targetSessionId: `${corpus.idPrefix}-sess-${String((i % 30) + 1).padStart(4, '0')}`, + workspaceDir: rng.pick(corpus.workingDirs), + enabled: i % 11 !== 10, + nextRunAt: baseTime + rng.int(120_000, 7200_000), + lastStatus: recentRuns[recentRuns.length - 1].status, + recentRuns, + runSeq: 7, + }); + } + return { + indexVersion: 3, + updatedAt: baseTime, + totalJobs: jobs.length, + jobs, + }; +} + +export const DEFAULT_SCHEDULE_PROFILE = { + coldReconnectTicks: [34, 72, 110, 148, 184, 214], + hostEvictTicks: [52, 128, 198], + concurrentSpecs: [ + { tick: 24, channel: 'local-db:sessions:list' }, + { tick: 92, channel: 'local-db:messages:view' }, + { tick: 162, channel: 'local-db:sessions:list' }, + { tick: 204, channel: 'maker:provider:list' }, + ], +}; + +/** + * Generate a deterministic 240-RPC multi-channel Cindy sync trace. + */ +export function generateTrace({ + seed = 20260501, + corpus = DEFAULT_CORPUS, + scheduleProfile = DEFAULT_SCHEDULE_PROFILE, +} = {}) { + const rng = createRng(seed); + let clock = 1_765_000_000_000 + (seed % 1000) * 60_000; + + const sessions = createInitialSessions(rng, corpus, clock); + const histA = createInitialSessionHistory(rng, corpus, 'active-A', clock); + const histB = createInitialSessionHistory(rng, corpus, 'active-B', clock); + const providerCatalog = createInitialProviders(rng, corpus, clock); + const scheduleIndex = createInitialSchedules(rng, corpus, clock); + + let sessionsPollCount = 0; + let bulkStormCount = 0; + let deviceOnlineFlip = false; + + function mutateSessions(bulkOverride = false) { + sessionsPollCount += 1; + clock += rng.int(1500, 4500); + const isBulkStorm = bulkOverride || (sessionsPollCount > 2 && sessionsPollCount % 10 === 0); + if (isBulkStorm) { + bulkStormCount += 1; + deviceOnlineFlip = !deviceOnlineFlip; + const ratio = 0.60 + rng.next() * 0.15; + const count = Math.floor(sessions.length * ratio); + const indices = rng.shuffle(Array.from({ length: sessions.length }, (_, i) => i)).slice(0, count); + for (const idx of indices) { + const s = sessions[idx]; + s.deviceOnline = deviceOnlineFlip; + s.tokenUsage.cacheRead += rng.int(50, 900); + if (idx % 5 === 0) s.updatedAt = clock; + } + } + const mutateCount = rng.int(4, 12); + const picked = []; + for (let i = 0; i < mutateCount; i += 1) { + const idx = rng.int(0, Math.min(sessions.length - 1, 45)); + if (!picked.includes(idx)) picked.push(idx); + } + for (const idx of picked) { + const s = sessions[idx]; + s.updatedAt = clock - rng.int(0, 900); + s.phase = rng.pick(['running', 'idle', 'waiting_approval']); + s.tokenUsage.input += rng.int(200, 4500); + s.tokenUsage.output += rng.int(80, 1200); + s.tokenUsage.costUsd = Math.round( + (s.tokenUsage.input * 0.000003 + s.tokenUsage.output * 0.000015 + s.tokenUsage.cacheRead * 0.0000003) * 10000, + ) / 10000; + s.unreadCount = s.phase === 'running' ? s.unreadCount + 1 : 0; + if (rng.bool(0.5)) { + s.lastMessagePreview = `${rng.pick(corpus.cjkTopics)} · ${makeSymbol(rng, corpus)} (${rng.hex(6)}): ${rng.pick(corpus.enObservations).slice(0, 56)}`; + } + } + const moveCount = Math.min(picked.length, rng.int(2, 5)); + for (let m = 0; m < moveCount; m += 1) { + const idx = picked[m]; + if (idx > 0 && idx < sessions.length) { + const [row] = sessions.splice(idx, 1); + const dest = rng.int(0, Math.min(8, sessions.length)); + sessions.splice(dest, 0, row); + } + } + } + + function snapshotSessions(scope) { + if (scope === 'pinned') { + const pinned = sessions.filter((s) => s.pinned).slice(0, 40); + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'pinned', + totalCount: pinned.length, + activeDeviceId: corpus.devices[0], + sessions: pinned, + }); + } + return cloneJson({ + version: 2, + fetchedAt: clock, + scope: 'all', + totalCount: sessions.length, + activeDeviceId: corpus.devices[0], + sessions, + }); + } + + function mutateHistory(hist, steps = 1) { + for (let s = 0; s < steps; s += 1) { + clock += rng.int(900, 2800); + const oldSuffix = hist.revSuffix; + hist.rev += 1; + const newSuffix = `:rev-${hist.rev}`; + applyRevisionSuffix(hist.items, oldSuffix, newSuffix); + hist.revSuffix = newSuffix; + + hist.runningWorkSummary.elapsedMs += rng.int(800, 3200); + hist.runningWorkSummary.stepCount += 1; + hist.runningWorkSummary.activeTool = rng.pick(corpus.toolNames); + hist.runningWorkSummary.lines.push( + `[rev ${hist.rev}] ${hist.runningWorkSummary.activeTool} ${makeSymbol(rng, corpus)} (${rng.hex(6)})`, + ); + if (hist.runningWorkSummary.lines.length > 6) { + hist.runningWorkSummary.lines.shift(); + } + + const lastItem = hist.items[hist.items.length - 1]; + const canStreamAppend = + hist.streamingTicksLeft > 0 + && lastItem + && lastItem.type === 'messages' + && lastItem.messages[0]?.role === 'assistant'; + + if (canStreamAppend) { + // Streaming text/thinking append (120–380 chars appended onto the last message!) + const msg = lastItem.messages[0]; + const appended = makeStreamAppendChunk(rng, corpus, hist.rev); + msg.content.text += `\n${appended}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + if (rng.bool(0.65) && typeof msg.thinking === 'string') { + msg.thinking += makeThinkingChunk(rng, corpus, hist.rev); + } + hist.streamingTicksLeft -= 1; + } else if (hist.items.length < 140) { + // Advance a conversation turn (user message + optional work step + new streaming assistant message) + const burst = rng.int(2, 4); + let lastAdded = null; + for (let b = 0; b < burst && hist.items.length < 140; b += 1) { + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + b * 250, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + lastAdded = item; + } + if (lastAdded && lastAdded.type === 'messages' && lastAdded.messages[0].role === 'assistant') { + hist.streamingTicksLeft = rng.int(3, 5); + } else if (hist.items.length < 140) { + // Ensure next item starts a streaming assistant turn + const item = makeMessageItem(rng, corpus, hist.sessionId, hist.nextSeq, clock + 900, hist.revSuffix); + hist.nextSeq += 1; + hist.items.push(item); + hist.streamingTicksLeft = + item.type === 'messages' && item.messages[0].role === 'assistant' ? rng.int(3, 5) : 0; + } else { + hist.streamingTicksLeft = 0; + } + } else { + for (let i = hist.items.length - 1; i >= 0; i -= 1) { + const cand = hist.items[i]; + if (cand.type === 'messages' && cand.messages[0].role === 'assistant') { + const msg = cand.messages[0]; + msg.content.text += `\n${makeStreamAppendChunk(rng, corpus, hist.rev)}`; + msg.remoteBodyVersion = sha256Hex(JSON.stringify(msg.content)); + break; + } + } + } + } + } + + function snapshotHistory(hist, beforeIndex = null) { + if (beforeIndex !== null) { + const start = Math.max(0, beforeIndex - 28); + const slice = hist.items.slice(start, beforeIndex); + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: start > 0, + nextBefore: slice[0]?.key ?? null, + before: hist.items[beforeIndex]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: slice, + }); + } + return cloneJson({ + sessionId: `${corpus.idPrefix}-${hist.sessionId}`, + hasMore: true, + nextBefore: hist.items[0]?.key ?? null, + revisionSuffix: hist.revSuffix, + runningWorkSummary: hist.runningWorkSummary, + items: hist.items, + }); + } + + function mutateProviders() { + clock += rng.int(1200, 3500); + providerCatalog.generatedAt = clock; + const statusChoices = ['healthy', 'healthy', 'healthy', 'degraded', 'rate_limited']; + const changedStatus = new Set([ + rng.int(0, providerCatalog.providers.length - 1), + rng.int(0, providerCatalog.providers.length - 1), + ]); + for (let i = 0; i < providerCatalog.providers.length; i += 1) { + const p = providerCatalog.providers[i]; + if (rng.bool(0.5) || changedStatus.has(i)) { + p.checkedAt = clock; + p.latencyMs = Math.max(45, p.latencyMs + rng.int(-35, 45)); + const nextPct = Math.min(99.9, Math.round((p.quota.usedPercent + rng.next() * 1.4) * 10) / 10); + p.quota.usedPercent = nextPct; + p.quota.remainingTokens = Math.max(0, Math.round(p.quota.dailyLimit * (1 - nextPct / 100))); + if (rng.bool(0.2)) { + p.quota.resetAt = clock + 6 * 3600_000; + } + } + if (changedStatus.has(i)) { + p.status = rng.pick(statusChoices); + } + } + } + + function mutateSchedules() { + clock += rng.int(1500, 4000); + scheduleIndex.updatedAt = clock; + const mutateCount = rng.int(1, 3); + const chosen = new Set(); + while (chosen.size < mutateCount) { + chosen.add(rng.int(0, scheduleIndex.jobs.length - 1)); + } + for (const idx of chosen) { + const job = scheduleIndex.jobs[idx]; + const durationMs = rng.int(1800, 42000); + const status = rng.bool(0.88) ? 'succeeded' : 'failed'; + const runEntry = { + runId: `${corpus.idPrefix}-run-${idx + 1}-${job.runSeq}-${rng.hex(4)}`, + startedAt: clock - durationMs, + finishedAt: clock, + status, + durationMs, + summary: `${job.name} [${rng.hex(6)}] (${rng.int(1, 20)} records, ${makeSymbol(rng, corpus)})`, + tokensUsed: rng.int(1400, 29000), + }; + job.runSeq += 1; + job.lastStatus = status; + job.nextRunAt = clock + rng.int(900_000, 7200_000); + job.recentRuns.push(runEntry); + if (job.recentRuns.length > 6) { + job.recentRuns.shift(); + } + } + } + + const concurrentByTick = new Map(scheduleProfile.concurrentSpecs.map((c) => [c.tick, c.channel])); + const coldReconnectSet = new Set(scheduleProfile.coldReconnectTicks); + const hostEvictSet = new Set(scheduleProfile.hostEvictTicks); + + const targets = { + 'local-db:sessions:list': 76, + 'local-db:messages:view': 98, + 'maker:provider:list': 28, + 'maker:schedule:list-sidebar-index-runs': 30, + }; + const emitted = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + const channelOrder = [ + 'local-db:messages:view', + 'local-db:sessions:list', + 'maker:provider:list', + 'maker:schedule:list-sidebar-index-runs', + ]; + const totalNonConcurrent = 232; + const tickChannels = []; + for (let i = 0; i < totalNonConcurrent; i += 1) { + let bestChannel = null; + let bestDeficit = -Infinity; + for (const ch of channelOrder) { + if (emitted[ch] >= targets[ch]) continue; + const expected = ((i + 1) * targets[ch]) / totalNonConcurrent; + const deficit = expected - emitted[ch]; + if (deficit > bestDeficit) { + bestDeficit = deficit; + bestChannel = ch; + } + } + emitted[bestChannel] += 1; + tickChannels.push(bestChannel); + } + + const steps = []; + let rpcCounter = 0; + let nonConcurrentIdx = 0; + let sessionReadSeq = 0; + let msgReadSeq = 0; + let rawJsonBytes = 0; + const channelCounts = { + 'local-db:sessions:list': 0, + 'local-db:messages:view': 0, + 'maker:provider:list': 0, + 'maker:schedule:list-sidebar-index-runs': 0, + }; + + function makeRpcRead(channel, forcePrimary = false, forceSession = null) { + rpcCounter += 1; + channelCounts[channel] += 1; + const id = `rpc-${String(rpcCounter).padStart(4, '0')}`; + let argsKey; + let groundTruthValue; + + if (channel === 'local-db:sessions:list') { + sessionReadSeq += 1; + mutateSessions(false); + const isPinned = !forcePrimary && sessionReadSeq % 5 === 0; + const scope = isPinned ? 'pinned' : 'all'; + argsKey = JSON.stringify({ scope, limit: isPinned ? 40 : 160 }); + groundTruthValue = snapshotSessions(scope); + } else if (channel === 'local-db:messages:view') { + msgReadSeq += 1; + const useA = forceSession !== null ? forceSession === 'A' : (msgReadSeq % 2 === 1); + const hist = useA ? histA : histB; + mutateHistory(hist, 1); + const isPaginated = !forcePrimary && msgReadSeq >= 10 && msgReadSeq % 8 === 2 && hist.items.length > 35; + if (isPaginated) { + const beforeIndex = Math.min(hist.items.length - 5, 30 + (msgReadSeq % 3) * 10); + const beforeKey = hist.items[beforeIndex].key; + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, before: beforeKey, limit: 28 }); + groundTruthValue = snapshotHistory(hist, beforeIndex); + } else { + argsKey = JSON.stringify({ sessionId: `${corpus.idPrefix}-${hist.sessionId}`, limit: 140 }); + groundTruthValue = snapshotHistory(hist, null); + } + } else if (channel === 'maker:provider:list') { + mutateProviders(); + argsKey = JSON.stringify({ includeModels: true, includeQuotas: true }); + groundTruthValue = cloneJson(providerCatalog); + } else if (channel === 'maker:schedule:list-sidebar-index-runs') { + mutateSchedules(); + argsKey = JSON.stringify({ limit: 40, recentRuns: 6 }); + groundTruthValue = cloneJson({ + indexVersion: scheduleIndex.indexVersion, + updatedAt: scheduleIndex.updatedAt, + totalJobs: scheduleIndex.totalJobs, + jobs: scheduleIndex.jobs.map(({ runSeq: _r, ...rest }) => rest), + }); + } else { + throw new Error(`Unknown channel: ${channel}`); + } + + rawJsonBytes += Buffer.byteLength(JSON.stringify(groundTruthValue), 'utf8'); + return { id, channel, argsKey, groundTruthValue }; + } + + let reconnectNum = 0; + let evictNum = 0; + + for (let tick = 0; tick < 236; tick += 1) { + if (coldReconnectSet.has(tick)) { + reconnectNum += 1; + mutateSessions(false); + mutateHistory(histA, rng.int(2, 4)); + mutateHistory(histB, rng.int(2, 3)); + mutateProviders(); + mutateSchedules(); + steps.push({ + type: 'cold_reconnect', + label: `mobile-cold-reconnect-${reconnectNum}`, + }); + } + if (hostEvictSet.has(tick)) { + evictNum += 1; + mutateSessions(false); + mutateHistory(histA, 1); + steps.push({ + type: 'host_evict', + label: `host-volatile-evict-${evictNum}`, + }); + } + + if (concurrentByTick.has(tick)) { + const ch = concurrentByTick.get(tick); + const forcedSess = ch === 'local-db:messages:view' ? 'A' : null; + const r1 = makeRpcRead(ch, true, forcedSess); + const r2 = makeRpcRead(ch, true, forcedSess); + steps.push({ + type: 'concurrent_rpc', + reads: [r1, r2], + }); + } else { + const ch = tickChannels[nonConcurrentIdx]; + nonConcurrentIdx += 1; + steps.push({ + type: 'rpc', + ...makeRpcRead(ch, false, null), + }); + } + } + + return { + seed, + meta: { + totalRpcs: rpcCounter, + channelCounts, + coldReconnectCount: reconnectNum, + hostEvictCount: evictNum, + concurrentPairCount: scheduleProfile.concurrentSpecs.length, + bulkStormCount, + finalHistoryLengthA: histA.items.length, + finalHistoryLengthB: histB.items.length, + rawJsonBytes, + }, + steps, + }; +} diff --git a/questions/opt-device-link-delta-sync/v2/author/stress-trace.mjs b/questions/opt-device-link-delta-sync/v2/author/stress-trace.mjs new file mode 100644 index 0000000..eadaff3 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/stress-trace.mjs @@ -0,0 +1,168 @@ +import { generateTrace } from './stress-trace-generator.mjs'; + +export const HELDOUT_SEED = 918273645; + +export const HELDOUT_CORPUS = { + idPrefix: 'ho2', + devices: [ + 'node-tokyo-macmini-09', + 'node-frankfurt-epyc-14', + 'node-seattle-thinkpad-22', + 'node-singapore-arm-07', + ], + workingDirs: [ + '/srv/builds/aurora-gateway', + '/srv/builds/nebula-indexer', + '/srv/builds/kestrel-mobile-app', + '/srv/builds/polaris-sync-engine', + '/srv/builds/solstice-telemetry', + '/srv/builds/horizon-cli', + ], + subdirs: [ + 'modules/transport/src', + 'modules/reconciler/src', + 'clients/ios-bridge/src', + 'clients/desktop-host/src', + 'edge/relay-router/src', + 'core/wire-codec/src', + 'spec/conformance', + 'tools/replay', + ], + fileStems: [ + 'frameMux', 'stateDiffer', 'pageDelta', 'bodyVault', + 'peerChannel', 'batchReader', 'outboxQueue', 'dictPush', + 'zlibAdapter', 'hostWorker', 'sessionIndex', 'coldResume', + 'driftProbe', 'retryScheduler', 'memoryCap', 'tokenStream', + 'varintPack', 'hashTree', 'journalSync', 'limitLedger', + ], + symbolVerbs: [ + 'align', 'diff', 'unpack', 'pack', 'sweep', 'strip', 'squash', + 'audit', 'route', 'dedupe', 'restore', 'marshal', 'decompress', 'trim', + 'splice', 'verify', 'flush', 'sanitize', + ], + symbolNouns: [ + 'BaseSlot', 'TranscriptPage', 'ContentBlock', 'PacketFrame', 'VersionRing', + 'OutlineTag', 'DigestList', 'ThreadRow', 'RateWindow', 'JobHistory', + 'MerkleChain', 'EditInstr', 'LeafHash', 'ClientState', 'SyncEnvelope', + 'StringPool', 'StreamTail', 'DiskRecord', + ], + cjkTopics: [ + '蜂窝网络高抖动下同步流量激增', '全局设备状态变更触发补丁中止', '后台重启后历史正文清单体积过大', + '助手流式输出尾部追加导致全文重发', '页级修订后缀污染未修改工作节点', '双请求并行读取造成旧基准失配', + '持久化落盘空间逼近双兆字节红线', '多模型供应商目录静态字段反复传输', '预置字典未对齐导致压缩率偏低', + '历史分页游标切换引发重复拉取', '跨进程隔离通道帧长度与轮次审计', '结构化数组重排与字段名冗余', + '宿主进程重启后的冷缓存集合核对', '中日韩与表情混合文本无损还原', '高频状态栏轮询带宽预算控制', + '定时巡检运行记录窗口移位压缩', + ], + enObservations: [ + 'Captured downstream burst when 65 percent of session rows flipped online flag', + 'Found streaming assistant output retransmitting unchanged 3 KiB markdown bodies', + 'Logged 22 KiB upstream manifest upload immediately after iOS cold relaunch', + 'Verified ring buffer retains prior snapshots across overlapping in-flight polls', + 'Measured raw deflate savings when seeded with previous synchronized base bytes', + 'Checked strict deep-equality across nested nulls, empty lists, and Unicode text', + 'Isolated page-wide outline suffix churn from actual work item payload edits', + 'Compared recursive keyed object patching against depth-limited row replacement', + 'Tracked compressed persistent cache footprint across six suspend-resume cycles', + 'Observed paginated history fetches sharing immutable blocks with latest page', + 'Evaluated multi-round Merkle prefix exchange for append-only transcript sync', + 'Measured binary varint field encoding on catalog and schedule index updates', + ], + cjkActions: [ + '应按唯一标识匹配条目并深入字段级差分,避免单字段变动拖累整行重传', + '宿主丢失易失基准时可通过紧凑内容摘要或双轮哈希调和跳过已落盘条目', + '对流式增长的长字符串采用公共前缀加尾部增量编码,可消除九成以上重复载荷', + '在宿主侧为每个请求键保留有界多基准环,确保并发旧基准请求依然命中增量路径', + '以双方共享的旧快照作为压缩预置字典,可显著压缩重复路径与固定枚举标签', + '严格保留空对象、空数组、数字类型、特殊普通键及多字节字符的逐字段一致性', + '冷重连握手改用分桶哈希或前缀摘要树,将上行字节从数万字节降至百字节级', + '剥离页级后缀前必须核验全部子节点格式匹配,确保任意异常输入均可无损还原', + ], + agentKinds: ['claude-code', 'codex', 'gemini-cli', 'pi'], + modelLabels: [ + 'claude-opus-4-6', + 'gpt-5.4-high', + 'gemini-3.1-pro', + 'deepseek-v3.2', + 'qwen3.5-max', + 'kimi-k2-thinking', + ], + tagsPool: [ + 'wan', 'delta', 'reconcile', 'ios', 'android', 'critical', 'backlog', + 'codec', 'storage', 'framing', 'metrics', 'release', 'hardening', 'latency', + ], + sessionTitles: [ + '调试弱网蜂窝环境下跨端状态漂移与重连风暴', + 'Reduce upstream digest bloat on iOS cold resume', + '设计通用结构化二进制差分与前缀字典编码器', + 'Analyze multi-region gateway quota refresh spikes', + '修复定时巡检面板历史记录滑动窗口重复序列化', + 'Benchmark Merkle bucket reconciliation under packet loss', + '处理流式思维链增量追加导致的下行带宽放大', + 'Verify strict process isolation between host and peer', + '排查并发只读请求基准淘汰引发的全量回退', + 'Optimize persistent disk cache eviction under 2 MiB cap', + '验证日文与表情符号混合长日志精确还原一致', + 'Stress-test pagination boundary transitions across reconnects', + ], + toolNames: ['inspect_trace', 'verify_hash', 'run_bench', 'diff_snapshot', 'profile_codec'], + workTitles: [ + 'Audit cold-start manifest overhead', + 'Replay held-out cellular trace', + 'Validate binary varint decoder bounds', + 'Strip volatile outline revision suffixes', + 'Check concurrent stale-base ring hits', + 'Measure preset-dictionary compression ratio', + ], + providers: [ + { id: 'claude-prod', name: 'Claude Enterprise Hub', kind: 'anthropic', baseUrl: 'https://claude-gw.aurora.example/v1', region: 'us-east-2', tier: 'dedicated' }, + { id: 'openai-prod', name: 'OpenAI Dedicated Pool', kind: 'openai', baseUrl: 'https://oai-gw.aurora.example/v1', region: 'us-west-1', tier: 'dedicated' }, + { id: 'gemini-cloud', name: 'Gemini Global Cloud', kind: 'gemini', baseUrl: 'https://gemini-gw.aurora.example/v1beta', region: 'europe-west4', tier: 'enterprise' }, + { id: 'vertex-eu', name: 'Vertex EU Frankfurt', kind: 'vertex', baseUrl: 'https://eu-vertex.aurora.example/v1', region: 'europe-west3', tier: 'enterprise' }, + { id: 'bedrock-ap', name: 'Bedrock Tokyo Relay', kind: 'bedrock', baseUrl: 'https://ap-bedrock.aurora.example', region: 'ap-northeast-1', tier: 'enterprise' }, + { id: 'deepseek-hk', name: 'DeepSeek HK Cluster', kind: 'openai-compat', baseUrl: 'https://ds-hk.aurora.example/v1', region: 'ap-east-1', tier: 'scale' }, + { id: 'router-edge', name: 'Edge Multi-Model Router', kind: 'openai-compat', baseUrl: 'https://edge-router.aurora.example/v1', region: 'global', tier: 'prepaid' }, + { id: 'grok-fast', name: 'Grok Inference Mesh', kind: 'openai-compat', baseUrl: 'https://grok-mesh.aurora.example/v1', region: 'us-central1', tier: 'pro' }, + { id: 'qwen-sh', name: 'Qwen Shanghai Cloud', kind: 'openai-compat', baseUrl: 'https://qwen-sh.aurora.example/v1', region: 'cn-shanghai', tier: 'enterprise' }, + { id: 'kimi-bj', name: 'Kimi Beijing Gateway', kind: 'openai-compat', baseUrl: 'https://kimi-bj.aurora.example/v1', region: 'cn-beijing', tier: 'pro' }, + { id: 'glm-hz', name: 'GLM Hangzhou Endpoint', kind: 'openai-compat', baseUrl: 'https://glm-hz.aurora.example/v4', region: 'cn-hangzhou', tier: 'pro' }, + { id: 'minimax-sg', name: 'MiniMax Singapore Pool', kind: 'anthropic-compat', baseUrl: 'https://mm-sg.aurora.example/anthropic', region: 'ap-southeast-1', tier: 'coding' }, + { id: 'vllm-lab', name: 'On-Prem vLLM H100 Rack', kind: 'openai-compat', baseUrl: 'http://10.24.0.18:8000/v1', region: 'on-prem', tier: 'internal' }, + { id: 'fallback-eu', name: 'EU Failover Proxy', kind: 'openai-compat', baseUrl: 'https://failover-eu.aurora.example/v1', region: 'eu-west-1', tier: 'internal' }, + ], + scheduleNames: [ + 'Hourly cellular sync telemetry rollup', + '每两小时巡检跨区域中继断连率', + 'Nightly binary codec fuzz verification', + 'Automated database compaction & vacuum', + '检查高流量会话持久化缓存命中率', + 'Daily provider quota burn forecast', + 'Weekly cold-reconnect regression sweep', + '定期归档过期远控诊断快照', + ], + schedulePrompts: [ + 'Aggregate wire-byte telemetry across all relay POPs and alert on regressions exceeding 10%.', + '扫描过去两小时内出现增量基准失配的会话,汇总失败原因并输出修复建议。', + 'Run fuzzing corpus against binary patch decoders and confirm zero parity mismatches.', + 'Analyze provider quota burn trajectories and recommend fallback routing weights.', + ], +}; + +export const HELDOUT_SCHEDULE_PROFILE = { + coldReconnectTicks: [28, 66, 102, 142, 178, 210], + hostEvictTicks: [46, 120, 192], + concurrentSpecs: [ + { tick: 19, channel: 'local-db:sessions:list' }, + { tick: 86, channel: 'local-db:messages:view' }, + { tick: 156, channel: 'local-db:sessions:list' }, + { tick: 202, channel: 'maker:provider:list' }, + ], +}; + +export function generateHeldoutTrace() { + return generateTrace({ + seed: HELDOUT_SEED, + corpus: HELDOUT_CORPUS, + scheduleProfile: HELDOUT_SCHEDULE_PROFILE, + }); +} diff --git a/questions/opt-device-link-delta-sync/v2/author/worker-client.mjs b/questions/opt-device-link-delta-sync/v2/author/worker-client.mjs new file mode 100644 index 0000000..46a66ad --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/worker-client.mjs @@ -0,0 +1,152 @@ +import module from 'node:module'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const allowedRoot = path.resolve(srcDir); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const ALLOWED_BUILTINS = new Set([ + 'node:zlib', 'zlib', + 'node:crypto', 'crypto', + 'node:buffer', 'buffer', + 'node:util', 'util', + 'node:string_decoder', 'string_decoder', + 'node:assert', 'assert', 'node:assert/strict', +]); + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('file://')) { + const resolved = nextResolve(specifier, context); + if (resolved?.url?.startsWith('file://')) { + const targetPath = path.resolve(fileURLToPath(resolved.url)); + if (targetPath !== allowedRoot && !targetPath.startsWith(allowedRoot + path.sep)) { + throw new Error(`Forbidden import outside src/: ${specifier}`); + } + } + return resolved; + } + if (!ALLOWED_BUILTINS.has(specifier)) { + throw new Error(`Forbidden built-in or external import: ${specifier}`); + } + return nextResolve(specifier, context); + }, + }); +} + +for (const key of ['fetch', 'WebSocket', 'XMLHttpRequest']) { + try { delete globalThis[key]; } catch { /* ignore */ } +} +for (const key of ['getBuiltinModule', 'dlopen', 'binding']) { + try { + Object.defineProperty(process, key, { + value: () => { throw new Error(`Forbidden process.${key}`); }, + configurable: false, + writable: false, + }); + } catch { /* ignore */ } +} + +const modUrl = pathToFileURL(path.join(allowedRoot, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/author/worker-host.mjs b/questions/opt-device-link-delta-sync/v2/author/worker-host.mjs new file mode 100644 index 0000000..6a4dd40 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/author/worker-host.mjs @@ -0,0 +1,107 @@ +import module from 'node:module'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const allowedRoot = path.resolve(srcDir); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const ALLOWED_BUILTINS = new Set([ + 'node:zlib', 'zlib', + 'node:crypto', 'crypto', + 'node:buffer', 'buffer', + 'node:util', 'util', + 'node:string_decoder', 'string_decoder', + 'node:assert', 'assert', 'node:assert/strict', +]); + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('file://')) { + const resolved = nextResolve(specifier, context); + if (resolved?.url?.startsWith('file://')) { + const targetPath = path.resolve(fileURLToPath(resolved.url)); + if (targetPath !== allowedRoot && !targetPath.startsWith(allowedRoot + path.sep)) { + throw new Error(`Forbidden import outside src/: ${specifier}`); + } + } + return resolved; + } + if (!ALLOWED_BUILTINS.has(specifier)) { + throw new Error(`Forbidden built-in or external import: ${specifier}`); + } + return nextResolve(specifier, context); + }, + }); +} + +// Neutralize global network / dynamic builtin escape hatches before loading submission code. +for (const key of ['fetch', 'WebSocket', 'XMLHttpRequest']) { + try { delete globalThis[key]; } catch { /* ignore */ } +} +for (const key of ['getBuiltinModule', 'dlopen', 'binding']) { + try { + Object.defineProperty(process, key, { + value: () => { throw new Error(`Forbidden process.${key}`); }, + configurable: false, + writable: false, + }); + } catch { /* ignore */ } +} + +const modUrl = pathToFileURL(path.join(allowedRoot, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const beforeJson = req.verifyImmutable ? JSON.stringify(req.groundTruthValue) : null; + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + if (beforeJson !== null && JSON.stringify(req.groundTruthValue) !== beforeJson) { + throw new Error('host.handleFrame mutated groundTruthValue'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/candidate/CONTRACT.md b/questions/opt-device-link-delta-sync/v2/candidate/CONTRACT.md new file mode 100644 index 0000000..13da075 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/CONTRACT.md @@ -0,0 +1,102 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (one of the Cindy channels in the recording, or any other channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +Lifecycle steps between reads: +- `cold_reconnect`: the client exports `persistentState` (checked against `maxPersistentBytes`), then **both** the Client and the Host child processes are terminated and respawned; the new Client receives only `{ persistentState }`, the new Host starts empty. +- `client_restart`: the same for the Client only; the Host process (and its volatile state) keeps running. +- `host_evict`: the Host process alone is terminated and respawned; the Client stays warm. + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 20s` for the full held-out recording, including process spawns). +4. **Generalization**: The score comes from an unseen held-out recording of different real tasks (different de-identification key, different text, ids and sizes). A separate synthetic stress trace with many cold reconnects, host evictions and concurrent stale-base reads is run as a correctness gate only. Do not hardcode trace strings or schema assumptions that break on unseen payloads. + +## 6. Workload Provenance + +Both recordings were made by running Cindy's transfer-baseline scenario (`apps/desktop/src/test/transfer-baseline`, phone profile) at the source commit in `question.json`, with its synthetic content swapped for real de-identified tasks and every remote RPC recorded as the Desktop handler returned it. History pages are recorded complete (the product's own `historyDelta` option removed), and product protocol options (`historyDelta`, `messageBodies`) are removed from the request arguments: they belong to the protocol you are replacing. The tasks were de-identified before recording (harness prompt text replaced by same-shape surrogate text; paths, user name, e-mail and account ids pseudonymized). Tool results that the database had compacted after archiving were restored from the engine's own transcript, as the live database held them; plugin-engine tasks keep the compacted marker. diff --git a/questions/opt-device-link-delta-sync/v2/candidate/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v2/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..be264f2 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/ENVIRONMENT.md @@ -0,0 +1,11 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic two-process replay of the public real recording (162 reads, 10 channels) reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, reduction vs raw JSON and the product's own measured wire bytes for the same reads +- Data: `corpus/public-trace.json.br` (brotli-compressed JSON, loaded by `lib/trace-loader.mjs`). The held-out recording used for the score is not shipped. diff --git a/questions/opt-device-link-delta-sync/v2/candidate/TASK.md b/questions/opt-device-link-delta-sync/v2/candidate/TASK.md new file mode 100644 index 0000000..5d27a96 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC sync protocol (`src/sync-protocol.mjs`), extracted from the desktop-to-mobile remote session path (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). When a user follows a task from the phone, every read below crosses a metered, often cellular, link; fewer bytes mean faster pages and less data used. + +## What the real workload looks like + +`corpus/public-trace.json.br` is a recorded phone session, not a generated one. It was captured by running Cindy's own transfer-baseline scenario (real `DeviceLinkClient`, real relay, real Desktop `local-db:*` handlers on a migrated SQLite database, real phone history-view controller and recovery core) with the host database filled from 13 real, de-identified Cindy tasks in which Claude Code, Codex and a plugin engine worked on open-source code. Live turns stream real prose and real tool calls with their real results. + +It holds 162 reads (~3.4 MB of complete JSON) on 10 channels, in the order the host received them: + +- `local-db:messages:view` (56 reads, most of the bytes): the history page the phone renders, re-read after every streamed step of a live turn, after reconnects, and as read-ahead for the five most recent tasks. +- `local-db:messages:work-details`, `local-db:sessions:list`, `local-db:sessions:get` and several small status reads (`maker:list-active`, `maker:input:get-projection`, `maker:goal:get-status`, `maker:get-pending-interactions`, `local-db:messages:view-intent`, `sidebar-settings:get-project-aliases`). +- Lifecycle events: a new host and phone process between scenario runs (`cold_reconnect`), a new phone process on the same host (`client_restart`), and reads that were in flight together (`concurrent_rpc`). + +The baseline in `src/` follows today's product strategy at the payload level: it only diffs `local-db:sessions:list` (depth 2), only reuses whole identical history items, gzips everything else independently, and keeps no history across process restarts. On the public recording it sends 1,022,246 B. For reference, the product itself put 1,081,479 B on the WebSocket for the same reads, a number that also includes its message envelopes and transport framing, which this question does not count. + +For orientation: compressing each connection's reads in order with Brotli-11, with full shared history inside the connection and nothing kept across restarts, takes 178,329 B on the public recording. Using persisted state across restarts can go lower still. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every read, including reads after restarts and concurrent reads built on a stale base. +- Respect **strict two-process isolation**: Host and Client run in separate Node.js child processes and communicate **only** through `Uint8Array` wire frames. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return at most `maxPersistentBytes` (default `2 MiB`), and every RPC must finish within `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended goal**: drive `total_wire_bytes` (all upstream and downstream bytes of all rounds of all RPCs) as low as possible on an **unseen held-out recording** made the same way from 13 different real tasks, de-identified with a different key. +- Run `npm test` and `npm run bench` to verify parity and measure your reduction. +- Record your analysis, protocol design, trade-offs and verified results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v2/candidate/bench/workload.mjs b/questions/opt-device-link-delta-sync/v2/candidate/bench/workload.mjs new file mode 100644 index 0000000..126dcd4 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark() { + const trace = loadPublicTrace(); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + trace: trace.name, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + product_rpc_wire_bytes: trace.meta.productRpcWireBytes, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + client_restarts: trace.meta.clientRestartCount, + concurrent_pairs: trace.meta.concurrentPairCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v2/candidate/corpus/public-trace.json.br b/questions/opt-device-link-delta-sync/v2/candidate/corpus/public-trace.json.br new file mode 100644 index 0000000..e196d5c Binary files /dev/null and b/questions/opt-device-link-delta-sync/v2/candidate/corpus/public-trace.json.br differ diff --git a/questions/opt-device-link-delta-sync/v2/candidate/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v2/candidate/lib/rpc-harness.mjs new file mode 100644 index 0000000..fa01758 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/lib/rpc-harness.mjs @@ -0,0 +1,306 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'client_restart') { + // A new controller process on the same running host (e.g. the phone app relaunched): + // kill & respawn Client from its persisted state only; Host keeps its volatile state. + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v2/candidate/lib/trace-loader.mjs b/questions/opt-device-link-delta-sync/v2/candidate/lib/trace-loader.mjs new file mode 100644 index 0000000..3c832bc --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/lib/trace-loader.mjs @@ -0,0 +1,22 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +/** + * Load a recorded RPC workload (brotli-compressed JSON: { name, meta, steps }). + * Steps: { type: 'rpc', id, channel, argsKey, groundTruthValue } + * | { type: 'concurrent_rpc', reads: [read, read] } + * | { type: 'cold_reconnect' } | { type: 'client_restart' } | { type: 'host_evict' } + */ +export function loadTrace(file) { + return JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); +} + +export const PUBLIC_TRACE_PATH = path.resolve(HERE, '../corpus/public-trace.json.br'); + +export function loadPublicTrace() { + return loadTrace(PUBLIC_TRACE_PATH); +} diff --git a/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/candidate/package.json b/questions/opt-device-link-delta-sync/v2/candidate/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v2/candidate/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v2/candidate/src/sync-protocol.mjs new file mode 100644 index 0000000..9a56c1c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/src/sync-protocol.mjs @@ -0,0 +1,708 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Authentic Cindy device-link baseline: + * - invokeDelta enabled ONLY on `local-db:sessions:list` with MAX_DEPTH = 2, + * MAX_DELTA_RATIO = 0.5 abort cliff, MAX_UNVERIFIED_DELTAS = 8 reset cliff, + * and single-slot base tracking. + * - historyViewDelta item-level replacement + SessionMessageReuse 64-hex SHA-256 + * manifest on `local-db:messages:view`. + * - Plain ifNoneMatch + gzipBase64 JSON on all other channels. + */ + +const INVOKE_DELTA_CHANNELS = new Set(['local-db:sessions:list']); +const MESSAGES_VIEW_CHANNEL = 'local-db:messages:view'; +const MAX_DEPTH = 2; +const MAX_DELTA_RATIO = 0.5; +const MAX_UNVERIFIED_DELTAS = 8; +const INVOKE_TRANSFER_MIN_GZIP_BYTES = 1024; +const MAX_REUSE_MANIFEST_ENTRIES = 256; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function sha256Hex(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex'); +} + +function encodeJsonBytes(obj) { + return encoder.encode(JSON.stringify(obj)); +} + +function decodeJsonBytes(bytes) { + return JSON.parse(decoder.decode(bytes)); +} + +function gzipBase64(text) { + return zlib.gzipSync(Buffer.from(text, 'utf8')).toString('base64'); +} + +function gunzipBase64(b64) { + return zlib.gunzipSync(Buffer.from(b64, 'base64')).toString('utf8'); +} + +function samePlainKeys(a, b) { + const left = Object.keys(a); + const right = Object.keys(b); + return left.length === right.length && left.every((k, i) => k === right[i]); +} + +function invokeDiff(base, next, depth) { + if (depth < MAX_DEPTH && Array.isArray(base) && Array.isArray(next)) { + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + let reused = 0; + let inPlace = base.length === next.length; + const a = next.map((element, pos) => { + const idx = byText.get(JSON.stringify(element)); + if (idx === undefined) { + inPlace = false; + return [element]; + } + reused += 1; + if (idx !== pos) inPlace = false; + return idx; + }); + if (inPlace) return undefined; + return reused > 0 ? { a } : { s: next }; + } + if (depth < MAX_DEPTH && isPlainObject(base) && isPlainObject(next) && samePlainKeys(base, next)) { + const o = {}; + let changed = false; + for (const key of Object.keys(next)) { + const child = invokeDiff(base[key], next[key], depth + 1); + if (child !== undefined) { + o[key] = child; + changed = true; + } + } + return changed ? { o } : undefined; + } + return JSON.stringify(base) === JSON.stringify(next) ? undefined : { s: next }; +} + +function invokeApply(base, patch, depth) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if (depth >= MAX_DEPTH) throw new Error('delta patch too deep'); + if ('a' in patch) { + return patch.a.map((entry) => (typeof entry === 'number' ? base[entry] : entry[0])); + } + if ('o' in patch) { + const result = {}; + for (const key of Object.keys(base)) { + const child = Object.prototype.hasOwnProperty.call(patch.o, key) ? patch.o[key] : undefined; + result[key] = invokeApply(base[key], child, depth + 1); + } + return result; + } + throw new Error('invalid delta patch'); +} + +function computeInvokePatch(baseText, nextText) { + const base = JSON.parse(baseText); + const next = JSON.parse(nextText); + const patch = invokeDiff(base, next, 0); + if (!patch || 's' in patch) return null; + if (JSON.stringify(patch).length > nextText.length * MAX_DELTA_RATIO) return null; + return patch; +} + +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function stripSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => + typeof rev === 'string' && rev.endsWith(suffix) ? rev.slice(0, -suffix.length) : rev, + ); +} + +function appendSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)); +} + +function isReusableMessage(row) { + return ( + isPlainObject(row) + && typeof row.id === 'string' + && row.id.length > 0 + && (row.role === 'assistant' || row.role === 'user') + && typeof row.remoteBodyVersion === 'string' + && /^[a-f0-9]{64}$/.test(row.remoteBodyVersion) + && isPlainObject(row.content) + && typeof row.content.text === 'string' + ); +} + +function mapMessageRows(value, fn) { + if (!isPlainObject(value) || !Array.isArray(value.items)) return value; + return { + ...value, + items: value.items.map((item) => { + if (isPlainObject(item) && item.type === 'messages' && Array.isArray(item.messages)) { + return { + ...item, + messages: item.messages.map((row) => (isPlainObject(row) ? fn(row) : row)), + }; + } + return item; + }), + }; +} + +function parseSessionArgs(argsKey) { + try { + const parsed = JSON.parse(argsKey); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +export function createHostSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // Single latest base per (channel, argsKey) for invokeDelta + const invokeBases = new Map(); + let invokeBaseBytes = 0; + + // Volatile historyViewDelta bases keyed by token + const historyBases = new Map(); + let historyBaseBytes = 0; + let tokenSeq = 0; + + function evictVolatileBases() { + invokeBases.clear(); + invokeBaseBytes = 0; + historyBases.clear(); + historyBaseBytes = 0; + } + + function rememberInvokeBase(key, tag, text) { + const prev = invokeBases.get(key); + if (prev) { + invokeBaseBytes -= prev.text.length; + invokeBases.delete(key); + } + if (text.length > maxCacheBytes / 2) return; + invokeBases.set(key, { tag, text }); + invokeBaseBytes += text.length; + while (invokeBases.size > 32 || invokeBaseBytes > maxCacheBytes / 2) { + const oldestKey = invokeBases.keys().next().value; + const oldest = invokeBases.get(oldestKey); + invokeBaseBytes -= oldest.text.length; + invokeBases.delete(oldestKey); + } + } + + function rememberHistoryBase(token, itemsJson) { + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + if (bytes > maxCacheBytes / 2) return false; + historyBases.set(token, { itemsJson, bytes }); + historyBaseBytes += bytes; + while (historyBases.size > 16 || historyBaseBytes > maxCacheBytes / 2) { + const oldestKey = historyBases.keys().next().value; + const oldest = historyBases.get(oldestKey); + historyBaseBytes -= oldest.bytes; + historyBases.delete(oldestKey); + } + return true; + } + + function encodeTransferEnvelope(value, ifNoneMatch, allowGzip) { + const text = JSON.stringify(value); + const tag = sha256Hex(text); + if (ifNoneMatch && ifNoneMatch === tag) { + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, notModified: true } }); + } + const utf8Bytes = Buffer.byteLength(text, 'utf8'); + if (allowGzip && utf8Bytes >= INVOKE_TRANSFER_MIN_GZIP_BYTES) { + const b64 = gzipBase64(text); + if (b64.length + 48 < utf8Bytes * 0.9) { + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, gzipBase64: b64 } }); + } + } + return encodeJsonBytes({ ok: true, result: value, transfer: { tag } }); + } + + function handleHistoryView(argsKey, req, groundTruthValue) { + const parsedArgs = parseSessionArgs(argsKey); + const isLatestPage = parsedArgs.before == null; + let payloadValue = groundTruthValue; + + // 1. Apply historyViewDelta if latest page and client opted in + if ( + isLatestPage + && req.historyDelta?.version === 1 + && isPlainObject(groundTruthValue) + && Array.isArray(groundTruthValue.items) + ) { + const suffix = + typeof groundTruthValue.revisionSuffix === 'string' + && groundTruthValue.revisionSuffix + && allWorkRevisionsEndWith(groundTruthValue.items, groundTruthValue.revisionSuffix) + ? groundTruthValue.revisionSuffix + : undefined; + const strippedJson = groundTruthValue.items.map((item) => JSON.stringify(stripSuffix(item, suffix))); + const baseEntry = req.historyDelta.base ? historyBases.get(req.historyDelta.base) : undefined; + let outItems = groundTruthValue.items; + let matchedBase; + + if (baseEntry) { + matchedBase = req.historyDelta.base; + const baseMap = new Map(); + for (let i = 0; i < baseEntry.itemsJson.length; i += 1) { + if (!baseMap.has(baseEntry.itemsJson[i])) baseMap.set(baseEntry.itemsJson[i], i); + } + const compressedItems = []; + let runStart = -1; + let runCount = 0; + const flushRun = () => { + if (runCount > 0) { + compressedItems.push({ type: 'same', from: runStart, count: runCount }); + runStart = -1; + runCount = 0; + } + }; + for (let i = 0; i < strippedJson.length; i += 1) { + const baseIdx = baseMap.get(strippedJson[i]); + if (baseIdx !== undefined) { + if (runCount > 0 && baseIdx === runStart + runCount) { + runCount += 1; + } else { + flushRun(); + runStart = baseIdx; + runCount = 1; + } + } else { + flushRun(); + compressedItems.push(groundTruthValue.items[i]); + } + } + flushRun(); + outItems = compressedItems; + } + + tokenSeq += 1; + const token = `hvd-${tokenSeq}`; + const stored = rememberHistoryBase(token, strippedJson); + payloadValue = { + ...groundTruthValue, + items: outItems, + historyDelta: { + version: 1, + ...(stored ? { token } : {}), + ...(matchedBase ? { base: matchedBase } : {}), + ...(suffix ? { revisionSuffix: suffix } : {}), + }, + }; + } + + // 2. Apply SessionMessageReuse body omission if client advertised known [id, sha256] pairs + if (req.messageBodies?.version === 1 && Array.isArray(req.messageBodies.known) && req.messageBodies.known.length > 0) { + const known = new Map(); + for (const pair of req.messageBodies.known) { + if (Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string') { + known.set(pair[0], pair[1]); + } + } + let strippedAny = false; + const strippedVal = mapMessageRows(payloadValue, (row) => { + if (isReusableMessage(row) && known.get(row.id) === row.remoteBodyVersion) { + strippedAny = true; + const { content: _c, ...rest } = row; + return rest; + } + return row; + }); + if (strippedAny) { + payloadValue = { format: 'message-bodies-v1', value: strippedVal }; + } + } + + return encodeTransferEnvelope(payloadValue, req.transfer?.ifNoneMatch, req.transfer?.gzip === 1); + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue }) { + const req = decodeJsonBytes(requestBytes); + + if (channel === MESSAGES_VIEW_CHANNEL) { + return handleHistoryView(argsKey, req, groundTruthValue); + } + + const text = JSON.stringify(groundTruthValue); + const tag = sha256Hex(text); + const transfer = req.transfer || {}; + + if (transfer.ifNoneMatch && transfer.ifNoneMatch === tag) { + if (transfer.delta === 1 && INVOKE_DELTA_CHANNELS.has(channel)) { + rememberInvokeBase(`${channel}\u0000${argsKey}`, tag, text); + } + return encodeJsonBytes({ ok: true, result: null, transfer: { tag, notModified: true } }); + } + + if (transfer.delta === 1 && INVOKE_DELTA_CHANNELS.has(channel)) { + const key = `${channel}\u0000${argsKey}`; + const base = invokeBases.get(key); + rememberInvokeBase(key, tag, text); + if (base && transfer.ifNoneMatch && base.tag === transfer.ifNoneMatch) { + const patch = computeInvokePatch(base.text, text); + if (patch) { + const patchText = JSON.stringify(patch); + const patchBytes = Buffer.byteLength(patchText, 'utf8'); + if (transfer.gzip === 1 && patchBytes >= INVOKE_TRANSFER_MIN_GZIP_BYTES) { + const b64 = gzipBase64(patchText); + if (b64.length + 16 < patchBytes * 0.9) { + return encodeJsonBytes({ + ok: true, + result: null, + transfer: { tag, delta: { base: base.tag, length: text.length, gzipBase64: b64 } }, + }); + } + } + return encodeJsonBytes({ + ok: true, + result: null, + transfer: { tag, delta: { base: base.tag, length: text.length, patch } }, + }); + } + } + } + + return encodeTransferEnvelope(groundTruthValue, transfer.ifNoneMatch, transfer.gzip === 1); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + const maxPersistentBodyEntries = options.maxPersistentBodyEntries ?? DEFAULT_MAX_PERSISTENT_BODY_ENTRIES; + + // Volatile caches (cleared on cold reconnect) + const invokeCache = new Map(); + let invokeCacheBytes = 0; + const historyCache = new Map(); + let historyCacheBytes = 0; + const inflight = new Map(); + + // Persistent immutable message body cache (SessionMessageReuse) + // key: `${sessionId}\u0000${msgId}` -> { sessionId, id, version, contentJson } + const persistentBodies = new Map(); + let persistentBodyBytes = 0; + + function loadPersistentState(bytes) { + persistentBodies.clear(); + persistentBodyBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const json = zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8'); + const rows = JSON.parse(json); + if (!Array.isArray(rows)) return; + for (const entry of rows) { + if (!entry || typeof entry.sessionId !== 'string' || typeof entry.id !== 'string') continue; + rememberPersistentBody(entry.sessionId, entry.id, entry.version, entry.contentJson); + } + } catch { + // Ignore corrupt persistent blob + } + } + + function rememberPersistentBody(sessionId, id, version, contentJson) { + const key = `${sessionId}\u0000${id}`; + const prev = persistentBodies.get(key); + if (prev) { + persistentBodyBytes -= prev.contentJson.length; + persistentBodies.delete(key); + } + if (contentJson.length > maxPersistentBytes / 2) return; + persistentBodies.set(key, { sessionId, id, version, contentJson }); + persistentBodyBytes += contentJson.length; + while (persistentBodies.size > maxPersistentBodyEntries || persistentBodyBytes > maxPersistentBytes) { + const oldestKey = persistentBodies.keys().next().value; + const oldest = persistentBodies.get(oldestKey); + persistentBodyBytes -= oldest.contentJson.length; + persistentBodies.delete(oldestKey); + } + } + + function exportPersistentState() { + const rows = Array.from(persistentBodies.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.shift(); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snapshot = exportPersistentState(); + invokeCache.clear(); + invokeCacheBytes = 0; + historyCache.clear(); + historyCacheBytes = 0; + inflight.clear(); + loadPersistentState(snapshot); + } + + function rememberInvokeCache(key, entry) { + const prev = invokeCache.get(key); + if (prev) { + invokeCacheBytes -= prev.text.length; + invokeCache.delete(key); + } + if (entry.text.length > maxCacheBytes / 2) return; + invokeCache.set(key, entry); + invokeCacheBytes += entry.text.length; + while (invokeCache.size > 32 || invokeCacheBytes > maxCacheBytes / 2) { + const oldestKey = invokeCache.keys().next().value; + const oldest = invokeCache.get(oldestKey); + invokeCacheBytes -= oldest.text.length; + invokeCache.delete(oldestKey); + } + } + + function rememberHistoryCache(key, entry) { + const prev = historyCache.get(key); + if (prev) { + historyCacheBytes -= prev.bytes; + historyCache.delete(key); + } + if (entry.bytes > maxCacheBytes / 2) return; + historyCache.set(key, entry); + historyCacheBytes += entry.bytes; + while (historyCache.size > 16 || historyCacheBytes > maxCacheBytes / 2) { + const oldestKey = historyCache.keys().next().value; + const oldest = historyCache.get(oldestKey); + historyCacheBytes -= oldest.bytes; + historyCache.delete(oldestKey); + } + } + + if (options.persistentState) { + loadPersistentState(options.persistentState); + } + + function beginRead({ readId, channel, argsKey }) { + const cacheKey = `${channel}\u0000${argsKey}`; + + if (channel === MESSAGES_VIEW_CHANNEL) { + const parsedArgs = parseSessionArgs(argsKey); + const sessionId = typeof parsedArgs.sessionId === 'string' ? parsedArgs.sessionId : ''; + const isLatestPage = parsedArgs.before == null; + const hvdKey = `${sessionId}\u0000latest`; + const hvdSnap = isLatestPage ? historyCache.get(hvdKey) : undefined; + + // Snapshot known bodies from persistent cache when no volatile historyDelta base exists + const bodySnap = new Map(); + const knownPairs = []; + if (!hvdSnap && sessionId) { + const allForSession = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) allForSession.push(entry); + } + const recent = allForSession.slice(-MAX_REUSE_MANIFEST_ENTRIES); + for (const entry of recent) { + bodySnap.set(entry.id, entry); + knownPairs.push([entry.id, entry.version]); + } + } + + const reqObj = { + transfer: { + gzip: 1, + }, + ...(isLatestPage + ? { historyDelta: { version: 1, ...(hvdSnap ? { base: hvdSnap.token } : {}) } } + : {}), + ...(knownPairs.length > 0 ? { messageBodies: { version: 1, known: knownPairs } } : {}), + }; + inflight.set(readId, { + channel, + cacheKey, + sessionId, + hvdKey, + hvdSnap, + bodySnap, + cachedTransfer: undefined, + }); + return encodeJsonBytes(reqObj); + } + + const cached = invokeCache.get(cacheKey); + const transfer = { gzip: 1 }; + // Simulate Cindy Mobile's MAX_UNVERIFIED_DELTAS = 8 reset cliff + if (cached && (cached.unverified ?? 0) < MAX_UNVERIFIED_DELTAS) { + transfer.ifNoneMatch = cached.tag; + } + if (INVOKE_DELTA_CHANNELS.has(channel)) { + transfer.delta = 1; + } + inflight.set(readId, { channel, cacheKey, cached }); + return encodeJsonBytes({ transfer }); + } + + function decodeTransfer(resp, cached, cacheKey) { + const transfer = resp.transfer || {}; + if (transfer.notModified) { + if (!cached || cached.tag !== transfer.tag) throw new Error('unexpected notModified'); + const val = JSON.parse(cached.text); + rememberInvokeCache(cacheKey, { tag: transfer.tag, text: cached.text, unverified: cached.unverified }); + return val; + } + if (transfer.delta) { + const delta = transfer.delta; + if (!cached || cached.tag !== delta.base) throw new Error('unexpected delta base'); + const patch = typeof delta.gzipBase64 === 'string' ? JSON.parse(gunzipBase64(delta.gzipBase64)) : delta.patch; + const value = invokeApply(JSON.parse(cached.text), patch, 0); + const text = JSON.stringify(value); + rememberInvokeCache(cacheKey, { + tag: transfer.tag, + text, + unverified: (cached.unverified ?? 0) + 1, + }); + return value; + } + let text; + let value; + if (typeof transfer.gzipBase64 === 'string') { + text = gunzipBase64(transfer.gzipBase64); + value = JSON.parse(text); + } else { + value = resp.result; + text = JSON.stringify(value); + } + if (transfer.tag) { + rememberInvokeCache(cacheKey, { tag: transfer.tag, text, unverified: 0 }); + } + return value; + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + inflight.delete(readId); + const resp = decodeJsonBytes(responseBytes); + + if (state.channel === MESSAGES_VIEW_CHANNEL) { + let decoded = decodeTransfer(resp, state.cachedTransfer, state.cacheKey); + + // 1. Restore SessionMessageReuse omitted message bodies + const packed = isPlainObject(decoded) && decoded.format === 'message-bodies-v1'; + const inner = packed ? decoded.value : decoded; + decoded = mapMessageRows(inner, (row) => { + let restored = row; + if (packed && !Object.prototype.hasOwnProperty.call(row, 'content')) { + const hit = state.bodySnap.get(row.id); + if (!hit || hit.version !== row.remoteBodyVersion) { + throw new Error(`Missing persistent body for ${row.id}`); + } + restored = { ...row, content: JSON.parse(hit.contentJson) }; + } + if (state.sessionId && isReusableMessage(restored)) { + rememberPersistentBody( + state.sessionId, + restored.id, + restored.remoteBodyVersion, + JSON.stringify(restored.content), + ); + } + return restored; + }); + + // 2. Restore historyViewDelta `same` runs + if (isPlainObject(decoded) && Array.isArray(decoded.items) && decoded.historyDelta?.version === 1) { + const { historyDelta: delta, ...page } = decoded; + const suffix = typeof delta.revisionSuffix === 'string' && delta.revisionSuffix ? delta.revisionSuffix : undefined; + const items = []; + for (const item of decoded.items) { + if (isPlainObject(item) && item.type === 'same') { + if (!state.hvdSnap || delta.base !== state.hvdSnap.token) { + throw new Error('historyViewDelta base mismatch'); + } + for (let i = item.from; i < item.from + item.count; i += 1) { + items.push(appendSuffix(JSON.parse(state.hvdSnap.itemsJson[i]), suffix)); + } + } else { + items.push(item); + } + } + const restoredPage = { ...page, items }; + if (typeof delta.token === 'string') { + const itemsJson = items.map((it) => JSON.stringify(stripSuffix(it, suffix))); + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + rememberHistoryCache(state.hvdKey, { token: delta.token, itemsJson, bytes }); + } + return { done: true, value: restoredPage }; + } + return { done: true, value: decoded }; + } + + const value = decodeTransfer(resp, state.cached, state.cacheKey); + return { done: true, value }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v2/candidate/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v2/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..dfd2fa3 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/candidate/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated parity check on the first part of the public real workload', async () => { + const fullTrace = loadPublicTrace(); + // The first 60 steps: open a task, stream a live turn, reconnect, list + read-ahead. + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/CONTRACT.md b/questions/opt-device-link-delta-sync/v2/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..13da075 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/CONTRACT.md @@ -0,0 +1,102 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (one of the Cindy channels in the recording, or any other channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +Lifecycle steps between reads: +- `cold_reconnect`: the client exports `persistentState` (checked against `maxPersistentBytes`), then **both** the Client and the Host child processes are terminated and respawned; the new Client receives only `{ persistentState }`, the new Host starts empty. +- `client_restart`: the same for the Client only; the Host process (and its volatile state) keeps running. +- `host_evict`: the Host process alone is terminated and respawned; the Client stays warm. + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 20s` for the full held-out recording, including process spawns). +4. **Generalization**: The score comes from an unseen held-out recording of different real tasks (different de-identification key, different text, ids and sizes). A separate synthetic stress trace with many cold reconnects, host evictions and concurrent stale-base reads is run as a correctness gate only. Do not hardcode trace strings or schema assumptions that break on unseen payloads. + +## 6. Workload Provenance + +Both recordings were made by running Cindy's transfer-baseline scenario (`apps/desktop/src/test/transfer-baseline`, phone profile) at the source commit in `question.json`, with its synthetic content swapped for real de-identified tasks and every remote RPC recorded as the Desktop handler returned it. History pages are recorded complete (the product's own `historyDelta` option removed), and product protocol options (`historyDelta`, `messageBodies`) are removed from the request arguments: they belong to the protocol you are replacing. The tasks were de-identified before recording (harness prompt text replaced by same-shape surrogate text; paths, user name, e-mail and account ids pseudonymized). Tool results that the database had compacted after archiving were restored from the engine's own transcript, as the live database held them; plugin-engine tasks keep the compacted marker. diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v2/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..be264f2 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,11 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic two-process replay of the public real recording (162 reads, 10 channels) reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, reduction vs raw JSON and the product's own measured wire bytes for the same reads +- Data: `corpus/public-trace.json.br` (brotli-compressed JSON, loaded by `lib/trace-loader.mjs`). The held-out recording used for the score is not shipped. diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/TASK.md b/questions/opt-device-link-delta-sync/v2/controls/incomplete/TASK.md new file mode 100644 index 0000000..5d27a96 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC sync protocol (`src/sync-protocol.mjs`), extracted from the desktop-to-mobile remote session path (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). When a user follows a task from the phone, every read below crosses a metered, often cellular, link; fewer bytes mean faster pages and less data used. + +## What the real workload looks like + +`corpus/public-trace.json.br` is a recorded phone session, not a generated one. It was captured by running Cindy's own transfer-baseline scenario (real `DeviceLinkClient`, real relay, real Desktop `local-db:*` handlers on a migrated SQLite database, real phone history-view controller and recovery core) with the host database filled from 13 real, de-identified Cindy tasks in which Claude Code, Codex and a plugin engine worked on open-source code. Live turns stream real prose and real tool calls with their real results. + +It holds 162 reads (~3.4 MB of complete JSON) on 10 channels, in the order the host received them: + +- `local-db:messages:view` (56 reads, most of the bytes): the history page the phone renders, re-read after every streamed step of a live turn, after reconnects, and as read-ahead for the five most recent tasks. +- `local-db:messages:work-details`, `local-db:sessions:list`, `local-db:sessions:get` and several small status reads (`maker:list-active`, `maker:input:get-projection`, `maker:goal:get-status`, `maker:get-pending-interactions`, `local-db:messages:view-intent`, `sidebar-settings:get-project-aliases`). +- Lifecycle events: a new host and phone process between scenario runs (`cold_reconnect`), a new phone process on the same host (`client_restart`), and reads that were in flight together (`concurrent_rpc`). + +The baseline in `src/` follows today's product strategy at the payload level: it only diffs `local-db:sessions:list` (depth 2), only reuses whole identical history items, gzips everything else independently, and keeps no history across process restarts. On the public recording it sends 1,022,246 B. For reference, the product itself put 1,081,479 B on the WebSocket for the same reads, a number that also includes its message envelopes and transport framing, which this question does not count. + +For orientation: compressing each connection's reads in order with Brotli-11, with full shared history inside the connection and nothing kept across restarts, takes 178,329 B on the public recording. Using persisted state across restarts can go lower still. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every read, including reads after restarts and concurrent reads built on a stale base. +- Respect **strict two-process isolation**: Host and Client run in separate Node.js child processes and communicate **only** through `Uint8Array` wire frames. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return at most `maxPersistentBytes` (default `2 MiB`), and every RPC must finish within `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended goal**: drive `total_wire_bytes` (all upstream and downstream bytes of all rounds of all RPCs) as low as possible on an **unseen held-out recording** made the same way from 13 different real tasks, de-identified with a different key. +- Run `npm test` and `npm run bench` to verify parity and measure your reduction. +- Record your analysis, protocol design, trade-offs and verified results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/bench/workload.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..126dcd4 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark() { + const trace = loadPublicTrace(); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + trace: trace.name, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + product_rpc_wire_bytes: trace.meta.productRpcWireBytes, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + client_restarts: trace.meta.clientRestartCount, + concurrent_pairs: trace.meta.concurrentPairCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/corpus/public-trace.json.br b/questions/opt-device-link-delta-sync/v2/controls/incomplete/corpus/public-trace.json.br new file mode 100644 index 0000000..e196d5c Binary files /dev/null and b/questions/opt-device-link-delta-sync/v2/controls/incomplete/corpus/public-trace.json.br differ diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/rpc-harness.mjs new file mode 100644 index 0000000..fa01758 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/rpc-harness.mjs @@ -0,0 +1,306 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'client_restart') { + // A new controller process on the same running host (e.g. the phone app relaunched): + // kill & respawn Client from its persisted state only; Host keeps its volatile state. + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/trace-loader.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/trace-loader.mjs new file mode 100644 index 0000000..3c832bc --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/trace-loader.mjs @@ -0,0 +1,22 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +/** + * Load a recorded RPC workload (brotli-compressed JSON: { name, meta, steps }). + * Steps: { type: 'rpc', id, channel, argsKey, groundTruthValue } + * | { type: 'concurrent_rpc', reads: [read, read] } + * | { type: 'cold_reconnect' } | { type: 'client_restart' } | { type: 'host_evict' } + */ +export function loadTrace(file) { + return JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); +} + +export const PUBLIC_TRACE_PATH = path.resolve(HERE, '../corpus/public-trace.json.br'); + +export function loadPublicTrace() { + return loadTrace(PUBLIC_TRACE_PATH); +} diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/package.json b/questions/opt-device-link-delta-sync/v2/controls/incomplete/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/src/sync-protocol.mjs new file mode 100644 index 0000000..c12dc5b --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/src/sync-protocol.mjs @@ -0,0 +1,645 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Incomplete optimization control: + * - Extends invokeDelta (MAX_DEPTH = 2, row-level replacement) across ALL channels. + * - Removes MAX_UNVERIFIED_DELTAS = 8 reset cliff and raises MAX_DELTA_RATIO to 0.85. + * - Uses binary gzip framing instead of gzipBase64 inside JSON. + * Still misses: + * - Recursive field-level diff (replaces whole session/provider/schedule/message rows). + * - String-append / streaming text diff. + * - Multi-base host snapshot retention (falls back to full on concurrent stale-base reads). + * - Compact cold-cache reconciliation (still sends 64-hex SHA-256 manifest on messages:view, + * no cold reuse on other channels). + */ + +const MESSAGES_VIEW_CHANNEL = 'local-db:messages:view'; +const MAX_DEPTH = 2; +const MAX_DELTA_RATIO = 0.85; +const MAX_REUSE_MANIFEST_ENTRIES = 256; + +const FRAME_PLAIN = 0; +const FRAME_GZIP = 1; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function sha256Hex(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex'); +} + +function packFrame(obj) { + const raw = Buffer.from(JSON.stringify(obj), 'utf8'); + if (raw.byteLength >= 128) { + const gz = zlib.gzipSync(raw, { level: 9 }); + if (gz.byteLength + 1 < raw.byteLength) { + const out = new Uint8Array(gz.byteLength + 1); + out[0] = FRAME_GZIP; + out.set(gz, 1); + return out; + } + } + const out = new Uint8Array(raw.byteLength + 1); + out[0] = FRAME_PLAIN; + out.set(raw, 1); + return out; +} + +function unpackFrame(bytes) { + const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const tag = buf[0]; + const body = buf.subarray(1); + const raw = tag === FRAME_GZIP ? zlib.gunzipSync(body) : body; + return JSON.parse(raw.toString('utf8')); +} + +function samePlainKeys(a, b) { + const left = Object.keys(a); + const right = Object.keys(b); + return left.length === right.length && left.every((k, i) => k === right[i]); +} + +function shallowDiff(base, next, depth) { + if (depth < MAX_DEPTH && Array.isArray(base) && Array.isArray(next)) { + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + let reused = 0; + let inPlace = base.length === next.length; + const a = next.map((el, pos) => { + const idx = byText.get(JSON.stringify(el)); + if (idx === undefined) { + inPlace = false; + return [el]; + } + reused += 1; + if (idx !== pos) inPlace = false; + return idx; + }); + if (inPlace) return undefined; + return reused > 0 ? { a } : { s: next }; + } + if (depth < MAX_DEPTH && isPlainObject(base) && isPlainObject(next) && samePlainKeys(base, next)) { + const o = {}; + let changed = false; + for (const key of Object.keys(next)) { + const child = shallowDiff(base[key], next[key], depth + 1); + if (child !== undefined) { + o[key] = child; + changed = true; + } + } + return changed ? { o } : undefined; + } + return JSON.stringify(base) === JSON.stringify(next) ? undefined : { s: next }; +} + +function shallowApply(base, patch, depth) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if (depth >= MAX_DEPTH) throw new Error('patch too deep'); + if ('a' in patch) { + return patch.a.map((entry) => (typeof entry === 'number' ? base[entry] : entry[0])); + } + if ('o' in patch) { + const out = {}; + for (const key of Object.keys(base)) { + const child = Object.prototype.hasOwnProperty.call(patch.o, key) ? patch.o[key] : undefined; + out[key] = shallowApply(base[key], child, depth + 1); + } + return out; + } + throw new Error('invalid patch'); +} + +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function stripSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => + typeof rev === 'string' && rev.endsWith(suffix) ? rev.slice(0, -suffix.length) : rev, + ); +} + +function appendSuffix(item, suffix) { + if (!suffix) return item; + return swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)); +} + +function isReusableMessage(row) { + return ( + isPlainObject(row) + && typeof row.id === 'string' + && row.id.length > 0 + && (row.role === 'assistant' || row.role === 'user') + && typeof row.remoteBodyVersion === 'string' + && /^[a-f0-9]{64}$/.test(row.remoteBodyVersion) + && isPlainObject(row.content) + && typeof row.content.text === 'string' + ); +} + +function mapMessageRows(value, fn) { + if (!isPlainObject(value) || !Array.isArray(value.items)) return value; + return { + ...value, + items: value.items.map((item) => { + if (isPlainObject(item) && item.type === 'messages' && Array.isArray(item.messages)) { + return { + ...item, + messages: item.messages.map((row) => (isPlainObject(row) ? fn(row) : row)), + }; + } + return item; + }), + }; +} + +function parseArgs(argsKey) { + try { + const parsed = JSON.parse(argsKey); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +export function createHostSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // Keep last 2 snapshots per (channel, argsKey) (still MAX_DEPTH=2 row replacement, gzip, 64-hex cold manifest) + const bases = new Map(); + let baseBytes = 0; + const historyBases = new Map(); + let historyBytes = 0; + let tokenSeq = 0; + + function evictVolatileBases() { + bases.clear(); + baseBytes = 0; + historyBases.clear(); + historyBytes = 0; + } + + function rememberBase(key, tag, text) { + if (text.length > maxCacheBytes / 2) return; + let list = bases.get(key); + if (!list) { + list = []; + bases.set(key, list); + } else { + bases.delete(key); + bases.set(key, list); + } + const existing = list.findIndex((e) => e.tag === tag); + if (existing >= 0) { + const [e] = list.splice(existing, 1); + list.push(e); + return; + } + list.push({ tag, text }); + baseBytes += text.length; + while (list.length > 2) { + const dropped = list.shift(); + baseBytes -= dropped.text.length; + } + while (bases.size > 32 || baseBytes > maxCacheBytes / 2) { + const oldestKey = bases.keys().next().value; + const oldestList = bases.get(oldestKey); + for (const e of oldestList) baseBytes -= e.text.length; + bases.delete(oldestKey); + } + } + + function findBase(key, tag) { + const list = bases.get(key); + if (!list) return undefined; + for (let i = list.length - 1; i >= 0; i -= 1) { + if (list[i].tag === tag) return list[i]; + } + return undefined; + } + + function rememberHistoryBase(token, itemsJson) { + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + if (bytes > maxCacheBytes / 2) return false; + historyBases.set(token, { itemsJson, bytes }); + historyBytes += bytes; + while (historyBases.size > 16 || historyBytes > maxCacheBytes / 2) { + const oldestKey = historyBases.keys().next().value; + const oldest = historyBases.get(oldestKey); + historyBytes -= oldest.bytes; + historyBases.delete(oldestKey); + } + return true; + } + + function handleHistoryView(argsKey, req, groundTruthValue) { + const parsedArgs = parseArgs(argsKey); + const isLatestPage = parsedArgs.before == null; + let payloadValue = groundTruthValue; + + if ( + isLatestPage + && req.hvd + && isPlainObject(groundTruthValue) + && Array.isArray(groundTruthValue.items) + ) { + const suffix = + typeof groundTruthValue.revisionSuffix === 'string' + && groundTruthValue.revisionSuffix + && allWorkRevisionsEndWith(groundTruthValue.items, groundTruthValue.revisionSuffix) + ? groundTruthValue.revisionSuffix + : undefined; + const strippedJson = groundTruthValue.items.map((item) => JSON.stringify(stripSuffix(item, suffix))); + const baseEntry = req.hvd.base ? historyBases.get(req.hvd.base) : undefined; + let outItems = groundTruthValue.items; + let matchedBase; + + if (baseEntry) { + matchedBase = req.hvd.base; + const baseMap = new Map(); + for (let i = 0; i < baseEntry.itemsJson.length; i += 1) { + if (!baseMap.has(baseEntry.itemsJson[i])) baseMap.set(baseEntry.itemsJson[i], i); + } + const compressedItems = []; + let runStart = -1; + let runCount = 0; + const flush = () => { + if (runCount > 0) { + compressedItems.push({ type: 'same', from: runStart, count: runCount }); + runStart = -1; + runCount = 0; + } + }; + for (let i = 0; i < strippedJson.length; i += 1) { + const baseIdx = baseMap.get(strippedJson[i]); + if (baseIdx !== undefined) { + if (runCount > 0 && baseIdx === runStart + runCount) runCount += 1; + else { + flush(); + runStart = baseIdx; + runCount = 1; + } + } else { + flush(); + compressedItems.push(groundTruthValue.items[i]); + } + } + flush(); + outItems = compressedItems; + } else if (req.hvd.base && req.hasBodies) { + return packFrame({ kind: 'hvd-miss' }); + } + + tokenSeq += 1; + const token = `h-${tokenSeq}`; + const stored = rememberHistoryBase(token, strippedJson); + payloadValue = { + ...groundTruthValue, + items: outItems, + _hvd: { + ...(stored ? { token } : {}), + ...(matchedBase ? { base: matchedBase } : {}), + ...(suffix ? { suffix } : {}), + }, + }; + } + + if (Array.isArray(req.knownBodies) && req.knownBodies.length > 0) { + const known = new Map(req.knownBodies); + let strippedAny = false; + const strippedVal = mapMessageRows(payloadValue, (row) => { + if (isReusableMessage(row) && known.get(row.id) === row.remoteBodyVersion) { + strippedAny = true; + const { content: _c, ...rest } = row; + return rest; + } + return row; + }); + if (strippedAny) { + return packFrame({ kind: 'hvd-bodies', value: strippedVal }); + } + } + + return packFrame({ kind: 'hvd', value: payloadValue }); + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue }) { + const req = unpackFrame(requestBytes); + + if (channel === MESSAGES_VIEW_CHANNEL) { + return handleHistoryView(argsKey, req, groundTruthValue); + } + + const text = JSON.stringify(groundTruthValue); + const tag = sha256Hex(text).slice(0, 24); + const key = `${channel}\u0000${argsKey}`; + const base = req.base ? findBase(key, req.base) : undefined; + rememberBase(key, tag, text); + + if (req.base && req.base === tag) { + return packFrame({ kind: 'same', tag }); + } + + if (base && req.base && base.tag === req.base) { + const patch = shallowDiff(JSON.parse(base.text), groundTruthValue, 0); + if (patch && !('s' in patch)) { + const deltaFrame = packFrame({ kind: 'delta', tag, base: base.tag, patch }); + const fullFrame = packFrame({ kind: 'full', tag, value: groundTruthValue }); + return deltaFrame.byteLength <= fullFrame.byteLength ? deltaFrame : fullFrame; + } + } + + return packFrame({ kind: 'full', tag, value: groundTruthValue }); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + const maxPersistentBodyEntries = options.maxPersistentBodyEntries ?? DEFAULT_MAX_PERSISTENT_BODY_ENTRIES; + + const cache = new Map(); + let cacheBytes = 0; + const historyCache = new Map(); + let historyBytes = 0; + const inflight = new Map(); + + const persistentBodies = new Map(); + let persistentBodyBytes = 0; + + function loadPersistentState(bytes) { + persistentBodies.clear(); + persistentBodyBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const rows = JSON.parse(zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8')); + if (!Array.isArray(rows)) return; + for (const e of rows) { + if (e && typeof e.sessionId === 'string' && typeof e.id === 'string') { + rememberBody(e.sessionId, e.id, e.version, e.contentJson); + } + } + } catch { + // ignore + } + } + + function rememberBody(sessionId, id, version, contentJson) { + const key = `${sessionId}\u0000${id}`; + const prev = persistentBodies.get(key); + if (prev) { + persistentBodyBytes -= prev.contentJson.length; + persistentBodies.delete(key); + } + if (contentJson.length > maxPersistentBytes / 2) return; + persistentBodies.set(key, { sessionId, id, version, contentJson }); + persistentBodyBytes += contentJson.length; + while (persistentBodies.size > maxPersistentBodyEntries || persistentBodyBytes > maxPersistentBytes) { + const oldestKey = persistentBodies.keys().next().value; + const oldest = persistentBodies.get(oldestKey); + persistentBodyBytes -= oldest.contentJson.length; + persistentBodies.delete(oldestKey); + } + } + + function exportPersistentState() { + const rows = Array.from(persistentBodies.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.shift(); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8')); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snap = exportPersistentState(); + cache.clear(); + cacheBytes = 0; + historyCache.clear(); + historyBytes = 0; + inflight.clear(); + loadPersistentState(snap); + } + + function rememberCache(key, tag, text) { + const prev = cache.get(key); + if (prev) { + cacheBytes -= prev.text.length; + cache.delete(key); + } + if (text.length > maxCacheBytes / 2) return; + cache.set(key, { tag, text }); + cacheBytes += text.length; + while (cache.size > 32 || cacheBytes > maxCacheBytes / 2) { + const oldestKey = cache.keys().next().value; + const oldest = cache.get(oldestKey); + cacheBytes -= oldest.text.length; + cache.delete(oldestKey); + } + } + + function rememberHistory(key, entry) { + const prev = historyCache.get(key); + if (prev) { + historyBytes -= prev.bytes; + historyCache.delete(key); + } + if (entry.bytes > maxCacheBytes / 2) return; + historyCache.set(key, entry); + historyBytes += entry.bytes; + while (historyCache.size > 16 || historyBytes > maxCacheBytes / 2) { + const oldestKey = historyCache.keys().next().value; + const oldest = historyCache.get(oldestKey); + historyBytes -= oldest.bytes; + historyCache.delete(oldestKey); + } + } + + if (options.persistentState) loadPersistentState(options.persistentState); + + function beginRead({ readId, channel, argsKey }) { + const key = `${channel}\u0000${argsKey}`; + if (channel === MESSAGES_VIEW_CHANNEL) { + const parsedArgs = parseArgs(argsKey); + const sessionId = typeof parsedArgs.sessionId === 'string' ? parsedArgs.sessionId : ''; + const isLatestPage = parsedArgs.before == null; + const hvdKey = `${sessionId}\u0000latest`; + const hvdSnap = isLatestPage ? historyCache.get(hvdKey) : undefined; + const bodySnap = new Map(); + const knownBodies = []; + if (!hvdSnap && sessionId) { + const list = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) list.push(entry); + } + for (const entry of list.slice(-MAX_REUSE_MANIFEST_ENTRIES)) { + bodySnap.set(entry.id, entry); + knownBodies.push([entry.id, entry.version]); + } + } + inflight.set(readId, { channel, key, sessionId, hvdKey, hvdSnap, bodySnap, isLatestPage }); + let hasBodies = false; + if (hvdSnap && sessionId) { + for (const entry of persistentBodies.values()) { + if (entry.sessionId === sessionId) { hasBodies = true; break; } + } + } + return packFrame({ + ...(isLatestPage ? { hvd: hvdSnap ? { base: hvdSnap.token } : {} } : {}), + ...(hasBodies ? { hasBodies: 1 } : {}), + ...(knownBodies.length > 0 ? { knownBodies } : {}), + }); + } + + const cached = cache.get(key); + inflight.set(readId, { channel, key, cached }); + return packFrame(cached ? { base: cached.tag } : {}); + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + const resp = unpackFrame(responseBytes); + + if (resp.kind === 'hvd-miss') { + const bodySnap = new Map(); + const knownBodies = []; + const list = []; + for (const entry of persistentBodies.values()) { + if (entry.sessionId === state.sessionId) list.push(entry); + } + for (const entry of list.slice(-MAX_REUSE_MANIFEST_ENTRIES)) { + bodySnap.set(entry.id, entry); + knownBodies.push([entry.id, entry.version]); + } + state.hvdSnap = undefined; + state.bodySnap = bodySnap; + return { + done: false, + nextRequestBytes: packFrame({ + ...(state.isLatestPage ? { hvd: {} } : {}), + ...(knownBodies.length > 0 ? { knownBodies } : {}), + }), + }; + } + + inflight.delete(readId); + + if (state.channel === MESSAGES_VIEW_CHANNEL) { + const packed = resp.kind === 'hvd-bodies'; + let decoded = mapMessageRows(resp.value, (row) => { + let restored = row; + if (packed && !Object.prototype.hasOwnProperty.call(row, 'content')) { + const hit = state.bodySnap.get(row.id); + if (!hit || hit.version !== row.remoteBodyVersion) { + throw new Error(`Missing body for ${row.id}`); + } + restored = { ...row, content: JSON.parse(hit.contentJson) }; + } + if (state.sessionId && isReusableMessage(restored)) { + rememberBody(state.sessionId, restored.id, restored.remoteBodyVersion, JSON.stringify(restored.content)); + } + return restored; + }); + + if (isPlainObject(decoded) && Array.isArray(decoded.items) && decoded._hvd) { + const { _hvd: delta, ...page } = decoded; + const suffix = typeof delta.suffix === 'string' && delta.suffix ? delta.suffix : undefined; + const items = []; + for (const item of decoded.items) { + if (isPlainObject(item) && item.type === 'same') { + if (!state.hvdSnap || delta.base !== state.hvdSnap.token) throw new Error('hvd base mismatch'); + for (let i = item.from; i < item.from + item.count; i += 1) { + items.push(appendSuffix(JSON.parse(state.hvdSnap.itemsJson[i]), suffix)); + } + } else { + items.push(item); + } + } + const restoredPage = { ...page, items }; + if (typeof delta.token === 'string') { + const itemsJson = items.map((it) => JSON.stringify(stripSuffix(it, suffix))); + let bytes = 0; + for (const s of itemsJson) bytes += s.length; + rememberHistory(state.hvdKey, { token: delta.token, itemsJson, bytes }); + } + return { done: true, value: restoredPage }; + } + return { done: true, value: decoded }; + } + + if (resp.kind === 'same') { + const val = JSON.parse(state.cached.text); + rememberCache(state.key, resp.tag, state.cached.text); + return { done: true, value: val }; + } + if (resp.kind === 'delta') { + const val = shallowApply(JSON.parse(state.cached.text), resp.patch, 0); + rememberCache(state.key, resp.tag, JSON.stringify(val)); + return { done: true, value: val }; + } + rememberCache(state.key, resp.tag, JSON.stringify(resp.value)); + return { done: true, value: resp.value }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v2/controls/incomplete/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v2/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..dfd2fa3 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated parity check on the first part of the public real workload', async () => { + const fullTrace = loadPublicTrace(); + // The first 60 steps: open a task, stream a live turn, reconnect, list + read-ahead. + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-device-link-delta-sync/v2/question.json b/questions/opt-device-link-delta-sync/v2/question.json new file mode 100644 index 0000000..8ed8867 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/question.json @@ -0,0 +1,41 @@ +{ + "id": "opt-device-link-delta-sync", + "revision": "v2", + "scoringVersion": "metric-v1", + "title": "跨设备 RPC 结构化增量同步与冷缓存调和优化", + "status": "calibrated", + "changeNote": "v2: replaces the synthetic trace generator with recorded real phone sessions. Cindy's own transfer-baseline scenario (real DeviceLinkClient, relay, Desktop local-db handlers, phone history-view controller and recovery core; phone profile) was run with its synthetic content swapped for 13 real de-identified tasks per split (the opt-cshare-compression v2 corpora: Claude Code, Codex and a plugin engine on open-source code), and every RPC was recorded as the handler returned it (history pages complete, product protocol options removed from the arguments). Public: 162 reads / 3.4 MB; held-out: 164 reads / 1.7 MB from different tasks and a different key. Lifecycle: new host+phone between runs (cold_reconnect), new phone process on the same host (client_restart), concurrent in-flight pairs. The synthetic generator remains only as a gate-only stress trace. Baseline = today's strategy (list-only depth-2 diff, identical-item reuse, per-read gzip) on the held-out recording; target = the per-connection shared-history floor (Brotli-11 of each connection's reads in order, reset at every restart) plus 2 B per read; going below it needs persisted state across restarts.", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "wire_efficiency", + "weight": "1", + "mode": "metric", + "gate": [ + "gate_exact_json_parity", + "gate_process_isolation", + "gate_reconnect_and_drift", + "gate_wire_sanity" + ], + "metric": { + "id": "total_wire_bytes", + "label": "Held-out real phone session wire bytes", + "unit": "B", + "direction": "lower", + "baseline": 447183, + "target": 123500, + "scale": "log" + } + } + ] +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/CONTRACT.md b/questions/opt-device-link-delta-sync/v2/reference/CONTRACT.md new file mode 100644 index 0000000..13da075 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/CONTRACT.md @@ -0,0 +1,102 @@ +# Protocol & Evaluation Contract + +This contract defines the required exports, wire-frame exchange loop, isolation boundaries, and correctness invariants for `src/sync-protocol.mjs`. Within these boundaries, **you have full freedom over the wire format, diffing algorithm, string/binary encoding, compression, dictionary seeding, and single- or multi-round cold-cache reconciliation protocol**. + +## 1. Required Exports (`src/sync-protocol.mjs`) + +- `PROTOCOL_MAX_ROUNDS` (`4`) +- `DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY` (`8`) +- `DEFAULT_MAX_CACHE_BYTES` (`4 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BYTES` (`2 * 1024 * 1024`) +- `DEFAULT_MAX_PERSISTENT_BODY_ENTRIES` (`512`) +- `createHostSyncEndpoint(options?)` +- `createClientSyncEndpoint(options?)` + +You may add helper `.mjs` modules inside `src/` and import them relatively from `src/sync-protocol.mjs`. + +## 2. Host Endpoint Interface + +```js +const host = createHostSyncEndpoint({ + maxBaseSnapshotsPerKey: 8, // default 8 + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB +}); +``` + +- `host.handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round }) => Uint8Array` + - `channel`: `string` (one of the Cindy channels in the recording, or any other channel name). + - `argsKey`: `string` (canonical serialized request arguments). + - `requestBytes`: `Uint8Array` produced by the client for this `round` (`0 <= round < PROTOCOL_MAX_ROUNDS`). + - `groundTruthValue`: any JSON-serializable JavaScript value (must **not** be mutated). Across multiple rounds of the same RPC read, `groundTruthValue` is the same immutable snapshot. + - `round`: integer in `[0, PROTOCOL_MAX_ROUNDS - 1]`. + - Must return a `Uint8Array` (or Node `Buffer`) containing the response wire frame. +- `host.evictVolatileBases() => void` + - Drops all volatile in-memory base snapshots and sync state. In the isolated evaluator, host volatile-base eviction is enforced by **terminating and respawning the Host child process** with fresh state. + +## 3. Client Endpoint Interface + +```js +const client = createClientSyncEndpoint({ + maxCacheBytes: 4 * 1024 * 1024, // default 4 MiB + maxPersistentBytes: 2 * 1024 * 1024, // default 2 MiB + maxPersistentBodyEntries: 512, // default 512 + persistentState: null, // optional Uint8Array restored after cold reconnect +}); +``` + +- `client.beginRead({ readId, channel, argsKey }) => Uint8Array` + - Starts a read identified by unique string `readId` and returns the round-0 `requestBytes` (`Uint8Array`). + - Multiple reads may be in flight concurrently (e.g., `beginRead(r1)` then `beginRead(r2)` before `receiveResponse(r1)`). +- `client.receiveResponse({ readId, channel, argsKey, responseBytes, round }) => { done: true, value } | { done: false, nextRequestBytes: Uint8Array }` + - Consumes `responseBytes` (`Uint8Array`) from the host for `readId` at `round`. + - Return `{ done: true, value }` when the complete RPC result has been reconstructed. + - Return `{ done: false, nextRequestBytes }` (with `nextRequestBytes instanceof Uint8Array`) to perform another protocol round (`round + 1`, up to `PROTOCOL_MAX_ROUNDS = 4` total rounds: `round = 0, 1, 2, 3`). On `round === 3`, the client **must** return `{ done: true, value }`. + - Note: **Every byte** of every `requestBytes`, `nextRequestBytes`, and `responseBytes` across all rounds is counted toward `total_wire_bytes`. +- `client.exportPersistentState() => Uint8Array` + - Serializes the client's persistent disk cache into a `Uint8Array` of at most `maxPersistentBytes` bytes (`<= 2 MiB` by default). +- `client.simulateColdReconnect() => void` + - Clears all volatile in-memory bases and pending reads, reloading only from `exportPersistentState()`. + - In the isolated evaluator, mobile cold reconnect is enforced by **exporting `persistentState`, verifying `persistentState.byteLength <= maxPersistentBytes`, terminating and respawning the Client child process with only `{ persistentState }`, and resetting/respawning the Host child process** (so neither side shares volatile connection state). + +## 4. Wire Exchange Loop (Exact Harness Semantics) + +For a normal RPC read: +```js +let round = 0; +let req = client.beginRead({ readId, channel, argsKey }); +while (true) { + totalWireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + totalWireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + break; + } + round += 1; + assert(round < PROTOCOL_MAX_ROUNDS); + req = step.nextRequestBytes; +} +``` + +Lifecycle steps between reads: +- `cold_reconnect`: the client exports `persistentState` (checked against `maxPersistentBytes`), then **both** the Client and the Host child processes are terminated and respawned; the new Client receives only `{ persistentState }`, the new Host starts empty. +- `client_restart`: the same for the Client only; the Host process (and its volatile state) keeps running. +- `host_evict`: the Host process alone is terminated and respawned; the Client stays warm. + +For a concurrent in-flight stale-base pair `(r1, r2)`: +1. Client calls `req1 = beginRead(r1)` and `req2 = beginRead(r2)` **before** receiving either response. +2. Host serves `res1 = handleFrame(r1, groundTruth1, round=0)` and then `res2 = handleFrame(r2, groundTruth2, round=0)` (both round-0 requests carry the older pre-`r1` base!). +3. Client finishes `r1` (including any follow-up rounds `1..3` if `done === false`) and then finishes `r2` (including any follow-up rounds `1..3` if `done === false`). +4. Both `r1` and `r2` must reconstruct exact `deepStrictEqual` copies of `groundTruth1` and `groundTruth2`. + +## 5. Correctness, Isolation & Resource Invariants + +1. **Exact JSON Parity**: Every reconstructed `value` must satisfy `assert.deepStrictEqual(value, groundTruthValue)` — preserving exact primitive types (`null`, booleans, numbers including `0`/`-0`-normalized JSON numbers and floats, empty strings, Unicode CJK/emoji), arrays (including empty arrays and element order), nested objects (including empty objects and plain keys such as `"constructor"`, `"toString"`, `"valueOf"`, `"hasOwnProperty"`). +2. **Physical Two-Process Isolation**: In evaluation, Host runs in Child Process A and Client runs in Child Process B. Only base64-encoded wire frames pass between them. Only pure compute built-ins (`node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert`) and relative imports inside `src/` are permitted. Filesystem, network, IPC, and subprocess modules are forbidden. +3. **Reconnect, Eviction & Cache Bounds**: Protocol must handle cold reconnects, host volatile-base evictions, concurrent stale-base reads, unknown/unseen channels, and arbitrary JSON shapes without error, within `maxPersistentBytes` and reasonable runtime (`< 20s` for the full held-out recording, including process spawns). +4. **Generalization**: The score comes from an unseen held-out recording of different real tasks (different de-identification key, different text, ids and sizes). A separate synthetic stress trace with many cold reconnects, host evictions and concurrent stale-base reads is run as a correctness gate only. Do not hardcode trace strings or schema assumptions that break on unseen payloads. + +## 6. Workload Provenance + +Both recordings were made by running Cindy's transfer-baseline scenario (`apps/desktop/src/test/transfer-baseline`, phone profile) at the source commit in `question.json`, with its synthetic content swapped for real de-identified tasks and every remote RPC recorded as the Desktop handler returned it. History pages are recorded complete (the product's own `historyDelta` option removed), and product protocol options (`historyDelta`, `messageBodies`) are removed from the request arguments: they belong to the protocol you are replacing. The tasks were de-identified before recording (harness prompt text replaced by same-shape surrogate text; paths, user name, e-mail and account ids pseudonymized). Tool results that the database had compacted after archiving were restored from the engine's own transcript, as the live database held them; plugin-engine tasks keep the compacted marker. diff --git a/questions/opt-device-link-delta-sync/v2/reference/ENVIRONMENT.md b/questions/opt-device-link-delta-sync/v2/reference/ENVIRONMENT.md new file mode 100644 index 0000000..be264f2 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/ENVIRONMENT.md @@ -0,0 +1,11 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Official grading needs Node.js `>= 20`: the grader runs your code in a separate process under Node's permission model. On older Node the run is reported as an environment problem, not scored. +- Allowed built-in imports in `src/`: `node:zlib`, `node:crypto`, `node:buffer`, `node:util`, `node:string_decoder`, `node:assert` (plus relative imports within `src/`). No filesystem, network, child-process, or shared-memory APIs. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: Wire byte totals (`total_wire_bytes`) are strictly deterministic integers across runs on identical traces. +- Public checks: + - `npm test` — functional correctness, edge-case JSON parity, process isolation, cold reconnect, host eviction, and concurrent stale-base tests + - `npm run bench` — deterministic two-process replay of the public real recording (162 reads, 10 channels) reporting `total_wire_bytes`, upstream/downstream split, per-channel breakdown, reduction vs raw JSON and the product's own measured wire bytes for the same reads +- Data: `corpus/public-trace.json.br` (brotli-compressed JSON, loaded by `lib/trace-loader.mjs`). The held-out recording used for the score is not shipped. diff --git a/questions/opt-device-link-delta-sync/v2/reference/TASK.md b/questions/opt-device-link-delta-sync/v2/reference/TASK.md new file mode 100644 index 0000000..5d27a96 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's cross-device `device-link` RPC sync protocol (`src/sync-protocol.mjs`), extracted from the desktop-to-mobile remote session path (`packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts`). When a user follows a task from the phone, every read below crosses a metered, often cellular, link; fewer bytes mean faster pages and less data used. + +## What the real workload looks like + +`corpus/public-trace.json.br` is a recorded phone session, not a generated one. It was captured by running Cindy's own transfer-baseline scenario (real `DeviceLinkClient`, real relay, real Desktop `local-db:*` handlers on a migrated SQLite database, real phone history-view controller and recovery core) with the host database filled from 13 real, de-identified Cindy tasks in which Claude Code, Codex and a plugin engine worked on open-source code. Live turns stream real prose and real tool calls with their real results. + +It holds 162 reads (~3.4 MB of complete JSON) on 10 channels, in the order the host received them: + +- `local-db:messages:view` (56 reads, most of the bytes): the history page the phone renders, re-read after every streamed step of a live turn, after reconnects, and as read-ahead for the five most recent tasks. +- `local-db:messages:work-details`, `local-db:sessions:list`, `local-db:sessions:get` and several small status reads (`maker:list-active`, `maker:input:get-projection`, `maker:goal:get-status`, `maker:get-pending-interactions`, `local-db:messages:view-intent`, `sidebar-settings:get-project-aliases`). +- Lifecycle events: a new host and phone process between scenario runs (`cold_reconnect`), a new phone process on the same host (`client_restart`), and reads that were in flight together (`concurrent_rpc`). + +The baseline in `src/` follows today's product strategy at the payload level: it only diffs `local-db:sessions:list` (depth 2), only reuses whole identical history items, gzips everything else independently, and keeps no history across process restarts. On the public recording it sends 1,022,246 B. For reference, the product itself put 1,081,479 B on the WebSocket for the same reads, a number that also includes its message envelopes and transport framing, which this question does not count. + +For orientation: compressing each connection's reads in order with Brotli-11, with full shared history inside the connection and nothing kept across restarts, takes 178,329 B on the public recording. Using persisted state across restarts can go lower still. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` carefully before making changes. +- Preserve **100% exact JSON parity (`assert.deepStrictEqual`)** on every read, including reads after restarts and concurrent reads built on a stale base. +- Respect **strict two-process isolation**: Host and Client run in separate Node.js child processes and communicate **only** through `Uint8Array` wire frames. +- Respect **cache & persistence bounds**: `exportPersistentState()` must return at most `maxPersistentBytes` (default `2 MiB`), and every RPC must finish within `PROTOCOL_MAX_ROUNDS = 4` rounds. +- **Open-ended goal**: drive `total_wire_bytes` (all upstream and downstream bytes of all rounds of all RPCs) as low as possible on an **unseen held-out recording** made the same way from 13 different real tasks, de-identified with a different key. +- Run `npm test` and `npm run bench` to verify parity and measure your reduction. +- Record your analysis, protocol design, trade-offs and verified results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料与加载器、运行环境和题面。 diff --git a/questions/opt-device-link-delta-sync/v2/reference/bench/workload.mjs b/questions/opt-device-link-delta-sync/v2/reference/bench/workload.mjs new file mode 100644 index 0000000..126dcd4 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/bench/workload.mjs @@ -0,0 +1,50 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +export async function runBenchmark() { + const trace = loadPublicTrace(); + const t0 = performance.now(); + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace }); + const elapsedMs = Math.round(performance.now() - t0); + + return { + trace: trace.name, + total_wire_bytes: stats.totalWireBytes, + upstream_bytes: stats.upstreamBytes, + downstream_bytes: stats.downstreamBytes, + raw_json_bytes: trace.meta.rawJsonBytes, + reduction_vs_raw_pct: Math.round((1 - stats.totalWireBytes / trace.meta.rawJsonBytes) * 10000) / 100, + product_rpc_wire_bytes: trace.meta.productRpcWireBytes, + rpc_count: stats.rpcCount, + total_rounds: stats.totalRounds, + max_rounds_used: stats.maxRoundsUsed, + max_persistent_bytes: stats.maxPersistentBytesSeen, + elapsed_ms: elapsedMs, + trace_meta: { + cold_reconnects: trace.meta.coldReconnectCount, + client_restarts: trace.meta.clientRestartCount, + concurrent_pairs: trace.meta.concurrentPairCount, + }, + per_channel: stats.perChannel, + }; +} + +if (isMainModule()) { + const result = await runBenchmark(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/corpus/public-trace.json.br b/questions/opt-device-link-delta-sync/v2/reference/corpus/public-trace.json.br new file mode 100644 index 0000000..e196d5c Binary files /dev/null and b/questions/opt-device-link-delta-sync/v2/reference/corpus/public-trace.json.br differ diff --git a/questions/opt-device-link-delta-sync/v2/reference/lib/rpc-harness.mjs b/questions/opt-device-link-delta-sync/v2/reference/lib/rpc-harness.mjs new file mode 100644 index 0000000..fa01758 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/lib/rpc-harness.mjs @@ -0,0 +1,306 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const MAX_ROUNDS = 4; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; + +class JsonLineWorker { + constructor(scriptPath, args) { + this.child = spawn(process.execPath, [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + env: { + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', + TMPDIR: process.env.TMPDIR || '', + LANG: 'en_US.UTF-8', + }, + }); + this.stderr = ''; + this.child.stderr.on('data', (chunk) => { + this.stderr = (this.stderr + chunk.toString('utf8')).slice(-8000); + }); + this.pending = []; + this.closed = false; + this.rl = readline.createInterface({ input: this.child.stdout, crlfDelay: Infinity }); + this.rl.on('line', (line) => { + const next = this.pending.shift(); + if (!next) return; + try { + next.resolve(JSON.parse(line)); + } catch (err) { + next.reject(new Error(`Malformed worker JSON: ${err.message} (stderr: ${this.stderr})`)); + } + }); + this.child.on('exit', (code, signal) => { + this.closed = true; + while (this.pending.length > 0) { + const next = this.pending.shift(); + next.reject(new Error(`Worker exited unexpectedly (code=${code}, signal=${signal}): ${this.stderr}`)); + } + }); + } + + call(payload) { + if (this.closed) { + return Promise.reject(new Error(`Worker already closed: ${this.stderr}`)); + } + return new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + this.child.stdin.write(JSON.stringify(payload) + '\n'); + }).then((res) => { + if (!res.ok) { + throw new Error(res.error || `Worker error: ${this.stderr}`); + } + return res; + }); + } + + async close() { + if (this.closed) return; + this.closed = true; + try { + this.child.stdin.end(); + this.child.kill('SIGTERM'); + } catch { + // ignore + } + await new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) return resolve(); + const timer = setTimeout(() => { + try { this.child.kill('SIGKILL'); } catch { /* ignore */ } + resolve(); + }, 1500); + this.child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +} + +/** + * Executes a full trace across two physically isolated child processes (Host & Client). + * Cold reconnects physically kill & respawn both Client (with persistentState <= maxPersistentBytes) + * and Host; host evictions physically kill & respawn Host. + */ +export async function runIsolatedTrace({ + srcDir, + trace, + hostOptions = { maxBaseSnapshotsPerKey: 8, maxCacheBytes: 4 * 1024 * 1024 }, + clientOptions = { + maxCacheBytes: 4 * 1024 * 1024, + maxPersistentBytes: DEFAULT_MAX_PERSISTENT_BYTES, + maxPersistentBodyEntries: 512, + }, + hostWorkerPath = path.join(HERE, 'worker-host.mjs'), + clientWorkerPath = path.join(HERE, 'worker-client.mjs'), +}) { + const maxPersistentBytes = clientOptions.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + let hostWorker = null; + let clientWorker = null; + + async function spawnHost() { + if (hostWorker) await hostWorker.close(); + hostWorker = new JsonLineWorker(hostWorkerPath, [srcDir, JSON.stringify(hostOptions)]); + const ping = await hostWorker.call({ op: 'ping' }); + return ping.pid; + } + + async function spawnClient(persistentBase64 = null) { + if (clientWorker) await clientWorker.close(); + clientWorker = new JsonLineWorker(clientWorkerPath, [srcDir, JSON.stringify(clientOptions)]); + const init = await clientWorker.call({ + op: 'init', + options: persistentBase64 !== null ? { persistentBase64 } : {}, + }); + return init.pid; + } + + const stats = { + totalWireBytes: 0, + upstreamBytes: 0, + downstreamBytes: 0, + totalRounds: 0, + maxRoundsUsed: 0, + rpcCount: 0, + maxPersistentBytesSeen: 0, + hostPid: null, + clientPid: null, + perChannel: {}, + }; + + function recordWire(channel, up, down) { + stats.upstreamBytes += up; + stats.downstreamBytes += down; + stats.totalWireBytes += up + down; + if (!stats.perChannel[channel]) { + stats.perChannel[channel] = { rpcs: 0, rounds: 0, upstreamBytes: 0, downstreamBytes: 0, totalWireBytes: 0 }; + } + stats.perChannel[channel].upstreamBytes += up; + stats.perChannel[channel].downstreamBytes += down; + stats.perChannel[channel].totalWireBytes += up + down; + } + + function finishRpcMetric(channel, rounds) { + stats.rpcCount += 1; + stats.totalRounds += rounds; + if (rounds > stats.maxRoundsUsed) stats.maxRoundsUsed = rounds; + stats.perChannel[channel].rpcs += 1; + stats.perChannel[channel].rounds += rounds; + } + + async function finishFromRound0(read, res0Base64) { + let round = 0; + let respBase64 = res0Base64; + while (true) { + const step = await clientWorker.call({ + op: 'receiveResponse', + readId: read.id, + channel: read.channel, + argsKey: read.argsKey, + responseBase64: respBase64, + round, + }); + if (step.done) { + assert.deepStrictEqual( + step.value, + read.groundTruthValue, + `Exact JSON parity mismatch on ${read.id} (${read.channel}, round ${round})`, + ); + finishRpcMetric(read.channel, round + 1); + return; + } + round += 1; + if (round >= MAX_ROUNDS) { + throw new Error(`Exceeded PROTOCOL_MAX_ROUNDS (${MAX_ROUNDS}) on ${read.id} (${read.channel})`); + } + const nextReqBytes = Buffer.from(step.nextRequestBase64, 'base64').byteLength; + const hostRes = await hostWorker.call({ + op: 'handleFrame', + channel: read.channel, + argsKey: read.argsKey, + requestBase64: step.nextRequestBase64, + groundTruthValue: read.groundTruthValue, + round, + }); + const nextResBytes = Buffer.from(hostRes.responseBase64, 'base64').byteLength; + recordWire(read.channel, nextReqBytes, nextResBytes); + respBase64 = hostRes.responseBase64; + } + } + + try { + stats.hostPid = await spawnHost(); + stats.clientPid = await spawnClient(null); + assert.notEqual(stats.hostPid, stats.clientPid, 'Host and Client must run in distinct OS processes'); + + for (const step of trace.steps) { + if (step.type === 'cold_reconnect') { + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + // Physical cold reconnect: kill & respawn Client with persistentState only, + // and respawn Host (clearing volatile peer delta bases). + await spawnClient(exported.persistentBase64); + await spawnHost(); + } else if (step.type === 'client_restart') { + // A new controller process on the same running host (e.g. the phone app relaunched): + // kill & respawn Client from its persisted state only; Host keeps its volatile state. + const exported = await clientWorker.call({ op: 'exportPersistentState' }); + if (exported.byteLength > maxPersistentBytes) { + throw new Error( + `exportPersistentState exceeded maxPersistentBytes (${exported.byteLength} > ${maxPersistentBytes})`, + ); + } + if (exported.byteLength > stats.maxPersistentBytesSeen) { + stats.maxPersistentBytesSeen = exported.byteLength; + } + await spawnClient(exported.persistentBase64); + } else if (step.type === 'host_evict') { + // Physical host volatile-base eviction: kill & respawn Host only; Client stays warm in RAM. + await spawnHost(); + } else if (step.type === 'rpc') { + const req0 = await clientWorker.call({ + op: 'beginRead', + readId: step.id, + channel: step.channel, + argsKey: step.argsKey, + }); + const reqBytes = Buffer.from(req0.requestBase64, 'base64').byteLength; + const res0 = await hostWorker.call({ + op: 'handleFrame', + channel: step.channel, + argsKey: step.argsKey, + requestBase64: req0.requestBase64, + groundTruthValue: step.groundTruthValue, + round: 0, + }); + const resBytes = Buffer.from(res0.responseBase64, 'base64').byteLength; + recordWire(step.channel, reqBytes, resBytes); + await finishFromRound0(step, res0.responseBase64); + } else if (step.type === 'concurrent_rpc') { + const [r1, r2] = step.reads; + // Client builds BOTH round-0 requests BEFORE seeing either response (stale-base overlap!). + const req1 = await clientWorker.call({ + op: 'beginRead', + readId: r1.id, + channel: r1.channel, + argsKey: r1.argsKey, + }); + const req2 = await clientWorker.call({ + op: 'beginRead', + readId: r2.id, + channel: r2.channel, + argsKey: r2.argsKey, + }); + const req1Bytes = Buffer.from(req1.requestBase64, 'base64').byteLength; + const req2Bytes = Buffer.from(req2.requestBase64, 'base64').byteLength; + + // Host serves r1 first (advancing its state), then r2 (which still carries pre-r1 base!). + const res1 = await hostWorker.call({ + op: 'handleFrame', + channel: r1.channel, + argsKey: r1.argsKey, + requestBase64: req1.requestBase64, + groundTruthValue: r1.groundTruthValue, + round: 0, + }); + const res2 = await hostWorker.call({ + op: 'handleFrame', + channel: r2.channel, + argsKey: r2.argsKey, + requestBase64: req2.requestBase64, + groundTruthValue: r2.groundTruthValue, + round: 0, + }); + const res1Bytes = Buffer.from(res1.responseBase64, 'base64').byteLength; + const res2Bytes = Buffer.from(res2.responseBase64, 'base64').byteLength; + recordWire(r1.channel, req1Bytes, res1Bytes); + recordWire(r2.channel, req2Bytes, res2Bytes); + + // Client decodes r1 (and any follow-up rounds), then decodes r2 (and any follow-up rounds). + await finishFromRound0(r1, res1.responseBase64); + await finishFromRound0(r2, res2.responseBase64); + } else { + throw new Error(`Unknown trace step type: ${step.type}`); + } + } + + return stats; + } finally { + await Promise.all([ + hostWorker ? hostWorker.close() : Promise.resolve(), + clientWorker ? clientWorker.close() : Promise.resolve(), + ]); + } +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/lib/trace-loader.mjs b/questions/opt-device-link-delta-sync/v2/reference/lib/trace-loader.mjs new file mode 100644 index 0000000..3c832bc --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/lib/trace-loader.mjs @@ -0,0 +1,22 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +/** + * Load a recorded RPC workload (brotli-compressed JSON: { name, meta, steps }). + * Steps: { type: 'rpc', id, channel, argsKey, groundTruthValue } + * | { type: 'concurrent_rpc', reads: [read, read] } + * | { type: 'cold_reconnect' } | { type: 'client_restart' } | { type: 'host_evict' } + */ +export function loadTrace(file) { + return JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(file)).toString('utf8')); +} + +export const PUBLIC_TRACE_PATH = path.resolve(HERE, '../corpus/public-trace.json.br'); + +export function loadPublicTrace() { + return loadTrace(PUBLIC_TRACE_PATH); +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/lib/worker-client.mjs b/questions/opt-device-link-delta-sync/v2/reference/lib/worker-client.mjs new file mode 100644 index 0000000..d969157 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/lib/worker-client.mjs @@ -0,0 +1,107 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const rawOptions = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createClientSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createClientSyncEndpoint'); +} + +let client = null; + +function initClient(initOpts = {}) { + const opts = { ...rawOptions, ...initOpts }; + if (typeof opts.persistentBase64 === 'string') { + const buf = Buffer.from(opts.persistentBase64, 'base64'); + opts.persistentState = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + delete opts.persistentBase64; + } + client = mod.createClientSyncEndpoint(opts); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'init') { + initClient(req.options || {}); + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else if (req.op === 'beginRead') { + if (!client) initClient(); + const out = client.beginRead({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + }); + if (!(out instanceof Uint8Array)) { + throw new Error('client.beginRead must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + requestBase64: Buffer.from(out.buffer, out.byteOffset, out.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'receiveResponse') { + if (!client) throw new Error('Client not initialized'); + const respBuf = Buffer.from(req.responseBase64, 'base64'); + const res = client.receiveResponse({ + readId: req.readId, + channel: req.channel, + argsKey: req.argsKey, + responseBytes: new Uint8Array(respBuf.buffer, respBuf.byteOffset, respBuf.byteLength), + round: req.round, + }); + if (!res || typeof res !== 'object' || typeof res.done !== 'boolean') { + throw new Error('client.receiveResponse must return { done: true, value } or { done: false, nextRequestBytes }'); + } + if (res.done) { + process.stdout.write(JSON.stringify({ ok: true, done: true, value: res.value }) + '\n'); + } else { + if (!(res.nextRequestBytes instanceof Uint8Array)) { + throw new Error('client.receiveResponse with done:false must return nextRequestBytes as Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + done: false, + nextRequestBase64: Buffer.from( + res.nextRequestBytes.buffer, + res.nextRequestBytes.byteOffset, + res.nextRequestBytes.byteLength, + ).toString('base64'), + }) + '\n'); + } + } else if (req.op === 'exportPersistentState') { + if (!client) initClient(); + const persisted = client.exportPersistentState(); + if (!(persisted instanceof Uint8Array)) { + throw new Error('client.exportPersistentState must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + persistentBase64: Buffer.from(persisted.buffer, persisted.byteOffset, persisted.byteLength).toString('base64'), + byteLength: persisted.byteLength, + }) + '\n'); + } else if (req.op === 'simulateColdReconnect') { + if (!client) initClient(); + client.simulateColdReconnect(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else { + throw new Error(`Unknown client op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/reference/lib/worker-host.mjs b/questions/opt-device-link-delta-sync/v2/reference/lib/worker-host.mjs new file mode 100644 index 0000000..0d49068 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/lib/worker-host.mjs @@ -0,0 +1,57 @@ +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [srcDir, optionsJson] = process.argv.slice(2); +const options = optionsJson ? JSON.parse(optionsJson) : {}; + +const modUrl = pathToFileURL(path.join(srcDir, 'sync-protocol.mjs')).href; +const mod = await import(modUrl); +if (typeof mod.createHostSyncEndpoint !== 'function') { + throw new Error('sync-protocol.mjs must export createHostSyncEndpoint'); +} + +const host = mod.createHostSyncEndpoint(options); + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +rl.on('line', (line) => { + if (!line.trim()) return; + let req; + try { + req = JSON.parse(line); + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: `Invalid IPC JSON: ${err.message}` }) + '\n'); + return; + } + try { + if (req.op === 'handleFrame') { + const requestBytes = Buffer.from(req.requestBase64, 'base64'); + const res = host.handleFrame({ + channel: req.channel, + argsKey: req.argsKey, + requestBytes: new Uint8Array(requestBytes.buffer, requestBytes.byteOffset, requestBytes.byteLength), + groundTruthValue: req.groundTruthValue, + round: req.round, + }); + if (!(res instanceof Uint8Array)) { + throw new Error('host.handleFrame must return a Uint8Array'); + } + process.stdout.write(JSON.stringify({ + ok: true, + responseBase64: Buffer.from(res.buffer, res.byteOffset, res.byteLength).toString('base64'), + }) + '\n'); + } else if (req.op === 'evictVolatileBases') { + host.evictVolatileBases(); + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'ping') { + process.stdout.write(JSON.stringify({ ok: true, pid: process.pid }) + '\n'); + } else { + throw new Error(`Unknown host op: ${req.op}`); + } + } catch (err) { + process.stdout.write(JSON.stringify({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + '\n'); + } +}); diff --git a/questions/opt-device-link-delta-sync/v2/reference/package.json b/questions/opt-device-link-delta-sync/v2/reference/package.json new file mode 100644 index 0000000..2e2973c --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-device-link-delta-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/src/sync-protocol.mjs b/questions/opt-device-link-delta-sync/v2/reference/src/sync-protocol.mjs new file mode 100644 index 0000000..a2e4637 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/src/sync-protocol.mjs @@ -0,0 +1,796 @@ +import crypto from 'node:crypto'; +import zlib from 'node:zlib'; + +export const PROTOCOL_MAX_ROUNDS = 4; +export const DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY = 8; +export const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BYTES = 2 * 1024 * 1024; +export const DEFAULT_MAX_PERSISTENT_BODY_ENTRIES = 512; + +/** + * Reference human optimization: + * - Cross-channel keyed recursive field-level JSON patch (handles arbitrary nesting, + * object key additions/deletions/edits, keyed record arrays matched by id/key with + * per-record field patches, and revisionSuffix normalization). + * - Multi-base snapshot ring on Host (up to maxBaseSnapshotsPerKey = 8) so concurrent + * in-flight stale-base reads stay incremental. + * - Eliminates MAX_DELTA_RATIO = 0.5 abort cliff and MAX_UNVERIFIED_DELTAS = 8 reset cliff. + * - Compact 8-byte (16-hex) cold-cache digests for messages:view bodies & keyed rows + * persisted across mobile cold reconnects. + * - Raw DEFLATE framing (`deflateRawSync`). + * + * Intentionally does NOT implement: + * - String append / prefix-suffix / line-delta ops (streaming appends still replace the text field). + * - Binary / varint / key-interning patch encoding (uses JSON patch objects). + * - Base-seeded preset-dictionary DEFLATE (`{ dictionary: baseBuf }`). + * - Compact Merkle prefix hashes / Golomb-coded sets / Bloom + 2-RTT cold reconciliation. + */ + +const FLAG_RAW = 0; +const FLAG_DEFLATE = 1; +const DELETE_SENTINEL = { $d: 1 }; + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function hash16(text) { + return crypto.createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 12); +} + +function packFrame(obj) { + const raw = Buffer.from(JSON.stringify(obj), 'utf8'); + if (raw.byteLength >= 96) { + const compressed = zlib.deflateRawSync(raw, { level: 9 }); + if (compressed.byteLength + 1 < raw.byteLength) { + const out = new Uint8Array(compressed.byteLength + 1); + out[0] = FLAG_DEFLATE; + out.set(compressed, 1); + return out; + } + } + const out = new Uint8Array(raw.byteLength + 1); + out[0] = FLAG_RAW; + out.set(raw, 1); + return out; +} + +function unpackFrame(bytes) { + const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const body = buf.subarray(1); + const raw = buf[0] === FLAG_DEFLATE ? zlib.inflateRawSync(body) : body; + return JSON.parse(raw.toString('utf8')); +} + +// --- revisionSuffix normalization for history pages (like historyViewDelta.ts) --- +function swapSummary(summary, swap) { + if (!isPlainObject(summary)) return summary; + const next = { ...summary, revision: swap(summary.revision) }; + if (summary.preview !== undefined) next.preview = swapSummary(summary.preview, swap); + return next; +} + +function swapHistoryItem(item, swap) { + if (!isPlainObject(item)) return item; + if (item.type === 'work' && Array.isArray(item.children)) { + const out = { ...item, children: item.children.map((c) => swapHistoryItem(c, swap)) }; + if (item.summary !== undefined) out.summary = swapSummary(item.summary, swap); + return out; + } + if (item.type === 'work' && item.summary !== undefined) { + return { ...item, summary: swapSummary(item.summary, swap) }; + } + return item; +} + +function allWorkRevisionsEndWith(items, suffix) { + for (let i = 0; i < items.length; i += 1) { + const item = items[i]; + if (!isPlainObject(item) || item.type !== 'work') continue; + if (item.summary !== undefined) { + if (!isPlainObject(item.summary) || typeof item.summary.revision !== 'string' || !item.summary.revision.endsWith(suffix)) { + return false; + } + if (item.summary.preview !== undefined) { + if (!isPlainObject(item.summary.preview) || typeof item.summary.preview.revision !== 'string' || !item.summary.preview.revision.endsWith(suffix)) { + return false; + } + } + } + if (Array.isArray(item.children) && !allWorkRevisionsEndWith(item.children, suffix)) { + return false; + } + } + return true; +} + +function normalizePageForDiff(value) { + if ( + !isPlainObject(value) + || typeof value.revisionSuffix !== 'string' + || !value.revisionSuffix + || !Array.isArray(value.items) + || !allWorkRevisionsEndWith(value.items, value.revisionSuffix) + ) { + return { normalized: value, suffixed: false }; + } + const suffix = value.revisionSuffix; + const items = value.items.map((item) => + swapHistoryItem(item, (rev) => rev.slice(0, -suffix.length)), + ); + return { normalized: { ...value, items }, suffixed: true }; +} + +function denormalizePageAfterApply(value, suffixed) { + if (!suffixed || !isPlainObject(value) || typeof value.revisionSuffix !== 'string' || !value.revisionSuffix || !Array.isArray(value.items)) { + return value; + } + const suffix = value.revisionSuffix; + const items = value.items.map((item) => + swapHistoryItem(item, (rev) => (typeof rev === 'string' ? rev + suffix : rev)), + ); + return { ...value, items }; +} + +// --- Recursive keyed JSON patch --- +function detectArrayKeyField(arr) { + if (!Array.isArray(arr) || arr.length === 0) return null; + for (const candidate of ['id', 'key', 'runId']) { + const seen = new Set(); + let ok = true; + for (let i = 0; i < arr.length; i += 1) { + const el = arr[i]; + if (!isPlainObject(el) || typeof el[candidate] !== 'string' || el[candidate].length === 0 || seen.has(el[candidate])) { + ok = false; + break; + } + seen.add(el[candidate]); + } + if (ok) return candidate; + } + return null; +} + +function deepEqual(a, b) { + if (Object.is(a, b)) return true; + if (typeof a !== typeof b || a === null || b === null) return false; + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let i = 0; i < a.length; i += 1) { + if (!deepEqual(a[i], b[i])) return false; + } + return true; + } + if (Array.isArray(b)) return false; + if (typeof a === 'object') { + const ka = Object.keys(a); + const kb = Object.keys(b); + if (ka.length !== kb.length) return false; + for (let i = 0; i < ka.length; i += 1) { + const k = ka[i]; + if (!Object.prototype.hasOwnProperty.call(b, k)) return false; + if (!deepEqual(a[k], b[k])) return false; + } + return true; + } + return false; +} + +/** + * Patch representation: + * - undefined: unchanged + * - { s: value }: full replacement + * - { o: [[key, childPatch | DELETE_SENTINEL], ...] }: object field patch (safe for prototype keys!) + * - { k: ops }: keyed/indexed array patch where each op is: + * - integer `idx` -> reuse base[idx] + * - [startIdx, count] -> reuse base[startIdx .. startIdx+count-1] + * - [idx, patch, 1] -> apply recursive patch to base[idx] + * - { v: literal } -> new literal element + */ +function diffValue(base, next) { + if (Object.is(base, next)) return undefined; + if (base === null || next === null || typeof base !== 'object' || typeof next !== 'object') { + return { s: next }; + } + if (Array.isArray(base) !== Array.isArray(next)) { + return { s: next }; + } + + if (Array.isArray(base)) { + if (deepEqual(base, next)) return undefined; + if (base.length === 0 || next.length === 0) return { s: next }; + + const keyField = detectArrayKeyField(base); + const nextKeyField = detectArrayKeyField(next); + if (keyField && keyField === nextKeyField) { + const baseByKey = new Map(); + for (let i = 0; i < base.length; i += 1) { + baseByKey.set(base[i][keyField], i); + } + const ops = []; + let runStart = -1; + let runLen = 0; + const flushRun = () => { + if (runLen === 1) ops.push(runStart); + else if (runLen > 1) ops.push([runStart, runLen]); + runStart = -1; + runLen = 0; + }; + let matchedAny = false; + for (let i = 0; i < next.length; i += 1) { + const el = next[i]; + const bi = baseByKey.get(el[keyField]); + if (bi === undefined) { + flushRun(); + ops.push({ v: el }); + } else { + matchedAny = true; + const childPatch = diffValue(base[bi], el); + if (childPatch === undefined) { + if (runLen > 0 && bi === runStart + runLen) { + runLen += 1; + } else { + flushRun(); + runStart = bi; + runLen = 1; + } + } else { + flushRun(); + ops.push([bi, childPatch, 1]); + } + } + } + flushRun(); + return matchedAny ? { k: ops } : { s: next }; + } + + // Unkeyed array: match identical elements by JSON text + const byText = new Map(); + for (let i = 0; i < base.length; i += 1) { + const t = JSON.stringify(base[i]); + if (!byText.has(t)) byText.set(t, i); + } + const ops = []; + let reused = 0; + for (let i = 0; i < next.length; i += 1) { + const idx = byText.get(JSON.stringify(next[i])); + if (idx !== undefined) { + reused += 1; + ops.push(idx); + } else { + ops.push({ v: next[i] }); + } + } + return reused > 0 ? { k: ops } : { s: next }; + } + + // Plain object diff using entries array so keys like "constructor"/"toString" are 100% safe + const entries = []; + const nextKeys = Object.keys(next); + const baseKeys = Object.keys(base); + for (let i = 0; i < baseKeys.length; i += 1) { + const k = baseKeys[i]; + if (!Object.prototype.hasOwnProperty.call(next, k)) { + entries.push([k, DELETE_SENTINEL]); + } + } + for (let i = 0; i < nextKeys.length; i += 1) { + const k = nextKeys[i]; + if (!Object.prototype.hasOwnProperty.call(base, k)) { + entries.push([k, { s: next[k] }]); + } else { + const child = diffValue(base[k], next[k]); + if (child !== undefined) { + entries.push([k, child]); + } + } + } + if (entries.length === 0) return undefined; + return { o: entries }; +} + +function applyPatch(base, patch) { + if (patch === undefined) return base; + if ('s' in patch) return patch.s; + if ('k' in patch) { + const out = []; + for (let i = 0; i < patch.k.length; i += 1) { + const op = patch.k[i]; + if (typeof op === 'number') { + out.push(base[op]); + } else if (Array.isArray(op)) { + if (op.length === 2) { + for (let j = op[0]; j < op[0] + op[1]; j += 1) out.push(base[j]); + } else { + out.push(applyPatch(base[op[0]], op[1])); + } + } else { + out.push(op.v); + } + } + return out; + } + if ('o' in patch) { + const out = {}; + const deletes = new Set(); + const updates = new Map(); + for (let i = 0; i < patch.o.length; i += 1) { + const [k, p] = patch.o[i]; + if (isPlainObject(p) && p.$d === 1) deletes.add(k); + else updates.set(k, p); + } + for (const k of Object.keys(base)) { + if (deletes.has(k)) continue; + if (updates.has(k)) { + out[k] = applyPatch(base[k], updates.get(k)); + updates.delete(k); + } else { + out[k] = base[k]; + } + } + for (const [k, p] of updates.entries()) { + out[k] = applyPatch(undefined, p); + } + return out; + } + throw new Error('Invalid reference patch node'); +} + +// --- Cold-cache reusable item extraction & substitution (8-byte / 16-hex digests) --- +function extractColdItems(channel, value) { + const out = []; + if (!isPlainObject(value)) return out; + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const suffix = typeof value.revisionSuffix === 'string' ? value.revisionSuffix : ''; + for (const item of value.items) { + if (!isPlainObject(item) || typeof item.key !== 'string') continue; + const stripped = suffix ? swapHistoryItem(item, (r) => (typeof r === 'string' && r.endsWith(suffix) ? r.slice(0, -suffix.length) : r)) : item; + const json = JSON.stringify(stripped); + out.push({ scope: `msg:${value.sessionId || ''}`, id: item.key, hash: hash16(json), json }); + } + } else if (channel === 'local-db:sessions:list' && Array.isArray(value.sessions)) { + for (const row of value.sessions) { + if (isPlainObject(row) && typeof row.id === 'string') { + const json = JSON.stringify(row); + out.push({ scope: 'sess', id: row.id, hash: hash16(json), json }); + } + } + } else if (channel === 'maker:provider:list' && Array.isArray(value.providers)) { + for (const p of value.providers) { + if (isPlainObject(p) && typeof p.id === 'string') { + const json = JSON.stringify(p); + out.push({ scope: 'prov', id: p.id, hash: hash16(json), json }); + if (Array.isArray(p.models)) { + const mj = JSON.stringify(p.models); + out.push({ scope: 'prov', id: `${p.id}#models`, hash: hash16(mj), json: mj }); + } + } + } + } else if (channel === 'maker:schedule:list-sidebar-index-runs' && Array.isArray(value.jobs)) { + for (const j of value.jobs) { + if (isPlainObject(j) && typeof j.id === 'string') { + const json = JSON.stringify(j); + out.push({ scope: 'sched', id: j.id, hash: hash16(json), json }); + } + } + } + return out; +} + +function coldScopeFor(channel, argsKey) { + if (channel === 'local-db:messages:view') { + try { + const parsed = JSON.parse(argsKey); + return `msg:${parsed?.sessionId || ''}`; + } catch { + return 'msg:'; + } + } + if (channel === 'local-db:sessions:list') return 'sess'; + if (channel === 'maker:provider:list') return 'prov'; + if (channel === 'maker:schedule:list-sidebar-index-runs') return 'sched'; + return null; +} + +function substituteColdKnown(channel, value, knownPairs) { + if (!isPlainObject(value) || !Array.isArray(knownPairs) || knownPairs.length === 0) return { value, refs: null }; + // Map id -> { hash, cIdx } where cIdx is the integer index in client's knownPairs array + const knownMap = new Map(); + for (let i = 0; i < knownPairs.length; i += 1) { + const pair = knownPairs[i]; + if (Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string') { + knownMap.set(pair[0], { hash: pair[1], cIdx: i }); + } + } + const refs = []; + + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const suffix = typeof value.revisionSuffix === 'string' && allWorkRevisionsEndWith(value.items, value.revisionSuffix) + ? value.revisionSuffix + : ''; + const items = value.items.map((item, idx) => { + if (isPlainObject(item) && typeof item.key === 'string') { + const hit = knownMap.get(item.key); + if (hit) { + const stripped = suffix ? swapHistoryItem(item, (r) => r.slice(0, -suffix.length)) : item; + if (hash16(JSON.stringify(stripped)) === hit.hash) { + refs.push([idx, hit.cIdx]); + return null; + } + } + } + return item; + }); + return refs.length > 0 ? { value: { ...value, items }, refs, suffix } : { value, refs: null }; + } + + const field = + channel === 'local-db:sessions:list' ? 'sessions' + : channel === 'maker:provider:list' ? 'providers' + : channel === 'maker:schedule:list-sidebar-index-runs' ? 'jobs' + : null; + if (field && Array.isArray(value[field])) { + const modelRefs = []; + const nextArr = value[field].map((row, idx) => { + if (isPlainObject(row) && typeof row.id === 'string') { + const hit = knownMap.get(row.id); + if (hit && hash16(JSON.stringify(row)) === hit.hash) { + refs.push([idx, hit.cIdx]); + return null; + } + if (field === 'providers' && Array.isArray(row.models)) { + const mHit = knownMap.get(`${row.id}#models`); + if (mHit && hash16(JSON.stringify(row.models)) === mHit.hash) { + modelRefs.push([idx, mHit.cIdx]); + return { ...row, models: null }; + } + } + } + return row; + }); + return (refs.length > 0 || modelRefs.length > 0) + ? { value: { ...value, [field]: nextArr }, refs, modelRefs, suffix: '' } + : { value, refs: null }; + } + return { value, refs: null }; +} + +function restoreColdKnown(channel, value, refs, modelRefs, suffix, coldList) { + if (!isPlainObject(value) || !Array.isArray(refs)) return value; + if (channel === 'local-db:messages:view' && Array.isArray(value.items)) { + const items = value.items.slice(); + for (let i = 0; i < refs.length; i += 1) { + const [idx, cIdx] = refs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache item index ${cIdx}`); + const parsed = JSON.parse(stored.json); + items[idx] = suffix ? swapHistoryItem(parsed, (r) => (typeof r === 'string' ? r + suffix : r)) : parsed; + } + return { ...value, items }; + } + + const field = + channel === 'local-db:sessions:list' ? 'sessions' + : channel === 'maker:provider:list' ? 'providers' + : channel === 'maker:schedule:list-sidebar-index-runs' ? 'jobs' + : null; + if (field && Array.isArray(value[field])) { + const arr = value[field].slice(); + for (let i = 0; i < refs.length; i += 1) { + const [idx, cIdx] = refs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache row index ${cIdx}`); + arr[idx] = JSON.parse(stored.json); + } + if (Array.isArray(modelRefs)) { + for (let i = 0; i < modelRefs.length; i += 1) { + const [idx, cIdx] = modelRefs[i]; + const stored = coldList[cIdx]; + if (!stored) throw new Error(`Missing cold-cache models index ${cIdx}`); + arr[idx] = { ...arr[idx], models: JSON.parse(stored.json) }; + } + } + return { ...value, [field]: arr }; + } + return value; +} + +export function createHostSyncEndpoint(options = {}) { + const maxBaseSnapshotsPerKey = options.maxBaseSnapshotsPerKey ?? DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY; + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + + // key -> Array<{ id, normalized, bytes }> + const rings = new Map(); + let totalBytes = 0; + + function evictVolatileBases() { + rings.clear(); + totalBytes = 0; + } + + function evictOneOldest() { + for (const [k, ring] of rings.entries()) { + const removed = ring.shift(); + if (removed) totalBytes -= removed.bytes; + if (ring.length === 0) rings.delete(k); + return; + } + } + + function rememberSnapshot(key, id, normalized, bytes, suffixed) { + if (bytes > maxCacheBytes / 2) return; + let ring = rings.get(key); + if (!ring) { + ring = []; + rings.set(key, ring); + } else { + // Refresh LRU order of the key + rings.delete(key); + rings.set(key, ring); + } + const existingIdx = ring.findIndex((s) => s.id === id); + if (existingIdx >= 0) { + const [existing] = ring.splice(existingIdx, 1); + ring.push(existing); + return; + } + ring.push({ id, normalized, bytes, suffixed }); + totalBytes += bytes; + while (ring.length > maxBaseSnapshotsPerKey) { + const dropped = ring.shift(); + totalBytes -= dropped.bytes; + } + while (totalBytes > maxCacheBytes && rings.size > 0) { + evictOneOldest(); + } + } + + function findBase(key, baseId) { + const ring = rings.get(key); + if (!ring) return undefined; + for (let i = ring.length - 1; i >= 0; i -= 1) { + if (ring[i].id === baseId) return ring[i]; + } + return undefined; + } + + function handleFrame({ channel, argsKey, requestBytes, groundTruthValue, round = 0 }) { + const req = unpackFrame(requestBytes); + const key = `${channel}\u0000${argsKey}`; + const { normalized, suffixed } = normalizePageForDiff(groundTruthValue); + const normJson = JSON.stringify(normalized); + const nextId = hash16(`${suffixed ? '1' : '0'}:${normJson}`); + + const baseSnap = req.base ? findBase(key, req.base) : undefined; + rememberSnapshot(key, nextId, normalized, normJson.length, suffixed); + + if (req.base && req.base === nextId) { + return packFrame({ t: 'same', id: nextId, sx: suffixed ? 1 : 0 }); + } + + if (baseSnap && baseSnap.suffixed === suffixed) { + const patch = diffValue(baseSnap.normalized, normalized); + if (patch === undefined) { + return packFrame({ t: 'same', id: nextId, sx: suffixed ? 1 : 0 }); + } + const deltaFrame = packFrame({ t: 'delta', id: nextId, base: baseSnap.id, p: patch, sx: suffixed ? 1 : 0 }); + const fullFrame = packFrame({ t: 'full', id: nextId, v: groundTruthValue, sx: suffixed ? 1 : 0 }); + return deltaFrame.byteLength <= fullFrame.byteLength ? deltaFrame : fullFrame; + } + + // If client advertised a warm base that was evicted on the Host, request a Round-1 cold-digest retry. + if (req.base && req.hasCold && round < PROTOCOL_MAX_ROUNDS - 1 && normJson.length >= 2048) { + return packFrame({ t: 'miss' }); + } + + // Cold path: substitute any items matching client's compact digest manifest + if (Array.isArray(req.cold) && req.cold.length > 0) { + const { value: subVal, refs, modelRefs, suffix } = substituteColdKnown(channel, groundTruthValue, req.cold); + if (refs) { + return packFrame({ + t: 'cold', + id: nextId, + v: subVal, + r: refs, + ...(modelRefs && modelRefs.length > 0 ? { mr: modelRefs } : {}), + sf: suffix, + sx: suffixed ? 1 : 0, + }); + } + } + + return packFrame({ t: 'full', id: nextId, v: groundTruthValue, sx: suffixed ? 1 : 0 }); + } + + return { handleFrame, evictVolatileBases }; +} + +export function createClientSyncEndpoint(options = {}) { + const maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + const maxPersistentBytes = options.maxPersistentBytes ?? DEFAULT_MAX_PERSISTENT_BYTES; + + // Volatile state: key -> { id, normalized, bytes } + const cache = new Map(); + let cacheBytes = 0; + const inflight = new Map(); + + // Persistent cold-cache store: `${scope}\u0000${id}` -> { scope, id, hash, json } + const persistent = new Map(); + let persistentRawBytes = 0; + + function rememberPersistent(scope, id, hash, json) { + const k = `${scope}\u0000${id}`; + const prev = persistent.get(k); + if (prev) { + persistentRawBytes -= prev.json.length; + persistent.delete(k); + } + if (json.length > maxPersistentBytes / 2) return; + persistent.set(k, { scope, id, hash, json }); + persistentRawBytes += json.length; + // Cap raw stored JSON at ~4 MiB (compresses well under 2 MiB; enforced tightly on export) + while (persistent.size > 1200 || persistentRawBytes > maxPersistentBytes * 2) { + const oldestKey = persistent.keys().next().value; + const oldest = persistent.get(oldestKey); + persistentRawBytes -= oldest.json.length; + persistent.delete(oldestKey); + } + } + + function loadPersistentState(bytes) { + persistent.clear(); + persistentRawBytes = 0; + if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return; + try { + const rows = JSON.parse(zlib.inflateRawSync(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString('utf8')); + if (!Array.isArray(rows)) return; + for (const r of rows) { + if (r && typeof r.scope === 'string' && typeof r.id === 'string' && typeof r.hash === 'string' && typeof r.json === 'string') { + rememberPersistent(r.scope, r.id, r.hash, r.json); + } + } + } catch { + // ignore corrupt blob + } + } + + function exportPersistentState() { + const rows = Array.from(persistent.values()); + let out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8'), { level: 6 }); + while (out.byteLength > maxPersistentBytes && rows.length > 0) { + rows.splice(0, Math.max(1, Math.floor(rows.length * 0.15))); + out = zlib.deflateRawSync(Buffer.from(JSON.stringify(rows), 'utf8'), { level: 6 }); + } + return new Uint8Array(out.buffer, out.byteOffset, out.byteLength); + } + + function simulateColdReconnect() { + const snap = exportPersistentState(); + cache.clear(); + cacheBytes = 0; + inflight.clear(); + loadPersistentState(snap); + } + + function rememberCache(key, id, normalized, bytes) { + const prev = cache.get(key); + if (prev) { + cacheBytes -= prev.bytes; + cache.delete(key); + } + if (bytes > maxCacheBytes / 2) return; + cache.set(key, { id, normalized, bytes }); + cacheBytes += bytes; + while (cache.size > 32 || cacheBytes > maxCacheBytes) { + const oldestKey = cache.keys().next().value; + const oldest = cache.get(oldestKey); + cacheBytes -= oldest.bytes; + cache.delete(oldestKey); + } + } + + function recordPersistentFromValue(channel, value) { + const items = extractColdItems(channel, value); + for (let i = 0; i < items.length; i += 1) { + const it = items[i]; + rememberPersistent(it.scope, it.id, it.hash, it.json); + } + } + + if (options.persistentState) { + loadPersistentState(options.persistentState); + } + + function buildColdManifest(channel, argsKey) { + const scope = coldScopeFor(channel, argsKey); + const coldList = []; + const coldPairs = []; + let pinnedOnly = false; + if (channel === 'local-db:sessions:list') { + try { pinnedOnly = JSON.parse(argsKey)?.scope === 'pinned'; } catch { /* ignore */ } + } + if (scope) { + for (const entry of persistent.values()) { + if (entry.scope !== scope) continue; + if (pinnedOnly && !entry.json.includes('"pinned":true')) continue; + coldList.push(entry); + coldPairs.push([entry.id, entry.hash]); + } + } + return { coldList, coldPairs }; + } + + function beginRead({ readId, channel, argsKey }) { + const key = `${channel}\u0000${argsKey}`; + const cached = cache.get(key); + + if (cached) { + const scope = coldScopeFor(channel, argsKey); + let hasCold = false; + if (scope) { + for (const entry of persistent.values()) { + if (entry.scope === scope) { + hasCold = true; + break; + } + } + } + inflight.set(readId, { channel, argsKey, key, cached, coldList: null }); + return packFrame(hasCold ? { base: cached.id, hasCold: 1 } : { base: cached.id }); + } + + const { coldList, coldPairs } = buildColdManifest(channel, argsKey); + inflight.set(readId, { channel, argsKey, key, cached: null, coldList }); + return packFrame(coldPairs.length > 0 ? { cold: coldPairs } : {}); + } + + function receiveResponse({ readId, responseBytes }) { + const state = inflight.get(readId); + const resp = unpackFrame(responseBytes); + + if (resp.t === 'miss') { + const { coldList, coldPairs } = buildColdManifest(state.channel, state.argsKey); + state.coldList = coldList; + return { done: false, nextRequestBytes: packFrame(coldPairs.length > 0 ? { cold: coldPairs } : {}) }; + } + + inflight.delete(readId); + + let finalValue; + let normalized; + const suffixed = resp.sx === 1; + + if (resp.t === 'same') { + if (!state.cached) throw new Error('Unexpected same without cached base'); + normalized = JSON.parse(JSON.stringify(state.cached.normalized)); + finalValue = denormalizePageAfterApply(normalized, suffixed); + } else if (resp.t === 'delta') { + if (!state.cached || state.cached.id !== resp.base) { + throw new Error(`Delta base mismatch: expected ${state.cached?.id}, got ${resp.base}`); + } + const baseClone = JSON.parse(JSON.stringify(state.cached.normalized)); + normalized = applyPatch(baseClone, resp.p); + finalValue = denormalizePageAfterApply(normalized, suffixed); + } else if (resp.t === 'cold') { + finalValue = restoreColdKnown(state.channel, resp.v, resp.r, resp.mr, resp.sf || '', state.coldList); + normalized = normalizePageForDiff(finalValue).normalized; + } else if (resp.t === 'full') { + finalValue = resp.v; + normalized = normalizePageForDiff(finalValue).normalized; + } else { + throw new Error(`Unknown response kind: ${resp.t}`); + } + + const normJson = JSON.stringify(normalized); + rememberCache(state.key, resp.id, normalized, normJson.length); + recordPersistentFromValue(state.channel, finalValue); + return { done: true, value: finalValue }; + } + + return { + beginRead, + receiveResponse, + exportPersistentState, + simulateColdReconnect, + }; +} diff --git a/questions/opt-device-link-delta-sync/v2/reference/tests/smoke.test.mjs b/questions/opt-device-link-delta-sync/v2/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..dfd2fa3 --- /dev/null +++ b/questions/opt-device-link-delta-sync/v2/reference/tests/smoke.test.mjs @@ -0,0 +1,179 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + PROTOCOL_MAX_ROUNDS, + DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, + DEFAULT_MAX_CACHE_BYTES, + DEFAULT_MAX_PERSISTENT_BYTES, + DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, + createHostSyncEndpoint, + createClientSyncEndpoint, +} from '../src/sync-protocol.mjs'; +import { loadPublicTrace } from '../lib/trace-loader.mjs'; +import { runIsolatedTrace } from '../lib/rpc-harness.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SRC_DIR = path.resolve(HERE, '../src'); + +function exchangeRpc(host, client, { readId, channel, argsKey, groundTruthValue }) { + const snapshotBefore = JSON.stringify(groundTruthValue); + let round = 0; + let req = client.beginRead({ readId, channel, argsKey }); + let wireBytes = 0; + + while (true) { + assert.ok(req instanceof Uint8Array, `requestBytes at round ${round} must be Uint8Array`); + wireBytes += req.byteLength; + const res = host.handleFrame({ channel, argsKey, requestBytes: req, groundTruthValue, round }); + assert.ok(res instanceof Uint8Array, `responseBytes at round ${round} must be Uint8Array`); + wireBytes += res.byteLength; + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + assert.equal(typeof step?.done, 'boolean', 'receiveResponse must return { done: boolean, ... }'); + if (step.done) { + assert.deepStrictEqual(step.value, groundTruthValue); + assert.equal(JSON.stringify(groundTruthValue), snapshotBefore, 'host must not mutate groundTruthValue'); + return { value: step.value, wireBytes, rounds: round + 1 }; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS, `exceeded PROTOCOL_MAX_ROUNDS (${PROTOCOL_MAX_ROUNDS})`); + req = step.nextRequestBytes; + } +} + +test('required constants and endpoint exports match contract', () => { + assert.equal(PROTOCOL_MAX_ROUNDS, 4); + assert.equal(DEFAULT_MAX_BASE_SNAPSHOTS_PER_KEY, 8); + assert.equal(DEFAULT_MAX_CACHE_BYTES, 4 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BYTES, 2 * 1024 * 1024); + assert.equal(DEFAULT_MAX_PERSISTENT_BODY_ENTRIES, 512); + assert.equal(typeof createHostSyncEndpoint, 'function'); + assert.equal(typeof createClientSyncEndpoint, 'function'); +}); + +test('exact JSON parity across edge-case shapes, Unicode, deletions, and prototype-named keys', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'custom:edge-cases'; + const argsKey = '{"case":"all"}'; + + const payloads = [ + null, + true, + false, + 0, + -42.75, + '', + 'Hello 🌍 你好世界「增量同步」\nLine 2\t\u0000nullbyte', + [], + {}, + { + emptyArr: [], + emptyObj: {}, + nil: null, + constructor: 'plain-constructor-value', + toString: 123, + valueOf: [true, false, null], + hasOwnProperty: { nested: 'ok' }, + items: [ + { id: 'a', text: 'initial text 🚀', tags: ['x', 'y'], meta: { a: 1, b: 2 } }, + { id: 'b', text: 'unchanged', tags: [], meta: null }, + ], + }, + { + emptyArr: [1], + emptyObj: { added: 'yes' }, + nil: 'no-longer-null', + constructor: 'updated-constructor', + hasOwnProperty: { nested: 'updated', extra: [0, 1] }, + // toString & valueOf intentionally deleted + items: [ + { id: 'b', text: 'unchanged', tags: [], meta: null }, + { id: 'a', text: 'initial text 🚀 + appended 中文片段 ✨', tags: ['y', 'z'], meta: { a: 1, c: 3 } }, + { id: 'c', text: 'brand new', tags: ['new'], meta: {} }, + ], + }, + ]; + + payloads.forEach((groundTruthValue, idx) => { + exchangeRpc(host, client, { + readId: `edge-${idx}`, + channel, + argsKey, + groundTruthValue, + }); + }); +}); + +test('cold reconnect, host volatile-base eviction, and concurrent in-flight stale-base reads', () => { + const host = createHostSyncEndpoint(); + const client = createClientSyncEndpoint(); + const channel = 'local-db:sessions:list'; + const argsKey = '{"scope":"all","limit":20}'; + + const makeState = (rev) => ({ + version: 2, + fetchedAt: 1765000000000 + rev * 1000, + sessions: Array.from({ length: 20 }, (_, i) => ({ + id: `s-${i}`, + title: `Session ${i}`, + phase: i === rev % 20 ? 'running' : 'idle', + unreadCount: i === rev % 20 ? rev : 0, + updatedAt: 1765000000000 + (i === rev % 20 ? rev * 1000 : 0), + })), + }); + + // Warm up + exchangeRpc(host, client, { readId: 'r1', channel, argsKey, groundTruthValue: makeState(1) }); + exchangeRpc(host, client, { readId: 'r2', channel, argsKey, groundTruthValue: makeState(2) }); + + // Concurrent stale-base pair: r3 and r4 both built before receiving r3 response + const v3 = makeState(3); + const v4 = makeState(4); + const req3 = client.beginRead({ readId: 'r3', channel, argsKey }); + const req4 = client.beginRead({ readId: 'r4', channel, argsKey }); + const res3 = host.handleFrame({ channel, argsKey, requestBytes: req3, groundTruthValue: v3, round: 0 }); + const res4 = host.handleFrame({ channel, argsKey, requestBytes: req4, groundTruthValue: v4, round: 0 }); + + const finishFromRes0 = (readId, res0, truth) => { + let round = 0; + let res = res0; + while (true) { + const step = client.receiveResponse({ readId, channel, argsKey, responseBytes: res, round }); + if (step.done) { + assert.deepStrictEqual(step.value, truth); + return; + } + round += 1; + assert.ok(round < PROTOCOL_MAX_ROUNDS); + res = host.handleFrame({ channel, argsKey, requestBytes: step.nextRequestBytes, groundTruthValue: truth, round }); + } + }; + finishFromRes0('r3', res3, v3); + finishFromRes0('r4', res4, v4); + + // Host volatile-base eviction (client stays warm) + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r5', channel, argsKey, groundTruthValue: makeState(5) }); + + // Mobile cold reconnect (client drops volatile bases, keeps persistent state <= maxPersistentBytes) + const persisted = client.exportPersistentState(); + assert.ok(persisted instanceof Uint8Array); + assert.ok(persisted.byteLength <= DEFAULT_MAX_PERSISTENT_BYTES); + client.simulateColdReconnect(); + host.evictVolatileBases(); + exchangeRpc(host, client, { readId: 'r6', channel, argsKey, groundTruthValue: makeState(6) }); +}); + +test('two-process isolated parity check on the first part of the public real workload', async () => { + const fullTrace = loadPublicTrace(); + // The first 60 steps: open a task, stream a live turn, reconnect, list + read-ahead. + const shortTrace = { ...fullTrace, steps: fullTrace.steps.slice(0, 60) }; + const stats = await runIsolatedTrace({ srcDir: SRC_DIR, trace: shortTrace }); + assert.notEqual(stats.hostPid, stats.clientPid); + assert.ok(stats.totalWireBytes > 0); + assert.ok(stats.maxRoundsUsed <= PROTOCOL_MAX_ROUNDS); + assert.ok(stats.maxPersistentBytesSeen <= DEFAULT_MAX_PERSISTENT_BYTES); +}); diff --git a/questions/opt-relay-congestion-scheduler/v1/author/editable.json b/questions/opt-relay-congestion-scheduler/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-relay-congestion-scheduler/v1/author/evaluator.mjs b/questions/opt-relay-congestion-scheduler/v1/author/evaluator.mjs new file mode 100644 index 0000000..a84d780 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/evaluator.mjs @@ -0,0 +1,642 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const Q_ROOT = path.resolve(HERE, '..'); +const SIM_PATH = path.join(Q_ROOT, 'candidate', 'sim', 'network.mjs'); +const PUBLIC_BENCH_PATH = path.join(Q_ROOT, 'candidate', 'bench', 'workload.mjs'); + +const [subDir] = process.argv.slice(2); +if (!subDir) { + throw new Error('Usage: node evaluator.mjs '); +} + +const simMod = await import(pathToFileURL(SIM_PATH).href); +const { + MAX_PACKET_BYTES, + SplitMix64, + SimLink, + sha256Hex, + generateProfileMessages, + runSimulation, +} = simMod; + +const transportUrl = pathToFileURL(path.join(subDir, 'transport.mjs')).href; +const transportMod = await import(transportUrl); +const { createRelaySender, createPeerReceiver } = transportMod; + +if (typeof createRelaySender !== 'function' || typeof createPeerReceiver !== 'function') { + throw new Error('src/transport.mjs must export createRelaySender and createPeerReceiver'); +} + +const { PUBLIC_PROFILES, aggregateMetrics } = await import(pathToFileURL(PUBLIC_BENCH_PATH).href); + +const KiB = 1024; + +// 4 Unseen Held-Out Evaluation Profiles (used to compute the 3 scored metrics!) +const HELDOUT_PROFILES = [ + { + name: 'heldout-4g-burst', + seed: 51515, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 3_200_000, + propagationDelayMs: 60, + jitterMs: 14, + jitterFifo: true, + lossProb: 0.02, + burstEveryMs: 2400, + burstLenMs: 140, + burstLossProb: 0.45, + queueBytes: 48_000, + }, + uplink: { + bitsPerSecond: 3_200_000, + propagationDelayMs: 60, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 96, 64, 96, 80, 96].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 48, 96, 64, 96, 80, 96, 64].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [48, 96, 64, 96, 80, 96, 64, 96].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 4400]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, + { + name: 'heldout-cross-ocean', + seed: 62626, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 8_000_000, + propagationDelayMs: 110, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.025, + reorderProb: 0.03, + reorderExtraMs: 35, + dupProb: 0.01, + queueBytes: 36_000, + }, + uplink: { + bitsPerSecond: 8_000_000, + propagationDelayMs: 110, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + reorderProb: 0.02, + reorderExtraMs: 25, + dupProb: 0.01, + queueBytes: 64_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [128, 192, 128, 256, 128, 192, 128, 256, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [192, 128, 256, 128, 192, 128, 256, 128, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 140, + minBytes: 140, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 3200]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, + { + name: 'heldout-wifi-stall', + seed: 73737, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 2_500_000, + propagationDelayMs: 40, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.03, + stallEveryMs: 3200, + stallLenMs: 350, + stallOffsetMs: 2000, + queueBytes: 40_000, + }, + uplink: { + bitsPerSecond: 2_500_000, + propagationDelayMs: 40, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.015, + stallEveryMs: 3200, + stallLenMs: 350, + stallOffsetMs: 2000, + queueBytes: 40_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 128, 64, 96, 80, 128].map((k) => k * KiB), + waveTimesMs: [0, 1200, 2400], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 64, 128, 48, 96, 80, 128, 64].map((k) => k * KiB), + waveTimesMs: [0, 1200, 2400], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 880, + deadlineMs: 20_000, + windows: [[120, 4200]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, + { + name: 'heldout-policer-blackout', + seed: 84848, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 6_000_000, + bucketBytesPerSec: 375_000, + bucketDepthBytes: 36_000, + propagationDelayMs: 45, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.015, + queueBytes: 48_000, + outages: [[2400, 4400]], + }, + uplink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 45, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 48_000, + outages: [[2400, 4400]], + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 96, 64, 96, 80, 96].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 48, 96, 64, 96, 80, 96, 64].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [48, 96, 64, 96, 80, 96, 64, 96].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 2150], [4480, 7000]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, +]; + +function checkUnitAdversarial() { + const rng = new SplitMix64(133742); + const peers = ['u-0', 'u-1']; + const messages = []; + // Mix tiny (1 B, 120 B), boundary (1199 B, 1200 B, 1201 B), and multi-chunk (32 KiB) payloads + const sizes = [1, 120, 1199, 1200, 1201, 2400, 32 * KiB, 250, 48 * KiB, 17, 16 * KiB, 899]; + for (let i = 0; i < sizes.length; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 's-ctrl' : 's-data', + msgId: `u-msg-${i}`, + priority: sizes[i] <= 900 ? 'interactive' : 'bulk', + payload: rng.fillBytes(sizes[i]), + enqueuedMs: i * 85, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-adversarial', + seed: 99123, + peers, + downlink: { + bitsPerSecond: 2_000_000, + propagationDelayMs: 55, + jitterMs: 18, + jitterFifo: false, + lossProb: 0.12, + reorderProb: 0.18, + reorderExtraMs: 45, + dupProb: 0.12, + queueBytes: 32_000, + outages: [[700, 1400]], + }, + uplink: { + bitsPerSecond: 2_000_000, + propagationDelayMs: 55, + jitterMs: 15, + lossProb: 0.10, + reorderProb: 0.12, + reorderExtraMs: 35, + dupProb: 0.10, + queueBytes: 32_000, + outages: [[700, 1400]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `unit exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `unit packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `unit interactive deadline failed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +} + +/** + * Isolated subprocess check proving sender and receiver communicate STRICTLY + * via serialized wire Uint8Array packets with zero shared module/heap state. + */ +async function checkWireIsolationSubprocess() { + const childTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-relay-iso-')); + const child = spawn(process.execPath, [path.join(HERE, 'wire-probe-child.mjs'), subDir], { + cwd: childTmp, + env: { + PATH: process.env.PATH, + TMPDIR: childTmp, + TEMP: childTmp, + TMP: childTmp, + }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + let stderrBuf = ''; + child.stderr.on('data', (d) => { stderrBuf = (stderrBuf + d).slice(-4000); }); + + const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity }); + const lineQueue = []; + const waiters = []; + rl.on('line', (line) => { + if (waiters.length > 0) waiters.shift()(line); + else lineQueue.push(line); + }); + + const nextLine = () => new Promise((resolve, reject) => { + if (lineQueue.length > 0) return resolve(lineQueue.shift()); + const onExit = (code) => reject(new Error(`wire-probe-child exited early (${code}): ${stderrBuf}`)); + child.once('exit', onExit); + waiters.push((line) => { + child.off('exit', onExit); + resolve(line); + }); + }); + + const rpc = async (obj) => { + child.stdin.write(JSON.stringify(obj) + '\n'); + const line = await nextLine(); + const res = JSON.parse(line); + if (!res.ok) throw new Error(`wire-probe-child error: ${res.error}`); + return res; + }; + + try { + const peers = ['iso-0', 'iso-1']; + await rpc({ op: 'init', peers, maxPacketBytes: MAX_PACKET_BYTES }); + + const rng = new SplitMix64(424242); + const messages = [ + { peerId: 'iso-0', streamId: 'bulk', msgId: 'b1', priority: 'bulk', payload: rng.fillBytes(12 * KiB), enqueuedMs: 0, deadlineMs: 20_000 }, + { peerId: 'iso-1', streamId: 'bulk', msgId: 'b2', priority: 'bulk', payload: rng.fillBytes(12 * KiB), enqueuedMs: 0, deadlineMs: 20_000 }, + { peerId: 'iso-0', streamId: 'ctrl', msgId: 'i1', priority: 'interactive', payload: rng.fillBytes(300), enqueuedMs: 60, deadlineMs: 18_000 }, + { peerId: 'iso-1', streamId: 'ctrl', msgId: 'i2', priority: 'interactive', payload: rng.fillBytes(450), enqueuedMs: 120, deadlineMs: 18_000 }, + { peerId: 'iso-0', streamId: 'ctrl', msgId: 'i3', priority: 'interactive', payload: rng.fillBytes(200), enqueuedMs: 550, deadlineMs: 18_000 }, + { peerId: 'iso-1', streamId: 'ctrl', msgId: 'i4', priority: 'interactive', payload: rng.fillBytes(600), enqueuedMs: 620, deadlineMs: 18_000 }, + ]; + + const downlink = new SimLink( + { + bitsPerSecond: 3_000_000, + propagationDelayMs: 40, + jitterMs: 8, + lossProb: 0.06, + reorderProb: 0.08, + reorderExtraMs: 25, + dupProb: 0.05, + queueBytes: 36_000, + outages: [[250, 500]], + }, + 77777, + ); + const uplink = new SimLink( + { + bitsPerSecond: 3_000_000, + propagationDelayMs: 40, + jitterMs: 6, + lossProb: 0.04, + queueBytes: 36_000, + outages: [[250, 500]], + }, + 88888, + ); + + const sender = createRelaySender({ maxPacketBytes: MAX_PACKET_BYTES, peers: [...peers] }); + const expectedByStream = new Map(); + const events = []; + let seq = 0; + + for (const m of messages) { + const key = `${m.peerId}\u0000${m.streamId}`; + if (!expectedByStream.has(key)) expectedByStream.set(key, { head: 0, items: [] }); + expectedByStream.get(key).items.push({ + msgId: m.msgId, + sha256: sha256Hex(m.payload), + byteLength: m.payload.byteLength, + enqueuedUs: Math.round(m.enqueuedMs * 1000), + deadlineMs: m.deadlineMs, + priority: m.priority, + }); + events.push({ timeUs: Math.round(m.enqueuedMs * 1000), seq: seq++, type: 'ENQUEUE', data: m }); + } + + const pushEv = (timeUs, type, data) => { + events.push({ timeUs, seq: seq++, type, data }); + }; + + const receiverNextWakeUs = new Map(peers.map((p) => [p, Infinity])); + let senderNextWakeUs = Infinity; + let nowUs = 0; + let deliveredCount = 0; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + assert.ok(steps < 200_000 && nowUs <= 60_000_000, `wire isolation probe stalled (${deliveredCount}/${messages.length})`); + events.sort((a, b) => a.timeUs - b.timeUs || a.seq - b.seq); + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touched = new Set(); + + while (events.length > 0 && events[0].timeUs <= nowUs) { + const ev = events.shift(); + if (ev.type === 'ENQUEUE') { + sender.enqueue(nowMs, { ...ev.data, payload: new Uint8Array(ev.data.payload) }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const hex = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex'); + const res = await rpc({ op: 'data', peerId, nowMs, hex }); + for (const item of res.delivered) { + const key = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(key); + assert.ok(q && q.head < q.items.length, `Unexpected wire-isolated delivery ${key}/${item.msgId}`); + const exp = q.items[q.head++]; + assert.equal(item.msgId, exp.msgId, 'Wire-isolated FIFO order mismatch'); + assert.equal(item.byteLength, exp.byteLength, 'Wire-isolated payload length mismatch'); + assert.equal(item.sha256, exp.sha256, 'Wire-isolated SHA-256 mismatch'); + if (exp.priority === 'interactive') { + assert.ok((nowUs - exp.enqueuedUs) / 1000 <= exp.deadlineMs, 'Wire-isolated interactive deadline miss'); + } + deliveredCount += 1; + } + for (const ackHex of res.ackPackets) { + assert.ok(typeof ackHex === 'string', 'Invalid ACK packet from isolated receiver'); + const buf = Buffer.from(ackHex, 'hex'); + const ackBytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + assert.ok(ackBytes.byteLength > 0 && ackBytes.byteLength <= MAX_PACKET_BYTES, 'ACK bounds violated'); + for (const atUs of uplink.transmit(nowUs, ackBytes.byteLength)) { + pushEv(atUs, 'ACK_ARRIVAL', { peerId, bytes: new Uint8Array(ackBytes) }); + } + } + touched.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + sender.onAckPacket(nowMs, ev.data.peerId, new Uint8Array(ev.data.bytes)); + senderActive = true; + } + } + + for (const peerId of peers) { + if (touched.has(peerId) || receiverNextWakeUs.get(peerId) <= nowUs) { + const res = await rpc({ op: 'poll', peerId, nowMs }); + for (const ackHex of res.ackPackets) { + assert.ok(typeof ackHex === 'string', 'Invalid poll ACK packet'); + const buf = Buffer.from(ackHex, 'hex'); + const ackBytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + assert.ok(ackBytes.byteLength > 0 && ackBytes.byteLength <= MAX_PACKET_BYTES, 'ACK bounds violated'); + for (const atUs of uplink.transmit(nowUs, ackBytes.byteLength)) { + pushEv(atUs, 'ACK_ARRIVAL', { peerId, bytes: new Uint8Array(ackBytes) }); + } + } + receiverNextWakeUs.set( + peerId, + res.nextWakeMs !== null ? Math.max(nowUs + 10, Math.ceil(res.nextWakeMs * 1000)) : Infinity, + ); + } + } + + if (deliveredCount >= messages.length) break; + + if (senderActive) { + const tx = sender.pollTx(nowMs); + for (const pkt of tx?.packets ?? []) { + assert.ok(peers.includes(pkt.peerId), `Invalid peerId ${pkt.peerId}`); + assert.ok( + pkt.bytes instanceof Uint8Array && pkt.bytes.byteLength > 0 && pkt.bytes.byteLength <= MAX_PACKET_BYTES, + `Invalid TX packet length ${pkt.bytes?.byteLength}`, + ); + const copy = new Uint8Array(pkt.bytes); + for (const atUs of downlink.transmit(nowUs, copy.byteLength)) { + pushEv(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = tx?.nextWakeMs; + senderNextWakeUs = typeof nw === 'number' && Number.isFinite(nw) + ? Math.max(nowUs + 10, Math.ceil(nw * 1000)) + : Infinity; + } + + if (deliveredCount >= messages.length) break; + + events.sort((a, b) => a.timeUs - b.timeUs || a.seq - b.seq); + let nextUs = events.length > 0 ? events[0].timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const w of receiverNextWakeUs.values()) { + if (w < nextUs) nextUs = w; + } + assert.ok(Number.isFinite(nextUs), `wire isolation probe idle with ${deliveredCount}/${messages.length} delivered`); + nowUs = Math.max(nowUs + 1, nextUs); + } + + await rpc({ op: 'quit' }); + } finally { + child.kill('SIGKILL'); + await fs.rm(childTmp, { recursive: true, force: true }); + } +} + +const errors = []; +let unitExactOk = false; +let gate_wire_isolation = false; + +try { + checkUnitAdversarial(); + unitExactOk = true; +} catch (err) { + errors.push(`unitAdversarial: ${err.message}`); +} + +try { + await checkWireIsolationSubprocess(); + gate_wire_isolation = true; +} catch (err) { + errors.push(`wireIsolation: ${err.message}`); +} + +const publicResults = []; +for (const profile of PUBLIC_PROFILES) { + try { + const messages = generateProfileMessages(profile); + const res = runSimulation({ profile, messages, createRelaySender, createPeerReceiver }); + publicResults.push(res); + if (!res.ok) errors.push(`public/${profile.name}: ${res.violations.slice(0, 3).join('; ')}`); + if (res.jainsFairness < 0.85) { + errors.push(`public/${profile.name}: fairness ${res.jainsFairness.toFixed(4)} < 0.85`); + } + } catch (err) { + errors.push(`public/${profile.name}: ${err.message}`); + } +} + +const heldoutResults = []; +for (const profile of HELDOUT_PROFILES) { + try { + const messages = generateProfileMessages(profile); + const res = runSimulation({ profile, messages, createRelaySender, createPeerReceiver }); + heldoutResults.push(res); + if (!res.ok) errors.push(`heldout/${profile.name}: ${res.violations.slice(0, 3).join('; ')}`); + if (res.jainsFairness < 0.85) { + errors.push(`heldout/${profile.name}: fairness ${res.jainsFairness.toFixed(4)} < 0.85`); + } + } catch (err) { + errors.push(`heldout/${profile.name}: ${err.message}`); + } +} + +const allProfileResults = [...publicResults, ...heldoutResults]; +const allProfilesRan = publicResults.length === PUBLIC_PROFILES.length && heldoutResults.length === HELDOUT_PROFILES.length; + +const gate_exact_delivery = + unitExactOk + && allProfilesRan + && allProfileResults.every((r) => r.exactDeliveryOk === true); + +const gate_zero_interactive_drops = + unitExactOk + && allProfilesRan + && allProfileResults.every((r) => r.interactiveDeadlineOk === true && r.packetBoundsOk === true); + +const gate_peer_fairness = + allProfilesRan + && allProfileResults.every((r) => r.jainsFairness >= 0.85); + +const heldoutSummary = heldoutResults.length === HELDOUT_PROFILES.length + ? aggregateMetrics(heldoutResults) + : { + interactive_p99_ms: 999999, + wire_overhead_pct: 999999, + bulk_goodput_pct: 0, + min_jains_fairness: 0, + }; + +const publicSummary = publicResults.length === PUBLIC_PROFILES.length + ? aggregateMetrics(publicResults) + : null; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_delivery, + gate_zero_interactive_drops, + gate_peer_fairness, + gate_wire_isolation, + }, + metrics: { + interactive_p99_ms: heldoutSummary.interactive_p99_ms, + wire_overhead_pct: heldoutSummary.wire_overhead_pct, + bulk_goodput_pct: heldoutSummary.bulk_goodput_pct, + }, + details: { + errors, + publicSummary, + heldoutSummary, + profiles: allProfileResults.map((r) => ({ + name: r.name, + ok: r.ok, + interactiveP99Ms: Number(r.interactiveP99Ms.toFixed(2)), + interactiveP50Ms: Number(r.interactiveP50Ms.toFixed(2)), + interactiveMaxMs: Number(r.interactiveMaxMs.toFixed(2)), + wireOverheadPct: Number(r.wireOverheadPct.toFixed(2)), + bulkGoodputPct: Number(r.bulkGoodputPct.toFixed(2)), + jainsFairness: Number(r.jainsFairness.toFixed(4)), + jainsFairnessMidpoint: Number(r.jainsFairnessMidpoint.toFixed(4)), + jainsFairnessCompletion: Number(r.jainsFairnessCompletion.toFixed(4)), + finishMs: Number(r.finishMs.toFixed(1)), + downlinkStats: r.downlinkStats, + uplinkStats: r.uplinkStats, + })), + }, +})); diff --git a/questions/opt-relay-congestion-scheduler/v1/author/grade.py b/questions/opt-relay-congestion-scheduler/v1/author/grade.py new file mode 100644 index 0000000..595cbdf --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/simulator/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=180 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-relay-congestion-scheduler/v1/author/grade_impl.py b/questions/opt-relay-congestion-scheduler/v1/author/grade_impl.py new file mode 100644 index 0000000..a302df2 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/grade_impl.py @@ -0,0 +1,39 @@ +"""Isolated pure-Node quantitative grader: runs unit + subprocess wire-isolation + public + held-out profiles.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-relay-opt-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=120 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-relay-congestion-scheduler/v1/author/result-channel.mjs b/questions/opt-relay-congestion-scheduler/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/author/wire-probe-child.mjs b/questions/opt-relay-congestion-scheduler/v1/author/wire-probe-child.mjs new file mode 100644 index 0000000..8854998 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/author/wire-probe-child.mjs @@ -0,0 +1,68 @@ +import crypto from 'node:crypto'; +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [subDir] = process.argv.slice(2); +const transportMod = await import(pathToFileURL(path.join(subDir, 'transport.mjs')).href); +const { createPeerReceiver } = transportMod; + +const receivers = new Map(); + +function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +function toHex(bytes) { + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex'); +} + +function fromHex(hex) { + const buf = Buffer.from(hex, 'hex'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + +rl.on('line', (line) => { + if (!line.trim()) return; + try { + const req = JSON.parse(line); + if (req.op === 'init') { + receivers.clear(); + for (const peerId of req.peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes: req.maxPacketBytes })); + } + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'data') { + const recv = receivers.get(req.peerId); + const res = recv.onDataPacket(req.nowMs, fromHex(req.hex)); + const delivered = (res?.delivered ?? []).map((item) => ({ + streamId: item.streamId, + msgId: item.msgId, + byteLength: item.payload instanceof Uint8Array ? item.payload.byteLength : -1, + sha256: item.payload instanceof Uint8Array ? sha256Hex(item.payload) : null, + })); + const ackPackets = (res?.ackPackets ?? []).map((p) => + p instanceof Uint8Array ? toHex(p) : null, + ); + process.stdout.write(JSON.stringify({ ok: true, delivered, ackPackets }) + '\n'); + } else if (req.op === 'poll') { + const recv = receivers.get(req.peerId); + const res = recv.pollControl(req.nowMs); + const ackPackets = (res?.ackPackets ?? []).map((p) => + p instanceof Uint8Array ? toHex(p) : null, + ); + const nw = res?.nextWakeMs; + const nextWakeMs = typeof nw === 'number' && Number.isFinite(nw) ? nw : null; + process.stdout.write(JSON.stringify({ ok: true, ackPackets, nextWakeMs }) + '\n'); + } else if (req.op === 'quit') { + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + process.exit(0); + } else { + process.stdout.write(JSON.stringify({ ok: false, error: `unknown op ${req.op}` }) + '\n'); + } + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: err?.message ?? String(err) }) + '\n'); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..91b4295 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/CONTRACT.md @@ -0,0 +1,49 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public profiles, and all 4 unseen held-out profiles: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..615cd4d --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public profiles. + - `npm run bench` — runs the 4 public weak-network profiles (`cellular-mixed`, `airplane-wifi`, `shallow-queue-fanout`, `cloud-policer-outage`) and prints per-profile and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/TASK.md b/questions/opt-relay-congestion-scheduler/v1/candidate/TASK.md new file mode 100644 index 0000000..b63ac47 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/TASK.md @@ -0,0 +1,30 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, 120–900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring ultra-low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, 24–256 KiB each, e.g., `messages:view`, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +## Observed Production Symptoms + +1. **Multi-second interactive Head-of-Line (HoL) blocking & tail latency**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — pushing interactive P99 above 4,000–6,000 ms on weak links. +2. **Severe wire overhead (>45–70%) from unpaced bursts and Go-Back-N retransmissions**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts at window boundaries into shallow bottleneck queues (24–36 KB) and token-bucket policers, triggering tail/policer drops, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Poor bottleneck utilization (~15–20% bulk goodput)**: The static frame budget cannot scale up on higher-BDP links (e.g., cross-ocean 6–8 Mbps paths), collapses under random wireless loss or periodic stalls, and recovers slowly after multi-second outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/blackout detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics across diverse unseen weak-network profiles (cellular burst loss, high-BDP reordering + shallow queues, periodic Wi-Fi stalls, token-bucket policers, and multi-second blackouts): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Note that final grading evaluates on **both** the public profiles and unseen held-out profiles with different rates, RTTs, burst/reorder/stall/policer/blackout regimes, and seeds. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..a3a7c0e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/bench/workload.mjs @@ -0,0 +1,267 @@ +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const KiB = 1024; + +export const PUBLIC_PROFILES = [ + { + name: 'cellular-mixed', + seed: 10101, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.015, + queueBytes: 64_000, + }, + uplink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 3600]], + peers: ['peer-2', 'peer-3', 'peer-0', 'peer-2', 'peer-3', 'peer-1'], + }, + }, + { + name: 'airplane-wifi', + seed: 20202, + peers: ['peer-0', 'peer-1', 'peer-2'], + downlink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 22, + jitterFifo: true, + lossProb: 0.04, + burstEveryMs: 3200, + burstLenMs: 160, + burstLossProb: 0.45, + queueBytes: 48_000, + }, + uplink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 18, + jitterFifo: true, + lossProb: 0.02, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [48, 64, 32, 64, 48, 64, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [64, 48, 64, 32, 64, 48, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + ], + interactive: { + count: 100, + minBytes: 120, + maxBytes: 850, + deadlineMs: 20_000, + windows: [[150, 4600]], + peers: ['peer-2', 'peer-2', 'peer-0', 'peer-2', 'peer-1'], + }, + }, + { + name: 'shallow-queue-fanout', + seed: 30303, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 24_000, + }, + uplink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [64, 128, 96, 128, 64, 128, 96, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 140, + minBytes: 150, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[100, 3600]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, + { + name: 'cloud-policer-outage', + seed: 40404, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 5_000_000, + bucketBytesPerSec: 437_500, + bucketDepthBytes: 40_000, + propagationDelayMs: 40, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + uplink: { + bitsPerSecond: 5_000_000, + propagationDelayMs: 40, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 1950], [4080, 6100]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, +]; + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/package.json b/questions/opt-relay-congestion-scheduler/v1/candidate/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/sim/network.mjs new file mode 100644 index 0000000..e53c0a6 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/sim/network.mjs @@ -0,0 +1,821 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + const size = minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 120_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/src/congestion.mjs new file mode 100644 index 0000000..9c9b8d4 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/src/congestion.mjs @@ -0,0 +1,119 @@ +/** + * Baseline congestion control & retransmission state modeled on Cindy's + * legacy fixed frame-count CongestionSendBudget + cumulative-ACK static RTO. + */ + +export const FIXED_WINDOW_MS = 240; +export const FIXED_WINDOW_FRAMES = 32; +export const STATIC_RTO_MS = 2000; +export const MAX_UNACKED_PACKETS = 48; +export const RETRY_PASS_BUDGET = 16; + +/** + * Shared physical-frame budget: fixed packet-count window per 250ms, + * byte-blind and unpaced (emits full burst at each window boundary). + */ +export class CongestionSendBudget { + constructor(capacity = FIXED_WINDOW_FRAMES, intervalMs = FIXED_WINDOW_MS) { + this.capacity = capacity; + this.intervalMs = intervalMs; + this.windowIndex = -1; + this.spent = 0; + } + + _syncWindow(nowMs) { + const idx = Math.floor(nowMs / this.intervalMs); + if (idx !== this.windowIndex) { + this.windowIndex = idx; + this.spent = 0; + } + } + + remaining(nowMs) { + this._syncWindow(nowMs); + return Math.max(0, this.capacity - this.spent); + } + + take(nowMs, frames = 1) { + this._syncWindow(nowMs); + if (this.spent + frames > this.capacity) return false; + this.spent += frames; + return true; + } + + nextRefillMs(nowMs) { + this._syncWindow(nowMs); + if (this.spent < this.capacity) return nowMs; + return (this.windowIndex + 1) * this.intervalMs; + } +} + +/** + * Per-peer cumulative-ACK tracking with static 2000ms RTO and Go-Back-N style retry. + */ +export class PeerReliabilityState { + constructor(peerId) { + this.peerId = peerId; + this.nextSeq = 1; + this.sndUna = 1; + /** @type {Map} */ + this.unacked = new Map(); + this.lastRetryPassMs = -Infinity; + } + + canSendNew() { + return this.unacked.size < MAX_UNACKED_PACKETS; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs) { + this.unacked.set(seq, { + seq, + bytes, + firstSentMs: nowMs, + lastSentMs: nowMs, + }); + } + + onCumulativeAck(ackSeq) { + if (ackSeq <= this.sndUna) return; + for (let s = this.sndUna; s < ackSeq; s += 1) { + this.unacked.delete(s); + } + this.sndUna = ackSeq; + } + + hasTimedOut(nowMs) { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return false; + return nowMs - oldest.lastSentMs >= STATIC_RTO_MS; + } + + nextTimeoutMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + return oldest.lastSentMs + STATIC_RTO_MS; + } + + /** + * Go-Back-N style retransmit pass from sndUna onward (cumulative ACK gives no SACK info). + */ + collectRetransmits(nowMs, maxFrames) { + if (!this.hasTimedOut(nowMs) || maxFrames <= 0) return []; + const limit = Math.min(maxFrames, RETRY_PASS_BUDGET); + const out = []; + for (let s = this.sndUna; s < this.nextSeq && out.length < limit; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + entry.lastSentMs = nowMs; + out.push(entry.bytes); + } + this.lastRetryPassMs = nowMs; + return out; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/src/scheduler.mjs new file mode 100644 index 0000000..7be4a6e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/src/scheduler.mjs @@ -0,0 +1,118 @@ +/** + * Baseline relay scheduler: + * - Per-peer FIFO message queue (no interactive priority queue) + * - Atomic multi-packet message turns (no interactive preemption mid-bulk-message) + * - Round-robin across peers at whole-message boundaries + */ + +export class RelayScheduler { + constructor(peers) { + this.peers = [...peers]; + /** @type {Map>} */ + this.queues = new Map(); + for (const peerId of this.peers) { + this.queues.set(peerId, []); + } + this.activePeer = null; + this.cursor = 0; + } + + enqueue(msg, chunkSize) { + let q = this.queues.get(msg.peerId); + if (!q) { + q = []; + this.queues.set(msg.peerId, q); + this.peers.push(msg.peerId); + } + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + // Admitted ahead of unstarted bulk messages on the same peer (like InvokeScheduler), + // but never preempts an already-started atomic bulk message or other peers' turns. + let insertIdx = q.length; + const startIdx = q.length > 0 && q[0].nextSegment > 0 ? 1 : 0; + for (let i = startIdx; i < q.length; i += 1) { + if (q[i].priority !== 'interactive') { + insertIdx = i; + break; + } + } + q.splice(insertIdx, 0, entry); + } else { + q.push(entry); + } + } + + hasPending() { + for (const q of this.queues.values()) { + if (q.length > 0) return true; + } + return false; + } + + /** + * Pick next segment to transmit. Keeps sending the active atomic message + * to completion unless that peer's reliability window is temporarily full. + */ + nextSegment(canPeerSend) { + if (this.activePeer !== null) { + const aq = this.queues.get(this.activePeer); + if (aq && aq.length > 0) { + if (canPeerSend(this.activePeer)) { + return this._popSegmentFrom(this.activePeer, aq); + } + } else { + this.activePeer = null; + } + } + + const n = this.peers.length; + for (let i = 0; i < n; i += 1) { + const idx = (this.cursor + i) % n; + const peerId = this.peers[idx]; + const q = this.queues.get(peerId); + if (!q || q.length === 0) continue; + if (!canPeerSend(peerId)) continue; + this.activePeer = peerId; + this.cursor = (idx + 1) % n; + return this._popSegmentFrom(peerId, q); + } + return null; + } + + _popSegmentFrom(peerId, q) { + const head = q[0]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const slice = head.payload.subarray(start, end); + head.nextSegment += 1; + const finished = head.nextSegment >= head.totalSegments; + if (finished) { + q.shift(); + if (this.activePeer === peerId) { + this.activePeer = null; + } + } + return { + peerId, + streamId: head.streamId, + msgId: head.msgId, + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data: slice, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/src/transport.mjs new file mode 100644 index 0000000..73ab8ee --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/src/transport.mjs @@ -0,0 +1,217 @@ +import { CongestionSendBudget, PeerReliabilityState } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_ACK = 2; +const MAX_META_RESERVE = 140; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(meta, payloadSlice, maxPacketBytes) { + const headerBytes = textEncoder.encode(JSON.stringify(meta)); + const totalLen = 3 + headerBytes.byteLength + payloadSlice.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Encoded data packet (${totalLen} B) exceeds maxPacketBytes (${maxPacketBytes} B)`); + } + const out = new Uint8Array(totalLen); + out[0] = PKT_DATA; + out[1] = (headerBytes.byteLength >>> 8) & 0xff; + out[2] = headerBytes.byteLength & 0xff; + out.set(headerBytes, 3); + out.set(payloadSlice, 3 + headerBytes.byteLength); + return out; +} + +function decodeDataPacket(packetBytes) { + if (!(packetBytes instanceof Uint8Array) || packetBytes.byteLength < 3 || packetBytes[0] !== PKT_DATA) { + return null; + } + const headerLen = (packetBytes[1] << 8) | packetBytes[2]; + if (3 + headerLen > packetBytes.byteLength) return null; + const meta = JSON.parse(textDecoder.decode(packetBytes.subarray(3, 3 + headerLen))); + const data = packetBytes.subarray(3 + headerLen); + return { meta, data }; +} + +function encodeAckPacket(ackSeq) { + const body = textEncoder.encode(JSON.stringify({ v: 1, ackSeq })); + const out = new Uint8Array(1 + body.byteLength); + out[0] = PKT_ACK; + out.set(body, 1); + return out; +} + +function decodeAckPacket(packetBytes) { + if (!(packetBytes instanceof Uint8Array) || packetBytes.byteLength < 2 || packetBytes[0] !== PKT_ACK) { + return null; + } + return JSON.parse(textDecoder.decode(packetBytes.subarray(1))); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - MAX_META_RESERVE); + + const budget = new CongestionSendBudget(); + const scheduler = new RelayScheduler(peers); + const peerStates = new Map(); + for (const peerId of peers) { + peerStates.set(peerId, new PeerReliabilityState(peerId)); + } + + function getPeerState(peerId) { + let st = peerStates.get(peerId); + if (!st) { + st = new PeerReliabilityState(peerId); + peerStates.set(peerId, st); + } + return st; + } + + return { + enqueue(nowMs, msg) { + getPeerState(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const ack = decodeAckPacket(packetBytes); + if (!ack || typeof ack.ackSeq !== 'number') return; + getPeerState(peerId).onCumulativeAck(ack.ackSeq); + }, + + pollTx(nowMs) { + const packets = []; + + // 1. Retransmissions for timed-out peers (Go-Back-N from sndUna) + for (const [peerId, st] of peerStates) { + const rem = budget.remaining(nowMs); + if (rem <= 0) break; + if (st.hasTimedOut(nowMs)) { + const retries = st.collectRetransmits(nowMs, rem); + for (const bytes of retries) { + if (!budget.take(nowMs, 1)) break; + packets.push({ peerId, bytes }); + } + } + } + + // 2. New segments using remaining fixed-window frame budget + while (budget.remaining(nowMs) > 0) { + const seg = scheduler.nextSegment((peerId) => getPeerState(peerId).canSendNew()); + if (!seg) break; + const st = getPeerState(seg.peerId); + const seq = st.allocateSeq(); + const bytes = encodeDataPacket( + { + v: 1, + seq, + s: seg.streamId, + m: seg.msgId, + i: seg.segIndex, + n: seg.totalSegments, + t: seg.totalBytes, + }, + seg.data, + maxPacketBytes, + ); + budget.take(nowMs, 1); + st.recordSent(seq, bytes, nowMs); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + let hasUnacked = false; + for (const st of peerStates.values()) { + if (st.unacked.size > 0) { + hasUnacked = true; + const rtoMs = st.nextTimeoutMs(); + if (rtoMs < nextWakeMs) nextWakeMs = rtoMs; + } + } + if (scheduler.hasPending() || (hasUnacked && budget.remaining(nowMs) === 0)) { + const refillMs = budget.nextRefillMs(nowMs); + if (refillMs > nowMs && refillMs < nextWakeMs) { + nextWakeMs = refillMs; + } + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + /** @type {Map} */ + const reorderBuffer = new Map(); + /** @type {Map, received: number }>} */ + const reassemblies = new Map(); + + function assembleSegment(meta, data) { + if (meta.n === 1) { + return { streamId: meta.s, msgId: meta.m, payload: new Uint8Array(data) }; + } + const key = `${meta.s}\u0000${meta.m}`; + let entry = reassemblies.get(key); + if (!entry) { + entry = { + streamId: meta.s, + msgId: meta.m, + totalSegments: meta.n, + totalBytes: meta.t, + parts: new Array(meta.n).fill(null), + received: 0, + }; + reassemblies.set(key, entry); + } + if (entry.parts[meta.i] === null) { + entry.parts[meta.i] = new Uint8Array(data); + entry.received += 1; + } + if (entry.received === entry.totalSegments) { + reassemblies.delete(key); + const out = new Uint8Array(entry.totalBytes); + let offset = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], offset); + offset += entry.parts[i].byteLength; + } + return { streamId: entry.streamId, msgId: entry.msgId, payload: out }; + } + return null; + } + + return { + onDataPacket(nowMs, packetBytes) { + const parsed = decodeDataPacket(packetBytes); + if (!parsed) return { delivered: [], ackPackets: [] }; + + const { meta, data } = parsed; + const delivered = []; + if (meta.seq >= rcvNext && !reorderBuffer.has(meta.seq)) { + reorderBuffer.set(meta.seq, { meta, data: new Uint8Array(data) }); + } + + while (reorderBuffer.has(rcvNext)) { + const item = reorderBuffer.get(rcvNext); + reorderBuffer.delete(rcvNext); + rcvNext += 1; + const msg = assembleSegment(item.meta, item.data); + if (msg) delivered.push(msg); + } + + // Immediate cumulative-ACK-only response (no SACK, no delayed coalescing) + return { + delivered, + ackPackets: [encodeAckPacket(rcvNext)], + }; + }, + + pollControl(nowMs) { + return { ackPackets: [], nextWakeMs: Infinity }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/candidate/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..91b4295 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,49 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public profiles, and all 4 unseen held-out profiles: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..615cd4d --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public profiles. + - `npm run bench` — runs the 4 public weak-network profiles (`cellular-mixed`, `airplane-wifi`, `shallow-queue-fanout`, `cloud-policer-outage`) and prints per-profile and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/TASK.md b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..b63ac47 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/TASK.md @@ -0,0 +1,30 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, 120–900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring ultra-low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, 24–256 KiB each, e.g., `messages:view`, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +## Observed Production Symptoms + +1. **Multi-second interactive Head-of-Line (HoL) blocking & tail latency**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — pushing interactive P99 above 4,000–6,000 ms on weak links. +2. **Severe wire overhead (>45–70%) from unpaced bursts and Go-Back-N retransmissions**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts at window boundaries into shallow bottleneck queues (24–36 KB) and token-bucket policers, triggering tail/policer drops, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Poor bottleneck utilization (~15–20% bulk goodput)**: The static frame budget cannot scale up on higher-BDP links (e.g., cross-ocean 6–8 Mbps paths), collapses under random wireless loss or periodic stalls, and recovers slowly after multi-second outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/blackout detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics across diverse unseen weak-network profiles (cellular burst loss, high-BDP reordering + shallow queues, periodic Wi-Fi stalls, token-bucket policers, and multi-second blackouts): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Note that final grading evaluates on **both** the public profiles and unseen held-out profiles with different rates, RTTs, burst/reorder/stall/policer/blackout regimes, and seeds. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..a3a7c0e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,267 @@ +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const KiB = 1024; + +export const PUBLIC_PROFILES = [ + { + name: 'cellular-mixed', + seed: 10101, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.015, + queueBytes: 64_000, + }, + uplink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 3600]], + peers: ['peer-2', 'peer-3', 'peer-0', 'peer-2', 'peer-3', 'peer-1'], + }, + }, + { + name: 'airplane-wifi', + seed: 20202, + peers: ['peer-0', 'peer-1', 'peer-2'], + downlink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 22, + jitterFifo: true, + lossProb: 0.04, + burstEveryMs: 3200, + burstLenMs: 160, + burstLossProb: 0.45, + queueBytes: 48_000, + }, + uplink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 18, + jitterFifo: true, + lossProb: 0.02, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [48, 64, 32, 64, 48, 64, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [64, 48, 64, 32, 64, 48, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + ], + interactive: { + count: 100, + minBytes: 120, + maxBytes: 850, + deadlineMs: 20_000, + windows: [[150, 4600]], + peers: ['peer-2', 'peer-2', 'peer-0', 'peer-2', 'peer-1'], + }, + }, + { + name: 'shallow-queue-fanout', + seed: 30303, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 24_000, + }, + uplink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [64, 128, 96, 128, 64, 128, 96, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 140, + minBytes: 150, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[100, 3600]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, + { + name: 'cloud-policer-outage', + seed: 40404, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 5_000_000, + bucketBytesPerSec: 437_500, + bucketDepthBytes: 40_000, + propagationDelayMs: 40, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + uplink: { + bitsPerSecond: 5_000_000, + propagationDelayMs: 40, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 1950], [4080, 6100]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, +]; + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/package.json b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/sim/network.mjs new file mode 100644 index 0000000..e53c0a6 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/sim/network.mjs @@ -0,0 +1,821 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + const size = minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 120_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/congestion.mjs new file mode 100644 index 0000000..fe7e330 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/congestion.mjs @@ -0,0 +1,120 @@ +/** + * Incomplete optimization control: + * Adds interactive priority queue & chunk preemption plus slightly faster static + * interactive retry timer, but still uses an unpaced fixed frame-count window, + * cumulative-ACK-only (no SACK), Go-Back-N retransmission, and no RTT/congestion control. + */ + +export const FIXED_WINDOW_MS = 100; +export const FIXED_WINDOW_FRAMES = 24; +export const BULK_STATIC_RTO_MS = 1800; +export const INTERACTIVE_STATIC_RTO_MS = 600; +export const MAX_UNACKED_PACKETS = 56; +export const RETRY_PASS_BUDGET = 16; + +export class CongestionSendBudget { + constructor(capacity = FIXED_WINDOW_FRAMES, intervalMs = FIXED_WINDOW_MS) { + this.capacity = capacity; + this.intervalMs = intervalMs; + this.windowIndex = -1; + this.spent = 0; + } + + _syncWindow(nowMs) { + const idx = Math.floor(nowMs / this.intervalMs); + if (idx !== this.windowIndex) { + this.windowIndex = idx; + this.spent = 0; + } + } + + remaining(nowMs) { + this._syncWindow(nowMs); + return Math.max(0, this.capacity - this.spent); + } + + take(nowMs, frames = 1) { + this._syncWindow(nowMs); + if (this.spent + frames > this.capacity) return false; + this.spent += frames; + return true; + } + + nextRefillMs(nowMs) { + this._syncWindow(nowMs); + if (this.spent < this.capacity) return nowMs; + return (this.windowIndex + 1) * this.intervalMs; + } +} + +export class PeerReliabilityState { + constructor(peerId) { + this.peerId = peerId; + this.nextSeq = 1; + this.sndUna = 1; + this.unacked = new Map(); + } + + canSendNew(isInteractive) { + const cap = isInteractive ? MAX_UNACKED_PACKETS + 16 : MAX_UNACKED_PACKETS; + return this.unacked.size < cap; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs, isInteractive) { + this.unacked.set(seq, { + seq, + bytes, + isInteractive, + firstSentMs: nowMs, + lastSentMs: nowMs, + }); + } + + onCumulativeAck(ackSeq) { + if (ackSeq <= this.sndUna) return; + for (let s = this.sndUna; s < ackSeq; s += 1) { + this.unacked.delete(s); + } + this.sndUna = ackSeq; + } + + _headRtoMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + for (const entry of this.unacked.values()) { + if (entry.isInteractive) return INTERACTIVE_STATIC_RTO_MS; + } + return BULK_STATIC_RTO_MS; + } + + hasTimedOut(nowMs) { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return false; + return nowMs - oldest.lastSentMs >= this._headRtoMs(); + } + + nextTimeoutMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + return oldest.lastSentMs + this._headRtoMs(); + } + + collectRetransmits(nowMs, maxFrames) { + if (!this.hasTimedOut(nowMs) || maxFrames <= 0) return []; + const limit = Math.min(maxFrames, RETRY_PASS_BUDGET); + const out = []; + for (let s = this.sndUna; s < this.nextSeq && out.length < limit; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + entry.lastSentMs = nowMs; + out.push(entry.bytes); + } + return out; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/scheduler.mjs new file mode 100644 index 0000000..17ef129 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/scheduler.mjs @@ -0,0 +1,104 @@ +/** + * Incomplete optimization scheduler: + * Adds strict interactive priority queue & packet-level preemption across peers, + * plus simple round-robin chunking across bulk peers. + */ + +export class RelayScheduler { + constructor(peers) { + this.peers = [...peers]; + this.interactiveQueue = []; + this.bulkQueues = new Map(); + for (const peerId of this.peers) { + this.bulkQueues.set(peerId, []); + } + this.bulkCursor = 0; + this.streamMsgSeq = new Map(); + } + + _nextStreamSeq(peerId, streamId) { + const key = `${peerId}\u0000${streamId}`; + const seq = (this.streamMsgSeq.get(key) ?? 0) + 1; + this.streamMsgSeq.set(key, seq); + return seq; + } + + enqueue(msg, chunkSize) { + if (!this.bulkQueues.has(msg.peerId)) { + this.bulkQueues.set(msg.peerId, []); + this.peers.push(msg.peerId); + } + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + streamSeq: this._nextStreamSeq(msg.peerId, msg.streamId), + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + this.interactiveQueue.push(entry); + } else { + this.bulkQueues.get(msg.peerId).push(entry); + } + } + + hasPending() { + if (this.interactiveQueue.length > 0) return true; + for (const q of this.bulkQueues.values()) { + if (q.length > 0) return true; + } + return false; + } + + nextSegment(canPeerSend) { + // Always preempt with interactive segments first + for (let i = 0; i < this.interactiveQueue.length; i += 1) { + const entry = this.interactiveQueue[i]; + if (!canPeerSend(entry.peerId, true)) continue; + return this._popSegment(this.interactiveQueue, i); + } + + // Round-robin single chunk per bulk peer + const n = this.peers.length; + for (let i = 0; i < n; i += 1) { + const idx = (this.bulkCursor + i) % n; + const peerId = this.peers[idx]; + const q = this.bulkQueues.get(peerId); + if (!q || q.length === 0) continue; + if (!canPeerSend(peerId, false)) continue; + this.bulkCursor = (idx + 1) % n; + return this._popSegment(q, 0); + } + return null; + } + + _popSegment(queue, index) { + const head = queue[index]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const slice = head.payload.subarray(start, end); + head.nextSegment += 1; + if (head.nextSegment >= head.totalSegments) { + queue.splice(index, 1); + } + return { + peerId: head.peerId, + streamId: head.streamId, + msgId: head.msgId, + streamSeq: head.streamSeq, + isInteractive: head.priority === 'interactive', + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data: slice, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/transport.mjs new file mode 100644 index 0000000..8c52a12 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/src/transport.mjs @@ -0,0 +1,240 @@ +import { CongestionSendBudget, PeerReliabilityState } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_ACK = 2; +const FIXED_HDR = 18; +const MAX_ID_OVERHEAD = 48; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(seq, seg, maxPacketBytes) { + const sBytes = textEncoder.encode(seg.streamId); + const mBytes = textEncoder.encode(seg.msgId); + const headerLen = FIXED_HDR + sBytes.byteLength + mBytes.byteLength; + const totalLen = headerLen + seg.data.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Packet (${totalLen}) exceeds maxPacketBytes (${maxPacketBytes})`); + } + const out = new Uint8Array(totalLen); + const dv = new DataView(out.buffer); + out[0] = PKT_DATA; + out[1] = seg.isInteractive ? 1 : 0; + dv.setUint32(2, seq); + dv.setUint32(6, seg.streamSeq); + dv.setUint16(10, seg.segIndex); + dv.setUint16(12, seg.totalSegments); + dv.setUint16(14, sBytes.byteLength); + dv.setUint16(16, mBytes.byteLength); + let off = FIXED_HDR; + out.set(sBytes, off); + off += sBytes.byteLength; + out.set(mBytes, off); + off += mBytes.byteLength; + out.set(seg.data, off); + return out; +} + +function decodeDataPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < FIXED_HDR || bytes[0] !== PKT_DATA) { + return null; + } + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const isInteractive = bytes[1] === 1; + const seq = dv.getUint32(2); + const streamSeq = dv.getUint32(6); + const segIndex = dv.getUint16(10); + const totalSegments = dv.getUint16(12); + const sLen = dv.getUint16(14); + const mLen = dv.getUint16(16); + const dataOff = FIXED_HDR + sLen + mLen; + if (dataOff > bytes.byteLength) return null; + const streamId = textDecoder.decode(bytes.subarray(FIXED_HDR, FIXED_HDR + sLen)); + const msgId = textDecoder.decode(bytes.subarray(FIXED_HDR + sLen, dataOff)); + const data = bytes.subarray(dataOff); + return { seq, isInteractive, streamId, msgId, streamSeq, segIndex, totalSegments, data }; +} + +function encodeAckPacket(ackSeq) { + const out = new Uint8Array(5); + out[0] = PKT_ACK; + new DataView(out.buffer).setUint32(1, ackSeq); + return out; +} + +function decodeAckPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < 5 || bytes[0] !== PKT_ACK) return null; + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - FIXED_HDR - MAX_ID_OVERHEAD); + + const budget = new CongestionSendBudget(); + const scheduler = new RelayScheduler(peers); + const peerStates = new Map(); + for (const peerId of peers) { + peerStates.set(peerId, new PeerReliabilityState(peerId)); + } + + function getPeerState(peerId) { + let st = peerStates.get(peerId); + if (!st) { + st = new PeerReliabilityState(peerId); + peerStates.set(peerId, st); + } + return st; + } + + return { + enqueue(nowMs, msg) { + getPeerState(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const ackSeq = decodeAckPacket(packetBytes); + if (ackSeq === null) return; + getPeerState(peerId).onCumulativeAck(ackSeq); + }, + + pollTx(nowMs) { + const packets = []; + + for (const [peerId, st] of peerStates) { + const rem = budget.remaining(nowMs); + if (rem <= 0) break; + if (st.hasTimedOut(nowMs)) { + const retries = st.collectRetransmits(nowMs, rem); + for (const bytes of retries) { + if (!budget.take(nowMs, 1)) break; + packets.push({ peerId, bytes }); + } + } + } + + while (budget.remaining(nowMs) > 0) { + const seg = scheduler.nextSegment((peerId, isInteractive) => + getPeerState(peerId).canSendNew(isInteractive), + ); + if (!seg) break; + const st = getPeerState(seg.peerId); + const seq = st.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + budget.take(nowMs, 1); + st.recordSent(seq, bytes, nowMs, seg.isInteractive); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + let hasUnacked = false; + for (const st of peerStates.values()) { + if (st.unacked.size > 0) { + hasUnacked = true; + const rtoMs = st.nextTimeoutMs(); + if (rtoMs < nextWakeMs) nextWakeMs = rtoMs; + } + } + if (scheduler.hasPending() || (hasUnacked && budget.remaining(nowMs) === 0)) { + const refillMs = budget.nextRefillMs(nowMs); + if (refillMs > nowMs && refillMs < nextWakeMs) { + nextWakeMs = refillMs; + } + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + const seenSeqs = new Set(); + /** @type {Map, pending: Map }>} */ + const streams = new Map(); + + function getStream(streamId) { + let st = streams.get(streamId); + if (!st) { + st = { nextStreamSeq: 1, ready: new Map(), pending: new Map() }; + streams.set(streamId, st); + } + return st; + } + + return { + onDataPacket(nowMs, packetBytes) { + const pkt = decodeDataPacket(packetBytes); + if (!pkt) return { delivered: [], ackPackets: [] }; + + const delivered = []; + const isNewSeq = pkt.seq >= rcvNext && !seenSeqs.has(pkt.seq); + if (isNewSeq) { + seenSeqs.add(pkt.seq); + while (seenSeqs.has(rcvNext)) { + seenSeqs.delete(rcvNext); + rcvNext += 1; + } + + const st = getStream(pkt.streamId); + if (pkt.streamSeq >= st.nextStreamSeq && !st.ready.has(pkt.streamSeq)) { + if (pkt.totalSegments === 1) { + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: pkt.msgId, + payload: new Uint8Array(pkt.data), + }); + } else { + let entry = st.pending.get(pkt.streamSeq); + if (!entry) { + entry = { + msgId: pkt.msgId, + totalSegments: pkt.totalSegments, + parts: new Array(pkt.totalSegments).fill(null), + received: 0, + totalBytes: 0, + }; + st.pending.set(pkt.streamSeq, entry); + } + if (entry.parts[pkt.segIndex] === null) { + entry.parts[pkt.segIndex] = new Uint8Array(pkt.data); + entry.received += 1; + entry.totalBytes += pkt.data.byteLength; + } + if (entry.received === entry.totalSegments) { + st.pending.delete(pkt.streamSeq); + const out = new Uint8Array(entry.totalBytes); + let off = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], off); + off += entry.parts[i].byteLength; + } + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: entry.msgId, + payload: out, + }); + } + } + while (st.ready.has(st.nextStreamSeq)) { + delivered.push(st.ready.get(st.nextStreamSeq)); + st.ready.delete(st.nextStreamSeq); + st.nextStreamSeq += 1; + } + } + } + + return { + delivered, + ackPackets: [encodeAckPacket(rcvNext)], + }; + }, + + pollControl(nowMs) { + return { ackPackets: [], nextWakeMs: Infinity }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v1/question.json b/questions/opt-relay-congestion-scheduler/v1/question.json new file mode 100644 index 0000000..6ce25ed --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/question.json @@ -0,0 +1,81 @@ +{ + "id": "opt-relay-congestion-scheduler", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "共享中继弱网拥塞调度、抢占式分片与选择性重传优化", + "status": "calibrated", + "changeNote": "High-ceiling deterministic weak-network relay scheduling, congestion control, and selective reliability optimization extracted from makecindy/cindy device-link + agent-net-core/sim.", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "interactive_latency", + "weight": "1/2", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "interactive_p99_ms", + "label": "Interactive P99 latency (geomean)", + "unit": "ms", + "direction": "lower", + "baseline": 4200, + "target": 120, + "scale": "log" + } + }, + { + "id": "wire_efficiency", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "wire_overhead_pct", + "label": "Total wire overhead", + "unit": "%", + "direction": "lower", + "baseline": 55, + "target": 4.5, + "scale": "log" + } + }, + { + "id": "bulk_throughput", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "bulk_goodput_pct", + "label": "Bulk bottleneck goodput", + "unit": "%", + "direction": "higher", + "baseline": 15, + "target": 94, + "scale": "linear" + } + } + ] +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v1/reference/CONTRACT.md new file mode 100644 index 0000000..91b4295 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/CONTRACT.md @@ -0,0 +1,49 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public profiles, and all 4 unseen held-out profiles: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..615cd4d --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public profiles. + - `npm run bench` — runs the 4 public weak-network profiles (`cellular-mixed`, `airplane-wifi`, `shallow-queue-fanout`, `cloud-policer-outage`) and prints per-profile and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/TASK.md b/questions/opt-relay-congestion-scheduler/v1/reference/TASK.md new file mode 100644 index 0000000..b63ac47 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/TASK.md @@ -0,0 +1,30 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, 120–900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring ultra-low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, 24–256 KiB each, e.g., `messages:view`, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +## Observed Production Symptoms + +1. **Multi-second interactive Head-of-Line (HoL) blocking & tail latency**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — pushing interactive P99 above 4,000–6,000 ms on weak links. +2. **Severe wire overhead (>45–70%) from unpaced bursts and Go-Back-N retransmissions**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts at window boundaries into shallow bottleneck queues (24–36 KB) and token-bucket policers, triggering tail/policer drops, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Poor bottleneck utilization (~15–20% bulk goodput)**: The static frame budget cannot scale up on higher-BDP links (e.g., cross-ocean 6–8 Mbps paths), collapses under random wireless loss or periodic stalls, and recovers slowly after multi-second outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/blackout detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics across diverse unseen weak-network profiles (cellular burst loss, high-BDP reordering + shallow queues, periodic Wi-Fi stalls, token-bucket policers, and multi-second blackouts): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Note that final grading evaluates on **both** the public profiles and unseen held-out profiles with different rates, RTTs, burst/reorder/stall/policer/blackout regimes, and seeds. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..a3a7c0e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/bench/workload.mjs @@ -0,0 +1,267 @@ +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; +import { realpathSync } from 'node:fs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const KiB = 1024; + +export const PUBLIC_PROFILES = [ + { + name: 'cellular-mixed', + seed: 10101, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.015, + queueBytes: 64_000, + }, + uplink: { + bitsPerSecond: 4_000_000, + propagationDelayMs: 50, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 3600]], + peers: ['peer-2', 'peer-3', 'peer-0', 'peer-2', 'peer-3', 'peer-1'], + }, + }, + { + name: 'airplane-wifi', + seed: 20202, + peers: ['peer-0', 'peer-1', 'peer-2'], + downlink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 22, + jitterFifo: true, + lossProb: 0.04, + burstEveryMs: 3200, + burstLenMs: 160, + burstLossProb: 0.45, + queueBytes: 48_000, + }, + uplink: { + bitsPerSecond: 1_200_000, + propagationDelayMs: 220, + jitterMs: 18, + jitterFifo: true, + lossProb: 0.02, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [48, 64, 32, 64, 48, 64, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [64, 48, 64, 32, 64, 48, 64].map((k) => k * KiB), + waveTimesMs: [0, 1400, 2800], + }, + ], + interactive: { + count: 100, + minBytes: 120, + maxBytes: 850, + deadlineMs: 20_000, + windows: [[150, 4600]], + peers: ['peer-2', 'peer-2', 'peer-0', 'peer-2', 'peer-1'], + }, + }, + { + name: 'shallow-queue-fanout', + seed: 30303, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 24_000, + }, + uplink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 35, + jitterMs: 5, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [64, 128, 96, 128, 64, 128, 96, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 140, + minBytes: 150, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[100, 3600]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, + { + name: 'cloud-policer-outage', + seed: 40404, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 5_000_000, + bucketBytesPerSec: 437_500, + bucketDepthBytes: 40_000, + propagationDelayMs: 40, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + uplink: { + bitsPerSecond: 5_000_000, + propagationDelayMs: 40, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.005, + queueBytes: 64_000, + outages: [[2200, 4000]], + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [96, 128, 64, 128, 96, 128, 64, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [128, 64, 128, 96, 128, 64, 128, 96, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 4100], + }, + ], + interactive: { + count: 120, + minBytes: 120, + maxBytes: 900, + deadlineMs: 18_000, + windows: [[120, 1950], [4080, 6100]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, +]; + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/package.json b/questions/opt-relay-congestion-scheduler/v1/reference/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/sim/network.mjs new file mode 100644 index 0000000..e53c0a6 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/sim/network.mjs @@ -0,0 +1,821 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + const size = minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 120_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/src/congestion.mjs new file mode 100644 index 0000000..1eaf2d6 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/src/congestion.mjs @@ -0,0 +1,247 @@ +/** + * Reference congestion control & reliability: + * - Shared-link AIMD (wireless-tolerant high-speed AIMD) congestion window across all peers + * - Jacobson/Karels SRTT / RTTVAR / RTO estimation + * - Selective ACK (SACK ranges) + 3-dup-SACK fast retransmit + * + * Intentionally leaves SOTA headroom: + * - Unpaced window bursts (no fine-grained inter-packet pacing) + * - No BBR / delivery-rate / policer-aware rate control + * - No proactive FEC on interactive packets + * - No RACK / Tail-Loss Probe (TLP) + */ + +export const MSS = 1200; +const INITIAL_CWND = 20 * MSS; +const MIN_CWND = 10 * MSS; +const MAX_CWND = 240 * MSS; +const INITIAL_SSTHRESH = 64 * MSS; +const INTERACTIVE_CWND_RESERVE = 6 * MSS; +const DUP_SACK_THRESHOLD = 3; +const MIN_RTO_MS = 160; +const MAX_RTO_MS = 1800; + +export class SharedAimdController { + constructor() { + this.cwnd = INITIAL_CWND; + this.ssthresh = INITIAL_SSTHRESH; + this.inflightBytes = 0; + + this.srttMs = null; + this.rttVarMs = 50; + this.lastLossReductionMs = -Infinity; + this.lastBurstLossCount = 0; + } + + onRttSample(sampleMs) { + if (!Number.isFinite(sampleMs) || sampleMs <= 0) return; + const clamped = Math.min(4000, sampleMs); + if (this.srttMs === null) { + this.srttMs = clamped; + this.rttVarMs = clamped / 2; + } else { + this.rttVarMs = 0.75 * this.rttVarMs + 0.25 * Math.abs(this.srttMs - clamped); + this.srttMs = 0.875 * this.srttMs + 0.125 * clamped; + } + } + + rtoMs(retries = 0) { + const base = this.srttMs === null + ? 350 + : Math.max(MIN_RTO_MS, Math.min(MAX_RTO_MS, this.srttMs + Math.max(25, 4 * this.rttVarMs))); + const backoff = Math.min(4, 2 ** Math.min(3, retries)); + return Math.min(MAX_RTO_MS, base * backoff); + } + + canSend(bytes, isInteractive) { + const limit = isInteractive ? this.cwnd + INTERACTIVE_CWND_RESERVE : this.cwnd; + return this.inflightBytes + bytes <= limit || (isInteractive && this.inflightBytes < INTERACTIVE_CWND_RESERVE); + } + + onPacketSent(bytes) { + this.inflightBytes += bytes; + } + + onPacketFreed(bytes) { + this.inflightBytes = Math.max(0, this.inflightBytes - bytes); + } + + onBytesAcked(ackedBytes) { + if (ackedBytes <= 0) return; + if (this.cwnd < this.ssthresh) { + this.cwnd = Math.min(MAX_CWND, this.cwnd + ackedBytes); + } else { + // Standard AIMD growth (+3 MSS per RTT) + this.cwnd = Math.min(MAX_CWND, this.cwnd + (3 * MSS * ackedBytes) / Math.max(MSS, this.cwnd)); + } + } + + onCongestionEvent(nowMs, isTimeout, lostInEvent = 1) { + const minInterval = this.srttMs !== null ? Math.max(60, this.srttMs) : 150; + if (nowMs - this.lastLossReductionMs < minInterval) return; + this.lastLossReductionMs = nowMs; + this.lastBurstLossCount = lostInEvent; + const beta = isTimeout ? 0.6 : (lostInEvent >= 3 ? 0.7 : 0.8); + this.ssthresh = Math.max(MIN_CWND, Math.floor(this.cwnd * beta)); + this.cwnd = this.ssthresh; + } +} + +export class PeerSackTracker { + constructor(peerId, cc) { + this.peerId = peerId; + this.cc = cc; + this.nextSeq = 1; + this.sndUna = 1; + this.highestSacked = 0; + this.unacked = new Map(); + this.retransmitQueueInteractive = []; + this.retransmitQueueBulk = []; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs, isInteractive) { + const size = bytes.byteLength; + this.unacked.set(seq, { + seq, + bytes, + size, + isInteractive, + sentMs: nowMs, + firstSentMs: nowMs, + retries: 0, + retransmitEpochSeq: seq, + inFlight: true, + needsRetransmit: false, + }); + this.cc.onPacketSent(size); + } + + _queueRetransmit(entry) { + if (entry.needsRetransmit) return; + entry.needsRetransmit = true; + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + if (entry.isInteractive) { + this.retransmitQueueInteractive.push(entry.seq); + } else { + this.retransmitQueueBulk.push(entry.seq); + } + } + + onSackAck(nowMs, cumAckSeq, echoSeq, sackRanges) { + let newlyAckedBytes = 0; + let lossCount = 0; + + if (echoSeq > 0) { + const echoed = this.unacked.get(echoSeq); + if (echoed && echoed.retries === 0) { + this.cc.onRttSample(nowMs - echoed.firstSentMs); + } + } + + if (cumAckSeq > this.sndUna) { + for (let s = this.sndUna; s < cumAckSeq; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + this.unacked.delete(s); + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + newlyAckedBytes += entry.size; + } + this.sndUna = cumAckSeq; + } + + for (const [start, end] of sackRanges) { + if (end - 1 > this.highestSacked) this.highestSacked = end - 1; + for (let s = Math.max(start, this.sndUna); s < end; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + this.unacked.delete(s); + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + newlyAckedBytes += entry.size; + } + } + + if (newlyAckedBytes > 0) { + this.cc.onBytesAcked(newlyAckedBytes); + } + + if (this.highestSacked >= this.sndUna + DUP_SACK_THRESHOLD) { + const thresholdSeq = this.highestSacked - DUP_SACK_THRESHOLD; + for (const entry of this.unacked.values()) { + if (entry.retransmitEpochSeq <= thresholdSeq && entry.inFlight && !entry.needsRetransmit) { + this._queueRetransmit(entry); + lossCount += 1; + } + } + } + + if (lossCount > 0) { + this.cc.onCongestionEvent(nowMs, false, lossCount); + } + } + + checkTimeouts(nowMs) { + let timeoutCount = 0; + for (const entry of this.unacked.values()) { + if (!entry.inFlight || entry.needsRetransmit) continue; + const rto = this.cc.rtoMs(entry.retries); + if (nowMs - entry.sentMs >= rto) { + this._queueRetransmit(entry); + timeoutCount += 1; + } + } + if (timeoutCount > 0) { + this.cc.onCongestionEvent(nowMs, true, timeoutCount); + } + } + + popRetransmit(nowMs, interactiveOnly) { + const queue = interactiveOnly ? this.retransmitQueueInteractive : this.retransmitQueueBulk; + while (queue.length > 0) { + const seq = queue.shift(); + const entry = this.unacked.get(seq); + if (!entry || !entry.needsRetransmit) continue; + if (!this.cc.canSend(entry.size, entry.isInteractive)) { + queue.unshift(seq); + return null; + } + entry.needsRetransmit = false; + entry.inFlight = true; + entry.retries += 1; + entry.sentMs = nowMs; + entry.retransmitEpochSeq = this.nextSeq; + this.cc.onPacketSent(entry.size); + return entry.bytes; + } + return null; + } + + hasPendingRetransmit(interactiveOnly) { + const q = interactiveOnly ? this.retransmitQueueInteractive : this.retransmitQueueBulk; + return q.length > 0; + } + + nextTimeoutMs() { + let earliest = Infinity; + for (const entry of this.unacked.values()) { + if (!entry.inFlight || entry.needsRetransmit) continue; + const t = entry.sentMs + this.cc.rtoMs(entry.retries); + if (t < earliest) earliest = t; + } + return earliest; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/src/scheduler.mjs new file mode 100644 index 0000000..b5f5921 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/src/scheduler.mjs @@ -0,0 +1,170 @@ +/** + * Reference relay scheduler: + * - Strict priority preemption for interactive messages across all peers + * - Byte-weighted Deficit Round-Robin (DRR) across bulk peers for fair sharing + * - Independent per-(peerId, streamId) delivery sequence numbers + */ + +const DRR_QUANTUM_BYTES = 2400; + +export class RelayScheduler { + constructor(peers) { + this.peers = []; + this.interactiveQueue = []; + this.bulkPeers = new Map(); // peerId -> { queue: [], deficit: number } + this.activeBulkList = []; + this.streamMsgSeq = new Map(); + for (const peerId of peers) { + this._ensurePeer(peerId); + } + } + + _ensurePeer(peerId) { + if (!this.bulkPeers.has(peerId)) { + this.peers.push(peerId); + this.bulkPeers.set(peerId, { queue: [], deficit: 0, active: false }); + } + return this.bulkPeers.get(peerId); + } + + _nextStreamSeq(peerId, streamId) { + const key = `${peerId}\u0000${streamId}`; + const seq = (this.streamMsgSeq.get(key) ?? 0) + 1; + this.streamMsgSeq.set(key, seq); + return seq; + } + + enqueue(msg, chunkSize) { + const state = this._ensurePeer(msg.peerId); + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + streamSeq: this._nextStreamSeq(msg.peerId, msg.streamId), + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + this.interactiveQueue.push(entry); + } else { + state.queue.push(entry); + if (!state.active) { + state.active = true; + state.deficit = 0; + this.activeBulkList.push(msg.peerId); + } + } + } + + hasInteractive() { + return this.interactiveQueue.length > 0; + } + + hasBulk() { + return this.activeBulkList.length > 0; + } + + peekNextInteractiveSize() { + if (!this.interactiveQueue.length) return 0; + const head = this.interactiveQueue[0]; + const start = head.nextSegment * head.chunkSize; + return Math.min(head.chunkSize, head.totalBytes - start); + } + + popInteractiveSegment() { + if (!this.interactiveQueue.length) return null; + return this._popFromQueue(this.interactiveQueue, 0); + } + + /** + * Byte-weighted Deficit Round-Robin (DRR) across active bulk peers. + */ + popBulkSegment(canSendBytes) { + let rounds = this.activeBulkList.length; + if (rounds === 0) return null; + + // Allow up to 2 passes so peers receive a fresh quantum if all deficits are low + for (let pass = 0; pass < 2; pass += 1) { + let checked = 0; + const count = this.activeBulkList.length; + while (checked < count && this.activeBulkList.length > 0) { + checked += 1; + const peerId = this.activeBulkList[0]; + const st = this.bulkPeers.get(peerId); + if (!st || st.queue.length === 0) { + this.activeBulkList.shift(); + if (st) { + st.active = false; + st.deficit = 0; + } + continue; + } + + if (st.deficit <= 0) { + st.deficit += DRR_QUANTUM_BYTES; + } + + const head = st.queue[0]; + const start = head.nextSegment * head.chunkSize; + const segBytes = Math.min(head.chunkSize, head.totalBytes - start); + const estPacketBytes = segBytes + 48; + + if (!canSendBytes(estPacketBytes)) { + return null; + } + + if (segBytes <= st.deficit) { + st.deficit -= segBytes; + const seg = this._popFromQueue(st.queue, 0); + if (st.queue.length === 0) { + this.activeBulkList.shift(); + st.active = false; + st.deficit = 0; + } else if (st.deficit < head.chunkSize) { + // Rotate to back of active DRR list + this.activeBulkList.push(this.activeBulkList.shift()); + } + return seg; + } + + // Not enough deficit yet; rotate to back and grant quantum next turn + this.activeBulkList.push(this.activeBulkList.shift()); + } + // Top up all active peers by one quantum if none could fire + for (const peerId of this.activeBulkList) { + const st = this.bulkPeers.get(peerId); + if (st) st.deficit += DRR_QUANTUM_BYTES; + } + } + return null; + } + + _popFromQueue(queue, idx) { + const head = queue[idx]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const data = head.payload.subarray(start, end); + head.nextSegment += 1; + if (head.nextSegment >= head.totalSegments) { + queue.splice(idx, 1); + } + return { + peerId: head.peerId, + streamId: head.streamId, + msgId: head.msgId, + streamSeq: head.streamSeq, + isInteractive: head.priority === 'interactive', + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/src/transport.mjs new file mode 100644 index 0000000..5e61e3d --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/src/transport.mjs @@ -0,0 +1,328 @@ +import { PeerSackTracker, SharedAimdController } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_SACK = 2; +const FIXED_DATA_HDR = 18; +const MAX_ID_OVERHEAD = 44; +const MAX_SACK_RANGES = 4; +const DELAYED_ACK_MS = 12; +const DELAYED_ACK_PKTS = 2; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(seq, seg, maxPacketBytes) { + const sBytes = textEncoder.encode(seg.streamId); + const mBytes = textEncoder.encode(seg.msgId); + const headerLen = FIXED_DATA_HDR + sBytes.byteLength + mBytes.byteLength; + const totalLen = headerLen + seg.data.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Packet (${totalLen}) exceeds maxPacketBytes (${maxPacketBytes})`); + } + const out = new Uint8Array(totalLen); + const dv = new DataView(out.buffer); + out[0] = PKT_DATA; + out[1] = seg.isInteractive ? 1 : 0; + dv.setUint32(2, seq); + dv.setUint32(6, seg.streamSeq); + dv.setUint16(10, seg.segIndex); + dv.setUint16(12, seg.totalSegments); + dv.setUint16(14, sBytes.byteLength); + dv.setUint16(16, mBytes.byteLength); + let off = FIXED_DATA_HDR; + out.set(sBytes, off); + off += sBytes.byteLength; + out.set(mBytes, off); + off += mBytes.byteLength; + out.set(seg.data, off); + return out; +} + +function decodeDataPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < FIXED_DATA_HDR || bytes[0] !== PKT_DATA) { + return null; + } + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const isInteractive = bytes[1] === 1; + const seq = dv.getUint32(2); + const streamSeq = dv.getUint32(6); + const segIndex = dv.getUint16(10); + const totalSegments = dv.getUint16(12); + const sLen = dv.getUint16(14); + const mLen = dv.getUint16(16); + const dataOff = FIXED_DATA_HDR + sLen + mLen; + if (dataOff > bytes.byteLength) return null; + const streamId = textDecoder.decode(bytes.subarray(FIXED_DATA_HDR, FIXED_DATA_HDR + sLen)); + const msgId = textDecoder.decode(bytes.subarray(FIXED_DATA_HDR + sLen, dataOff)); + const data = bytes.subarray(dataOff); + return { seq, isInteractive, streamId, msgId, streamSeq, segIndex, totalSegments, data }; +} + +function encodeSackPacket(cumAckSeq, echoSeq, ranges) { + const count = Math.min(MAX_SACK_RANGES, ranges.length); + const out = new Uint8Array(10 + count * 8); + const dv = new DataView(out.buffer); + out[0] = PKT_SACK; + out[1] = count; + dv.setUint32(2, cumAckSeq); + dv.setUint32(6, echoSeq); + let off = 10; + for (let i = 0; i < count; i += 1) { + dv.setUint32(off, ranges[i][0]); + dv.setUint32(off + 4, ranges[i][1]); + off += 8; + } + return out; +} + +function decodeSackPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < 10 || bytes[0] !== PKT_SACK) return null; + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const count = bytes[1]; + if (10 + count * 8 > bytes.byteLength) return null; + const cumAckSeq = dv.getUint32(2); + const echoSeq = dv.getUint32(6); + const ranges = []; + let off = 10; + for (let i = 0; i < count; i += 1) { + ranges.push([dv.getUint32(off), dv.getUint32(off + 4)]); + off += 8; + } + return { cumAckSeq, echoSeq, ranges }; +} + +function buildSackRanges(oooSet, rcvNext) { + if (oooSet.size === 0) return []; + const sorted = [...oooSet].filter((s) => s > rcvNext).sort((a, b) => a - b); + if (!sorted.length) return []; + const ranges = []; + let start = sorted[0]; + let end = start + 1; + for (let i = 1; i < sorted.length; i += 1) { + if (sorted[i] === end) { + end += 1; + } else { + ranges.push([start, end]); + start = sorted[i]; + end = start + 1; + } + } + ranges.push([start, end]); + // Prioritize most recent ranges if > MAX_SACK_RANGES + return ranges.length <= MAX_SACK_RANGES ? ranges : ranges.slice(ranges.length - MAX_SACK_RANGES); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - FIXED_DATA_HDR - MAX_ID_OVERHEAD); + + const cc = new SharedAimdController(); + const scheduler = new RelayScheduler(peers); + const peerTrackers = new Map(); + for (const peerId of peers) { + peerTrackers.set(peerId, new PeerSackTracker(peerId, cc)); + } + + function getTracker(peerId) { + let t = peerTrackers.get(peerId); + if (!t) { + t = new PeerSackTracker(peerId, cc); + peerTrackers.set(peerId, t); + } + return t; + } + + return { + enqueue(nowMs, msg) { + getTracker(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const sack = decodeSackPacket(packetBytes); + if (!sack) return; + getTracker(peerId).onSackAck(nowMs, sack.cumAckSeq, sack.echoSeq, sack.ranges); + }, + + pollTx(nowMs) { + const packets = []; + + // Check RTO timeouts across all peers + for (const tracker of peerTrackers.values()) { + tracker.checkTimeouts(nowMs); + } + + // 1. Interactive retransmissions (highest priority) + for (const [peerId, tracker] of peerTrackers) { + while (tracker.hasPendingRetransmit(true)) { + const bytes = tracker.popRetransmit(nowMs, true); + if (!bytes) break; + packets.push({ peerId, bytes }); + } + } + + // 2. New interactive segments + while (scheduler.hasInteractive()) { + const estBytes = scheduler.peekNextInteractiveSize() + FIXED_DATA_HDR + MAX_ID_OVERHEAD; + if (!cc.canSend(estBytes, true)) break; + const seg = scheduler.popInteractiveSegment(); + if (!seg) break; + const tracker = getTracker(seg.peerId); + const seq = tracker.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + tracker.recordSent(seq, bytes, nowMs, true); + packets.push({ peerId: seg.peerId, bytes }); + } + + // 3. Bulk retransmissions (selective SACK/RTO) + let sentBulkRetry = true; + while (sentBulkRetry) { + sentBulkRetry = false; + for (const [peerId, tracker] of peerTrackers) { + if (!tracker.hasPendingRetransmit(false)) continue; + const bytes = tracker.popRetransmit(nowMs, false); + if (bytes) { + packets.push({ peerId, bytes }); + sentBulkRetry = true; + } + } + } + + // 4. New bulk segments via byte-weighted DRR within shared AIMD cwnd + while (scheduler.hasBulk()) { + const seg = scheduler.popBulkSegment((estBytes) => cc.canSend(estBytes, false)); + if (!seg) break; + const tracker = getTracker(seg.peerId); + const seq = tracker.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + tracker.recordSent(seq, bytes, nowMs, false); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + for (const tracker of peerTrackers.values()) { + const t = tracker.nextTimeoutMs(); + if (t < nextWakeMs) nextWakeMs = t; + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + const oooSet = new Set(); + const streams = new Map(); + + let unackedCount = 0; + let ackDueMs = Infinity; + let lastEchoSeq = 0; + + function getStream(streamId) { + let st = streams.get(streamId); + if (!st) { + st = { nextStreamSeq: 1, ready: new Map(), pending: new Map() }; + streams.set(streamId, st); + } + return st; + } + + function makeAck() { + unackedCount = 0; + ackDueMs = Infinity; + return encodeSackPacket(rcvNext, lastEchoSeq, buildSackRanges(oooSet, rcvNext)); + } + + return { + onDataPacket(nowMs, packetBytes) { + const pkt = decodeDataPacket(packetBytes); + if (!pkt) return { delivered: [], ackPackets: [] }; + + const delivered = []; + let immediateAck = pkt.isInteractive; + const isDuplicate = pkt.seq < rcvNext || oooSet.has(pkt.seq); + if (isDuplicate) { + immediateAck = true; + } else { + lastEchoSeq = pkt.seq; + if (pkt.seq === rcvNext) { + rcvNext += 1; + while (oooSet.has(rcvNext)) { + oooSet.delete(rcvNext); + rcvNext += 1; + } + if (oooSet.size > 0) immediateAck = true; + } else { + oooSet.add(pkt.seq); + immediateAck = true; + } + + const st = getStream(pkt.streamId); + if (pkt.streamSeq >= st.nextStreamSeq && !st.ready.has(pkt.streamSeq)) { + if (pkt.totalSegments === 1) { + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: pkt.msgId, + payload: new Uint8Array(pkt.data), + }); + } else { + let entry = st.pending.get(pkt.streamSeq); + if (!entry) { + entry = { + msgId: pkt.msgId, + totalSegments: pkt.totalSegments, + parts: new Array(pkt.totalSegments).fill(null), + received: 0, + totalBytes: 0, + }; + st.pending.set(pkt.streamSeq, entry); + } + if (entry.parts[pkt.segIndex] === null) { + entry.parts[pkt.segIndex] = new Uint8Array(pkt.data); + entry.received += 1; + entry.totalBytes += pkt.data.byteLength; + } + if (entry.received === entry.totalSegments) { + st.pending.delete(pkt.streamSeq); + const out = new Uint8Array(entry.totalBytes); + let off = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], off); + off += entry.parts[i].byteLength; + } + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: entry.msgId, + payload: out, + }); + } + } + while (st.ready.has(st.nextStreamSeq)) { + delivered.push(st.ready.get(st.nextStreamSeq)); + st.ready.delete(st.nextStreamSeq); + st.nextStreamSeq += 1; + } + } + } + + unackedCount += 1; + if (immediateAck || unackedCount >= DELAYED_ACK_PKTS) { + return { delivered, ackPackets: [makeAck()] }; + } + if (!Number.isFinite(ackDueMs)) { + ackDueMs = nowMs + DELAYED_ACK_MS; + } + return { delivered, ackPackets: [] }; + }, + + pollControl(nowMs) { + if (unackedCount > 0 && nowMs >= ackDueMs) { + return { ackPackets: [makeAck()], nextWakeMs: Infinity }; + } + return { ackPackets: [], nextWakeMs: ackDueMs }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v1/reference/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v2/author/editable.json b/questions/opt-relay-congestion-scheduler/v2/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-relay-congestion-scheduler/v2/author/evaluator.mjs b/questions/opt-relay-congestion-scheduler/v2/author/evaluator.mjs new file mode 100644 index 0000000..5be5f99 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/evaluator.mjs @@ -0,0 +1,664 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const Q_ROOT = path.resolve(HERE, '..'); +const SIM_PATH = path.join(Q_ROOT, 'candidate', 'sim', 'network.mjs'); +const PUBLIC_BENCH_PATH = path.join(Q_ROOT, 'candidate', 'bench', 'workload.mjs'); + +const [subDir] = process.argv.slice(2); +if (!subDir) { + throw new Error('Usage: node evaluator.mjs '); +} + +const simMod = await import(pathToFileURL(SIM_PATH).href); +const { + MAX_PACKET_BYTES, + SplitMix64, + SimLink, + sha256Hex, + generateProfileMessages, + runSimulation, +} = simMod; + +const transportUrl = pathToFileURL(path.join(subDir, 'transport.mjs')).href; +const transportMod = await import(transportUrl); +const { createRelaySender, createPeerReceiver } = transportMod; + +if (typeof createRelaySender !== 'function' || typeof createPeerReceiver !== 'function') { + throw new Error('src/transport.mjs must export createRelaySender and createPeerReceiver'); +} + +const { PUBLIC_PROFILES, aggregateMetrics } = await import(pathToFileURL(PUBLIC_BENCH_PATH).href); + +const KiB = 1024; + +// 4 unseen real relay links (different app instances and controllers from the public ones) +// produce the 3 scored metrics. +const HELDOUT_PROFILES = JSON.parse(await fs.readFile(path.join(HERE, 'heldout', 'heldout-profiles.json'), 'utf8')); + +// Synthetic stress links (reordering, duplication, bursty loss, policers) from v1: gates only. +const STRESS_PROFILES = [ + { + name: 'stress-4g-burst', + seed: 51515, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 3_200_000, + propagationDelayMs: 60, + jitterMs: 14, + jitterFifo: true, + lossProb: 0.02, + burstEveryMs: 2400, + burstLenMs: 140, + burstLossProb: 0.45, + queueBytes: 48_000, + }, + uplink: { + bitsPerSecond: 3_200_000, + propagationDelayMs: 60, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 48_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 96, 64, 96, 80, 96].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 48, 96, 64, 96, 80, 96, 64].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [48, 96, 64, 96, 80, 96, 64, 96].map((k) => k * KiB), + waveTimesMs: [0, 1100, 2200], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 4400]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, + { + name: 'stress-cross-ocean', + seed: 62626, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 8_000_000, + propagationDelayMs: 110, + jitterMs: 10, + jitterFifo: true, + lossProb: 0.025, + reorderProb: 0.03, + reorderExtraMs: 35, + dupProb: 0.01, + queueBytes: 36_000, + }, + uplink: { + bitsPerSecond: 8_000_000, + propagationDelayMs: 110, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.01, + reorderProb: 0.02, + reorderExtraMs: 25, + dupProb: 0.01, + queueBytes: 64_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [128, 192, 128, 256, 128, 192, 128, 256, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [192, 128, 256, 128, 192, 128, 256, 128, 128, 128].map((k) => k * KiB), + waveTimesMs: [0, 900, 1800], + }, + ], + interactive: { + count: 140, + minBytes: 140, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 3200]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, + { + name: 'stress-wifi-stall', + seed: 73737, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3'], + downlink: { + bitsPerSecond: 2_500_000, + propagationDelayMs: 40, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.03, + stallEveryMs: 3200, + stallLenMs: 350, + stallOffsetMs: 2000, + queueBytes: 40_000, + }, + uplink: { + bitsPerSecond: 2_500_000, + propagationDelayMs: 40, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.015, + stallEveryMs: 3200, + stallLenMs: 350, + stallOffsetMs: 2000, + queueBytes: 40_000, + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 128, 64, 96, 80, 128].map((k) => k * KiB), + waveTimesMs: [0, 1200, 2400], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 64, 128, 48, 96, 80, 128, 64].map((k) => k * KiB), + waveTimesMs: [0, 1200, 2400], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 880, + deadlineMs: 20_000, + windows: [[120, 4200]], + peers: ['peer-2', 'peer-3', 'peer-2', 'peer-3', 'peer-0'], + }, + }, + { + name: 'stress-policer-blackout', + seed: 84848, + peers: ['peer-0', 'peer-1', 'peer-2', 'peer-3', 'peer-4'], + downlink: { + bitsPerSecond: 6_000_000, + bucketBytesPerSec: 375_000, + bucketDepthBytes: 36_000, + propagationDelayMs: 45, + jitterMs: 8, + jitterFifo: true, + lossProb: 0.015, + queueBytes: 48_000, + outages: [[2400, 4400]], + }, + uplink: { + bitsPerSecond: 6_000_000, + propagationDelayMs: 45, + jitterMs: 6, + jitterFifo: true, + lossProb: 0.01, + queueBytes: 48_000, + outages: [[2400, 4400]], + }, + bulkPeers: [ + { + peerId: 'peer-0', + streamId: 'bulk-0', + messageSizes: [64, 96, 48, 96, 64, 96, 80, 96].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + { + peerId: 'peer-1', + streamId: 'bulk-0', + messageSizes: [96, 48, 96, 64, 96, 80, 96, 64].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + { + peerId: 'peer-2', + streamId: 'bulk-0', + messageSizes: [48, 96, 64, 96, 80, 96, 64, 96].map((k) => k * KiB), + waveTimesMs: [0, 1000, 4450], + }, + ], + interactive: { + count: 140, + minBytes: 120, + maxBytes: 900, + deadlineMs: 20_000, + windows: [[120, 2150], [4480, 7000]], + peers: ['peer-3', 'peer-4', 'peer-3', 'peer-4', 'peer-0'], + }, + }, +]; + +function checkUnitAdversarial() { + const rng = new SplitMix64(133742); + const peers = ['u-0', 'u-1']; + const messages = []; + // Mix tiny (1 B, 120 B), boundary (1199 B, 1200 B, 1201 B), and multi-chunk (32 KiB) payloads + const sizes = [1, 120, 1199, 1200, 1201, 2400, 32 * KiB, 250, 48 * KiB, 17, 16 * KiB, 899]; + for (let i = 0; i < sizes.length; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 's-ctrl' : 's-data', + msgId: `u-msg-${i}`, + priority: sizes[i] <= 900 ? 'interactive' : 'bulk', + payload: rng.fillBytes(sizes[i]), + enqueuedMs: i * 85, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-adversarial', + seed: 99123, + peers, + downlink: { + bitsPerSecond: 2_000_000, + propagationDelayMs: 55, + jitterMs: 18, + jitterFifo: false, + lossProb: 0.12, + reorderProb: 0.18, + reorderExtraMs: 45, + dupProb: 0.12, + queueBytes: 32_000, + outages: [[700, 1400]], + }, + uplink: { + bitsPerSecond: 2_000_000, + propagationDelayMs: 55, + jitterMs: 15, + lossProb: 0.10, + reorderProb: 0.12, + reorderExtraMs: 35, + dupProb: 0.10, + queueBytes: 32_000, + outages: [[700, 1400]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `unit exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `unit packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `unit interactive deadline failed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +} + +/** + * Isolated subprocess check proving sender and receiver communicate STRICTLY + * via serialized wire Uint8Array packets with zero shared module/heap state. + */ +async function checkWireIsolationSubprocess() { + const childTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-relay-iso-')); + const child = spawn(process.execPath, [path.join(HERE, 'wire-probe-child.mjs'), subDir], { + cwd: childTmp, + env: { + PATH: process.env.PATH, + TMPDIR: childTmp, + TEMP: childTmp, + TMP: childTmp, + }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + let stderrBuf = ''; + child.stderr.on('data', (d) => { stderrBuf = (stderrBuf + d).slice(-4000); }); + + const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity }); + const lineQueue = []; + const waiters = []; + rl.on('line', (line) => { + if (waiters.length > 0) waiters.shift()(line); + else lineQueue.push(line); + }); + + const nextLine = () => new Promise((resolve, reject) => { + if (lineQueue.length > 0) return resolve(lineQueue.shift()); + const onExit = (code) => reject(new Error(`wire-probe-child exited early (${code}): ${stderrBuf}`)); + child.once('exit', onExit); + waiters.push((line) => { + child.off('exit', onExit); + resolve(line); + }); + }); + + const rpc = async (obj) => { + child.stdin.write(JSON.stringify(obj) + '\n'); + const line = await nextLine(); + const res = JSON.parse(line); + if (!res.ok) throw new Error(`wire-probe-child error: ${res.error}`); + return res; + }; + + try { + const peers = ['iso-0', 'iso-1']; + await rpc({ op: 'init', peers, maxPacketBytes: MAX_PACKET_BYTES }); + + const rng = new SplitMix64(424242); + const messages = [ + { peerId: 'iso-0', streamId: 'bulk', msgId: 'b1', priority: 'bulk', payload: rng.fillBytes(12 * KiB), enqueuedMs: 0, deadlineMs: 20_000 }, + { peerId: 'iso-1', streamId: 'bulk', msgId: 'b2', priority: 'bulk', payload: rng.fillBytes(12 * KiB), enqueuedMs: 0, deadlineMs: 20_000 }, + { peerId: 'iso-0', streamId: 'ctrl', msgId: 'i1', priority: 'interactive', payload: rng.fillBytes(300), enqueuedMs: 60, deadlineMs: 18_000 }, + { peerId: 'iso-1', streamId: 'ctrl', msgId: 'i2', priority: 'interactive', payload: rng.fillBytes(450), enqueuedMs: 120, deadlineMs: 18_000 }, + { peerId: 'iso-0', streamId: 'ctrl', msgId: 'i3', priority: 'interactive', payload: rng.fillBytes(200), enqueuedMs: 550, deadlineMs: 18_000 }, + { peerId: 'iso-1', streamId: 'ctrl', msgId: 'i4', priority: 'interactive', payload: rng.fillBytes(600), enqueuedMs: 620, deadlineMs: 18_000 }, + ]; + + const downlink = new SimLink( + { + bitsPerSecond: 3_000_000, + propagationDelayMs: 40, + jitterMs: 8, + lossProb: 0.06, + reorderProb: 0.08, + reorderExtraMs: 25, + dupProb: 0.05, + queueBytes: 36_000, + outages: [[250, 500]], + }, + 77777, + ); + const uplink = new SimLink( + { + bitsPerSecond: 3_000_000, + propagationDelayMs: 40, + jitterMs: 6, + lossProb: 0.04, + queueBytes: 36_000, + outages: [[250, 500]], + }, + 88888, + ); + + const sender = createRelaySender({ maxPacketBytes: MAX_PACKET_BYTES, peers: [...peers] }); + const expectedByStream = new Map(); + const events = []; + let seq = 0; + + for (const m of messages) { + const key = `${m.peerId}\u0000${m.streamId}`; + if (!expectedByStream.has(key)) expectedByStream.set(key, { head: 0, items: [] }); + expectedByStream.get(key).items.push({ + msgId: m.msgId, + sha256: sha256Hex(m.payload), + byteLength: m.payload.byteLength, + enqueuedUs: Math.round(m.enqueuedMs * 1000), + deadlineMs: m.deadlineMs, + priority: m.priority, + }); + events.push({ timeUs: Math.round(m.enqueuedMs * 1000), seq: seq++, type: 'ENQUEUE', data: m }); + } + + const pushEv = (timeUs, type, data) => { + events.push({ timeUs, seq: seq++, type, data }); + }; + + const receiverNextWakeUs = new Map(peers.map((p) => [p, Infinity])); + let senderNextWakeUs = Infinity; + let nowUs = 0; + let deliveredCount = 0; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + assert.ok(steps < 200_000 && nowUs <= 60_000_000, `wire isolation probe stalled (${deliveredCount}/${messages.length})`); + events.sort((a, b) => a.timeUs - b.timeUs || a.seq - b.seq); + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touched = new Set(); + + while (events.length > 0 && events[0].timeUs <= nowUs) { + const ev = events.shift(); + if (ev.type === 'ENQUEUE') { + sender.enqueue(nowMs, { ...ev.data, payload: new Uint8Array(ev.data.payload) }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const hex = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex'); + const res = await rpc({ op: 'data', peerId, nowMs, hex }); + for (const item of res.delivered) { + const key = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(key); + assert.ok(q && q.head < q.items.length, `Unexpected wire-isolated delivery ${key}/${item.msgId}`); + const exp = q.items[q.head++]; + assert.equal(item.msgId, exp.msgId, 'Wire-isolated FIFO order mismatch'); + assert.equal(item.byteLength, exp.byteLength, 'Wire-isolated payload length mismatch'); + assert.equal(item.sha256, exp.sha256, 'Wire-isolated SHA-256 mismatch'); + if (exp.priority === 'interactive') { + assert.ok((nowUs - exp.enqueuedUs) / 1000 <= exp.deadlineMs, 'Wire-isolated interactive deadline miss'); + } + deliveredCount += 1; + } + for (const ackHex of res.ackPackets) { + assert.ok(typeof ackHex === 'string', 'Invalid ACK packet from isolated receiver'); + const buf = Buffer.from(ackHex, 'hex'); + const ackBytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + assert.ok(ackBytes.byteLength > 0 && ackBytes.byteLength <= MAX_PACKET_BYTES, 'ACK bounds violated'); + for (const atUs of uplink.transmit(nowUs, ackBytes.byteLength)) { + pushEv(atUs, 'ACK_ARRIVAL', { peerId, bytes: new Uint8Array(ackBytes) }); + } + } + touched.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + sender.onAckPacket(nowMs, ev.data.peerId, new Uint8Array(ev.data.bytes)); + senderActive = true; + } + } + + for (const peerId of peers) { + if (touched.has(peerId) || receiverNextWakeUs.get(peerId) <= nowUs) { + const res = await rpc({ op: 'poll', peerId, nowMs }); + for (const ackHex of res.ackPackets) { + assert.ok(typeof ackHex === 'string', 'Invalid poll ACK packet'); + const buf = Buffer.from(ackHex, 'hex'); + const ackBytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + assert.ok(ackBytes.byteLength > 0 && ackBytes.byteLength <= MAX_PACKET_BYTES, 'ACK bounds violated'); + for (const atUs of uplink.transmit(nowUs, ackBytes.byteLength)) { + pushEv(atUs, 'ACK_ARRIVAL', { peerId, bytes: new Uint8Array(ackBytes) }); + } + } + receiverNextWakeUs.set( + peerId, + res.nextWakeMs !== null ? Math.max(nowUs + 10, Math.ceil(res.nextWakeMs * 1000)) : Infinity, + ); + } + } + + if (deliveredCount >= messages.length) break; + + if (senderActive) { + const tx = sender.pollTx(nowMs); + for (const pkt of tx?.packets ?? []) { + assert.ok(peers.includes(pkt.peerId), `Invalid peerId ${pkt.peerId}`); + assert.ok( + pkt.bytes instanceof Uint8Array && pkt.bytes.byteLength > 0 && pkt.bytes.byteLength <= MAX_PACKET_BYTES, + `Invalid TX packet length ${pkt.bytes?.byteLength}`, + ); + const copy = new Uint8Array(pkt.bytes); + for (const atUs of downlink.transmit(nowUs, copy.byteLength)) { + pushEv(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = tx?.nextWakeMs; + senderNextWakeUs = typeof nw === 'number' && Number.isFinite(nw) + ? Math.max(nowUs + 10, Math.ceil(nw * 1000)) + : Infinity; + } + + if (deliveredCount >= messages.length) break; + + events.sort((a, b) => a.timeUs - b.timeUs || a.seq - b.seq); + let nextUs = events.length > 0 ? events[0].timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const w of receiverNextWakeUs.values()) { + if (w < nextUs) nextUs = w; + } + assert.ok(Number.isFinite(nextUs), `wire isolation probe idle with ${deliveredCount}/${messages.length} delivered`); + nowUs = Math.max(nowUs + 1, nextUs); + } + + await rpc({ op: 'quit' }); + } finally { + child.kill('SIGKILL'); + await fs.rm(childTmp, { recursive: true, force: true }); + } +} + +const errors = []; +let unitExactOk = false; +let gate_wire_isolation = false; + +try { + checkUnitAdversarial(); + unitExactOk = true; +} catch (err) { + errors.push(`unitAdversarial: ${err.message}`); +} + +try { + await checkWireIsolationSubprocess(); + gate_wire_isolation = true; +} catch (err) { + errors.push(`wireIsolation: ${err.message}`); +} + +const publicResults = []; +for (const profile of PUBLIC_PROFILES) { + try { + const messages = generateProfileMessages(profile); + const res = runSimulation({ profile, messages, createRelaySender, createPeerReceiver }); + publicResults.push(res); + if (!res.ok) errors.push(`public/${profile.name}: ${res.violations.slice(0, 3).join('; ')}`); + if (res.jainsFairness < 0.85) { + errors.push(`public/${profile.name}: fairness ${res.jainsFairness.toFixed(4)} < 0.85`); + } + } catch (err) { + errors.push(`public/${profile.name}: ${err.message}`); + } +} + +const heldoutResults = []; +for (const profile of HELDOUT_PROFILES) { + try { + const messages = generateProfileMessages(profile); + const res = runSimulation({ profile, messages, createRelaySender, createPeerReceiver }); + heldoutResults.push(res); + if (!res.ok) errors.push(`heldout/${profile.name}: ${res.violations.slice(0, 3).join('; ')}`); + if (res.jainsFairness < 0.85) { + errors.push(`heldout/${profile.name}: fairness ${res.jainsFairness.toFixed(4)} < 0.85`); + } + } catch (err) { + errors.push(`heldout/${profile.name}: ${err.message}`); + } +} + +const stressResults = []; +for (const profile of STRESS_PROFILES) { + try { + const messages = generateProfileMessages(profile); + const res = runSimulation({ profile, messages, createRelaySender, createPeerReceiver }); + stressResults.push(res); + if (!res.ok) errors.push(`stress/${profile.name}: ${res.violations.slice(0, 3).join('; ')}`); + if (res.jainsFairness < 0.85) { + errors.push(`stress/${profile.name}: fairness ${res.jainsFairness.toFixed(4)} < 0.85`); + } + } catch (err) { + errors.push(`stress/${profile.name}: ${err.message}`); + } +} + +const allProfileResults = [...publicResults, ...heldoutResults, ...stressResults]; +const allProfilesRan = publicResults.length === PUBLIC_PROFILES.length + && heldoutResults.length === HELDOUT_PROFILES.length + && stressResults.length === STRESS_PROFILES.length; + +const gate_exact_delivery = + unitExactOk + && allProfilesRan + && allProfileResults.every((r) => r.exactDeliveryOk === true); + +const gate_zero_interactive_drops = + unitExactOk + && allProfilesRan + && allProfileResults.every((r) => r.interactiveDeadlineOk === true && r.packetBoundsOk === true); + +const gate_peer_fairness = + allProfilesRan + && allProfileResults.every((r) => r.jainsFairness >= 0.85); + +const heldoutSummary = heldoutResults.length === HELDOUT_PROFILES.length + ? aggregateMetrics(heldoutResults) + : { + interactive_p99_ms: 999999, + wire_overhead_pct: 999999, + bulk_goodput_pct: 0, + min_jains_fairness: 0, + }; + +const publicSummary = publicResults.length === PUBLIC_PROFILES.length + ? aggregateMetrics(publicResults) + : null; + +trusted.emit(({ + status: 'graded', + items: { + gate_exact_delivery, + gate_zero_interactive_drops, + gate_peer_fairness, + gate_wire_isolation, + }, + metrics: { + interactive_p99_ms: heldoutSummary.interactive_p99_ms, + wire_overhead_pct: heldoutSummary.wire_overhead_pct, + bulk_goodput_pct: heldoutSummary.bulk_goodput_pct, + }, + details: { + errors, + publicSummary, + heldoutSummary, + stressSummary: stressResults.length === STRESS_PROFILES.length ? aggregateMetrics(stressResults) : null, + profiles: allProfileResults.map((r) => ({ + name: r.name, + ok: r.ok, + interactiveP99Ms: Number(r.interactiveP99Ms.toFixed(2)), + interactiveP50Ms: Number(r.interactiveP50Ms.toFixed(2)), + interactiveMaxMs: Number(r.interactiveMaxMs.toFixed(2)), + wireOverheadPct: Number(r.wireOverheadPct.toFixed(2)), + bulkGoodputPct: Number(r.bulkGoodputPct.toFixed(2)), + jainsFairness: Number(r.jainsFairness.toFixed(4)), + jainsFairnessMidpoint: Number(r.jainsFairnessMidpoint.toFixed(4)), + jainsFairnessCompletion: Number(r.jainsFairnessCompletion.toFixed(4)), + finishMs: Number(r.finishMs.toFixed(1)), + downlinkStats: r.downlinkStats, + uplinkStats: r.uplinkStats, + })), + }, +})); diff --git a/questions/opt-relay-congestion-scheduler/v2/author/grade.py b/questions/opt-relay-congestion-scheduler/v2/author/grade.py new file mode 100644 index 0000000..595cbdf --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/simulator/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=180 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-relay-congestion-scheduler/v2/author/grade_impl.py b/questions/opt-relay-congestion-scheduler/v2/author/grade_impl.py new file mode 100644 index 0000000..a302df2 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/grade_impl.py @@ -0,0 +1,39 @@ +"""Isolated pure-Node quantitative grader: runs unit + subprocess wire-isolation + public + held-out profiles.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-relay-opt-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=120 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-relay-congestion-scheduler/v2/author/heldout/heldout-profiles.json b/questions/opt-relay-congestion-scheduler/v2/author/heldout/heldout-profiles.json new file mode 100644 index 0000000..63b0361 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/heldout/heldout-profiles.json @@ -0,0 +1,879 @@ +[ + { + "name": "heldout-real-0", + "seed": 97000, + "source": { + "sends": 1923, + "spanHours": 8.91, + "rttP50Ms": 363, + "rttP90Ms": 896, + "lossPct": 1.586, + "stallsPerHour": 19.97, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 182, + "jitterMs": 182, + "jitterFifo": true, + "lossProb": 0.01586, + "queueBytes": 17483, + "outages": [ + [ + 1500, + 2691 + ], + [ + 2979, + 4148 + ], + [ + 20145, + 21738 + ], + [ + 38231, + 58866 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 182, + "jitterMs": 182, + "jitterFifo": true, + "lossProb": 0.01586, + "queueBytes": 17483 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 20278, + 17938, + 45230, + 45230, + 45228, + 44202, + 44186, + 44186, + 44184 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 18110, + 18111, + 18112, + 36220, + 36221, + 36222 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 20278, + 17938, + 45230, + 45230, + 45228, + 44202, + 44186, + 44186, + 44184 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 18110, + 18111, + 18112, + 36220, + 36221, + 36222 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 602, + 694, + 1068, + 560, + 687, + 943, + 553, + 660, + 819, + 546, + 628, + 730, + 411, + 607, + 697, + 1115, + 560, + 687, + 947, + 553, + 667, + 833, + 546, + 629, + 735, + 436, + 614, + 701, + 1195, + 560, + 687, + 967, + 553, + 671, + 847, + 546, + 630, + 750, + 490, + 621, + 705, + 1272, + 560, + 687, + 976, + 553, + 676, + 859, + 546, + 630, + 759, + 507, + 623, + 714, + 1385, + 560, + 687, + 1055, + 558, + 676, + 859, + 553, + 630, + 767, + 544, + 623, + 720, + 1500, + 562, + 687, + 1063, + 560, + 679, + 863, + 553, + 630, + 794, + 546, + 623, + 727, + 1723, + 581, + 689, + 1067, + 560, + 682, + 877, + 553, + 633, + 805, + 546, + 627, + 729, + 328, + 600, + 694, + 1067, + 560, + 686, + 925, + 553, + 644, + 818, + 546, + 628, + 729, + 411, + 607, + 697, + 1107, + 560, + 687, + 947, + 553, + 664, + 829, + 546, + 629, + 735 + ], + "deadlineMs": 68635, + "windows": [ + [ + 120, + 60366 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "heldout-real-1", + "seed": 97001, + "source": { + "sends": 601, + "spanHours": 13.11, + "rttP50Ms": 366, + "rttP90Ms": 491, + "lossPct": 5.354, + "stallsPerHour": 35.77, + "capacityBps": 268736 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 268736, + "propagationDelayMs": 183, + "jitterMs": 62, + "jitterFifo": true, + "lossProb": 0.05354, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 46538 + ] + ] + }, + "uplink": { + "bitsPerSecond": 268736, + "propagationDelayMs": 183, + "jitterMs": 62, + "jitterFifo": true, + "lossProb": 0.05354, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 14411, + 28823 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 14411, + 28823 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 334, + 334, + 462, + 334, + 334, + 343, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 375, + 334, + 332, + 334, + 334, + 482, + 334, + 334, + 458, + 334, + 334, + 334, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 343, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 437, + 334, + 334, + 334, + 334, + 484, + 334, + 334, + 460, + 334, + 334, + 334, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 343, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 439, + 334, + 334, + 334, + 334, + 654, + 334, + 334, + 460, + 334, + 334, + 341, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 345, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 439, + 334, + 334, + 334, + 334, + 294, + 334, + 334, + 462, + 334, + 334, + 343, + 334, + 332, + 334, + 334, + 462, + 334, + 334, + 371, + 334, + 332, + 334, + 334, + 480 + ], + "deadlineMs": 93038, + "windows": [ + [ + 120, + 48038 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "heldout-real-2", + "seed": 97002, + "source": { + "sends": 376, + "spanHours": 6.35, + "rttP50Ms": 234, + "rttP90Ms": 327, + "lossPct": 2.338, + "stallsPerHour": 26.44, + "capacityBps": 247594 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2" + ], + "downlink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 117, + "jitterMs": 46, + "jitterFifo": true, + "lossProb": 0.02338, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 6520 + ] + ] + }, + "uplink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 117, + "jitterMs": 46, + "jitterFifo": true, + "lossProb": 0.02338, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 164953, + 164953 + ], + "waveTimesMs": [ + 0, + 2406 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 164953, + 164953 + ], + "waveTimesMs": [ + 0, + 2406 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 334, + 332, + 350, + 334, + 353, + 334, + 332, + 334, + 332, + 350, + 334, + 439, + 334, + 332, + 343, + 334, + 352, + 334, + 484, + 334, + 332, + 348, + 334, + 352, + 334, + 332, + 334, + 332, + 350, + 334, + 404, + 334, + 332, + 334, + 334, + 352, + 334, + 462, + 334, + 332, + 345, + 334, + 352, + 334, + 330, + 334, + 332, + 350, + 334, + 352, + 334, + 332, + 334, + 332, + 350, + 334, + 437, + 334, + 332, + 343, + 334, + 352, + 334, + 484, + 334, + 332, + 348, + 334, + 352, + 334, + 332, + 334, + 332, + 350, + 334, + 373, + 334, + 332, + 334, + 334, + 352, + 334, + 439, + 334, + 332, + 345, + 334, + 352, + 334, + 330, + 334, + 332, + 348, + 334, + 352, + 334, + 332, + 334, + 332, + 350, + 334, + 437, + 334, + 332, + 337, + 334, + 352, + 334, + 484, + 334, + 332, + 348, + 334, + 352, + 334, + 330, + 334, + 332, + 350 + ], + "deadlineMs": 53020, + "windows": [ + [ + 120, + 8020 + ] + ], + "peers": [ + "peer-2", + "peer-0", + "peer-2", + "peer-1" + ] + } + }, + { + "name": "heldout-real-3", + "seed": 97003, + "source": { + "sends": 316, + "spanHours": 9.62, + "rttP50Ms": 283, + "rttP90Ms": 394, + "lossPct": 2.769, + "stallsPerHour": 18.61, + "capacityBps": 365326 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 365326, + "propagationDelayMs": 142, + "jitterMs": 56, + "jitterFifo": true, + "lossProb": 0.02769, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 25749 + ], + [ + 56973, + 58259 + ] + ] + }, + "uplink": { + "bitsPerSecond": 365326, + "propagationDelayMs": 142, + "jitterMs": 56, + "jitterFifo": true, + "lossProb": 0.02769, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 163649, + 163649, + 163649 + ], + "waveTimesMs": [ + 0, + 17928, + 35855 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 163649, + 163649, + 163649 + ], + "waveTimesMs": [ + 0, + 17928, + 35855 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 330, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 330, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 330, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 327, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 294, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 855, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 462, + 332, + 332, + 334, + 345, + 332, + 332, + 334, + 334, + 460, + 332, + 332, + 334, + 343, + 332, + 332, + 334, + 334, + 439, + 332, + 332, + 334, + 343, + 332, + 332, + 334, + 334, + 439, + 332, + 332, + 334, + 343, + 332, + 332, + 334, + 334, + 439, + 332, + 332, + 334, + 343, + 332, + 332, + 334, + 334, + 437, + 332, + 332, + 334, + 341, + 332, + 332, + 332, + 334, + 437, + 332, + 332 + ], + "deadlineMs": 72249, + "windows": [ + [ + 120, + 59759 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + } +] \ No newline at end of file diff --git a/questions/opt-relay-congestion-scheduler/v2/author/result-channel.mjs b/questions/opt-relay-congestion-scheduler/v2/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/author/wire-probe-child.mjs b/questions/opt-relay-congestion-scheduler/v2/author/wire-probe-child.mjs new file mode 100644 index 0000000..8854998 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/author/wire-probe-child.mjs @@ -0,0 +1,68 @@ +import crypto from 'node:crypto'; +import path from 'node:path'; +import readline from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +const [subDir] = process.argv.slice(2); +const transportMod = await import(pathToFileURL(path.join(subDir, 'transport.mjs')).href); +const { createPeerReceiver } = transportMod; + +const receivers = new Map(); + +function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +function toHex(bytes) { + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex'); +} + +function fromHex(hex) { + const buf = Buffer.from(hex, 'hex'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); +} + +const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + +rl.on('line', (line) => { + if (!line.trim()) return; + try { + const req = JSON.parse(line); + if (req.op === 'init') { + receivers.clear(); + for (const peerId of req.peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes: req.maxPacketBytes })); + } + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + } else if (req.op === 'data') { + const recv = receivers.get(req.peerId); + const res = recv.onDataPacket(req.nowMs, fromHex(req.hex)); + const delivered = (res?.delivered ?? []).map((item) => ({ + streamId: item.streamId, + msgId: item.msgId, + byteLength: item.payload instanceof Uint8Array ? item.payload.byteLength : -1, + sha256: item.payload instanceof Uint8Array ? sha256Hex(item.payload) : null, + })); + const ackPackets = (res?.ackPackets ?? []).map((p) => + p instanceof Uint8Array ? toHex(p) : null, + ); + process.stdout.write(JSON.stringify({ ok: true, delivered, ackPackets }) + '\n'); + } else if (req.op === 'poll') { + const recv = receivers.get(req.peerId); + const res = recv.pollControl(req.nowMs); + const ackPackets = (res?.ackPackets ?? []).map((p) => + p instanceof Uint8Array ? toHex(p) : null, + ); + const nw = res?.nextWakeMs; + const nextWakeMs = typeof nw === 'number' && Number.isFinite(nw) ? nw : null; + process.stdout.write(JSON.stringify({ ok: true, ackPackets, nextWakeMs }) + '\n'); + } else if (req.op === 'quit') { + process.stdout.write(JSON.stringify({ ok: true }) + '\n'); + process.exit(0); + } else { + process.stdout.write(JSON.stringify({ ok: false, error: `unknown op ${req.op}` }) + '\n'); + } + } catch (err) { + process.stdout.write(JSON.stringify({ ok: false, error: err?.message ?? String(err) }) + '\n'); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v2/candidate/CONTRACT.md new file mode 100644 index 0000000..fffe3f1 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/CONTRACT.md @@ -0,0 +1,61 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public real links, all 4 unseen held-out real links, and all 4 synthetic stress links: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). On real links `deadlineMs` is a no-starvation bound (longest outage + twice the bulk backlog's link time + 8 s); latency itself is scored by `interactive_p99_ms`. +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. + +## 4. Workload Provenance + +The public (`profiles/public-profiles.json`) and held-out links come from `device-link diagnostic` records in Cindy Desktop logs of real relay connections (`scripts/extract-real-link-profiles.py` in the question bank). Only numeric fields and product channel names were read; app instances and controllers became `link-N` / `peer-N`, and times became offsets, so the files carry no message content, accounts, device ids or wall-clock times. Each link (one app instance serving one controller, at least 150 acknowledged relay sends) gives: + +- `propagationDelayMs` = half the relay round-trip p50; `jitterMs` = half of (p90 − p50), FIFO. +- `lossProb` = retransmitted share of sends (attempts beyond the first). +- `outages`: sends whose current attempt waited at least max(1.5 s, 3 × RTT p50) for an ack, each as (wait − RTT p50), taken from the link's worst real minute and shifted to start at 1.5 s. +- `bitsPerSecond`: p95 goodput of large (≥ 32 KiB) replies on that link — a lower bound, because the product paced those transfers itself; links without enough large replies use the median over all links (262 kbit/s); never below 256 kbit/s. `queueBytes` = capacity × (RTT p90 − RTT p50), clamped to 16–256 KB. +- Message sizes: real interactive (≤ 2 KiB) and bulk (≥ 16 KiB) send sizes on that link. Two controllers pull the same bulk backlog of 20 s of link capacity in three request waves; up to two more controllers send the 120 interactive messages. Interactive messages that would be issued during an outage are queued and flushed right after it, as the app does. + +Arrival times are modeled, not replayed: the diagnostics are sampled, so they do not contain every send. diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v2/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..e28fd08 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public real links. + - `npm run bench` — runs the 4 public real links (`real-0` … `real-3`, from `profiles/public-profiles.json`) and prints per-link and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. +- Data: `profiles/public-profiles.json` (measured link profiles, see `CONTRACT.md` §4). The held-out links used for the score are not shipped. diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/TASK.md b/questions/opt-relay-congestion-scheduler/v2/candidate/TASK.md new file mode 100644 index 0000000..518fb52 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/TASK.md @@ -0,0 +1,33 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`, one per connected controller) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, real send sizes of about 300–1,900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, real send sizes of about 16–165 KiB, e.g., `messages:view` history pages, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +The links are real: every profile was measured from Cindy Desktop's own device-link diagnostics on real relay connections (round-trip 230–410 ms, 0.3–5.4% retransmitted sends, roughly 250–510 kbit/s of usable capacity, and ack stalls of 1–45 s that become link outages). See `CONTRACT.md` §4 for how each number was derived. + +## Observed Production Symptoms (the starter on the 4 public real links) + +1. **Tens of seconds of interactive Head-of-Line (HoL) blocking**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — interactive P99 is about 24 s (geomean) on the public links. +2. **Wire overhead around 140%**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts into shallow bottleneck queues (16–22 KB) and keeps retransmitting into multi-second outages, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Bulk goodput around 45% of the bottleneck**: The static frame budget collapses under random loss and recovers slowly after outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/outage detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics on unseen real links (different app instances and controllers from the public ones): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Final grading runs the public links and 4 unseen held-out real links (the score comes from the held-out links only), plus synthetic stress links with reordering, duplication, token-bucket policers and bursty loss that must pass every gate but do not affect the score. +- The score targets are physical bounds, not a reference implementation: interactive P99 980 ms (an ideal sender that puts interactive messages on an otherwise empty link), wire overhead 4.7% (headers, acks and the lost share only), bulk goodput 90% (what is left after loss, headers and interactive traffic). The three are not reachable at the same time; better trade-offs keep scoring higher. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/bench/workload.mjs new file mode 100644 index 0000000..e30ce8c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/bench/workload.mjs @@ -0,0 +1,84 @@ +import { readFileSync, realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + + +// Four real relay links measured from Cindy Desktop device-link diagnostics +// (see CONTRACT.md "Workload provenance"). Held-out links used for the score are not shipped. +export const PUBLIC_PROFILES = JSON.parse( + readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'profiles', 'public-profiles.json'), 'utf8'), +); + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/package.json b/questions/opt-relay-congestion-scheduler/v2/candidate/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/profiles/public-profiles.json b/questions/opt-relay-congestion-scheduler/v2/candidate/profiles/public-profiles.json new file mode 100644 index 0000000..b053423 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/profiles/public-profiles.json @@ -0,0 +1,926 @@ +[ + { + "name": "real-0", + "seed": 11000, + "source": { + "sends": 2037, + "spanHours": 6.69, + "rttP50Ms": 407, + "rttP90Ms": 760, + "lossPct": 0.342, + "stallsPerHour": 28.26, + "capacityBps": 506047 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329, + "outages": [ + [ + 1500, + 8209 + ] + ] + }, + "uplink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 459, + 546, + 553, + 560, + 584, + 618, + 627, + 630, + 636, + 676, + 687, + 702, + 729, + 741, + 797, + 886, + 1024, + 1159, + 364, + 461, + 546, + 553, + 560, + 588, + 618, + 627, + 630, + 637, + 676, + 687, + 702, + 729, + 742, + 798, + 894, + 1027, + 1167, + 364, + 469, + 546, + 553, + 560, + 594, + 618, + 627, + 630, + 638, + 676, + 687, + 703, + 729, + 743, + 799, + 904, + 1028, + 1179, + 364, + 469, + 546, + 553, + 560, + 597, + 619, + 627, + 630, + 639, + 677, + 687, + 705, + 729, + 744, + 801, + 906, + 1030, + 1183, + 373, + 476, + 546, + 553, + 560, + 600, + 621, + 628, + 630, + 640, + 678, + 687, + 706, + 729, + 745, + 805, + 928, + 1032, + 1191, + 375, + 478, + 546, + 553, + 560, + 602, + 621, + 628, + 630, + 642, + 679, + 687, + 708, + 729, + 745, + 808, + 930, + 1036, + 1208, + 375, + 491, + 546, + 553, + 560, + 602 + ], + "deadlineMs": 54709, + "windows": [ + [ + 120, + 9709 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-1", + "seed": 11001, + "source": { + "sends": 1212, + "spanHours": 9.64, + "rttP50Ms": 285, + "rttP90Ms": 477, + "lossPct": 0.899, + "stallsPerHour": 10.79, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3334 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 1233, + 1032, + 867, + 783, + 730, + 702, + 687, + 668, + 630, + 630, + 621, + 584, + 560, + 553, + 546, + 437, + 1659, + 1173, + 996, + 838, + 763, + 729, + 697, + 687, + 664, + 630, + 629, + 621, + 564, + 560, + 553, + 529, + 411, + 1395, + 1131, + 947, + 821, + 756, + 728, + 690, + 682, + 645, + 630, + 628, + 615, + 562, + 560, + 553, + 493, + 411, + 1349, + 1067, + 943, + 805, + 746, + 718, + 687, + 679, + 633, + 630, + 625, + 607, + 562, + 560, + 551, + 478, + 371, + 1271, + 1055, + 885, + 792, + 734, + 708, + 687, + 673, + 631, + 630, + 623, + 602, + 560, + 553, + 546, + 446, + 1940, + 1210, + 1020, + 858, + 774, + 729, + 697, + 687, + 667, + 630, + 629, + 621, + 581, + 560, + 553, + 546, + 426, + 1455, + 1143, + 971, + 833, + 759, + 729, + 694, + 685, + 654, + 630, + 628, + 619, + 562, + 560, + 553, + 497, + 411, + 1373, + 1084 + ], + "deadlineMs": 49834, + "windows": [ + [ + 120, + 5000 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-2", + "seed": 11002, + "source": { + "sends": 377, + "spanHours": 9.64, + "rttP50Ms": 286, + "rttP90Ms": 394, + "lossPct": 3.333, + "stallsPerHour": 17.54, + "capacityBps": 238288 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3098 + ], + [ + 4490, + 7865 + ], + [ + 8163, + 10097 + ], + [ + 10872, + 16223 + ] + ] + }, + "uplink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 853, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 439, + 462, + 484, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 367, + 437, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 594, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 437, + 462, + 482, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 344, + 357, + 431, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 484, + 332, + 332, + 332, + 332, + 334 + ], + "deadlineMs": 53351, + "windows": [ + [ + 120, + 17723 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-3", + "seed": 11003, + "source": { + "sends": 663, + "spanHours": 11.97, + "rttP50Ms": 317, + "rttP90Ms": 552, + "lossPct": 2.5, + "stallsPerHour": 40.84, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 25186 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 431, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 435, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 335, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 336, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332 + ], + "deadlineMs": 71686, + "windows": [ + [ + 120, + 26686 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + } +] \ No newline at end of file diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/sim/network.mjs new file mode 100644 index 0000000..834065c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/sim/network.mjs @@ -0,0 +1,825 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + // Real profiles list measured message sizes; synthetic ones give a uniform range. + const realSizes = spec.interactive.sizes; + const size = Array.isArray(realSizes) && realSizes.length > 0 + ? realSizes[i % realSizes.length] + : minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 180_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/src/congestion.mjs new file mode 100644 index 0000000..9c9b8d4 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/src/congestion.mjs @@ -0,0 +1,119 @@ +/** + * Baseline congestion control & retransmission state modeled on Cindy's + * legacy fixed frame-count CongestionSendBudget + cumulative-ACK static RTO. + */ + +export const FIXED_WINDOW_MS = 240; +export const FIXED_WINDOW_FRAMES = 32; +export const STATIC_RTO_MS = 2000; +export const MAX_UNACKED_PACKETS = 48; +export const RETRY_PASS_BUDGET = 16; + +/** + * Shared physical-frame budget: fixed packet-count window per 250ms, + * byte-blind and unpaced (emits full burst at each window boundary). + */ +export class CongestionSendBudget { + constructor(capacity = FIXED_WINDOW_FRAMES, intervalMs = FIXED_WINDOW_MS) { + this.capacity = capacity; + this.intervalMs = intervalMs; + this.windowIndex = -1; + this.spent = 0; + } + + _syncWindow(nowMs) { + const idx = Math.floor(nowMs / this.intervalMs); + if (idx !== this.windowIndex) { + this.windowIndex = idx; + this.spent = 0; + } + } + + remaining(nowMs) { + this._syncWindow(nowMs); + return Math.max(0, this.capacity - this.spent); + } + + take(nowMs, frames = 1) { + this._syncWindow(nowMs); + if (this.spent + frames > this.capacity) return false; + this.spent += frames; + return true; + } + + nextRefillMs(nowMs) { + this._syncWindow(nowMs); + if (this.spent < this.capacity) return nowMs; + return (this.windowIndex + 1) * this.intervalMs; + } +} + +/** + * Per-peer cumulative-ACK tracking with static 2000ms RTO and Go-Back-N style retry. + */ +export class PeerReliabilityState { + constructor(peerId) { + this.peerId = peerId; + this.nextSeq = 1; + this.sndUna = 1; + /** @type {Map} */ + this.unacked = new Map(); + this.lastRetryPassMs = -Infinity; + } + + canSendNew() { + return this.unacked.size < MAX_UNACKED_PACKETS; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs) { + this.unacked.set(seq, { + seq, + bytes, + firstSentMs: nowMs, + lastSentMs: nowMs, + }); + } + + onCumulativeAck(ackSeq) { + if (ackSeq <= this.sndUna) return; + for (let s = this.sndUna; s < ackSeq; s += 1) { + this.unacked.delete(s); + } + this.sndUna = ackSeq; + } + + hasTimedOut(nowMs) { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return false; + return nowMs - oldest.lastSentMs >= STATIC_RTO_MS; + } + + nextTimeoutMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + return oldest.lastSentMs + STATIC_RTO_MS; + } + + /** + * Go-Back-N style retransmit pass from sndUna onward (cumulative ACK gives no SACK info). + */ + collectRetransmits(nowMs, maxFrames) { + if (!this.hasTimedOut(nowMs) || maxFrames <= 0) return []; + const limit = Math.min(maxFrames, RETRY_PASS_BUDGET); + const out = []; + for (let s = this.sndUna; s < this.nextSeq && out.length < limit; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + entry.lastSentMs = nowMs; + out.push(entry.bytes); + } + this.lastRetryPassMs = nowMs; + return out; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/src/scheduler.mjs new file mode 100644 index 0000000..7be4a6e --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/src/scheduler.mjs @@ -0,0 +1,118 @@ +/** + * Baseline relay scheduler: + * - Per-peer FIFO message queue (no interactive priority queue) + * - Atomic multi-packet message turns (no interactive preemption mid-bulk-message) + * - Round-robin across peers at whole-message boundaries + */ + +export class RelayScheduler { + constructor(peers) { + this.peers = [...peers]; + /** @type {Map>} */ + this.queues = new Map(); + for (const peerId of this.peers) { + this.queues.set(peerId, []); + } + this.activePeer = null; + this.cursor = 0; + } + + enqueue(msg, chunkSize) { + let q = this.queues.get(msg.peerId); + if (!q) { + q = []; + this.queues.set(msg.peerId, q); + this.peers.push(msg.peerId); + } + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + // Admitted ahead of unstarted bulk messages on the same peer (like InvokeScheduler), + // but never preempts an already-started atomic bulk message or other peers' turns. + let insertIdx = q.length; + const startIdx = q.length > 0 && q[0].nextSegment > 0 ? 1 : 0; + for (let i = startIdx; i < q.length; i += 1) { + if (q[i].priority !== 'interactive') { + insertIdx = i; + break; + } + } + q.splice(insertIdx, 0, entry); + } else { + q.push(entry); + } + } + + hasPending() { + for (const q of this.queues.values()) { + if (q.length > 0) return true; + } + return false; + } + + /** + * Pick next segment to transmit. Keeps sending the active atomic message + * to completion unless that peer's reliability window is temporarily full. + */ + nextSegment(canPeerSend) { + if (this.activePeer !== null) { + const aq = this.queues.get(this.activePeer); + if (aq && aq.length > 0) { + if (canPeerSend(this.activePeer)) { + return this._popSegmentFrom(this.activePeer, aq); + } + } else { + this.activePeer = null; + } + } + + const n = this.peers.length; + for (let i = 0; i < n; i += 1) { + const idx = (this.cursor + i) % n; + const peerId = this.peers[idx]; + const q = this.queues.get(peerId); + if (!q || q.length === 0) continue; + if (!canPeerSend(peerId)) continue; + this.activePeer = peerId; + this.cursor = (idx + 1) % n; + return this._popSegmentFrom(peerId, q); + } + return null; + } + + _popSegmentFrom(peerId, q) { + const head = q[0]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const slice = head.payload.subarray(start, end); + head.nextSegment += 1; + const finished = head.nextSegment >= head.totalSegments; + if (finished) { + q.shift(); + if (this.activePeer === peerId) { + this.activePeer = null; + } + } + return { + peerId, + streamId: head.streamId, + msgId: head.msgId, + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data: slice, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/src/transport.mjs new file mode 100644 index 0000000..73ab8ee --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/src/transport.mjs @@ -0,0 +1,217 @@ +import { CongestionSendBudget, PeerReliabilityState } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_ACK = 2; +const MAX_META_RESERVE = 140; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(meta, payloadSlice, maxPacketBytes) { + const headerBytes = textEncoder.encode(JSON.stringify(meta)); + const totalLen = 3 + headerBytes.byteLength + payloadSlice.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Encoded data packet (${totalLen} B) exceeds maxPacketBytes (${maxPacketBytes} B)`); + } + const out = new Uint8Array(totalLen); + out[0] = PKT_DATA; + out[1] = (headerBytes.byteLength >>> 8) & 0xff; + out[2] = headerBytes.byteLength & 0xff; + out.set(headerBytes, 3); + out.set(payloadSlice, 3 + headerBytes.byteLength); + return out; +} + +function decodeDataPacket(packetBytes) { + if (!(packetBytes instanceof Uint8Array) || packetBytes.byteLength < 3 || packetBytes[0] !== PKT_DATA) { + return null; + } + const headerLen = (packetBytes[1] << 8) | packetBytes[2]; + if (3 + headerLen > packetBytes.byteLength) return null; + const meta = JSON.parse(textDecoder.decode(packetBytes.subarray(3, 3 + headerLen))); + const data = packetBytes.subarray(3 + headerLen); + return { meta, data }; +} + +function encodeAckPacket(ackSeq) { + const body = textEncoder.encode(JSON.stringify({ v: 1, ackSeq })); + const out = new Uint8Array(1 + body.byteLength); + out[0] = PKT_ACK; + out.set(body, 1); + return out; +} + +function decodeAckPacket(packetBytes) { + if (!(packetBytes instanceof Uint8Array) || packetBytes.byteLength < 2 || packetBytes[0] !== PKT_ACK) { + return null; + } + return JSON.parse(textDecoder.decode(packetBytes.subarray(1))); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - MAX_META_RESERVE); + + const budget = new CongestionSendBudget(); + const scheduler = new RelayScheduler(peers); + const peerStates = new Map(); + for (const peerId of peers) { + peerStates.set(peerId, new PeerReliabilityState(peerId)); + } + + function getPeerState(peerId) { + let st = peerStates.get(peerId); + if (!st) { + st = new PeerReliabilityState(peerId); + peerStates.set(peerId, st); + } + return st; + } + + return { + enqueue(nowMs, msg) { + getPeerState(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const ack = decodeAckPacket(packetBytes); + if (!ack || typeof ack.ackSeq !== 'number') return; + getPeerState(peerId).onCumulativeAck(ack.ackSeq); + }, + + pollTx(nowMs) { + const packets = []; + + // 1. Retransmissions for timed-out peers (Go-Back-N from sndUna) + for (const [peerId, st] of peerStates) { + const rem = budget.remaining(nowMs); + if (rem <= 0) break; + if (st.hasTimedOut(nowMs)) { + const retries = st.collectRetransmits(nowMs, rem); + for (const bytes of retries) { + if (!budget.take(nowMs, 1)) break; + packets.push({ peerId, bytes }); + } + } + } + + // 2. New segments using remaining fixed-window frame budget + while (budget.remaining(nowMs) > 0) { + const seg = scheduler.nextSegment((peerId) => getPeerState(peerId).canSendNew()); + if (!seg) break; + const st = getPeerState(seg.peerId); + const seq = st.allocateSeq(); + const bytes = encodeDataPacket( + { + v: 1, + seq, + s: seg.streamId, + m: seg.msgId, + i: seg.segIndex, + n: seg.totalSegments, + t: seg.totalBytes, + }, + seg.data, + maxPacketBytes, + ); + budget.take(nowMs, 1); + st.recordSent(seq, bytes, nowMs); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + let hasUnacked = false; + for (const st of peerStates.values()) { + if (st.unacked.size > 0) { + hasUnacked = true; + const rtoMs = st.nextTimeoutMs(); + if (rtoMs < nextWakeMs) nextWakeMs = rtoMs; + } + } + if (scheduler.hasPending() || (hasUnacked && budget.remaining(nowMs) === 0)) { + const refillMs = budget.nextRefillMs(nowMs); + if (refillMs > nowMs && refillMs < nextWakeMs) { + nextWakeMs = refillMs; + } + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + /** @type {Map} */ + const reorderBuffer = new Map(); + /** @type {Map, received: number }>} */ + const reassemblies = new Map(); + + function assembleSegment(meta, data) { + if (meta.n === 1) { + return { streamId: meta.s, msgId: meta.m, payload: new Uint8Array(data) }; + } + const key = `${meta.s}\u0000${meta.m}`; + let entry = reassemblies.get(key); + if (!entry) { + entry = { + streamId: meta.s, + msgId: meta.m, + totalSegments: meta.n, + totalBytes: meta.t, + parts: new Array(meta.n).fill(null), + received: 0, + }; + reassemblies.set(key, entry); + } + if (entry.parts[meta.i] === null) { + entry.parts[meta.i] = new Uint8Array(data); + entry.received += 1; + } + if (entry.received === entry.totalSegments) { + reassemblies.delete(key); + const out = new Uint8Array(entry.totalBytes); + let offset = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], offset); + offset += entry.parts[i].byteLength; + } + return { streamId: entry.streamId, msgId: entry.msgId, payload: out }; + } + return null; + } + + return { + onDataPacket(nowMs, packetBytes) { + const parsed = decodeDataPacket(packetBytes); + if (!parsed) return { delivered: [], ackPackets: [] }; + + const { meta, data } = parsed; + const delivered = []; + if (meta.seq >= rcvNext && !reorderBuffer.has(meta.seq)) { + reorderBuffer.set(meta.seq, { meta, data: new Uint8Array(data) }); + } + + while (reorderBuffer.has(rcvNext)) { + const item = reorderBuffer.get(rcvNext); + reorderBuffer.delete(rcvNext); + rcvNext += 1; + const msg = assembleSegment(item.meta, item.data); + if (msg) delivered.push(msg); + } + + // Immediate cumulative-ACK-only response (no SACK, no delayed coalescing) + return { + delivered, + ackPackets: [encodeAckPacket(rcvNext)], + }; + }, + + pollControl(nowMs) { + return { ackPackets: [], nextWakeMs: Infinity }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/candidate/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v2/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/candidate/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..fffe3f1 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/CONTRACT.md @@ -0,0 +1,61 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public real links, all 4 unseen held-out real links, and all 4 synthetic stress links: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). On real links `deadlineMs` is a no-starvation bound (longest outage + twice the bulk backlog's link time + 8 s); latency itself is scored by `interactive_p99_ms`. +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. + +## 4. Workload Provenance + +The public (`profiles/public-profiles.json`) and held-out links come from `device-link diagnostic` records in Cindy Desktop logs of real relay connections (`scripts/extract-real-link-profiles.py` in the question bank). Only numeric fields and product channel names were read; app instances and controllers became `link-N` / `peer-N`, and times became offsets, so the files carry no message content, accounts, device ids or wall-clock times. Each link (one app instance serving one controller, at least 150 acknowledged relay sends) gives: + +- `propagationDelayMs` = half the relay round-trip p50; `jitterMs` = half of (p90 − p50), FIFO. +- `lossProb` = retransmitted share of sends (attempts beyond the first). +- `outages`: sends whose current attempt waited at least max(1.5 s, 3 × RTT p50) for an ack, each as (wait − RTT p50), taken from the link's worst real minute and shifted to start at 1.5 s. +- `bitsPerSecond`: p95 goodput of large (≥ 32 KiB) replies on that link — a lower bound, because the product paced those transfers itself; links without enough large replies use the median over all links (262 kbit/s); never below 256 kbit/s. `queueBytes` = capacity × (RTT p90 − RTT p50), clamped to 16–256 KB. +- Message sizes: real interactive (≤ 2 KiB) and bulk (≥ 16 KiB) send sizes on that link. Two controllers pull the same bulk backlog of 20 s of link capacity in three request waves; up to two more controllers send the 120 interactive messages. Interactive messages that would be issued during an outage are queued and flushed right after it, as the app does. + +Arrival times are modeled, not replayed: the diagnostics are sampled, so they do not contain every send. diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..e28fd08 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public real links. + - `npm run bench` — runs the 4 public real links (`real-0` … `real-3`, from `profiles/public-profiles.json`) and prints per-link and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. +- Data: `profiles/public-profiles.json` (measured link profiles, see `CONTRACT.md` §4). The held-out links used for the score are not shipped. diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/TASK.md b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/TASK.md new file mode 100644 index 0000000..518fb52 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/TASK.md @@ -0,0 +1,33 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`, one per connected controller) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, real send sizes of about 300–1,900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, real send sizes of about 16–165 KiB, e.g., `messages:view` history pages, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +The links are real: every profile was measured from Cindy Desktop's own device-link diagnostics on real relay connections (round-trip 230–410 ms, 0.3–5.4% retransmitted sends, roughly 250–510 kbit/s of usable capacity, and ack stalls of 1–45 s that become link outages). See `CONTRACT.md` §4 for how each number was derived. + +## Observed Production Symptoms (the starter on the 4 public real links) + +1. **Tens of seconds of interactive Head-of-Line (HoL) blocking**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — interactive P99 is about 24 s (geomean) on the public links. +2. **Wire overhead around 140%**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts into shallow bottleneck queues (16–22 KB) and keeps retransmitting into multi-second outages, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Bulk goodput around 45% of the bottleneck**: The static frame budget collapses under random loss and recovers slowly after outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/outage detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics on unseen real links (different app instances and controllers from the public ones): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Final grading runs the public links and 4 unseen held-out real links (the score comes from the held-out links only), plus synthetic stress links with reordering, duplication, token-bucket policers and bursty loss that must pass every gate but do not affect the score. +- The score targets are physical bounds, not a reference implementation: interactive P99 980 ms (an ideal sender that puts interactive messages on an otherwise empty link), wire overhead 4.7% (headers, acks and the lost share only), bulk goodput 90% (what is left after loss, headers and interactive traffic). The three are not reachable at the same time; better trade-offs keep scoring higher. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..e30ce8c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/bench/workload.mjs @@ -0,0 +1,84 @@ +import { readFileSync, realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + + +// Four real relay links measured from Cindy Desktop device-link diagnostics +// (see CONTRACT.md "Workload provenance"). Held-out links used for the score are not shipped. +export const PUBLIC_PROFILES = JSON.parse( + readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'profiles', 'public-profiles.json'), 'utf8'), +); + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/package.json b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/profiles/public-profiles.json b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/profiles/public-profiles.json new file mode 100644 index 0000000..b053423 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/profiles/public-profiles.json @@ -0,0 +1,926 @@ +[ + { + "name": "real-0", + "seed": 11000, + "source": { + "sends": 2037, + "spanHours": 6.69, + "rttP50Ms": 407, + "rttP90Ms": 760, + "lossPct": 0.342, + "stallsPerHour": 28.26, + "capacityBps": 506047 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329, + "outages": [ + [ + 1500, + 8209 + ] + ] + }, + "uplink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 459, + 546, + 553, + 560, + 584, + 618, + 627, + 630, + 636, + 676, + 687, + 702, + 729, + 741, + 797, + 886, + 1024, + 1159, + 364, + 461, + 546, + 553, + 560, + 588, + 618, + 627, + 630, + 637, + 676, + 687, + 702, + 729, + 742, + 798, + 894, + 1027, + 1167, + 364, + 469, + 546, + 553, + 560, + 594, + 618, + 627, + 630, + 638, + 676, + 687, + 703, + 729, + 743, + 799, + 904, + 1028, + 1179, + 364, + 469, + 546, + 553, + 560, + 597, + 619, + 627, + 630, + 639, + 677, + 687, + 705, + 729, + 744, + 801, + 906, + 1030, + 1183, + 373, + 476, + 546, + 553, + 560, + 600, + 621, + 628, + 630, + 640, + 678, + 687, + 706, + 729, + 745, + 805, + 928, + 1032, + 1191, + 375, + 478, + 546, + 553, + 560, + 602, + 621, + 628, + 630, + 642, + 679, + 687, + 708, + 729, + 745, + 808, + 930, + 1036, + 1208, + 375, + 491, + 546, + 553, + 560, + 602 + ], + "deadlineMs": 54709, + "windows": [ + [ + 120, + 9709 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-1", + "seed": 11001, + "source": { + "sends": 1212, + "spanHours": 9.64, + "rttP50Ms": 285, + "rttP90Ms": 477, + "lossPct": 0.899, + "stallsPerHour": 10.79, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3334 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 1233, + 1032, + 867, + 783, + 730, + 702, + 687, + 668, + 630, + 630, + 621, + 584, + 560, + 553, + 546, + 437, + 1659, + 1173, + 996, + 838, + 763, + 729, + 697, + 687, + 664, + 630, + 629, + 621, + 564, + 560, + 553, + 529, + 411, + 1395, + 1131, + 947, + 821, + 756, + 728, + 690, + 682, + 645, + 630, + 628, + 615, + 562, + 560, + 553, + 493, + 411, + 1349, + 1067, + 943, + 805, + 746, + 718, + 687, + 679, + 633, + 630, + 625, + 607, + 562, + 560, + 551, + 478, + 371, + 1271, + 1055, + 885, + 792, + 734, + 708, + 687, + 673, + 631, + 630, + 623, + 602, + 560, + 553, + 546, + 446, + 1940, + 1210, + 1020, + 858, + 774, + 729, + 697, + 687, + 667, + 630, + 629, + 621, + 581, + 560, + 553, + 546, + 426, + 1455, + 1143, + 971, + 833, + 759, + 729, + 694, + 685, + 654, + 630, + 628, + 619, + 562, + 560, + 553, + 497, + 411, + 1373, + 1084 + ], + "deadlineMs": 49834, + "windows": [ + [ + 120, + 5000 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-2", + "seed": 11002, + "source": { + "sends": 377, + "spanHours": 9.64, + "rttP50Ms": 286, + "rttP90Ms": 394, + "lossPct": 3.333, + "stallsPerHour": 17.54, + "capacityBps": 238288 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3098 + ], + [ + 4490, + 7865 + ], + [ + 8163, + 10097 + ], + [ + 10872, + 16223 + ] + ] + }, + "uplink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 853, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 439, + 462, + 484, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 367, + 437, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 594, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 437, + 462, + 482, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 344, + 357, + 431, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 484, + 332, + 332, + 332, + 332, + 334 + ], + "deadlineMs": 53351, + "windows": [ + [ + 120, + 17723 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-3", + "seed": 11003, + "source": { + "sends": 663, + "spanHours": 11.97, + "rttP50Ms": 317, + "rttP90Ms": 552, + "lossPct": 2.5, + "stallsPerHour": 40.84, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 25186 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 431, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 435, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 335, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 336, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332 + ], + "deadlineMs": 71686, + "windows": [ + [ + 120, + 26686 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + } +] \ No newline at end of file diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/sim/network.mjs new file mode 100644 index 0000000..834065c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/sim/network.mjs @@ -0,0 +1,825 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + // Real profiles list measured message sizes; synthetic ones give a uniform range. + const realSizes = spec.interactive.sizes; + const size = Array.isArray(realSizes) && realSizes.length > 0 + ? realSizes[i % realSizes.length] + : minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 180_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/congestion.mjs new file mode 100644 index 0000000..fe7e330 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/congestion.mjs @@ -0,0 +1,120 @@ +/** + * Incomplete optimization control: + * Adds interactive priority queue & chunk preemption plus slightly faster static + * interactive retry timer, but still uses an unpaced fixed frame-count window, + * cumulative-ACK-only (no SACK), Go-Back-N retransmission, and no RTT/congestion control. + */ + +export const FIXED_WINDOW_MS = 100; +export const FIXED_WINDOW_FRAMES = 24; +export const BULK_STATIC_RTO_MS = 1800; +export const INTERACTIVE_STATIC_RTO_MS = 600; +export const MAX_UNACKED_PACKETS = 56; +export const RETRY_PASS_BUDGET = 16; + +export class CongestionSendBudget { + constructor(capacity = FIXED_WINDOW_FRAMES, intervalMs = FIXED_WINDOW_MS) { + this.capacity = capacity; + this.intervalMs = intervalMs; + this.windowIndex = -1; + this.spent = 0; + } + + _syncWindow(nowMs) { + const idx = Math.floor(nowMs / this.intervalMs); + if (idx !== this.windowIndex) { + this.windowIndex = idx; + this.spent = 0; + } + } + + remaining(nowMs) { + this._syncWindow(nowMs); + return Math.max(0, this.capacity - this.spent); + } + + take(nowMs, frames = 1) { + this._syncWindow(nowMs); + if (this.spent + frames > this.capacity) return false; + this.spent += frames; + return true; + } + + nextRefillMs(nowMs) { + this._syncWindow(nowMs); + if (this.spent < this.capacity) return nowMs; + return (this.windowIndex + 1) * this.intervalMs; + } +} + +export class PeerReliabilityState { + constructor(peerId) { + this.peerId = peerId; + this.nextSeq = 1; + this.sndUna = 1; + this.unacked = new Map(); + } + + canSendNew(isInteractive) { + const cap = isInteractive ? MAX_UNACKED_PACKETS + 16 : MAX_UNACKED_PACKETS; + return this.unacked.size < cap; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs, isInteractive) { + this.unacked.set(seq, { + seq, + bytes, + isInteractive, + firstSentMs: nowMs, + lastSentMs: nowMs, + }); + } + + onCumulativeAck(ackSeq) { + if (ackSeq <= this.sndUna) return; + for (let s = this.sndUna; s < ackSeq; s += 1) { + this.unacked.delete(s); + } + this.sndUna = ackSeq; + } + + _headRtoMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + for (const entry of this.unacked.values()) { + if (entry.isInteractive) return INTERACTIVE_STATIC_RTO_MS; + } + return BULK_STATIC_RTO_MS; + } + + hasTimedOut(nowMs) { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return false; + return nowMs - oldest.lastSentMs >= this._headRtoMs(); + } + + nextTimeoutMs() { + const oldest = this.unacked.get(this.sndUna); + if (!oldest) return Infinity; + return oldest.lastSentMs + this._headRtoMs(); + } + + collectRetransmits(nowMs, maxFrames) { + if (!this.hasTimedOut(nowMs) || maxFrames <= 0) return []; + const limit = Math.min(maxFrames, RETRY_PASS_BUDGET); + const out = []; + for (let s = this.sndUna; s < this.nextSeq && out.length < limit; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + entry.lastSentMs = nowMs; + out.push(entry.bytes); + } + return out; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/scheduler.mjs new file mode 100644 index 0000000..17ef129 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/scheduler.mjs @@ -0,0 +1,104 @@ +/** + * Incomplete optimization scheduler: + * Adds strict interactive priority queue & packet-level preemption across peers, + * plus simple round-robin chunking across bulk peers. + */ + +export class RelayScheduler { + constructor(peers) { + this.peers = [...peers]; + this.interactiveQueue = []; + this.bulkQueues = new Map(); + for (const peerId of this.peers) { + this.bulkQueues.set(peerId, []); + } + this.bulkCursor = 0; + this.streamMsgSeq = new Map(); + } + + _nextStreamSeq(peerId, streamId) { + const key = `${peerId}\u0000${streamId}`; + const seq = (this.streamMsgSeq.get(key) ?? 0) + 1; + this.streamMsgSeq.set(key, seq); + return seq; + } + + enqueue(msg, chunkSize) { + if (!this.bulkQueues.has(msg.peerId)) { + this.bulkQueues.set(msg.peerId, []); + this.peers.push(msg.peerId); + } + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + streamSeq: this._nextStreamSeq(msg.peerId, msg.streamId), + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + this.interactiveQueue.push(entry); + } else { + this.bulkQueues.get(msg.peerId).push(entry); + } + } + + hasPending() { + if (this.interactiveQueue.length > 0) return true; + for (const q of this.bulkQueues.values()) { + if (q.length > 0) return true; + } + return false; + } + + nextSegment(canPeerSend) { + // Always preempt with interactive segments first + for (let i = 0; i < this.interactiveQueue.length; i += 1) { + const entry = this.interactiveQueue[i]; + if (!canPeerSend(entry.peerId, true)) continue; + return this._popSegment(this.interactiveQueue, i); + } + + // Round-robin single chunk per bulk peer + const n = this.peers.length; + for (let i = 0; i < n; i += 1) { + const idx = (this.bulkCursor + i) % n; + const peerId = this.peers[idx]; + const q = this.bulkQueues.get(peerId); + if (!q || q.length === 0) continue; + if (!canPeerSend(peerId, false)) continue; + this.bulkCursor = (idx + 1) % n; + return this._popSegment(q, 0); + } + return null; + } + + _popSegment(queue, index) { + const head = queue[index]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const slice = head.payload.subarray(start, end); + head.nextSegment += 1; + if (head.nextSegment >= head.totalSegments) { + queue.splice(index, 1); + } + return { + peerId: head.peerId, + streamId: head.streamId, + msgId: head.msgId, + streamSeq: head.streamSeq, + isInteractive: head.priority === 'interactive', + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data: slice, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/transport.mjs new file mode 100644 index 0000000..8c52a12 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/src/transport.mjs @@ -0,0 +1,240 @@ +import { CongestionSendBudget, PeerReliabilityState } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_ACK = 2; +const FIXED_HDR = 18; +const MAX_ID_OVERHEAD = 48; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(seq, seg, maxPacketBytes) { + const sBytes = textEncoder.encode(seg.streamId); + const mBytes = textEncoder.encode(seg.msgId); + const headerLen = FIXED_HDR + sBytes.byteLength + mBytes.byteLength; + const totalLen = headerLen + seg.data.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Packet (${totalLen}) exceeds maxPacketBytes (${maxPacketBytes})`); + } + const out = new Uint8Array(totalLen); + const dv = new DataView(out.buffer); + out[0] = PKT_DATA; + out[1] = seg.isInteractive ? 1 : 0; + dv.setUint32(2, seq); + dv.setUint32(6, seg.streamSeq); + dv.setUint16(10, seg.segIndex); + dv.setUint16(12, seg.totalSegments); + dv.setUint16(14, sBytes.byteLength); + dv.setUint16(16, mBytes.byteLength); + let off = FIXED_HDR; + out.set(sBytes, off); + off += sBytes.byteLength; + out.set(mBytes, off); + off += mBytes.byteLength; + out.set(seg.data, off); + return out; +} + +function decodeDataPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < FIXED_HDR || bytes[0] !== PKT_DATA) { + return null; + } + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const isInteractive = bytes[1] === 1; + const seq = dv.getUint32(2); + const streamSeq = dv.getUint32(6); + const segIndex = dv.getUint16(10); + const totalSegments = dv.getUint16(12); + const sLen = dv.getUint16(14); + const mLen = dv.getUint16(16); + const dataOff = FIXED_HDR + sLen + mLen; + if (dataOff > bytes.byteLength) return null; + const streamId = textDecoder.decode(bytes.subarray(FIXED_HDR, FIXED_HDR + sLen)); + const msgId = textDecoder.decode(bytes.subarray(FIXED_HDR + sLen, dataOff)); + const data = bytes.subarray(dataOff); + return { seq, isInteractive, streamId, msgId, streamSeq, segIndex, totalSegments, data }; +} + +function encodeAckPacket(ackSeq) { + const out = new Uint8Array(5); + out[0] = PKT_ACK; + new DataView(out.buffer).setUint32(1, ackSeq); + return out; +} + +function decodeAckPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < 5 || bytes[0] !== PKT_ACK) return null; + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - FIXED_HDR - MAX_ID_OVERHEAD); + + const budget = new CongestionSendBudget(); + const scheduler = new RelayScheduler(peers); + const peerStates = new Map(); + for (const peerId of peers) { + peerStates.set(peerId, new PeerReliabilityState(peerId)); + } + + function getPeerState(peerId) { + let st = peerStates.get(peerId); + if (!st) { + st = new PeerReliabilityState(peerId); + peerStates.set(peerId, st); + } + return st; + } + + return { + enqueue(nowMs, msg) { + getPeerState(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const ackSeq = decodeAckPacket(packetBytes); + if (ackSeq === null) return; + getPeerState(peerId).onCumulativeAck(ackSeq); + }, + + pollTx(nowMs) { + const packets = []; + + for (const [peerId, st] of peerStates) { + const rem = budget.remaining(nowMs); + if (rem <= 0) break; + if (st.hasTimedOut(nowMs)) { + const retries = st.collectRetransmits(nowMs, rem); + for (const bytes of retries) { + if (!budget.take(nowMs, 1)) break; + packets.push({ peerId, bytes }); + } + } + } + + while (budget.remaining(nowMs) > 0) { + const seg = scheduler.nextSegment((peerId, isInteractive) => + getPeerState(peerId).canSendNew(isInteractive), + ); + if (!seg) break; + const st = getPeerState(seg.peerId); + const seq = st.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + budget.take(nowMs, 1); + st.recordSent(seq, bytes, nowMs, seg.isInteractive); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + let hasUnacked = false; + for (const st of peerStates.values()) { + if (st.unacked.size > 0) { + hasUnacked = true; + const rtoMs = st.nextTimeoutMs(); + if (rtoMs < nextWakeMs) nextWakeMs = rtoMs; + } + } + if (scheduler.hasPending() || (hasUnacked && budget.remaining(nowMs) === 0)) { + const refillMs = budget.nextRefillMs(nowMs); + if (refillMs > nowMs && refillMs < nextWakeMs) { + nextWakeMs = refillMs; + } + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + const seenSeqs = new Set(); + /** @type {Map, pending: Map }>} */ + const streams = new Map(); + + function getStream(streamId) { + let st = streams.get(streamId); + if (!st) { + st = { nextStreamSeq: 1, ready: new Map(), pending: new Map() }; + streams.set(streamId, st); + } + return st; + } + + return { + onDataPacket(nowMs, packetBytes) { + const pkt = decodeDataPacket(packetBytes); + if (!pkt) return { delivered: [], ackPackets: [] }; + + const delivered = []; + const isNewSeq = pkt.seq >= rcvNext && !seenSeqs.has(pkt.seq); + if (isNewSeq) { + seenSeqs.add(pkt.seq); + while (seenSeqs.has(rcvNext)) { + seenSeqs.delete(rcvNext); + rcvNext += 1; + } + + const st = getStream(pkt.streamId); + if (pkt.streamSeq >= st.nextStreamSeq && !st.ready.has(pkt.streamSeq)) { + if (pkt.totalSegments === 1) { + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: pkt.msgId, + payload: new Uint8Array(pkt.data), + }); + } else { + let entry = st.pending.get(pkt.streamSeq); + if (!entry) { + entry = { + msgId: pkt.msgId, + totalSegments: pkt.totalSegments, + parts: new Array(pkt.totalSegments).fill(null), + received: 0, + totalBytes: 0, + }; + st.pending.set(pkt.streamSeq, entry); + } + if (entry.parts[pkt.segIndex] === null) { + entry.parts[pkt.segIndex] = new Uint8Array(pkt.data); + entry.received += 1; + entry.totalBytes += pkt.data.byteLength; + } + if (entry.received === entry.totalSegments) { + st.pending.delete(pkt.streamSeq); + const out = new Uint8Array(entry.totalBytes); + let off = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], off); + off += entry.parts[i].byteLength; + } + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: entry.msgId, + payload: out, + }); + } + } + while (st.ready.has(st.nextStreamSeq)) { + delivered.push(st.ready.get(st.nextStreamSeq)); + st.ready.delete(st.nextStreamSeq); + st.nextStreamSeq += 1; + } + } + } + + return { + delivered, + ackPackets: [encodeAckPacket(rcvNext)], + }; + }, + + pollControl(nowMs) { + return { ackPackets: [], nextWakeMs: Infinity }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-relay-congestion-scheduler/v2/question.json b/questions/opt-relay-congestion-scheduler/v2/question.json new file mode 100644 index 0000000..7d175c5 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/question.json @@ -0,0 +1,81 @@ +{ + "id": "opt-relay-congestion-scheduler", + "revision": "v2", + "scoringVersion": "metric-v1", + "title": "共享中继弱网拥塞调度、抢占式分片与选择性重传优化", + "status": "calibrated", + "changeNote": "v2: replaces the four invented weak-network profiles with real relay links measured from Cindy Desktop device-link diagnostics (21 app-instance x controller links over the personal-update builds; scripts/extract-real-link-profiles.py). Per link: relay RTT p50/p90, retransmitted share of sends as loss, ack stalls of at least max(1.5 s, 3 x RTT) placed as outages in the link's worst real minute, product-paced goodput of large replies as a capacity lower bound (median 262 kbps where unmeasured), and real message sizes (interactive <= 2 KiB, bulk >= 16 KiB; bulk backlog = 20 s of capacity split over two controllers). 4 public links ship with the candidate; 4 different links are held out for the score; v1's synthetic profiles (reordering, duplication, policers, bursty loss) stay as gate-only stress links. Interactive deadlines become a no-starvation gate (longest outage + twice the bulk backlog + 8 s). Baseline = the starter on the held-out links; targets are per-metric physical bounds: p99 of an ideal interactive-only link schedule plus propagation and worst jitter (980 ms), loss + 10 B header + ack floor (4.7%), loss/header/interactive-share goodput ceiling (90%).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "interactive_latency", + "weight": "1/2", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "interactive_p99_ms", + "label": "Held-out real links: interactive P99 latency (geomean)", + "unit": "ms", + "direction": "lower", + "baseline": 26875, + "target": 980, + "scale": "log" + } + }, + { + "id": "wire_efficiency", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "wire_overhead_pct", + "label": "Held-out real links: total wire overhead", + "unit": "%", + "direction": "lower", + "baseline": 181.4, + "target": 4.7, + "scale": "log" + } + }, + { + "id": "bulk_throughput", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_exact_delivery", + "gate_zero_interactive_drops", + "gate_peer_fairness", + "gate_wire_isolation" + ], + "metric": { + "id": "bulk_goodput_pct", + "label": "Held-out real links: bulk bottleneck goodput", + "unit": "%", + "direction": "higher", + "baseline": 42.98, + "target": 90, + "scale": "linear" + } + } + ] +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/CONTRACT.md b/questions/opt-relay-congestion-scheduler/v2/reference/CONTRACT.md new file mode 100644 index 0000000..fffe3f1 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/CONTRACT.md @@ -0,0 +1,61 @@ +# Protocol & Simulator Contract + +This contract specifies the required public entrypoint in `src/transport.mjs`, simulator physical rules (`sim/network.mjs`), and correctness invariants. Within these invariants, **you are completely free to design the wire packet format, framing, scheduling, congestion/pacing control, selective reliability, and adaptive redundancy** across `src/`. + +## 1. Public Protocol Interface (`src/transport.mjs`) + +`src/transport.mjs` MUST export the following two factory functions (helper modules such as `src/congestion.mjs`, `src/scheduler.mjs`, or additional files under `src/` may be freely modified or added): + +### `export function createRelaySender(config)` +- `config`: `{ maxPacketBytes: number, peers: string[] }` (default `maxPacketBytes = 1200`). +- Returns an object with: + - `enqueue(nowMs, msg)`: + - `nowMs`: virtual clock timestamp in milliseconds (monotonically non-decreasing floating-point ms with microsecond resolution, e.g., `12.400`). + - `msg`: `{ peerId: string, streamId: string, msgId: string, priority: 'interactive' | 'bulk', payload: Uint8Array, deadlineMs: number }`. + - Payloads are high-entropy incompressible `Uint8Array` buffers; `msg.payload` may have arbitrary byte length (`>= 1` B up to `>= 256` KiB). + - `onAckPacket(nowMs, peerId, packetBytes)`: + - Receives a raw `Uint8Array` control/ACK packet emitted by `peerId`'s receiver after traversing the reverse uplink. + - `pollTx(nowMs)`: + - Returns `{ packets: Array<{ peerId: string, bytes: Uint8Array }>, nextWakeMs: number }`. + - Every packet must target a configured `peerId` and satisfy `bytes instanceof Uint8Array && bytes.byteLength > 0 && bytes.byteLength <= maxPacketBytes`. + - Return `nextWakeMs: Infinity` when no future timer wakeup is needed (the simulator always calls `pollTx` immediately upon new `enqueue` or `onAckPacket` events). + +### `export function createPeerReceiver(peerId, config)` +- `peerId`: string identifier of this peer. +- `config`: `{ maxPacketBytes: number }`. +- Returns an object with: + - `onDataPacket(nowMs, packetBytes)`: + - Receives a raw `Uint8Array` packet emitted by the sender after traversing the shared downlink. + - Returns `{ delivered: Array<{ streamId: string, msgId: string, payload: Uint8Array }>, ackPackets: Array }`. + - `pollControl(nowMs)`: + - Invoked by the simulator after data arrivals at `nowMs` and whenever the receiver's previously returned `nextWakeMs` is reached. + - Returns `{ ackPackets: Array, nextWakeMs: number }`. + - Every packet in `ackPackets` must satisfy `pkt instanceof Uint8Array && pkt.byteLength > 0 && pkt.byteLength <= maxPacketBytes`. + +## 2. Physical Link & Billing Rules (`sim/network.mjs`, read-only) + +- **Shared bottleneck downlink** (`Sender → Relay → Peers`): All peers share one serialized bottleneck pipe (`bitsPerSecond`) with a finite tail-drop byte queue (`queueBytes`), optional ingress token-bucket policer (`bucketBytesPerSec`, `bucketDepthBytes`), optional outage blackouts (`outages`), independent time-based burst loss + random loss, bounded FIFO jitter, optional packet reordering, duplication, and periodic Wi-Fi stalls (which hold arrivals and release them together without dropping). +- **Reverse ACK uplink** (`Peers → Relay → Sender`): Carries receiver `ackPackets` back to the sender with propagation delay, jitter, loss, outages, stalls, and bandwidth/queue limits. +- **Full wire billing**: Every emitted downlink data byte (headers, payload, retransmissions, FEC/parity) AND every emitted uplink ACK byte is billed to `totalWireBytes` and physically traverses the links. +- **Incompressible payloads**: Payloads are SplitMix64 high-entropy random bytes; throughput and wire overhead must be won through protocol, scheduling, and congestion efficiency rather than payload compression. + +## 3. Hard Correctness & Anti-Cheat Gates + +All four gates must pass on unit tests, all 4 public real links, all 4 unseen held-out real links, and all 4 synthetic stress links: + +1. `gate_exact_delivery`: Every enqueued interactive and bulk message is delivered exactly once with matching byte length and SHA-256 hash in strict FIFO order per `(peerId, streamId)`. +2. `gate_zero_interactive_drops`: Zero interactive messages miss `deadlineMs`, and every emitted packet obeys `0 < bytes.byteLength <= maxPacketBytes` (`1200`). On real links `deadlineMs` is a no-starvation bound (longest outage + twice the bulk backlog's link time + 8 s); latency itself is scored by `interactive_p99_ms`. +3. `gate_peer_fairness`: Jain's Fairness Index across concurrent bulk peers is `>= 0.85` on every multi-bulk profile (evaluated as `min(midpointShareFairness, completionThroughputFairness)` so starving one peer until another completes fails). +4. `gate_wire_isolation`: Verified by running `createRelaySender` and `createPeerReceiver` in **separate OS processes** passing only serialized `Uint8Array` packets over IPC. Zero shared module variables, `globalThis` channels, or filesystem side channels are permitted. + +## 4. Workload Provenance + +The public (`profiles/public-profiles.json`) and held-out links come from `device-link diagnostic` records in Cindy Desktop logs of real relay connections (`scripts/extract-real-link-profiles.py` in the question bank). Only numeric fields and product channel names were read; app instances and controllers became `link-N` / `peer-N`, and times became offsets, so the files carry no message content, accounts, device ids or wall-clock times. Each link (one app instance serving one controller, at least 150 acknowledged relay sends) gives: + +- `propagationDelayMs` = half the relay round-trip p50; `jitterMs` = half of (p90 − p50), FIFO. +- `lossProb` = retransmitted share of sends (attempts beyond the first). +- `outages`: sends whose current attempt waited at least max(1.5 s, 3 × RTT p50) for an ack, each as (wait − RTT p50), taken from the link's worst real minute and shifted to start at 1.5 s. +- `bitsPerSecond`: p95 goodput of large (≥ 32 KiB) replies on that link — a lower bound, because the product paced those transfers itself; links without enough large replies use the median over all links (262 kbit/s); never below 256 kbit/s. `queueBytes` = capacity × (RTT p90 − RTT p50), clamped to 16–256 KB. +- Message sizes: real interactive (≤ 2 KiB) and bulk (≥ 16 KiB) send sizes on that link. Two controllers pull the same bulk backlog of 20 s of link capacity in three request waves; up to two more controllers send the 120 interactive messages. Interactive messages that would be issued during an outage are queued and flushed right after it, as the app does. + +Arrival times are modeled, not replayed: the diagnostics are sampled, so they do not contain every send. diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/ENVIRONMENT.md b/questions/opt-relay-congestion-scheduler/v2/reference/ENVIRONMENT.md new file mode 100644 index 0000000..e28fd08 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a 100% deterministic SplitMix64 PRNG and a virtual discrete-event microsecond clock (`sim/network.mjs`) — latency, wire overhead, goodput, and fairness metrics have zero wall-clock jitter and are bit-identical across runs and hardware. +- Public checks: + - `npm test` — unit adversarial chaos test (loss, reorder, duplication, blackout) + correctness & fairness assertions across all 4 public real links. + - `npm run bench` — runs the 4 public real links (`real-0` … `real-3`, from `profiles/public-profiles.json`) and prints per-link and aggregate `interactive_p99_ms`, `wire_overhead_pct`, `bulk_goodput_pct`, and `min_jains_fairness`. +- Data: `profiles/public-profiles.json` (measured link profiles, see `CONTRACT.md` §4). The held-out links used for the score are not shipped. diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/TASK.md b/questions/opt-relay-congestion-scheduler/v2/reference/TASK.md new file mode 100644 index 0000000..518fb52 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/TASK.md @@ -0,0 +1,33 @@ +# Task + +You are optimizing Cindy's shared-relay weak-network congestion control, multi-peer scheduler, packet framing, and reliable delivery protocol extracted from `packages/device-link` (`congestionSendBudget.ts`, `invokeScheduler.ts`, `transport.ts`) and modeled against realistic weak-network link physics (`packages/agent-net-core/sim`). + +A single sender shares one bottleneck relay downlink (and reverse ACK uplink) to serve multiple concurrent peers (`peer-0..peer-K`, one per connected controller) simultaneously mixing: +- **Interactive messages** (`priority: 'interactive'`, real send sizes of about 300–1,900 B, e.g., `maker:send`, `maker:abort`, permission approvals, UI actions) requiring low P99 latency. +- **Bulk transfers** (`priority: 'bulk'`, real send sizes of about 16–165 KiB, e.g., `messages:view` history pages, file chunks, screenshots) requiring high bottleneck utilization and fair sharing across concurrent bulk peers. + +The links are real: every profile was measured from Cindy Desktop's own device-link diagnostics on real relay connections (round-trip 230–410 ms, 0.3–5.4% retransmitted sends, roughly 250–510 kbit/s of usable capacity, and ack stalls of 1–45 s that become link outages). See `CONTRACT.md` §4 for how each number was derived. + +## Observed Production Symptoms (the starter on the 4 public real links) + +1. **Tens of seconds of interactive Head-of-Line (HoL) blocking**: The baseline scheduler transmits multi-packet bulk messages atomically without interactive preemption across peers, uses a single per-peer ordered stream (so lost bulk packets block interactive delivery), and relies on a static `2000ms` retry timer — interactive P99 is about 24 s (geomean) on the public links. +2. **Wire overhead around 140%**: The byte-blind fixed frame-count window (`32 frames / 240ms`) dumps full bursts into shallow bottleneck queues (16–22 KB) and keeps retransmitting into multi-second outages, while cumulative-ACK-only tracking forces redundant Go-Back-N retransmissions and verbose JSON metadata headers waste per-packet capacity. +3. **Bulk goodput around 45% of the bottleneck**: The static frame budget collapses under random loss and recovers slowly after outages. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness and physical wire-protocol invariants** defined in `CONTRACT.md`: + - **Exact delivery**: 100% of interactive and bulk messages must be delivered bit-exact (SHA-256 verified against high-entropy incompressible payloads) in strict FIFO order per `(peerId, streamId)`. + - **Packet bounds & zero interactive drops**: Every emitted data and ACK packet must satisfy `0 < bytes.byteLength <= maxPacketBytes` (`1200` B), and zero interactive messages may miss their `deadlineMs`. + - **Peer fairness**: Jain's Fairness Index across concurrent bulk peers must remain `>= 0.85` (both at transfer midpoint and at completion) on every multi-bulk profile. + - **Strict wire-only isolation**: `createRelaySender` and `createPeerReceiver` must communicate **exclusively** via serialized `Uint8Array` packets returned/accepted through the contract methods — zero shared module state, globals, or side channels (verified across separate OS processes). +- **Open-ended optimization goal**: You control both sender and receiver inside `src/` and may freely redesign framing, scheduling, congestion control, pacing, selective ACK/SACK, RTT/loss/stall/outage detection, and adaptive FEC/redundancy to simultaneously optimize all three metrics on unseen real links (different app instances and controllers from the public ones): + - `interactive_p99_ms` (weight `1/2`, lower is better, log scale): Geometric mean of Interactive P99 completion latency across held-out profiles. + - `wire_overhead_pct` (weight `1/4`, lower is better, log scale): `(totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes * 100` (all downlink data + headers + retransmissions + parity + uplink ACKs are billed). + - `bulk_goodput_pct` (weight `1/4`, higher is better, linear scale): Mean effective bulk goodput as `%` of theoretical available bottleneck bandwidth across held-out profiles. +- Run `npm test` and `npm run bench` to verify correctness and compare public-profile numbers. Final grading runs the public links and 4 unseen held-out real links (the score comes from the held-out links only), plus synthetic stress links with reordering, duplication, token-bucket policers and bursty loss that must pass every gate but do not affect the score. +- The score targets are physical bounds, not a reference implementation: interactive P99 980 ms (an ideal sender that puts interactive messages on an otherwise empty link), wire overhead 4.7% (headers, acks and the lost share only), bulk goodput 90% (what is left after loss, headers and interactive traffic). The three are not reachable at the same time; better trade-offs keep scoring higher. +- Record your analysis, protocol design, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、模拟器、基准脚本、运行环境和题面。 diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/bench/workload.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/bench/workload.mjs new file mode 100644 index 0000000..e30ce8c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/bench/workload.mjs @@ -0,0 +1,84 @@ +import { readFileSync, realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + + +// Four real relay links measured from Cindy Desktop device-link diagnostics +// (see CONTRACT.md "Workload provenance"). Held-out links used for the score are not shipped. +export const PUBLIC_PROFILES = JSON.parse( + readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'profiles', 'public-profiles.json'), 'utf8'), +); + +export function aggregateMetrics(results) { + let logSumP99 = 0; + let totalWireBytes = 0; + let totalUniquePayloadBytes = 0; + let goodputSum = 0; + let minFairness = 1; + let allOk = true; + + for (const r of results) { + if (!r.ok) allOk = false; + logSumP99 += Math.log(Math.max(1, r.interactiveP99Ms)); + totalWireBytes += r.totalWireBytes; + totalUniquePayloadBytes += r.totalUniquePayloadBytes; + goodputSum += r.bulkGoodputPct; + if (r.jainsFairness < minFairness) minFairness = r.jainsFairness; + } + + return { + allOk, + interactive_p99_ms: Number(Math.exp(logSumP99 / results.length).toFixed(2)), + wire_overhead_pct: Number((((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100).toFixed(2)), + bulk_goodput_pct: Number((goodputSum / results.length).toFixed(2)), + min_jains_fairness: Number(minFairness.toFixed(4)), + }; +} + +export function runPublicBench(transportMod = { createRelaySender, createPeerReceiver }) { + const results = []; + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender: transportMod.createRelaySender, + createPeerReceiver: transportMod.createPeerReceiver, + }); + results.push(res); + } + return { results, summary: aggregateMetrics(results) }; +} + +const isMain = isMainModule(); +if (isMain) { + const { results, summary } = runPublicBench(); + console.log('\nPublic Relay Congestion Profiles:'); + for (const r of results) { + console.log( + ` ${r.name.padEnd(22)} ok=${String(r.ok).padEnd(5)} ` + + `p99=${r.interactiveP99Ms.toFixed(1).padStart(7)}ms ` + + `overhead=${r.wireOverheadPct.toFixed(2).padStart(6)}% ` + + `goodput=${r.bulkGoodputPct.toFixed(2).padStart(6)}% ` + + `jain=${r.jainsFairness.toFixed(3)} ` + + `qDrops=${r.downlinkStats.queueDrops} pDrops=${r.downlinkStats.policerDrops} lDrops=${r.downlinkStats.lossDrops}`, + ); + if (r.violations.length) { + console.log(` violations: ${r.violations.slice(0, 3).join('; ')}`); + } + } + console.log('\nPublic Summary:', JSON.stringify(summary)); + if (!summary.allOk || summary.min_jains_fairness < 0.85) { + process.exitCode = 1; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/package.json b/questions/opt-relay-congestion-scheduler/v2/reference/package.json new file mode 100644 index 0000000..d8a3a64 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-relay-congestion-scheduler", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/profiles/public-profiles.json b/questions/opt-relay-congestion-scheduler/v2/reference/profiles/public-profiles.json new file mode 100644 index 0000000..b053423 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/profiles/public-profiles.json @@ -0,0 +1,926 @@ +[ + { + "name": "real-0", + "seed": 11000, + "source": { + "sends": 2037, + "spanHours": 6.69, + "rttP50Ms": 407, + "rttP90Ms": 760, + "lossPct": 0.342, + "stallsPerHour": 28.26, + "capacityBps": 506047 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329, + "outages": [ + [ + 1500, + 8209 + ] + ] + }, + "uplink": { + "bitsPerSecond": 506047, + "propagationDelayMs": 204, + "jitterMs": 176, + "jitterFifo": true, + "lossProb": 0.00342, + "queueBytes": 22329 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 18016, + 44610, + 44626, + 24685, + 44610, + 17242, + 44396, + 44626, + 24665, + 44610, + 88126, + 30554, + 44610, + 24665, + 44610, + 86922 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 3, + 4, + 5, + 2913, + 2914, + 2915, + 2916, + 2917, + 5825, + 5826, + 5827, + 5828, + 5829 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 459, + 546, + 553, + 560, + 584, + 618, + 627, + 630, + 636, + 676, + 687, + 702, + 729, + 741, + 797, + 886, + 1024, + 1159, + 364, + 461, + 546, + 553, + 560, + 588, + 618, + 627, + 630, + 637, + 676, + 687, + 702, + 729, + 742, + 798, + 894, + 1027, + 1167, + 364, + 469, + 546, + 553, + 560, + 594, + 618, + 627, + 630, + 638, + 676, + 687, + 703, + 729, + 743, + 799, + 904, + 1028, + 1179, + 364, + 469, + 546, + 553, + 560, + 597, + 619, + 627, + 630, + 639, + 677, + 687, + 705, + 729, + 744, + 801, + 906, + 1030, + 1183, + 373, + 476, + 546, + 553, + 560, + 600, + 621, + 628, + 630, + 640, + 678, + 687, + 706, + 729, + 745, + 805, + 928, + 1032, + 1191, + 375, + 478, + 546, + 553, + 560, + 602, + 621, + 628, + 630, + 642, + 679, + 687, + 708, + 729, + 745, + 808, + 930, + 1036, + 1208, + 375, + 491, + 546, + 553, + 560, + 602 + ], + "deadlineMs": 54709, + "windows": [ + [ + 120, + 9709 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-1", + "seed": 11001, + "source": { + "sends": 1212, + "spanHours": 9.64, + "rttP50Ms": 285, + "rttP90Ms": 477, + "lossPct": 0.899, + "stallsPerHour": 10.79, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3334 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 142, + "jitterMs": 96, + "jitterFifo": true, + "lossProb": 0.00899, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 24569, + 43786, + 43618, + 43598, + 24569, + 43786, + 43618, + 43598, + 40706 + ], + "waveTimesMs": [ + 0, + 1, + 2, + 1500, + 1501, + 1502, + 3000, + 3001, + 3002 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 364, + 1233, + 1032, + 867, + 783, + 730, + 702, + 687, + 668, + 630, + 630, + 621, + 584, + 560, + 553, + 546, + 437, + 1659, + 1173, + 996, + 838, + 763, + 729, + 697, + 687, + 664, + 630, + 629, + 621, + 564, + 560, + 553, + 529, + 411, + 1395, + 1131, + 947, + 821, + 756, + 728, + 690, + 682, + 645, + 630, + 628, + 615, + 562, + 560, + 553, + 493, + 411, + 1349, + 1067, + 943, + 805, + 746, + 718, + 687, + 679, + 633, + 630, + 625, + 607, + 562, + 560, + 551, + 478, + 371, + 1271, + 1055, + 885, + 792, + 734, + 708, + 687, + 673, + 631, + 630, + 623, + 602, + 560, + 553, + 546, + 446, + 1940, + 1210, + 1020, + 858, + 774, + 729, + 697, + 687, + 667, + 630, + 629, + 621, + 581, + 560, + 553, + 546, + 426, + 1455, + 1143, + 971, + 833, + 759, + 729, + 694, + 685, + 654, + 630, + 628, + 619, + 562, + 560, + 553, + 497, + 411, + 1373, + 1084 + ], + "deadlineMs": 49834, + "windows": [ + [ + 120, + 5000 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-2", + "seed": 11002, + "source": { + "sends": 377, + "spanHours": 9.64, + "rttP50Ms": 286, + "rttP90Ms": 394, + "lossPct": 3.333, + "stallsPerHour": 17.54, + "capacityBps": 238288 + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 3098 + ], + [ + 4490, + 7865 + ], + [ + 8163, + 10097 + ], + [ + 10872, + 16223 + ] + ] + }, + "uplink": { + "bitsPerSecond": 256000, + "propagationDelayMs": 143, + "jitterMs": 54, + "jitterFifo": true, + "lossProb": 0.03333, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 164318, + 164318 + ], + "waveTimesMs": [ + 0, + 5317 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 853, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 439, + 462, + 484, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 367, + 437, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 594, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 345, + 394, + 437, + 462, + 482, + 330, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 334, + 344, + 357, + 431, + 460, + 462, + 329, + 332, + 332, + 332, + 332, + 334, + 334, + 334, + 334, + 334, + 334, + 343, + 345, + 418, + 439, + 462, + 484, + 332, + 332, + 332, + 332, + 334 + ], + "deadlineMs": 53351, + "windows": [ + [ + 120, + 17723 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + }, + { + "name": "real-3", + "seed": 11003, + "source": { + "sends": 663, + "spanHours": 11.97, + "rttP50Ms": 317, + "rttP90Ms": 552, + "lossPct": 2.5, + "stallsPerHour": 40.84, + "capacityBps": null + }, + "peers": [ + "peer-0", + "peer-1", + "peer-2", + "peer-3" + ], + "downlink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000, + "outages": [ + [ + 1500, + 25186 + ] + ] + }, + "uplink": { + "bitsPerSecond": 262418, + "propagationDelayMs": 158, + "jitterMs": 118, + "jitterFifo": true, + "lossProb": 0.025, + "queueBytes": 16000 + }, + "bulkPeers": [ + { + "peerId": "peer-0", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + }, + { + "peerId": "peer-1", + "streamId": "bulk-0", + "messageSizes": [ + 167419, + 167419 + ], + "waveTimesMs": [ + 0, + 8006 + ] + } + ], + "interactive": { + "count": 120, + "sizes": [ + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 418, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 330, + 334, + 439, + 332, + 431, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 435, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 335, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 439, + 334, + 437, + 332, + 336, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332, + 334, + 332 + ], + "deadlineMs": 71686, + "windows": [ + [ + 120, + 26686 + ] + ], + "peers": [ + "peer-2", + "peer-3", + "peer-0", + "peer-2", + "peer-3", + "peer-1" + ] + } + } +] \ No newline at end of file diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/sim/network.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/sim/network.mjs new file mode 100644 index 0000000..834065c --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/sim/network.mjs @@ -0,0 +1,825 @@ +import crypto from 'node:crypto'; + +export const MAX_PACKET_BYTES = 1200; + +const MASK_64 = (1n << 64n) - 1n; +const SM_GAMMA = 0x9e3779b97f4a7c15n; +const SM_MUL1 = 0xbf58476d1ce4e5b9n; +const SM_MUL2 = 0x94d049bb133111ebn; +const INV_2_53 = 1 / 9007199254740992; + +/** Deterministic SplitMix64 PRNG (exact 64-bit unsigned arithmetic). */ +export class SplitMix64 { + constructor(seed) { + this.state = BigInt.asUintN(64, BigInt(seed)); + } + + nextU64() { + this.state = (this.state + SM_GAMMA) & MASK_64; + let z = this.state; + z = ((z ^ (z >> 30n)) * SM_MUL1) & MASK_64; + z = ((z ^ (z >> 27n)) * SM_MUL2) & MASK_64; + return (z ^ (z >> 31n)) & MASK_64; + } + + nextFloat() { + return Number(this.nextU64() >> 11n) * INV_2_53; + } + + chance(probability) { + if (probability <= 0) return false; + if (probability >= 1) return true; + return this.nextFloat() < probability; + } + + below(bound) { + if (bound <= 0) return 0; + return Number(this.nextU64() % BigInt(bound)); + } + + /** High-entropy incompressible payload bytes. */ + fillBytes(length) { + const out = new Uint8Array(length); + let offset = 0; + while (offset + 8 <= length) { + const v = this.nextU64(); + const lo = Number(v & 0xffffffffn); + const hi = Number((v >> 32n) & 0xffffffffn); + out[offset] = lo & 0xff; + out[offset + 1] = (lo >>> 8) & 0xff; + out[offset + 2] = (lo >>> 16) & 0xff; + out[offset + 3] = (lo >>> 24) & 0xff; + out[offset + 4] = hi & 0xff; + out[offset + 5] = (hi >>> 8) & 0xff; + out[offset + 6] = (hi >>> 16) & 0xff; + out[offset + 7] = (hi >>> 24) & 0xff; + offset += 8; + } + if (offset < length) { + let v = this.nextU64(); + while (offset < length) { + out[offset++] = Number(v & 0xffn); + v >>= 8n; + } + } + return out; + } +} + +export function sha256Hex(bytes) { + return crypto.createHash('sha256').update(bytes).digest('hex'); +} + +export function percentile(values, p) { + if (!values.length) return 0; + const sorted = [...values].sort((a, b) => a - b); + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, Math.min(sorted.length - 1, idx))]; +} + +export function jainsFairnessIndex(values) { + if (values.length <= 1) return 1; + let sum = 0; + let sq = 0; + for (const v of values) { + sum += v; + sq += v * v; + } + if (sq <= 0) return 0; + return (sum * sum) / (values.length * sq); +} + +export function computeOutageOverlapUs(outagesUs, startUs, endUs) { + if (!outagesUs.length || endUs <= startUs) return 0; + const clamped = []; + for (const [s, e] of outagesUs) { + const a = Math.max(s, startUs); + const b = Math.min(e, endUs); + if (b > a) clamped.push([a, b]); + } + if (!clamped.length) return 0; + clamped.sort((x, y) => x[0] - y[0]); + let total = 0; + let curS = clamped[0][0]; + let curE = clamped[0][1]; + for (let i = 1; i < clamped.length; i += 1) { + const [s, e] = clamped[i]; + if (s <= curE) { + if (e > curE) curE = e; + } else { + total += curE - curS; + curS = s; + curE = e; + } + } + total += curE - curS; + return total; +} + +class MinHeap { + constructor() { + this.items = []; + } + + get size() { + return this.items.length; + } + + peek() { + return this.items.length ? this.items[0] : null; + } + + push(item) { + const arr = this.items; + arr.push(item); + let i = arr.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (compareEvent(arr[i], arr[parent]) >= 0) break; + const tmp = arr[parent]; + arr[parent] = arr[i]; + arr[i] = tmp; + i = parent; + } + } + + pop() { + const arr = this.items; + if (!arr.length) return null; + const top = arr[0]; + const last = arr.pop(); + if (arr.length) { + arr[0] = last; + let i = 0; + const len = arr.length; + while (true) { + const left = (i << 1) + 1; + const right = left + 1; + let smallest = i; + if (left < len && compareEvent(arr[left], arr[smallest]) < 0) smallest = left; + if (right < len && compareEvent(arr[right], arr[smallest]) < 0) smallest = right; + if (smallest === i) break; + const tmp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = tmp; + i = smallest; + } + } + return top; + } +} + +function compareEvent(a, b) { + if (a.timeUs !== b.timeUs) return a.timeUs - b.timeUs; + return a.seq - b.seq; +} + +/** + * Unidirectional virtual-clock link with: + * - Outage windows + * - Token-bucket policer (drops bursts above bucket rate without queue delay) + * - Shared bottleneck serialization rate + shallow tail-drop byte queue + * - Independent time-based burst loss calendar + random loss + * - Bounded FIFO jitter, explicit reordering, duplication, and periodic Wi-Fi stalls + */ +export class SimLink { + constructor(profile, seed) { + this.bitsPerSecond = profile.bitsPerSecond ?? 0; + this.propagationDelayUs = Math.round((profile.propagationDelayMs ?? 0) * 1000); + this.jitterUs = Math.round((profile.jitterMs ?? 0) * 1000); + this.jitterFifo = profile.jitterFifo !== false; + this.lossProb = profile.lossProb ?? 0; + this.burstEveryUs = Math.round((profile.burstEveryMs ?? 0) * 1000); + this.burstLenUs = Math.round((profile.burstLenMs ?? 0) * 1000); + this.burstLossProb = profile.burstLossProb ?? 0; + this.reorderProb = profile.reorderProb ?? 0; + this.reorderExtraUs = Math.round((profile.reorderExtraMs ?? 0) * 1000); + this.dupProb = profile.dupProb ?? 0; + this.queueBytes = profile.queueBytes ?? 0; + this.bucketBytesPerSec = profile.bucketBytesPerSec ?? 0; + this.bucketDepthBytes = profile.bucketDepthBytes ?? 0; + this.outagesUs = (profile.outages ?? []).map(([s, e]) => [Math.round(s * 1000), Math.round(e * 1000)]); + this.stallEveryUs = Math.round((profile.stallEveryMs ?? 0) * 1000); + this.stallLenUs = Math.round((profile.stallLenMs ?? 0) * 1000); + this.stallOffsetUs = Math.round((profile.stallOffsetMs ?? 0) * 1000); + + this.packetRng = new SplitMix64(BigInt(seed) ^ 0x243f6a8885a308d3n); + this.burstRng = new SplitMix64(BigInt(seed) ^ 0x13198a2e03707344n); + + this.nextFreeUs = 0; + this.lastFifoArrivalUs = 0; + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + this.bucketUpdatedUs = 0; + + this.burstStartUs = Infinity; + this.burstEndUs = 0; + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + this._scheduleBurst(0); + } + + this.stats = { + txPackets: 0, + txBytes: 0, + outageDrops: 0, + policerDrops: 0, + queueDrops: 0, + lossDrops: 0, + deliveredPackets: 0, + duplicatedPackets: 0, + reorderedPackets: 0, + }; + } + + _scheduleBurst(afterUs) { + const gap = 1 + this.burstRng.below(2 * this.burstEveryUs); + const length = 1 + this.burstRng.below(2 * this.burstLenUs); + this.burstStartUs = afterUs + gap; + this.burstEndUs = this.burstStartUs + length; + } + + effectiveBottleneckBytesPerSec() { + const linkBps = this.bitsPerSecond > 0 ? this.bitsPerSecond / 8 : Infinity; + const bucketBps = this.bucketBytesPerSec > 0 ? this.bucketBytesPerSec : Infinity; + return Math.min(linkBps, bucketBps); + } + + transmit(nowUs, sizeBytes) { + this.stats.txPackets += 1; + this.stats.txBytes += sizeBytes; + + // 1. Outage windows + for (let i = 0; i < this.outagesUs.length; i += 1) { + const [s, e] = this.outagesUs[i]; + if (nowUs >= s && nowUs < e) { + this.stats.outageDrops += 1; + return []; + } + } + + // 2. Token-bucket policer (drops excess bursts without queue delay) + if (this.bucketBytesPerSec > 0) { + const dtUs = nowUs - this.bucketUpdatedUs; + if (dtUs > 0) { + if (dtUs * this.bucketBytesPerSec > 1e14) { + this.tokens = this.bucketDepthBytes; + this.bucketFracUs = 0; + } else { + const numer = dtUs * this.bucketBytesPerSec + this.bucketFracUs; + const add = Math.floor(numer / 1_000_000); + this.bucketFracUs = numer - add * 1_000_000; + this.tokens = Math.min(this.bucketDepthBytes, this.tokens + add); + if (this.tokens === this.bucketDepthBytes) this.bucketFracUs = 0; + } + this.bucketUpdatedUs = nowUs; + } + if (this.tokens < sizeBytes) { + this.stats.policerDrops += 1; + return []; + } + this.tokens -= sizeBytes; + } + + // 3. Shared bottleneck queue & serialization + let departureUs = nowUs; + if (this.bitsPerSecond > 0) { + const backlogUs = Math.max(0, this.nextFreeUs - nowUs); + if (this.queueBytes > 0) { + const backlogBytes = (backlogUs * this.bitsPerSecond) / 8_000_000; + if (backlogBytes + sizeBytes > this.queueBytes) { + this.stats.queueDrops += 1; + return []; + } + } + const txUs = Math.max(1, Math.ceil((sizeBytes * 8_000_000) / this.bitsPerSecond)); + const startUs = Math.max(nowUs, this.nextFreeUs); + departureUs = startUs + txUs; + this.nextFreeUs = departureUs; + } + + // 4. Independent time-based burst loss + random loss (after consuming bottleneck airtime) + if (this.burstEveryUs > 0 && this.burstLenUs > 0) { + while (this.burstEndUs <= nowUs) { + this._scheduleBurst(this.burstEndUs); + } + } + const inBurst = nowUs >= this.burstStartUs && nowUs < this.burstEndUs; + const effectiveLoss = inBurst ? this.burstLossProb : this.lossProb; + if (effectiveLoss > 0 && this.packetRng.chance(effectiveLoss)) { + this.stats.lossDrops += 1; + return []; + } + + // 5. Propagation + bounded FIFO jitter + const jitter = this.jitterUs > 0 ? this.packetRng.below(this.jitterUs + 1) : 0; + let arrivalUs = departureUs + this.propagationDelayUs + jitter; + if (this.jitterFifo) { + if (arrivalUs < this.lastFifoArrivalUs) arrivalUs = this.lastFifoArrivalUs; + this.lastFifoArrivalUs = arrivalUs; + } + + // 6. Explicit reordering + if (this.reorderProb > 0 && this.packetRng.chance(this.reorderProb)) { + this.stats.reorderedPackets += 1; + arrivalUs += 1 + this.packetRng.below(Math.max(1, this.reorderExtraUs)); + } + + // 7. Periodic Wi-Fi stalls (holds arrivals until end of stall without dropping) + if (this.stallEveryUs > 0 && this.stallLenUs > 0) { + const shifted = arrivalUs + this.stallOffsetUs; + const phase = shifted % this.stallEveryUs; + if (phase < this.stallLenUs) { + arrivalUs += this.stallLenUs - phase; + } + } + + // 8. Duplication + if (this.dupProb > 0 && this.packetRng.chance(this.dupProb)) { + this.stats.duplicatedPackets += 1; + this.stats.deliveredPackets += 2; + const dupExtra = 1 + this.packetRng.below(Math.max(1, this.propagationDelayUs)); + return [arrivalUs, arrivalUs + dupExtra]; + } + + this.stats.deliveredPackets += 1; + return [arrivalUs]; + } +} + +/** + * Generates deterministic messages with high-entropy incompressible SplitMix64 payloads. + */ +export function generateProfileMessages(spec) { + const rng = new SplitMix64(BigInt(spec.seed) ^ 0x9e3779b97f4a7c15n); + const messages = []; + let seqId = 1; + + // Bulk waves: enqueued across configured waves so all bulk peers start simultaneously + // and remain continuously backlogged without artificial idle gaps. + for (const peerSpec of spec.bulkPeers) { + const peerId = peerSpec.peerId; + const streamId = peerSpec.streamId ?? 'bulk-0'; + const sizes = peerSpec.messageSizes; + const waveTimesMs = peerSpec.waveTimesMs ?? [0]; + for (let i = 0; i < sizes.length; i += 1) { + const waveIdx = Math.min(waveTimesMs.length - 1, Math.floor((i * waveTimesMs.length) / sizes.length)); + const enqueuedMs = waveTimesMs[waveIdx]; + const payload = rng.fillBytes(sizes[i]); + messages.push({ + peerId, + streamId, + msgId: `b-${peerId}-${seqId++}`, + priority: 'bulk', + payload, + enqueuedMs, + deadlineMs: peerSpec.deadlineMs ?? 60_000, + }); + } + } + + // Interactive messages across configured active windows + const windows = spec.interactive.windows; // [[startMs, endMs], ...] + const totalCount = spec.interactive.count; + const minBytes = spec.interactive.minBytes ?? 120; + const maxBytes = spec.interactive.maxBytes ?? 900; + const deadlineMs = spec.interactive.deadlineMs ?? 18_000; + const iPeers = spec.interactive.peers; + + let totalWindowMs = 0; + for (const [s, e] of windows) totalWindowMs += Math.max(0, e - s); + + for (let i = 0; i < totalCount; i += 1) { + const frac = totalCount === 1 ? 0.5 : i / (totalCount - 1); + let targetOffset = frac * totalWindowMs; + let enqueuedMs = windows[0][0]; + for (const [s, e] of windows) { + const span = Math.max(0, e - s); + if (targetOffset <= span || s === windows[windows.length - 1][0]) { + enqueuedMs = s + Math.min(span, targetOffset); + break; + } + targetOffset -= span; + } + // Small deterministic micro-jitter within +-4ms while staying inside window + const jitterMs = (rng.below(8001) - 4000) / 1000; + enqueuedMs = Math.max(0, Math.round((enqueuedMs + jitterMs) * 1000) / 1000); + // Keep out of blackout windows if any + for (const [os, oe] of spec.downlink.outages ?? []) { + if (enqueuedMs >= os - 150 && enqueuedMs < oe + 50) { + enqueuedMs = oe + 50 + (i % 7) * 5; + } + } + + const peerId = iPeers[i % iPeers.length]; + const streamId = `ctrl-${(i % 2)}`; + // Real profiles list measured message sizes; synthetic ones give a uniform range. + const realSizes = spec.interactive.sizes; + const size = Array.isArray(realSizes) && realSizes.length > 0 + ? realSizes[i % realSizes.length] + : minBytes + rng.below(maxBytes - minBytes + 1); + const payload = rng.fillBytes(size); + messages.push({ + peerId, + streamId, + msgId: `i-${peerId}-${seqId++}`, + priority: 'interactive', + payload, + enqueuedMs, + deadlineMs, + }); + } + + messages.sort((a, b) => a.enqueuedMs - b.enqueuedMs || a.msgId.localeCompare(b.msgId)); + return messages; +} + +/** + * Runs a complete virtual-clock discrete-event simulation for one profile. + */ +export function runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + maxSimMs = 180_000, + maxSteps = 2_500_000, +}) { + const maxPacketBytes = profile.maxPacketBytes ?? MAX_PACKET_BYTES; + const peers = [...profile.peers]; + const peerSet = new Set(peers); + const seed = BigInt(profile.seed ?? 1); + + const downlink = new SimLink(profile.downlink, seed ^ 0xa5a5a5a5a5a5a5a5n); + const uplink = new SimLink(profile.uplink ?? profile.downlink, seed ^ 0x5a5a5a5a5a5a5a5an); + + const sender = createRelaySender({ maxPacketBytes, peers: [...peers] }); + const receivers = new Map(); + const receiverNextWakeUs = new Map(); + for (const peerId of peers) { + receivers.set(peerId, createPeerReceiver(peerId, { maxPacketBytes })); + receiverNextWakeUs.set(peerId, Infinity); + } + + const heap = new MinHeap(); + let eventSeq = 0; + const pushEvent = (timeUs, type, data) => { + heap.push({ timeUs, seq: eventSeq++, type, data }); + }; + + // Pre-compute SHA-256 hashes & expected FIFO delivery queues per (peerId, streamId) + const expectedByStream = new Map(); + const bulkPeerTargetBytes = new Map(); + const bulkPeerDeliveredBytes = new Map(); + const bulkPeerStartUs = new Map(); + const bulkPeerFinishUs = new Map(); + const bulkPeerMidpointBytes = new Map(); + + let totalUniquePayloadBytes = 0; + let totalBulkPayloadBytes = 0; + let totalInteractivePayloadBytes = 0; + let bulkStartUs = Infinity; + let bulkFinishUs = 0; + let interactiveCount = 0; + + for (const msg of messages) { + const hash = sha256Hex(msg.payload); + const enqueuedUs = Math.round(msg.enqueuedMs * 1000); + const streamKey = `${msg.peerId}\u0000${msg.streamId}`; + let q = expectedByStream.get(streamKey); + if (!q) { + q = { head: 0, items: [] }; + expectedByStream.set(streamKey, q); + } + q.items.push({ + msgId: msg.msgId, + sha256: hash, + byteLength: msg.payload.byteLength, + priority: msg.priority, + enqueuedUs, + deadlineMs: msg.deadlineMs, + }); + + totalUniquePayloadBytes += msg.payload.byteLength; + if (msg.priority === 'bulk') { + totalBulkPayloadBytes += msg.payload.byteLength; + if (enqueuedUs < bulkStartUs) bulkStartUs = enqueuedUs; + bulkPeerTargetBytes.set(msg.peerId, (bulkPeerTargetBytes.get(msg.peerId) ?? 0) + msg.payload.byteLength); + if (!bulkPeerStartUs.has(msg.peerId) || enqueuedUs < bulkPeerStartUs.get(msg.peerId)) { + bulkPeerStartUs.set(msg.peerId, enqueuedUs); + } + } else { + totalInteractivePayloadBytes += msg.payload.byteLength; + interactiveCount += 1; + } + + pushEvent(enqueuedUs, 'ENQUEUE', { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + priority: msg.priority, + payload: msg.payload, + deadlineMs: msg.deadlineMs, + }); + } + + const bulkPeers = [...bulkPeerTargetBytes.keys()].sort(); + for (const p of bulkPeers) bulkPeerDeliveredBytes.set(p, 0); + + const violations = []; + let packetBoundsOk = true; + let exactDeliveryOk = true; + let deliveredCount = 0; + let totalDeliveredBulkBytes = 0; + let midpointRecorded = false; + const interactiveLatenciesMs = []; + let interactiveDeadlineMisses = 0; + + const recordViolation = (msg) => { + if (violations.length < 20) violations.push(msg); + }; + + const handleDelivered = (peerId, nowUs, delivered) => { + if (!Array.isArray(delivered)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: delivered is not an array`); + return; + } + for (const item of delivered) { + if (!item || typeof item.streamId !== 'string' || typeof item.msgId !== 'string' || !(item.payload instanceof Uint8Array)) { + exactDeliveryOk = false; + recordViolation(`${peerId}: malformed delivered item`); + continue; + } + const streamKey = `${peerId}\u0000${item.streamId}`; + const q = expectedByStream.get(streamKey); + if (!q || q.head >= q.items.length) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: unexpected extra delivery ${item.msgId}`); + continue; + } + const expected = q.items[q.head]; + if (item.msgId !== expected.msgId) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}: FIFO order mismatch (got ${item.msgId}, expected ${expected.msgId})`); + continue; + } + if (item.payload.byteLength !== expected.byteLength || sha256Hex(item.payload) !== expected.sha256) { + exactDeliveryOk = false; + recordViolation(`${peerId}/${item.streamId}/${item.msgId}: SHA-256 payload corruption`); + continue; + } + q.head += 1; + deliveredCount += 1; + const latencyMs = (nowUs - expected.enqueuedUs) / 1000; + if (expected.priority === 'interactive') { + interactiveLatenciesMs.push(latencyMs); + if (latencyMs > expected.deadlineMs) { + interactiveDeadlineMisses += 1; + recordViolation(`${peerId}/${item.msgId}: interactive deadline missed (${latencyMs.toFixed(1)}ms > ${expected.deadlineMs}ms)`); + } + } else { + totalDeliveredBulkBytes += expected.byteLength; + const prev = bulkPeerDeliveredBytes.get(peerId) ?? 0; + bulkPeerDeliveredBytes.set(peerId, prev + expected.byteLength); + if (nowUs > bulkFinishUs) bulkFinishUs = nowUs; + if (nowUs > (bulkPeerFinishUs.get(peerId) ?? 0)) bulkPeerFinishUs.set(peerId, nowUs); + if (!midpointRecorded && totalBulkPayloadBytes > 0 && totalDeliveredBulkBytes >= totalBulkPayloadBytes * 0.5) { + midpointRecorded = true; + for (const bp of bulkPeers) { + bulkPeerMidpointBytes.set(bp, bulkPeerDeliveredBytes.get(bp) ?? 0); + } + } + } + } + }; + + const transmitAckPackets = (peerId, nowUs, ackPackets) => { + if (!Array.isArray(ackPackets)) { + packetBoundsOk = false; + recordViolation(`${peerId}: ackPackets is not an array`); + return; + } + for (const pkt of ackPackets) { + if (!(pkt instanceof Uint8Array) || pkt.byteLength === 0 || pkt.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`${peerId}: invalid ACK packet size ${pkt?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt); + const arrivals = uplink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'ACK_ARRIVAL', { peerId, bytes: copy }); + } + } + }; + + const maxSimUs = Math.round(maxSimMs * 1000); + let nowUs = 0; + let senderNextWakeUs = Infinity; + let steps = 0; + + while (deliveredCount < messages.length) { + steps += 1; + if (steps > maxSteps) { + exactDeliveryOk = false; + recordViolation(`simulation step limit (${maxSteps}) exceeded at ${(nowUs / 1000).toFixed(1)}ms`); + break; + } + if (nowUs > maxSimUs) { + exactDeliveryOk = false; + recordViolation(`simulation time limit (${maxSimMs}ms) exceeded; delivered ${deliveredCount}/${messages.length}`); + break; + } + + const nowMs = nowUs / 1000; + let senderActive = senderNextWakeUs <= nowUs; + const touchedReceivers = new Set(); + + while (heap.size > 0 && heap.peek().timeUs <= nowUs) { + const ev = heap.pop(); + if (ev.type === 'ENQUEUE') { + const m = ev.data; + sender.enqueue(nowMs, { + peerId: m.peerId, + streamId: m.streamId, + msgId: m.msgId, + priority: m.priority, + payload: new Uint8Array(m.payload), + deadlineMs: m.deadlineMs, + }); + senderActive = true; + } else if (ev.type === 'DATA_ARRIVAL') { + const { peerId, bytes } = ev.data; + const recv = receivers.get(peerId); + const res = recv.onDataPacket(nowMs, new Uint8Array(bytes)); + if (res && res.delivered && res.delivered.length) { + handleDelivered(peerId, nowUs, res.delivered); + } + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + touchedReceivers.add(peerId); + } else if (ev.type === 'ACK_ARRIVAL') { + const { peerId, bytes } = ev.data; + sender.onAckPacket(nowMs, peerId, new Uint8Array(bytes)); + senderActive = true; + } + } + + // Poll receivers that either received data or reached their wake time + for (const peerId of peers) { + const wakeUs = receiverNextWakeUs.get(peerId); + if (touchedReceivers.has(peerId) || wakeUs <= nowUs) { + const res = receivers.get(peerId).pollControl(nowMs); + if (res && res.ackPackets && res.ackPackets.length) { + transmitAckPackets(peerId, nowUs, res.ackPackets); + } + const nw = res?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + receiverNextWakeUs.set(peerId, Math.max(nowUs + 10, Math.ceil(nw * 1000))); + } else { + receiverNextWakeUs.set(peerId, Infinity); + } + } + } + + if (deliveredCount >= messages.length) break; + + // Poll sender TX + if (senderActive) { + const txRes = sender.pollTx(nowMs); + const packets = txRes?.packets ?? []; + for (const pkt of packets) { + if (!pkt || !peerSet.has(pkt.peerId) || !(pkt.bytes instanceof Uint8Array) || pkt.bytes.byteLength === 0 || pkt.bytes.byteLength > maxPacketBytes) { + packetBoundsOk = false; + recordViolation(`sender: invalid packet for peer=${pkt?.peerId} size=${pkt?.bytes?.byteLength}`); + continue; + } + const copy = new Uint8Array(pkt.bytes); + const arrivals = downlink.transmit(nowUs, copy.byteLength); + for (const atUs of arrivals) { + pushEvent(atUs, 'DATA_ARRIVAL', { peerId: pkt.peerId, bytes: copy }); + } + } + const nw = txRes?.nextWakeMs; + if (typeof nw === 'number' && Number.isFinite(nw)) { + senderNextWakeUs = Math.max(nowUs + 10, Math.ceil(nw * 1000)); + } else { + senderNextWakeUs = Infinity; + } + } + + if (deliveredCount >= messages.length) break; + + let nextUs = heap.size > 0 ? heap.peek().timeUs : Infinity; + if (senderNextWakeUs < nextUs) nextUs = senderNextWakeUs; + for (const peerId of peers) { + const rw = receiverNextWakeUs.get(peerId); + if (rw < nextUs) nextUs = rw; + } + if (!Number.isFinite(nextUs)) { + exactDeliveryOk = false; + recordViolation(`simulation stalled with no pending events; delivered ${deliveredCount}/${messages.length}`); + break; + } + nowUs = Math.max(nowUs + 1, nextUs); + } + + if (deliveredCount !== messages.length) { + exactDeliveryOk = false; + } + + const downlinkWireBytes = downlink.stats.txBytes; + const uplinkWireBytes = uplink.stats.txBytes; + const totalWireBytes = downlinkWireBytes + uplinkWireBytes; + const wireOverheadPct = totalUniquePayloadBytes > 0 + ? ((totalWireBytes - totalUniquePayloadBytes) / totalUniquePayloadBytes) * 100 + : 0; + + const effBottleneckBytesPerSec = downlink.effectiveBottleneckBytesPerSec(); + let bulkActiveDurationMs = 0; + let bulkGoodputBps = 0; + let bulkGoodputPct = 100; + if (totalBulkPayloadBytes > 0 && bulkFinishUs > bulkStartUs) { + const outageUs = computeOutageOverlapUs(downlink.outagesUs, bulkStartUs, bulkFinishUs); + const activeUs = Math.max(1000, bulkFinishUs - bulkStartUs - outageUs - downlink.propagationDelayUs); + bulkActiveDurationMs = activeUs / 1000; + const goodputBytesPerSec = totalBulkPayloadBytes / (activeUs / 1_000_000); + bulkGoodputBps = goodputBytesPerSec * 8; + bulkGoodputPct = Number.isFinite(effBottleneckBytesPerSec) && effBottleneckBytesPerSec > 0 + ? Math.min(100, (goodputBytesPerSec / effBottleneckBytesPerSec) * 100) + : 100; + } else if (totalBulkPayloadBytes > 0) { + bulkGoodputPct = 0; + } + + // Jain's Fairness Index across concurrent bulk peers (min of completion throughput & midpoint share) + const perPeerBulk = {}; + const completionNormalized = []; + const midpointNormalized = []; + for (const bp of bulkPeers) { + const target = bulkPeerTargetBytes.get(bp) ?? 0; + const startUs = bulkPeerStartUs.get(bp) ?? 0; + const finUs = bulkPeerFinishUs.get(bp) ?? nowUs; + const midBytes = bulkPeerMidpointBytes.get(bp) ?? 0; + const outageUs = computeOutageOverlapUs(downlink.outagesUs, startUs, finUs); + const activeUs = Math.max(1000, finUs - startUs - outageUs); + const rateBytesPerSec = target / (activeUs / 1_000_000); + completionNormalized.push(rateBytesPerSec); + midpointNormalized.push(target > 0 ? midBytes / target : 1); + perPeerBulk[bp] = { + bytes: target, + startMs: startUs / 1000, + finishMs: finUs / 1000, + midpointBytes: midBytes, + throughputBps: rateBytesPerSec * 8, + }; + } + const jainsFairnessCompletion = jainsFairnessIndex(completionNormalized); + const jainsFairnessMidpoint = midpointRecorded ? jainsFairnessIndex(midpointNormalized) : 0; + const jainsFairness = bulkPeers.length <= 1 + ? 1 + : Math.min(jainsFairnessCompletion, jainsFairnessMidpoint); + + const interactiveP99Ms = percentile(interactiveLatenciesMs, 99); + const interactiveP50Ms = percentile(interactiveLatenciesMs, 50); + const interactiveMaxMs = interactiveLatenciesMs.length ? Math.max(...interactiveLatenciesMs) : 0; + const interactiveDeadlineOk = interactiveDeadlineMisses === 0 && interactiveLatenciesMs.length === interactiveCount; + + return { + name: profile.name, + ok: exactDeliveryOk && packetBoundsOk && interactiveDeadlineOk && violations.length === 0, + exactDeliveryOk, + packetBoundsOk, + interactiveDeadlineOk, + deliveredCount, + totalMessages: messages.length, + interactiveCount, + interactiveP99Ms, + interactiveP50Ms, + interactiveMaxMs, + interactiveDeadlineMisses, + totalWireBytes, + downlinkWireBytes, + uplinkWireBytes, + totalUniquePayloadBytes, + totalBulkPayloadBytes, + totalInteractivePayloadBytes, + wireOverheadPct, + bulkGoodputPct, + bulkGoodputBps, + effectiveBottleneckBps: effBottleneckBytesPerSec * 8, + bulkStartMs: bulkStartUs === Infinity ? 0 : bulkStartUs / 1000, + bulkFinishMs: bulkFinishUs / 1000, + bulkActiveDurationMs, + finishMs: nowUs / 1000, + jainsFairness, + jainsFairnessCompletion, + jainsFairnessMidpoint, + perPeerBulk, + downlinkStats: { ...downlink.stats }, + uplinkStats: { ...uplink.stats }, + steps, + violations, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/src/congestion.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/src/congestion.mjs new file mode 100644 index 0000000..a1a13e0 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/src/congestion.mjs @@ -0,0 +1,266 @@ +/** + * Reference congestion control & reliability: + * - Shared-link AIMD (wireless-tolerant high-speed AIMD) congestion window across all peers + * - Delay cap: stops growing (and drains) once the latest RTT says more than 4 packets sit in + * the bottleneck queue, so interactive packets are not queued behind or tail-dropped by bulk + * - Jacobson/Karels SRTT / RTTVAR / RTO estimation + * - Selective ACK (SACK ranges) + 3-dup-SACK fast retransmit + * - Outage mode lives in transport.mjs (probe instead of retransmitting into a dead link) + * + * Intentionally leaves headroom: + * - Unpaced window bursts (no fine-grained inter-packet pacing) + * - No BBR / delivery-rate / policer-aware rate control + * - No proactive FEC on interactive packets + * - No RACK / Tail-Loss Probe (TLP); outage detection waits for 3 RTTs of silence + */ + +export const MSS = 1200; +const INITIAL_CWND = 20 * MSS; +const MIN_CWND = 10 * MSS; +const MAX_CWND = 240 * MSS; +const INITIAL_SSTHRESH = 64 * MSS; +const INTERACTIVE_CWND_RESERVE = 6 * MSS; +const DUP_SACK_THRESHOLD = 3; +const MIN_RTO_MS = 160; +const QUEUE_TARGET_BYTES = 4 * MSS; +const QUEUE_JITTER_ALLOWANCE = 0; +const MAX_RTO_MS = 1800; + +export class SharedAimdController { + constructor() { + this.cwnd = INITIAL_CWND; + this.ssthresh = INITIAL_SSTHRESH; + this.inflightBytes = 0; + + this.srttMs = null; + this.rttVarMs = 50; + this.minRttMs = Infinity; + this.lastRttMs = null; + this.lastLossReductionMs = -Infinity; + this.lastBurstLossCount = 0; + } + + onRttSample(sampleMs) { + if (!Number.isFinite(sampleMs) || sampleMs <= 0) return; + const clamped = Math.min(4000, sampleMs); + this.lastRttMs = clamped; + if (clamped < this.minRttMs) this.minRttMs = clamped; + if (this.srttMs === null) { + this.srttMs = clamped; + this.rttVarMs = clamped / 2; + } else { + this.rttVarMs = 0.75 * this.rttVarMs + 0.25 * Math.abs(this.srttMs - clamped); + this.srttMs = 0.875 * this.srttMs + 0.125 * clamped; + } + } + + rtoMs(retries = 0) { + const base = this.srttMs === null + ? 350 + : Math.max(MIN_RTO_MS, Math.min(MAX_RTO_MS, this.srttMs + Math.max(25, 4 * this.rttVarMs))); + const backoff = Math.min(4, 2 ** Math.min(3, retries)); + return Math.min(MAX_RTO_MS, base * backoff); + } + + canSend(bytes, isInteractive) { + const limit = isInteractive ? this.cwnd + INTERACTIVE_CWND_RESERVE : this.cwnd; + return this.inflightBytes + bytes <= limit || (isInteractive && this.inflightBytes < INTERACTIVE_CWND_RESERVE); + } + + onPacketSent(bytes) { + this.inflightBytes += bytes; + } + + onPacketFreed(bytes) { + this.inflightBytes = Math.max(0, this.inflightBytes - bytes); + } + + onBytesAcked(ackedBytes) { + if (ackedBytes <= 0) return; + // Delay cap: estimate bytes sitting in the bottleneck queue from the latest RTT above the + // minimum; past QUEUE_TARGET stop growing and drain slowly, so interactive packets never wait + // behind (or get tail-dropped by) a full bulk queue. + if (this.lastRttMs !== null && Number.isFinite(this.minRttMs)) { + const queued = (this.cwnd * Math.max(0, this.lastRttMs - this.minRttMs - QUEUE_JITTER_ALLOWANCE * this.rttVarMs)) / this.lastRttMs; + if (queued > QUEUE_TARGET_BYTES) { + this.cwnd = Math.max(MIN_CWND, this.cwnd - (MSS * ackedBytes) / Math.max(MSS, this.cwnd)); + return; + } + } + if (this.cwnd < this.ssthresh) { + this.cwnd = Math.min(MAX_CWND, this.cwnd + ackedBytes); + } else { + // Standard AIMD growth (+3 MSS per RTT) + this.cwnd = Math.min(MAX_CWND, this.cwnd + (3 * MSS * ackedBytes) / Math.max(MSS, this.cwnd)); + } + } + + onCongestionEvent(nowMs, isTimeout, lostInEvent = 1) { + const minInterval = this.srttMs !== null ? Math.max(60, this.srttMs) : 150; + if (nowMs - this.lastLossReductionMs < minInterval) return; + this.lastLossReductionMs = nowMs; + this.lastBurstLossCount = lostInEvent; + const beta = isTimeout ? 0.6 : (lostInEvent >= 3 ? 0.7 : 0.8); + this.ssthresh = Math.max(MIN_CWND, Math.floor(this.cwnd * beta)); + this.cwnd = this.ssthresh; + } +} + +export class PeerSackTracker { + constructor(peerId, cc) { + this.peerId = peerId; + this.cc = cc; + this.nextSeq = 1; + this.sndUna = 1; + this.highestSacked = 0; + this.unacked = new Map(); + this.retransmitQueueInteractive = []; + this.retransmitQueueBulk = []; + } + + allocateSeq() { + const seq = this.nextSeq; + this.nextSeq += 1; + return seq; + } + + recordSent(seq, bytes, nowMs, isInteractive) { + const size = bytes.byteLength; + this.unacked.set(seq, { + seq, + bytes, + size, + isInteractive, + sentMs: nowMs, + firstSentMs: nowMs, + retries: 0, + retransmitEpochSeq: seq, + inFlight: true, + needsRetransmit: false, + }); + this.cc.onPacketSent(size); + } + + _queueRetransmit(entry) { + if (entry.needsRetransmit) return; + entry.needsRetransmit = true; + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + if (entry.isInteractive) { + this.retransmitQueueInteractive.push(entry.seq); + } else { + this.retransmitQueueBulk.push(entry.seq); + } + } + + onSackAck(nowMs, cumAckSeq, echoSeq, sackRanges) { + let newlyAckedBytes = 0; + let lossCount = 0; + + if (echoSeq > 0) { + const echoed = this.unacked.get(echoSeq); + if (echoed && echoed.retries === 0) { + this.cc.onRttSample(nowMs - echoed.firstSentMs); + } + } + + if (cumAckSeq > this.sndUna) { + for (let s = this.sndUna; s < cumAckSeq; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + this.unacked.delete(s); + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + newlyAckedBytes += entry.size; + } + this.sndUna = cumAckSeq; + } + + for (const [start, end] of sackRanges) { + if (end - 1 > this.highestSacked) this.highestSacked = end - 1; + for (let s = Math.max(start, this.sndUna); s < end; s += 1) { + const entry = this.unacked.get(s); + if (!entry) continue; + this.unacked.delete(s); + if (entry.inFlight) { + entry.inFlight = false; + this.cc.onPacketFreed(entry.size); + } + newlyAckedBytes += entry.size; + } + } + + if (newlyAckedBytes > 0) { + this.cc.onBytesAcked(newlyAckedBytes); + } + + if (this.highestSacked >= this.sndUna + DUP_SACK_THRESHOLD) { + const thresholdSeq = this.highestSacked - DUP_SACK_THRESHOLD; + for (const entry of this.unacked.values()) { + if (entry.retransmitEpochSeq <= thresholdSeq && entry.inFlight && !entry.needsRetransmit) { + this._queueRetransmit(entry); + lossCount += 1; + } + } + } + + if (lossCount > 0) { + this.cc.onCongestionEvent(nowMs, false, lossCount); + } + } + + checkTimeouts(nowMs) { + let timeoutCount = 0; + for (const entry of this.unacked.values()) { + if (!entry.inFlight || entry.needsRetransmit) continue; + const rto = this.cc.rtoMs(entry.retries); + if (nowMs - entry.sentMs >= rto) { + this._queueRetransmit(entry); + timeoutCount += 1; + } + } + if (timeoutCount > 0) { + this.cc.onCongestionEvent(nowMs, true, timeoutCount); + } + } + + popRetransmit(nowMs, interactiveOnly) { + const queue = interactiveOnly ? this.retransmitQueueInteractive : this.retransmitQueueBulk; + while (queue.length > 0) { + const seq = queue.shift(); + const entry = this.unacked.get(seq); + if (!entry || !entry.needsRetransmit) continue; + if (!this.cc.canSend(entry.size, entry.isInteractive)) { + queue.unshift(seq); + return null; + } + entry.needsRetransmit = false; + entry.inFlight = true; + entry.retries += 1; + entry.sentMs = nowMs; + entry.retransmitEpochSeq = this.nextSeq; + this.cc.onPacketSent(entry.size); + return entry.bytes; + } + return null; + } + + hasPendingRetransmit(interactiveOnly) { + const q = interactiveOnly ? this.retransmitQueueInteractive : this.retransmitQueueBulk; + return q.length > 0; + } + + nextTimeoutMs() { + let earliest = Infinity; + for (const entry of this.unacked.values()) { + if (!entry.inFlight || entry.needsRetransmit) continue; + const t = entry.sentMs + this.cc.rtoMs(entry.retries); + if (t < earliest) earliest = t; + } + return earliest; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/src/scheduler.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/src/scheduler.mjs new file mode 100644 index 0000000..b5f5921 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/src/scheduler.mjs @@ -0,0 +1,170 @@ +/** + * Reference relay scheduler: + * - Strict priority preemption for interactive messages across all peers + * - Byte-weighted Deficit Round-Robin (DRR) across bulk peers for fair sharing + * - Independent per-(peerId, streamId) delivery sequence numbers + */ + +const DRR_QUANTUM_BYTES = 2400; + +export class RelayScheduler { + constructor(peers) { + this.peers = []; + this.interactiveQueue = []; + this.bulkPeers = new Map(); // peerId -> { queue: [], deficit: number } + this.activeBulkList = []; + this.streamMsgSeq = new Map(); + for (const peerId of peers) { + this._ensurePeer(peerId); + } + } + + _ensurePeer(peerId) { + if (!this.bulkPeers.has(peerId)) { + this.peers.push(peerId); + this.bulkPeers.set(peerId, { queue: [], deficit: 0, active: false }); + } + return this.bulkPeers.get(peerId); + } + + _nextStreamSeq(peerId, streamId) { + const key = `${peerId}\u0000${streamId}`; + const seq = (this.streamMsgSeq.get(key) ?? 0) + 1; + this.streamMsgSeq.set(key, seq); + return seq; + } + + enqueue(msg, chunkSize) { + const state = this._ensurePeer(msg.peerId); + const totalBytes = msg.payload.byteLength; + const totalSegments = Math.max(1, Math.ceil(totalBytes / chunkSize)); + const entry = { + peerId: msg.peerId, + streamId: msg.streamId, + msgId: msg.msgId, + streamSeq: this._nextStreamSeq(msg.peerId, msg.streamId), + priority: msg.priority, + payload: msg.payload, + chunkSize, + totalBytes, + totalSegments, + nextSegment: 0, + }; + if (msg.priority === 'interactive') { + this.interactiveQueue.push(entry); + } else { + state.queue.push(entry); + if (!state.active) { + state.active = true; + state.deficit = 0; + this.activeBulkList.push(msg.peerId); + } + } + } + + hasInteractive() { + return this.interactiveQueue.length > 0; + } + + hasBulk() { + return this.activeBulkList.length > 0; + } + + peekNextInteractiveSize() { + if (!this.interactiveQueue.length) return 0; + const head = this.interactiveQueue[0]; + const start = head.nextSegment * head.chunkSize; + return Math.min(head.chunkSize, head.totalBytes - start); + } + + popInteractiveSegment() { + if (!this.interactiveQueue.length) return null; + return this._popFromQueue(this.interactiveQueue, 0); + } + + /** + * Byte-weighted Deficit Round-Robin (DRR) across active bulk peers. + */ + popBulkSegment(canSendBytes) { + let rounds = this.activeBulkList.length; + if (rounds === 0) return null; + + // Allow up to 2 passes so peers receive a fresh quantum if all deficits are low + for (let pass = 0; pass < 2; pass += 1) { + let checked = 0; + const count = this.activeBulkList.length; + while (checked < count && this.activeBulkList.length > 0) { + checked += 1; + const peerId = this.activeBulkList[0]; + const st = this.bulkPeers.get(peerId); + if (!st || st.queue.length === 0) { + this.activeBulkList.shift(); + if (st) { + st.active = false; + st.deficit = 0; + } + continue; + } + + if (st.deficit <= 0) { + st.deficit += DRR_QUANTUM_BYTES; + } + + const head = st.queue[0]; + const start = head.nextSegment * head.chunkSize; + const segBytes = Math.min(head.chunkSize, head.totalBytes - start); + const estPacketBytes = segBytes + 48; + + if (!canSendBytes(estPacketBytes)) { + return null; + } + + if (segBytes <= st.deficit) { + st.deficit -= segBytes; + const seg = this._popFromQueue(st.queue, 0); + if (st.queue.length === 0) { + this.activeBulkList.shift(); + st.active = false; + st.deficit = 0; + } else if (st.deficit < head.chunkSize) { + // Rotate to back of active DRR list + this.activeBulkList.push(this.activeBulkList.shift()); + } + return seg; + } + + // Not enough deficit yet; rotate to back and grant quantum next turn + this.activeBulkList.push(this.activeBulkList.shift()); + } + // Top up all active peers by one quantum if none could fire + for (const peerId of this.activeBulkList) { + const st = this.bulkPeers.get(peerId); + if (st) st.deficit += DRR_QUANTUM_BYTES; + } + } + return null; + } + + _popFromQueue(queue, idx) { + const head = queue[idx]; + const segIndex = head.nextSegment; + const start = segIndex * head.chunkSize; + const end = Math.min(head.totalBytes, start + head.chunkSize); + const data = head.payload.subarray(start, end); + head.nextSegment += 1; + if (head.nextSegment >= head.totalSegments) { + queue.splice(idx, 1); + } + return { + peerId: head.peerId, + streamId: head.streamId, + msgId: head.msgId, + streamSeq: head.streamSeq, + isInteractive: head.priority === 'interactive', + segIndex, + totalSegments: head.totalSegments, + totalBytes: head.totalBytes, + data, + }; + } +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/src/transport.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/src/transport.mjs new file mode 100644 index 0000000..177e43f --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/src/transport.mjs @@ -0,0 +1,403 @@ +import { PeerSackTracker, SharedAimdController } from './congestion.mjs'; +import { RelayScheduler } from './scheduler.mjs'; + +const PKT_DATA = 1; +const PKT_SACK = 2; +const PKT_PROBE = 3; +// Outage handling: once no ACK has arrived for STALL_RTTS smoothed RTTs (at least STALL_MIN_MS) +// while data is outstanding, stop retransmitting into the dead link and send a 5-byte probe every +// probe interval instead. The first ACK after that resends everything still outstanding at once. +const STALL_RTTS = 3; +const STALL_MIN_MS = 900; +const PROBE_MIN_MS = 200; +const PROBE_MAX_MS = 500; +const FIXED_DATA_HDR = 18; +const MAX_ID_OVERHEAD = 44; +const MAX_SACK_RANGES = 4; +const DELAYED_ACK_MS = 12; +const DELAYED_ACK_PKTS = 2; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function encodeDataPacket(seq, seg, maxPacketBytes) { + const sBytes = textEncoder.encode(seg.streamId); + const mBytes = textEncoder.encode(seg.msgId); + const headerLen = FIXED_DATA_HDR + sBytes.byteLength + mBytes.byteLength; + const totalLen = headerLen + seg.data.byteLength; + if (totalLen > maxPacketBytes) { + throw new Error(`Packet (${totalLen}) exceeds maxPacketBytes (${maxPacketBytes})`); + } + const out = new Uint8Array(totalLen); + const dv = new DataView(out.buffer); + out[0] = PKT_DATA; + out[1] = seg.isInteractive ? 1 : 0; + dv.setUint32(2, seq); + dv.setUint32(6, seg.streamSeq); + dv.setUint16(10, seg.segIndex); + dv.setUint16(12, seg.totalSegments); + dv.setUint16(14, sBytes.byteLength); + dv.setUint16(16, mBytes.byteLength); + let off = FIXED_DATA_HDR; + out.set(sBytes, off); + off += sBytes.byteLength; + out.set(mBytes, off); + off += mBytes.byteLength; + out.set(seg.data, off); + return out; +} + +function decodeDataPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < FIXED_DATA_HDR || bytes[0] !== PKT_DATA) { + return null; + } + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const isInteractive = bytes[1] === 1; + const seq = dv.getUint32(2); + const streamSeq = dv.getUint32(6); + const segIndex = dv.getUint16(10); + const totalSegments = dv.getUint16(12); + const sLen = dv.getUint16(14); + const mLen = dv.getUint16(16); + const dataOff = FIXED_DATA_HDR + sLen + mLen; + if (dataOff > bytes.byteLength) return null; + const streamId = textDecoder.decode(bytes.subarray(FIXED_DATA_HDR, FIXED_DATA_HDR + sLen)); + const msgId = textDecoder.decode(bytes.subarray(FIXED_DATA_HDR + sLen, dataOff)); + const data = bytes.subarray(dataOff); + return { seq, isInteractive, streamId, msgId, streamSeq, segIndex, totalSegments, data }; +} + +function encodeSackPacket(cumAckSeq, echoSeq, ranges) { + const count = Math.min(MAX_SACK_RANGES, ranges.length); + const out = new Uint8Array(10 + count * 8); + const dv = new DataView(out.buffer); + out[0] = PKT_SACK; + out[1] = count; + dv.setUint32(2, cumAckSeq); + dv.setUint32(6, echoSeq); + let off = 10; + for (let i = 0; i < count; i += 1) { + dv.setUint32(off, ranges[i][0]); + dv.setUint32(off + 4, ranges[i][1]); + off += 8; + } + return out; +} + +function encodeProbePacket(probeId) { + const out = new Uint8Array(5); + out[0] = PKT_PROBE; + new DataView(out.buffer).setUint32(1, probeId >>> 0); + return out; +} + +function decodeSackPacket(bytes) { + if (!(bytes instanceof Uint8Array) || bytes.byteLength < 10 || bytes[0] !== PKT_SACK) return null; + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const count = bytes[1]; + if (10 + count * 8 > bytes.byteLength) return null; + const cumAckSeq = dv.getUint32(2); + const echoSeq = dv.getUint32(6); + const ranges = []; + let off = 10; + for (let i = 0; i < count; i += 1) { + ranges.push([dv.getUint32(off), dv.getUint32(off + 4)]); + off += 8; + } + return { cumAckSeq, echoSeq, ranges }; +} + +function buildSackRanges(oooSet, rcvNext) { + if (oooSet.size === 0) return []; + const sorted = [...oooSet].filter((s) => s > rcvNext).sort((a, b) => a - b); + if (!sorted.length) return []; + const ranges = []; + let start = sorted[0]; + let end = start + 1; + for (let i = 1; i < sorted.length; i += 1) { + if (sorted[i] === end) { + end += 1; + } else { + ranges.push([start, end]); + start = sorted[i]; + end = start + 1; + } + } + ranges.push([start, end]); + // Prioritize most recent ranges if > MAX_SACK_RANGES + return ranges.length <= MAX_SACK_RANGES ? ranges : ranges.slice(ranges.length - MAX_SACK_RANGES); +} + +export function createRelaySender(config) { + const maxPacketBytes = config?.maxPacketBytes ?? 1200; + const peers = config?.peers ?? []; + const chunkSize = Math.max(64, maxPacketBytes - FIXED_DATA_HDR - MAX_ID_OVERHEAD); + + const cc = new SharedAimdController(); + const scheduler = new RelayScheduler(peers); + const peerTrackers = new Map(); + for (const peerId of peers) { + peerTrackers.set(peerId, new PeerSackTracker(peerId, cc)); + } + + function getTracker(peerId) { + let t = peerTrackers.get(peerId); + if (!t) { + t = new PeerSackTracker(peerId, cc); + peerTrackers.set(peerId, t); + } + return t; + } + + let lastAckMs = -Infinity; + let stalledSinceMs = null; + let cwndBeforeStall = 0; + let nextProbeMs = 0; + let probeId = 0; + + function oldestOutstanding() { + let oldest = null; + for (const [peerId, tracker] of peerTrackers) { + for (const entry of tracker.unacked.values()) { + if (!oldest || entry.sentMs < oldest.sentMs) oldest = { peerId, sentMs: entry.sentMs }; + } + } + return oldest; + } + + function stallThresholdMs() { + return Math.max(STALL_MIN_MS, STALL_RTTS * (cc.srttMs ?? 350)); + } + + function probeIntervalMs() { + return Math.min(PROBE_MAX_MS, Math.max(PROBE_MIN_MS, cc.srttMs ?? 350)); + } + + function exitStall() { + // Everything sent before or during the outage is gone: resend it now, without treating the + // outage as congestion. + for (const tracker of peerTrackers.values()) { + for (const entry of tracker.unacked.values()) { + if (entry.sentMs <= stalledSinceMs || entry.inFlight) tracker._queueRetransmit(entry); + } + } + cc.cwnd = Math.max(cc.cwnd, cwndBeforeStall); + stalledSinceMs = null; + } + + return { + enqueue(nowMs, msg) { + getTracker(msg.peerId); + scheduler.enqueue(msg, chunkSize); + }, + + onAckPacket(nowMs, peerId, packetBytes) { + const sack = decodeSackPacket(packetBytes); + if (!sack) return; + lastAckMs = nowMs; + getTracker(peerId).onSackAck(nowMs, sack.cumAckSeq, sack.echoSeq, sack.ranges); + if (stalledSinceMs !== null) exitStall(); + }, + + pollTx(nowMs) { + const packets = []; + + if (stalledSinceMs === null) { + const oldest = oldestOutstanding(); + if (oldest && nowMs - Math.max(lastAckMs, oldest.sentMs) >= stallThresholdMs()) { + stalledSinceMs = nowMs; + cwndBeforeStall = cc.cwnd; + nextProbeMs = nowMs; + } + } + if (stalledSinceMs !== null) { + if (nowMs >= nextProbeMs) { + const oldest = oldestOutstanding(); + if (oldest) { + packets.push({ peerId: oldest.peerId, bytes: encodeProbePacket(probeId++) }); + } + nextProbeMs = nowMs + probeIntervalMs(); + } + return { packets, nextWakeMs: nextProbeMs }; + } + + // Check RTO timeouts across all peers + for (const tracker of peerTrackers.values()) { + tracker.checkTimeouts(nowMs); + } + + // 1. Interactive retransmissions (highest priority) + for (const [peerId, tracker] of peerTrackers) { + while (tracker.hasPendingRetransmit(true)) { + const bytes = tracker.popRetransmit(nowMs, true); + if (!bytes) break; + packets.push({ peerId, bytes }); + } + } + + // 2. New interactive segments + while (scheduler.hasInteractive()) { + const estBytes = scheduler.peekNextInteractiveSize() + FIXED_DATA_HDR + MAX_ID_OVERHEAD; + if (!cc.canSend(estBytes, true)) break; + const seg = scheduler.popInteractiveSegment(); + if (!seg) break; + const tracker = getTracker(seg.peerId); + const seq = tracker.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + tracker.recordSent(seq, bytes, nowMs, true); + packets.push({ peerId: seg.peerId, bytes }); + } + + // 3. Bulk retransmissions (selective SACK/RTO) + let sentBulkRetry = true; + while (sentBulkRetry) { + sentBulkRetry = false; + for (const [peerId, tracker] of peerTrackers) { + if (!tracker.hasPendingRetransmit(false)) continue; + const bytes = tracker.popRetransmit(nowMs, false); + if (bytes) { + packets.push({ peerId, bytes }); + sentBulkRetry = true; + } + } + } + + // 4. New bulk segments via byte-weighted DRR within shared AIMD cwnd + while (scheduler.hasBulk()) { + const seg = scheduler.popBulkSegment((estBytes) => cc.canSend(estBytes, false)); + if (!seg) break; + const tracker = getTracker(seg.peerId); + const seq = tracker.allocateSeq(); + const bytes = encodeDataPacket(seq, seg, maxPacketBytes); + tracker.recordSent(seq, bytes, nowMs, false); + packets.push({ peerId: seg.peerId, bytes }); + } + + let nextWakeMs = Infinity; + for (const tracker of peerTrackers.values()) { + const t = tracker.nextTimeoutMs(); + if (t < nextWakeMs) nextWakeMs = t; + } + + return { packets, nextWakeMs }; + }, + }; +} + +export function createPeerReceiver(peerId, config) { + let rcvNext = 1; + const oooSet = new Set(); + const streams = new Map(); + + let unackedCount = 0; + let ackDueMs = Infinity; + let lastEchoSeq = 0; + + function getStream(streamId) { + let st = streams.get(streamId); + if (!st) { + st = { nextStreamSeq: 1, ready: new Map(), pending: new Map() }; + streams.set(streamId, st); + } + return st; + } + + function makeAck() { + unackedCount = 0; + ackDueMs = Infinity; + return encodeSackPacket(rcvNext, lastEchoSeq, buildSackRanges(oooSet, rcvNext)); + } + + return { + onDataPacket(nowMs, packetBytes) { + if (packetBytes instanceof Uint8Array && packetBytes.byteLength === 5 && packetBytes[0] === PKT_PROBE) { + return { delivered: [], ackPackets: [makeAck()] }; + } + const pkt = decodeDataPacket(packetBytes); + if (!pkt) return { delivered: [], ackPackets: [] }; + + const delivered = []; + let immediateAck = pkt.isInteractive; + const isDuplicate = pkt.seq < rcvNext || oooSet.has(pkt.seq); + if (isDuplicate) { + immediateAck = true; + } else { + lastEchoSeq = pkt.seq; + if (pkt.seq === rcvNext) { + rcvNext += 1; + while (oooSet.has(rcvNext)) { + oooSet.delete(rcvNext); + rcvNext += 1; + } + if (oooSet.size > 0) immediateAck = true; + } else { + oooSet.add(pkt.seq); + immediateAck = true; + } + + const st = getStream(pkt.streamId); + if (pkt.streamSeq >= st.nextStreamSeq && !st.ready.has(pkt.streamSeq)) { + if (pkt.totalSegments === 1) { + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: pkt.msgId, + payload: new Uint8Array(pkt.data), + }); + } else { + let entry = st.pending.get(pkt.streamSeq); + if (!entry) { + entry = { + msgId: pkt.msgId, + totalSegments: pkt.totalSegments, + parts: new Array(pkt.totalSegments).fill(null), + received: 0, + totalBytes: 0, + }; + st.pending.set(pkt.streamSeq, entry); + } + if (entry.parts[pkt.segIndex] === null) { + entry.parts[pkt.segIndex] = new Uint8Array(pkt.data); + entry.received += 1; + entry.totalBytes += pkt.data.byteLength; + } + if (entry.received === entry.totalSegments) { + st.pending.delete(pkt.streamSeq); + const out = new Uint8Array(entry.totalBytes); + let off = 0; + for (let i = 0; i < entry.totalSegments; i += 1) { + out.set(entry.parts[i], off); + off += entry.parts[i].byteLength; + } + st.ready.set(pkt.streamSeq, { + streamId: pkt.streamId, + msgId: entry.msgId, + payload: out, + }); + } + } + while (st.ready.has(st.nextStreamSeq)) { + delivered.push(st.ready.get(st.nextStreamSeq)); + st.ready.delete(st.nextStreamSeq); + st.nextStreamSeq += 1; + } + } + } + + unackedCount += 1; + if (immediateAck || unackedCount >= DELAYED_ACK_PKTS) { + return { delivered, ackPackets: [makeAck()] }; + } + if (!Number.isFinite(ackDueMs)) { + ackDueMs = nowMs + DELAYED_ACK_MS; + } + return { delivered, ackPackets: [] }; + }, + + pollControl(nowMs) { + if (unackedCount > 0 && nowMs >= ackDueMs) { + return { ackPackets: [makeAck()], nextWakeMs: Infinity }; + } + return { ackPackets: [], nextWakeMs: ackDueMs }; + }, + }; +} diff --git a/questions/opt-relay-congestion-scheduler/v2/reference/tests/smoke.test.mjs b/questions/opt-relay-congestion-scheduler/v2/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..4dfac46 --- /dev/null +++ b/questions/opt-relay-congestion-scheduler/v2/reference/tests/smoke.test.mjs @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SplitMix64, generateProfileMessages, runSimulation } from '../sim/network.mjs'; +import { PUBLIC_PROFILES } from '../bench/workload.mjs'; +import { createPeerReceiver, createRelaySender } from '../src/transport.mjs'; + +test('exact bit-for-bit delivery and strict per-(peer, stream) FIFO under loss, reorder, dup, and blackout', () => { + const rng = new SplitMix64(999111); + const peers = ['peer-a', 'peer-b']; + const messages = []; + for (let i = 0; i < 12; i += 1) { + messages.push({ + peerId: peers[i % 2], + streamId: i % 3 === 0 ? 'ctrl' : 'bulk', + msgId: `m-${i}`, + priority: i % 3 === 0 ? 'interactive' : 'bulk', + payload: rng.fillBytes(i % 3 === 0 ? 320 + i * 25 : 16 * 1024 + i * 512), + enqueuedMs: i * 90, + deadlineMs: 20_000, + }); + } + + const res = runSimulation({ + profile: { + name: 'unit-chaos', + seed: 777, + peers, + downlink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 12, + jitterFifo: false, + lossProb: 0.08, + reorderProb: 0.15, + reorderExtraMs: 40, + dupProb: 0.10, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + uplink: { + bitsPerSecond: 3_000_000, + propagationDelayMs: 45, + jitterMs: 10, + lossProb: 0.08, + reorderProb: 0.10, + reorderExtraMs: 30, + dupProb: 0.08, + queueBytes: 36_000, + outages: [[600, 1200]], + }, + }, + messages, + createRelaySender, + createPeerReceiver, + }); + + assert.equal(res.exactDeliveryOk, true, `Exact delivery failed: ${res.violations.join('; ')}`); + assert.equal(res.packetBoundsOk, true, `Packet bounds failed: ${res.violations.join('; ')}`); + assert.equal(res.interactiveDeadlineOk, true, `Deadline missed: ${res.violations.join('; ')}`); + assert.equal(res.deliveredCount, messages.length); +}); + +test('all public profiles satisfy exact delivery, packet bounds, interactive deadlines, and fairness >= 0.85', () => { + for (const profile of PUBLIC_PROFILES) { + const messages = generateProfileMessages(profile); + const res = runSimulation({ + profile, + messages, + createRelaySender, + createPeerReceiver, + }); + assert.equal(res.ok, true, `${profile.name} failed: ${res.violations.join('; ')}`); + assert.ok( + res.jainsFairness >= 0.85, + `${profile.name} fairness ${res.jainsFairness.toFixed(3)} < 0.85`, + ); + } +}); diff --git a/questions/opt-routing-cost-sim/v1/author/editable.json b/questions/opt-routing-cost-sim/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/opt-routing-cost-sim/v1/author/evaluator.mjs b/questions/opt-routing-cost-sim/v1/author/evaluator.mjs new file mode 100644 index 0000000..1764113 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/evaluator.mjs @@ -0,0 +1,345 @@ +import { takeResultChannel } from './result-channel.mjs'; +/** + * Trusted evaluator for `opt-routing-cost-sim@v1`. + * + * Imports the immutable billing simulator and workload generator from `candidate/sim/`, + * loads the candidate's `router.mjs` from the isolated temp copy, verifies all 4 hard gates + * across unit edge cases + public + 3 unseen held-out 14-day traces, and reports mean 14-day + * held-out USD cost (`total_cost_usd`). + */ + +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + CACHE_1H_TTL_MS, + CACHE_5M_TTL_MS, + SEVEN_DAYS_MS, + createDefaultPoolConfig, + runSimulation, +} from '../candidate/sim/billing-sim.mjs'; +import { + DEFAULT_START_MS, + PUBLIC_SCENARIOS, + generateWorkload, +} from '../candidate/sim/workload-generator.mjs'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subSrcDir] = process.argv.slice(2); +if (!subSrcDir) { + throw new Error('Usage: node evaluator.mjs '); +} + +const routerMod = await import(pathToFileURL(path.join(subSrcDir, 'router.mjs')).href); +const { createCostRouter } = routerMod; +if (typeof createCostRouter !== 'function') { + throw new Error('src/router.mjs must export createCostRouter(poolConfig)'); +} + +// Unseen held-out 14-day traces with varied weekday/weekend phases, burst schedules, +// staggered 7d reset offsets, session gap mixtures, and mid-week provider outages. +const HELD_OUT_SCENARIOS = [ + { + name: 'heldout-wed-heavy-review', + seed: 910421, + startDayOfWeek: 2, // Wednesday + subAResetOffsetHours: 3 * 24 + 20, // Day 3 20:00 & Day 10 20:00 + subBResetOffsetHours: 1 * 24 + 6, // Day 1 06:00 & Day 8 06:00 + subAInitialUsedFrac: 0.42, + subBInitialUsedFrac: 0.72, + demandMultiplier: 1.06, + weekendDipFactor: 0.34, + burstIntensity: 1.15, + archetypeWeights: { + rapidCoding: 0.34, + reviewThinking: 0.12, + mixedCadence: 0.08, + oneShotSparse: 0.20, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 2 * 24 + 13.5, durationMin: 80 }, + { accountId: 'sub-b', startHour: 8 * 24 + 16.0, durationMin: 70 }, + { accountId: 'sub-a', startHour: 11 * 24 + 10.5, durationMin: 45 }, + ], + }, + { + name: 'heldout-fri-weekend-burst', + seed: 910422, + startDayOfWeek: 4, // Friday + subAResetOffsetHours: 4 * 24 + 12, // Day 4 12:00 & Day 11 12:00 + subBResetOffsetHours: 6 * 24 + 22, // Day 6 22:00 & Day 13 22:00 + subAInitialUsedFrac: 0.30, + subBInitialUsedFrac: 0.12, + demandMultiplier: 1.04, + weekendDipFactor: 0.52, + burstIntensity: 1.08, + archetypeWeights: { + rapidCoding: 0.37, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.25, + }, + outages: [ + { accountId: 'sub-b', startHour: 4 * 24 + 10.0, durationMin: 85 }, + { accountId: 'sub-b', startHour: 9 * 24 + 15.0, durationMin: 60 }, + ], + }, + { + name: 'heldout-sat-stagger-crunch', + seed: 910423, + startDayOfWeek: 5, // Saturday + subAResetOffsetHours: 1 * 24 + 22, // Day 1 22:00 & Day 8 22:00 + subBResetOffsetHours: 4 * 24 + 14, // Day 4 14:00 & Day 11 14:00 + subAInitialUsedFrac: 0.62, + subBInitialUsedFrac: 0.28, + demandMultiplier: 1.08, + weekendDipFactor: 0.30, + burstIntensity: 1.20, + archetypeWeights: { + rapidCoding: 0.35, + reviewThinking: 0.11, + mixedCadence: 0.07, + oneShotSparse: 0.20, + largeOneShot: 0.27, + }, + outages: [ + { accountId: 'sub-b', startHour: 3 * 24 + 11.5, durationMin: 75 }, + { accountId: 'sub-b', startHour: 10 * 24 + 14.0, durationMin: 90 }, + ], + }, +]; + +const MAX_SIM_RUNTIME_MS = 4000; +const MAX_P99_STALL_MS = 3000; +const MAX_FAILED_ATTEMPT_RATE = 0.02; + +function runUnitEdgeCases() { + const poolConfig = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + + // 1. All primary subscriptions + secondary-org exhausted -> must cleanly route to PAYG meeting minTier + { + const wl = { + name: 'unit-all-exhausted', + seed: 11, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 1_900_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 1_650_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 12_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 1_550_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'e1', sessionId: 'es1', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 1, prefixTokens: 2000, newInputTokens: 1000, estOutputTokens: 400, actualOutputTokens: 400, serviceDurationMs: 2000 }, + { turnId: 'e2', sessionId: 'es2', turnIndex: 0, arrivalMs: T0 + 20_000, minTier: 2, prefixTokens: 4000, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2500 }, + { turnId: 'e3', sessionId: 'es3', turnIndex: 0, arrivalMs: T0 + 30_000, minTier: 3, prefixTokens: 8000, newInputTokens: 2000, estOutputTokens: 1000, actualOutputTokens: 1000, serviceDurationMs: 3000 }, + ], + }; + const res = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0, 'exhausted-pool: dropped turns'); + assert.equal(res.tierViolations, 0, 'exhausted-pool: tier violations'); + assert.equal(res.invalidDecisions, 0, 'exhausted-pool: invalid decisions'); + assert.equal(res.failedAttempts, 0, 'exhausted-pool: should not spam exhausted accounts'); + } + + // 2. Mid-session cooldown/outage failover + excludedAccountIds compliance + { + const wl = { + name: 'unit-mid-session-outage', + seed: 12, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [ + { accountId: 'sub-a', startMs: T0 + 60_000, endMs: T0 + 1_800_000 }, + { accountId: 'sub-b', startMs: T0 + 60_000, endMs: T0 + 1_800_000 }, + ], + turns: [ + { turnId: 'o1', sessionId: 'os1', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 3, prefixTokens: 10000, newInputTokens: 1500, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + { turnId: 'o2', sessionId: 'os1', turnIndex: 1, arrivalMs: T0 + 90_000, minTier: 3, prefixTokens: 12300, newInputTokens: 1500, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + { turnId: 'o3', sessionId: 'os1', turnIndex: 2, arrivalMs: T0 + 150_000, minTier: 3, prefixTokens: 14600, newInputTokens: 1500, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + ], + }; + const res = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0, 'outage-failover: dropped turns'); + assert.equal(res.tierViolations, 0, 'outage-failover: tier violations'); + assert.equal(res.invalidDecisions, 0, 'outage-failover: invalid decisions'); + } + + // 3. 7d reset wraparound across multi-week jump + { + const wl = { + name: 'unit-7d-wraparound', + seed: 13, + startMs: T0, + endMs: T0 + 3 * SEVEN_DAYS_MS, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + 3_600_000 }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 12_500_000, sevenDayResetAtMs: T0 + 7_200_000 }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'w1', sessionId: 'ws1', turnIndex: 0, arrivalMs: T0 + 1000, minTier: 3, prefixTokens: 6000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'w2', sessionId: 'ws2', turnIndex: 0, arrivalMs: T0 + 3_600_000 + 10_000, minTier: 3, prefixTokens: 6000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'w3', sessionId: 'ws3', turnIndex: 0, arrivalMs: T0 + 2 * SEVEN_DAYS_MS + 10_000, minTier: 3, prefixTokens: 6000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + ], + }; + const res = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0, '7d-wraparound: dropped turns'); + assert.equal(res.tierViolations, 0, '7d-wraparound: tier violations'); + assert.equal(res.invalidDecisions, 0, '7d-wraparound: invalid decisions'); + } + + // 4. Exact 5m (300_000ms vs 300_001ms) and 1h (3_600_000ms vs 3_600_001ms) cache boundary handling + { + const wl = { + name: 'unit-cache-boundaries', + seed: 14, + startMs: T0, + endMs: T0 + 4 * 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'b1', sessionId: 'bs5m', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 3, prefixTokens: 12000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'b2', sessionId: 'bs5m', turnIndex: 1, arrivalMs: T0 + 10_000 + CACHE_5M_TTL_MS, minTier: 3, prefixTokens: 14000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'b3', sessionId: 'bs5m', turnIndex: 2, arrivalMs: T0 + 10_000 + 2 * CACHE_5M_TTL_MS + 1, minTier: 3, prefixTokens: 16000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'b4', sessionId: 'bs1h', turnIndex: 0, arrivalMs: T0 + 20_000, minTier: 3, prefixTokens: 20000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'b5', sessionId: 'bs1h', turnIndex: 1, arrivalMs: T0 + 20_000 + CACHE_1H_TTL_MS, minTier: 3, prefixTokens: 22000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + { turnId: 'b6', sessionId: 'bs1h', turnIndex: 2, arrivalMs: T0 + 20_000 + 2 * CACHE_1H_TTL_MS + 1, minTier: 3, prefixTokens: 24000, newInputTokens: 1500, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 2000 }, + ], + }; + const res = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0, 'cache-boundaries: dropped turns'); + assert.equal(res.tierViolations, 0, 'cache-boundaries: tier violations'); + assert.equal(res.invalidDecisions, 0, 'cache-boundaries: invalid decisions'); + } + + // 5. Determinism across two independent router instances on identical workload + { + const wl = generateWorkload({ ...PUBLIC_SCENARIOS[0], demandMultiplier: 0.08, poolConfig }); + const r1 = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + const r2 = runSimulation({ workload: wl, poolConfig, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(r1.totalCostUsd, r2.totalCostUsd, 'determinism: cost differs between identical runs'); + assert.equal(r1.servedTurns, r2.servedTurns, 'determinism: servedTurns differs'); + assert.equal(r1.failedAttempts, r2.failedAttempts, 'determinism: failedAttempts differs'); + } +} + +const errors = []; +let unitEdgeCasesOk = false; +try { + runUnitEdgeCases(); + unitEdgeCasesOk = true; +} catch (err) { + errors.push(`unit: ${err.message}`); +} + +const poolConfig = createDefaultPoolConfig(); +const traceResults = []; +const allScenarios = [ + { ...PUBLIC_SCENARIOS[0], split: 'public' }, + ...HELD_OUT_SCENARIOS.map((s) => ({ ...s, split: 'heldout' })), +]; + +let allServed = unitEdgeCasesOk; +let allTierFloor = unitEdgeCasesOk; +let allLatencySla = true; +let allCausalAndFast = unitEdgeCasesOk; +let heldOutCostSum = 0; +let heldOutCount = 0; + +for (const sc of allScenarios) { + try { + const workload = generateWorkload({ ...sc, poolConfig }); + const res = runSimulation({ + workload, + poolConfig, + createRouter: createCostRouter, + freezeCtx: true, + }); + + const servedOk = res.droppedTurns === 0 && res.invalidDecisions === 0 && res.servedTurns === res.totalTurns; + const tierOk = res.tierViolations === 0; + const latencyOk = res.p99StallMs <= MAX_P99_STALL_MS && res.failedAttemptRate < MAX_FAILED_ATTEMPT_RATE; + const fastOk = res.runtimeMs < MAX_SIM_RUNTIME_MS; + + if (!servedOk) { + allServed = false; + errors.push(`${sc.name}: dropped=${res.droppedTurns}, invalid=${res.invalidDecisions}`); + } + if (!tierOk) { + allTierFloor = false; + errors.push(`${sc.name}: tierViolations=${res.tierViolations}`); + } + if (!latencyOk) { + allLatencySla = false; + errors.push(`${sc.name}: p99StallMs=${res.p99StallMs}, failedAttemptRate=${(res.failedAttemptRate * 100).toFixed(2)}%`); + } + if (!fastOk) { + allCausalAndFast = false; + errors.push(`${sc.name}: runtimeMs=${res.runtimeMs} >= ${MAX_SIM_RUNTIME_MS}`); + } + + if (sc.split === 'heldout') { + heldOutCostSum += res.totalCostUsd; + heldOutCount += 1; + } + + traceResults.push({ + name: sc.name, + split: sc.split, + totalCostUsd: res.totalCostUsd, + totalTurns: res.totalTurns, + droppedTurns: res.droppedTurns, + tierViolations: res.tierViolations, + invalidDecisions: res.invalidDecisions, + failedAttemptRate: Number(res.failedAttemptRate.toFixed(5)), + p99StallMs: res.p99StallMs, + runtimeMs: res.runtimeMs, + cacheHitRate: Number(res.cacheStats.cacheHitRate.toFixed(4)), + cacheModes: res.cacheStats.byMode, + expiredQuotaUnits: res.expiredQuotaUnits, + }); + } catch (err) { + allServed = false; + allTierFloor = false; + allLatencySla = false; + allCausalAndFast = false; + errors.push(`${sc.name}: exception ${err.message}`); + } +} + +const totalCostUsd = heldOutCount === HELD_OUT_SCENARIOS.length + ? Number((heldOutCostSum / heldOutCount).toFixed(2)) + : 1_000_000; + +trusted.emit(({ + status: 'graded', + items: { + gate_all_served: allServed, + gate_tier_floor: allTierFloor, + gate_latency_sla: allLatencySla, + gate_causal_and_fast: allCausalAndFast, + }, + metrics: { + total_cost_usd: totalCostUsd, + }, + details: { + errors, + traces: traceResults, + }, +})); diff --git a/questions/opt-routing-cost-sim/v1/author/grade.py b/questions/opt-routing-cost-sim/v1/author/grade.py new file mode 100644 index 0000000..1cc257c --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/simulators/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/opt-routing-cost-sim/v1/author/grade_impl.py b/questions/opt-routing-cost-sim/v1/author/grade_impl.py new file mode 100644 index 0000000..9794b2f --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/grade_impl.py @@ -0,0 +1,42 @@ +"""Isolated pure-Node quantitative grader: runs correctness gates + public & unseen held-out 14-day simulations.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + src_dir = submission_root / 'src' + if not src_dir.is_dir(): + return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'} + with tempfile.TemporaryDirectory(prefix='eval-opt-routing-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(src_dir, sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/opt-routing-cost-sim/v1/author/oracle.mjs b/questions/opt-routing-cost-sim/v1/author/oracle.mjs new file mode 100644 index 0000000..f9c502f --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/oracle.mjs @@ -0,0 +1,524 @@ +/** + * Exact Offline Clairvoyant Lower Bound & Constructive Clairvoyant Oracle. + * + * Used by question authors to mathematically ground `target` in `question.json`: + * 1. Exact per-session DP computes the mathematically minimum effective input tokens per session + * (knowing exact future inter-turn gaps and exact actualOutputTokens, assuming zero account switches). + * 2. Exact staggered-7d LP dual + 5h peak-capacity relaxation computes a strict mathematical lower bound + * `strictLowerBoundUsd` and a 5h+7d lower bound `tightLowerBoundUsd`. + * 3. A constructive offline clairvoyant router runs inside the real `runSimulation()` using exact future + * gaps, exact outages, and exact future demand per 5h & 7d window to produce `clairvoyantSimUsd`. + */ + +import { + CACHE_1H_TTL_MS, + CACHE_5M_TTL_MS, + FIVE_HOURS_MS, + SEVEN_DAYS_MS, + computeTurnBilling, + createDefaultPoolConfig, + runSimulation, +} from '../candidate/sim/billing-sim.mjs'; + +const MODES = ['none', '5m', '1h']; +const WRITE_MULTS = { none: 1.0, '5m': 1.25, '1h': 2.0 }; +const TTL_MS = { none: 0, '5m': CACHE_5M_TTL_MS, '1h': CACHE_1H_TTL_MS }; + +/** + * Exact Dynamic Program for a single uninterrupted session on one account. + * Finds the mathematically minimum total effective input tokens for the session. + */ +export function solveSessionCacheDP(sessionTurns) { + const L = sessionTurns.length; + const warmPrefix = sessionTurns.map((t) => t.prefixTokens + t.newInputTokens + t.actualOutputTokens); + + let dp = new Map(); + dp.set('cold', { cost: 0, path: [] }); + + for (let i = 0; i < L; i += 1) { + const t = sessionTurns[i]; + const nextDp = new Map(); + + for (const [stateKey, stateVal] of dp.entries()) { + let cachedRead = 0; + let stateStillLive = false; + if (stateKey !== 'cold') { + const sep = stateKey.indexOf(':'); + const j = Number(stateKey.slice(0, sep)); + const m = stateKey.slice(sep + 1); + const expiresAt = sessionTurns[j].arrivalMs + TTL_MS[m]; + if (t.arrivalMs <= expiresAt) { + cachedRead = Math.min(t.prefixTokens, warmPrefix[j]); + stateStillLive = true; + } + } + + const uncached = (t.prefixTokens - cachedRead) + t.newInputTokens; + + for (const mode of MODES) { + const effInput = cachedRead * 0.10 + uncached * WRITE_MULTS[mode]; + const nextCost = stateVal.cost + effInput; + + let nextKey; + if (mode === 'none') { + nextKey = stateStillLive ? stateKey : 'cold'; + } else { + const nextArrival = i + 1 < L ? sessionTurns[i + 1].arrivalMs : Number.POSITIVE_INFINITY; + nextKey = nextArrival <= t.arrivalMs + TTL_MS[mode] ? `${i}:${mode}` : 'cold'; + } + + const existing = nextDp.get(nextKey); + if (!existing || nextCost < existing.cost) { + nextDp.set(nextKey, { + cost: nextCost, + path: [...stateVal.path, { mode, effInput, cachedRead }], + }); + } + } + } + dp = nextDp; + } + + let best = null; + for (const val of dp.values()) { + if (!best || val.cost < best.cost) best = val; + } + return best; +} + +function get7dWindowIndex(tMs, initialResetAtMs) { + if (tMs < initialResetAtMs) return 0; + return 1 + Math.floor((tMs - initialResetAtMs) / SEVEN_DAYS_MS); +} + +/** + * Computes: + * - `strict7dLowerBoundUsd`: strict LP lower bound relaxing 5h caps (mathematically unbeatable) + * - `tightLowerBoundUsd`: LP lower bound adding unavoidable 5h peak-bucket overflow surcharges + * - `clairvoyantSimUsd`: achievable offline clairvoyant simulation inside `runSimulation()` + */ +export function computeOfflineLowerBound(workload, poolConfig = createDefaultPoolConfig()) { + const bySession = new Map(); + for (const t of workload.turns) { + let list = bySession.get(t.sessionId); + if (!list) { + list = []; + bySession.set(t.sessionId, list); + } + list.push(t); + } + + const optimalModes = new Map(); + const dpEffByTurnId = new Map(); + const turnItems = []; + + for (const [, sTurns] of bySession.entries()) { + sTurns.sort((a, b) => a.turnIndex - b.turnIndex); + const solved = solveSessionCacheDP(sTurns); + for (let i = 0; i < sTurns.length; i += 1) { + const t = sTurns[i]; + const step = solved.path[i]; + optimalModes.set(t.turnId, step.mode); + dpEffByTurnId.set(t.turnId, step.effInput); + const effInput = step.effInput; + const out = t.actualOutputTokens; + const qUnits = effInput + 3.0 * out; + + let paygUsd; + if (t.minTier === 1) paygUsd = (effInput * 0.50 + out * 2.50) / 1_000_000; + else if (t.minTier === 2) paygUsd = (effInput * 3.00 + out * 15.00) / 1_000_000; + else paygUsd = (effInput * 10.00 + out * 30.00) / 1_000_000; + + const secUsd = (effInput * 1.50 + out * 7.50) / 1_000_000; + const canUseSec = secUsd < paygUsd; + + turnItems.push({ + turn: t, + effInput, + out, + qUnits, + paygUsd, + secUsd, + canUseSec, + secSavingsPerUnit: canUseSec ? (paygUsd - secUsd) / qUnits : 0, + bestNonSubUsd: Math.min(paygUsd, secUsd), + }); + } + } + + const subACfg = poolConfig.accounts.find((a) => a.id === 'sub-a'); + const subBCfg = poolConfig.accounts.find((a) => a.id === 'sub-b'); + const secCfg = poolConfig.accounts.find((a) => a.id === 'secondary-org'); + const initA = workload.initialAccountState['sub-a']; + const initB = workload.initialAccountState['sub-b']; + + const cap7dA = new Map(); + const cap7dB = new Map(); + for (const item of turnItems) { + const wa = get7dWindowIndex(item.turn.arrivalMs, initA.sevenDayResetAtMs); + if (!cap7dA.has(wa)) { + cap7dA.set(wa, wa === 0 ? Math.max(0, subACfg.sevenDayLimit - initA.sevenDayUsed) : subACfg.sevenDayLimit); + } + const wb = get7dWindowIndex(item.turn.arrivalMs, initB.sevenDayResetAtMs); + if (!cap7dB.has(wb)) { + cap7dB.set(wb, wb === 0 ? Math.max(0, subBCfg.sevenDayLimit - initB.sevenDayUsed) : subBCfg.sevenDayLimit); + } + } + + // Exact dual minimization of the staggered 7d packing LP (6 dual variables -> exact global optimum!) + function solveStaggered7dLP(items, getValPerUnit) { + const aKeys = [...cap7dA.keys()].sort((x, y) => x - y); + const bKeys = [...cap7dB.keys()].sort((x, y) => x - y); + const lamA = new Map(aKeys.map((k) => [k, 1.5e-6])); + const lamB = new Map(bKeys.map((k) => [k, 1.5e-6])); + + const pre = items.map((it) => ({ + wa: get7dWindowIndex(it.turn.arrivalMs, initA.sevenDayResetAtMs), + wb: get7dWindowIndex(it.turn.arrivalMs, initB.sevenDayResetAtMs), + qUnits: it.qUnits, + v: getValPerUnit(it), + })); + + function optimizeCoord(isA, key) { + const cap = isA ? cap7dA.get(key) : cap7dB.get(key); + const candidates = []; + for (let i = 0; i < pre.length; i += 1) { + const it = pre[i]; + if ((isA ? it.wa : it.wb) !== key) continue; + const otherLam = isA ? lamB.get(it.wb) : lamA.get(it.wa); + const effCap = Math.min(it.v, otherLam); + if (effCap > 0) candidates.push({ thresh: effCap, q: it.qUnits }); + } + candidates.sort((x, y) => y.thresh - x.thresh); + let cumQ = 0; + let bestLam = 0; + for (let i = 0; i < candidates.length; i += 1) { + cumQ += candidates[i].q; + if (cumQ > cap) { + bestLam = candidates[i].thresh; + break; + } + } + if (isA) lamA.set(key, bestLam); + else lamB.set(key, bestLam); + } + + let bestDual = pre.reduce((s, it) => s + it.qUnits * it.v, 0); + for (let iter = 0; iter < 80; iter += 1) { + for (const k of aKeys) optimizeCoord(true, k); + for (const k of bKeys) optimizeCoord(false, k); + let dual = 0; + for (const k of aKeys) dual += cap7dA.get(k) * lamA.get(k); + for (const k of bKeys) dual += cap7dB.get(k) * lamB.get(k); + for (let i = 0; i < pre.length; i += 1) { + const it = pre[i]; + const minLam = Math.min(lamA.get(it.wa), lamB.get(it.wb)); + if (it.v > minLam) dual += it.qUnits * (it.v - minLam); + } + if (dual < bestDual) bestDual = dual; + } + return { maxSavings: bestDual, lamA, lamB }; + } + + const baseCostNoSub = turnItems.reduce((s, it) => s + it.bestNonSubUsd, 0); + const lp7d = solveStaggered7dLP(turnItems, (it) => it.bestNonSubUsd / it.qUnits); + const strict7dLowerBoundUsd = Math.max(0, baseCostNoSub - lp7d.maxSavings); + + // Unavoidable 5h peak-bucket overflow surcharge (fixed 5h buckets; note rolling 5h is even stricter!) + const bucketMap = new Map(); + for (const it of turnItems) { + const bIdx = Math.floor((it.turn.arrivalMs - workload.startMs) / FIVE_HOURS_MS); + let list = bucketMap.get(bIdx); + if (!list) { + list = []; + bucketMap.set(bIdx, list); + } + list.push(it); + } + + let peak5hExtraUsd = 0; + for (const [, list] of bucketMap.entries()) { + const tier23 = list.filter((it) => it.canUseSec); + const totalQ = tier23.reduce((s, it) => s + it.qUnits, 0); + const max5hCap = subACfg.fiveHourLimit + subBCfg.fiveHourLimit + secCfg.fiveHourLimit; + if (totalQ > max5hCap) { + const sorted = [...tier23].sort((a, b) => a.secSavingsPerUnit - b.secSavingsPerUnit); + let spill = totalQ - max5hCap; + for (const it of sorted) { + if (spill <= 0) break; + const take = Math.min(spill, it.qUnits); + peak5hExtraUsd += take * it.secSavingsPerUnit; + spill -= take; + } + } + } + + // Constructive Offline Clairvoyant Simulation: + // Knows exact future gaps (DP optimal cache modes), exact outages, and exact future tier-3/tier-2 + // demand in the upcoming 5h window and remaining 7d windows! + const outageList = workload.outages ?? []; + const isOutage = (accId, nowMs) => outageList.some((o) => o.accountId === accId && nowMs >= o.startMs && nowMs < o.endMs); + + const nextGapByTurnId = new Map(); + const remSessionQByTurnId = new Map(); + for (const [, sTurns] of bySession.entries()) { + let suffixQ = 0; + for (let i = sTurns.length - 1; i >= 0; i -= 1) { + const t = sTurns[i]; + nextGapByTurnId.set( + t.turnId, + i + 1 < sTurns.length ? sTurns[i + 1].arrivalMs - t.arrivalMs : Number.POSITIVE_INFINITY, + ); + remSessionQByTurnId.set(t.turnId, suffixQ); + suffixQ += (dpEffByTurnId.get(t.turnId) ?? 0) + 3.0 * t.actualOutputTokens; + } + } + + // Prefix sums of exact future tier-3, tier-2, and peak-excess tier-3 demand by arrival time + const sortedTurns = workload.turns; + const N = sortedTurns.length; + const times = new Float64Array(N); + const cumT3 = new Float64Array(N + 1); + const cumT2 = new Float64Array(N + 1); + const cumPeakT3 = new Float64Array(N + 1); + + // Identify 5h sliding bursts where tier-3 demand exceeds secondary-org's 5h capacity! + let right = 0; + let winT3 = 0; + const isPeakT3Turn = new Uint8Array(N); + for (let i = 0; i < N; i += 1) { + while (right < N && sortedTurns[right].arrivalMs - sortedTurns[i].arrivalMs <= FIVE_HOURS_MS) { + const tr = sortedTurns[right]; + if (tr.minTier === 3) winT3 += (dpEffByTurnId.get(tr.turnId) ?? 0) + 3.0 * tr.actualOutputTokens; + right += 1; + } + if (winT3 > secCfg.fiveHourLimit * 0.90) { + for (let k = i; k < right; k += 1) { + if (sortedTurns[k].minTier === 3) isPeakT3Turn[k] = 1; + } + } + const ti = sortedTurns[i]; + if (ti.minTier === 3) winT3 -= (dpEffByTurnId.get(ti.turnId) ?? 0) + 3.0 * ti.actualOutputTokens; + } + + for (let i = 0; i < N; i += 1) { + const t = sortedTurns[i]; + times[i] = t.arrivalMs; + const q = (dpEffByTurnId.get(t.turnId) ?? 0) + 3.0 * t.actualOutputTokens; + cumT3[i + 1] = cumT3[i] + (t.minTier === 3 ? q : 0); + cumT2[i + 1] = cumT2[i] + (t.minTier === 2 ? q : 0); + cumPeakT3[i + 1] = cumPeakT3[i] + (isPeakT3Turn[i] ? q : 0); + } + + function lowerBoundIdx(arr, target) { + let lo = 0; + let hi = arr.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (arr[mid] < target) lo = mid + 1; + else hi = mid; + } + return lo; + } + + function exactFutureDemand(fromMs, toMs) { + if (toMs <= fromMs) return { t3: 0, t2: 0, peakT3: 0 }; + const i0 = lowerBoundIdx(times, fromMs); + const i1 = lowerBoundIdx(times, toMs); + return { + t3: cumT3[i1] - cumT3[i0], + t2: cumT2[i1] - cumT2[i0], + peakT3: cumPeakT3[i1] - cumPeakT3[i0], + }; + } + + const turnLookup = new Map(sortedTurns.map((t) => [`${t.sessionId}:${t.turnIndex}`, t])); + + function makeClairvoyantRouter(pool) { + return { + selectRoute(ctx) { + const { nowMs, excludedAccountIds, turn, accounts } = ctx; + const excluded = new Set(excludedAccountIds); + const exactTurn = turnLookup.get(`${turn.sessionId}:${turn.turnIndex}`); + const exactMode = exactTurn ? (optimalModes.get(exactTurn.turnId) ?? '5m') : '5m'; + const nextGap = exactTurn ? (nextGapByTurnId.get(exactTurn.turnId) ?? Number.POSITIVE_INFINITY) : Number.POSITIVE_INFINITY; + const outTokens = exactTurn ? exactTurn.actualOutputTokens : turn.estOutputTokens; + + const subA = accounts.find((a) => a.id === 'sub-a'); + const subB = accounts.find((a) => a.id === 'sub-b'); + const sec = accounts.find((a) => a.id === 'secondary-org'); + + const horizon5h = exactFutureDemand(nowMs, nowMs + FIVE_HOURS_MS); + const rem5hSubA = subA && !isOutage('sub-a', nowMs) ? Math.max(0, subA.fiveHourLimit - subA.fiveHourUsed) : 0; + const rem5hSubB = subB && !isOutage('sub-b', nowMs) ? Math.max(0, subB.fiveHourLimit - subB.fiveHourUsed) : 0; + const rem5hSec = sec ? Math.max(0, sec.fiveHourLimit - sec.fiveHourUsed) : 0; + const rem7dSubA = subA ? Math.max(0, subA.sevenDayLimit - subA.sevenDayUsed) : 0; + const rem7dSubB = subB ? Math.max(0, subB.sevenDayLimit - subB.sevenDayUsed) : 0; + const avail5hPool = Math.min(rem5hSubA, rem7dSubA) + Math.min(rem5hSubB, rem7dSubB) + rem5hSec; + const t3Crunch5h = horizon5h.t3 > avail5hPool * 0.80; + const secT3Crunch5h = horizon5h.t3 > rem5hSec * 0.90; + + function subShadow(acc) { + const other = acc.id === 'sub-a' ? subB : subA; + const rem = Math.max(0, acc.sevenDayLimit - acc.sevenDayUsed); + const resetAt = acc.sevenDayResetAtMs; + const fd = exactFutureDemand(nowMs, resetAt); + let otherHelp = 0; + if (other && other.sevenDayResetAtMs !== null) { + const oRem = Math.max(0, other.sevenDayLimit - other.sevenDayUsed); + if (other.sevenDayResetAtMs >= resetAt) { + otherHelp = oRem * ((resetAt - nowMs) / Math.max(1, other.sevenDayResetAtMs - nowMs)); + } else { + otherHelp = oRem + other.sevenDayLimit * ((resetAt - other.sevenDayResetAtMs) / SEVEN_DAYS_MS); + } + } + const poolCap = rem + otherHelp; + + // Marginal value ladder of subscription 7d quota: + // Notice secondary-org has NO 7d limit and costs ~$1.80/M off-peak, whereas during 5h peaks + // secondary-org saturates and tier-3 spills to $10/M (payg-t3) & tier-2 to $3.7/M (payg-t2)! + // So keeping sub 7d quota above ~$2.10/M when peak demand looms saves $10/M instead of $1.80/M! + let lam7d; + if (fd.peakT3 > poolCap * 0.90) { + lam7d = 4.6e-6; + } else if (fd.t3 > poolCap * 0.85) { + lam7d = 2.35e-6; + } else if (fd.t3 + fd.t2 > poolCap * 0.90) { + lam7d = 1.55e-6; + } else { + lam7d = Math.max(0.05e-6, ((fd.t3 + fd.t2) / Math.max(1, poolCap)) * 1.1e-6); + } + + // Differentiate staggered sub-a vs sub-b by remaining-to-demand ratio before own reset + const myDemandRatio = rem / Math.max(1, fd.t3 + fd.t2 * 0.5); + const otherReset = other?.sevenDayResetAtMs ?? resetAt; + const otherFd = exactFutureDemand(nowMs, otherReset); + const otherRem = other ? Math.max(0, other.sevenDayLimit - other.sevenDayUsed) : 0; + const otherRatio = otherRem / Math.max(1, otherFd.t3 + otherFd.t2 * 0.5); + if (myDemandRatio > otherRatio * 1.05) { + lam7d *= Math.max(0.50, otherRatio / Math.max(0.01, myDemandRatio)); + } + + // Near-reset 5h-drain-rate floor: if remaining 7d quota is close to the max physically drainable + // before reset (via 5h cap), drop shadow price aggressively so 0% expires unused! + const leftMs = Math.max(1, resetAt - nowMs); + const maxDrainable = Math.max(1, Math.ceil(leftMs / FIVE_HOURS_MS)) * acc.fiveHourLimit; + if (rem > maxDrainable * 0.65 || (leftMs < 24 * 3_600_000 && rem > fd.t3 * 0.55)) { + lam7d = Math.min(lam7d, 0.25e-6); + } else if (leftMs < 36 * 3_600_000 && rem > (fd.t3 + fd.t2) * 0.45) { + lam7d = Math.min(lam7d, 1.25e-6); + } + + // 5h protection during peak tier-3 crunch + let lam5h = 0; + const f5 = acc.fiveHourUsed / acc.fiveHourLimit; + if (t3Crunch5h) { + lam5h = 3.2e-6 + (f5 > 0.72 ? (f5 - 0.72) * 10.0e-6 : 0); + } else if (f5 > 0.80) { + lam5h = (f5 - 0.80) * 5.0e-6; + } + return lam7d + lam5h; + } + + const modesToTry = nextGap <= CACHE_5M_TTL_MS + ? [exactMode, '5m', 'none'] + : nextGap <= CACHE_1H_TTL_MS + ? [exactMode, '1h', 'none'] + : ['none']; + const uniqueModes = [...new Set(modesToTry)]; + + let bestChoice = null; + let bestScore = Number.POSITIVE_INFINITY; + + for (const acc of accounts) { + if (excluded.has(acc.id)) continue; + if (acc.capabilityTier < turn.minTier) continue; + if (acc.cooldownUntilMs !== null && nowMs < acc.cooldownUntilMs) continue; + if (isOutage(acc.id, nowMs)) continue; + if (acc.inFlight >= acc.maxInFlight) continue; + + const sameAsPrev = !turn.prevAccountId || turn.prevAccountId === acc.id; + const isWarm = sameAsPrev && acc.warmPrefixTokens > 0 && acc.warmExpiresAtMs !== null && nowMs <= acc.warmExpiresAtMs; + const cachedRead = isWarm ? Math.min(turn.prefixTokens, acc.warmPrefixTokens) : 0; + const handoff = turn.prevAccountId && turn.prevAccountId !== acc.id + ? Math.min(pool.handoffCapTokens, Math.round(turn.prefixTokens * pool.handoffRate)) + : 0; + + let shadowPerUnit = 0; + if (acc.kind === 'subscription') { + shadowPerUnit = subShadow(acc); + } else if (acc.kind === 'secondary') { + const f5 = acc.fiveHourUsed / acc.fiveHourLimit; + // During 5h tier-3 crunch, protect secondary-org from tier-2 (payg-t2 is $3.6/M, payg-t3 is $10/M!) + const lam5h = t3Crunch5h + ? 3.8e-6 + (f5 > 0.60 ? (f5 - 0.60) * 14.0e-6 : 0) + : (secT3Crunch5h && f5 > 0.55 ? 2.6e-6 + (f5 - 0.55) * 6.0e-6 : (f5 > 0.78 ? (f5 - 0.78) * 5.0e-6 : 0)); + const loadPen = acc.inFlight >= 3 ? 1.5e-6 : 0; + shadowPerUnit = lam5h + loadPen; + } + + const unitRate = acc.pricing.inputPerMTok / 1_000_000 + shadowPerUnit; + + for (const mode of uniqueModes) { + const billing = computeTurnBilling({ + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + outputTokens: outTokens, + cachedReadTokens: cachedRead, + handoffTokens: handoff, + cacheMode: mode, + pricing: acc.pricing, + quotaOutputWeight: 3.0, + meteredQuota: acc.fiveHourLimit !== null || acc.sevenDayLimit !== null, + }); + + if (acc.fiveHourLimit !== null && acc.fiveHourUsed + billing.quotaUnitsCharged > acc.fiveHourLimit) continue; + if (acc.sevenDayLimit !== null && acc.sevenDayUsed + billing.quotaUnitsCharged > acc.sevenDayLimit) continue; + + const nextWarmTokens = turn.prefixTokens + turn.newInputTokens + outTokens; + const willHitNext = (mode === '5m' && nextGap <= CACHE_5M_TTL_MS) || (mode === '1h' && nextGap <= CACHE_1H_TTL_MS); + let nextPrefixCost = 0; + if (Number.isFinite(nextGap)) { + if (willHitNext) { + nextPrefixCost = nextWarmTokens * 0.10 * unitRate; + } else if (mode === 'none' && isWarm && nextGap <= (acc.warmExpiresAtMs - nowMs)) { + const kept = Math.min(nextWarmTokens, acc.warmPrefixTokens); + nextPrefixCost = (kept * 0.10 + (nextWarmTokens - kept) * 1.0) * unitRate; + } else { + nextPrefixCost = nextWarmTokens * 1.15 * unitRate; + } + } + + const totalScore = billing.billedUsd + billing.quotaUnitsCharged * shadowPerUnit + nextPrefixCost; + if (totalScore < bestScore) { + bestScore = totalScore; + bestChoice = { accountId: acc.id, cacheMode: mode }; + } + } + } + + if (!bestChoice) { + const fallback = accounts + .filter((a) => !excluded.has(a.id) && a.capabilityTier >= turn.minTier) + .sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok)[0]; + return { accountId: fallback.id, cacheMode: 'none' }; + } + return bestChoice; + }, + onTurnResult() {}, + }; + } + + const clairvoyantSim = runSimulation({ + workload, + poolConfig, + createRouter: makeClairvoyantRouter, + }); + + return { + strict7dLowerBoundUsd: Number(strict7dLowerBoundUsd.toFixed(4)), + tightLowerBoundUsd: Number((strict7dLowerBoundUsd + peak5hExtraUsd).toFixed(4)), + clairvoyantSimUsd: clairvoyantSim.totalCostUsd, + clairvoyantSim, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/author/result-channel.mjs b/questions/opt-routing-cost-sim/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/candidate/CONTRACT.md b/questions/opt-routing-cost-sim/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..6e9f06b --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/CONTRACT.md @@ -0,0 +1,77 @@ +# Router & Simulator Contract + +This contract specifies the immutable billing/quota/prompt-cache physics (`sim/billing-sim.mjs`) and the causal online router interface (`src/router.mjs`). Within these invariants, you are free to implement any online algorithm inside `src/` (including helper modules imported by `src/router.mjs`). + +## 1. Public Router API (`src/router.mjs`) + +- Must export `createCostRouter(poolConfig)` returning `{ selectRoute(ctx), onTurnResult(outcome) }`. +- Both `poolConfig`, `ctx`, and `outcome` may be deeply frozen; mutating any input object is forbidden and fails `gate_causal_and_fast`. +- The router must be **strictly deterministic** (no `Math.random()`, no `Date.now()` wall-clock branching). + +### `poolConfig` +- `accounts`: array of 6 account specs (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), each with `{ id, kind, capabilityTier, pricing: { inputPerMTok, outputPerMTok, cacheReadMult, cacheWrite5mMult, cacheWrite1hMult }, quotaOutputWeight, fiveHourLimit, sevenDayLimit, maxInFlight, supportedCacheModes }`. +- `cacheTtlMs`: `{ '5m': 300_000, '1h': 3_600_000 }`. +- `handoffRate`: `0.08`, `handoffCapTokens`: `4000`, `retryDelayMs`: `1200`, `maxAttempts`: `4`. + +### `selectRoute(ctx)` → `{ accountId: string, cacheMode: 'none' | '5m' | '1h' }` +`ctx` contains ONLY causal present and past state (zero future lookahead, zero session archetype labels): +- `nowMs`: virtual timestamp (ms). +- `attempt`: `0 .. maxAttempts - 1`. +- `excludedAccountIds`: accounts already attempted and failed for this turn (must NOT be selected again). +- `turn`: `{ sessionId, turnIndex, minTier, prefixTokens, newInputTokens, estOutputTokens, prevAccountId, prevTurnAtMs, prevCacheMode, sessionTurnsSoFar, recentGapMsList }`. + - `estOutputTokens` is an unbiased estimate within ±12% of the turn's actual output tokens. + - `recentGapMsList` holds up to the last 8 observed inter-turn gaps (ms) in this session (empty on `turnIndex === 0`). +- `accounts`: snapshot of all 6 accounts at `nowMs`: + `{ id, kind, capabilityTier, pricing, fiveHourUsed, fiveHourLimit, fiveHourResetAtMs, sevenDayUsed, sevenDayLimit, sevenDayResetAtMs, inFlight, maxInFlight, cooldownUntilMs, warmPrefixTokens, warmExpiresAtMs }`. + - `warmPrefixTokens > 0 && warmExpiresAtMs !== null && nowMs <= warmExpiresAtMs` iff this session currently has a live warm prompt cache on that account (which requires continuing on `prevAccountId`). + +### `onTurnResult(outcome)` +Called after every attempt (both failed and succeeded): +- `{ nowMs, sessionId, accountId, cacheMode, ok, errorCode, billedUsd, quotaUnitsCharged, cachedReadTokens, actualOutputTokens, latencyMs }`. + +## 2. Exact Billing, Prompt-Cache & Quota Physics (`sim/billing-sim.mjs`) + +### Account Pool +| Account | Kind | Tier | Pricing (`$/MTok` in / out) | `5h` Cap (weighted tok) | `7d` Cap (weighted tok) | `maxInFlight` | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `sub-a` | `subscription` | 3 | `$0.00 / $0.00` | `1,900,000` | `15,500,000` | 4 | Staggered weekly `7d` reset; unused `7d` expires | +| `sub-b` | `subscription` | 3 | `$0.00 / $0.00` | `1,650,000` | `12,500,000` | 3 | Different staggered `7d` reset + occasional outages | +| `secondary-org` | `secondary` | 3 | `$1.50 / $7.50` | `1,550,000` | unlimited | 6 | Discounted org pool; transient 429 risk when `inFlight >= 3` or `5h >= 85%` | +| `payg-t1` | `payg` | 1 | `$0.50 / $2.50` | unlimited | unlimited | 64 | Unlimited PAYG fast/mini | +| `payg-t2` | `payg` | 2 | `$3.00 / $15.00` | unlimited | unlimited | 64 | Unlimited PAYG balanced | +| `payg-t3` | `payg` | 3 | `$10.00 / $30.00` | unlimited | unlimited | 64 | Unlimited PAYG frontier | + +All 6 accounts support `cacheMode` in `['none', '5m', '1h']`. + +### Prompt Cache & Handoff Arithmetic +For a turn `(prefixTokens, newInputTokens, actualOutputTokens)` served on `accountId` with `cacheMode`: +1. **Cache read**: If `(!prevAccountId || prevAccountId === accountId)` and a live cache exists for `(sessionId, accountId)` with `nowMs <= warm.expiresAtMs`, then `cachedReadTokens = min(prefixTokens, warm.warmPrefixTokens)`. Otherwise `cachedReadTokens = 0`. +2. **Cross-account handoff**: If `prevAccountId && prevAccountId !== accountId`, `handoffTokens = min(4000, Math.round(prefixTokens * 0.08))`; otherwise `0`. +3. **Uncached input**: `uncachedInputTokens = (prefixTokens - cachedReadTokens) + newInputTokens + handoffTokens`. +4. **Effective input tokens**: + - `'none'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.00` (leaves same-account warm entry unchanged; does not populate new cache). + - `'5m'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.25` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 300_000 }`). + - `'1h'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 2.00` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 3_600_000 }`). +5. **Dollar cost**: `billedUsd = (effectiveInputTokens * inputPerMTok + actualOutputTokens * outputPerMTok) / 1_000_000`. +6. **Quota units** (on accounts with finite `5h` or `7d` limits): `quotaUnitsCharged = effectiveInputTokens + 3.0 * actualOutputTokens`. + - `5h` rolling window starts on first spend (`fiveHourResetAtMs = nowMs + 5h`) and resets to `0` once `nowMs >= fiveHourResetAtMs`. + - `7d` weekly window resets on its staggered schedule (`sevenDayResetAtMs += 7d`); any unused `7d` quota expires at reset. + +### Failure, Outage & Retry Semantics +- An attempt fails (returning `errorCode` and incurring `1200 ms` stall delay before immediate re-query up to 4 attempts) if: + - `INVALID_ROUTE` (unknown account, excluded account, or invalid `cacheMode`), + - `COOLDOWN` (`nowMs < cooldownUntilMs`), + - `PROVIDER_OUTAGE` (scheduled outage; sets `cooldownUntilMs = nowMs + 180_000`), + - `CONCURRENCY_LIMIT` (`inFlight >= maxInFlight`), + - `RATE_LIMITED_7D` (`sevenDayUsed + quotaUnitsCharged > sevenDayLimit`), + - `RATE_LIMITED_5H` (`fiveHourUsed + quotaUnitsCharged > fiveHourLimit`), + - `TRANSIENT_429` (`secondary-org` load-dependent transient rate limit; sets `cooldownUntilMs = nowMs + 15_000`). +- Failing all 4 attempts drops the turn (`droppedTurns += 1`, failing `gate_all_served`). + +## 3. Hard Gates & Metric + +- `gate_all_served`: `droppedTurns === 0 && invalidDecisions === 0` across all unit tests, public trace, and unseen held-out traces. +- `gate_tier_floor`: `tierViolations === 0` (`capabilityTier >= turn.minTier` on 100% of turns). +- `gate_latency_sla`: `p99StallMs <= 3000` and `failedAttemptRate < 0.02` on every trace. +- `gate_causal_and_fast`: passes all frozen-context immutability and edge-case tests, deterministic, and `< 4000 ms` per 14-day simulation. +- **Primary metric**: `total_cost_usd` — mean 14-day USD bill across unseen held-out 14-day traces (lower is better, log-scaled between baseline and offline lower-bound target). diff --git a/questions/opt-routing-cost-sim/v1/candidate/ENVIRONMENT.md b/questions/opt-routing-cost-sim/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..9a166d6 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock and seeded deterministic traffic/failure generators — dollar cost, quota consumption, cache hits, and stall latencies are exact, hardware-independent numbers. +- Protected files: `sim/`, `bench/`, `tests/`, `package.json`, `TASK.md`, `CONTRACT.md`, `ENVIRONMENT.md` are read-only and verified by the submission gate; edit ONLY files under `src/`. +- Public checks: + - `npm test` — functional correctness, billing physics, immutability, determinism, and edge-case smoke tests + - `npm run bench` — deterministic 14-day public benchmark (2 distinct 14-day traces) reporting USD bill, per-account breakdown, expired `7d` quota, cache hit rate, latency SLA, and runtime diff --git a/questions/opt-routing-cost-sim/v1/candidate/TASK.md b/questions/opt-routing-cost-sim/v1/candidate/TASK.md new file mode 100644 index 0000000..3f45e35 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's online multi-account quota & prompt-cache cost router (`src/router.mjs`) extracted from production Smart Routing (`model-groups/pick.ts`, `turnRouting.ts`, `provider-group/scheduler.ts`, `usage/turnCostCalculator.ts`, and `agentcompass/engine/quota-economy.mjs`). + +## Observed Production Symptoms + +Over a realistic 14-day multi-turn coding and chat workload (~12,000 turns across ~600–750 sessions) sharing a **6-account multi-tier pool** (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), the current baseline router (`src/router.mjs`) racks up **~$800–$900 per 14 days** while leaving huge savings on the table: + +1. **Unprotected subscription quota**: Sends cheap `tier-1` (`$0.50/$2.50` PAYG alternative) and `tier-2` (`$3/$15`) turns straight onto scarce `$0`-marginal-cost subscriptions (`sub-a`, `sub-b`), burning weekly `7d` and rolling `5h` quotas early and forcing expensive `tier-3` (`$10/$30`) turns onto `payg-t3`. +2. **Rigid `'5m'`-only prompt caching**: Always sets `cacheMode: '5m'` on every turn: + - On **slow review/thinking sessions** (inter-turn gaps of 8–44 minutes), `'5m'` expires on every turn, re-paying `1.25×` write cost on growing 20k–80k prefixes instead of using `'1h'` (`2.0×` write once, `0.10×` reads thereafter). + - On **one-shot and ultra-sparse jobs** (including large batch summaries), `'5m'` pays an unnecessary `1.25×` write tax that is never read again instead of `'none'` (`1.0×`). + - On subscriptions (`sub-a`, `sub-b`), keeping warm prompt caches also stretches `5h` and `7d` quota **5–8× further** because cache reads consume only `0.10×` quota units. +3. **Cache-breaking transitions & binary cutoffs**: Breaks warm prompt caches blindly when crossing a fixed 85% `5h` cutoff or on concurrency ties, incurring both a cold re-write and an 8% cross-account handoff overhead (`min(4000, round(0.08 * prefixTokens))`). +4. **No online demand forecasting, shadow pricing, or staggered `7d` expiry pacing**: Fails to balance `sub-a` and `sub-b` across staggered weekly resets, weekday peaks vs quiet nights/weekends, `secondary-org` load-dependent transient 429s, and `sub-b` outage windows. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% of all four hard gates** (verified on unit edge cases, public traces, AND unseen held-out 14-day traces with different weekday/weekend phases, burst schedules, staggered reset offsets, session mixtures, and outages): + 1. `gate_all_served`: 100% of turns served (`0` dropped turns, `0` invalid routes). + 2. `gate_tier_floor`: 100% of turns routed to an account with `capabilityTier >= turn.minTier`. + 3. `gate_latency_sla`: P99 turn stall/retry delay `<= 3000 ms` and failed-attempt rate `< 2%`. + 4. `gate_causal_and_fast`: Strictly online/causal, never mutates frozen `ctx`/`outcome`/`poolConfig`, passes all edge-case checks, deterministic across runs, and completes each 14-day simulation in `< 4s`. +- **Open-ended optimization goal**: Design the strongest online routing & prompt-cache algorithm inside `src/` to drive the mean 14-day USD bill (`total_cost_usd`) as low as possible — without overfitting to public seeds! +- Run `npm test` and `npm run bench` to verify correctness and measure before/after savings. +- Record your analysis, algorithm design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;不可修改 `sim/`、`bench/`、`tests/`、`package.json`、`CONTRACT.md`、`ENVIRONMENT.md` 或 `TASK.md`。 diff --git a/questions/opt-routing-cost-sim/v1/candidate/bench/run-bench.mjs b/questions/opt-routing-cost-sim/v1/candidate/bench/run-bench.mjs new file mode 100644 index 0000000..ecf34d4 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/bench/run-bench.mjs @@ -0,0 +1,51 @@ +/** + * Public 14-day routing cost benchmark (protected read-only). + * Runs the 2 public 14-day scenarios with frozen contexts and reports full diagnostics. + */ + +import { createDefaultPoolConfig, runSimulation } from '../sim/billing-sim.mjs'; +import { PUBLIC_SCENARIOS, generateWorkload } from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +const poolConfig = createDefaultPoolConfig(); +let costSum = 0; +let allGatesPass = true; + +console.log('=== opt-routing-cost-sim Public 14-Day Benchmark ===\n'); + +for (const sc of PUBLIC_SCENARIOS) { + const workload = generateWorkload({ ...sc, poolConfig }); + const res = runSimulation({ + workload, + poolConfig, + createRouter: createCostRouter, + freezeCtx: true, + }); + + const servedOk = res.droppedTurns === 0 && res.invalidDecisions === 0; + const tierOk = res.tierViolations === 0; + const slaOk = res.p99StallMs <= 3000 && res.failedAttemptRate < 0.02; + const fastOk = res.runtimeMs < 4000; + const pass = servedOk && tierOk && slaOk && fastOk; + if (!pass) allGatesPass = false; + + costSum += res.totalCostUsd; + + console.log(`[${sc.name}] sessions=${workload.summary.sessions} turns=${res.totalTurns}`); + console.log(` Total 14d Cost : $${res.totalCostUsd.toFixed(2)}`); + console.log(` Gates : served=${servedOk} tierFloor=${tierOk} latencySla=${slaOk} fast=${fastOk}`); + console.log(` SLA & Perf : p99Stall=${res.p99StallMs}ms failRate=${(res.failedAttemptRate * 100).toFixed(2)}% runtime=${res.runtimeMs.toFixed(1)}ms`); + console.log(` Prompt Cache : hitRate=${(res.cacheStats.cacheHitRate * 100).toFixed(1)}% handoffTok=${res.cacheStats.handoffTokens} modes=${JSON.stringify(res.cacheStats.byMode)}`); + console.log(` Expired 7d Quota : sub-a=${(res.expiredQuotaUnits['sub-a'] / 1e6).toFixed(2)}M sub-b=${(res.expiredQuotaUnits['sub-b'] / 1e6).toFixed(2)}M`); + console.log(' Account Breakdown:'); + for (const [id, st] of Object.entries(res.byAccount)) { + console.log( + ` ${id.padEnd(14)} turns=${String(st.turns).padStart(5)} usd=$${st.billedUsd.toFixed(2).padStart(7)} quota=${(st.quotaUnits / 1e6).toFixed(2).padStart(5)}M fails=${String(st.failedAttempts).padStart(3)} modes=${JSON.stringify(st.cacheModes)}`, + ); + } + console.log(''); +} + +const meanCost = costSum / PUBLIC_SCENARIOS.length; +console.log(`Public Mean 14-day Cost: $${meanCost.toFixed(2)} (gates=${allGatesPass ? 'PASS' : 'FAIL'})`); +if (!allGatesPass) process.exitCode = 1; diff --git a/questions/opt-routing-cost-sim/v1/candidate/package.json b/questions/opt-routing-cost-sim/v1/candidate/package.json new file mode 100644 index 0000000..d840cd2 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-routing-cost-sim", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/run-bench.mjs" + } +} diff --git a/questions/opt-routing-cost-sim/v1/candidate/sim/billing-sim.mjs b/questions/opt-routing-cost-sim/v1/candidate/sim/billing-sim.mjs new file mode 100644 index 0000000..116e455 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/sim/billing-sim.mjs @@ -0,0 +1,697 @@ +/** + * Immutable 14-day multi-account billing, quota, concurrency, and prompt-cache simulator. + * Protected read-only: candidates must optimize `src/router.mjs` against this exact physics engine. + */ + +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +export const CACHE_5M_TTL_MS = 5 * 60_000; +export const CACHE_1H_TTL_MS = 60 * 60_000; + +export const VALID_CACHE_MODES = Object.freeze(['none', '5m', '1h']); +const VALID_CACHE_MODE_SET = new Set(VALID_CACHE_MODES); + +export const DEFAULT_HANDOFF_RATE = 0.08; +export const DEFAULT_HANDOFF_CAP_TOKENS = 4000; +export const DEFAULT_RETRY_DELAY_MS = 1200; +export const DEFAULT_MAX_ATTEMPTS = 4; +export const DEFAULT_QUOTA_OUTPUT_WEIGHT = 3.0; +export const OUTAGE_COOLDOWN_MS = 180_000; + +export function createDefaultPoolConfig(overrides = {}) { + const baseAccounts = [ + { + id: 'sub-a', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subAFiveHourLimit ?? 1_900_000, + sevenDayLimit: overrides.subASevenDayLimit ?? 15_500_000, + maxInFlight: 4, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'sub-b', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subBFiveHourLimit ?? 1_650_000, + sevenDayLimit: overrides.subBSevenDayLimit ?? 12_500_000, + maxInFlight: 3, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'secondary-org', + kind: 'secondary', + capabilityTier: 3, + pricing: { + inputPerMTok: 1.50, + outputPerMTok: 7.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.secondaryFiveHourLimit ?? 1_550_000, + sevenDayLimit: null, + maxInFlight: 6, + supportedCacheModes: ['none', '5m', '1h'], + transient429: { + inFlightThreshold: 3, + inFlightProbStep: 0.10, + fiveHourFracThreshold: 0.85, + fiveHourProb: 0.14, + cooldownMs: 15_000, + }, + }, + { + id: 'payg-t1', + kind: 'payg', + capabilityTier: 1, + pricing: { + inputPerMTok: 0.50, + outputPerMTok: 2.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t2', + kind: 'payg', + capabilityTier: 2, + pricing: { + inputPerMTok: 3.00, + outputPerMTok: 15.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t3', + kind: 'payg', + capabilityTier: 3, + pricing: { + inputPerMTok: 10.00, + outputPerMTok: 30.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + ]; + + return { + accounts: baseAccounts, + cacheTtlMs: { + '5m': CACHE_5M_TTL_MS, + '1h': CACHE_1H_TTL_MS, + }, + handoffRate: DEFAULT_HANDOFF_RATE, + handoffCapTokens: DEFAULT_HANDOFF_CAP_TOKENS, + retryDelayMs: DEFAULT_RETRY_DELAY_MS, + maxAttempts: DEFAULT_MAX_ATTEMPTS, + }; +} + +export function cacheWriteMultiplier(pricing, cacheMode) { + if (cacheMode === '5m') return pricing.cacheWrite5mMult; + if (cacheMode === '1h') return pricing.cacheWrite1hMult; + return 1.0; +} + +export function computeTurnBilling({ + prefixTokens, + newInputTokens, + outputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing, + quotaOutputWeight = DEFAULT_QUOTA_OUTPUT_WEIGHT, + meteredQuota = false, +}) { + const safeCached = Math.max(0, Math.min(prefixTokens, cachedReadTokens)); + const uncachedInputTokens = (prefixTokens - safeCached) + newInputTokens + handoffTokens; + const writeMult = cacheWriteMultiplier(pricing, cacheMode); + const readMult = pricing.cacheReadMult; + const effectiveInputTokens = safeCached * readMult + uncachedInputTokens * writeMult; + const billedUsd = (effectiveInputTokens * pricing.inputPerMTok + outputTokens * pricing.outputPerMTok) / 1_000_000; + const quotaUnitsCharged = meteredQuota ? effectiveInputTokens + quotaOutputWeight * outputTokens : 0; + return { + cachedReadTokens: safeCached, + uncachedInputTokens, + effectiveInputTokens, + billedUsd, + quotaUnitsCharged, + }; +} + +function deepFreeze(obj) { + if (!obj || typeof obj !== 'object' || Object.isFrozen(obj)) return obj; + Object.freeze(obj); + for (const val of Object.values(obj)) { + deepFreeze(val); + } + return obj; +} + +function deterministicUnitHash(seed, turnId, attempt, accountId) { + let h = (2166136261 ^ (seed >>> 0)) >>> 0; + const str = `${turnId}|${attempt}|${accountId}`; + for (let i = 0; i < str.length; i += 1) { + h ^= str.charCodeAt(i); + h = Math.imul(h, 16777619) >>> 0; + } + h ^= h >>> 16; + h = Math.imul(h, 0x7feb352d) >>> 0; + h ^= h >>> 15; + h = Math.imul(h, 0x846ca68b) >>> 0; + h ^= h >>> 16; + return (h >>> 0) / 4294967296; +} + +function percentile(sorted, p) { + if (sorted.length === 0) return 0; + const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1)); + return sorted[idx]; +} + +function clonePublicPoolConfig(poolConfig) { + return { + accounts: poolConfig.accounts.map((a) => ({ + id: a.id, + kind: a.kind, + capabilityTier: a.capabilityTier, + pricing: { ...a.pricing }, + quotaOutputWeight: a.quotaOutputWeight, + fiveHourLimit: a.fiveHourLimit, + sevenDayLimit: a.sevenDayLimit, + maxInFlight: a.maxInFlight, + supportedCacheModes: [...a.supportedCacheModes], + })), + cacheTtlMs: { ...poolConfig.cacheTtlMs }, + handoffRate: poolConfig.handoffRate, + handoffCapTokens: poolConfig.handoffCapTokens, + retryDelayMs: poolConfig.retryDelayMs, + maxAttempts: poolConfig.maxAttempts, + }; +} + +/** + * Runs a complete deterministic simulation over a workload trace. + * + * @param {object} params + * @param {object} params.workload - Output of generateWorkload() or custom unit-test workload + * @param {object} [params.poolConfig] - Account pool specification + * @param {Function} params.createRouter - Factory `(poolConfig) => ({ selectRoute, onTurnResult })` + * @param {boolean} [params.freezeCtx=false] - Deep-freeze ctx/outcome objects to enforce immutability + */ +export function runSimulation({ + workload, + poolConfig = createDefaultPoolConfig(), + createRouter, + freezeCtx = false, +}) { + const tStart = performance.now(); + const publicPool = clonePublicPoolConfig(poolConfig); + if (freezeCtx) deepFreeze(publicPool); + + const router = createRouter(publicPool); + if (!router || typeof router.selectRoute !== 'function' || typeof router.onTurnResult !== 'function') { + throw new Error('createCostRouter(poolConfig) must return { selectRoute, onTurnResult }'); + } + + const startMs = workload.startMs; + const initialAccountState = workload.initialAccountState ?? {}; + const outages = workload.outages ?? []; + const seed = workload.seed ?? 1; + + // Group outages by accountId for fast lookup + const outagesByAccount = new Map(); + for (const o of outages) { + let list = outagesByAccount.get(o.accountId); + if (!list) { + list = []; + outagesByAccount.set(o.accountId, list); + } + list.push(o); + } + + const accounts = poolConfig.accounts.map((cfg) => { + const init = initialAccountState[cfg.id] ?? {}; + return { + cfg, + id: cfg.id, + fiveHourUsed: init.fiveHourUsed ?? 0, + fiveHourResetAtMs: cfg.fiveHourLimit !== null ? (init.fiveHourResetAtMs ?? null) : null, + sevenDayUsed: init.sevenDayUsed ?? 0, + sevenDayResetAtMs: cfg.sevenDayLimit !== null ? (init.sevenDayResetAtMs ?? (startMs + SEVEN_DAYS_MS)) : null, + cooldownUntilMs: init.cooldownUntilMs ?? null, + activeEnds: [], + stats: { + turns: 0, + billedUsd: 0, + quotaUnits: 0, + cachedReadTokens: 0, + uncachedInputTokens: 0, + handoffTokens: 0, + outputTokens: 0, + failedAttempts: 0, + cacheModes: { none: 0, '5m': 0, '1h': 0 }, + }, + }; + }); + const accountById = new Map(accounts.map((a) => [a.id, a])); + const expiredQuotaUnits = Object.fromEntries( + accounts.filter((a) => a.cfg.sevenDayLimit !== null).map((a) => [a.id, 0]), + ); + + // Per-session runtime state: { prevAccountId, prevTurnAtMs, prevCacheMode, turnsSoFar, recentGapMsList, warm: { accountId, warmPrefixTokens, expiresAtMs } | null } + const sessions = new Map(); + + let totalCostUsd = 0; + let servedTurns = 0; + let droppedTurns = 0; + let tierViolations = 0; + let invalidDecisions = 0; + let totalAttempts = 0; + let failedAttempts = 0; + let totalPrefixTokens = 0; + let totalCachedReadTokens = 0; + let totalHandoffTokens = 0; + const cacheModeCounts = { none: 0, '5m': 0, '1h': 0 }; + const byTier = { + 1: { turns: 0, billedUsd: 0, byAccount: {} }, + 2: { turns: 0, billedUsd: 0, byAccount: {} }, + 3: { turns: 0, billedUsd: 0, byAccount: {} }, + }; + const stallDelays = []; + + function syncAccounts(nowMs) { + for (const acc of accounts) { + // Retire finished in-flight turns + if (acc.activeEnds.length > 0) { + let writeIdx = 0; + for (let i = 0; i < acc.activeEnds.length; i += 1) { + if (acc.activeEnds[i] > nowMs) { + acc.activeEnds[writeIdx] = acc.activeEnds[i]; + writeIdx += 1; + } + } + acc.activeEnds.length = writeIdx; + } + + // Reset expired 5h rolling window + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourResetAtMs !== null && nowMs >= acc.fiveHourResetAtMs) { + acc.fiveHourUsed = 0; + acc.fiveHourResetAtMs = null; + } + + // Reset expired 7d weekly window(s) + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayResetAtMs !== null && nowMs >= acc.sevenDayResetAtMs) { + const wasted = Math.max(0, acc.cfg.sevenDayLimit - acc.sevenDayUsed); + expiredQuotaUnits[acc.id] += wasted; + const periods = Math.floor((nowMs - acc.sevenDayResetAtMs) / SEVEN_DAYS_MS) + 1; + if (periods > 1) { + expiredQuotaUnits[acc.id] += (periods - 1) * acc.cfg.sevenDayLimit; + } + acc.sevenDayResetAtMs += periods * SEVEN_DAYS_MS; + acc.sevenDayUsed = 0; + } + + // Clear expired cooldown + if (acc.cooldownUntilMs !== null && nowMs >= acc.cooldownUntilMs) { + acc.cooldownUntilMs = null; + } + } + } + + function isInOutage(accountId, nowMs) { + const list = outagesByAccount.get(accountId); + if (!list) return false; + for (let i = 0; i < list.length; i += 1) { + const o = list[i]; + if (nowMs >= o.startMs && nowMs < o.endMs) return true; + } + return false; + } + + function checkTransient429(acc, turnId, attempt, nowMs) { + const tCfg = acc.cfg.transient429; + if (!tCfg) return false; + let prob = 0; + const inFlight = acc.activeEnds.length; + if (inFlight >= tCfg.inFlightThreshold) { + prob = Math.max(prob, (inFlight - tCfg.inFlightThreshold + 1) * tCfg.inFlightProbStep); + } + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed / acc.cfg.fiveHourLimit >= tCfg.fiveHourFracThreshold) { + prob = Math.max(prob, tCfg.fiveHourProb); + } + if (prob <= 0) return false; + const u = deterministicUnitHash(seed, turnId, attempt, acc.id); + if (u < prob) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, nowMs + tCfg.cooldownMs); + return true; + } + return false; + } + + const turns = workload.turns; + const maxAttempts = poolConfig.maxAttempts ?? DEFAULT_MAX_ATTEMPTS; + const retryDelayMs = poolConfig.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; + const handoffRate = poolConfig.handoffRate ?? DEFAULT_HANDOFF_RATE; + const handoffCapTokens = poolConfig.handoffCapTokens ?? DEFAULT_HANDOFF_CAP_TOKENS; + + for (let ti = 0; ti < turns.length; ti += 1) { + const turn = turns[ti]; + let sess = sessions.get(turn.sessionId); + if (!sess) { + sess = { + prevAccountId: null, + prevTurnAtMs: null, + prevCacheMode: null, + turnsSoFar: 0, + recentGapMsList: [], + warm: null, + }; + sessions.set(turn.sessionId, sess); + } + + const excluded = []; + let attemptNowMs = turn.arrivalMs; + let stallDelayMs = 0; + let served = false; + + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + totalAttempts += 1; + syncAccounts(attemptNowMs); + + // Clear expired warm entry for this session + if (sess.warm && attemptNowMs > sess.warm.expiresAtMs) { + sess.warm = null; + } + + const accountsSnapshot = accounts.map((acc) => { + const isWarmHere = sess.warm !== null + && sess.prevAccountId === acc.id + && sess.warm.accountId === acc.id + && attemptNowMs <= sess.warm.expiresAtMs; + return { + id: acc.id, + kind: acc.cfg.kind, + capabilityTier: acc.cfg.capabilityTier, + pricing: { ...acc.cfg.pricing }, + fiveHourUsed: acc.fiveHourUsed, + fiveHourLimit: acc.cfg.fiveHourLimit, + fiveHourResetAtMs: acc.fiveHourResetAtMs, + sevenDayUsed: acc.sevenDayUsed, + sevenDayLimit: acc.cfg.sevenDayLimit, + sevenDayResetAtMs: acc.sevenDayResetAtMs, + inFlight: acc.activeEnds.length, + maxInFlight: acc.cfg.maxInFlight, + cooldownUntilMs: acc.cooldownUntilMs, + warmPrefixTokens: isWarmHere ? sess.warm.warmPrefixTokens : 0, + warmExpiresAtMs: isWarmHere ? sess.warm.expiresAtMs : null, + }; + }); + + const ctx = { + nowMs: attemptNowMs, + attempt, + excludedAccountIds: [...excluded], + turn: { + sessionId: turn.sessionId, + turnIndex: turn.turnIndex, + minTier: turn.minTier, + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + estOutputTokens: turn.estOutputTokens, + prevAccountId: sess.prevAccountId, + prevTurnAtMs: sess.prevTurnAtMs, + prevCacheMode: sess.prevCacheMode, + sessionTurnsSoFar: sess.turnsSoFar, + recentGapMsList: [...sess.recentGapMsList], + }, + accounts: accountsSnapshot, + }; + if (freezeCtx) deepFreeze(ctx); + + const decision = router.selectRoute(ctx); + const accountId = decision && typeof decision.accountId === 'string' ? decision.accountId : ''; + const cacheMode = decision && typeof decision.cacheMode === 'string' ? decision.cacheMode : ''; + const acc = accountById.get(accountId); + + let errorCode = null; + if (!acc || !VALID_CACHE_MODE_SET.has(cacheMode) || excluded.includes(accountId)) { + errorCode = 'INVALID_ROUTE'; + invalidDecisions += 1; + } else if (acc.cooldownUntilMs !== null && attemptNowMs < acc.cooldownUntilMs) { + errorCode = 'COOLDOWN'; + } else if (isInOutage(accountId, attemptNowMs)) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, attemptNowMs + OUTAGE_COOLDOWN_MS); + errorCode = 'PROVIDER_OUTAGE'; + } else if (acc.activeEnds.length >= acc.cfg.maxInFlight) { + errorCode = 'CONCURRENCY_LIMIT'; + } + + // Compute exact billing & quota units for admission check + let billing = null; + let handoffTokens = 0; + if (!errorCode) { + const sameAsPrev = !sess.prevAccountId || sess.prevAccountId === accountId; + const isWarmHit = sameAsPrev + && sess.warm !== null + && sess.warm.accountId === accountId + && attemptNowMs <= sess.warm.expiresAtMs; + const cachedReadTokens = isWarmHit ? Math.min(turn.prefixTokens, sess.warm.warmPrefixTokens) : 0; + handoffTokens = sess.prevAccountId && sess.prevAccountId !== accountId + ? Math.min(handoffCapTokens, Math.round(turn.prefixTokens * handoffRate)) + : 0; + const meteredQuota = acc.cfg.fiveHourLimit !== null || acc.cfg.sevenDayLimit !== null; + billing = computeTurnBilling({ + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + outputTokens: turn.actualOutputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing: acc.cfg.pricing, + quotaOutputWeight: acc.cfg.quotaOutputWeight, + meteredQuota, + }); + + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayUsed + billing.quotaUnitsCharged > acc.cfg.sevenDayLimit) { + errorCode = 'RATE_LIMITED_7D'; + } else if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed + billing.quotaUnitsCharged > acc.cfg.fiveHourLimit) { + errorCode = 'RATE_LIMITED_5H'; + } else if (checkTransient429(acc, turn.turnId, attempt, attemptNowMs)) { + errorCode = 'TRANSIENT_429'; + } + } + + if (errorCode) { + failedAttempts += 1; + if (acc) acc.stats.failedAttempts += 1; + stallDelayMs += retryDelayMs; + attemptNowMs += retryDelayMs; + if (accountId && !excluded.includes(accountId)) excluded.push(accountId); + const failOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode: VALID_CACHE_MODE_SET.has(cacheMode) ? cacheMode : 'none', + ok: false, + errorCode, + billedUsd: 0, + quotaUnitsCharged: 0, + cachedReadTokens: 0, + actualOutputTokens: 0, + latencyMs: retryDelayMs, + }; + if (freezeCtx) deepFreeze(failOutcome); + router.onTurnResult(failOutcome); + continue; + } + + // Success! + served = true; + servedTurns += 1; + if (acc.cfg.capabilityTier < turn.minTier) { + tierViolations += 1; + } + + if (acc.cfg.fiveHourLimit !== null) { + if (acc.fiveHourResetAtMs === null) { + acc.fiveHourResetAtMs = attemptNowMs + FIVE_HOURS_MS; + } + acc.fiveHourUsed += billing.quotaUnitsCharged; + } + if (acc.cfg.sevenDayLimit !== null) { + acc.sevenDayUsed += billing.quotaUnitsCharged; + } + + acc.activeEnds.push(attemptNowMs + turn.serviceDurationMs); + + // Update cache state + const switchedAccount = sess.prevAccountId !== null && sess.prevAccountId !== accountId; + if (switchedAccount) { + sess.warm = null; + } + const nextWarmPrefix = turn.prefixTokens + turn.newInputTokens + turn.actualOutputTokens; + if (cacheMode === '5m') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['5m'], + }; + } else if (cacheMode === '1h') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['1h'], + }; + } + // If cacheMode === 'none': warm is unchanged on same account (already cleared if switched or expired) + + if (sess.prevTurnAtMs !== null) { + const gapMs = Math.max(0, attemptNowMs - sess.prevTurnAtMs); + sess.recentGapMsList.push(gapMs); + if (sess.recentGapMsList.length > 8) sess.recentGapMsList.shift(); + } + sess.prevAccountId = accountId; + sess.prevTurnAtMs = attemptNowMs; + sess.prevCacheMode = cacheMode; + sess.turnsSoFar += 1; + + totalCostUsd += billing.billedUsd; + totalPrefixTokens += turn.prefixTokens; + totalCachedReadTokens += billing.cachedReadTokens; + totalHandoffTokens += handoffTokens; + cacheModeCounts[cacheMode] += 1; + + acc.stats.turns += 1; + acc.stats.billedUsd += billing.billedUsd; + acc.stats.quotaUnits += billing.quotaUnitsCharged; + acc.stats.cachedReadTokens += billing.cachedReadTokens; + acc.stats.uncachedInputTokens += billing.uncachedInputTokens; + acc.stats.handoffTokens += handoffTokens; + acc.stats.outputTokens += turn.actualOutputTokens; + acc.stats.cacheModes[cacheMode] += 1; + + const tierBucket = byTier[turn.minTier]; + if (tierBucket) { + tierBucket.turns += 1; + tierBucket.billedUsd += billing.billedUsd; + tierBucket.byAccount[accountId] = (tierBucket.byAccount[accountId] ?? 0) + 1; + } + + const okOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode, + ok: true, + errorCode: null, + billedUsd: billing.billedUsd, + quotaUnitsCharged: billing.quotaUnitsCharged, + cachedReadTokens: billing.cachedReadTokens, + actualOutputTokens: turn.actualOutputTokens, + latencyMs: stallDelayMs + turn.serviceDurationMs, + }; + if (freezeCtx) deepFreeze(okOutcome); + router.onTurnResult(okOutcome); + break; + } + + if (!served) { + droppedTurns += 1; + } + stallDelays.push(stallDelayMs); + } + + // Final sync at end of simulation horizon to count any final-window reset + if (workload.endMs) { + syncAccounts(workload.endMs); + } + + stallDelays.sort((a, b) => a - b); + const runtimeMs = performance.now() - tStart; + + const byAccount = {}; + for (const acc of accounts) { + byAccount[acc.id] = { + ...acc.stats, + billedUsd: Number(acc.stats.billedUsd.toFixed(4)), + quotaUnits: Math.round(acc.stats.quotaUnits), + cacheModes: { ...acc.stats.cacheModes }, + }; + } + for (const t of [1, 2, 3]) { + byTier[t].billedUsd = Number(byTier[t].billedUsd.toFixed(4)); + } + + return { + totalCostUsd: Number(totalCostUsd.toFixed(4)), + totalTurns: turns.length, + servedTurns, + droppedTurns, + tierViolations, + invalidDecisions, + totalAttempts, + failedAttempts, + failedAttemptRate: totalAttempts > 0 ? failedAttempts / totalAttempts : 0, + p50StallMs: percentile(stallDelays, 0.50), + p95StallMs: percentile(stallDelays, 0.95), + p99StallMs: percentile(stallDelays, 0.99), + maxStallMs: stallDelays.length > 0 ? stallDelays[stallDelays.length - 1] : 0, + runtimeMs: Number(runtimeMs.toFixed(2)), + byAccount, + byTier, + expiredQuotaUnits: Object.fromEntries( + Object.entries(expiredQuotaUnits).map(([k, v]) => [k, Math.round(v)]), + ), + cacheStats: { + totalPrefixTokens, + totalCachedReadTokens, + cacheHitRate: totalPrefixTokens > 0 ? totalCachedReadTokens / totalPrefixTokens : 0, + handoffTokens: totalHandoffTokens, + byMode: { ...cacheModeCounts }, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/candidate/sim/workload-generator.mjs b/questions/opt-routing-cost-sim/v1/candidate/sim/workload-generator.mjs new file mode 100644 index 0000000..6050bcf --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/sim/workload-generator.mjs @@ -0,0 +1,370 @@ +/** + * Deterministic 14-day multi-turn session & traffic workload generator. + * Parameterized by seed and scenario profile; produces causal turn traces with zero hidden archetype hints. + */ + +import { FIVE_HOURS_MS, SEVEN_DAYS_MS, createDefaultPoolConfig } from './billing-sim.mjs'; + +const MINUTE_MS = 60_000; +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; +export const HORIZON_DAYS = 14; +export const HORIZON_MS = HORIZON_DAYS * DAY_MS; + +// Default Monday 2026-01-05 00:00:00 UTC +export const DEFAULT_START_MS = Date.UTC(2026, 0, 5, 0, 0, 0); + +function mulberry32(seed) { + let a = seed >>> 0; + return function rng() { + a = (a + 0x6d2b79f5) >>> 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function randRange(rng, lo, hi) { + return lo + (hi - lo) * rng(); +} + +function randInt(rng, lo, hi) { + return Math.floor(randRange(rng, lo, hi + 1)); +} + +function pickWeighted(rng, entries) { + let total = 0; + for (const [, w] of entries) total += w; + let r = rng() * total; + for (const [val, w] of entries) { + r -= w; + if (r <= 0) return val; + } + return entries[entries.length - 1][0]; +} + +// Realistic weekday hourly demand weights (0..23h local work clock), peaks at 10-12h & 14-18h. +const DEFAULT_WEEKDAY_HOURLY = [ + 0.14, 0.10, 0.08, 0.07, 0.08, 0.12, + 0.24, 0.45, 0.85, 1.35, 1.75, 1.85, + 1.30, 1.55, 1.95, 2.05, 1.90, 1.60, + 1.10, 0.78, 0.62, 0.48, 0.34, 0.22, +]; + +const DEFAULT_WEEKEND_HOURLY = [ + 0.10, 0.08, 0.06, 0.06, 0.06, 0.08, + 0.12, 0.18, 0.30, 0.48, 0.62, 0.68, + 0.65, 0.70, 0.72, 0.68, 0.60, 0.52, + 0.46, 0.42, 0.38, 0.30, 0.22, 0.14, +]; + +export const PUBLIC_SCENARIOS = [ + { + name: 'public-standard-mon', + seed: 20260401, + startDayOfWeek: 0, // Monday + subAResetOffsetHours: 2 * 24 + 8, // Day 2 08:00 & Day 9 08:00 + subBResetOffsetHours: 5 * 24 + 18, // Day 5 18:00 & Day 12 18:00 + subAInitialUsedFrac: 0.56, + subBInitialUsedFrac: 0.18, + demandMultiplier: 1.04, + weekendDipFactor: 0.42, + burstIntensity: 1.0, + archetypeWeights: { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ], + }, + { + name: 'public-shifted-thu', + seed: 20260402, + startDayOfWeek: 3, // Thursday + subAResetOffsetHours: 1 * 24 + 16, // Day 1 16:00 & Day 8 16:00 + subBResetOffsetHours: 4 * 24 + 10, // Day 4 10:00 & Day 11 10:00 + subAInitialUsedFrac: 0.68, + subBInitialUsedFrac: 0.34, + demandMultiplier: 1.08, + weekendDipFactor: 0.36, + burstIntensity: 1.12, + archetypeWeights: { + rapidCoding: 0.35, + reviewThinking: 0.11, + mixedCadence: 0.08, + oneShotSparse: 0.20, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 5 * 24 + 14.5, durationMin: 70 }, + { accountId: 'sub-b', startHour: 11 * 24 + 16.0, durationMin: 60 }, + ], + }, +]; + +/** + * Generates a deterministic 14-day multi-turn workload trace. + * Turn objects carry ZERO archetype hints — routers must infer patterns online. + */ +export function generateWorkload(options = {}) { + const seed = options.seed ?? 20260401; + const rng = mulberry32(seed); + const poolConfig = options.poolConfig ?? createDefaultPoolConfig(); + const startDayOfWeek = ((options.startDayOfWeek ?? 0) % 7 + 7) % 7; // 0=Mon..6=Sun + const startMs = options.startMs ?? (DEFAULT_START_MS + startDayOfWeek * DAY_MS); + const endMs = startMs + HORIZON_MS; + + const demandMultiplier = options.demandMultiplier ?? 1.0; + const weekendDipFactor = options.weekendDipFactor ?? 0.42; + const burstIntensity = options.burstIntensity ?? 1.0; + const weights = options.archetypeWeights ?? { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }; + const archetypeEntries = [ + ['rapidCoding', weights.rapidCoding], + ['reviewThinking', weights.reviewThinking], + ['mixedCadence', weights.mixedCadence], + ['oneShotSparse', weights.oneShotSparse], + ['largeOneShot', weights.largeOneShot], + ]; + + // Generate 3-4 realistic weekday burst episodes (e.g., release crunch / incident response) + const burstWindows = []; + for (let day = 0; day < HORIZON_DAYS; day += 1) { + const dow = (startDayOfWeek + day) % 7; + if (dow >= 5) continue; // bursts happen on weekdays + if (rng() < 0.38 * burstIntensity) { + const startHour = day * 24 + randRange(rng, 9.5, 15.5); + const durationHours = randRange(rng, 2.2, 4.0); + burstWindows.push({ + startHour, + endHour: startHour + durationHours, + mult: randRange(rng, 1.55, 2.15) * burstIntensity, + }); + } + } + + // Compute hourly session arrival rates targeting ~740 sessions -> ~11,500-12,500 turns over 14 days + const hourRates = new Array(HORIZON_DAYS * 24); + let rateSum = 0; + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const day = Math.floor(h / 24); + const hourOfDay = h % 24; + const dow = (startDayOfWeek + day) % 7; + const isWeekend = dow >= 5; + let rate = isWeekend + ? DEFAULT_WEEKEND_HOURLY[hourOfDay] * (weekendDipFactor / 0.42) + : DEFAULT_WEEKDAY_HOURLY[hourOfDay]; + for (const bw of burstWindows) { + if (h + 0.5 >= bw.startHour && h + 0.5 <= bw.endHour) { + rate *= bw.mult; + } + } + hourRates[h] = rate; + rateSum += rate; + } + + const targetSessions = Math.round(700 * demandMultiplier); + const turns = []; + let sessionSeq = 0; + let turnSeq = 0; + + // Also keep ground-truth session summaries for offline oracle / diagnostics (never passed to router!) + const sessionMeta = []; + + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const expected = (hourRates[h] / rateSum) * targetSessions; + // Poisson draw using Knuth algorithm + const L = Math.exp(-expected); + let k = 0; + let p = 1.0; + do { + k += 1; + p *= rng(); + } while (p > L); + const count = Math.max(0, k - 1); + + for (let s = 0; s < count; s += 1) { + sessionSeq += 1; + const sessionId = `s-${String(sessionSeq).padStart(4, '0')}`; + const archetype = pickWeighted(rng, archetypeEntries); + const sessionStartMs = startMs + h * HOUR_MS + Math.floor(rng() * HOUR_MS); + + let minTier; + let numTurns; + let initPrefix; + + if (archetype === 'rapidCoding') { + minTier = pickWeighted(rng, [[3, 0.37], [2, 0.25], [1, 0.38]]); + numTurns = randInt(rng, 28, 48); + initPrefix = randInt(rng, 5500, 12500); + } else if (archetype === 'reviewThinking') { + minTier = pickWeighted(rng, [[3, 0.56], [2, 0.34], [1, 0.10]]); + numTurns = randInt(rng, 9, 15); + initPrefix = randInt(rng, 11000, 21000); + } else if (archetype === 'mixedCadence') { + minTier = pickWeighted(rng, [[3, 0.50], [2, 0.32], [1, 0.18]]); + numTurns = randInt(rng, 14, 23); + initPrefix = randInt(rng, 8000, 15000); + } else if (archetype === 'oneShotSparse') { + minTier = pickWeighted(rng, [[1, 0.64], [2, 0.22], [3, 0.14]]); + numTurns = pickWeighted(rng, [[1, 0.66], [2, 0.24], [3, 0.10]]); + initPrefix = randInt(rng, 900, 3600); + } else { + // largeOneShot: single-turn batch summarization, PR diff digest, cron synthesis + minTier = pickWeighted(rng, [[1, 0.66], [2, 0.20], [3, 0.14]]); + numTurns = 1; + initPrefix = randInt(rng, 1000, 3500); + } + + const splitPoint = archetype === 'mixedCadence' ? randInt(rng, 5, Math.max(6, Math.floor(numTurns * 0.45))) : 0; + + let curMs = sessionStartMs; + let curPrefix = initPrefix; + let sessionTurnsAdded = 0; + + for (let ti = 0; ti < numTurns; ti += 1) { + if (curMs >= endMs - 60_000) break; + + let newInputTokens; + let actualOutputTokens; + if (archetype === 'rapidCoding') { + newInputTokens = randInt(rng, 850, 2400); + actualOutputTokens = randInt(rng, 450, 1600); + } else if (archetype === 'reviewThinking') { + newInputTokens = randInt(rng, 1300, 3600); + actualOutputTokens = randInt(rng, 900, 2600); + } else if (archetype === 'mixedCadence') { + newInputTokens = randInt(rng, 1000, 2800); + actualOutputTokens = randInt(rng, 650, 1950); + } else if (archetype === 'oneShotSparse') { + newInputTokens = randInt(rng, 600, 2200); + actualOutputTokens = randInt(rng, 300, 1100); + } else { + // largeOneShot + newInputTokens = randInt(rng, 14000, 36000); + actualOutputTokens = randInt(rng, 800, 2600); + } + + const estOutputTokens = Math.max(100, Math.round(actualOutputTokens * randRange(rng, 0.88, 1.12))); + // Realistic LLM streaming turn latency (~8-32s -> natural concurrency overlap during weekday bursts) + const serviceDurationMs = Math.min(34_000, Math.round(4500 + actualOutputTokens * 12.5)); + + turnSeq += 1; + turns.push({ + turnId: `t-${String(turnSeq).padStart(6, '0')}`, + sessionId, + turnIndex: ti, + arrivalMs: curMs, + minTier, + prefixTokens: curPrefix, + newInputTokens, + estOutputTokens, + actualOutputTokens, + serviceDurationMs, + }); + sessionTurnsAdded += 1; + + // Grow prefix deterministically for the next turn (cap growth smoothly at 115k for realism) + curPrefix = Math.min(115_000, curPrefix + newInputTokens + actualOutputTokens); + + // Compute causal gap to next turn + let gapMs; + if (archetype === 'rapidCoding') { + // 98.5% within 22s..3.5m (5m cache strictly optimal!), 1.5% long break > 75m + gapMs = rng() < 0.985 + ? Math.round(randRange(rng, 22_000, 210_000)) + : Math.round(randRange(rng, 75 * MINUTE_MS, 130 * MINUTE_MS)); + } else if (archetype === 'reviewThinking') { + // 92% in 8m..44m (1h cache strictly optimal vs 5m always expiring!), 4% fast follow-up, 4% long >70m + const u = rng(); + if (u < 0.92) gapMs = Math.round(randRange(rng, 8 * MINUTE_MS, 44 * MINUTE_MS)); + else if (u < 0.96) gapMs = Math.round(randRange(rng, 90_000, 240_000)); + else gapMs = Math.round(randRange(rng, 70 * MINUTE_MS, 135 * MINUTE_MS)); + } else if (archetype === 'mixedCadence') { + if (ti < splitPoint) { + gapMs = Math.round(randRange(rng, 25_000, 185_000)); + } else { + gapMs = Math.round(randRange(rng, 9 * MINUTE_MS, 42 * MINUTE_MS)); + } + } else { + // oneShotSparse: 80m..240m (exceeds 1h TTL) + gapMs = Math.round(randRange(rng, 80 * MINUTE_MS, 240 * MINUTE_MS)); + } + + curMs += Math.max(serviceDurationMs + 5000, gapMs); + } + + if (sessionTurnsAdded > 0) { + sessionMeta.push({ sessionId, archetype, minTier, turns: sessionTurnsAdded }); + } + } + } + + // Sort chronologically by arrivalMs, deterministic tie-break on turnId + turns.sort((a, b) => a.arrivalMs - b.arrivalMs || (a.turnId < b.turnId ? -1 : a.turnId > b.turnId ? 1 : 0)); + + const subA = poolConfig.accounts.find((a) => a.id === 'sub-a'); + const subB = poolConfig.accounts.find((a) => a.id === 'sub-b'); + + const subAResetOffsetHours = options.subAResetOffsetHours ?? (2 * 24 + 8); + const subBResetOffsetHours = options.subBResetOffsetHours ?? (5 * 24 + 18); + const subAInitialUsedFrac = options.subAInitialUsedFrac ?? 0.56; + const subBInitialUsedFrac = options.subBInitialUsedFrac ?? 0.18; + + const initialAccountState = { + 'sub-a': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subA?.sevenDayLimit ?? 15_500_000) * subAInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subAResetOffsetHours * HOUR_MS), + }, + 'sub-b': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subB?.sevenDayLimit ?? 12_500_000) * subBInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subBResetOffsetHours * HOUR_MS), + }, + 'secondary-org': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: 0, + sevenDayResetAtMs: null, + }, + }; + + const outages = (options.outages ?? [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ]).map((o) => ({ + accountId: o.accountId, + startMs: startMs + Math.round(o.startHour * HOUR_MS), + endMs: startMs + Math.round(o.startHour * HOUR_MS) + Math.round(o.durationMin * MINUTE_MS), + })); + + return { + name: options.name ?? `seed-${seed}`, + seed, + startMs, + endMs, + startDayOfWeek, + initialAccountState, + outages, + turns, + summary: { + sessions: sessionMeta.length, + turns: turns.length, + fiveHoursMs: FIVE_HOURS_MS, + sevenDaysMs: SEVEN_DAYS_MS, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/candidate/src/router.mjs b/questions/opt-routing-cost-sim/v1/candidate/src/router.mjs new file mode 100644 index 0000000..5705a5d --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/src/router.mjs @@ -0,0 +1,156 @@ +/** + * Baseline Cost Router (mirrors Cindy's current pickAutoCandidate heuristics). + * + * Strategy: + * - Static tier priority: primary subscriptions (`sub-a` -> `sub-b`) not 5h-tight + * -> `secondary-org` not 5h-tight + * -> primary subscriptions 5h-tight + * -> `secondary-org` 5h-tight + * -> cheapest PAYG meeting `minTier`. + * - Binary 85% 5h tight cutoff (unless 5h resets within 60 minutes). + * - Fixed >= 2.0x 7d expiring urgency priority within primary pool. + * - Always uses `cacheMode: '5m'`. + */ + +const FIVE_HOUR_TIGHT_FRAC = 0.85; +const FIVE_HOUR_RESET_SOON_MS = 60 * 60_000; +const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +const EXPIRING_URGENCY_THRESHOLD = 2.0; + +function estimateUnits(acc, turn, cacheMode, poolConfig) { + const isWarm = turn.prevAccountId === acc.id + && acc.warmPrefixTokens > 0 + && acc.warmExpiresAtMs !== null; + const cachedRead = isWarm ? Math.min(turn.prefixTokens, acc.warmPrefixTokens) : 0; + const handoff = turn.prevAccountId && turn.prevAccountId !== acc.id + ? Math.min(poolConfig.handoffCapTokens, Math.round(turn.prefixTokens * poolConfig.handoffRate)) + : 0; + const uncached = (turn.prefixTokens - cachedRead) + turn.newInputTokens + handoff; + const writeMult = cacheMode === '5m' + ? acc.pricing.cacheWrite5mMult + : cacheMode === '1h' + ? acc.pricing.cacheWrite1hMult + : 1.0; + const effInput = cachedRead * acc.pricing.cacheReadMult + uncached * writeMult; + return effInput + 3.0 * turn.estOutputTokens; +} + +function isFiveHourTight(acc, nowMs) { + if (acc.fiveHourLimit === null || acc.fiveHourLimit <= 0) return false; + const usedFrac = acc.fiveHourUsed / acc.fiveHourLimit; + if (usedFrac < FIVE_HOUR_TIGHT_FRAC) return false; + if (acc.fiveHourResetAtMs !== null && acc.fiveHourResetAtMs - nowMs <= FIVE_HOUR_RESET_SOON_MS) { + return false; + } + return true; +} + +function sevenDayUrgency(acc, nowMs) { + if (acc.sevenDayLimit === null || acc.sevenDayLimit <= 0 || acc.sevenDayResetAtMs === null) { + return null; + } + const timeLeftMs = acc.sevenDayResetAtMs - nowMs; + if (timeLeftMs <= 0) return null; + const timeLeftFrac = Math.min(1, timeLeftMs / SEVEN_DAYS_MS); + const remFrac = Math.max(0, 1 - acc.sevenDayUsed / acc.sevenDayLimit); + return remFrac / Math.max(1e-4, timeLeftFrac); +} + +export function createCostRouter(poolConfig) { + const paygOrder = new Map(poolConfig.accounts.map((a, idx) => [a.id, idx])); + let lastPrimaryId = null; + + function hasQuotaRoom(acc, estUnits) { + // Small safety margin for +/-12% output token estimation variance + const needed = estUnits * 1.08; + if (acc.fiveHourLimit !== null && acc.fiveHourUsed + needed > acc.fiveHourLimit) { + return false; + } + if (acc.sevenDayLimit !== null && acc.sevenDayUsed + needed > acc.sevenDayLimit) { + return false; + } + return true; + } + + function selectRoute(ctx) { + const { nowMs, excludedAccountIds, turn, accounts } = ctx; + const excluded = new Set(excludedAccountIds); + const cacheMode = '5m'; + + const eligible = accounts.filter((acc) => { + if (excluded.has(acc.id)) return false; + if (acc.capabilityTier < turn.minTier) return false; + if (acc.cooldownUntilMs !== null && nowMs < acc.cooldownUntilMs) return false; + if (acc.inFlight >= acc.maxInFlight) return false; + const est = estimateUnits(acc, turn, cacheMode, poolConfig); + return hasQuotaRoom(acc, est); + }); + + if (eligible.length === 0) { + // Emergency fallback: pick cheapest non-excluded PAYG meeting minTier (unlimited quota) + const emergency = accounts + .filter((a) => !excluded.has(a.id) && a.capabilityTier >= turn.minTier) + .sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok || (paygOrder.get(a.id) - paygOrder.get(b.id))); + return { accountId: emergency[0].id, cacheMode }; + } + + const primaries = eligible.filter((a) => a.kind === 'subscription'); + const secondaries = eligible.filter((a) => a.kind === 'secondary'); + const paygs = eligible.filter((a) => a.kind === 'payg'); + + const pickPrimary = (list) => { + const expiring = list + .map((acc) => ({ acc, urgency: sevenDayUrgency(acc, nowMs) ?? 0 })) + .filter((x) => x.urgency >= EXPIRING_URGENCY_THRESHOLD) + .sort((a, b) => b.urgency - a.urgency || a.acc.inFlight - b.acc.inFlight || (paygOrder.get(a.acc.id) - paygOrder.get(b.acc.id))); + if (expiring.length > 0) return expiring[0].acc; + // Mirrors Cindy pickWithinTier: quotaScore - AUTO_RUNNING_PENALTY * running + soft round-robin + const scored = list.map((acc) => { + const u = sevenDayUrgency(acc, nowMs) ?? 0.78; + const quotaScore = u <= 1.0 ? Math.max(0.05, u) : 1.0 + Math.min(1.0, u - 1.0) * 0.12; + const score = quotaScore - acc.inFlight * 0.30; + return { acc, score }; + }); + scored.sort((a, b) => b.score - a.score || (paygOrder.get(a.acc.id) - paygOrder.get(b.acc.id))); + // Soft rotation band (like Cindy AUTO_SOFT_ROTATE_GAP = 0.06) across equal-load primaries + const leader = scored[0]; + const band = scored.filter((x) => leader.score - x.score <= 0.08 && x.acc.inFlight <= leader.acc.inFlight); + if (band.length > 1 && lastPrimaryId) { + const idx = band.findIndex((x) => x.acc.id === lastPrimaryId); + if (idx >= 0) return band[(idx + 1) % band.length].acc; + } + return leader.acc; + }; + + const primaryRoomy = primaries.filter((a) => !isFiveHourTight(a, nowMs)); + if (primaryRoomy.length > 0) { + return { accountId: pickPrimary(primaryRoomy).id, cacheMode }; + } + + const secondaryRoomy = secondaries.filter((a) => !isFiveHourTight(a, nowMs)); + if (secondaryRoomy.length > 0) { + return { accountId: secondaryRoomy[0].id, cacheMode }; + } + + if (primaries.length > 0) { + return { accountId: pickPrimary(primaries).id, cacheMode }; + } + + if (secondaries.length > 0) { + return { accountId: secondaries[0].id, cacheMode }; + } + + const cheapestPayg = [...paygs].sort( + (a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok || (paygOrder.get(a.id) - paygOrder.get(b.id)), + )[0]; + return { accountId: cheapestPayg.id, cacheMode }; + } + + function onTurnResult(outcome) { + if (outcome.ok && (outcome.accountId === 'sub-a' || outcome.accountId === 'sub-b')) { + lastPrimaryId = outcome.accountId; + } + } + + return { selectRoute, onTurnResult }; +} diff --git a/questions/opt-routing-cost-sim/v1/candidate/tests/smoke.test.mjs b/questions/opt-routing-cost-sim/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..8606d33 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,144 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + CACHE_1H_TTL_MS, + CACHE_5M_TTL_MS, + SEVEN_DAYS_MS, + computeTurnBilling, + createDefaultPoolConfig, + runSimulation, +} from '../sim/billing-sim.mjs'; +import { + DEFAULT_START_MS, + PUBLIC_SCENARIOS, + generateWorkload, +} from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +test('prompt cache billing arithmetic and exact TTL boundaries', () => { + const pool = createDefaultPoolConfig(); + const payg3 = pool.accounts.find((a) => a.id === 'payg-t3'); + + // Cold 5m write: 10,000 uncached * 1.25 = 12,500 effective input -> $0.125 + 1,000 * $30/M = $0.155 + const cold5m = computeTurnBilling({ + prefixTokens: 8000, + newInputTokens: 2000, + outputTokens: 1000, + cachedReadTokens: 0, + handoffTokens: 0, + cacheMode: '5m', + pricing: payg3.pricing, + }); + assert.equal(cold5m.effectiveInputTokens, 12_500); + assert.ok(Math.abs(cold5m.billedUsd - 0.155) < 1e-9); + + // Warm 1h read: 11,000 * 0.10 + 2,000 * 2.00 = 5,100 effective input + const warm1h = computeTurnBilling({ + prefixTokens: 11_000, + newInputTokens: 2000, + outputTokens: 500, + cachedReadTokens: 11_000, + handoffTokens: 0, + cacheMode: '1h', + pricing: payg3.pricing, + }); + assert.equal(warm1h.effectiveInputTokens, 5100); + + // Verify exact 5m boundary (300_000ms HIT vs 300_001ms MISS) in simulator + const T0 = DEFAULT_START_MS; + const cachedReads = []; + const wl = { + name: 'cache-boundary-sim', + seed: 1, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: {}, + outages: [], + turns: [ + { turnId: 't1', sessionId: 's1', turnIndex: 0, arrivalMs: T0, minTier: 3, prefixTokens: 10_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't2', sessionId: 's1', turnIndex: 1, arrivalMs: T0 + CACHE_5M_TTL_MS, minTier: 3, prefixTokens: 11_500, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't3', sessionId: 's1', turnIndex: 2, arrivalMs: T0 + 2 * CACHE_5M_TTL_MS + 1, minTier: 3, prefixTokens: 13_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + ], + }; + runSimulation({ + workload: wl, + poolConfig: pool, + createRouter: () => ({ + selectRoute: () => ({ accountId: 'payg-t3', cacheMode: '5m' }), + onTurnResult: (o) => { cachedReads.push(o.cachedReadTokens); }, + }), + freezeCtx: true, + }); + assert.deepEqual(cachedReads, [0, 11_500, 0]); +}); + +test('router handles exhausted subscriptions and secondary-org with tier-compliant PAYG fallback', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'exhausted-subscriptions', + seed: 2, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 1_900_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 1_650_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 12_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 1_550_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'x1', sessionId: 'sx1', turnIndex: 0, arrivalMs: T0 + 1000, minTier: 1, prefixTokens: 2000, newInputTokens: 1000, estOutputTokens: 400, actualOutputTokens: 400, serviceDurationMs: 2000 }, + { turnId: 'x2', sessionId: 'sx2', turnIndex: 0, arrivalMs: T0 + 5000, minTier: 2, prefixTokens: 4000, newInputTokens: 1000, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'x3', sessionId: 'sx3', turnIndex: 0, arrivalMs: T0 + 9000, minTier: 3, prefixTokens: 8000, newInputTokens: 1000, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); + assert.equal(res.failedAttempts, 0); +}); + +test('router handles mid-session outage failover, 7d wraparound, and frozen ctx immutability', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'outage-and-wraparound', + seed: 3, + startMs: T0, + endMs: T0 + 2 * SEVEN_DAYS_MS, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + 3_600_000 }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [ + { accountId: 'sub-b', startMs: T0 + 60_000, endMs: T0 + 1_800_000 }, + ], + turns: [ + { turnId: 'm1', sessionId: 'sm1', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 3, prefixTokens: 10_000, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm2', sessionId: 'sm1', turnIndex: 1, arrivalMs: T0 + 120_000, minTier: 3, prefixTokens: 12_100, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm3', sessionId: 'sm1', turnIndex: 2, arrivalMs: T0 + 3_600_000 + CACHE_1H_TTL_MS, minTier: 3, prefixTokens: 14_200, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); +}); + +test('router is deterministic across repeated runs on a public slice', () => { + const pool = createDefaultPoolConfig(); + const wl = generateWorkload({ ...PUBLIC_SCENARIOS[0], demandMultiplier: 0.12, poolConfig: pool }); + const r1 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + const r2 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + + assert.equal(r1.droppedTurns, 0); + assert.equal(r1.tierViolations, 0); + assert.equal(r1.invalidDecisions, 0); + assert.equal(r1.totalCostUsd, r2.totalCostUsd); + assert.equal(r1.failedAttempts, r2.failedAttempts); + assert.deepEqual(r1.cacheStats, r2.cacheStats); +}); diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/CONTRACT.md b/questions/opt-routing-cost-sim/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..6e9f06b --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,77 @@ +# Router & Simulator Contract + +This contract specifies the immutable billing/quota/prompt-cache physics (`sim/billing-sim.mjs`) and the causal online router interface (`src/router.mjs`). Within these invariants, you are free to implement any online algorithm inside `src/` (including helper modules imported by `src/router.mjs`). + +## 1. Public Router API (`src/router.mjs`) + +- Must export `createCostRouter(poolConfig)` returning `{ selectRoute(ctx), onTurnResult(outcome) }`. +- Both `poolConfig`, `ctx`, and `outcome` may be deeply frozen; mutating any input object is forbidden and fails `gate_causal_and_fast`. +- The router must be **strictly deterministic** (no `Math.random()`, no `Date.now()` wall-clock branching). + +### `poolConfig` +- `accounts`: array of 6 account specs (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), each with `{ id, kind, capabilityTier, pricing: { inputPerMTok, outputPerMTok, cacheReadMult, cacheWrite5mMult, cacheWrite1hMult }, quotaOutputWeight, fiveHourLimit, sevenDayLimit, maxInFlight, supportedCacheModes }`. +- `cacheTtlMs`: `{ '5m': 300_000, '1h': 3_600_000 }`. +- `handoffRate`: `0.08`, `handoffCapTokens`: `4000`, `retryDelayMs`: `1200`, `maxAttempts`: `4`. + +### `selectRoute(ctx)` → `{ accountId: string, cacheMode: 'none' | '5m' | '1h' }` +`ctx` contains ONLY causal present and past state (zero future lookahead, zero session archetype labels): +- `nowMs`: virtual timestamp (ms). +- `attempt`: `0 .. maxAttempts - 1`. +- `excludedAccountIds`: accounts already attempted and failed for this turn (must NOT be selected again). +- `turn`: `{ sessionId, turnIndex, minTier, prefixTokens, newInputTokens, estOutputTokens, prevAccountId, prevTurnAtMs, prevCacheMode, sessionTurnsSoFar, recentGapMsList }`. + - `estOutputTokens` is an unbiased estimate within ±12% of the turn's actual output tokens. + - `recentGapMsList` holds up to the last 8 observed inter-turn gaps (ms) in this session (empty on `turnIndex === 0`). +- `accounts`: snapshot of all 6 accounts at `nowMs`: + `{ id, kind, capabilityTier, pricing, fiveHourUsed, fiveHourLimit, fiveHourResetAtMs, sevenDayUsed, sevenDayLimit, sevenDayResetAtMs, inFlight, maxInFlight, cooldownUntilMs, warmPrefixTokens, warmExpiresAtMs }`. + - `warmPrefixTokens > 0 && warmExpiresAtMs !== null && nowMs <= warmExpiresAtMs` iff this session currently has a live warm prompt cache on that account (which requires continuing on `prevAccountId`). + +### `onTurnResult(outcome)` +Called after every attempt (both failed and succeeded): +- `{ nowMs, sessionId, accountId, cacheMode, ok, errorCode, billedUsd, quotaUnitsCharged, cachedReadTokens, actualOutputTokens, latencyMs }`. + +## 2. Exact Billing, Prompt-Cache & Quota Physics (`sim/billing-sim.mjs`) + +### Account Pool +| Account | Kind | Tier | Pricing (`$/MTok` in / out) | `5h` Cap (weighted tok) | `7d` Cap (weighted tok) | `maxInFlight` | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `sub-a` | `subscription` | 3 | `$0.00 / $0.00` | `1,900,000` | `15,500,000` | 4 | Staggered weekly `7d` reset; unused `7d` expires | +| `sub-b` | `subscription` | 3 | `$0.00 / $0.00` | `1,650,000` | `12,500,000` | 3 | Different staggered `7d` reset + occasional outages | +| `secondary-org` | `secondary` | 3 | `$1.50 / $7.50` | `1,550,000` | unlimited | 6 | Discounted org pool; transient 429 risk when `inFlight >= 3` or `5h >= 85%` | +| `payg-t1` | `payg` | 1 | `$0.50 / $2.50` | unlimited | unlimited | 64 | Unlimited PAYG fast/mini | +| `payg-t2` | `payg` | 2 | `$3.00 / $15.00` | unlimited | unlimited | 64 | Unlimited PAYG balanced | +| `payg-t3` | `payg` | 3 | `$10.00 / $30.00` | unlimited | unlimited | 64 | Unlimited PAYG frontier | + +All 6 accounts support `cacheMode` in `['none', '5m', '1h']`. + +### Prompt Cache & Handoff Arithmetic +For a turn `(prefixTokens, newInputTokens, actualOutputTokens)` served on `accountId` with `cacheMode`: +1. **Cache read**: If `(!prevAccountId || prevAccountId === accountId)` and a live cache exists for `(sessionId, accountId)` with `nowMs <= warm.expiresAtMs`, then `cachedReadTokens = min(prefixTokens, warm.warmPrefixTokens)`. Otherwise `cachedReadTokens = 0`. +2. **Cross-account handoff**: If `prevAccountId && prevAccountId !== accountId`, `handoffTokens = min(4000, Math.round(prefixTokens * 0.08))`; otherwise `0`. +3. **Uncached input**: `uncachedInputTokens = (prefixTokens - cachedReadTokens) + newInputTokens + handoffTokens`. +4. **Effective input tokens**: + - `'none'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.00` (leaves same-account warm entry unchanged; does not populate new cache). + - `'5m'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.25` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 300_000 }`). + - `'1h'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 2.00` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 3_600_000 }`). +5. **Dollar cost**: `billedUsd = (effectiveInputTokens * inputPerMTok + actualOutputTokens * outputPerMTok) / 1_000_000`. +6. **Quota units** (on accounts with finite `5h` or `7d` limits): `quotaUnitsCharged = effectiveInputTokens + 3.0 * actualOutputTokens`. + - `5h` rolling window starts on first spend (`fiveHourResetAtMs = nowMs + 5h`) and resets to `0` once `nowMs >= fiveHourResetAtMs`. + - `7d` weekly window resets on its staggered schedule (`sevenDayResetAtMs += 7d`); any unused `7d` quota expires at reset. + +### Failure, Outage & Retry Semantics +- An attempt fails (returning `errorCode` and incurring `1200 ms` stall delay before immediate re-query up to 4 attempts) if: + - `INVALID_ROUTE` (unknown account, excluded account, or invalid `cacheMode`), + - `COOLDOWN` (`nowMs < cooldownUntilMs`), + - `PROVIDER_OUTAGE` (scheduled outage; sets `cooldownUntilMs = nowMs + 180_000`), + - `CONCURRENCY_LIMIT` (`inFlight >= maxInFlight`), + - `RATE_LIMITED_7D` (`sevenDayUsed + quotaUnitsCharged > sevenDayLimit`), + - `RATE_LIMITED_5H` (`fiveHourUsed + quotaUnitsCharged > fiveHourLimit`), + - `TRANSIENT_429` (`secondary-org` load-dependent transient rate limit; sets `cooldownUntilMs = nowMs + 15_000`). +- Failing all 4 attempts drops the turn (`droppedTurns += 1`, failing `gate_all_served`). + +## 3. Hard Gates & Metric + +- `gate_all_served`: `droppedTurns === 0 && invalidDecisions === 0` across all unit tests, public trace, and unseen held-out traces. +- `gate_tier_floor`: `tierViolations === 0` (`capabilityTier >= turn.minTier` on 100% of turns). +- `gate_latency_sla`: `p99StallMs <= 3000` and `failedAttemptRate < 0.02` on every trace. +- `gate_causal_and_fast`: passes all frozen-context immutability and edge-case tests, deterministic, and `< 4000 ms` per 14-day simulation. +- **Primary metric**: `total_cost_usd` — mean 14-day USD bill across unseen held-out 14-day traces (lower is better, log-scaled between baseline and offline lower-bound target). diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/ENVIRONMENT.md b/questions/opt-routing-cost-sim/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..9a166d6 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock and seeded deterministic traffic/failure generators — dollar cost, quota consumption, cache hits, and stall latencies are exact, hardware-independent numbers. +- Protected files: `sim/`, `bench/`, `tests/`, `package.json`, `TASK.md`, `CONTRACT.md`, `ENVIRONMENT.md` are read-only and verified by the submission gate; edit ONLY files under `src/`. +- Public checks: + - `npm test` — functional correctness, billing physics, immutability, determinism, and edge-case smoke tests + - `npm run bench` — deterministic 14-day public benchmark (2 distinct 14-day traces) reporting USD bill, per-account breakdown, expired `7d` quota, cache hit rate, latency SLA, and runtime diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/TASK.md b/questions/opt-routing-cost-sim/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..3f45e35 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's online multi-account quota & prompt-cache cost router (`src/router.mjs`) extracted from production Smart Routing (`model-groups/pick.ts`, `turnRouting.ts`, `provider-group/scheduler.ts`, `usage/turnCostCalculator.ts`, and `agentcompass/engine/quota-economy.mjs`). + +## Observed Production Symptoms + +Over a realistic 14-day multi-turn coding and chat workload (~12,000 turns across ~600–750 sessions) sharing a **6-account multi-tier pool** (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), the current baseline router (`src/router.mjs`) racks up **~$800–$900 per 14 days** while leaving huge savings on the table: + +1. **Unprotected subscription quota**: Sends cheap `tier-1` (`$0.50/$2.50` PAYG alternative) and `tier-2` (`$3/$15`) turns straight onto scarce `$0`-marginal-cost subscriptions (`sub-a`, `sub-b`), burning weekly `7d` and rolling `5h` quotas early and forcing expensive `tier-3` (`$10/$30`) turns onto `payg-t3`. +2. **Rigid `'5m'`-only prompt caching**: Always sets `cacheMode: '5m'` on every turn: + - On **slow review/thinking sessions** (inter-turn gaps of 8–44 minutes), `'5m'` expires on every turn, re-paying `1.25×` write cost on growing 20k–80k prefixes instead of using `'1h'` (`2.0×` write once, `0.10×` reads thereafter). + - On **one-shot and ultra-sparse jobs** (including large batch summaries), `'5m'` pays an unnecessary `1.25×` write tax that is never read again instead of `'none'` (`1.0×`). + - On subscriptions (`sub-a`, `sub-b`), keeping warm prompt caches also stretches `5h` and `7d` quota **5–8× further** because cache reads consume only `0.10×` quota units. +3. **Cache-breaking transitions & binary cutoffs**: Breaks warm prompt caches blindly when crossing a fixed 85% `5h` cutoff or on concurrency ties, incurring both a cold re-write and an 8% cross-account handoff overhead (`min(4000, round(0.08 * prefixTokens))`). +4. **No online demand forecasting, shadow pricing, or staggered `7d` expiry pacing**: Fails to balance `sub-a` and `sub-b` across staggered weekly resets, weekday peaks vs quiet nights/weekends, `secondary-org` load-dependent transient 429s, and `sub-b` outage windows. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% of all four hard gates** (verified on unit edge cases, public traces, AND unseen held-out 14-day traces with different weekday/weekend phases, burst schedules, staggered reset offsets, session mixtures, and outages): + 1. `gate_all_served`: 100% of turns served (`0` dropped turns, `0` invalid routes). + 2. `gate_tier_floor`: 100% of turns routed to an account with `capabilityTier >= turn.minTier`. + 3. `gate_latency_sla`: P99 turn stall/retry delay `<= 3000 ms` and failed-attempt rate `< 2%`. + 4. `gate_causal_and_fast`: Strictly online/causal, never mutates frozen `ctx`/`outcome`/`poolConfig`, passes all edge-case checks, deterministic across runs, and completes each 14-day simulation in `< 4s`. +- **Open-ended optimization goal**: Design the strongest online routing & prompt-cache algorithm inside `src/` to drive the mean 14-day USD bill (`total_cost_usd`) as low as possible — without overfitting to public seeds! +- Run `npm test` and `npm run bench` to verify correctness and measure before/after savings. +- Record your analysis, algorithm design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;不可修改 `sim/`、`bench/`、`tests/`、`package.json`、`CONTRACT.md`、`ENVIRONMENT.md` 或 `TASK.md`。 diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/bench/run-bench.mjs b/questions/opt-routing-cost-sim/v1/controls/incomplete/bench/run-bench.mjs new file mode 100644 index 0000000..ecf34d4 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/bench/run-bench.mjs @@ -0,0 +1,51 @@ +/** + * Public 14-day routing cost benchmark (protected read-only). + * Runs the 2 public 14-day scenarios with frozen contexts and reports full diagnostics. + */ + +import { createDefaultPoolConfig, runSimulation } from '../sim/billing-sim.mjs'; +import { PUBLIC_SCENARIOS, generateWorkload } from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +const poolConfig = createDefaultPoolConfig(); +let costSum = 0; +let allGatesPass = true; + +console.log('=== opt-routing-cost-sim Public 14-Day Benchmark ===\n'); + +for (const sc of PUBLIC_SCENARIOS) { + const workload = generateWorkload({ ...sc, poolConfig }); + const res = runSimulation({ + workload, + poolConfig, + createRouter: createCostRouter, + freezeCtx: true, + }); + + const servedOk = res.droppedTurns === 0 && res.invalidDecisions === 0; + const tierOk = res.tierViolations === 0; + const slaOk = res.p99StallMs <= 3000 && res.failedAttemptRate < 0.02; + const fastOk = res.runtimeMs < 4000; + const pass = servedOk && tierOk && slaOk && fastOk; + if (!pass) allGatesPass = false; + + costSum += res.totalCostUsd; + + console.log(`[${sc.name}] sessions=${workload.summary.sessions} turns=${res.totalTurns}`); + console.log(` Total 14d Cost : $${res.totalCostUsd.toFixed(2)}`); + console.log(` Gates : served=${servedOk} tierFloor=${tierOk} latencySla=${slaOk} fast=${fastOk}`); + console.log(` SLA & Perf : p99Stall=${res.p99StallMs}ms failRate=${(res.failedAttemptRate * 100).toFixed(2)}% runtime=${res.runtimeMs.toFixed(1)}ms`); + console.log(` Prompt Cache : hitRate=${(res.cacheStats.cacheHitRate * 100).toFixed(1)}% handoffTok=${res.cacheStats.handoffTokens} modes=${JSON.stringify(res.cacheStats.byMode)}`); + console.log(` Expired 7d Quota : sub-a=${(res.expiredQuotaUnits['sub-a'] / 1e6).toFixed(2)}M sub-b=${(res.expiredQuotaUnits['sub-b'] / 1e6).toFixed(2)}M`); + console.log(' Account Breakdown:'); + for (const [id, st] of Object.entries(res.byAccount)) { + console.log( + ` ${id.padEnd(14)} turns=${String(st.turns).padStart(5)} usd=$${st.billedUsd.toFixed(2).padStart(7)} quota=${(st.quotaUnits / 1e6).toFixed(2).padStart(5)}M fails=${String(st.failedAttempts).padStart(3)} modes=${JSON.stringify(st.cacheModes)}`, + ); + } + console.log(''); +} + +const meanCost = costSum / PUBLIC_SCENARIOS.length; +console.log(`Public Mean 14-day Cost: $${meanCost.toFixed(2)} (gates=${allGatesPass ? 'PASS' : 'FAIL'})`); +if (!allGatesPass) process.exitCode = 1; diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/package.json b/questions/opt-routing-cost-sim/v1/controls/incomplete/package.json new file mode 100644 index 0000000..d840cd2 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-routing-cost-sim", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/run-bench.mjs" + } +} diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/billing-sim.mjs b/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/billing-sim.mjs new file mode 100644 index 0000000..116e455 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/billing-sim.mjs @@ -0,0 +1,697 @@ +/** + * Immutable 14-day multi-account billing, quota, concurrency, and prompt-cache simulator. + * Protected read-only: candidates must optimize `src/router.mjs` against this exact physics engine. + */ + +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +export const CACHE_5M_TTL_MS = 5 * 60_000; +export const CACHE_1H_TTL_MS = 60 * 60_000; + +export const VALID_CACHE_MODES = Object.freeze(['none', '5m', '1h']); +const VALID_CACHE_MODE_SET = new Set(VALID_CACHE_MODES); + +export const DEFAULT_HANDOFF_RATE = 0.08; +export const DEFAULT_HANDOFF_CAP_TOKENS = 4000; +export const DEFAULT_RETRY_DELAY_MS = 1200; +export const DEFAULT_MAX_ATTEMPTS = 4; +export const DEFAULT_QUOTA_OUTPUT_WEIGHT = 3.0; +export const OUTAGE_COOLDOWN_MS = 180_000; + +export function createDefaultPoolConfig(overrides = {}) { + const baseAccounts = [ + { + id: 'sub-a', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subAFiveHourLimit ?? 1_900_000, + sevenDayLimit: overrides.subASevenDayLimit ?? 15_500_000, + maxInFlight: 4, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'sub-b', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subBFiveHourLimit ?? 1_650_000, + sevenDayLimit: overrides.subBSevenDayLimit ?? 12_500_000, + maxInFlight: 3, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'secondary-org', + kind: 'secondary', + capabilityTier: 3, + pricing: { + inputPerMTok: 1.50, + outputPerMTok: 7.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.secondaryFiveHourLimit ?? 1_550_000, + sevenDayLimit: null, + maxInFlight: 6, + supportedCacheModes: ['none', '5m', '1h'], + transient429: { + inFlightThreshold: 3, + inFlightProbStep: 0.10, + fiveHourFracThreshold: 0.85, + fiveHourProb: 0.14, + cooldownMs: 15_000, + }, + }, + { + id: 'payg-t1', + kind: 'payg', + capabilityTier: 1, + pricing: { + inputPerMTok: 0.50, + outputPerMTok: 2.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t2', + kind: 'payg', + capabilityTier: 2, + pricing: { + inputPerMTok: 3.00, + outputPerMTok: 15.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t3', + kind: 'payg', + capabilityTier: 3, + pricing: { + inputPerMTok: 10.00, + outputPerMTok: 30.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + ]; + + return { + accounts: baseAccounts, + cacheTtlMs: { + '5m': CACHE_5M_TTL_MS, + '1h': CACHE_1H_TTL_MS, + }, + handoffRate: DEFAULT_HANDOFF_RATE, + handoffCapTokens: DEFAULT_HANDOFF_CAP_TOKENS, + retryDelayMs: DEFAULT_RETRY_DELAY_MS, + maxAttempts: DEFAULT_MAX_ATTEMPTS, + }; +} + +export function cacheWriteMultiplier(pricing, cacheMode) { + if (cacheMode === '5m') return pricing.cacheWrite5mMult; + if (cacheMode === '1h') return pricing.cacheWrite1hMult; + return 1.0; +} + +export function computeTurnBilling({ + prefixTokens, + newInputTokens, + outputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing, + quotaOutputWeight = DEFAULT_QUOTA_OUTPUT_WEIGHT, + meteredQuota = false, +}) { + const safeCached = Math.max(0, Math.min(prefixTokens, cachedReadTokens)); + const uncachedInputTokens = (prefixTokens - safeCached) + newInputTokens + handoffTokens; + const writeMult = cacheWriteMultiplier(pricing, cacheMode); + const readMult = pricing.cacheReadMult; + const effectiveInputTokens = safeCached * readMult + uncachedInputTokens * writeMult; + const billedUsd = (effectiveInputTokens * pricing.inputPerMTok + outputTokens * pricing.outputPerMTok) / 1_000_000; + const quotaUnitsCharged = meteredQuota ? effectiveInputTokens + quotaOutputWeight * outputTokens : 0; + return { + cachedReadTokens: safeCached, + uncachedInputTokens, + effectiveInputTokens, + billedUsd, + quotaUnitsCharged, + }; +} + +function deepFreeze(obj) { + if (!obj || typeof obj !== 'object' || Object.isFrozen(obj)) return obj; + Object.freeze(obj); + for (const val of Object.values(obj)) { + deepFreeze(val); + } + return obj; +} + +function deterministicUnitHash(seed, turnId, attempt, accountId) { + let h = (2166136261 ^ (seed >>> 0)) >>> 0; + const str = `${turnId}|${attempt}|${accountId}`; + for (let i = 0; i < str.length; i += 1) { + h ^= str.charCodeAt(i); + h = Math.imul(h, 16777619) >>> 0; + } + h ^= h >>> 16; + h = Math.imul(h, 0x7feb352d) >>> 0; + h ^= h >>> 15; + h = Math.imul(h, 0x846ca68b) >>> 0; + h ^= h >>> 16; + return (h >>> 0) / 4294967296; +} + +function percentile(sorted, p) { + if (sorted.length === 0) return 0; + const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1)); + return sorted[idx]; +} + +function clonePublicPoolConfig(poolConfig) { + return { + accounts: poolConfig.accounts.map((a) => ({ + id: a.id, + kind: a.kind, + capabilityTier: a.capabilityTier, + pricing: { ...a.pricing }, + quotaOutputWeight: a.quotaOutputWeight, + fiveHourLimit: a.fiveHourLimit, + sevenDayLimit: a.sevenDayLimit, + maxInFlight: a.maxInFlight, + supportedCacheModes: [...a.supportedCacheModes], + })), + cacheTtlMs: { ...poolConfig.cacheTtlMs }, + handoffRate: poolConfig.handoffRate, + handoffCapTokens: poolConfig.handoffCapTokens, + retryDelayMs: poolConfig.retryDelayMs, + maxAttempts: poolConfig.maxAttempts, + }; +} + +/** + * Runs a complete deterministic simulation over a workload trace. + * + * @param {object} params + * @param {object} params.workload - Output of generateWorkload() or custom unit-test workload + * @param {object} [params.poolConfig] - Account pool specification + * @param {Function} params.createRouter - Factory `(poolConfig) => ({ selectRoute, onTurnResult })` + * @param {boolean} [params.freezeCtx=false] - Deep-freeze ctx/outcome objects to enforce immutability + */ +export function runSimulation({ + workload, + poolConfig = createDefaultPoolConfig(), + createRouter, + freezeCtx = false, +}) { + const tStart = performance.now(); + const publicPool = clonePublicPoolConfig(poolConfig); + if (freezeCtx) deepFreeze(publicPool); + + const router = createRouter(publicPool); + if (!router || typeof router.selectRoute !== 'function' || typeof router.onTurnResult !== 'function') { + throw new Error('createCostRouter(poolConfig) must return { selectRoute, onTurnResult }'); + } + + const startMs = workload.startMs; + const initialAccountState = workload.initialAccountState ?? {}; + const outages = workload.outages ?? []; + const seed = workload.seed ?? 1; + + // Group outages by accountId for fast lookup + const outagesByAccount = new Map(); + for (const o of outages) { + let list = outagesByAccount.get(o.accountId); + if (!list) { + list = []; + outagesByAccount.set(o.accountId, list); + } + list.push(o); + } + + const accounts = poolConfig.accounts.map((cfg) => { + const init = initialAccountState[cfg.id] ?? {}; + return { + cfg, + id: cfg.id, + fiveHourUsed: init.fiveHourUsed ?? 0, + fiveHourResetAtMs: cfg.fiveHourLimit !== null ? (init.fiveHourResetAtMs ?? null) : null, + sevenDayUsed: init.sevenDayUsed ?? 0, + sevenDayResetAtMs: cfg.sevenDayLimit !== null ? (init.sevenDayResetAtMs ?? (startMs + SEVEN_DAYS_MS)) : null, + cooldownUntilMs: init.cooldownUntilMs ?? null, + activeEnds: [], + stats: { + turns: 0, + billedUsd: 0, + quotaUnits: 0, + cachedReadTokens: 0, + uncachedInputTokens: 0, + handoffTokens: 0, + outputTokens: 0, + failedAttempts: 0, + cacheModes: { none: 0, '5m': 0, '1h': 0 }, + }, + }; + }); + const accountById = new Map(accounts.map((a) => [a.id, a])); + const expiredQuotaUnits = Object.fromEntries( + accounts.filter((a) => a.cfg.sevenDayLimit !== null).map((a) => [a.id, 0]), + ); + + // Per-session runtime state: { prevAccountId, prevTurnAtMs, prevCacheMode, turnsSoFar, recentGapMsList, warm: { accountId, warmPrefixTokens, expiresAtMs } | null } + const sessions = new Map(); + + let totalCostUsd = 0; + let servedTurns = 0; + let droppedTurns = 0; + let tierViolations = 0; + let invalidDecisions = 0; + let totalAttempts = 0; + let failedAttempts = 0; + let totalPrefixTokens = 0; + let totalCachedReadTokens = 0; + let totalHandoffTokens = 0; + const cacheModeCounts = { none: 0, '5m': 0, '1h': 0 }; + const byTier = { + 1: { turns: 0, billedUsd: 0, byAccount: {} }, + 2: { turns: 0, billedUsd: 0, byAccount: {} }, + 3: { turns: 0, billedUsd: 0, byAccount: {} }, + }; + const stallDelays = []; + + function syncAccounts(nowMs) { + for (const acc of accounts) { + // Retire finished in-flight turns + if (acc.activeEnds.length > 0) { + let writeIdx = 0; + for (let i = 0; i < acc.activeEnds.length; i += 1) { + if (acc.activeEnds[i] > nowMs) { + acc.activeEnds[writeIdx] = acc.activeEnds[i]; + writeIdx += 1; + } + } + acc.activeEnds.length = writeIdx; + } + + // Reset expired 5h rolling window + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourResetAtMs !== null && nowMs >= acc.fiveHourResetAtMs) { + acc.fiveHourUsed = 0; + acc.fiveHourResetAtMs = null; + } + + // Reset expired 7d weekly window(s) + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayResetAtMs !== null && nowMs >= acc.sevenDayResetAtMs) { + const wasted = Math.max(0, acc.cfg.sevenDayLimit - acc.sevenDayUsed); + expiredQuotaUnits[acc.id] += wasted; + const periods = Math.floor((nowMs - acc.sevenDayResetAtMs) / SEVEN_DAYS_MS) + 1; + if (periods > 1) { + expiredQuotaUnits[acc.id] += (periods - 1) * acc.cfg.sevenDayLimit; + } + acc.sevenDayResetAtMs += periods * SEVEN_DAYS_MS; + acc.sevenDayUsed = 0; + } + + // Clear expired cooldown + if (acc.cooldownUntilMs !== null && nowMs >= acc.cooldownUntilMs) { + acc.cooldownUntilMs = null; + } + } + } + + function isInOutage(accountId, nowMs) { + const list = outagesByAccount.get(accountId); + if (!list) return false; + for (let i = 0; i < list.length; i += 1) { + const o = list[i]; + if (nowMs >= o.startMs && nowMs < o.endMs) return true; + } + return false; + } + + function checkTransient429(acc, turnId, attempt, nowMs) { + const tCfg = acc.cfg.transient429; + if (!tCfg) return false; + let prob = 0; + const inFlight = acc.activeEnds.length; + if (inFlight >= tCfg.inFlightThreshold) { + prob = Math.max(prob, (inFlight - tCfg.inFlightThreshold + 1) * tCfg.inFlightProbStep); + } + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed / acc.cfg.fiveHourLimit >= tCfg.fiveHourFracThreshold) { + prob = Math.max(prob, tCfg.fiveHourProb); + } + if (prob <= 0) return false; + const u = deterministicUnitHash(seed, turnId, attempt, acc.id); + if (u < prob) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, nowMs + tCfg.cooldownMs); + return true; + } + return false; + } + + const turns = workload.turns; + const maxAttempts = poolConfig.maxAttempts ?? DEFAULT_MAX_ATTEMPTS; + const retryDelayMs = poolConfig.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; + const handoffRate = poolConfig.handoffRate ?? DEFAULT_HANDOFF_RATE; + const handoffCapTokens = poolConfig.handoffCapTokens ?? DEFAULT_HANDOFF_CAP_TOKENS; + + for (let ti = 0; ti < turns.length; ti += 1) { + const turn = turns[ti]; + let sess = sessions.get(turn.sessionId); + if (!sess) { + sess = { + prevAccountId: null, + prevTurnAtMs: null, + prevCacheMode: null, + turnsSoFar: 0, + recentGapMsList: [], + warm: null, + }; + sessions.set(turn.sessionId, sess); + } + + const excluded = []; + let attemptNowMs = turn.arrivalMs; + let stallDelayMs = 0; + let served = false; + + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + totalAttempts += 1; + syncAccounts(attemptNowMs); + + // Clear expired warm entry for this session + if (sess.warm && attemptNowMs > sess.warm.expiresAtMs) { + sess.warm = null; + } + + const accountsSnapshot = accounts.map((acc) => { + const isWarmHere = sess.warm !== null + && sess.prevAccountId === acc.id + && sess.warm.accountId === acc.id + && attemptNowMs <= sess.warm.expiresAtMs; + return { + id: acc.id, + kind: acc.cfg.kind, + capabilityTier: acc.cfg.capabilityTier, + pricing: { ...acc.cfg.pricing }, + fiveHourUsed: acc.fiveHourUsed, + fiveHourLimit: acc.cfg.fiveHourLimit, + fiveHourResetAtMs: acc.fiveHourResetAtMs, + sevenDayUsed: acc.sevenDayUsed, + sevenDayLimit: acc.cfg.sevenDayLimit, + sevenDayResetAtMs: acc.sevenDayResetAtMs, + inFlight: acc.activeEnds.length, + maxInFlight: acc.cfg.maxInFlight, + cooldownUntilMs: acc.cooldownUntilMs, + warmPrefixTokens: isWarmHere ? sess.warm.warmPrefixTokens : 0, + warmExpiresAtMs: isWarmHere ? sess.warm.expiresAtMs : null, + }; + }); + + const ctx = { + nowMs: attemptNowMs, + attempt, + excludedAccountIds: [...excluded], + turn: { + sessionId: turn.sessionId, + turnIndex: turn.turnIndex, + minTier: turn.minTier, + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + estOutputTokens: turn.estOutputTokens, + prevAccountId: sess.prevAccountId, + prevTurnAtMs: sess.prevTurnAtMs, + prevCacheMode: sess.prevCacheMode, + sessionTurnsSoFar: sess.turnsSoFar, + recentGapMsList: [...sess.recentGapMsList], + }, + accounts: accountsSnapshot, + }; + if (freezeCtx) deepFreeze(ctx); + + const decision = router.selectRoute(ctx); + const accountId = decision && typeof decision.accountId === 'string' ? decision.accountId : ''; + const cacheMode = decision && typeof decision.cacheMode === 'string' ? decision.cacheMode : ''; + const acc = accountById.get(accountId); + + let errorCode = null; + if (!acc || !VALID_CACHE_MODE_SET.has(cacheMode) || excluded.includes(accountId)) { + errorCode = 'INVALID_ROUTE'; + invalidDecisions += 1; + } else if (acc.cooldownUntilMs !== null && attemptNowMs < acc.cooldownUntilMs) { + errorCode = 'COOLDOWN'; + } else if (isInOutage(accountId, attemptNowMs)) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, attemptNowMs + OUTAGE_COOLDOWN_MS); + errorCode = 'PROVIDER_OUTAGE'; + } else if (acc.activeEnds.length >= acc.cfg.maxInFlight) { + errorCode = 'CONCURRENCY_LIMIT'; + } + + // Compute exact billing & quota units for admission check + let billing = null; + let handoffTokens = 0; + if (!errorCode) { + const sameAsPrev = !sess.prevAccountId || sess.prevAccountId === accountId; + const isWarmHit = sameAsPrev + && sess.warm !== null + && sess.warm.accountId === accountId + && attemptNowMs <= sess.warm.expiresAtMs; + const cachedReadTokens = isWarmHit ? Math.min(turn.prefixTokens, sess.warm.warmPrefixTokens) : 0; + handoffTokens = sess.prevAccountId && sess.prevAccountId !== accountId + ? Math.min(handoffCapTokens, Math.round(turn.prefixTokens * handoffRate)) + : 0; + const meteredQuota = acc.cfg.fiveHourLimit !== null || acc.cfg.sevenDayLimit !== null; + billing = computeTurnBilling({ + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + outputTokens: turn.actualOutputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing: acc.cfg.pricing, + quotaOutputWeight: acc.cfg.quotaOutputWeight, + meteredQuota, + }); + + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayUsed + billing.quotaUnitsCharged > acc.cfg.sevenDayLimit) { + errorCode = 'RATE_LIMITED_7D'; + } else if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed + billing.quotaUnitsCharged > acc.cfg.fiveHourLimit) { + errorCode = 'RATE_LIMITED_5H'; + } else if (checkTransient429(acc, turn.turnId, attempt, attemptNowMs)) { + errorCode = 'TRANSIENT_429'; + } + } + + if (errorCode) { + failedAttempts += 1; + if (acc) acc.stats.failedAttempts += 1; + stallDelayMs += retryDelayMs; + attemptNowMs += retryDelayMs; + if (accountId && !excluded.includes(accountId)) excluded.push(accountId); + const failOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode: VALID_CACHE_MODE_SET.has(cacheMode) ? cacheMode : 'none', + ok: false, + errorCode, + billedUsd: 0, + quotaUnitsCharged: 0, + cachedReadTokens: 0, + actualOutputTokens: 0, + latencyMs: retryDelayMs, + }; + if (freezeCtx) deepFreeze(failOutcome); + router.onTurnResult(failOutcome); + continue; + } + + // Success! + served = true; + servedTurns += 1; + if (acc.cfg.capabilityTier < turn.minTier) { + tierViolations += 1; + } + + if (acc.cfg.fiveHourLimit !== null) { + if (acc.fiveHourResetAtMs === null) { + acc.fiveHourResetAtMs = attemptNowMs + FIVE_HOURS_MS; + } + acc.fiveHourUsed += billing.quotaUnitsCharged; + } + if (acc.cfg.sevenDayLimit !== null) { + acc.sevenDayUsed += billing.quotaUnitsCharged; + } + + acc.activeEnds.push(attemptNowMs + turn.serviceDurationMs); + + // Update cache state + const switchedAccount = sess.prevAccountId !== null && sess.prevAccountId !== accountId; + if (switchedAccount) { + sess.warm = null; + } + const nextWarmPrefix = turn.prefixTokens + turn.newInputTokens + turn.actualOutputTokens; + if (cacheMode === '5m') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['5m'], + }; + } else if (cacheMode === '1h') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['1h'], + }; + } + // If cacheMode === 'none': warm is unchanged on same account (already cleared if switched or expired) + + if (sess.prevTurnAtMs !== null) { + const gapMs = Math.max(0, attemptNowMs - sess.prevTurnAtMs); + sess.recentGapMsList.push(gapMs); + if (sess.recentGapMsList.length > 8) sess.recentGapMsList.shift(); + } + sess.prevAccountId = accountId; + sess.prevTurnAtMs = attemptNowMs; + sess.prevCacheMode = cacheMode; + sess.turnsSoFar += 1; + + totalCostUsd += billing.billedUsd; + totalPrefixTokens += turn.prefixTokens; + totalCachedReadTokens += billing.cachedReadTokens; + totalHandoffTokens += handoffTokens; + cacheModeCounts[cacheMode] += 1; + + acc.stats.turns += 1; + acc.stats.billedUsd += billing.billedUsd; + acc.stats.quotaUnits += billing.quotaUnitsCharged; + acc.stats.cachedReadTokens += billing.cachedReadTokens; + acc.stats.uncachedInputTokens += billing.uncachedInputTokens; + acc.stats.handoffTokens += handoffTokens; + acc.stats.outputTokens += turn.actualOutputTokens; + acc.stats.cacheModes[cacheMode] += 1; + + const tierBucket = byTier[turn.minTier]; + if (tierBucket) { + tierBucket.turns += 1; + tierBucket.billedUsd += billing.billedUsd; + tierBucket.byAccount[accountId] = (tierBucket.byAccount[accountId] ?? 0) + 1; + } + + const okOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode, + ok: true, + errorCode: null, + billedUsd: billing.billedUsd, + quotaUnitsCharged: billing.quotaUnitsCharged, + cachedReadTokens: billing.cachedReadTokens, + actualOutputTokens: turn.actualOutputTokens, + latencyMs: stallDelayMs + turn.serviceDurationMs, + }; + if (freezeCtx) deepFreeze(okOutcome); + router.onTurnResult(okOutcome); + break; + } + + if (!served) { + droppedTurns += 1; + } + stallDelays.push(stallDelayMs); + } + + // Final sync at end of simulation horizon to count any final-window reset + if (workload.endMs) { + syncAccounts(workload.endMs); + } + + stallDelays.sort((a, b) => a - b); + const runtimeMs = performance.now() - tStart; + + const byAccount = {}; + for (const acc of accounts) { + byAccount[acc.id] = { + ...acc.stats, + billedUsd: Number(acc.stats.billedUsd.toFixed(4)), + quotaUnits: Math.round(acc.stats.quotaUnits), + cacheModes: { ...acc.stats.cacheModes }, + }; + } + for (const t of [1, 2, 3]) { + byTier[t].billedUsd = Number(byTier[t].billedUsd.toFixed(4)); + } + + return { + totalCostUsd: Number(totalCostUsd.toFixed(4)), + totalTurns: turns.length, + servedTurns, + droppedTurns, + tierViolations, + invalidDecisions, + totalAttempts, + failedAttempts, + failedAttemptRate: totalAttempts > 0 ? failedAttempts / totalAttempts : 0, + p50StallMs: percentile(stallDelays, 0.50), + p95StallMs: percentile(stallDelays, 0.95), + p99StallMs: percentile(stallDelays, 0.99), + maxStallMs: stallDelays.length > 0 ? stallDelays[stallDelays.length - 1] : 0, + runtimeMs: Number(runtimeMs.toFixed(2)), + byAccount, + byTier, + expiredQuotaUnits: Object.fromEntries( + Object.entries(expiredQuotaUnits).map(([k, v]) => [k, Math.round(v)]), + ), + cacheStats: { + totalPrefixTokens, + totalCachedReadTokens, + cacheHitRate: totalPrefixTokens > 0 ? totalCachedReadTokens / totalPrefixTokens : 0, + handoffTokens: totalHandoffTokens, + byMode: { ...cacheModeCounts }, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/workload-generator.mjs b/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/workload-generator.mjs new file mode 100644 index 0000000..6050bcf --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/sim/workload-generator.mjs @@ -0,0 +1,370 @@ +/** + * Deterministic 14-day multi-turn session & traffic workload generator. + * Parameterized by seed and scenario profile; produces causal turn traces with zero hidden archetype hints. + */ + +import { FIVE_HOURS_MS, SEVEN_DAYS_MS, createDefaultPoolConfig } from './billing-sim.mjs'; + +const MINUTE_MS = 60_000; +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; +export const HORIZON_DAYS = 14; +export const HORIZON_MS = HORIZON_DAYS * DAY_MS; + +// Default Monday 2026-01-05 00:00:00 UTC +export const DEFAULT_START_MS = Date.UTC(2026, 0, 5, 0, 0, 0); + +function mulberry32(seed) { + let a = seed >>> 0; + return function rng() { + a = (a + 0x6d2b79f5) >>> 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function randRange(rng, lo, hi) { + return lo + (hi - lo) * rng(); +} + +function randInt(rng, lo, hi) { + return Math.floor(randRange(rng, lo, hi + 1)); +} + +function pickWeighted(rng, entries) { + let total = 0; + for (const [, w] of entries) total += w; + let r = rng() * total; + for (const [val, w] of entries) { + r -= w; + if (r <= 0) return val; + } + return entries[entries.length - 1][0]; +} + +// Realistic weekday hourly demand weights (0..23h local work clock), peaks at 10-12h & 14-18h. +const DEFAULT_WEEKDAY_HOURLY = [ + 0.14, 0.10, 0.08, 0.07, 0.08, 0.12, + 0.24, 0.45, 0.85, 1.35, 1.75, 1.85, + 1.30, 1.55, 1.95, 2.05, 1.90, 1.60, + 1.10, 0.78, 0.62, 0.48, 0.34, 0.22, +]; + +const DEFAULT_WEEKEND_HOURLY = [ + 0.10, 0.08, 0.06, 0.06, 0.06, 0.08, + 0.12, 0.18, 0.30, 0.48, 0.62, 0.68, + 0.65, 0.70, 0.72, 0.68, 0.60, 0.52, + 0.46, 0.42, 0.38, 0.30, 0.22, 0.14, +]; + +export const PUBLIC_SCENARIOS = [ + { + name: 'public-standard-mon', + seed: 20260401, + startDayOfWeek: 0, // Monday + subAResetOffsetHours: 2 * 24 + 8, // Day 2 08:00 & Day 9 08:00 + subBResetOffsetHours: 5 * 24 + 18, // Day 5 18:00 & Day 12 18:00 + subAInitialUsedFrac: 0.56, + subBInitialUsedFrac: 0.18, + demandMultiplier: 1.04, + weekendDipFactor: 0.42, + burstIntensity: 1.0, + archetypeWeights: { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ], + }, + { + name: 'public-shifted-thu', + seed: 20260402, + startDayOfWeek: 3, // Thursday + subAResetOffsetHours: 1 * 24 + 16, // Day 1 16:00 & Day 8 16:00 + subBResetOffsetHours: 4 * 24 + 10, // Day 4 10:00 & Day 11 10:00 + subAInitialUsedFrac: 0.68, + subBInitialUsedFrac: 0.34, + demandMultiplier: 1.08, + weekendDipFactor: 0.36, + burstIntensity: 1.12, + archetypeWeights: { + rapidCoding: 0.35, + reviewThinking: 0.11, + mixedCadence: 0.08, + oneShotSparse: 0.20, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 5 * 24 + 14.5, durationMin: 70 }, + { accountId: 'sub-b', startHour: 11 * 24 + 16.0, durationMin: 60 }, + ], + }, +]; + +/** + * Generates a deterministic 14-day multi-turn workload trace. + * Turn objects carry ZERO archetype hints — routers must infer patterns online. + */ +export function generateWorkload(options = {}) { + const seed = options.seed ?? 20260401; + const rng = mulberry32(seed); + const poolConfig = options.poolConfig ?? createDefaultPoolConfig(); + const startDayOfWeek = ((options.startDayOfWeek ?? 0) % 7 + 7) % 7; // 0=Mon..6=Sun + const startMs = options.startMs ?? (DEFAULT_START_MS + startDayOfWeek * DAY_MS); + const endMs = startMs + HORIZON_MS; + + const demandMultiplier = options.demandMultiplier ?? 1.0; + const weekendDipFactor = options.weekendDipFactor ?? 0.42; + const burstIntensity = options.burstIntensity ?? 1.0; + const weights = options.archetypeWeights ?? { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }; + const archetypeEntries = [ + ['rapidCoding', weights.rapidCoding], + ['reviewThinking', weights.reviewThinking], + ['mixedCadence', weights.mixedCadence], + ['oneShotSparse', weights.oneShotSparse], + ['largeOneShot', weights.largeOneShot], + ]; + + // Generate 3-4 realistic weekday burst episodes (e.g., release crunch / incident response) + const burstWindows = []; + for (let day = 0; day < HORIZON_DAYS; day += 1) { + const dow = (startDayOfWeek + day) % 7; + if (dow >= 5) continue; // bursts happen on weekdays + if (rng() < 0.38 * burstIntensity) { + const startHour = day * 24 + randRange(rng, 9.5, 15.5); + const durationHours = randRange(rng, 2.2, 4.0); + burstWindows.push({ + startHour, + endHour: startHour + durationHours, + mult: randRange(rng, 1.55, 2.15) * burstIntensity, + }); + } + } + + // Compute hourly session arrival rates targeting ~740 sessions -> ~11,500-12,500 turns over 14 days + const hourRates = new Array(HORIZON_DAYS * 24); + let rateSum = 0; + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const day = Math.floor(h / 24); + const hourOfDay = h % 24; + const dow = (startDayOfWeek + day) % 7; + const isWeekend = dow >= 5; + let rate = isWeekend + ? DEFAULT_WEEKEND_HOURLY[hourOfDay] * (weekendDipFactor / 0.42) + : DEFAULT_WEEKDAY_HOURLY[hourOfDay]; + for (const bw of burstWindows) { + if (h + 0.5 >= bw.startHour && h + 0.5 <= bw.endHour) { + rate *= bw.mult; + } + } + hourRates[h] = rate; + rateSum += rate; + } + + const targetSessions = Math.round(700 * demandMultiplier); + const turns = []; + let sessionSeq = 0; + let turnSeq = 0; + + // Also keep ground-truth session summaries for offline oracle / diagnostics (never passed to router!) + const sessionMeta = []; + + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const expected = (hourRates[h] / rateSum) * targetSessions; + // Poisson draw using Knuth algorithm + const L = Math.exp(-expected); + let k = 0; + let p = 1.0; + do { + k += 1; + p *= rng(); + } while (p > L); + const count = Math.max(0, k - 1); + + for (let s = 0; s < count; s += 1) { + sessionSeq += 1; + const sessionId = `s-${String(sessionSeq).padStart(4, '0')}`; + const archetype = pickWeighted(rng, archetypeEntries); + const sessionStartMs = startMs + h * HOUR_MS + Math.floor(rng() * HOUR_MS); + + let minTier; + let numTurns; + let initPrefix; + + if (archetype === 'rapidCoding') { + minTier = pickWeighted(rng, [[3, 0.37], [2, 0.25], [1, 0.38]]); + numTurns = randInt(rng, 28, 48); + initPrefix = randInt(rng, 5500, 12500); + } else if (archetype === 'reviewThinking') { + minTier = pickWeighted(rng, [[3, 0.56], [2, 0.34], [1, 0.10]]); + numTurns = randInt(rng, 9, 15); + initPrefix = randInt(rng, 11000, 21000); + } else if (archetype === 'mixedCadence') { + minTier = pickWeighted(rng, [[3, 0.50], [2, 0.32], [1, 0.18]]); + numTurns = randInt(rng, 14, 23); + initPrefix = randInt(rng, 8000, 15000); + } else if (archetype === 'oneShotSparse') { + minTier = pickWeighted(rng, [[1, 0.64], [2, 0.22], [3, 0.14]]); + numTurns = pickWeighted(rng, [[1, 0.66], [2, 0.24], [3, 0.10]]); + initPrefix = randInt(rng, 900, 3600); + } else { + // largeOneShot: single-turn batch summarization, PR diff digest, cron synthesis + minTier = pickWeighted(rng, [[1, 0.66], [2, 0.20], [3, 0.14]]); + numTurns = 1; + initPrefix = randInt(rng, 1000, 3500); + } + + const splitPoint = archetype === 'mixedCadence' ? randInt(rng, 5, Math.max(6, Math.floor(numTurns * 0.45))) : 0; + + let curMs = sessionStartMs; + let curPrefix = initPrefix; + let sessionTurnsAdded = 0; + + for (let ti = 0; ti < numTurns; ti += 1) { + if (curMs >= endMs - 60_000) break; + + let newInputTokens; + let actualOutputTokens; + if (archetype === 'rapidCoding') { + newInputTokens = randInt(rng, 850, 2400); + actualOutputTokens = randInt(rng, 450, 1600); + } else if (archetype === 'reviewThinking') { + newInputTokens = randInt(rng, 1300, 3600); + actualOutputTokens = randInt(rng, 900, 2600); + } else if (archetype === 'mixedCadence') { + newInputTokens = randInt(rng, 1000, 2800); + actualOutputTokens = randInt(rng, 650, 1950); + } else if (archetype === 'oneShotSparse') { + newInputTokens = randInt(rng, 600, 2200); + actualOutputTokens = randInt(rng, 300, 1100); + } else { + // largeOneShot + newInputTokens = randInt(rng, 14000, 36000); + actualOutputTokens = randInt(rng, 800, 2600); + } + + const estOutputTokens = Math.max(100, Math.round(actualOutputTokens * randRange(rng, 0.88, 1.12))); + // Realistic LLM streaming turn latency (~8-32s -> natural concurrency overlap during weekday bursts) + const serviceDurationMs = Math.min(34_000, Math.round(4500 + actualOutputTokens * 12.5)); + + turnSeq += 1; + turns.push({ + turnId: `t-${String(turnSeq).padStart(6, '0')}`, + sessionId, + turnIndex: ti, + arrivalMs: curMs, + minTier, + prefixTokens: curPrefix, + newInputTokens, + estOutputTokens, + actualOutputTokens, + serviceDurationMs, + }); + sessionTurnsAdded += 1; + + // Grow prefix deterministically for the next turn (cap growth smoothly at 115k for realism) + curPrefix = Math.min(115_000, curPrefix + newInputTokens + actualOutputTokens); + + // Compute causal gap to next turn + let gapMs; + if (archetype === 'rapidCoding') { + // 98.5% within 22s..3.5m (5m cache strictly optimal!), 1.5% long break > 75m + gapMs = rng() < 0.985 + ? Math.round(randRange(rng, 22_000, 210_000)) + : Math.round(randRange(rng, 75 * MINUTE_MS, 130 * MINUTE_MS)); + } else if (archetype === 'reviewThinking') { + // 92% in 8m..44m (1h cache strictly optimal vs 5m always expiring!), 4% fast follow-up, 4% long >70m + const u = rng(); + if (u < 0.92) gapMs = Math.round(randRange(rng, 8 * MINUTE_MS, 44 * MINUTE_MS)); + else if (u < 0.96) gapMs = Math.round(randRange(rng, 90_000, 240_000)); + else gapMs = Math.round(randRange(rng, 70 * MINUTE_MS, 135 * MINUTE_MS)); + } else if (archetype === 'mixedCadence') { + if (ti < splitPoint) { + gapMs = Math.round(randRange(rng, 25_000, 185_000)); + } else { + gapMs = Math.round(randRange(rng, 9 * MINUTE_MS, 42 * MINUTE_MS)); + } + } else { + // oneShotSparse: 80m..240m (exceeds 1h TTL) + gapMs = Math.round(randRange(rng, 80 * MINUTE_MS, 240 * MINUTE_MS)); + } + + curMs += Math.max(serviceDurationMs + 5000, gapMs); + } + + if (sessionTurnsAdded > 0) { + sessionMeta.push({ sessionId, archetype, minTier, turns: sessionTurnsAdded }); + } + } + } + + // Sort chronologically by arrivalMs, deterministic tie-break on turnId + turns.sort((a, b) => a.arrivalMs - b.arrivalMs || (a.turnId < b.turnId ? -1 : a.turnId > b.turnId ? 1 : 0)); + + const subA = poolConfig.accounts.find((a) => a.id === 'sub-a'); + const subB = poolConfig.accounts.find((a) => a.id === 'sub-b'); + + const subAResetOffsetHours = options.subAResetOffsetHours ?? (2 * 24 + 8); + const subBResetOffsetHours = options.subBResetOffsetHours ?? (5 * 24 + 18); + const subAInitialUsedFrac = options.subAInitialUsedFrac ?? 0.56; + const subBInitialUsedFrac = options.subBInitialUsedFrac ?? 0.18; + + const initialAccountState = { + 'sub-a': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subA?.sevenDayLimit ?? 15_500_000) * subAInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subAResetOffsetHours * HOUR_MS), + }, + 'sub-b': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subB?.sevenDayLimit ?? 12_500_000) * subBInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subBResetOffsetHours * HOUR_MS), + }, + 'secondary-org': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: 0, + sevenDayResetAtMs: null, + }, + }; + + const outages = (options.outages ?? [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ]).map((o) => ({ + accountId: o.accountId, + startMs: startMs + Math.round(o.startHour * HOUR_MS), + endMs: startMs + Math.round(o.startHour * HOUR_MS) + Math.round(o.durationMin * MINUTE_MS), + })); + + return { + name: options.name ?? `seed-${seed}`, + seed, + startMs, + endMs, + startDayOfWeek, + initialAccountState, + outages, + turns, + summary: { + sessions: sessionMeta.length, + turns: turns.length, + fiveHoursMs: FIVE_HOURS_MS, + sevenDaysMs: SEVEN_DAYS_MS, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/src/router.mjs b/questions/opt-routing-cost-sim/v1/controls/incomplete/src/router.mjs new file mode 100644 index 0000000..8b40650 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/src/router.mjs @@ -0,0 +1,133 @@ +/** + * Incomplete Control Router: + * - Protects subscription & secondary-org quota from cheap tier-1 turns (routes tier-1 to payg-t1). + * - Preserves warm-cache session stickiness when prevAccountId is warm and has room. + * - Still ALWAYS uses `cacheMode: '5m'` (no 'none' for 1-shots, no '1h' for slow review sessions). + * - Still no 7d/5h shadow pricing, no tier-2 vs tier-3 quota reservation, no demand forecasting. + */ + +const FIVE_HOUR_TIGHT_FRAC = 0.85; +const FIVE_HOUR_RESET_SOON_MS = 60 * 60_000; +const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +const EXPIRING_URGENCY_THRESHOLD = 2.0; + +function estimateUnits(acc, turn, cacheMode, poolConfig) { + const isWarm = turn.prevAccountId === acc.id + && acc.warmPrefixTokens > 0 + && acc.warmExpiresAtMs !== null; + const cachedRead = isWarm ? Math.min(turn.prefixTokens, acc.warmPrefixTokens) : 0; + const handoff = turn.prevAccountId && turn.prevAccountId !== acc.id + ? Math.min(poolConfig.handoffCapTokens, Math.round(turn.prefixTokens * poolConfig.handoffRate)) + : 0; + const uncached = (turn.prefixTokens - cachedRead) + turn.newInputTokens + handoff; + const writeMult = cacheMode === '5m' + ? acc.pricing.cacheWrite5mMult + : cacheMode === '1h' + ? acc.pricing.cacheWrite1hMult + : 1.0; + const effInput = cachedRead * acc.pricing.cacheReadMult + uncached * writeMult; + return effInput + 3.0 * turn.estOutputTokens; +} + +function isFiveHourTight(acc, nowMs) { + if (acc.fiveHourLimit === null || acc.fiveHourLimit <= 0) return false; + const usedFrac = acc.fiveHourUsed / acc.fiveHourLimit; + if (usedFrac < FIVE_HOUR_TIGHT_FRAC) return false; + if (acc.fiveHourResetAtMs !== null && acc.fiveHourResetAtMs - nowMs <= FIVE_HOUR_RESET_SOON_MS) { + return false; + } + return true; +} + +function sevenDayUrgency(acc, nowMs) { + if (acc.sevenDayLimit === null || acc.sevenDayLimit <= 0 || acc.sevenDayResetAtMs === null) { + return null; + } + const timeLeftMs = acc.sevenDayResetAtMs - nowMs; + if (timeLeftMs <= 0) return null; + const timeLeftFrac = Math.min(1, timeLeftMs / SEVEN_DAYS_MS); + const remFrac = Math.max(0, 1 - acc.sevenDayUsed / acc.sevenDayLimit); + return remFrac / Math.max(1e-4, timeLeftFrac); +} + +export function createCostRouter(poolConfig) { + const accountOrder = new Map(poolConfig.accounts.map((a, idx) => [a.id, idx])); + + function isEligible(acc, nowMs, turn, cacheMode, excluded) { + if (excluded.has(acc.id)) return false; + if (acc.capabilityTier < turn.minTier) return false; + if (acc.cooldownUntilMs !== null && nowMs < acc.cooldownUntilMs) return false; + if (acc.inFlight >= acc.maxInFlight) return false; + const est = estimateUnits(acc, turn, cacheMode, poolConfig) * 1.08; + if (acc.fiveHourLimit !== null && acc.fiveHourUsed + est > acc.fiveHourLimit) return false; + if (acc.sevenDayLimit !== null && acc.sevenDayUsed + est > acc.sevenDayLimit) return false; + return true; + } + + function selectRoute(ctx) { + const { nowMs, excludedAccountIds, turn, accounts } = ctx; + const excluded = new Set(excludedAccountIds); + const cacheMode = '5m'; + + const eligible = accounts.filter((acc) => isEligible(acc, nowMs, turn, cacheMode, excluded)); + if (eligible.length === 0) { + const emergency = accounts + .filter((a) => !excluded.has(a.id) && a.capabilityTier >= turn.minTier) + .sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok); + return { accountId: emergency[0].id, cacheMode }; + } + + // 1. Protect subscriptions & secondary-org from cheap tier-1 turns + if (turn.minTier === 1) { + const payg1 = eligible.find((a) => a.id === 'payg-t1'); + if (payg1) return { accountId: payg1.id, cacheMode }; + } + + // 2. Simple warm-cache session stickiness (avoid breaking warm cache on 85% 5h threshold) + if (turn.prevAccountId) { + const prev = eligible.find((a) => a.id === turn.prevAccountId); + if (prev && prev.warmPrefixTokens > 0 && prev.warmExpiresAtMs !== null && nowMs <= prev.warmExpiresAtMs) { + return { accountId: prev.id, cacheMode }; + } + } + + const primaries = eligible.filter((a) => a.kind === 'subscription'); + const secondaries = eligible.filter((a) => a.kind === 'secondary'); + const paygs = eligible.filter((a) => a.kind === 'payg'); + + // 3. Partial tier-2 protection: avoid draining scarce subscriptions on tier-2 when payg-t2/secondary is available + if (turn.minTier === 2) { + const roomySurplusSub = primaries.find((a) => (sevenDayUrgency(a, nowMs) ?? 0) >= 1.5 && !isFiveHourTight(a, nowMs)); + if (roomySurplusSub) return { accountId: roomySurplusSub.id, cacheMode }; + const secRoomy = secondaries.find((a) => !isFiveHourTight(a, nowMs)); + if (secRoomy) return { accountId: secRoomy.id, cacheMode }; + const payg2 = paygs.find((a) => a.id === 'payg-t2'); + if (payg2) return { accountId: payg2.id, cacheMode }; + } + + const pickPrimary = (list) => { + const expiring = list + .map((acc) => ({ acc, urgency: sevenDayUrgency(acc, nowMs) ?? 0 })) + .filter((x) => x.urgency >= EXPIRING_URGENCY_THRESHOLD) + .sort((a, b) => b.urgency - a.urgency || (accountOrder.get(a.acc.id) - accountOrder.get(b.acc.id))); + if (expiring.length > 0) return expiring[0].acc; + return [...list].sort((a, b) => accountOrder.get(a.id) - accountOrder.get(b.id))[0]; + }; + + const primaryRoomy = primaries.filter((a) => !isFiveHourTight(a, nowMs)); + if (primaryRoomy.length > 0) return { accountId: pickPrimary(primaryRoomy).id, cacheMode }; + + const secondaryRoomy = secondaries.filter((a) => !isFiveHourTight(a, nowMs)); + if (secondaryRoomy.length > 0) return { accountId: secondaryRoomy[0].id, cacheMode }; + + if (primaries.length > 0) return { accountId: pickPrimary(primaries).id, cacheMode }; + if (secondaries.length > 0) return { accountId: secondaries[0].id, cacheMode }; + + const cheapestPayg = [...paygs].sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok)[0]; + return { accountId: cheapestPayg.id, cacheMode }; + } + + function onTurnResult(_outcome) {} + + return { selectRoute, onTurnResult }; +} diff --git a/questions/opt-routing-cost-sim/v1/controls/incomplete/tests/smoke.test.mjs b/questions/opt-routing-cost-sim/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..8606d33 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,144 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + CACHE_1H_TTL_MS, + CACHE_5M_TTL_MS, + SEVEN_DAYS_MS, + computeTurnBilling, + createDefaultPoolConfig, + runSimulation, +} from '../sim/billing-sim.mjs'; +import { + DEFAULT_START_MS, + PUBLIC_SCENARIOS, + generateWorkload, +} from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +test('prompt cache billing arithmetic and exact TTL boundaries', () => { + const pool = createDefaultPoolConfig(); + const payg3 = pool.accounts.find((a) => a.id === 'payg-t3'); + + // Cold 5m write: 10,000 uncached * 1.25 = 12,500 effective input -> $0.125 + 1,000 * $30/M = $0.155 + const cold5m = computeTurnBilling({ + prefixTokens: 8000, + newInputTokens: 2000, + outputTokens: 1000, + cachedReadTokens: 0, + handoffTokens: 0, + cacheMode: '5m', + pricing: payg3.pricing, + }); + assert.equal(cold5m.effectiveInputTokens, 12_500); + assert.ok(Math.abs(cold5m.billedUsd - 0.155) < 1e-9); + + // Warm 1h read: 11,000 * 0.10 + 2,000 * 2.00 = 5,100 effective input + const warm1h = computeTurnBilling({ + prefixTokens: 11_000, + newInputTokens: 2000, + outputTokens: 500, + cachedReadTokens: 11_000, + handoffTokens: 0, + cacheMode: '1h', + pricing: payg3.pricing, + }); + assert.equal(warm1h.effectiveInputTokens, 5100); + + // Verify exact 5m boundary (300_000ms HIT vs 300_001ms MISS) in simulator + const T0 = DEFAULT_START_MS; + const cachedReads = []; + const wl = { + name: 'cache-boundary-sim', + seed: 1, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: {}, + outages: [], + turns: [ + { turnId: 't1', sessionId: 's1', turnIndex: 0, arrivalMs: T0, minTier: 3, prefixTokens: 10_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't2', sessionId: 's1', turnIndex: 1, arrivalMs: T0 + CACHE_5M_TTL_MS, minTier: 3, prefixTokens: 11_500, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't3', sessionId: 's1', turnIndex: 2, arrivalMs: T0 + 2 * CACHE_5M_TTL_MS + 1, minTier: 3, prefixTokens: 13_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + ], + }; + runSimulation({ + workload: wl, + poolConfig: pool, + createRouter: () => ({ + selectRoute: () => ({ accountId: 'payg-t3', cacheMode: '5m' }), + onTurnResult: (o) => { cachedReads.push(o.cachedReadTokens); }, + }), + freezeCtx: true, + }); + assert.deepEqual(cachedReads, [0, 11_500, 0]); +}); + +test('router handles exhausted subscriptions and secondary-org with tier-compliant PAYG fallback', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'exhausted-subscriptions', + seed: 2, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 1_900_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 1_650_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 12_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 1_550_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'x1', sessionId: 'sx1', turnIndex: 0, arrivalMs: T0 + 1000, minTier: 1, prefixTokens: 2000, newInputTokens: 1000, estOutputTokens: 400, actualOutputTokens: 400, serviceDurationMs: 2000 }, + { turnId: 'x2', sessionId: 'sx2', turnIndex: 0, arrivalMs: T0 + 5000, minTier: 2, prefixTokens: 4000, newInputTokens: 1000, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'x3', sessionId: 'sx3', turnIndex: 0, arrivalMs: T0 + 9000, minTier: 3, prefixTokens: 8000, newInputTokens: 1000, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); + assert.equal(res.failedAttempts, 0); +}); + +test('router handles mid-session outage failover, 7d wraparound, and frozen ctx immutability', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'outage-and-wraparound', + seed: 3, + startMs: T0, + endMs: T0 + 2 * SEVEN_DAYS_MS, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + 3_600_000 }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [ + { accountId: 'sub-b', startMs: T0 + 60_000, endMs: T0 + 1_800_000 }, + ], + turns: [ + { turnId: 'm1', sessionId: 'sm1', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 3, prefixTokens: 10_000, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm2', sessionId: 'sm1', turnIndex: 1, arrivalMs: T0 + 120_000, minTier: 3, prefixTokens: 12_100, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm3', sessionId: 'sm1', turnIndex: 2, arrivalMs: T0 + 3_600_000 + CACHE_1H_TTL_MS, minTier: 3, prefixTokens: 14_200, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); +}); + +test('router is deterministic across repeated runs on a public slice', () => { + const pool = createDefaultPoolConfig(); + const wl = generateWorkload({ ...PUBLIC_SCENARIOS[0], demandMultiplier: 0.12, poolConfig: pool }); + const r1 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + const r2 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + + assert.equal(r1.droppedTurns, 0); + assert.equal(r1.tierViolations, 0); + assert.equal(r1.invalidDecisions, 0); + assert.equal(r1.totalCostUsd, r2.totalCostUsd); + assert.equal(r1.failedAttempts, r2.failedAttempts); + assert.deepEqual(r1.cacheStats, r2.cacheStats); +}); diff --git a/questions/opt-routing-cost-sim/v1/question.json b/questions/opt-routing-cost-sim/v1/question.json new file mode 100644 index 0000000..314b8e9 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/question.json @@ -0,0 +1,41 @@ +{ + "id": "opt-routing-cost-sim", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "14 天多账号配额与 Prompt Cache 省钱路由仿真", + "status": "calibrated", + "changeNote": "High-ceiling deterministic online cost-routing optimization question extracted from makecindy/cindy Smart Routing (model-groups/pick.ts, turnRouting.ts, provider-group/scheduler.ts, usage/turnCostCalculator.ts) and agentcompass/engine/quota-economy.mjs.", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "cost_efficiency", + "weight": "1", + "mode": "metric", + "gate": [ + "gate_all_served", + "gate_tier_floor", + "gate_latency_sla", + "gate_causal_and_fast" + ], + "metric": { + "id": "total_cost_usd", + "label": "Mean 14-day held-out cost", + "unit": "$", + "direction": "lower", + "baseline": 825, + "target": 100, + "scale": "log" + } + } + ] +} diff --git a/questions/opt-routing-cost-sim/v1/reference/CONTRACT.md b/questions/opt-routing-cost-sim/v1/reference/CONTRACT.md new file mode 100644 index 0000000..6e9f06b --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/CONTRACT.md @@ -0,0 +1,77 @@ +# Router & Simulator Contract + +This contract specifies the immutable billing/quota/prompt-cache physics (`sim/billing-sim.mjs`) and the causal online router interface (`src/router.mjs`). Within these invariants, you are free to implement any online algorithm inside `src/` (including helper modules imported by `src/router.mjs`). + +## 1. Public Router API (`src/router.mjs`) + +- Must export `createCostRouter(poolConfig)` returning `{ selectRoute(ctx), onTurnResult(outcome) }`. +- Both `poolConfig`, `ctx`, and `outcome` may be deeply frozen; mutating any input object is forbidden and fails `gate_causal_and_fast`. +- The router must be **strictly deterministic** (no `Math.random()`, no `Date.now()` wall-clock branching). + +### `poolConfig` +- `accounts`: array of 6 account specs (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), each with `{ id, kind, capabilityTier, pricing: { inputPerMTok, outputPerMTok, cacheReadMult, cacheWrite5mMult, cacheWrite1hMult }, quotaOutputWeight, fiveHourLimit, sevenDayLimit, maxInFlight, supportedCacheModes }`. +- `cacheTtlMs`: `{ '5m': 300_000, '1h': 3_600_000 }`. +- `handoffRate`: `0.08`, `handoffCapTokens`: `4000`, `retryDelayMs`: `1200`, `maxAttempts`: `4`. + +### `selectRoute(ctx)` → `{ accountId: string, cacheMode: 'none' | '5m' | '1h' }` +`ctx` contains ONLY causal present and past state (zero future lookahead, zero session archetype labels): +- `nowMs`: virtual timestamp (ms). +- `attempt`: `0 .. maxAttempts - 1`. +- `excludedAccountIds`: accounts already attempted and failed for this turn (must NOT be selected again). +- `turn`: `{ sessionId, turnIndex, minTier, prefixTokens, newInputTokens, estOutputTokens, prevAccountId, prevTurnAtMs, prevCacheMode, sessionTurnsSoFar, recentGapMsList }`. + - `estOutputTokens` is an unbiased estimate within ±12% of the turn's actual output tokens. + - `recentGapMsList` holds up to the last 8 observed inter-turn gaps (ms) in this session (empty on `turnIndex === 0`). +- `accounts`: snapshot of all 6 accounts at `nowMs`: + `{ id, kind, capabilityTier, pricing, fiveHourUsed, fiveHourLimit, fiveHourResetAtMs, sevenDayUsed, sevenDayLimit, sevenDayResetAtMs, inFlight, maxInFlight, cooldownUntilMs, warmPrefixTokens, warmExpiresAtMs }`. + - `warmPrefixTokens > 0 && warmExpiresAtMs !== null && nowMs <= warmExpiresAtMs` iff this session currently has a live warm prompt cache on that account (which requires continuing on `prevAccountId`). + +### `onTurnResult(outcome)` +Called after every attempt (both failed and succeeded): +- `{ nowMs, sessionId, accountId, cacheMode, ok, errorCode, billedUsd, quotaUnitsCharged, cachedReadTokens, actualOutputTokens, latencyMs }`. + +## 2. Exact Billing, Prompt-Cache & Quota Physics (`sim/billing-sim.mjs`) + +### Account Pool +| Account | Kind | Tier | Pricing (`$/MTok` in / out) | `5h` Cap (weighted tok) | `7d` Cap (weighted tok) | `maxInFlight` | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `sub-a` | `subscription` | 3 | `$0.00 / $0.00` | `1,900,000` | `15,500,000` | 4 | Staggered weekly `7d` reset; unused `7d` expires | +| `sub-b` | `subscription` | 3 | `$0.00 / $0.00` | `1,650,000` | `12,500,000` | 3 | Different staggered `7d` reset + occasional outages | +| `secondary-org` | `secondary` | 3 | `$1.50 / $7.50` | `1,550,000` | unlimited | 6 | Discounted org pool; transient 429 risk when `inFlight >= 3` or `5h >= 85%` | +| `payg-t1` | `payg` | 1 | `$0.50 / $2.50` | unlimited | unlimited | 64 | Unlimited PAYG fast/mini | +| `payg-t2` | `payg` | 2 | `$3.00 / $15.00` | unlimited | unlimited | 64 | Unlimited PAYG balanced | +| `payg-t3` | `payg` | 3 | `$10.00 / $30.00` | unlimited | unlimited | 64 | Unlimited PAYG frontier | + +All 6 accounts support `cacheMode` in `['none', '5m', '1h']`. + +### Prompt Cache & Handoff Arithmetic +For a turn `(prefixTokens, newInputTokens, actualOutputTokens)` served on `accountId` with `cacheMode`: +1. **Cache read**: If `(!prevAccountId || prevAccountId === accountId)` and a live cache exists for `(sessionId, accountId)` with `nowMs <= warm.expiresAtMs`, then `cachedReadTokens = min(prefixTokens, warm.warmPrefixTokens)`. Otherwise `cachedReadTokens = 0`. +2. **Cross-account handoff**: If `prevAccountId && prevAccountId !== accountId`, `handoffTokens = min(4000, Math.round(prefixTokens * 0.08))`; otherwise `0`. +3. **Uncached input**: `uncachedInputTokens = (prefixTokens - cachedReadTokens) + newInputTokens + handoffTokens`. +4. **Effective input tokens**: + - `'none'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.00` (leaves same-account warm entry unchanged; does not populate new cache). + - `'5m'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 1.25` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 300_000 }`). + - `'1h'`: `cachedReadTokens * 0.10 + uncachedInputTokens * 2.00` (sets warm cache to `{ warmPrefixTokens: prefixTokens + newInputTokens + actualOutputTokens, expiresAtMs: nowMs + 3_600_000 }`). +5. **Dollar cost**: `billedUsd = (effectiveInputTokens * inputPerMTok + actualOutputTokens * outputPerMTok) / 1_000_000`. +6. **Quota units** (on accounts with finite `5h` or `7d` limits): `quotaUnitsCharged = effectiveInputTokens + 3.0 * actualOutputTokens`. + - `5h` rolling window starts on first spend (`fiveHourResetAtMs = nowMs + 5h`) and resets to `0` once `nowMs >= fiveHourResetAtMs`. + - `7d` weekly window resets on its staggered schedule (`sevenDayResetAtMs += 7d`); any unused `7d` quota expires at reset. + +### Failure, Outage & Retry Semantics +- An attempt fails (returning `errorCode` and incurring `1200 ms` stall delay before immediate re-query up to 4 attempts) if: + - `INVALID_ROUTE` (unknown account, excluded account, or invalid `cacheMode`), + - `COOLDOWN` (`nowMs < cooldownUntilMs`), + - `PROVIDER_OUTAGE` (scheduled outage; sets `cooldownUntilMs = nowMs + 180_000`), + - `CONCURRENCY_LIMIT` (`inFlight >= maxInFlight`), + - `RATE_LIMITED_7D` (`sevenDayUsed + quotaUnitsCharged > sevenDayLimit`), + - `RATE_LIMITED_5H` (`fiveHourUsed + quotaUnitsCharged > fiveHourLimit`), + - `TRANSIENT_429` (`secondary-org` load-dependent transient rate limit; sets `cooldownUntilMs = nowMs + 15_000`). +- Failing all 4 attempts drops the turn (`droppedTurns += 1`, failing `gate_all_served`). + +## 3. Hard Gates & Metric + +- `gate_all_served`: `droppedTurns === 0 && invalidDecisions === 0` across all unit tests, public trace, and unseen held-out traces. +- `gate_tier_floor`: `tierViolations === 0` (`capabilityTier >= turn.minTier` on 100% of turns). +- `gate_latency_sla`: `p99StallMs <= 3000` and `failedAttemptRate < 0.02` on every trace. +- `gate_causal_and_fast`: passes all frozen-context immutability and edge-case tests, deterministic, and `< 4000 ms` per 14-day simulation. +- **Primary metric**: `total_cost_usd` — mean 14-day USD bill across unseen held-out 14-day traces (lower is better, log-scaled between baseline and offline lower-bound target). diff --git a/questions/opt-routing-cost-sim/v1/reference/ENVIRONMENT.md b/questions/opt-routing-cost-sim/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..9a166d6 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/ENVIRONMENT.md @@ -0,0 +1,9 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, fully offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock and seeded deterministic traffic/failure generators — dollar cost, quota consumption, cache hits, and stall latencies are exact, hardware-independent numbers. +- Protected files: `sim/`, `bench/`, `tests/`, `package.json`, `TASK.md`, `CONTRACT.md`, `ENVIRONMENT.md` are read-only and verified by the submission gate; edit ONLY files under `src/`. +- Public checks: + - `npm test` — functional correctness, billing physics, immutability, determinism, and edge-case smoke tests + - `npm run bench` — deterministic 14-day public benchmark (2 distinct 14-day traces) reporting USD bill, per-account breakdown, expired `7d` quota, cache hit rate, latency SLA, and runtime diff --git a/questions/opt-routing-cost-sim/v1/reference/TASK.md b/questions/opt-routing-cost-sim/v1/reference/TASK.md new file mode 100644 index 0000000..3f45e35 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/TASK.md @@ -0,0 +1,29 @@ +# Task + +You are optimizing Cindy's online multi-account quota & prompt-cache cost router (`src/router.mjs`) extracted from production Smart Routing (`model-groups/pick.ts`, `turnRouting.ts`, `provider-group/scheduler.ts`, `usage/turnCostCalculator.ts`, and `agentcompass/engine/quota-economy.mjs`). + +## Observed Production Symptoms + +Over a realistic 14-day multi-turn coding and chat workload (~12,000 turns across ~600–750 sessions) sharing a **6-account multi-tier pool** (`sub-a`, `sub-b`, `secondary-org`, `payg-t1`, `payg-t2`, `payg-t3`), the current baseline router (`src/router.mjs`) racks up **~$800–$900 per 14 days** while leaving huge savings on the table: + +1. **Unprotected subscription quota**: Sends cheap `tier-1` (`$0.50/$2.50` PAYG alternative) and `tier-2` (`$3/$15`) turns straight onto scarce `$0`-marginal-cost subscriptions (`sub-a`, `sub-b`), burning weekly `7d` and rolling `5h` quotas early and forcing expensive `tier-3` (`$10/$30`) turns onto `payg-t3`. +2. **Rigid `'5m'`-only prompt caching**: Always sets `cacheMode: '5m'` on every turn: + - On **slow review/thinking sessions** (inter-turn gaps of 8–44 minutes), `'5m'` expires on every turn, re-paying `1.25×` write cost on growing 20k–80k prefixes instead of using `'1h'` (`2.0×` write once, `0.10×` reads thereafter). + - On **one-shot and ultra-sparse jobs** (including large batch summaries), `'5m'` pays an unnecessary `1.25×` write tax that is never read again instead of `'none'` (`1.0×`). + - On subscriptions (`sub-a`, `sub-b`), keeping warm prompt caches also stretches `5h` and `7d` quota **5–8× further** because cache reads consume only `0.10×` quota units. +3. **Cache-breaking transitions & binary cutoffs**: Breaks warm prompt caches blindly when crossing a fixed 85% `5h` cutoff or on concurrency ties, incurring both a cold re-write and an 8% cross-account handoff overhead (`min(4000, round(0.08 * prefixTokens))`). +4. **No online demand forecasting, shadow pricing, or staggered `7d` expiry pacing**: Fails to balance `sub-a` and `sub-b` across staggered weekly resets, weekday peaks vs quiet nights/weekends, `secondary-org` load-dependent transient 429s, and `sub-b` outage windows. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% of all four hard gates** (verified on unit edge cases, public traces, AND unseen held-out 14-day traces with different weekday/weekend phases, burst schedules, staggered reset offsets, session mixtures, and outages): + 1. `gate_all_served`: 100% of turns served (`0` dropped turns, `0` invalid routes). + 2. `gate_tier_floor`: 100% of turns routed to an account with `capabilityTier >= turn.minTier`. + 3. `gate_latency_sla`: P99 turn stall/retry delay `<= 3000 ms` and failed-attempt rate `< 2%`. + 4. `gate_causal_and_fast`: Strictly online/causal, never mutates frozen `ctx`/`outcome`/`poolConfig`, passes all edge-case checks, deterministic across runs, and completes each 14-day simulation in `< 4s`. +- **Open-ended optimization goal**: Design the strongest online routing & prompt-cache algorithm inside `src/` to drive the mean 14-day USD bill (`total_cost_usd`) as low as possible — without overfitting to public seeds! +- Run `npm test` and `npm run bench` to verify correctness and measure before/after savings. +- Record your analysis, algorithm design, trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;不可修改 `sim/`、`bench/`、`tests/`、`package.json`、`CONTRACT.md`、`ENVIRONMENT.md` 或 `TASK.md`。 diff --git a/questions/opt-routing-cost-sim/v1/reference/bench/run-bench.mjs b/questions/opt-routing-cost-sim/v1/reference/bench/run-bench.mjs new file mode 100644 index 0000000..ecf34d4 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/bench/run-bench.mjs @@ -0,0 +1,51 @@ +/** + * Public 14-day routing cost benchmark (protected read-only). + * Runs the 2 public 14-day scenarios with frozen contexts and reports full diagnostics. + */ + +import { createDefaultPoolConfig, runSimulation } from '../sim/billing-sim.mjs'; +import { PUBLIC_SCENARIOS, generateWorkload } from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +const poolConfig = createDefaultPoolConfig(); +let costSum = 0; +let allGatesPass = true; + +console.log('=== opt-routing-cost-sim Public 14-Day Benchmark ===\n'); + +for (const sc of PUBLIC_SCENARIOS) { + const workload = generateWorkload({ ...sc, poolConfig }); + const res = runSimulation({ + workload, + poolConfig, + createRouter: createCostRouter, + freezeCtx: true, + }); + + const servedOk = res.droppedTurns === 0 && res.invalidDecisions === 0; + const tierOk = res.tierViolations === 0; + const slaOk = res.p99StallMs <= 3000 && res.failedAttemptRate < 0.02; + const fastOk = res.runtimeMs < 4000; + const pass = servedOk && tierOk && slaOk && fastOk; + if (!pass) allGatesPass = false; + + costSum += res.totalCostUsd; + + console.log(`[${sc.name}] sessions=${workload.summary.sessions} turns=${res.totalTurns}`); + console.log(` Total 14d Cost : $${res.totalCostUsd.toFixed(2)}`); + console.log(` Gates : served=${servedOk} tierFloor=${tierOk} latencySla=${slaOk} fast=${fastOk}`); + console.log(` SLA & Perf : p99Stall=${res.p99StallMs}ms failRate=${(res.failedAttemptRate * 100).toFixed(2)}% runtime=${res.runtimeMs.toFixed(1)}ms`); + console.log(` Prompt Cache : hitRate=${(res.cacheStats.cacheHitRate * 100).toFixed(1)}% handoffTok=${res.cacheStats.handoffTokens} modes=${JSON.stringify(res.cacheStats.byMode)}`); + console.log(` Expired 7d Quota : sub-a=${(res.expiredQuotaUnits['sub-a'] / 1e6).toFixed(2)}M sub-b=${(res.expiredQuotaUnits['sub-b'] / 1e6).toFixed(2)}M`); + console.log(' Account Breakdown:'); + for (const [id, st] of Object.entries(res.byAccount)) { + console.log( + ` ${id.padEnd(14)} turns=${String(st.turns).padStart(5)} usd=$${st.billedUsd.toFixed(2).padStart(7)} quota=${(st.quotaUnits / 1e6).toFixed(2).padStart(5)}M fails=${String(st.failedAttempts).padStart(3)} modes=${JSON.stringify(st.cacheModes)}`, + ); + } + console.log(''); +} + +const meanCost = costSum / PUBLIC_SCENARIOS.length; +console.log(`Public Mean 14-day Cost: $${meanCost.toFixed(2)} (gates=${allGatesPass ? 'PASS' : 'FAIL'})`); +if (!allGatesPass) process.exitCode = 1; diff --git a/questions/opt-routing-cost-sim/v1/reference/package.json b/questions/opt-routing-cost-sim/v1/reference/package.json new file mode 100644 index 0000000..d840cd2 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-opt-routing-cost-sim", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/run-bench.mjs" + } +} diff --git a/questions/opt-routing-cost-sim/v1/reference/sim/billing-sim.mjs b/questions/opt-routing-cost-sim/v1/reference/sim/billing-sim.mjs new file mode 100644 index 0000000..116e455 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/sim/billing-sim.mjs @@ -0,0 +1,697 @@ +/** + * Immutable 14-day multi-account billing, quota, concurrency, and prompt-cache simulator. + * Protected read-only: candidates must optimize `src/router.mjs` against this exact physics engine. + */ + +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +export const CACHE_5M_TTL_MS = 5 * 60_000; +export const CACHE_1H_TTL_MS = 60 * 60_000; + +export const VALID_CACHE_MODES = Object.freeze(['none', '5m', '1h']); +const VALID_CACHE_MODE_SET = new Set(VALID_CACHE_MODES); + +export const DEFAULT_HANDOFF_RATE = 0.08; +export const DEFAULT_HANDOFF_CAP_TOKENS = 4000; +export const DEFAULT_RETRY_DELAY_MS = 1200; +export const DEFAULT_MAX_ATTEMPTS = 4; +export const DEFAULT_QUOTA_OUTPUT_WEIGHT = 3.0; +export const OUTAGE_COOLDOWN_MS = 180_000; + +export function createDefaultPoolConfig(overrides = {}) { + const baseAccounts = [ + { + id: 'sub-a', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subAFiveHourLimit ?? 1_900_000, + sevenDayLimit: overrides.subASevenDayLimit ?? 15_500_000, + maxInFlight: 4, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'sub-b', + kind: 'subscription', + capabilityTier: 3, + pricing: { + inputPerMTok: 0, + outputPerMTok: 0, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.subBFiveHourLimit ?? 1_650_000, + sevenDayLimit: overrides.subBSevenDayLimit ?? 12_500_000, + maxInFlight: 3, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'secondary-org', + kind: 'secondary', + capabilityTier: 3, + pricing: { + inputPerMTok: 1.50, + outputPerMTok: 7.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: overrides.secondaryFiveHourLimit ?? 1_550_000, + sevenDayLimit: null, + maxInFlight: 6, + supportedCacheModes: ['none', '5m', '1h'], + transient429: { + inFlightThreshold: 3, + inFlightProbStep: 0.10, + fiveHourFracThreshold: 0.85, + fiveHourProb: 0.14, + cooldownMs: 15_000, + }, + }, + { + id: 'payg-t1', + kind: 'payg', + capabilityTier: 1, + pricing: { + inputPerMTok: 0.50, + outputPerMTok: 2.50, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t2', + kind: 'payg', + capabilityTier: 2, + pricing: { + inputPerMTok: 3.00, + outputPerMTok: 15.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + { + id: 'payg-t3', + kind: 'payg', + capabilityTier: 3, + pricing: { + inputPerMTok: 10.00, + outputPerMTok: 30.00, + cacheReadMult: 0.10, + cacheWrite5mMult: 1.25, + cacheWrite1hMult: 2.00, + }, + quotaOutputWeight: DEFAULT_QUOTA_OUTPUT_WEIGHT, + fiveHourLimit: null, + sevenDayLimit: null, + maxInFlight: 64, + supportedCacheModes: ['none', '5m', '1h'], + transient429: null, + }, + ]; + + return { + accounts: baseAccounts, + cacheTtlMs: { + '5m': CACHE_5M_TTL_MS, + '1h': CACHE_1H_TTL_MS, + }, + handoffRate: DEFAULT_HANDOFF_RATE, + handoffCapTokens: DEFAULT_HANDOFF_CAP_TOKENS, + retryDelayMs: DEFAULT_RETRY_DELAY_MS, + maxAttempts: DEFAULT_MAX_ATTEMPTS, + }; +} + +export function cacheWriteMultiplier(pricing, cacheMode) { + if (cacheMode === '5m') return pricing.cacheWrite5mMult; + if (cacheMode === '1h') return pricing.cacheWrite1hMult; + return 1.0; +} + +export function computeTurnBilling({ + prefixTokens, + newInputTokens, + outputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing, + quotaOutputWeight = DEFAULT_QUOTA_OUTPUT_WEIGHT, + meteredQuota = false, +}) { + const safeCached = Math.max(0, Math.min(prefixTokens, cachedReadTokens)); + const uncachedInputTokens = (prefixTokens - safeCached) + newInputTokens + handoffTokens; + const writeMult = cacheWriteMultiplier(pricing, cacheMode); + const readMult = pricing.cacheReadMult; + const effectiveInputTokens = safeCached * readMult + uncachedInputTokens * writeMult; + const billedUsd = (effectiveInputTokens * pricing.inputPerMTok + outputTokens * pricing.outputPerMTok) / 1_000_000; + const quotaUnitsCharged = meteredQuota ? effectiveInputTokens + quotaOutputWeight * outputTokens : 0; + return { + cachedReadTokens: safeCached, + uncachedInputTokens, + effectiveInputTokens, + billedUsd, + quotaUnitsCharged, + }; +} + +function deepFreeze(obj) { + if (!obj || typeof obj !== 'object' || Object.isFrozen(obj)) return obj; + Object.freeze(obj); + for (const val of Object.values(obj)) { + deepFreeze(val); + } + return obj; +} + +function deterministicUnitHash(seed, turnId, attempt, accountId) { + let h = (2166136261 ^ (seed >>> 0)) >>> 0; + const str = `${turnId}|${attempt}|${accountId}`; + for (let i = 0; i < str.length; i += 1) { + h ^= str.charCodeAt(i); + h = Math.imul(h, 16777619) >>> 0; + } + h ^= h >>> 16; + h = Math.imul(h, 0x7feb352d) >>> 0; + h ^= h >>> 15; + h = Math.imul(h, 0x846ca68b) >>> 0; + h ^= h >>> 16; + return (h >>> 0) / 4294967296; +} + +function percentile(sorted, p) { + if (sorted.length === 0) return 0; + const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1)); + return sorted[idx]; +} + +function clonePublicPoolConfig(poolConfig) { + return { + accounts: poolConfig.accounts.map((a) => ({ + id: a.id, + kind: a.kind, + capabilityTier: a.capabilityTier, + pricing: { ...a.pricing }, + quotaOutputWeight: a.quotaOutputWeight, + fiveHourLimit: a.fiveHourLimit, + sevenDayLimit: a.sevenDayLimit, + maxInFlight: a.maxInFlight, + supportedCacheModes: [...a.supportedCacheModes], + })), + cacheTtlMs: { ...poolConfig.cacheTtlMs }, + handoffRate: poolConfig.handoffRate, + handoffCapTokens: poolConfig.handoffCapTokens, + retryDelayMs: poolConfig.retryDelayMs, + maxAttempts: poolConfig.maxAttempts, + }; +} + +/** + * Runs a complete deterministic simulation over a workload trace. + * + * @param {object} params + * @param {object} params.workload - Output of generateWorkload() or custom unit-test workload + * @param {object} [params.poolConfig] - Account pool specification + * @param {Function} params.createRouter - Factory `(poolConfig) => ({ selectRoute, onTurnResult })` + * @param {boolean} [params.freezeCtx=false] - Deep-freeze ctx/outcome objects to enforce immutability + */ +export function runSimulation({ + workload, + poolConfig = createDefaultPoolConfig(), + createRouter, + freezeCtx = false, +}) { + const tStart = performance.now(); + const publicPool = clonePublicPoolConfig(poolConfig); + if (freezeCtx) deepFreeze(publicPool); + + const router = createRouter(publicPool); + if (!router || typeof router.selectRoute !== 'function' || typeof router.onTurnResult !== 'function') { + throw new Error('createCostRouter(poolConfig) must return { selectRoute, onTurnResult }'); + } + + const startMs = workload.startMs; + const initialAccountState = workload.initialAccountState ?? {}; + const outages = workload.outages ?? []; + const seed = workload.seed ?? 1; + + // Group outages by accountId for fast lookup + const outagesByAccount = new Map(); + for (const o of outages) { + let list = outagesByAccount.get(o.accountId); + if (!list) { + list = []; + outagesByAccount.set(o.accountId, list); + } + list.push(o); + } + + const accounts = poolConfig.accounts.map((cfg) => { + const init = initialAccountState[cfg.id] ?? {}; + return { + cfg, + id: cfg.id, + fiveHourUsed: init.fiveHourUsed ?? 0, + fiveHourResetAtMs: cfg.fiveHourLimit !== null ? (init.fiveHourResetAtMs ?? null) : null, + sevenDayUsed: init.sevenDayUsed ?? 0, + sevenDayResetAtMs: cfg.sevenDayLimit !== null ? (init.sevenDayResetAtMs ?? (startMs + SEVEN_DAYS_MS)) : null, + cooldownUntilMs: init.cooldownUntilMs ?? null, + activeEnds: [], + stats: { + turns: 0, + billedUsd: 0, + quotaUnits: 0, + cachedReadTokens: 0, + uncachedInputTokens: 0, + handoffTokens: 0, + outputTokens: 0, + failedAttempts: 0, + cacheModes: { none: 0, '5m': 0, '1h': 0 }, + }, + }; + }); + const accountById = new Map(accounts.map((a) => [a.id, a])); + const expiredQuotaUnits = Object.fromEntries( + accounts.filter((a) => a.cfg.sevenDayLimit !== null).map((a) => [a.id, 0]), + ); + + // Per-session runtime state: { prevAccountId, prevTurnAtMs, prevCacheMode, turnsSoFar, recentGapMsList, warm: { accountId, warmPrefixTokens, expiresAtMs } | null } + const sessions = new Map(); + + let totalCostUsd = 0; + let servedTurns = 0; + let droppedTurns = 0; + let tierViolations = 0; + let invalidDecisions = 0; + let totalAttempts = 0; + let failedAttempts = 0; + let totalPrefixTokens = 0; + let totalCachedReadTokens = 0; + let totalHandoffTokens = 0; + const cacheModeCounts = { none: 0, '5m': 0, '1h': 0 }; + const byTier = { + 1: { turns: 0, billedUsd: 0, byAccount: {} }, + 2: { turns: 0, billedUsd: 0, byAccount: {} }, + 3: { turns: 0, billedUsd: 0, byAccount: {} }, + }; + const stallDelays = []; + + function syncAccounts(nowMs) { + for (const acc of accounts) { + // Retire finished in-flight turns + if (acc.activeEnds.length > 0) { + let writeIdx = 0; + for (let i = 0; i < acc.activeEnds.length; i += 1) { + if (acc.activeEnds[i] > nowMs) { + acc.activeEnds[writeIdx] = acc.activeEnds[i]; + writeIdx += 1; + } + } + acc.activeEnds.length = writeIdx; + } + + // Reset expired 5h rolling window + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourResetAtMs !== null && nowMs >= acc.fiveHourResetAtMs) { + acc.fiveHourUsed = 0; + acc.fiveHourResetAtMs = null; + } + + // Reset expired 7d weekly window(s) + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayResetAtMs !== null && nowMs >= acc.sevenDayResetAtMs) { + const wasted = Math.max(0, acc.cfg.sevenDayLimit - acc.sevenDayUsed); + expiredQuotaUnits[acc.id] += wasted; + const periods = Math.floor((nowMs - acc.sevenDayResetAtMs) / SEVEN_DAYS_MS) + 1; + if (periods > 1) { + expiredQuotaUnits[acc.id] += (periods - 1) * acc.cfg.sevenDayLimit; + } + acc.sevenDayResetAtMs += periods * SEVEN_DAYS_MS; + acc.sevenDayUsed = 0; + } + + // Clear expired cooldown + if (acc.cooldownUntilMs !== null && nowMs >= acc.cooldownUntilMs) { + acc.cooldownUntilMs = null; + } + } + } + + function isInOutage(accountId, nowMs) { + const list = outagesByAccount.get(accountId); + if (!list) return false; + for (let i = 0; i < list.length; i += 1) { + const o = list[i]; + if (nowMs >= o.startMs && nowMs < o.endMs) return true; + } + return false; + } + + function checkTransient429(acc, turnId, attempt, nowMs) { + const tCfg = acc.cfg.transient429; + if (!tCfg) return false; + let prob = 0; + const inFlight = acc.activeEnds.length; + if (inFlight >= tCfg.inFlightThreshold) { + prob = Math.max(prob, (inFlight - tCfg.inFlightThreshold + 1) * tCfg.inFlightProbStep); + } + if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed / acc.cfg.fiveHourLimit >= tCfg.fiveHourFracThreshold) { + prob = Math.max(prob, tCfg.fiveHourProb); + } + if (prob <= 0) return false; + const u = deterministicUnitHash(seed, turnId, attempt, acc.id); + if (u < prob) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, nowMs + tCfg.cooldownMs); + return true; + } + return false; + } + + const turns = workload.turns; + const maxAttempts = poolConfig.maxAttempts ?? DEFAULT_MAX_ATTEMPTS; + const retryDelayMs = poolConfig.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; + const handoffRate = poolConfig.handoffRate ?? DEFAULT_HANDOFF_RATE; + const handoffCapTokens = poolConfig.handoffCapTokens ?? DEFAULT_HANDOFF_CAP_TOKENS; + + for (let ti = 0; ti < turns.length; ti += 1) { + const turn = turns[ti]; + let sess = sessions.get(turn.sessionId); + if (!sess) { + sess = { + prevAccountId: null, + prevTurnAtMs: null, + prevCacheMode: null, + turnsSoFar: 0, + recentGapMsList: [], + warm: null, + }; + sessions.set(turn.sessionId, sess); + } + + const excluded = []; + let attemptNowMs = turn.arrivalMs; + let stallDelayMs = 0; + let served = false; + + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + totalAttempts += 1; + syncAccounts(attemptNowMs); + + // Clear expired warm entry for this session + if (sess.warm && attemptNowMs > sess.warm.expiresAtMs) { + sess.warm = null; + } + + const accountsSnapshot = accounts.map((acc) => { + const isWarmHere = sess.warm !== null + && sess.prevAccountId === acc.id + && sess.warm.accountId === acc.id + && attemptNowMs <= sess.warm.expiresAtMs; + return { + id: acc.id, + kind: acc.cfg.kind, + capabilityTier: acc.cfg.capabilityTier, + pricing: { ...acc.cfg.pricing }, + fiveHourUsed: acc.fiveHourUsed, + fiveHourLimit: acc.cfg.fiveHourLimit, + fiveHourResetAtMs: acc.fiveHourResetAtMs, + sevenDayUsed: acc.sevenDayUsed, + sevenDayLimit: acc.cfg.sevenDayLimit, + sevenDayResetAtMs: acc.sevenDayResetAtMs, + inFlight: acc.activeEnds.length, + maxInFlight: acc.cfg.maxInFlight, + cooldownUntilMs: acc.cooldownUntilMs, + warmPrefixTokens: isWarmHere ? sess.warm.warmPrefixTokens : 0, + warmExpiresAtMs: isWarmHere ? sess.warm.expiresAtMs : null, + }; + }); + + const ctx = { + nowMs: attemptNowMs, + attempt, + excludedAccountIds: [...excluded], + turn: { + sessionId: turn.sessionId, + turnIndex: turn.turnIndex, + minTier: turn.minTier, + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + estOutputTokens: turn.estOutputTokens, + prevAccountId: sess.prevAccountId, + prevTurnAtMs: sess.prevTurnAtMs, + prevCacheMode: sess.prevCacheMode, + sessionTurnsSoFar: sess.turnsSoFar, + recentGapMsList: [...sess.recentGapMsList], + }, + accounts: accountsSnapshot, + }; + if (freezeCtx) deepFreeze(ctx); + + const decision = router.selectRoute(ctx); + const accountId = decision && typeof decision.accountId === 'string' ? decision.accountId : ''; + const cacheMode = decision && typeof decision.cacheMode === 'string' ? decision.cacheMode : ''; + const acc = accountById.get(accountId); + + let errorCode = null; + if (!acc || !VALID_CACHE_MODE_SET.has(cacheMode) || excluded.includes(accountId)) { + errorCode = 'INVALID_ROUTE'; + invalidDecisions += 1; + } else if (acc.cooldownUntilMs !== null && attemptNowMs < acc.cooldownUntilMs) { + errorCode = 'COOLDOWN'; + } else if (isInOutage(accountId, attemptNowMs)) { + acc.cooldownUntilMs = Math.max(acc.cooldownUntilMs ?? 0, attemptNowMs + OUTAGE_COOLDOWN_MS); + errorCode = 'PROVIDER_OUTAGE'; + } else if (acc.activeEnds.length >= acc.cfg.maxInFlight) { + errorCode = 'CONCURRENCY_LIMIT'; + } + + // Compute exact billing & quota units for admission check + let billing = null; + let handoffTokens = 0; + if (!errorCode) { + const sameAsPrev = !sess.prevAccountId || sess.prevAccountId === accountId; + const isWarmHit = sameAsPrev + && sess.warm !== null + && sess.warm.accountId === accountId + && attemptNowMs <= sess.warm.expiresAtMs; + const cachedReadTokens = isWarmHit ? Math.min(turn.prefixTokens, sess.warm.warmPrefixTokens) : 0; + handoffTokens = sess.prevAccountId && sess.prevAccountId !== accountId + ? Math.min(handoffCapTokens, Math.round(turn.prefixTokens * handoffRate)) + : 0; + const meteredQuota = acc.cfg.fiveHourLimit !== null || acc.cfg.sevenDayLimit !== null; + billing = computeTurnBilling({ + prefixTokens: turn.prefixTokens, + newInputTokens: turn.newInputTokens, + outputTokens: turn.actualOutputTokens, + cachedReadTokens, + handoffTokens, + cacheMode, + pricing: acc.cfg.pricing, + quotaOutputWeight: acc.cfg.quotaOutputWeight, + meteredQuota, + }); + + if (acc.cfg.sevenDayLimit !== null && acc.sevenDayUsed + billing.quotaUnitsCharged > acc.cfg.sevenDayLimit) { + errorCode = 'RATE_LIMITED_7D'; + } else if (acc.cfg.fiveHourLimit !== null && acc.fiveHourUsed + billing.quotaUnitsCharged > acc.cfg.fiveHourLimit) { + errorCode = 'RATE_LIMITED_5H'; + } else if (checkTransient429(acc, turn.turnId, attempt, attemptNowMs)) { + errorCode = 'TRANSIENT_429'; + } + } + + if (errorCode) { + failedAttempts += 1; + if (acc) acc.stats.failedAttempts += 1; + stallDelayMs += retryDelayMs; + attemptNowMs += retryDelayMs; + if (accountId && !excluded.includes(accountId)) excluded.push(accountId); + const failOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode: VALID_CACHE_MODE_SET.has(cacheMode) ? cacheMode : 'none', + ok: false, + errorCode, + billedUsd: 0, + quotaUnitsCharged: 0, + cachedReadTokens: 0, + actualOutputTokens: 0, + latencyMs: retryDelayMs, + }; + if (freezeCtx) deepFreeze(failOutcome); + router.onTurnResult(failOutcome); + continue; + } + + // Success! + served = true; + servedTurns += 1; + if (acc.cfg.capabilityTier < turn.minTier) { + tierViolations += 1; + } + + if (acc.cfg.fiveHourLimit !== null) { + if (acc.fiveHourResetAtMs === null) { + acc.fiveHourResetAtMs = attemptNowMs + FIVE_HOURS_MS; + } + acc.fiveHourUsed += billing.quotaUnitsCharged; + } + if (acc.cfg.sevenDayLimit !== null) { + acc.sevenDayUsed += billing.quotaUnitsCharged; + } + + acc.activeEnds.push(attemptNowMs + turn.serviceDurationMs); + + // Update cache state + const switchedAccount = sess.prevAccountId !== null && sess.prevAccountId !== accountId; + if (switchedAccount) { + sess.warm = null; + } + const nextWarmPrefix = turn.prefixTokens + turn.newInputTokens + turn.actualOutputTokens; + if (cacheMode === '5m') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['5m'], + }; + } else if (cacheMode === '1h') { + sess.warm = { + accountId, + warmPrefixTokens: nextWarmPrefix, + expiresAtMs: attemptNowMs + poolConfig.cacheTtlMs['1h'], + }; + } + // If cacheMode === 'none': warm is unchanged on same account (already cleared if switched or expired) + + if (sess.prevTurnAtMs !== null) { + const gapMs = Math.max(0, attemptNowMs - sess.prevTurnAtMs); + sess.recentGapMsList.push(gapMs); + if (sess.recentGapMsList.length > 8) sess.recentGapMsList.shift(); + } + sess.prevAccountId = accountId; + sess.prevTurnAtMs = attemptNowMs; + sess.prevCacheMode = cacheMode; + sess.turnsSoFar += 1; + + totalCostUsd += billing.billedUsd; + totalPrefixTokens += turn.prefixTokens; + totalCachedReadTokens += billing.cachedReadTokens; + totalHandoffTokens += handoffTokens; + cacheModeCounts[cacheMode] += 1; + + acc.stats.turns += 1; + acc.stats.billedUsd += billing.billedUsd; + acc.stats.quotaUnits += billing.quotaUnitsCharged; + acc.stats.cachedReadTokens += billing.cachedReadTokens; + acc.stats.uncachedInputTokens += billing.uncachedInputTokens; + acc.stats.handoffTokens += handoffTokens; + acc.stats.outputTokens += turn.actualOutputTokens; + acc.stats.cacheModes[cacheMode] += 1; + + const tierBucket = byTier[turn.minTier]; + if (tierBucket) { + tierBucket.turns += 1; + tierBucket.billedUsd += billing.billedUsd; + tierBucket.byAccount[accountId] = (tierBucket.byAccount[accountId] ?? 0) + 1; + } + + const okOutcome = { + nowMs: attemptNowMs, + sessionId: turn.sessionId, + accountId, + cacheMode, + ok: true, + errorCode: null, + billedUsd: billing.billedUsd, + quotaUnitsCharged: billing.quotaUnitsCharged, + cachedReadTokens: billing.cachedReadTokens, + actualOutputTokens: turn.actualOutputTokens, + latencyMs: stallDelayMs + turn.serviceDurationMs, + }; + if (freezeCtx) deepFreeze(okOutcome); + router.onTurnResult(okOutcome); + break; + } + + if (!served) { + droppedTurns += 1; + } + stallDelays.push(stallDelayMs); + } + + // Final sync at end of simulation horizon to count any final-window reset + if (workload.endMs) { + syncAccounts(workload.endMs); + } + + stallDelays.sort((a, b) => a - b); + const runtimeMs = performance.now() - tStart; + + const byAccount = {}; + for (const acc of accounts) { + byAccount[acc.id] = { + ...acc.stats, + billedUsd: Number(acc.stats.billedUsd.toFixed(4)), + quotaUnits: Math.round(acc.stats.quotaUnits), + cacheModes: { ...acc.stats.cacheModes }, + }; + } + for (const t of [1, 2, 3]) { + byTier[t].billedUsd = Number(byTier[t].billedUsd.toFixed(4)); + } + + return { + totalCostUsd: Number(totalCostUsd.toFixed(4)), + totalTurns: turns.length, + servedTurns, + droppedTurns, + tierViolations, + invalidDecisions, + totalAttempts, + failedAttempts, + failedAttemptRate: totalAttempts > 0 ? failedAttempts / totalAttempts : 0, + p50StallMs: percentile(stallDelays, 0.50), + p95StallMs: percentile(stallDelays, 0.95), + p99StallMs: percentile(stallDelays, 0.99), + maxStallMs: stallDelays.length > 0 ? stallDelays[stallDelays.length - 1] : 0, + runtimeMs: Number(runtimeMs.toFixed(2)), + byAccount, + byTier, + expiredQuotaUnits: Object.fromEntries( + Object.entries(expiredQuotaUnits).map(([k, v]) => [k, Math.round(v)]), + ), + cacheStats: { + totalPrefixTokens, + totalCachedReadTokens, + cacheHitRate: totalPrefixTokens > 0 ? totalCachedReadTokens / totalPrefixTokens : 0, + handoffTokens: totalHandoffTokens, + byMode: { ...cacheModeCounts }, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/reference/sim/workload-generator.mjs b/questions/opt-routing-cost-sim/v1/reference/sim/workload-generator.mjs new file mode 100644 index 0000000..6050bcf --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/sim/workload-generator.mjs @@ -0,0 +1,370 @@ +/** + * Deterministic 14-day multi-turn session & traffic workload generator. + * Parameterized by seed and scenario profile; produces causal turn traces with zero hidden archetype hints. + */ + +import { FIVE_HOURS_MS, SEVEN_DAYS_MS, createDefaultPoolConfig } from './billing-sim.mjs'; + +const MINUTE_MS = 60_000; +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; +export const HORIZON_DAYS = 14; +export const HORIZON_MS = HORIZON_DAYS * DAY_MS; + +// Default Monday 2026-01-05 00:00:00 UTC +export const DEFAULT_START_MS = Date.UTC(2026, 0, 5, 0, 0, 0); + +function mulberry32(seed) { + let a = seed >>> 0; + return function rng() { + a = (a + 0x6d2b79f5) >>> 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function randRange(rng, lo, hi) { + return lo + (hi - lo) * rng(); +} + +function randInt(rng, lo, hi) { + return Math.floor(randRange(rng, lo, hi + 1)); +} + +function pickWeighted(rng, entries) { + let total = 0; + for (const [, w] of entries) total += w; + let r = rng() * total; + for (const [val, w] of entries) { + r -= w; + if (r <= 0) return val; + } + return entries[entries.length - 1][0]; +} + +// Realistic weekday hourly demand weights (0..23h local work clock), peaks at 10-12h & 14-18h. +const DEFAULT_WEEKDAY_HOURLY = [ + 0.14, 0.10, 0.08, 0.07, 0.08, 0.12, + 0.24, 0.45, 0.85, 1.35, 1.75, 1.85, + 1.30, 1.55, 1.95, 2.05, 1.90, 1.60, + 1.10, 0.78, 0.62, 0.48, 0.34, 0.22, +]; + +const DEFAULT_WEEKEND_HOURLY = [ + 0.10, 0.08, 0.06, 0.06, 0.06, 0.08, + 0.12, 0.18, 0.30, 0.48, 0.62, 0.68, + 0.65, 0.70, 0.72, 0.68, 0.60, 0.52, + 0.46, 0.42, 0.38, 0.30, 0.22, 0.14, +]; + +export const PUBLIC_SCENARIOS = [ + { + name: 'public-standard-mon', + seed: 20260401, + startDayOfWeek: 0, // Monday + subAResetOffsetHours: 2 * 24 + 8, // Day 2 08:00 & Day 9 08:00 + subBResetOffsetHours: 5 * 24 + 18, // Day 5 18:00 & Day 12 18:00 + subAInitialUsedFrac: 0.56, + subBInitialUsedFrac: 0.18, + demandMultiplier: 1.04, + weekendDipFactor: 0.42, + burstIntensity: 1.0, + archetypeWeights: { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ], + }, + { + name: 'public-shifted-thu', + seed: 20260402, + startDayOfWeek: 3, // Thursday + subAResetOffsetHours: 1 * 24 + 16, // Day 1 16:00 & Day 8 16:00 + subBResetOffsetHours: 4 * 24 + 10, // Day 4 10:00 & Day 11 10:00 + subAInitialUsedFrac: 0.68, + subBInitialUsedFrac: 0.34, + demandMultiplier: 1.08, + weekendDipFactor: 0.36, + burstIntensity: 1.12, + archetypeWeights: { + rapidCoding: 0.35, + reviewThinking: 0.11, + mixedCadence: 0.08, + oneShotSparse: 0.20, + largeOneShot: 0.26, + }, + outages: [ + { accountId: 'sub-b', startHour: 5 * 24 + 14.5, durationMin: 70 }, + { accountId: 'sub-b', startHour: 11 * 24 + 16.0, durationMin: 60 }, + ], + }, +]; + +/** + * Generates a deterministic 14-day multi-turn workload trace. + * Turn objects carry ZERO archetype hints — routers must infer patterns online. + */ +export function generateWorkload(options = {}) { + const seed = options.seed ?? 20260401; + const rng = mulberry32(seed); + const poolConfig = options.poolConfig ?? createDefaultPoolConfig(); + const startDayOfWeek = ((options.startDayOfWeek ?? 0) % 7 + 7) % 7; // 0=Mon..6=Sun + const startMs = options.startMs ?? (DEFAULT_START_MS + startDayOfWeek * DAY_MS); + const endMs = startMs + HORIZON_MS; + + const demandMultiplier = options.demandMultiplier ?? 1.0; + const weekendDipFactor = options.weekendDipFactor ?? 0.42; + const burstIntensity = options.burstIntensity ?? 1.0; + const weights = options.archetypeWeights ?? { + rapidCoding: 0.36, + reviewThinking: 0.10, + mixedCadence: 0.07, + oneShotSparse: 0.21, + largeOneShot: 0.26, + }; + const archetypeEntries = [ + ['rapidCoding', weights.rapidCoding], + ['reviewThinking', weights.reviewThinking], + ['mixedCadence', weights.mixedCadence], + ['oneShotSparse', weights.oneShotSparse], + ['largeOneShot', weights.largeOneShot], + ]; + + // Generate 3-4 realistic weekday burst episodes (e.g., release crunch / incident response) + const burstWindows = []; + for (let day = 0; day < HORIZON_DAYS; day += 1) { + const dow = (startDayOfWeek + day) % 7; + if (dow >= 5) continue; // bursts happen on weekdays + if (rng() < 0.38 * burstIntensity) { + const startHour = day * 24 + randRange(rng, 9.5, 15.5); + const durationHours = randRange(rng, 2.2, 4.0); + burstWindows.push({ + startHour, + endHour: startHour + durationHours, + mult: randRange(rng, 1.55, 2.15) * burstIntensity, + }); + } + } + + // Compute hourly session arrival rates targeting ~740 sessions -> ~11,500-12,500 turns over 14 days + const hourRates = new Array(HORIZON_DAYS * 24); + let rateSum = 0; + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const day = Math.floor(h / 24); + const hourOfDay = h % 24; + const dow = (startDayOfWeek + day) % 7; + const isWeekend = dow >= 5; + let rate = isWeekend + ? DEFAULT_WEEKEND_HOURLY[hourOfDay] * (weekendDipFactor / 0.42) + : DEFAULT_WEEKDAY_HOURLY[hourOfDay]; + for (const bw of burstWindows) { + if (h + 0.5 >= bw.startHour && h + 0.5 <= bw.endHour) { + rate *= bw.mult; + } + } + hourRates[h] = rate; + rateSum += rate; + } + + const targetSessions = Math.round(700 * demandMultiplier); + const turns = []; + let sessionSeq = 0; + let turnSeq = 0; + + // Also keep ground-truth session summaries for offline oracle / diagnostics (never passed to router!) + const sessionMeta = []; + + for (let h = 0; h < HORIZON_DAYS * 24; h += 1) { + const expected = (hourRates[h] / rateSum) * targetSessions; + // Poisson draw using Knuth algorithm + const L = Math.exp(-expected); + let k = 0; + let p = 1.0; + do { + k += 1; + p *= rng(); + } while (p > L); + const count = Math.max(0, k - 1); + + for (let s = 0; s < count; s += 1) { + sessionSeq += 1; + const sessionId = `s-${String(sessionSeq).padStart(4, '0')}`; + const archetype = pickWeighted(rng, archetypeEntries); + const sessionStartMs = startMs + h * HOUR_MS + Math.floor(rng() * HOUR_MS); + + let minTier; + let numTurns; + let initPrefix; + + if (archetype === 'rapidCoding') { + minTier = pickWeighted(rng, [[3, 0.37], [2, 0.25], [1, 0.38]]); + numTurns = randInt(rng, 28, 48); + initPrefix = randInt(rng, 5500, 12500); + } else if (archetype === 'reviewThinking') { + minTier = pickWeighted(rng, [[3, 0.56], [2, 0.34], [1, 0.10]]); + numTurns = randInt(rng, 9, 15); + initPrefix = randInt(rng, 11000, 21000); + } else if (archetype === 'mixedCadence') { + minTier = pickWeighted(rng, [[3, 0.50], [2, 0.32], [1, 0.18]]); + numTurns = randInt(rng, 14, 23); + initPrefix = randInt(rng, 8000, 15000); + } else if (archetype === 'oneShotSparse') { + minTier = pickWeighted(rng, [[1, 0.64], [2, 0.22], [3, 0.14]]); + numTurns = pickWeighted(rng, [[1, 0.66], [2, 0.24], [3, 0.10]]); + initPrefix = randInt(rng, 900, 3600); + } else { + // largeOneShot: single-turn batch summarization, PR diff digest, cron synthesis + minTier = pickWeighted(rng, [[1, 0.66], [2, 0.20], [3, 0.14]]); + numTurns = 1; + initPrefix = randInt(rng, 1000, 3500); + } + + const splitPoint = archetype === 'mixedCadence' ? randInt(rng, 5, Math.max(6, Math.floor(numTurns * 0.45))) : 0; + + let curMs = sessionStartMs; + let curPrefix = initPrefix; + let sessionTurnsAdded = 0; + + for (let ti = 0; ti < numTurns; ti += 1) { + if (curMs >= endMs - 60_000) break; + + let newInputTokens; + let actualOutputTokens; + if (archetype === 'rapidCoding') { + newInputTokens = randInt(rng, 850, 2400); + actualOutputTokens = randInt(rng, 450, 1600); + } else if (archetype === 'reviewThinking') { + newInputTokens = randInt(rng, 1300, 3600); + actualOutputTokens = randInt(rng, 900, 2600); + } else if (archetype === 'mixedCadence') { + newInputTokens = randInt(rng, 1000, 2800); + actualOutputTokens = randInt(rng, 650, 1950); + } else if (archetype === 'oneShotSparse') { + newInputTokens = randInt(rng, 600, 2200); + actualOutputTokens = randInt(rng, 300, 1100); + } else { + // largeOneShot + newInputTokens = randInt(rng, 14000, 36000); + actualOutputTokens = randInt(rng, 800, 2600); + } + + const estOutputTokens = Math.max(100, Math.round(actualOutputTokens * randRange(rng, 0.88, 1.12))); + // Realistic LLM streaming turn latency (~8-32s -> natural concurrency overlap during weekday bursts) + const serviceDurationMs = Math.min(34_000, Math.round(4500 + actualOutputTokens * 12.5)); + + turnSeq += 1; + turns.push({ + turnId: `t-${String(turnSeq).padStart(6, '0')}`, + sessionId, + turnIndex: ti, + arrivalMs: curMs, + minTier, + prefixTokens: curPrefix, + newInputTokens, + estOutputTokens, + actualOutputTokens, + serviceDurationMs, + }); + sessionTurnsAdded += 1; + + // Grow prefix deterministically for the next turn (cap growth smoothly at 115k for realism) + curPrefix = Math.min(115_000, curPrefix + newInputTokens + actualOutputTokens); + + // Compute causal gap to next turn + let gapMs; + if (archetype === 'rapidCoding') { + // 98.5% within 22s..3.5m (5m cache strictly optimal!), 1.5% long break > 75m + gapMs = rng() < 0.985 + ? Math.round(randRange(rng, 22_000, 210_000)) + : Math.round(randRange(rng, 75 * MINUTE_MS, 130 * MINUTE_MS)); + } else if (archetype === 'reviewThinking') { + // 92% in 8m..44m (1h cache strictly optimal vs 5m always expiring!), 4% fast follow-up, 4% long >70m + const u = rng(); + if (u < 0.92) gapMs = Math.round(randRange(rng, 8 * MINUTE_MS, 44 * MINUTE_MS)); + else if (u < 0.96) gapMs = Math.round(randRange(rng, 90_000, 240_000)); + else gapMs = Math.round(randRange(rng, 70 * MINUTE_MS, 135 * MINUTE_MS)); + } else if (archetype === 'mixedCadence') { + if (ti < splitPoint) { + gapMs = Math.round(randRange(rng, 25_000, 185_000)); + } else { + gapMs = Math.round(randRange(rng, 9 * MINUTE_MS, 42 * MINUTE_MS)); + } + } else { + // oneShotSparse: 80m..240m (exceeds 1h TTL) + gapMs = Math.round(randRange(rng, 80 * MINUTE_MS, 240 * MINUTE_MS)); + } + + curMs += Math.max(serviceDurationMs + 5000, gapMs); + } + + if (sessionTurnsAdded > 0) { + sessionMeta.push({ sessionId, archetype, minTier, turns: sessionTurnsAdded }); + } + } + } + + // Sort chronologically by arrivalMs, deterministic tie-break on turnId + turns.sort((a, b) => a.arrivalMs - b.arrivalMs || (a.turnId < b.turnId ? -1 : a.turnId > b.turnId ? 1 : 0)); + + const subA = poolConfig.accounts.find((a) => a.id === 'sub-a'); + const subB = poolConfig.accounts.find((a) => a.id === 'sub-b'); + + const subAResetOffsetHours = options.subAResetOffsetHours ?? (2 * 24 + 8); + const subBResetOffsetHours = options.subBResetOffsetHours ?? (5 * 24 + 18); + const subAInitialUsedFrac = options.subAInitialUsedFrac ?? 0.56; + const subBInitialUsedFrac = options.subBInitialUsedFrac ?? 0.18; + + const initialAccountState = { + 'sub-a': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subA?.sevenDayLimit ?? 15_500_000) * subAInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subAResetOffsetHours * HOUR_MS), + }, + 'sub-b': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: Math.round((subB?.sevenDayLimit ?? 12_500_000) * subBInitialUsedFrac), + sevenDayResetAtMs: startMs + Math.round(subBResetOffsetHours * HOUR_MS), + }, + 'secondary-org': { + fiveHourUsed: 0, + fiveHourResetAtMs: null, + sevenDayUsed: 0, + sevenDayResetAtMs: null, + }, + }; + + const outages = (options.outages ?? [ + { accountId: 'sub-b', startHour: 3 * 24 + 15.0, durationMin: 65 }, + { accountId: 'sub-b', startHour: 10 * 24 + 11.0, durationMin: 75 }, + ]).map((o) => ({ + accountId: o.accountId, + startMs: startMs + Math.round(o.startHour * HOUR_MS), + endMs: startMs + Math.round(o.startHour * HOUR_MS) + Math.round(o.durationMin * MINUTE_MS), + })); + + return { + name: options.name ?? `seed-${seed}`, + seed, + startMs, + endMs, + startDayOfWeek, + initialAccountState, + outages, + turns, + summary: { + sessions: sessionMeta.length, + turns: turns.length, + fiveHoursMs: FIVE_HOURS_MS, + sevenDaysMs: SEVEN_DAYS_MS, + }, + }; +} diff --git a/questions/opt-routing-cost-sim/v1/reference/src/router.mjs b/questions/opt-routing-cost-sim/v1/reference/src/router.mjs new file mode 100644 index 0000000..f8302af --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/src/router.mjs @@ -0,0 +1,161 @@ +/** + * Reference Cost Router (solid human optimization): + * - Tier-value quota reservation: reserves subscriptions for tier-3 turns (admitting tier-2 only + * on clear 7d surplus, and tier-1 only on strong expiring surplus near reset). + * - Warm-cache session stickiness: keeps warm sessions on their current account when affordable. + * - Basic `none` / `5m` / `1h` cache mode heuristic from `recentGapMsList` and turn-0 size. + * - Leaves room for SOTA online primal-dual shadow pricing, weekday/weekend demand forecasting, + * exact marginal cache-break vs quota arbitrage, and Bayesian survival-time cache modeling. + */ + +const MINUTE_MS = 60_000; +const HOUR_MS = 3_600_000; +const SEVEN_DAYS_MS = 7 * 24 * HOUR_MS; + +function estimateTurnCost(acc, turn, cacheMode, poolConfig) { + const isWarm = turn.prevAccountId === acc.id + && acc.warmPrefixTokens > 0 + && acc.warmExpiresAtMs !== null; + const cachedRead = isWarm ? Math.min(turn.prefixTokens, acc.warmPrefixTokens) : 0; + const handoff = turn.prevAccountId && turn.prevAccountId !== acc.id + ? Math.min(poolConfig.handoffCapTokens, Math.round(turn.prefixTokens * poolConfig.handoffRate)) + : 0; + const uncached = (turn.prefixTokens - cachedRead) + turn.newInputTokens + handoff; + const writeMult = cacheMode === '5m' + ? acc.pricing.cacheWrite5mMult + : cacheMode === '1h' + ? acc.pricing.cacheWrite1hMult + : 1.0; + const effInput = cachedRead * acc.pricing.cacheReadMult + uncached * writeMult; + const quotaUnits = effInput + 3.0 * turn.estOutputTokens; + const usd = (effInput * acc.pricing.inputPerMTok + turn.estOutputTokens * acc.pricing.outputPerMTok) / 1_000_000; + return { cachedRead, uncached, effInput, quotaUnits, usd, isWarm }; +} + +function sevenDayUrgency(acc, nowMs) { + if (acc.sevenDayLimit === null || acc.sevenDayLimit <= 0 || acc.sevenDayResetAtMs === null) return 0; + const leftMs = acc.sevenDayResetAtMs - nowMs; + if (leftMs <= 0) return 0; + const timeLeftFrac = Math.min(1, leftMs / SEVEN_DAYS_MS); + const remFrac = Math.max(0, 1 - acc.sevenDayUsed / acc.sevenDayLimit); + return remFrac / Math.max(1e-4, timeLeftFrac); +} + +function chooseCacheModeHeuristic(turn) { + const gaps = turn.recentGapMsList; + const n = gaps.length; + + // Basic turn-0 heuristic: avoid cache write surcharge on tiny prompts + if (turn.turnIndex === 0) { + if (turn.prefixTokens < 3000 && turn.newInputTokens < 1800) return 'none'; + return '5m'; + } + + if (n > 0) { + const lastGap = gaps[n - 1]; + if (lastGap > 65 * MINUTE_MS) return 'none'; + // Basic heuristic from recentGapMsList: switch to 1h once 2 slow (5m..58m) gaps are observed + const slowGaps = gaps.filter((g) => g > 5 * MINUTE_MS && g <= 58 * MINUTE_MS).length; + if (slowGaps >= 2) return '1h'; + } + + return '5m'; +} + +export function createCostRouter(poolConfig) { + function canFit(acc, nowMs, turn, cacheMode, excluded) { + if (excluded.has(acc.id)) return false; + if (acc.capabilityTier < turn.minTier) return false; + if (acc.cooldownUntilMs !== null && nowMs < acc.cooldownUntilMs) return false; + if (acc.inFlight >= acc.maxInFlight) return false; + const est = estimateTurnCost(acc, turn, cacheMode, poolConfig); + const needed = est.quotaUnits * 1.09; + if (acc.fiveHourLimit !== null && acc.fiveHourUsed + needed > acc.fiveHourLimit) return false; + if (acc.sevenDayLimit !== null && acc.sevenDayUsed + needed > acc.sevenDayLimit) return false; + return true; + } + + function selectRoute(ctx) { + const { nowMs, excludedAccountIds, turn, accounts } = ctx; + const excluded = new Set(excludedAccountIds); + const cacheMode = chooseCacheModeHeuristic(turn); + + const eligible = accounts.filter((a) => canFit(a, nowMs, turn, cacheMode, excluded)); + if (eligible.length === 0) { + const emergency = accounts + .filter((a) => !excluded.has(a.id) && a.capabilityTier >= turn.minTier) + .sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok); + return { accountId: emergency[0].id, cacheMode }; + } + + const subs = eligible + .filter((a) => a.kind === 'subscription') + .map((acc) => ({ + acc, + urgency: sevenDayUrgency(acc, nowMs), + left7dHours: acc.sevenDayResetAtMs !== null ? (acc.sevenDayResetAtMs - nowMs) / HOUR_MS : 999, + fiveHourFrac: acc.fiveHourLimit ? acc.fiveHourUsed / acc.fiveHourLimit : 0, + })) + .sort((a, b) => b.urgency - a.urgency); + + const secondary = eligible.find((a) => a.kind === 'secondary') ?? null; + const cheapestPayg = eligible + .filter((a) => a.kind === 'payg') + .sort((a, b) => a.pricing.inputPerMTok - b.pricing.inputPerMTok)[0] ?? null; + + // 1. Keep warm cache on prevAccountId when it is still a sensible account for this tier + if (turn.prevAccountId) { + const prev = eligible.find((a) => a.id === turn.prevAccountId); + if (prev && prev.warmPrefixTokens > 0 && prev.warmExpiresAtMs !== null && nowMs <= prev.warmExpiresAtMs) { + // Don't keep tier-1 stuck on expensive secondary-org or scarce subscriptions if prefix is small + const keepPrev = + turn.minTier === 3 + || (turn.minTier === 2 && (prev.kind === 'subscription' || prev.kind === 'secondary' || prev.id === 'payg-t2')) + || (turn.minTier === 1 && prev.id === 'payg-t1') + || (prev.kind === 'subscription' && prev.warmPrefixTokens >= 10_000); + if (keepPrev) { + // Avoid triggering secondary-org overload 429s when another safe option exists + if (prev.kind !== 'secondary' || prev.inFlight < 3) { + return { accountId: prev.id, cacheMode }; + } + } + } + } + + // 2. Tier-1 routing: default to payg-t1 ($0.50/$2.50), only absorb expiring sub surplus near reset + if (turn.minTier === 1) { + const expiringSub = subs.find((s) => s.left7dHours <= 18 && s.urgency >= 1.9 && s.fiveHourFrac < 0.72); + if (expiringSub) return { accountId: expiringSub.acc.id, cacheMode }; + if (cheapestPayg) return { accountId: cheapestPayg.id, cacheMode }; + } + + // 3. Tier-2 routing: prefer subscriptions only on clear surplus; otherwise secondary-org (when healthy) or payg-t2 + if (turn.minTier === 2) { + const surplusSub = subs.find((s) => s.urgency >= 1.45 && s.fiveHourFrac < 0.78); + if (surplusSub) return { accountId: surplusSub.acc.id, cacheMode }; + if (secondary && secondary.inFlight < 3 && (secondary.fiveHourUsed / secondary.fiveHourLimit) < 0.75) { + return { accountId: secondary.id, cacheMode }; + } + if (cheapestPayg) return { accountId: cheapestPayg.id, cacheMode }; + } + + // 4. Tier-3 routing: highest value ($10/$30 outside option) -> subscriptions first -> secondary-org -> payg-t3 + if (subs.length > 0) { + // Pick highest urgency subscription with 5h room (prefer not near 5h cap) + const roomy = subs.filter((s) => s.fiveHourFrac < 0.90); + const chosen = roomy.length > 0 ? roomy[0] : subs[0]; + return { accountId: chosen.acc.id, cacheMode }; + } + + if (secondary && secondary.inFlight < 4) { + return { accountId: secondary.id, cacheMode }; + } + + if (secondary) return { accountId: secondary.id, cacheMode }; + return { accountId: (cheapestPayg ?? eligible[0]).id, cacheMode }; + } + + function onTurnResult(_outcome) {} + + return { selectRoute, onTurnResult }; +} diff --git a/questions/opt-routing-cost-sim/v1/reference/tests/smoke.test.mjs b/questions/opt-routing-cost-sim/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..8606d33 --- /dev/null +++ b/questions/opt-routing-cost-sim/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,144 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + CACHE_1H_TTL_MS, + CACHE_5M_TTL_MS, + SEVEN_DAYS_MS, + computeTurnBilling, + createDefaultPoolConfig, + runSimulation, +} from '../sim/billing-sim.mjs'; +import { + DEFAULT_START_MS, + PUBLIC_SCENARIOS, + generateWorkload, +} from '../sim/workload-generator.mjs'; +import { createCostRouter } from '../src/router.mjs'; + +test('prompt cache billing arithmetic and exact TTL boundaries', () => { + const pool = createDefaultPoolConfig(); + const payg3 = pool.accounts.find((a) => a.id === 'payg-t3'); + + // Cold 5m write: 10,000 uncached * 1.25 = 12,500 effective input -> $0.125 + 1,000 * $30/M = $0.155 + const cold5m = computeTurnBilling({ + prefixTokens: 8000, + newInputTokens: 2000, + outputTokens: 1000, + cachedReadTokens: 0, + handoffTokens: 0, + cacheMode: '5m', + pricing: payg3.pricing, + }); + assert.equal(cold5m.effectiveInputTokens, 12_500); + assert.ok(Math.abs(cold5m.billedUsd - 0.155) < 1e-9); + + // Warm 1h read: 11,000 * 0.10 + 2,000 * 2.00 = 5,100 effective input + const warm1h = computeTurnBilling({ + prefixTokens: 11_000, + newInputTokens: 2000, + outputTokens: 500, + cachedReadTokens: 11_000, + handoffTokens: 0, + cacheMode: '1h', + pricing: payg3.pricing, + }); + assert.equal(warm1h.effectiveInputTokens, 5100); + + // Verify exact 5m boundary (300_000ms HIT vs 300_001ms MISS) in simulator + const T0 = DEFAULT_START_MS; + const cachedReads = []; + const wl = { + name: 'cache-boundary-sim', + seed: 1, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: {}, + outages: [], + turns: [ + { turnId: 't1', sessionId: 's1', turnIndex: 0, arrivalMs: T0, minTier: 3, prefixTokens: 10_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't2', sessionId: 's1', turnIndex: 1, arrivalMs: T0 + CACHE_5M_TTL_MS, minTier: 3, prefixTokens: 11_500, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + { turnId: 't3', sessionId: 's1', turnIndex: 2, arrivalMs: T0 + 2 * CACHE_5M_TTL_MS + 1, minTier: 3, prefixTokens: 13_000, newInputTokens: 1000, estOutputTokens: 500, actualOutputTokens: 500, serviceDurationMs: 1000 }, + ], + }; + runSimulation({ + workload: wl, + poolConfig: pool, + createRouter: () => ({ + selectRoute: () => ({ accountId: 'payg-t3', cacheMode: '5m' }), + onTurnResult: (o) => { cachedReads.push(o.cachedReadTokens); }, + }), + freezeCtx: true, + }); + assert.deepEqual(cachedReads, [0, 11_500, 0]); +}); + +test('router handles exhausted subscriptions and secondary-org with tier-compliant PAYG fallback', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'exhausted-subscriptions', + seed: 2, + startMs: T0, + endMs: T0 + 3_600_000, + initialAccountState: { + 'sub-a': { fiveHourUsed: 1_900_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'sub-b': { fiveHourUsed: 1_650_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 12_500_000, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 1_550_000, fiveHourResetAtMs: T0 + 18_000_000, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [], + turns: [ + { turnId: 'x1', sessionId: 'sx1', turnIndex: 0, arrivalMs: T0 + 1000, minTier: 1, prefixTokens: 2000, newInputTokens: 1000, estOutputTokens: 400, actualOutputTokens: 400, serviceDurationMs: 2000 }, + { turnId: 'x2', sessionId: 'sx2', turnIndex: 0, arrivalMs: T0 + 5000, minTier: 2, prefixTokens: 4000, newInputTokens: 1000, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'x3', sessionId: 'sx3', turnIndex: 0, arrivalMs: T0 + 9000, minTier: 3, prefixTokens: 8000, newInputTokens: 1000, estOutputTokens: 800, actualOutputTokens: 800, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); + assert.equal(res.failedAttempts, 0); +}); + +test('router handles mid-session outage failover, 7d wraparound, and frozen ctx immutability', () => { + const pool = createDefaultPoolConfig(); + const T0 = DEFAULT_START_MS; + const wl = { + name: 'outage-and-wraparound', + seed: 3, + startMs: T0, + endMs: T0 + 2 * SEVEN_DAYS_MS, + initialAccountState: { + 'sub-a': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 15_500_000, sevenDayResetAtMs: T0 + 3_600_000 }, + 'sub-b': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: T0 + SEVEN_DAYS_MS }, + 'secondary-org': { fiveHourUsed: 0, fiveHourResetAtMs: null, sevenDayUsed: 0, sevenDayResetAtMs: null }, + }, + outages: [ + { accountId: 'sub-b', startMs: T0 + 60_000, endMs: T0 + 1_800_000 }, + ], + turns: [ + { turnId: 'm1', sessionId: 'sm1', turnIndex: 0, arrivalMs: T0 + 10_000, minTier: 3, prefixTokens: 10_000, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm2', sessionId: 'sm1', turnIndex: 1, arrivalMs: T0 + 120_000, minTier: 3, prefixTokens: 12_100, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + { turnId: 'm3', sessionId: 'sm1', turnIndex: 2, arrivalMs: T0 + 3_600_000 + CACHE_1H_TTL_MS, minTier: 3, prefixTokens: 14_200, newInputTokens: 1500, estOutputTokens: 600, actualOutputTokens: 600, serviceDurationMs: 2000 }, + ], + }; + + const res = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + assert.equal(res.droppedTurns, 0); + assert.equal(res.tierViolations, 0); + assert.equal(res.invalidDecisions, 0); +}); + +test('router is deterministic across repeated runs on a public slice', () => { + const pool = createDefaultPoolConfig(); + const wl = generateWorkload({ ...PUBLIC_SCENARIOS[0], demandMultiplier: 0.12, poolConfig: pool }); + const r1 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + const r2 = runSimulation({ workload: wl, poolConfig: pool, createRouter: createCostRouter, freezeCtx: true }); + + assert.equal(r1.droppedTurns, 0); + assert.equal(r1.tierViolations, 0); + assert.equal(r1.invalidDecisions, 0); + assert.equal(r1.totalCostUsd, r2.totalCostUsd); + assert.equal(r1.failedAttempts, r2.failedAttempts); + assert.deepEqual(r1.cacheStats, r2.cacheStats); +}); diff --git a/questions/opt-routing-cost-sim/v2/README.md b/questions/opt-routing-cost-sim/v2/README.md new file mode 100644 index 0000000..ed45caa --- /dev/null +++ b/questions/opt-routing-cost-sim/v2/README.md @@ -0,0 +1,22 @@ +# opt-routing-cost-sim v2 — 暂缓(未校准草稿) + +v2 原计划把 v1 的合成负载换成本机真实用量:`scripts/extract-real-routing-trace.py` 只读 Cindy 数据库里每轮的用量字段(不读消息内容),按 14 天窗口导出到时间、时长、会话序号、模型、来源和四类 token 数。这里的 `candidate/sim`(回放计费器、账号池与价目表)和 `candidate/src/router.mjs`(今天 Smart Routing 的策略:粘住缓存仍热的账号、否则选剩余额度最多的订阅、一律 5 分钟缓存)是当时的草稿。真实用量没有入库。 + +## 为什么暂缓 + +用三个真实 14 天窗口回放(4,673 / 12,911 / 21,042 轮,折合官方价分别约 $6.2k / $22.9k / $26.5k,绝大多数由订阅承担): + +| 窗口 | 今天的路由按量计费 | 必须走按量的部分(只有网关能接的模型) | +|---|---:|---:| +| 1 | $0.17 | $0.17 | +| 2 | $204 | $0.15 | +| 3 | $63 | $36 | + +- 第 2、3 窗口高出下限的部分,来自订阅额度的估法:5 小时和 7 天额度取的是记录里实际用到的最高值,只是真实上限的下限。按真实上限这些溢出大概率不存在,所以这部分“可省的钱”是建模假设,不是用户真实会省下的钱。 +- 缓存时长(5 分钟 / 1 小时)选得再好,折合官方价的消耗也只少约 1.4–1.6%(粗略上界:假设所有间隔不超过缓存时长的轮次都命中)。 + +用真实负载评分时,分差主要会反映额度估值,而不是路由本身好坏;为了拉开分差去缩小额度,又等于为了出题刻意加难度。因此 v2 不发布、不进 suite,v1(合成负载)作为历史版本保留。 + +## 什么时候重启 + +当真实日志里出现订阅被限流后溢出到按量、或按量花费变得可观时,用上面的脚本重新导出窗口,重新估额度上限(最好用服务商返回的真实额度信息),再按 `docs/calibration-checklist.md` 校准。 diff --git a/questions/opt-routing-cost-sim/v2/candidate/sim/billing-sim.mjs b/questions/opt-routing-cost-sim/v2/candidate/sim/billing-sim.mjs new file mode 100644 index 0000000..1052426 --- /dev/null +++ b/questions/opt-routing-cost-sim/v2/candidate/sim/billing-sim.mjs @@ -0,0 +1,280 @@ +/** + * Replay simulator for real recorded traffic (protected read-only). + * + * Every turn in a trace is a real turn recorded on a Cindy machine. The router picks which + * account serves it and which prompt-cache TTL to use; the simulator bills the turn with the + * exact rules in CONTRACT.md §2 and keeps per-account quota windows. + */ + +import { CACHE_TTL_MS, FIVE_HOURS_MS, SEVEN_DAYS_MS, modelFamily } from './pool.mjs'; + +export const VALID_CACHE_MODES = Object.freeze(['5m', '1h']); + +function deepFreeze(obj) { + if (obj && typeof obj === 'object' && !Object.isFrozen(obj)) { + Object.freeze(obj); + for (const v of Object.values(obj)) deepFreeze(v); + } + return obj; +} + +function clone(obj) { + return JSON.parse(JSON.stringify(obj)); +} + +function percentile(sorted, p) { + if (!sorted.length) return 0; + return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]; +} + +/** Write price for the chosen TTL, or null when the model has no such tier. */ +export function cacheWritePrice(price, cacheMode) { + if (cacheMode === '1h') return price.cacheWrite1h ?? null; + if (cacheMode === '5m') return price.cacheWrite5m; + return null; +} + +/** + * API-equivalent USD for one turn: the turn-start context is read from cache when warm, + * otherwise written at the chosen TTL's price; in-turn volume bills the same everywhere + * except that in-turn cache writes also follow the chosen TTL. + */ +export function computeTurnCostUsd({ turn, price, cacheMode, warmHit }) { + const write = cacheWritePrice(price, cacheMode); + if (write === null) return null; + const start = turn.contextTokens * (warmHit ? price.cacheRead : write); + const inner = turn.innerCacheReadTokens * price.cacheRead + + turn.innerCacheWriteTokens * write + + turn.innerInputTokens * price.input + + turn.outputTokens * price.output; + return (start + inner) / 1_000_000; +} + +/** Load a recorded trace file (see CONTRACT.md §1) into turn objects ordered by arrival. */ +export function loadTrace(traceJson, poolConfig) { + const turns = []; + const turnIndex = new Map(); + for (const rec of traceJson.turns) { + const [t, d, s, model, P, ri, ci, ii, o] = rec; + const family = modelFamily(model); + if (!family || !poolConfig.prices[model]) continue; + const sessionId = `s${s}`; + const idx = turnIndex.get(sessionId) ?? 0; + turnIndex.set(sessionId, idx + 1); + turns.push({ + turnId: `${traceJson.name}#${turns.length}`, + sessionId, + turnIndex: idx, + arrivalMs: t, + serviceDurationMs: d, + model, + family, + contextTokens: P, + innerCacheReadTokens: ri, + innerCacheWriteTokens: ci, + innerInputTokens: ii, + outputTokens: o, + }); + } + return { name: traceJson.name, turns }; +} + +export function runSimulation({ trace, poolConfig, createRouter, freezeCtx = true }) { + const t0 = performance.now(); + const ttl = poolConfig.cacheTtlMs ?? CACHE_TTL_MS; + const retryDelayMs = poolConfig.retryDelayMs; + const maxAttempts = poolConfig.maxAttempts; + const prices = poolConfig.prices; + + const routerPool = freezeCtx ? deepFreeze(clone(poolConfig)) : clone(poolConfig); + const router = createRouter(routerPool); + + const accounts = new Map(); + for (const cfg of poolConfig.accounts) { + accounts.set(cfg.id, { + cfg, + fiveHourUsedUsd: 0, + fiveHourResetAtMs: null, + sevenDayUsedUsd: 0, + sevenDayResetAtMs: cfg.sevenDayResetOffsetMs, + stats: { turns: 0, billedUsd: 0, apiUsd: 0, failedAttempts: 0, cacheModes: {} }, + expiredSevenDayUsd: 0, + }); + } + + function syncAccount(acc, nowMs) { + if (acc.fiveHourResetAtMs !== null && nowMs >= acc.fiveHourResetAtMs) { + acc.fiveHourUsedUsd = 0; + acc.fiveHourResetAtMs = null; + } + if (acc.sevenDayResetAtMs !== null) { + while (nowMs >= acc.sevenDayResetAtMs) { + if (acc.cfg.sevenDayBudgetUsd !== null) { + acc.expiredSevenDayUsd += Math.max(0, acc.cfg.sevenDayBudgetUsd - acc.sevenDayUsedUsd); + } + acc.sevenDayUsedUsd = 0; + acc.sevenDayResetAtMs += SEVEN_DAYS_MS; + } + } + } + + function exhausted(acc) { + const c = acc.cfg; + return (c.fiveHourBudgetUsd !== null && acc.fiveHourUsedUsd >= c.fiveHourBudgetUsd) + || (c.sevenDayBudgetUsd !== null && acc.sevenDayUsedUsd >= c.sevenDayBudgetUsd); + } + + const sessions = new Map(); + let totalBilledUsd = 0; + let totalApiUsd = 0; + let droppedTurns = 0; + let invalidDecisions = 0; + let familyViolations = 0; + let failedAttempts = 0; + let totalAttempts = 0; + let warmStarts = 0; + let mutationDetected = false; + const stalls = []; + const byMode = { '5m': 0, '1h': 0 }; + + for (const turn of trace.turns) { + let sess = sessions.get(turn.sessionId); + if (!sess) { + sess = { prevAccountId: null, prevCacheMode: null, prevTurnEndMs: null, gaps: [], warm: new Map() }; + sessions.set(turn.sessionId, sess); + } + const eligible = poolConfig.accounts.filter((a) => a.families.includes(turn.family)).map((a) => a.id); + let nowMs = turn.arrivalMs; + const excluded = []; + let served = false; + let stallMs = 0; + + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + for (const acc of accounts.values()) syncAccount(acc, nowMs); + const ctx = { + nowMs, + attempt, + excludedAccountIds: excluded.slice(), + turn: { + sessionId: turn.sessionId, + turnIndex: turn.turnIndex, + model: turn.model, + family: turn.family, + contextTokens: turn.contextTokens, + eligibleAccountIds: eligible.slice(), + prevAccountId: sess.prevAccountId, + prevCacheMode: sess.prevCacheMode, + prevTurnEndMs: sess.prevTurnEndMs, + recentGapMsList: sess.gaps.slice(-8), + }, + accounts: [...accounts.values()].map((acc) => { + const w = sess.warm.get(acc.cfg.id); + return { + id: acc.cfg.id, + kind: acc.cfg.kind, + families: acc.cfg.families.slice(), + fiveHourUsedUsd: acc.fiveHourUsedUsd, + fiveHourBudgetUsd: acc.cfg.fiveHourBudgetUsd, + fiveHourResetAtMs: acc.fiveHourResetAtMs, + sevenDayUsedUsd: acc.sevenDayUsedUsd, + sevenDayBudgetUsd: acc.cfg.sevenDayBudgetUsd, + sevenDayResetAtMs: acc.sevenDayResetAtMs, + warmExpiresAtMs: w && w >= nowMs ? w : null, + }; + }), + }; + const frozenCtx = freezeCtx ? deepFreeze(ctx) : ctx; + const snapshot = freezeCtx ? null : JSON.stringify(ctx); + const decision = router.selectRoute(frozenCtx) ?? {}; + if (snapshot !== null && JSON.stringify(ctx) !== snapshot) mutationDetected = true; + totalAttempts += 1; + + const accountId = decision.accountId; + const cacheMode = decision.cacheMode; + const acc = accounts.get(accountId); + const price = prices[turn.model]; + let errorCode = null; + if (!acc || excluded.includes(accountId) || !VALID_CACHE_MODES.includes(cacheMode)) { + errorCode = 'INVALID_ROUTE'; + } else if (!acc.cfg.families.includes(turn.family)) { + errorCode = 'FAMILY_MISMATCH'; + } else if (cacheWritePrice(price, cacheMode) === null) { + errorCode = 'UNSUPPORTED_CACHE_MODE'; + } else if (exhausted(acc)) { + errorCode = 'RATE_LIMITED'; + } + + if (errorCode) { + if (errorCode === 'INVALID_ROUTE' || errorCode === 'UNSUPPORTED_CACHE_MODE') invalidDecisions += 1; + if (errorCode === 'FAMILY_MISMATCH') familyViolations += 1; + failedAttempts += 1; + if (acc) acc.stats.failedAttempts += 1; + router.onTurnResult(deepFreeze({ + nowMs, sessionId: turn.sessionId, accountId, cacheMode, ok: false, errorCode, + billedUsd: 0, apiEquivalentUsd: 0, warmHit: false, endMs: nowMs, + })); + if (accountId && !excluded.includes(accountId)) excluded.push(accountId); + nowMs += retryDelayMs; + stallMs += retryDelayMs; + continue; + } + + const warmUntil = sess.warm.get(accountId); + const warmHit = sess.prevAccountId === accountId && warmUntil !== undefined && nowMs <= warmUntil; + const apiUsd = computeTurnCostUsd({ turn, price, cacheMode, warmHit }); + const billedUsd = acc.cfg.kind === 'payg' ? apiUsd : 0; + if (acc.cfg.kind !== 'payg') { + if (acc.fiveHourResetAtMs === null) acc.fiveHourResetAtMs = nowMs + FIVE_HOURS_MS; + acc.fiveHourUsedUsd += apiUsd; + acc.sevenDayUsedUsd += apiUsd; + } + const endMs = nowMs + turn.serviceDurationMs; + if (sess.prevAccountId !== accountId) sess.warm.clear(); + sess.warm.set(accountId, endMs + ttl[cacheMode]); + if (sess.prevTurnEndMs !== null) sess.gaps.push(Math.max(0, turn.arrivalMs - sess.prevTurnEndMs)); + sess.prevAccountId = accountId; + sess.prevCacheMode = cacheMode; + sess.prevTurnEndMs = endMs; + + totalBilledUsd += billedUsd; + totalApiUsd += apiUsd; + if (warmHit) warmStarts += 1; + byMode[cacheMode] += 1; + acc.stats.turns += 1; + acc.stats.billedUsd += billedUsd; + acc.stats.apiUsd += apiUsd; + acc.stats.cacheModes[cacheMode] = (acc.stats.cacheModes[cacheMode] ?? 0) + 1; + router.onTurnResult(deepFreeze({ + nowMs, sessionId: turn.sessionId, accountId, cacheMode, ok: true, errorCode: null, + billedUsd, apiEquivalentUsd: apiUsd, warmHit, endMs, + })); + served = true; + break; + } + if (!served) droppedTurns += 1; + stalls.push(stallMs); + } + + const lastMs = trace.turns.length ? trace.turns[trace.turns.length - 1].arrivalMs : 0; + for (const acc of accounts.values()) syncAccount(acc, lastMs); + stalls.sort((a, b) => a - b); + const byAccount = {}; + for (const acc of accounts.values()) byAccount[acc.cfg.id] = { ...acc.stats, expiredSevenDayUsd: acc.expiredSevenDayUsd }; + return { + traceName: trace.name, + totalTurns: trace.turns.length, + totalCostUsd: totalBilledUsd, + totalApiEquivalentUsd: totalApiUsd, + droppedTurns, + invalidDecisions, + familyViolations, + failedAttempts, + failedAttemptRate: totalAttempts ? failedAttempts / totalAttempts : 0, + p99StallMs: percentile(stalls, 0.99), + warmStartRate: trace.turns.length ? warmStarts / trace.turns.length : 0, + cacheModes: byMode, + byAccount, + mutationDetected, + runtimeMs: performance.now() - t0, + }; +} diff --git a/questions/opt-routing-cost-sim/v2/candidate/sim/pool.mjs b/questions/opt-routing-cost-sim/v2/candidate/sim/pool.mjs new file mode 100644 index 0000000..08dbc04 --- /dev/null +++ b/questions/opt-routing-cost-sim/v2/candidate/sim/pool.mjs @@ -0,0 +1,88 @@ +/** + * Account pool and price table (protected read-only). + * + * The pool mirrors the account structure of the machine the traces were recorded on: + * one Claude subscription, three Codex subscriptions on the same plan, one Gemini + * subscription, and a pay-as-you-go gateway that serves every model at its official price. + * + * Prices are the official USD standard tariffs from Cindy's bundled model catalog + * (`resolveModelReferencePrice`, evaluated at 2026-12-01), per million tokens. + * `cacheWrite1h` is null where the vendor has no 1-hour cache tier. + * + * Subscription budgets are expressed in API-equivalent USD (what the same tokens would + * cost at the official price). They were set from the highest 5-hour and 7-day spend + * each plan actually served in the recorded traffic (see CONTRACT.md §3). + */ + +export const MODEL_PRICES = Object.freeze({ + 'claude-opus-5-5': { input: 4, output: 20, cacheRead: 0.2, cacheWrite5m: 5, cacheWrite1h: 8 }, + 'claude-opus-5': { input: 5, output: 25, cacheRead: 0.5, cacheWrite5m: 6.25, cacheWrite1h: 10 }, + 'claude-fable-5-2': { input: 8, output: 40, cacheRead: 0.2, cacheWrite5m: 10, cacheWrite1h: 16 }, + 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.1, cacheWrite5m: 2.5, cacheWrite1h: 4 }, + 'claude-haiku-5-5': { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite5m: 0.125, cacheWrite1h: 0.2 }, + 'gpt-6.2-sol': { input: 2, output: 10, cacheRead: 0.1, cacheWrite5m: 2.5, cacheWrite1h: null }, + 'gpt-6.2-astra': { input: 8, output: 40, cacheRead: 0.4, cacheWrite5m: 10, cacheWrite1h: null }, + 'gpt-6.1-sol': { input: 2, output: 10, cacheRead: 0.1, cacheWrite5m: 2.5, cacheWrite1h: null }, + 'gpt-6-sol': { input: 2, output: 10, cacheRead: 0.2, cacheWrite5m: 2.5, cacheWrite1h: null }, + 'gpt-6-astra': { input: 10, output: 50, cacheRead: 1, cacheWrite5m: 12.5, cacheWrite1h: null }, + 'gpt-5.6-luna': { input: 0.2, output: 1.2, cacheRead: 0.02, cacheWrite5m: 0.25, cacheWrite1h: null }, + 'gpt-6-luna': { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite5m: 0.125, cacheWrite1h: null }, + // Gemini and DeepSeek have no separate cache-write tariff: writes bill as input. + 'gemini-4-neon': { input: 3, output: 15, cacheRead: 0.15, cacheWrite5m: 3, cacheWrite1h: null }, + 'gemini-4-carbon': { input: 4, output: 20, cacheRead: 0.2, cacheWrite5m: 4, cacheWrite1h: null }, + 'deepseek-flash': { input: 0.3, output: 1.2, cacheRead: 0.006, cacheWrite5m: 0.3, cacheWrite1h: null }, + 'deepseek-v4-flash': { input: 0.3, output: 1.2, cacheRead: 0.006, cacheWrite5m: 0.3, cacheWrite1h: null }, +}); + +export function modelFamily(model) { + if (model.startsWith('claude-')) return 'anthropic'; + if (model.startsWith('gpt-')) return 'openai'; + if (model.startsWith('gemini-')) return 'google'; + if (model.startsWith('deepseek')) return 'deepseek'; + return null; +} + +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const SEVEN_DAYS_MS = 7 * 24 * 3_600_000; +export const CACHE_TTL_MS = Object.freeze({ '5m': 5 * 60_000, '1h': 60 * 60_000 }); + +const MIN = 60_000; +const HOUR = 60 * MIN; +const DAY = 24 * HOUR; + +function subscription(id, families, fiveHourBudgetUsd, sevenDayBudgetUsd, sevenDayResetOffsetMs) { + return { + id, + kind: 'subscription', + families, + fiveHourBudgetUsd, + sevenDayBudgetUsd, + // First weekly reset, measured from the trace's Monday 00:00; repeats every 7 days. + sevenDayResetOffsetMs, + }; +} + +export function createPoolConfig() { + return { + accounts: [ + // Weekly reset offsets are conventions (staggered across the week), not account data. + subscription('claude-sub-1', ['anthropic'], 850, 5_600, 4 * DAY + 10 * HOUR), + subscription('codex-sub-1', ['openai'], 570, 4_200, 2 * DAY + 18 * HOUR), + subscription('codex-sub-2', ['openai'], 570, 4_200, 2 * DAY + 20 * HOUR), + subscription('codex-sub-3', ['openai'], 570, 4_200, 1 * DAY + 14 * HOUR), + subscription('google-sub-1', ['google'], 450, 4_300, 5 * DAY + 8 * HOUR), + { + id: 'payg-gateway', + kind: 'payg', + families: ['anthropic', 'openai', 'google', 'deepseek'], + fiveHourBudgetUsd: null, + sevenDayBudgetUsd: null, + sevenDayResetOffsetMs: null, + }, + ], + prices: MODEL_PRICES, + cacheTtlMs: CACHE_TTL_MS, + retryDelayMs: 1200, + maxAttempts: 4, + }; +} diff --git a/questions/opt-routing-cost-sim/v2/candidate/src/router.mjs b/questions/opt-routing-cost-sim/v2/candidate/src/router.mjs new file mode 100644 index 0000000..866ffe0 --- /dev/null +++ b/questions/opt-routing-cost-sim/v2/candidate/src/router.mjs @@ -0,0 +1,51 @@ +/** + * Source router: the policy Cindy's Smart Routing uses today, reduced to this pool. + * + * - Keep the session on its previous account while that account's prompt cache is still warm + * and its 5-hour window is below 85%. + * - Otherwise pick the subscription with the most quota left (the smaller of the 5-hour and + * 7-day remaining fractions); fall back to the pay-as-you-go gateway when none is left. + * - Always request the default 5-minute prompt cache. + */ + +const STICKY_FIVE_HOUR_LIMIT = 0.85; + +function remainingFraction(acc) { + let frac = 1; + if (acc.fiveHourBudgetUsd !== null) frac = Math.min(frac, 1 - acc.fiveHourUsedUsd / acc.fiveHourBudgetUsd); + if (acc.sevenDayBudgetUsd !== null) frac = Math.min(frac, 1 - acc.sevenDayUsedUsd / acc.sevenDayBudgetUsd); + return frac; +} + +export function createCostRouter(poolConfig) { + void poolConfig; + return { + selectRoute(ctx) { + const { turn } = ctx; + const excluded = new Set(ctx.excludedAccountIds); + const eligible = ctx.accounts.filter((a) => turn.eligibleAccountIds.includes(a.id) && !excluded.has(a.id)); + + const prev = eligible.find((a) => a.id === turn.prevAccountId); + if (prev && prev.warmExpiresAtMs !== null && remainingFraction(prev) > 0) { + const fiveHourFrac = prev.fiveHourBudgetUsd === null ? 0 : prev.fiveHourUsedUsd / prev.fiveHourBudgetUsd; + if (fiveHourFrac < STICKY_FIVE_HOUR_LIMIT) return { accountId: prev.id, cacheMode: '5m' }; + } + + let best = null; + let bestFrac = 0; + for (const acc of eligible) { + if (acc.kind !== 'subscription') continue; + const frac = remainingFraction(acc); + if (frac > bestFrac) { + best = acc; + bestFrac = frac; + } + } + if (best) return { accountId: best.id, cacheMode: '5m' }; + + const payg = eligible.find((a) => a.kind === 'payg'); + return { accountId: (payg ?? eligible[0] ?? ctx.accounts[0]).id, cacheMode: '5m' }; + }, + onTurnResult() {}, + }; +} diff --git a/questions/perf-github-api-budget/v1/author/editable.json b/questions/perf-github-api-budget/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/perf-github-api-budget/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/perf-github-api-budget/v1/author/evaluator.mjs b/questions/perf-github-api-budget/v1/author/evaluator.mjs new file mode 100644 index 0000000..d3289ca --- /dev/null +++ b/questions/perf-github-api-budget/v1/author/evaluator.mjs @@ -0,0 +1,1046 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir] = process.argv.slice(2); +const [rateLimitMod, statusMod, watchMod] = await Promise.all([ + import(pathToFileURL(path.join(subDir, 'shared-rate-limit.mjs')).href), + import(pathToFileURL(path.join(subDir, 'pr-status-service.mjs')).href), + import(pathToFileURL(path.join(subDir, 'pr-follow-watch.mjs')).href), +]); + +const { PrStatusService, prStatusKey } = statusMod; +const { PrFollowWatch } = watchMod; +const { + createSharedRateLimitStore, + parseSharedRateLimitPayload, + MAX_SHARED_RATE_LIMIT_MS, +} = rateLimitMod; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const T0 = 1_760_000_000_000; +const SIM_MINUTES = 48 * 60; +const GQL_HOURLY_LIMIT = 500; +const REST_HOURLY_LIMIT = 1000; + +function makeClock(start = T0) { + let t = start; + return { + now: () => t, + set: (v) => { t = v; }, + advance: (ms) => { t += ms; }, + }; +} + +function createDeterministicGateway(clock) { + const prs = new Map(); + let gqlRemaining = GQL_HOURLY_LIMIT; + let restRemaining = REST_HOURLY_LIMIT; + let windowResetAt = clock.now() + HOUR; + + const stats = { + graphqlCalls: 0, + graphqlPoints: 0, + rest200Calls: 0, + rest304Calls: 0, + rateLimitBreaches: 0, + wastedBusyCalls: 0, + wastedMergedCalls: 0, + }; + + function syncWindow() { + const now = clock.now(); + if (now >= windowResetAt) { + const hoursElapsed = Math.floor((now - windowResetAt) / HOUR) + 1; + windowResetAt += hoursElapsed * HOUR; + gqlRemaining = GQL_HOURLY_LIMIT; + restRemaining = REST_HOURLY_LIMIT; + } + } + + function makeHeaders(resource, remaining, limit) { + return { + 'x-ratelimit-resource': resource, + 'x-ratelimit-remaining': String(remaining), + 'x-ratelimit-limit': String(limit), + 'x-ratelimit-reset': String(Math.floor(windowResetAt / 1000)), + }; + } + + function rateLimitError(resource, remaining, limit) { + const err = new Error('GITHUB_RATE_LIMITED'); + err.status = 429; + err.code = 'GITHUB_RATE_LIMITED'; + err.headers = makeHeaders(resource, remaining, limit); + return err; + } + + function setPr(q, remote) { + const key = prStatusKey(q); + const prev = prs.get(key); + const version = (prev?.version ?? 0) + 1; + prs.set(key, { + q, + remote: { ...remote }, + version, + etag: `"v${version}-${remote.state}-${remote.head_sha}"`, + }); + } + + function updatePr(q, patch) { + const key = prStatusKey(q); + const cur = prs.get(key); + if (!cur) throw new Error(`Unknown PR ${key}`); + setPr(q, { ...cur.remote, ...patch }); + } + + function consumeExternalGraphql(targetRemaining) { + syncWindow(); + gqlRemaining = Math.max(0, Math.min(gqlRemaining, targetRemaining)); + return { remaining: gqlRemaining, limit: GQL_HOURLY_LIMIT, resetAt: windowResetAt }; + } + + const gateway = { + async graphqlSingle(q) { + syncWindow(); + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const entry = prs.get(prStatusKey(q)); + return { + remote: entry ? { ...entry.remote } : null, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async graphqlBatch({ owner, repo, prNumbers }) { + syncWindow(); + if (!Array.isArray(prNumbers) || prNumbers.length === 0 || prNumbers.length > 8) { + const err = new Error('Invalid batch size (must be 1..8)'); + err.status = 400; + throw err; + } + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const items = {}; + for (const prNumber of prNumbers) { + const entry = prs.get(prStatusKey({ owner, repo, prNumber })); + if (!entry) items[prNumber] = { ok: false, notFound: true }; + else items[prNumber] = { ok: true, remote: { ...entry.remote } }; + } + return { + items, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async restGetPr(q, opts = {}) { + syncWindow(); + const entry = prs.get(prStatusKey(q)); + if (!entry) { + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + const err = new Error('NOT_FOUND'); + err.status = 404; + err.headers = makeHeaders('core', restRemaining, REST_HOURLY_LIMIT); + throw err; + } + if (opts?.etag && opts.etag === entry.etag) { + stats.rest304Calls += 1; + return { + status: 304, + notModified: true, + etag: entry.etag, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + } + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + return { + status: 200, + notModified: false, + etag: entry.etag, + remote: { ...entry.remote }, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + }, + }; + + return { gateway, stats, setPr, updatePr, consumeExternalGraphql }; +} + +async function checkRefreshPenetrates() { + const clock = makeClock(); + const sim = createDeterministicGateway(clock); + const qMerged = { owner: 'acme', repo: 'core', prNumber: 77 }; + const qClosed = { owner: 'acme', repo: 'core', prNumber: 78 }; + sim.setPr(qMerged, { + state: 'merged', + merged: true, + merged_at: new Date(clock.now() - HOUR).toISOString(), + head_sha: 'sha-m1', + title: 'Before refresh', + checks: 'success', + }); + sim.setPr(qClosed, { + state: 'closed', + merged: false, + head_sha: 'sha-c1', + title: 'Closed title', + checks: 'failure', + }); + const svc = new PrStatusService({ gateway: sim.gateway, now: clock.now }); + const [m1, c1] = await svc.getStatuses([qMerged, qClosed]); + assert.equal(m1.ok, true); + assert.equal(m1.status, 'merged'); + assert.equal(c1.status, 'closed'); + + sim.updatePr(qMerged, { title: 'After refresh' }); + sim.updatePr(qClosed, { state: 'open', title: 'Reopened title' }); + clock.advance(10_000); + + const [m2, c2] = await svc.getStatuses([qMerged, qClosed], { refresh: true }); + assert.equal(m2.ok, true); + assert.equal(m2.title, 'After refresh'); + assert.equal(c2.ok, true); + assert.equal(c2.status, 'open'); + assert.equal(c2.title, 'Reopened title'); +} + +async function checkPartialErrorIsolation() { + const clock = makeClock(); + const restHitNumbers = []; + let batchCalled = false; + const remoteFor = (n, src) => ({ + state: 'open', + merged: false, + head_sha: `sha-${n}-${src}`, + title: `PR #${n} (${src})`, + checks: 'success', + }); + + const gateway = { + async graphqlSingle(q) { + if (q.prNumber === 2) { + const err = new Error('transient 502'); + err.status = 502; + throw err; + } + if (q.prNumber === 3) return { remote: null }; + return { remote: remoteFor(q.prNumber, 'gql') }; + }, + async graphqlBatch({ prNumbers }) { + batchCalled = true; + const items = {}; + for (const n of prNumbers) { + if (n === 2) { + const err = new Error('transient partial error'); + err.status = 502; + items[n] = { ok: false, error: err }; + } else if (n === 3) { + items[n] = { ok: false, notFound: true }; + } else { + items[n] = { ok: true, remote: remoteFor(n, 'gql') }; + } + } + return { items }; + }, + async restGetPr(q) { + restHitNumbers.push(q.prNumber); + if (q.prNumber === 3) { + const err = new Error('NOT_FOUND'); + err.status = 404; + throw err; + } + return { status: 200, notModified: false, etag: `"e-${q.prNumber}"`, remote: remoteFor(q.prNumber, 'rest') }; + }, + }; + + const svc = new PrStatusService({ gateway, now: clock.now }); + const queries = [1, 2, 3, 4].map((prNumber) => ({ owner: 'acme', repo: 'core', prNumber })); + const res = await svc.getStatuses(queries); + assert.equal(res.length, 4); + assert.equal(res[0].ok, true); + assert.equal(res[1].ok, true); + assert.equal(res[1].headSha, 'sha-2-rest'); + assert.equal(res[2].ok, false); + assert.equal(res[2].reason, 'not-found'); + assert.equal(res[3].ok, true); + if (batchCalled) { + assert.equal(res[0].headSha, 'sha-1-gql'); + assert.equal(res[3].headSha, 'sha-4-gql'); + // ONLY PR #2 should have fallen back to REST; #1/#4 stay from GraphQL and #3 (404) skips REST. + assert.deepEqual(restHitNumbers, [2]); + } +} + +async function checkAuth401ShortCircuit() { + const clock = makeClock(); + let gqlCalls = 0; + let restCalls = 0; + const authErr = () => { + const err = new Error('Unauthorized'); + err.status = 401; + return err; + }; + const gateway = { + async graphqlSingle() { + gqlCalls += 1; + throw authErr(); + }, + async graphqlBatch() { + gqlCalls += 1; + throw authErr(); + }, + async restGetPr() { + restCalls += 1; + throw authErr(); + }, + }; + + const svc = new PrStatusService({ gateway, now: clock.now }); + const queries = [ + { owner: 'acme', repo: 'core', prNumber: 1 }, + { owner: 'acme', repo: 'core', prNumber: 2 }, + { owner: 'acme', repo: 'web', prNumber: 3 }, + { owner: 'acme', repo: 'web', prNumber: 4 }, + ]; + const res = await svc.getStatuses(queries); + assert.equal(res.length, 4); + for (const item of res) { + assert.equal(item.ok, false); + assert.equal(item.reason, 'gh-not-logged-in'); + } + // Must short-circuit after the very first 401 with zero fallback or remaining batch calls. + assert.equal(gqlCalls + restCalls, 1); +} + +async function checkAccountSwitchIsolation() { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-gh-acct-')); + try { + const clock = makeClock(); + let activeScope = 'acct-A'; + const store = createSharedRateLimitStore({ stateDir: dir }); + await store.record({ + bucket: 'graphql', + remaining: 0, + limit: 500, + resetAt: clock.now() + HOUR, + until: clock.now() + HOUR, + immediate: true, + now: clock.now(), + }); + await store.flush(); + + let fetchedFor = ''; + const gateway = { + async graphqlSingle(q) { + fetchedFor = activeScope; + return { remote: { state: 'merged', merged: true, head_sha: `sha-${activeScope}`, title: `T-${activeScope}` } }; + }, + async graphqlBatch({ prNumbers }) { + fetchedFor = activeScope; + const items = {}; + for (const n of prNumbers) { + items[n] = { ok: true, remote: { state: 'merged', merged: true, head_sha: `sha-${activeScope}`, title: `T-${activeScope}` } }; + } + return { items }; + }, + async restGetPr() { + fetchedFor = activeScope; + return { status: 200, notModified: false, etag: `"e-${activeScope}"`, remote: { state: 'merged', merged: true, head_sha: `sha-${activeScope}`, title: `T-${activeScope}` } }; + }, + }; + + const svc = new PrStatusService({ + gateway, + rateLimitStore: store, + now: clock.now, + scope: () => activeScope, + }); + const q = { owner: 'acme', repo: 'core', prNumber: 99 }; + const [rA] = await svc.getStatuses([q]); + assert.equal(rA.ok, true); + assert.equal(rA.headSha, 'sha-acct-A'); + assert.equal(store.isRateLimited('graphql', clock.now()), true); + + // Switch account at +10s. + clock.advance(10_000); + activeScope = 'acct-B'; + const [rB] = await svc.getStatuses([q]); + assert.equal(rB.ok, true); + assert.equal(rB.headSha, 'sha-acct-B'); + assert.equal(fetchedFor, 'acct-B'); + + // Old account's graphql bucket must be ignored even after refreshing from disk! + await store.refresh(clock.now(), true); + assert.equal(store.isRateLimited('graphql', clock.now()), false); + assert.equal(store.getPressure('graphql', clock.now()).level, 'normal'); + + // Writing a new REST observation must discard pre-switch stale GraphQL bucket on disk. + await store.record({ + bucket: 'rest', + remaining: 990, + limit: 1000, + resetAt: clock.now() + HOUR, + immediate: true, + now: clock.now(), + }); + await store.flush(); + const rawDisk = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(rawDisk.until, 0); + assert.equal(rawDisk.buckets.graphql, undefined); + assert.equal(rawDisk.buckets.rest.remaining, 990); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +async function checkAtomicRateLimitWrite() { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-gh-atomic-')); + try { + const now = T0; + const store = createSharedRateLimitStore({ stateDir: dir, writeThrottleMs: 0 }); + const writes = []; + for (let i = 0; i < 10; i += 1) { + writes.push( + store.record({ + bucket: i % 2 === 0 ? 'graphql' : 'rest', + remaining: 500 - i * 10, + limit: 500, + resetAt: now + HOUR, + immediate: true, + now: now + i * 100, + }), + ); + } + await Promise.all(writes); + await store.flush(); + + // No stray .tmp files left behind. + const entries = await fs.readdir(dir); + assert.deepEqual(entries, ['.rate-limit.json']); + const raw = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.ok(raw.buckets.graphql && raw.buckets.rest); + + // Privacy check: only allowed top-level keys. + const allowedTop = new Set(['until', 'bucket', 'reportedAt', 'reportedBy', 'summary', 'updatedAt', 'buckets']); + for (const k of Object.keys(raw)) { + assert.ok(allowedTop.has(k), `Unexpected key in .rate-limit.json: ${k}`); + } + + // REST-only rate limit must NOT set top-level until > 0. + await store.record({ + bucket: 'rest', + remaining: 0, + limit: 1000, + resetAt: now + HOUR, + until: now + HOUR, + immediate: true, + now: now + 5000, + }); + await store.flush(); + const rawRestOnly = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(rawRestOnly.until, 0); + assert.equal(rawRestOnly.buckets.rest.until, now + HOUR); + + // GraphQL rate limit MUST sync top-level until. + await store.record({ + bucket: 'graphql', + remaining: 0, + limit: 500, + resetAt: now + HOUR, + until: now + HOUR, + immediate: true, + now: now + 6000, + }); + await store.flush(); + const rawGql = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(rawGql.until, now + HOUR); + assert.equal(rawGql.bucket, 'graphql'); + + // Legacy top-level until parsing + timestamp clamping. + const legacy = parseSharedRateLimitPayload({ until: now + 10 * HOUR }, now); + assert.equal(legacy.until, now + MAX_SHARED_RATE_LIMIT_MS); + assert.equal(legacy.buckets.graphql.until, now + MAX_SHARED_RATE_LIMIT_MS); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +async function checkUnitRealUpdates() { + const clock = makeClock(); + const sim = createDeterministicGateway(clock); + const q = { owner: 'acme', repo: 'core', prNumber: 555 }; + sim.setPr(q, { state: 'open', merged: false, head_sha: 'sha-1', checks: 'pending', unresolved_count: 0, updated_at: '2026-01-01T00:00:00Z' }); + const svc = new PrStatusService({ gateway: sim.gateway, now: clock.now }); + const delivered = []; + let busy = false; + const schedule = { + id: 'unit-s1', + prKey: prStatusKey(q), + prQuery: q, + targetSessionId: 'unit-sess', + createdAt: clock.now() - HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }; + const watch = new PrFollowWatch({ + now: clock.now, + prStatusService: svc, + listSchedules: () => [schedule], + isSessionBusy: () => busy, + hasQueuedPrompt: () => false, + hasSuccessfulRunSince: () => false, + expireSchedule: () => { schedule.expired = true; }, + runSchedule: async (s) => { + if (busy) return { deferred: true }; + const [fresh] = await svc.getStatuses([s.prQuery], { refresh: true }); + delivered.push(`${fresh.headSha}|${fresh.unresolvedCount}|${fresh.checks}|${fresh.status}`); + return { deferred: false }; + }, + }); + + // Baseline + let [st] = await svc.getStatuses([q]); + watch.observe(q, st); + + // 1. New commit + clock.advance(2 * MINUTE); + sim.updatePr(q, { head_sha: 'sha-2', updated_at: '2026-01-01T00:02:00Z' }); + [st] = await svc.getStatuses([q]); + let obs = watch.observe(q, st); + assert.equal(obs.changed, true); + await watch.triggerPr(q, obs); + + // 2. New comment while session is BUSY -> must deliver once session becomes idle + busy = true; + clock.advance(2 * MINUTE); + sim.updatePr(q, { unresolved_count: 2, updated_at: '2026-01-01T00:04:00Z' }); + [st] = await svc.getStatuses([q]); + obs = watch.observe(q, st); + assert.equal(obs.changed, true); + await watch.triggerPr(q, obs); + assert.equal(delivered.length, 1); + + busy = false; + clock.advance(2 * MINUTE); + await watch.notifySessionIdle('unit-sess'); + await watch.tick(clock.now()); + assert.equal(delivered.length, 2); + + // 3. CI transition + clock.advance(2 * MINUTE); + sim.updatePr(q, { checks: 'success', updated_at: '2026-01-01T00:08:00Z' }); + [st] = await svc.getStatuses([q]); + obs = watch.observe(q, st); + assert.equal(obs.changed, true); + await watch.triggerPr(q, obs); + + assert.deepEqual(delivered, [ + 'sha-2|0|pending|open', + 'sha-2|2|pending|open', + 'sha-2|2|success|open', + ]); +} + +async function runFull48hSimulation() { + const clock = makeClock(T0); + const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), 'eval-gh-sim-')); + try { + const rateLimitStore = createSharedRateLimitStore({ + stateDir, + writeThrottleMs: 30 * MINUTE, + }); + const sim = createDeterministicGateway(clock); + + const repoSpec = [ + { owner: 'acme', repo: 'core', baseNum: 100, count: 16 }, + { owner: 'acme', repo: 'desktop', baseNum: 200, count: 14 }, + { owner: 'acme', repo: 'web', baseNum: 300, count: 12 }, + { owner: 'acme', repo: 'cli', baseNum: 400, count: 8 }, + ]; + const allQueries = []; + for (const r of repoSpec) { + for (let i = 1; i <= r.count; i += 1) { + allQueries.push({ owner: r.owner, repo: r.repo, prNumber: r.baseNum + i }); + } + } + + const schedules = new Map(); + const successfulRuns = new Map(); + const busySessions = new Set(); + const queuedPrompts = new Set(); + const mergedObservedAt = new Map(); + const deliveredEvents = new Map(); + const expectedUpdates = []; + + for (let idx = 0; idx < allQueries.length; idx += 1) { + const q = allQueries[idx]; + const key = prStatusKey(q); + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + const scheduleId = `sched-${idx + 1}`; + + if (idx < 15) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-m-${idx}`, + title: `Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, [T0 - 2 * HOUR - 50 * MINUTE]); + } else if (idx < 17) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-mg-${idx}`, + title: `Grace Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + graceOnlyFail: true, + }); + successfulRuns.set(scheduleId, []); + } else if (idx >= 22 && idx < 28) { + sim.setPr(q, { + state: 'closed', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 4 * HOUR).toISOString(), + head_sha: `sha-c-${idx}`, + title: `Closed PR ${idx}`, + checks: 'failure', + unresolved_count: 0, + review_decision: null, + }); + if (idx === 22) { + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } else { + sim.setPr(q, { + state: 'open', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 30 * MINUTE).toISOString(), + head_sha: `sha-open-${idx}-0`, + title: `Open PR ${idx}`, + checks: 'pending', + unresolved_count: 0, + review_decision: null, + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } + + const prStatusService = new PrStatusService({ + gateway: sim.gateway, + rateLimitStore, + now: clock.now, + }); + const latestPrEventId = new Map(); + const expectedDeadlines = new Map(); + const deliveredAtMinute = new Map(); + + const watch = new PrFollowWatch({ + now: clock.now, + prStatusService, + listSchedules: () => Array.from(schedules.values()), + isSessionBusy: (sessionId) => busySessions.has(sessionId), + hasQueuedPrompt: (sessionId, scheduleId) => queuedPrompts.has(`${sessionId}:${scheduleId}`), + hasSuccessfulRunSince: (scheduleId, sinceMs) => + (successfulRuns.get(scheduleId) ?? []).some((ts) => ts >= sinceMs), + expireSchedule: (scheduleId) => { + const s = schedules.get(scheduleId); + if (s) s.expired = true; + }, + runSchedule: async (schedule, info = {}) => { + const [fresh] = await prStatusService.getStatuses([schedule.prQuery], { refresh: true }); + const now = clock.now(); + const isBusy = busySessions.has(schedule.targetSessionId); + const isQueued = queuedPrompts.has(`${schedule.targetSessionId}:${schedule.id}`); + if (isBusy || isQueued) { + sim.stats.wastedBusyCalls += 1; + return { deferred: true, reason: isQueued ? 'already-queued' : 'session-running' }; + } + if (fresh?.ok && fresh.status === 'merged' && fresh.mergedAt != null && schedule.createdAt < fresh.mergedAt) { + const alreadyRan = (successfulRuns.get(schedule.id) ?? []).some((ts) => ts >= fresh.mergedAt); + const obsAt = mergedObservedAt.get(schedule.prKey); + const pastGrace = + info.changeKind !== 'merged' && obsAt !== undefined && now - obsAt >= 2 * HOUR; + if (alreadyRan || pastGrace) { + sim.stats.wastedMergedCalls += 1; + return { deferred: false }; + } + if (schedule.graceOnlyFail) return { deferred: false, failed: true }; + successfulRuns.get(schedule.id).push(now); + } + const evId = latestPrEventId.get(schedule.prKey); + if (evId) { + const fullKey = `${schedule.prKey}#${evId}`; + deliveredEvents.set(fullKey, true); + if (!deliveredAtMinute.has(fullKey)) { + deliveredAtMinute.set(fullKey, Math.round((now - T0) / MINUTE)); + } + } + return { deferred: false }; + }, + }); + + const prEventsByMinute = new Map(); + const addPrEvent = (minute, ev) => { + const list = prEventsByMinute.get(minute) ?? []; + list.push(ev); + prEventsByMinute.set(minute, list); + }; + + const mergeHours = [2, 5, 9, 14, 20]; + for (let i = 0; i < mergeHours.length; i += 1) { + const idx = 17 + i; + const m = mergeHours[i] * 60 + 4; + const evId = `merge-${idx}`; + addPrEvent(m, { + idx, + evId, + patch: (now) => ({ + state: 'merged', + merged: true, + merged_at: new Date(now).toISOString(), + updated_at: new Date(now).toISOString(), + checks: 'success', + review_decision: 'APPROVED', + }), + }); + const mergeEvKey = `${prStatusKey(allQueries[idx])}#${evId}`; + expectedUpdates.push(mergeEvKey); + expectedDeadlines.set(mergeEvKey, { minute: m, sessionId: `session-${String((idx % 20) + 1).padStart(2, '0')}` }); + } + + addPrEvent(8 * 60 + 7, { + idx: 28, + evId: 'close-28', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + addPrEvent(16 * 60 + 7, { + idx: 29, + evId: 'close-29', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + addPrEvent(24 * 60 + 5, { + idx: 22, + evId: 'reopen-22', + webhookRefresh: true, + patch: (now) => ({ + state: 'open', + merged: false, + head_sha: 'sha-reopen-22', + checks: 'pending', + updated_at: new Date(now).toISOString(), + }), + }); + const reopenKey = `${prStatusKey(allQueries[22])}#reopen-22`; + expectedUpdates.push(reopenKey); + expectedDeadlines.set(reopenKey, { minute: 24 * 60 + 5, sessionId: `session-${String((22 % 20) + 1).padStart(2, '0')}` }); + + for (let step = 0; step < 60; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; + if (minute >= SIM_MINUTES - 60) continue; + const evId = `upd-${step}`; + const mod = step % 3; + addPrEvent(minute, { + idx, + evId, + patch: (now) => { + if (mod === 0) { + return { head_sha: `sha-open-${idx}-${step + 1}`, checks: 'pending', updated_at: new Date(now).toISOString() }; + } + if (mod === 1) { + return { unresolved_count: (step % 4) + 1, review_decision: 'CHANGES_REQUESTED', updated_at: new Date(now).toISOString() }; + } + return { checks: step % 2 === 0 ? 'success' : 'failure', updated_at: new Date(now).toISOString() }; + }, + }); + const updKey = `${prStatusKey(allQueries[idx])}#${evId}`; + expectedUpdates.push(updKey); + expectedDeadlines.set(updKey, { minute, sessionId: `session-${String((idx % 20) + 1).padStart(2, '0')}` }); + } + + const busyWindows = []; + for (let step = 0; step < 36; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + if (step % 2 === 0) { + busyWindows.push({ start: minute - 2, end: minute + 28, sessionId, queuedScheduleId: null }); + } else { + busyWindows.push({ start: minute - 1, end: minute + 20, sessionId, queuedScheduleId: `sched-${idx + 1}` }); + } + } + busyWindows.push({ + start: 300, + end: 325, + sessionId: `session-${String((18 % 20) + 1).padStart(2, '0')}`, + queuedScheduleId: null, + }); + + const peakExternalHours = new Map([ + [4, 0], + [12, 20], + [20, 0], + [28, 20], + [36, 0], + [44, 20], + ]); + + for (let m = 0; m < SIM_MINUTES; m += 1) { + clock.set(T0 + m * MINUTE); + const now = clock.now(); + + const prevBusy = new Set(busySessions); + const prevQueued = new Set(queuedPrompts); + busySessions.clear(); + queuedPrompts.clear(); + for (const w of busyWindows) { + if (m >= w.start && m < w.end) { + if (w.queuedScheduleId) queuedPrompts.add(`${w.sessionId}:${w.queuedScheduleId}`); + else busySessions.add(w.sessionId); + } + } + const becameIdle = new Set(); + for (const s of prevBusy) if (!busySessions.has(s)) becameIdle.add(s); + for (const qk of prevQueued) if (!queuedPrompts.has(qk)) becameIdle.add(qk.split(':')[0]); + for (const sessionId of becameIdle) await watch.notifySessionIdle(sessionId); + + if (m % 60 === 2) { + const hour = Math.floor(m / 60); + if (peakExternalHours.has(hour)) { + await rateLimitStore.flush(); + const targetRem = peakExternalHours.get(hour); + const ext = sim.consumeExternalGraphql(targetRem); + const peerStore = createSharedRateLimitStore({ stateDir }); + await peerStore.record({ + bucket: 'graphql', + remaining: ext.remaining, + limit: ext.limit, + resetAt: ext.resetAt, + ...(ext.remaining === 0 ? { until: ext.resetAt } : {}), + immediate: true, + now, + }); + await peerStore.flush(); + } + } + + const events = prEventsByMinute.get(m); + if (events) { + for (const ev of events) { + const q = allQueries[ev.idx]; + const key = prStatusKey(q); + sim.updatePr(q, ev.patch(now)); + latestPrEventId.set(key, ev.evId); + if (ev.webhookRefresh) { + const [res] = await prStatusService.getStatuses([q], { refresh: true }); + const obs = watch.observe(q, res); + if (obs.changed) await watch.triggerPr(q, obs); + } + } + } + + if (m % 3 === 0) { + const results = await prStatusService.getStatuses(allQueries); + for (let i = 0; i < allQueries.length; i += 1) { + const q = allQueries[i]; + const res = results[i]; + if (res?.ok && res.status === 'merged' && !mergedObservedAt.has(prStatusKey(q))) { + mergedObservedAt.set(prStatusKey(q), now); + } + const obs = watch.observe(q, res); + if (obs.changed) await watch.triggerPr(q, obs); + } + } + + if (m === 12 * 60 + 10 || m === 36 * 60 + 10) { + await prStatusService.getStatuses([allQueries[0]], { refresh: true }); + } + + if (m > 0 && m % 20 === 0) { + for (let idx = 0; idx <= 21; idx += 1) { + const schedule = schedules.get(`sched-${idx + 1}`); + if (schedule && schedule.active && !schedule.expired) { + const st = prStatusService.getCachedStatus(schedule.prQuery); + if (st?.ok && st.status === 'merged') { + await watch.handleScheduledTick(schedule); + } + } + } + } + + await watch.tick(now); + } + + await rateLimitStore.flush(); + const missedUpdates = expectedUpdates.filter((id) => !deliveredEvents.has(id)); + const lateUpdates = []; + for (const id of expectedUpdates) { + if (!deliveredEvents.has(id)) continue; + const info = expectedDeadlines.get(id); + const deliveredMin = deliveredAtMinute.get(id); + if (info && Number.isFinite(deliveredMin)) { + let readyMinute = info.minute; + for (const w of busyWindows) { + if (w.sessionId === info.sessionId && info.minute >= w.start - 3 && info.minute < w.end) { + readyMinute = Math.max(readyMinute, w.end); + } + } + if (deliveredMin > readyMinute + 6) { + lateUpdates.push(`${id}(lag=${deliveredMin - readyMinute}m)`); + } + } + } + return { + api_quota_points: sim.stats.graphqlPoints + sim.stats.rest200Calls, + wasted_busy_merged_calls: sim.stats.wastedBusyCalls + sim.stats.wastedMergedCalls, + rate_limit_breaches: sim.stats.rateLimitBreaches, + missedUpdateCount: missedUpdates.length, + missedUpdates, + lateUpdateCount: lateUpdates.length, + lateUpdates, + breakdown: { ...sim.stats }, + }; + } finally { + await fs.rm(stateDir, { recursive: true, force: true }); + } +} + +const errors = []; +let gate_refresh_penetrates = false; +let gate_partial_error_isolation = false; +let gate_auth_401_short_circuit = false; +let gate_account_switch_isolation = false; +let gate_atomic_rate_limit_write = false; +let unitRealUpdatesOk = false; + +try { await checkRefreshPenetrates(); gate_refresh_penetrates = true; } catch (e) { errors.push('refresh: ' + e.message); } +try { await checkPartialErrorIsolation(); gate_partial_error_isolation = true; } catch (e) { errors.push('partial: ' + e.message); } +try { await checkAuth401ShortCircuit(); gate_auth_401_short_circuit = true; } catch (e) { errors.push('401: ' + e.message); } +try { await checkAccountSwitchIsolation(); gate_account_switch_isolation = true; } catch (e) { errors.push('accountSwitch: ' + e.message); } +try { await checkAtomicRateLimitWrite(); gate_atomic_rate_limit_write = true; } catch (e) { errors.push('atomicWrite: ' + e.message); } +try { await checkUnitRealUpdates(); unitRealUpdatesOk = true; } catch (e) { errors.push('unitUpdates: ' + e.message); } + +let simResult = { + api_quota_points: 1_000_000, + wasted_busy_merged_calls: 1_000_000, + rate_limit_breaches: 1_000_000, + missedUpdateCount: 999, +}; +try { + simResult = await runFull48hSimulation(); + if (simResult.missedUpdateCount > 0) { + errors.push(`simUpdates: missed ${simResult.missedUpdateCount} updates (${simResult.missedUpdates.slice(0, 5).join(', ')})`); + } + if (simResult.lateUpdateCount > 0) { + errors.push(`simLatency: ${simResult.lateUpdateCount} stale deliveries >6m SLA (${simResult.lateUpdates.slice(0, 5).join(', ')})`); + } +} catch (e) { + errors.push('sim: ' + e.message); +} + +const gate_real_updates = unitRealUpdatesOk && simResult.missedUpdateCount === 0 && (simResult.lateUpdateCount ?? 0) === 0; + +trusted.emit(({ + status: 'graded', + items: { + gate_real_updates, + gate_refresh_penetrates, + gate_partial_error_isolation, + gate_auth_401_short_circuit, + gate_account_switch_isolation, + gate_atomic_rate_limit_write, + }, + metrics: { + api_quota_points: simResult.api_quota_points, + wasted_busy_merged_calls: simResult.wasted_busy_merged_calls, + rate_limit_breaches: simResult.rate_limit_breaches, + }, + details: { + errors, + breakdown: simResult.breakdown, + }, +})); diff --git a/questions/perf-github-api-budget/v1/author/grade.py b/questions/perf-github-api-budget/v1/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/perf-github-api-budget/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/perf-github-api-budget/v1/author/grade_impl.py b/questions/perf-github-api-budget/v1/author/grade_impl.py new file mode 100644 index 0000000..6d5cc19 --- /dev/null +++ b/questions/perf-github-api-budget/v1/author/grade_impl.py @@ -0,0 +1,40 @@ +"""Isolated pure-Node quantitative grader: runs correctness gates + deterministic 48h GitHub API simulation.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-gh-budget-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/perf-github-api-budget/v1/author/result-channel.mjs b/questions/perf-github-api-budget/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/perf-github-api-budget/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/perf-github-api-budget/v1/candidate/CONTRACT.md b/questions/perf-github-api-budget/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..c1fadf6 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/CONTRACT.md @@ -0,0 +1,43 @@ +# Product & Protocol Contract + +This contract specifies required public module interfaces, gateway cost semantics, and correctness/safety invariants. Within these invariants, **you are free to design the optimal fetching, caching, conditional-ETag, batching, and polling/deferral strategy** to minimize total billable API quota usage. + +## 1. Shared Rate-Limit Store (`src/shared-rate-limit.mjs`) + +- Exports: `MAX_SHARED_RATE_LIMIT_MS` (`2 * 60 * 60_000`), `DEFAULT_SHARED_READ_CACHE_MS`, `DEFAULT_SHARED_WRITE_THROTTLE_MS`, `classifyQuotaPressure(remaining, limit)`, `parseSharedRateLimitPayload(raw, now)`, `SharedRateLimitStore`, `createSharedRateLimitStore(options)`. +- `options`: `{ stateDir?: string | null, readCacheMs?: number, writeThrottleMs?: number }` (persists to `/.rate-limit.json` when `stateDir` is set; memory-only otherwise). +- Public methods: `isCacheFresh(now)`, `readCached(now)`, `refresh(now, force = false)`, `record(obs)`, `flush()`, `getBucket(bucket, now)`, `getPressure(bucket, now)`, `isRateLimited(bucket, now)`, `shouldPreferRest(now)`, `clearOnAccountSwitch(invalidatedAt)`, `clearMemoryCache(invalidatedAt)`. +- **Persistence & safety invariants**: + - Writes are serialized, written atomically via temp file (`0o600` in `0o700` dir) + `rename`, clean up temp files on error, and never throw. + - **Privacy**: `.rate-limit.json` may contain ONLY numeric quota/reset timestamps and generic labels (`until`, `bucket`, `reportedAt`, `reportedBy`, `summary`, `updatedAt`, `buckets`) — never tokens, usernames, repo names, or raw errors. + - **Legacy compatibility**: `parseSharedRateLimitPayload` clamps `until`/`resetAt` to `<= now + MAX_SHARED_RATE_LIMIT_MS` and maps legacy top-level `until > now` onto `buckets[bucket ?? 'graphql']`. Written top-level `until` is `> 0` ONLY when `graphql` is rate-limited; a REST-only rate limit must keep top-level `until === 0`. + - **Account switch**: `clearOnAccountSwitch(invalidatedAt)` clears memory, advances generation, ignores pre-invalidation entries (`updatedAt < invalidatedAt`) even after `refresh()`, and drops them on subsequent merged disk writes. + - **Cross-process coordination**: Concurrent processes writing `.rate-limit.json` must observe peer rate-limit / critical-pressure updates without losing newer local or peer observations. + +## 2. PR Status Service (`src/pr-status-service.mjs`) + +- Exports: `DEFAULT_OPEN_TTL_MS`, `DEFAULT_MERGED_TTL_MS`, `DEFAULT_CLOSED_TTL_MS`, `DEFAULT_MAX_CACHE_ENTRIES`, `PR_GRAPHQL_BATCH_MAX` (`8`), `prStatusKey(q)`, `PrStatusService`. +- Constructor: `new PrStatusService({ gateway, rateLimitStore?, now?, openTtlMs?, mergedTtlMs?, closedTtlMs?, maxCacheEntries?, scope?, onObserved? })`. +- Public methods: `getStatuses(queries, opts?)`, `getCachedStatus(q)` (zero-network synchronous lookup), `getCacheSize()`, `invalidate(nextScope?)`. +- **Gateway interface & billing model**: + - `gateway.graphqlSingle(q)` → **1 GraphQL pt** (returns `{ remote, headers? }`). + - `gateway.graphqlBatch({ owner, repo, prNumbers })` (`1 <= prNumbers.length <= 8`, same repo) → **1 GraphQL pt total** (returns `{ items, headers? }`). + - `gateway.restGetPr(q, { etag? })` → **`0` pts** on `{ status: 304, notModified: true, etag, headers? }`; **1 REST pt** on `{ status: 200, notModified: false, etag, remote, headers? }`. +- **Correctness & freshness invariants**: + - `opts.refresh === true` always penetrates cache and fetches live remote state (including merged/closed PRs). + - Real PR updates on open PRs (commits, comments, CI status changes) must be observed promptly when polled (2-minute sequential transitions and 6-minute end-to-end delivery SLA). + - If `graphqlBatch` is used and an individual item fails with a non-`notFound` error, fall back ONLY that PR without poisoning valid siblings; clean `notFound` returns `{ ok: false, ..., reason: 'not-found' }` with zero fallback. + - On HTTP `401`, immediately short-circuit and return `{ ok: false, ..., reason: 'gh-not-logged-in' }` for all remaining queries in the call with **zero** fallback or subsequent gateway requests. + - Scope/account change (`invalidate()` or `scope()` changing) clears cached statuses, ETags, and calls `rateLimitStore?.clearOnAccountSwitch(now)`. + - Every gateway response/error with rate-limit headers must update `rateLimitStore` so quota pressure stays accurate across processes. + +## 3. PR Follow Watch (`src/pr-follow-watch.mjs`) + +- Exports: `MIN_RETRIGGER_MS`, `MAX_DEFER_BACKOFF_MS`, `PR_FOLLOW_END_GRACE_MS` (`2 * 60 * 60_000`), `computeDeferredBackoffMs(deferCount)`, `prStatusSignature(result)`, `PrFollowWatch`. +- Constructor: `new PrFollowWatch({ now?, prStatusService?, listSchedules, isSessionBusy?, hasQueuedPrompt?, hasSuccessfulRunSince?, expireSchedule?, runSchedule })`. +- Public methods: `reset()`, `observe(query, result)`, `triggerPr(query, info)`, `handleScheduledTick(schedule)`, `notifySessionIdle(sessionId)`, `tick(now)`. +- **Scheduling & delivery invariants**: + - Deliver 100% of real PR updates (commits, comments, CI transitions, merges, reopens) within the freshness SLA. + - Do not invoke `runSchedule` while `isSessionBusy(sessionId)` or `hasQueuedPrompt(sessionId, scheduleId)` is true; defer with bounded backoff and immediately drain pending wakeups on `notifySessionIdle(sessionId)`. + - Expire settled merged follow schedules via `expireSchedule` with **zero network calls** (using cached merged state): when `createdAt < mergedAt` and either a successful run already happened since `mergedAt` or a recurring follow's merge was observed `>= PR_FOLLOW_END_GRACE_MS` ago. + - Never prematurely expire schedules created at or after `mergedAt`, and ignore pre-creation merge events for them. diff --git a/questions/perf-github-api-budget/v1/candidate/ENVIRONMENT.md b/questions/perf-github-api-budget/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..df2c3a7 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock (`now()`) and an in-memory mock GitHub gateway — quota points, wasted calls, and rate-limit breaches are exact, hardware-independent integers. +- Public checks: + - `npm test` — functional correctness smoke tests + - `npm run bench` — deterministic 48-hour 50-PR workload benchmark reporting `api_quota_points`, `wasted_busy_merged_calls`, and `rate_limit_breaches` diff --git a/questions/perf-github-api-budget/v1/candidate/TASK.md b/questions/perf-github-api-budget/v1/candidate/TASK.md new file mode 100644 index 0000000..57b4f63 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/TASK.md @@ -0,0 +1,27 @@ +# Task + +You are optimizing Cindy's GitHub PR status polling, PR-follow scheduling, and cross-process rate-limit coordination pipeline extracted from production desktop operations. + +## Observed Production Symptoms + +1. **Severe GitHub API quota burn & repeated 429 breaches**: Polling 50 tracked PRs across 4 repositories over 48 hours burns >50,000 billable API points and triggers >30,000 HTTP 429 failures. Sibling processes share the same GitHub account quota via `.rate-limit.json`, yet quota pressure is not coordinated effectively across processes or transports. +2. **Wasted pre-run GitHub calls on busy sessions and settled merged PRs**: When a PR changes while its bound session is busy or already has a queued prompt, `PrFollowWatch` keeps firing the runner repeatedly only to defer—and recurring ticks continue polling already-merged PRs long after they have settled. +3. **Small FIFO cache**: The status cache evicts at 200 entries in FIFO order instead of keeping active multi-repo PRs warm. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness, freshness, and safety invariants** defined in `CONTRACT.md`: + - Every real PR update (new commit, review/comment change, CI status transition, merge, reopen) must be detected and delivered promptly (within the freshness SLA; zero missed updates). + - Explicit `refresh: true` must always penetrate the cache (including merged PRs). + - Single-PR errors must not poison sibling PRs, clean 404s must not waste fallbacks, and HTTP 401 must immediately short-circuit with zero extra calls. + - Account switches must clear cached PR statuses, ETags, and stale rate-limit buckets. + - Cross-process rate-limit persistence must remain atomic, privacy-safe, and backward-compatible with legacy top-level `until` files. +- **Open-ended optimization goal**: You are free to choose the most effective transport selection (GraphQL batching vs conditional REST `ETag` / `304 Not Modified`), caching, invalidation, backoff, and scheduling strategy across `src/` to drive all three 48-hour simulation metrics as low as possible: + - `api_quota_points` (total billable API points — lower is better; `304 Not Modified` costs `0` points!) + - `wasted_busy_merged_calls` (calls wasted on busy/queued sessions or settled merged PRs — drive to `0`) + - `rate_limit_breaches` (429/exhausted failures — drive to `0`) +- Run `npm test` and `npm run bench` to verify correctness and compare before/after numbers. +- Record your analysis, design trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-github-api-budget/v1/candidate/bench/workload.mjs b/questions/perf-github-api-budget/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..7c29d79 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/bench/workload.mjs @@ -0,0 +1,626 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore } from '../src/shared-rate-limit.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const T0 = 1_760_000_000_000; +const SIM_MINUTES = 48 * 60; // 48 hours +const GQL_HOURLY_LIMIT = 500; +const REST_HOURLY_LIMIT = 1000; + +export function createDeterministicGateway(clock) { + const prs = new Map(); + let gqlRemaining = GQL_HOURLY_LIMIT; + let restRemaining = REST_HOURLY_LIMIT; + let windowResetAt = clock.now() + HOUR; + + const stats = { + graphqlCalls: 0, + graphqlPoints: 0, + rest200Calls: 0, + rest304Calls: 0, + rateLimitBreaches: 0, + wastedBusyCalls: 0, + wastedMergedCalls: 0, + }; + + function syncWindow() { + const now = clock.now(); + if (now >= windowResetAt) { + const hoursElapsed = Math.floor((now - windowResetAt) / HOUR) + 1; + windowResetAt += hoursElapsed * HOUR; + gqlRemaining = GQL_HOURLY_LIMIT; + restRemaining = REST_HOURLY_LIMIT; + } + } + + function makeHeaders(resource, remaining, limit) { + return { + 'x-ratelimit-resource': resource, + 'x-ratelimit-remaining': String(remaining), + 'x-ratelimit-limit': String(limit), + 'x-ratelimit-reset': String(Math.floor(windowResetAt / 1000)), + }; + } + + function rateLimitError(resource, remaining, limit) { + const err = new Error('GITHUB_RATE_LIMITED'); + err.status = 429; + err.code = 'GITHUB_RATE_LIMITED'; + err.headers = makeHeaders(resource, remaining, limit); + return err; + } + + function setPr(q, remote) { + const key = prStatusKey(q); + const prev = prs.get(key); + const version = (prev?.version ?? 0) + 1; + prs.set(key, { + q, + remote: { ...remote }, + version, + etag: `"v${version}-${remote.state}-${remote.head_sha}"`, + }); + } + + function updatePr(q, patch) { + const key = prStatusKey(q); + const cur = prs.get(key); + if (!cur) throw new Error(`Unknown PR ${key}`); + setPr(q, { ...cur.remote, ...patch }); + } + + function consumeExternalGraphql(targetRemaining) { + syncWindow(); + gqlRemaining = Math.max(0, Math.min(gqlRemaining, targetRemaining)); + return { remaining: gqlRemaining, limit: GQL_HOURLY_LIMIT, resetAt: windowResetAt }; + } + + const gateway = { + async graphqlSingle(q) { + syncWindow(); + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const entry = prs.get(prStatusKey(q)); + return { + remote: entry ? { ...entry.remote } : null, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async graphqlBatch({ owner, repo, prNumbers }) { + syncWindow(); + if (!Array.isArray(prNumbers) || prNumbers.length === 0 || prNumbers.length > 8) { + const err = new Error('Invalid batch size (must be 1..8)'); + err.status = 400; + throw err; + } + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const items = {}; + for (const prNumber of prNumbers) { + const entry = prs.get(prStatusKey({ owner, repo, prNumber })); + if (!entry) { + items[prNumber] = { ok: false, notFound: true }; + } else { + items[prNumber] = { ok: true, remote: { ...entry.remote } }; + } + } + return { + items, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async restGetPr(q, opts = {}) { + syncWindow(); + const entry = prs.get(prStatusKey(q)); + if (!entry) { + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + const err = new Error('NOT_FOUND'); + err.status = 404; + err.headers = makeHeaders('core', restRemaining, REST_HOURLY_LIMIT); + throw err; + } + if (opts?.etag && opts.etag === entry.etag) { + // Conditional GET 304 Not Modified costs 0 billable REST quota points. + stats.rest304Calls += 1; + return { + status: 304, + notModified: true, + etag: entry.etag, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + } + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + return { + status: 200, + notModified: false, + etag: entry.etag, + remote: { ...entry.remote }, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + }, + }; + + return { gateway, stats, setPr, updatePr, consumeExternalGraphql }; +} + +export async function runSimulation() { + let currentTime = T0; + const clock = { + now: () => currentTime, + set: (t) => { + currentTime = t; + }, + }; + + const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-gh-budget-bench-')); + try { + const rateLimitStore = createSharedRateLimitStore({ + stateDir, + writeThrottleMs: 30 * MINUTE, + }); + const sim = createDeterministicGateway(clock); + + const repoSpec = [ + { owner: 'acme', repo: 'core', baseNum: 100, count: 16 }, + { owner: 'acme', repo: 'desktop', baseNum: 200, count: 14 }, + { owner: 'acme', repo: 'web', baseNum: 300, count: 12 }, + { owner: 'acme', repo: 'cli', baseNum: 400, count: 8 }, + ]; + + const allQueries = []; + for (const r of repoSpec) { + for (let i = 1; i <= r.count; i += 1) { + allQueries.push({ owner: r.owner, repo: r.repo, prNumber: r.baseNum + i }); + } + } + + // Partition 50 PRs: + // 0..14 (15): pre-merged with completed post-merge run + // 15..16 (2): pre-merged with no post-merge run (tests 2h grace-window convergence) + // 17..21 (5): open at T0, merge during hours 2..20 + // 22..27 (6): pre-closed (unmerged); #22 reopens at hour 24 via refresh:true + // 28..29 (2): open at T0, close at hours 8 & 16 + // 30..49 (20): active open PRs throughout 48h + const schedules = new Map(); + const successfulRuns = new Map(); // scheduleId -> number[] + const busySessions = new Set(); + const queuedPrompts = new Set(); // `${sessionId}:${scheduleId}` + const mergedObservedAt = new Map(); // key -> ms + const deliveredEvents = new Map(); // `${key}#${eventId}` -> true + const expectedUpdates = []; + + for (let idx = 0; idx < allQueries.length; idx += 1) { + const q = allQueries[idx]; + const key = prStatusKey(q); + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + const scheduleId = `sched-${idx + 1}`; + + if (idx < 15) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-m-${idx}`, + title: `Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, [T0 - 2 * HOUR - 50 * MINUTE]); + } else if (idx < 17) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-mg-${idx}`, + title: `Grace Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + graceOnlyFail: true, + }); + successfulRuns.set(scheduleId, []); + } else if (idx >= 22 && idx < 28) { + sim.setPr(q, { + state: 'closed', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 4 * HOUR).toISOString(), + head_sha: `sha-c-${idx}`, + title: `Closed PR ${idx}`, + checks: 'failure', + unresolved_count: 0, + review_decision: null, + }); + if (idx === 22) { + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } else { + sim.setPr(q, { + state: 'open', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 30 * MINUTE).toISOString(), + head_sha: `sha-open-${idx}-0`, + title: `Open PR ${idx}`, + checks: 'pending', + unresolved_count: 0, + review_decision: null, + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 1 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } + + const prStatusService = new PrStatusService({ + gateway: sim.gateway, + rateLimitStore, + now: clock.now, + }); + + // Latest expected event marker per PR so we verify real updates are delivered. + const latestPrEventId = new Map(); + + const watch = new PrFollowWatch({ + now: clock.now, + prStatusService, + listSchedules: () => Array.from(schedules.values()), + isSessionBusy: (sessionId) => busySessions.has(sessionId), + hasQueuedPrompt: (sessionId, scheduleId) => queuedPrompts.has(`${sessionId}:${scheduleId}`), + hasSuccessfulRunSince: (scheduleId, sinceMs) => + (successfulRuns.get(scheduleId) ?? []).some((ts) => ts >= sinceMs), + expireSchedule: (scheduleId) => { + const s = schedules.get(scheduleId); + if (s) s.expired = true; + }, + runSchedule: async (schedule, info = {}) => { + // Runner preRunHook fetches fresh PR status from GitHub before checking session/merged state. + const [fresh] = await prStatusService.getStatuses([schedule.prQuery], { refresh: true }); + const now = clock.now(); + const isBusy = busySessions.has(schedule.targetSessionId); + const isQueued = queuedPrompts.has(`${schedule.targetSessionId}:${schedule.id}`); + if (isBusy || isQueued) { + sim.stats.wastedBusyCalls += 1; + return { deferred: true, reason: isQueued ? 'already-queued' : 'session-running' }; + } + if (fresh?.ok && fresh.status === 'merged' && fresh.mergedAt != null && schedule.createdAt < fresh.mergedAt) { + const alreadyRan = (successfulRuns.get(schedule.id) ?? []).some((ts) => ts >= fresh.mergedAt); + const obsAt = mergedObservedAt.get(schedule.prKey); + const pastGrace = + info.changeKind !== 'merged' && obsAt !== undefined && now - obsAt >= 2 * HOUR; + if (alreadyRan || pastGrace) { + sim.stats.wastedMergedCalls += 1; + return { deferred: false }; + } + if (schedule.graceOnlyFail) { + // Simulate a failed post-merge run so grace-window expiry is exercised. + return { deferred: false, failed: true }; + } + successfulRuns.get(schedule.id).push(now); + } + const evId = latestPrEventId.get(schedule.prKey); + if (evId) deliveredEvents.set(`${schedule.prKey}#${evId}`, true); + return { deferred: false }; + }, + }); + + // Build deterministic event timeline across 48 hours. + const prEventsByMinute = new Map(); + const addPrEvent = (minute, ev) => { + const list = prEventsByMinute.get(minute) ?? []; + list.push(ev); + prEventsByMinute.set(minute, list); + }; + + // 5 open PRs (17..21) merge at hours 2, 5, 9, 14, 20. + const mergeHours = [2, 5, 9, 14, 20]; + for (let i = 0; i < mergeHours.length; i += 1) { + const idx = 17 + i; + const m = mergeHours[i] * 60 + 4; + const evId = `merge-${idx}`; + addPrEvent(m, { + idx, + evId, + kind: 'merge', + patch: (now) => ({ + state: 'merged', + merged: true, + merged_at: new Date(now).toISOString(), + updated_at: new Date(now).toISOString(), + checks: 'success', + review_decision: 'APPROVED', + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // 2 open PRs (28, 29) close at hours 8 and 16. + addPrEvent(8 * 60 + 7, { + idx: 28, + evId: 'close-28', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + addPrEvent(16 * 60 + 7, { + idx: 29, + evId: 'close-29', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + + // Closed PR #22 reopens at hour 24 via explicit webhook refresh. + addPrEvent(24 * 60 + 5, { + idx: 22, + evId: 'reopen-22', + kind: 'reopen-webhook', + webhookRefresh: true, + patch: (now) => ({ + state: 'open', + merged: false, + head_sha: 'sha-reopen-22', + checks: 'pending', + updated_at: new Date(now).toISOString(), + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[22])}#reopen-22`); + + // 60 real updates (commits, comments/reviews, CI checks) on the 20 active open PRs (30..49). + for (let step = 0; step < 60; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; // spaced every 45 minutes across 48h + if (minute >= SIM_MINUTES - 60) continue; + const evId = `upd-${step}`; + const mod = step % 3; + addPrEvent(minute, { + idx, + evId, + kind: mod === 0 ? 'commit' : mod === 1 ? 'comment' : 'ci', + patch: (now) => { + if (mod === 0) { + return { head_sha: `sha-open-${idx}-${step + 1}`, checks: 'pending', updated_at: new Date(now).toISOString() }; + } + if (mod === 1) { + return { unresolved_count: (step % 4) + 1, review_decision: 'CHANGES_REQUESTED', updated_at: new Date(now).toISOString() }; + } + return { checks: step % 2 === 0 ? 'success' : 'failure', updated_at: new Date(now).toISOString() }; + }, + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // Busy session windows overlapping ~35 of those updates + merge #18 (at hour 5). + const busyWindows = []; + for (let step = 0; step < 36; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + if (step % 2 === 0) { + busyWindows.push({ start: minute - 2, end: minute + 28, sessionId, queuedScheduleId: null }); + } else { + busyWindows.push({ start: minute - 1, end: minute + 20, sessionId, queuedScheduleId: `sched-${idx + 1}` }); + } + } + // Also overlap merge of PR #18 (hour 5 = minute 304) with busy session. + busyWindows.push({ + start: 300, + end: 325, + sessionId: `session-${String((18 % 20) + 1).padStart(2, '0')}`, + queuedScheduleId: null, + }); + + const peakExternalHours = new Map([ + [4, 0], // exhausted + [12, 20], // critical (<= 50) + [20, 0], // exhausted + [28, 20], // critical + [36, 0], // exhausted + [44, 20], // critical + ]); + + // Step through 48 hours minute by minute. + for (let m = 0; m < SIM_MINUTES; m += 1) { + clock.set(T0 + m * MINUTE); + const now = clock.now(); + + // 1. Update busy/queued session states and notify idle transitions. + const prevBusy = new Set(busySessions); + const prevQueued = new Set(queuedPrompts); + busySessions.clear(); + queuedPrompts.clear(); + for (const w of busyWindows) { + if (m >= w.start && m < w.end) { + if (w.queuedScheduleId) queuedPrompts.add(`${w.sessionId}:${w.queuedScheduleId}`); + else busySessions.add(w.sessionId); + } + } + const becameIdle = new Set(); + for (const s of prevBusy) if (!busySessions.has(s)) becameIdle.add(s); + for (const qk of prevQueued) { + if (!queuedPrompts.has(qk)) becameIdle.add(qk.split(':')[0]); + } + for (const sessionId of becameIdle) { + await watch.notifySessionIdle(sessionId); + } + + // 2. Simulate external sibling process writing shared .rate-limit.json during peak hours. + if (m % 60 === 2) { + const hour = Math.floor(m / 60); + if (peakExternalHours.has(hour)) { + await rateLimitStore.flush(); + const targetRem = peakExternalHours.get(hour); + const ext = sim.consumeExternalGraphql(targetRem); + const peerStore = createSharedRateLimitStore({ stateDir }); + await peerStore.record({ + bucket: 'graphql', + remaining: ext.remaining, + limit: ext.limit, + resetAt: ext.resetAt, + ...(ext.remaining === 0 ? { until: ext.resetAt } : {}), + immediate: true, + now, + }); + await peerStore.flush(); + } + } + + // 3. Apply scheduled PR mutations. + const events = prEventsByMinute.get(m); + if (events) { + for (const ev of events) { + const q = allQueries[ev.idx]; + const key = prStatusKey(q); + sim.updatePr(q, ev.patch(now)); + latestPrEventId.set(key, ev.evId); + if (ev.webhookRefresh) { + const [res] = await prStatusService.getStatuses([q], { refresh: true }); + const obs = watch.observe(q, res); + if (obs.changed) await watch.triggerPr(q, obs); + } + } + } + + // 4. Periodic workspace PR status polling (every 3 minutes across all 50 PRs). + if (m % 3 === 0) { + const results = await prStatusService.getStatuses(allQueries); + for (let i = 0; i < allQueries.length; i += 1) { + const q = allQueries[i]; + const res = results[i]; + if (res?.ok && res.status === 'merged' && !mergedObservedAt.has(prStatusKey(q))) { + mergedObservedAt.set(prStatusKey(q), now); + } + const obs = watch.observe(q, res); + if (obs.changed) { + await watch.triggerPr(q, obs); + } + } + } + + // 5. Explicit user refresh on merged PRs at hours 12 and 36. + if (m === 12 * 60 + 10 || m === 36 * 60 + 10) { + await prStatusService.getStatuses([allQueries[0]], { refresh: true }); + } + + // 6. Recurring PR-follow cron ticks every 20 minutes on merged schedules (0..21). + if (m > 0 && m % 20 === 0) { + for (let idx = 0; idx <= 21; idx += 1) { + const schedule = schedules.get(`sched-${idx + 1}`); + if (schedule && schedule.active && !schedule.expired) { + const st = prStatusService.getCachedStatus(schedule.prQuery); + if (st?.ok && st.status === 'merged') { + await watch.handleScheduledTick(schedule); + } + } + } + } + + // 7. Drain due pending follow wakeups. + await watch.tick(now); + } + + await rateLimitStore.flush(); + const missedUpdates = expectedUpdates.filter((id) => !deliveredEvents.has(id)); + const api_quota_points = sim.stats.graphqlPoints + sim.stats.rest200Calls; + const wasted_busy_merged_calls = sim.stats.wastedBusyCalls + sim.stats.wastedMergedCalls; + const rate_limit_breaches = sim.stats.rateLimitBreaches; + + return { + api_quota_points, + wasted_busy_merged_calls, + rate_limit_breaches, + breakdown: { ...sim.stats }, + expectedUpdateCount: expectedUpdates.length, + missedUpdateCount: missedUpdates.length, + missedUpdates, + }; + } finally { + await fs.rm(stateDir, { recursive: true, force: true }); + } +} + +if (isMainModule()) { + const result = await runSimulation(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/perf-github-api-budget/v1/candidate/package.json b/questions/perf-github-api-budget/v1/candidate/package.json new file mode 100644 index 0000000..c301e7f --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-github-api-budget", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-github-api-budget/v1/candidate/src/pr-follow-watch.mjs b/questions/perf-github-api-budget/v1/candidate/src/pr-follow-watch.mjs new file mode 100644 index 0000000..0e6a89e --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/src/pr-follow-watch.mjs @@ -0,0 +1,113 @@ +import { prStatusKey } from './pr-status-service.mjs'; + +export const MIN_RETRIGGER_MS = 60_000; +export const MAX_DEFER_BACKOFF_MS = 15 * 60_000; +export const PR_FOLLOW_END_GRACE_MS = 2 * 60 * 60_000; + +export function computeDeferredBackoffMs(deferCount) { + if (deferCount <= 1) return MIN_RETRIGGER_MS; + return Math.min(MAX_DEFER_BACKOFF_MS, MIN_RETRIGGER_MS * 2 ** (deferCount - 1)); +} + +export function prStatusSignature(result) { + if (!result?.ok) return null; + return [ + result.status ?? '', + result.headSha ?? '', + result.checks ?? '', + String(result.unresolvedCount ?? 0), + result.reviewDecision ?? '', + result.updatedAt ?? '', + ].join('|'); +} + +export class PrFollowWatch { + constructor(deps) { + this.deps = deps; + this.now = deps.now ?? Date.now; + this.signatures = new Map(); + this.pending = new Map(); + } + + reset() { + this.signatures.clear(); + this.pending.clear(); + } + + observe(query, result) { + const fresh = prStatusSignature(result); + if (fresh === null) return { changed: false, changeKind: null }; + const key = prStatusKey(query); + const previous = this.signatures.get(key); + this.signatures.set(key, fresh); + if (previous === undefined || previous === fresh) { + return { changed: false, changeKind: null }; + } + const prevStatus = previous.split('|')[0]; + const changeKind = + result.status === 'merged' && prevStatus !== 'merged' + ? 'merged' + : result.status === 'open' && prevStatus === 'closed' + ? 'reopened' + : 'update'; + return { + changed: true, + changeKind, + ...(result.status === 'merged' && result.mergedAt != null ? { mergedAt: result.mergedAt } : {}), + }; + } + + async triggerPr(query, info = {}) { + const key = prStatusKey(query); + const schedules = (await this.deps.listSchedules()).filter( + (s) => s.active && !s.expired && s.prKey === key, + ); + for (const schedule of schedules) { + await this._dispatchSchedule(schedule, info); + } + } + + async handleScheduledTick(schedule) { + if (!schedule.active || schedule.expired) return { status: 'skipped' }; + // Baseline: no zero-network merged expiry, no busy/queued short-circuit before running preRunHook. + return this._dispatchSchedule(schedule, { changeKind: 'scheduled-tick' }); + } + + async _dispatchSchedule(schedule, info) { + const now = this.now(); + this.pending.delete(schedule.id); + const outcome = await this.deps.runSchedule(schedule, info); + if (outcome?.deferred) { + // Baseline: flat 1-minute retry loop with no exponential backoff. + this.pending.set(schedule.id, { + schedule, + info, + notBefore: now + MIN_RETRIGGER_MS, + }); + return { status: 'deferred' }; + } + return { status: 'ran' }; + } + + async notifySessionIdle(_sessionId) { + // Baseline: does not wake deferred schedules early on session idle. + } + + async tick(now = this.now()) { + const due = []; + for (const [id, entry] of this.pending.entries()) { + if (entry.notBefore <= now) { + due.push([id, entry]); + } + } + for (const [id, entry] of due) { + if (!this.pending.has(id)) continue; + const latest = (await this.deps.listSchedules()).find((s) => s.id === id); + if (!latest || !latest.active || latest.expired) { + this.pending.delete(id); + continue; + } + await this._dispatchSchedule(latest, entry.info); + } + } +} diff --git a/questions/perf-github-api-budget/v1/candidate/src/pr-status-service.mjs b/questions/perf-github-api-budget/v1/candidate/src/pr-status-service.mjs new file mode 100644 index 0000000..9f488f7 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/src/pr-status-service.mjs @@ -0,0 +1,192 @@ +export const DEFAULT_OPEN_TTL_MS = 60_000; +export const DEFAULT_MERGED_TTL_MS = 24 * 60 * 60_000; +export const DEFAULT_CLOSED_TTL_MS = 30 * 60_000; +export const DEFAULT_MAX_CACHE_ENTRIES = 200; +export const PR_GRAPHQL_BATCH_MAX = 8; + +export function prStatusKey(q) { + return `${q.owner.toLowerCase()}/${q.repo.toLowerCase()}#${q.prNumber}`; +} + +function mapRemoteStatus(remote) { + if (remote.merged || remote.state === 'merged' || remote.state === 'MERGED') return 'merged'; + if (remote.state === 'closed' || remote.state === 'CLOSED') return 'closed'; + return 'open'; +} + +export class PrStatusService { + constructor(deps) { + this.deps = deps; + this.gateway = deps.gateway; + this.rateLimitStore = deps.rateLimitStore ?? null; + this.now = deps.now ?? Date.now; + this.openTtlMs = deps.openTtlMs ?? DEFAULT_OPEN_TTL_MS; + this.mergedTtlMs = Math.max(this.openTtlMs, deps.mergedTtlMs ?? DEFAULT_MERGED_TTL_MS); + this.closedTtlMs = Math.max(this.openTtlMs, deps.closedTtlMs ?? DEFAULT_CLOSED_TTL_MS); + this.maxCacheEntries = Math.max(1, Math.floor(deps.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES)); + this.cache = new Map(); + this.scope = null; + this.generation = 0; + } + + getCacheSize() { + return this.cache.size; + } + + getCachedStatus(q) { + return this.cache.get(prStatusKey(q))?.result; + } + + invalidate(nextScope = this.scope) { + this.generation += 1; + this.scope = nextScope; + this.cache.clear(); + this.rateLimitStore?.clearOnAccountSwitch(this.now()); + } + + _buildOkResult(q, remote) { + const status = mapRemoteStatus(remote); + const mergedAt = + remote.merged_at !== undefined && remote.merged_at !== null + ? typeof remote.merged_at === 'number' + ? remote.merged_at + : Date.parse(remote.merged_at) + : null; + return { + ok: true, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + status, + headSha: remote.head_sha ?? '', + title: remote.title ?? '', + checks: remote.checks ?? 'pending', + unresolvedCount: remote.unresolved_count ?? 0, + reviewDecision: remote.review_decision ?? null, + updatedAt: remote.updated_at ?? '', + mergedAt: Number.isFinite(mergedAt) ? mergedAt : null, + observedAt: this.now(), + }; + } + + _commitCachedResult(key, q, result) { + const fetchedAt = this.now(); + // Baseline: flat openTtlMs for all states + FIFO eviction at 200 entries. + if (this.cache.size >= this.maxCacheEntries && !this.cache.has(key)) { + this.cache.delete(this.cache.keys().next().value); + } + this.cache.set(key, { + result, + fetchedAt, + expiresAt: fetchedAt + this.openTtlMs, + }); + try { + this.deps.onObserved?.(q, result); + } catch { + // Observers are best-effort. + } + } + + async _checkScope() { + if (!this.deps.scope) return; + const nextScope = await this.deps.scope(); + if (this.scope === null) { + this.scope = nextScope; + return; + } + if (nextScope !== this.scope) { + this.invalidate(nextScope); + } + } + + async _fetchOne(q) { + try { + const res = await this.gateway.graphqlSingle(q); + if (!res?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + return this._buildOkResult(q, res.remote); + } catch (err) { + const status = err?.status; + if (status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + // Baseline fallback: plain REST without ETag caching and without proactive switching. + try { + const rest = await this.gateway.restGetPr(q, {}); + if (!rest?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + return this._buildOkResult(q, rest.remote); + } catch (restErr) { + if (restErr?.status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (restErr?.status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + if (restErr?.status === 429 || restErr?.code === 'GITHUB_RATE_LIMITED') { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'rate-limited' }; + } + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'fetch-failed' }; + } + } + } + + async getStatuses(queries, opts = {}) { + await this._checkScope(); + const generation = this.generation; + const refresh = opts.refresh === true; + const results = new Array(queries.length); + let aborted401 = false; + + for (let i = 0; i < queries.length; i += 1) { + const q = queries[i]; + const key = prStatusKey(q); + if (aborted401) { + results[i] = { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'gh-not-logged-in' }; + continue; + } + const now = this.now(); + const cached = this.cache.get(key); + if (!refresh && cached && cached.expiresAt > now) { + results[i] = cached.result; + continue; + } + const fetched = await this._fetchOne(q); + if (generation !== this.generation) { + results[i] = { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'gh-not-logged-in' }; + continue; + } + if (fetched._shortCircuit401) { + aborted401 = true; + const { _shortCircuit401: _, ...clean } = fetched; + results[i] = clean; + continue; + } + if (fetched.ok || fetched.reason === 'not-found') { + this._commitCachedResult(key, q, fetched); + } + results[i] = fetched; + } + + return results; + } +} diff --git a/questions/perf-github-api-budget/v1/candidate/src/shared-rate-limit.mjs b/questions/perf-github-api-budget/v1/candidate/src/shared-rate-limit.mjs new file mode 100644 index 0000000..df50015 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/src/shared-rate-limit.mjs @@ -0,0 +1,387 @@ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export const MAX_SHARED_RATE_LIMIT_MS = 2 * 60 * 60_000; +export const DEFAULT_SHARED_READ_CACHE_MS = 5_000; +export const DEFAULT_SHARED_WRITE_THROTTLE_MS = 30_000; +const SIGNIFICANT_DROP_MIN_INTERVAL_MS = 5_000; +const SAME_WINDOW_TOLERANCE_MS = 60_000; +const RATE_LIMIT_FILENAME = '.rate-limit.json'; + +export function classifyQuotaPressure(remaining, limit) { + if (remaining === 0) return 'exhausted'; + if (remaining <= Math.max(50, Math.floor(limit * 0.05))) return 'critical'; + if (remaining <= Math.max(200, Math.floor(limit * 0.2))) return 'low'; + return 'normal'; +} + +function resolveRateLimitFilePath(configuredDir) { + if (configuredDir === null || configuredDir === undefined) return null; + if (typeof configuredDir === 'string') { + const trimmed = configuredDir.trim(); + return trimmed ? path.join(trimmed, RATE_LIMIT_FILENAME) : null; + } + return null; +} + +function clampTimestampMs(value, now) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return 0; + return Math.min(Math.floor(num), now + MAX_SHARED_RATE_LIMIT_MS); +} + +function parseNonNegativeInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num < 0) return undefined; + return Math.floor(num); +} + +function parsePositiveInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return undefined; + return Math.floor(num); +} + +function parseBucketState(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined; + const until = clampTimestampMs(raw.until, now); + const remaining = parseNonNegativeInt(raw.remaining); + const limit = parsePositiveInt(raw.limit); + const resetAt = clampTimestampMs(raw.resetAt, now) || undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? 0; + if (until === 0 && remaining === undefined && limit === undefined && resetAt === undefined) { + return undefined; + } + return { + until, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt, + }; +} + +export function parseSharedRateLimitPayload(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const topUntil = clampTimestampMs(raw.until, now); + const topBucket = raw.bucket === 'graphql' || raw.bucket === 'rest' ? raw.bucket : undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? parseNonNegativeInt(raw.reportedAt) ?? 0; + const reportedAt = parseNonNegativeInt(raw.reportedAt); + + const buckets = {}; + if (raw.buckets && typeof raw.buckets === 'object' && !Array.isArray(raw.buckets)) { + const gql = parseBucketState(raw.buckets.graphql, now); + const rest = parseBucketState(raw.buckets.rest, now); + if (gql) buckets.graphql = gql; + if (rest) buckets.rest = rest; + } + + if (topUntil > now) { + const targetBucket = topBucket ?? 'graphql'; + const existing = buckets[targetBucket]; + if (!existing || topUntil > existing.until) { + buckets[targetBucket] = { + ...existing, + until: topUntil, + updatedAt: Math.max(existing?.updatedAt ?? 0, updatedAt), + }; + } + } + + if (topUntil === 0 && !buckets.graphql && !buckets.rest) return null; + + return { + until: topUntil, + ...(topBucket ? { bucket: topBucket } : {}), + ...(reportedAt !== undefined ? { reportedAt } : {}), + updatedAt, + buckets, + }; +} + +async function readRateLimitFile(filePath, now) { + try { + const text = await fs.readFile(filePath, 'utf8'); + return parseSharedRateLimitPayload(JSON.parse(text), now); + } catch { + return null; + } +} + +async function writeRateLimitFileAtomic(filePath, payload) { + const dir = path.dirname(filePath); + const tmpFile = path.join( + dir, + `${RATE_LIMIT_FILENAME}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`, + ); + try { + const content = `${JSON.stringify(payload, null, 2)}\n`; + await fs.writeFile(tmpFile, content, { encoding: 'utf8', mode: 0o600 }); + await fs.chmod(tmpFile, 0o600).catch(() => undefined); + await fs.rename(tmpFile, filePath); + } catch { + await fs.unlink(tmpFile).catch(() => undefined); + } +} + +function mergeBucketState(existing, obs) { + const now = obs.now; + const obsUntil = obs.until !== undefined ? clampTimestampMs(obs.until, now) : undefined; + const obsResetAt = obs.resetAt !== undefined ? clampTimestampMs(obs.resetAt, now) : undefined; + const existingResetAt = existing?.resetAt ?? 0; + const windowAdvanced = + obsResetAt !== undefined && + obsResetAt > 0 && + existingResetAt > 0 && + obsResetAt > existingResetAt + SAME_WINDOW_TOLERANCE_MS; + if (!windowAdvanced && existing && existing.updatedAt > now) { + return existing; + } + const existingActiveUntil = !windowAdvanced && existing && existing.until > now ? existing.until : 0; + + let nextUntil = existingActiveUntil; + if (obsUntil !== undefined && obsUntil > now) { + nextUntil = Math.max(existingActiveUntil, obsUntil); + } else if (windowAdvanced) { + nextUntil = obsUntil && obsUntil > now ? obsUntil : 0; + } else if (obs.remaining !== undefined && obs.remaining > 0 && existingActiveUntil <= now) { + nextUntil = 0; + } + + const remaining = + obs.remaining !== undefined + ? Math.max(0, Math.floor(obs.remaining)) + : !windowAdvanced + ? existing?.remaining + : undefined; + const limit = + obs.limit !== undefined && obs.limit > 0 + ? Math.floor(obs.limit) + : !windowAdvanced + ? existing?.limit + : undefined; + const resetAt = + obsResetAt && obsResetAt > 0 + ? obsResetAt + : !windowAdvanced && existingResetAt > now + ? existingResetAt + : undefined; + + return { + until: nextUntil, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt: now, + }; +} + +function buildSnapshot(existing, obs, ignoreBefore) { + const otherBucket = obs.bucket === 'graphql' ? 'rest' : 'graphql'; + const mergedBuckets = {}; + const existingOther = existing?.buckets?.[otherBucket]; + if (existingOther && existingOther.updatedAt >= ignoreBefore) { + mergedBuckets[otherBucket] = existingOther; + } + const previousBucket = existing?.buckets?.[obs.bucket]; + mergedBuckets[obs.bucket] = mergeBucketState( + previousBucket && previousBucket.updatedAt >= ignoreBefore ? previousBucket : undefined, + obs, + ); + + const graphqlUntil = mergedBuckets.graphql?.until ?? 0; + const topUntil = graphqlUntil > obs.now ? graphqlUntil : 0; + return { + until: topUntil, + ...(topUntil > 0 + ? { + bucket: 'graphql', + reportedAt: + existing?.buckets?.graphql?.until === topUntil + ? existing?.reportedAt ?? obs.now + : obs.now, + reportedBy: 'cindy-desktop', + summary: 'GitHub GraphQL API rate limit reached', + } + : {}), + updatedAt: obs.now, + buckets: mergedBuckets, + }; +} + +export class SharedRateLimitStore { + constructor(options = {}) { + this.stateDir = options.stateDir ?? null; + this.readCacheMs = Math.max(0, options.readCacheMs ?? DEFAULT_SHARED_READ_CACHE_MS); + this.writeThrottleMs = Math.max(0, options.writeThrottleMs ?? DEFAULT_SHARED_WRITE_THROTTLE_MS); + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.inFlightRead = null; + this.writeQueue = Promise.resolve(); + this.ignoreBefore = 0; + this.generation = 0; + this.lastWritten = new Map(); + } + + isCacheFresh(now) { + return now - this.lastReadAt < this.readCacheMs; + } + + readCached(now) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (now - this.lastReadAt >= this.readCacheMs && !this.inFlightRead) { + void this.refresh(now).catch(() => undefined); + } + return this.cachedSnapshot; + } + + async refresh(now, force = false) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (!force && now - this.lastReadAt < this.readCacheMs) { + return this.cachedSnapshot; + } + if (this.inFlightRead) return this.inFlightRead; + const readGeneration = this.generation; + const op = readRateLimitFile(filePath, now) + .then((snap) => { + if (readGeneration !== this.generation) return null; + this.cachedSnapshot = snap; + this.lastReadAt = now; + return snap; + }) + .finally(() => { + if (this.inFlightRead === op) this.inFlightRead = null; + }); + this.inFlightRead = op; + return op; + } + + _shouldWrite(obs) { + if (obs.immediate) return true; + const prev = this.lastWritten.get(obs.bucket); + if (!prev) return true; + const elapsed = obs.now - prev.at; + const windowChanged = + obs.resetAt !== undefined && + prev.resetAt !== undefined && + Math.abs(obs.resetAt - prev.resetAt) > SAME_WINDOW_TOLERANCE_MS; + if (windowChanged) return true; + if ( + obs.remaining !== undefined && + prev.remaining !== undefined && + elapsed >= SIGNIFICANT_DROP_MIN_INTERVAL_MS + ) { + const dropThreshold = Math.max(100, Math.floor((obs.limit ?? 5000) * 0.05)); + if (prev.remaining - obs.remaining >= dropThreshold) return true; + } + if (elapsed >= this.writeThrottleMs && (obs.remaining !== prev.remaining || obs.resetAt !== prev.resetAt)) { + return true; + } + return false; + } + + record(obs) { + const nextInMemory = buildSnapshot(this.cachedSnapshot, obs, this.ignoreBefore); + this.cachedSnapshot = nextInMemory; + this.lastReadAt = obs.now; + + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath || !this._shouldWrite(obs)) return Promise.resolve(); + + this.lastWritten.set(obs.bucket, { + at: obs.now, + remaining: obs.remaining, + resetAt: obs.resetAt, + until: obs.until ?? 0, + }); + + const writeGeneration = this.generation; + const ignoreBefore = this.ignoreBefore; + const run = async () => { + if (writeGeneration !== this.generation) return; + const dir = path.dirname(filePath); + await fs.mkdir(dir, { recursive: true, mode: 0o700 }); + await fs.chmod(dir, 0o700).catch(() => undefined); + const existing = await readRateLimitFile(filePath, obs.now); + if (writeGeneration !== this.generation) return; + const snapshot = buildSnapshot(existing, obs, ignoreBefore); + await writeRateLimitFileAtomic(filePath, snapshot); + if (writeGeneration !== this.generation) return; + if (obs.now >= this.lastReadAt) { + this.cachedSnapshot = snapshot; + this.lastReadAt = obs.now; + } + }; + + this.writeQueue = this.writeQueue.then(run).catch(() => undefined); + return this.writeQueue; + } + + flush() { + return this.writeQueue; + } + + getBucket(bucket, now) { + const snap = this.readCached(now); + const entry = snap?.buckets?.[bucket]; + if (!entry) return undefined; + if (this.ignoreBefore > 0 && entry.updatedAt < this.ignoreBefore) return undefined; + return entry; + } + + isRateLimited(bucket, now) { + const entry = this.getBucket(bucket, now); + return Boolean(entry && entry.until > now); + } + + getPressure(bucket, now) { + const entry = this.getBucket(bucket, now); + if (this.isRateLimited(bucket, now)) { + return { + level: 'exhausted', + ...(entry?.remaining !== undefined ? { remaining: entry.remaining } : {}), + ...(entry?.limit !== undefined ? { limit: entry.limit } : {}), + ...(entry?.resetAt !== undefined ? { resetAt: entry.resetAt } : entry?.until ? { resetAt: entry.until } : {}), + }; + } + if ( + !entry || + entry.remaining === undefined || + entry.limit === undefined || + (entry.resetAt !== undefined && entry.resetAt <= now) + ) { + return { level: 'normal' }; + } + return { + level: classifyQuotaPressure(entry.remaining, entry.limit), + remaining: entry.remaining, + limit: entry.limit, + ...(entry.resetAt !== undefined ? { resetAt: entry.resetAt } : {}), + }; + } + + /** Baseline: does not proactively route away from GraphQL to REST ETag. */ + shouldPreferRest(_now) { + return false; + } + + clearMemoryCache(invalidatedAt) { + this.ignoreBefore = invalidatedAt; + this.generation += 1; + this.inFlightRead = null; + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.lastWritten.clear(); + } + + clearOnAccountSwitch(invalidatedAt) { + this.clearMemoryCache(invalidatedAt); + } +} + +export function createSharedRateLimitStore(options = {}) { + return new SharedRateLimitStore(options); +} diff --git a/questions/perf-github-api-budget/v1/candidate/tests/smoke.test.mjs b/questions/perf-github-api-budget/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..6e165e1 --- /dev/null +++ b/questions/perf-github-api-budget/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,130 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch, computeDeferredBackoffMs } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore, parseSharedRateLimitPayload } from '../src/shared-rate-limit.mjs'; + +function makeClock(start = 1_760_000_000_000) { + let t = start; + return { + now: () => t, + advance: (ms) => { + t += ms; + }, + }; +} + +test('PrStatusService fetches statuses, penetrates cache on refresh:true, and short-circuits 401', async () => { + const clock = makeClock(); + let calls = 0; + let restCalls = 0; + let title = 'Initial title'; + const gateway = { + async graphqlSingle(q) { + calls += 1; + if (q.prNumber === 401) { + const err = new Error('Unauthorized'); + err.status = 401; + throw err; + } + return { + remote: { + state: 'merged', + merged: true, + merged_at: new Date(clock.now() - 10_000).toISOString(), + head_sha: `sha-${calls}`, + title, + checks: 'success', + }, + }; + }, + async restGetPr() { + restCalls += 1; + throw new Error('should not call REST on 401'); + }, + }; + + const svc = new PrStatusService({ gateway, now: clock.now }); + const q = { owner: 'acme', repo: 'core', prNumber: 1 }; + const [first] = await svc.getStatuses([q]); + assert.equal(first.ok, true); + assert.equal(first.status, 'merged'); + + title = 'Updated after refresh'; + const [refreshed] = await svc.getStatuses([q], { refresh: true }); + assert.equal(refreshed.ok, true); + assert.equal(refreshed.title, 'Updated after refresh'); + + const authResults = await svc.getStatuses([ + { owner: 'acme', repo: 'core', prNumber: 401 }, + { owner: 'acme', repo: 'core', prNumber: 2 }, + ]); + assert.equal(authResults[0].ok, false); + assert.equal(authResults[0].reason, 'gh-not-logged-in'); + assert.equal(authResults[1].ok, false); + assert.equal(authResults[1].reason, 'gh-not-logged-in'); + assert.equal(restCalls, 0); +}); + +test('SharedRateLimitStore persists atomically, supports legacy until, and clears on account switch', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-rl-smoke-')); + try { + const now = 1_760_000_000_000; + const store = createSharedRateLimitStore({ stateDir: dir }); + await store.record({ + bucket: 'graphql', + remaining: 0, + limit: 5000, + resetAt: now + 300_000, + until: now + 300_000, + immediate: true, + now, + }); + await store.flush(); + + const files = await fs.readdir(dir); + assert.deepEqual(files, ['.rate-limit.json']); + const raw = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(raw.until, now + 300_000); + assert.equal(raw.buckets.graphql.remaining, 0); + + const legacy = parseSharedRateLimitPayload({ until: now + 120_000 }, now); + assert.equal(legacy.buckets.graphql.until, now + 120_000); + + store.clearOnAccountSwitch(now + 1000); + assert.equal(store.isRateLimited('graphql', now + 1000), false); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('PrFollowWatch observes changes and computes bounded exponential backoff', async () => { + assert.equal(computeDeferredBackoffMs(1), 60_000); + assert.equal(computeDeferredBackoffMs(2), 120_000); + assert.equal(computeDeferredBackoffMs(5), 15 * 60_000); + + const clock = makeClock(); + const q = { owner: 'acme', repo: 'core', prNumber: 7 }; + const ran = []; + const watch = new PrFollowWatch({ + now: clock.now, + listSchedules: () => [ + { id: 's1', prKey: prStatusKey(q), prQuery: q, targetSessionId: 'sess-1', createdAt: clock.now() - 10_000, active: true, expired: false }, + ], + runSchedule: async (s) => { + ran.push(s.id); + return { deferred: false }; + }, + }); + + const o1 = watch.observe(q, { ok: true, status: 'open', headSha: 'a', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '1' }); + assert.equal(o1.changed, false); + const o2 = watch.observe(q, { ok: true, status: 'open', headSha: 'b', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '2' }); + assert.equal(o2.changed, true); + await watch.triggerPr(q, o2); + assert.deepEqual(ran, ['s1']); +}); diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/CONTRACT.md b/questions/perf-github-api-budget/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..c1fadf6 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,43 @@ +# Product & Protocol Contract + +This contract specifies required public module interfaces, gateway cost semantics, and correctness/safety invariants. Within these invariants, **you are free to design the optimal fetching, caching, conditional-ETag, batching, and polling/deferral strategy** to minimize total billable API quota usage. + +## 1. Shared Rate-Limit Store (`src/shared-rate-limit.mjs`) + +- Exports: `MAX_SHARED_RATE_LIMIT_MS` (`2 * 60 * 60_000`), `DEFAULT_SHARED_READ_CACHE_MS`, `DEFAULT_SHARED_WRITE_THROTTLE_MS`, `classifyQuotaPressure(remaining, limit)`, `parseSharedRateLimitPayload(raw, now)`, `SharedRateLimitStore`, `createSharedRateLimitStore(options)`. +- `options`: `{ stateDir?: string | null, readCacheMs?: number, writeThrottleMs?: number }` (persists to `/.rate-limit.json` when `stateDir` is set; memory-only otherwise). +- Public methods: `isCacheFresh(now)`, `readCached(now)`, `refresh(now, force = false)`, `record(obs)`, `flush()`, `getBucket(bucket, now)`, `getPressure(bucket, now)`, `isRateLimited(bucket, now)`, `shouldPreferRest(now)`, `clearOnAccountSwitch(invalidatedAt)`, `clearMemoryCache(invalidatedAt)`. +- **Persistence & safety invariants**: + - Writes are serialized, written atomically via temp file (`0o600` in `0o700` dir) + `rename`, clean up temp files on error, and never throw. + - **Privacy**: `.rate-limit.json` may contain ONLY numeric quota/reset timestamps and generic labels (`until`, `bucket`, `reportedAt`, `reportedBy`, `summary`, `updatedAt`, `buckets`) — never tokens, usernames, repo names, or raw errors. + - **Legacy compatibility**: `parseSharedRateLimitPayload` clamps `until`/`resetAt` to `<= now + MAX_SHARED_RATE_LIMIT_MS` and maps legacy top-level `until > now` onto `buckets[bucket ?? 'graphql']`. Written top-level `until` is `> 0` ONLY when `graphql` is rate-limited; a REST-only rate limit must keep top-level `until === 0`. + - **Account switch**: `clearOnAccountSwitch(invalidatedAt)` clears memory, advances generation, ignores pre-invalidation entries (`updatedAt < invalidatedAt`) even after `refresh()`, and drops them on subsequent merged disk writes. + - **Cross-process coordination**: Concurrent processes writing `.rate-limit.json` must observe peer rate-limit / critical-pressure updates without losing newer local or peer observations. + +## 2. PR Status Service (`src/pr-status-service.mjs`) + +- Exports: `DEFAULT_OPEN_TTL_MS`, `DEFAULT_MERGED_TTL_MS`, `DEFAULT_CLOSED_TTL_MS`, `DEFAULT_MAX_CACHE_ENTRIES`, `PR_GRAPHQL_BATCH_MAX` (`8`), `prStatusKey(q)`, `PrStatusService`. +- Constructor: `new PrStatusService({ gateway, rateLimitStore?, now?, openTtlMs?, mergedTtlMs?, closedTtlMs?, maxCacheEntries?, scope?, onObserved? })`. +- Public methods: `getStatuses(queries, opts?)`, `getCachedStatus(q)` (zero-network synchronous lookup), `getCacheSize()`, `invalidate(nextScope?)`. +- **Gateway interface & billing model**: + - `gateway.graphqlSingle(q)` → **1 GraphQL pt** (returns `{ remote, headers? }`). + - `gateway.graphqlBatch({ owner, repo, prNumbers })` (`1 <= prNumbers.length <= 8`, same repo) → **1 GraphQL pt total** (returns `{ items, headers? }`). + - `gateway.restGetPr(q, { etag? })` → **`0` pts** on `{ status: 304, notModified: true, etag, headers? }`; **1 REST pt** on `{ status: 200, notModified: false, etag, remote, headers? }`. +- **Correctness & freshness invariants**: + - `opts.refresh === true` always penetrates cache and fetches live remote state (including merged/closed PRs). + - Real PR updates on open PRs (commits, comments, CI status changes) must be observed promptly when polled (2-minute sequential transitions and 6-minute end-to-end delivery SLA). + - If `graphqlBatch` is used and an individual item fails with a non-`notFound` error, fall back ONLY that PR without poisoning valid siblings; clean `notFound` returns `{ ok: false, ..., reason: 'not-found' }` with zero fallback. + - On HTTP `401`, immediately short-circuit and return `{ ok: false, ..., reason: 'gh-not-logged-in' }` for all remaining queries in the call with **zero** fallback or subsequent gateway requests. + - Scope/account change (`invalidate()` or `scope()` changing) clears cached statuses, ETags, and calls `rateLimitStore?.clearOnAccountSwitch(now)`. + - Every gateway response/error with rate-limit headers must update `rateLimitStore` so quota pressure stays accurate across processes. + +## 3. PR Follow Watch (`src/pr-follow-watch.mjs`) + +- Exports: `MIN_RETRIGGER_MS`, `MAX_DEFER_BACKOFF_MS`, `PR_FOLLOW_END_GRACE_MS` (`2 * 60 * 60_000`), `computeDeferredBackoffMs(deferCount)`, `prStatusSignature(result)`, `PrFollowWatch`. +- Constructor: `new PrFollowWatch({ now?, prStatusService?, listSchedules, isSessionBusy?, hasQueuedPrompt?, hasSuccessfulRunSince?, expireSchedule?, runSchedule })`. +- Public methods: `reset()`, `observe(query, result)`, `triggerPr(query, info)`, `handleScheduledTick(schedule)`, `notifySessionIdle(sessionId)`, `tick(now)`. +- **Scheduling & delivery invariants**: + - Deliver 100% of real PR updates (commits, comments, CI transitions, merges, reopens) within the freshness SLA. + - Do not invoke `runSchedule` while `isSessionBusy(sessionId)` or `hasQueuedPrompt(sessionId, scheduleId)` is true; defer with bounded backoff and immediately drain pending wakeups on `notifySessionIdle(sessionId)`. + - Expire settled merged follow schedules via `expireSchedule` with **zero network calls** (using cached merged state): when `createdAt < mergedAt` and either a successful run already happened since `mergedAt` or a recurring follow's merge was observed `>= PR_FOLLOW_END_GRACE_MS` ago. + - Never prematurely expire schedules created at or after `mergedAt`, and ignore pre-creation merge events for them. diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/ENVIRONMENT.md b/questions/perf-github-api-budget/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..df2c3a7 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock (`now()`) and an in-memory mock GitHub gateway — quota points, wasted calls, and rate-limit breaches are exact, hardware-independent integers. +- Public checks: + - `npm test` — functional correctness smoke tests + - `npm run bench` — deterministic 48-hour 50-PR workload benchmark reporting `api_quota_points`, `wasted_busy_merged_calls`, and `rate_limit_breaches` diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/TASK.md b/questions/perf-github-api-budget/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..57b4f63 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/TASK.md @@ -0,0 +1,27 @@ +# Task + +You are optimizing Cindy's GitHub PR status polling, PR-follow scheduling, and cross-process rate-limit coordination pipeline extracted from production desktop operations. + +## Observed Production Symptoms + +1. **Severe GitHub API quota burn & repeated 429 breaches**: Polling 50 tracked PRs across 4 repositories over 48 hours burns >50,000 billable API points and triggers >30,000 HTTP 429 failures. Sibling processes share the same GitHub account quota via `.rate-limit.json`, yet quota pressure is not coordinated effectively across processes or transports. +2. **Wasted pre-run GitHub calls on busy sessions and settled merged PRs**: When a PR changes while its bound session is busy or already has a queued prompt, `PrFollowWatch` keeps firing the runner repeatedly only to defer—and recurring ticks continue polling already-merged PRs long after they have settled. +3. **Small FIFO cache**: The status cache evicts at 200 entries in FIFO order instead of keeping active multi-repo PRs warm. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness, freshness, and safety invariants** defined in `CONTRACT.md`: + - Every real PR update (new commit, review/comment change, CI status transition, merge, reopen) must be detected and delivered promptly (within the freshness SLA; zero missed updates). + - Explicit `refresh: true` must always penetrate the cache (including merged PRs). + - Single-PR errors must not poison sibling PRs, clean 404s must not waste fallbacks, and HTTP 401 must immediately short-circuit with zero extra calls. + - Account switches must clear cached PR statuses, ETags, and stale rate-limit buckets. + - Cross-process rate-limit persistence must remain atomic, privacy-safe, and backward-compatible with legacy top-level `until` files. +- **Open-ended optimization goal**: You are free to choose the most effective transport selection (GraphQL batching vs conditional REST `ETag` / `304 Not Modified`), caching, invalidation, backoff, and scheduling strategy across `src/` to drive all three 48-hour simulation metrics as low as possible: + - `api_quota_points` (total billable API points — lower is better; `304 Not Modified` costs `0` points!) + - `wasted_busy_merged_calls` (calls wasted on busy/queued sessions or settled merged PRs — drive to `0`) + - `rate_limit_breaches` (429/exhausted failures — drive to `0`) +- Run `npm test` and `npm run bench` to verify correctness and compare before/after numbers. +- Record your analysis, design trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/bench/workload.mjs b/questions/perf-github-api-budget/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..7c29d79 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,626 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore } from '../src/shared-rate-limit.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const T0 = 1_760_000_000_000; +const SIM_MINUTES = 48 * 60; // 48 hours +const GQL_HOURLY_LIMIT = 500; +const REST_HOURLY_LIMIT = 1000; + +export function createDeterministicGateway(clock) { + const prs = new Map(); + let gqlRemaining = GQL_HOURLY_LIMIT; + let restRemaining = REST_HOURLY_LIMIT; + let windowResetAt = clock.now() + HOUR; + + const stats = { + graphqlCalls: 0, + graphqlPoints: 0, + rest200Calls: 0, + rest304Calls: 0, + rateLimitBreaches: 0, + wastedBusyCalls: 0, + wastedMergedCalls: 0, + }; + + function syncWindow() { + const now = clock.now(); + if (now >= windowResetAt) { + const hoursElapsed = Math.floor((now - windowResetAt) / HOUR) + 1; + windowResetAt += hoursElapsed * HOUR; + gqlRemaining = GQL_HOURLY_LIMIT; + restRemaining = REST_HOURLY_LIMIT; + } + } + + function makeHeaders(resource, remaining, limit) { + return { + 'x-ratelimit-resource': resource, + 'x-ratelimit-remaining': String(remaining), + 'x-ratelimit-limit': String(limit), + 'x-ratelimit-reset': String(Math.floor(windowResetAt / 1000)), + }; + } + + function rateLimitError(resource, remaining, limit) { + const err = new Error('GITHUB_RATE_LIMITED'); + err.status = 429; + err.code = 'GITHUB_RATE_LIMITED'; + err.headers = makeHeaders(resource, remaining, limit); + return err; + } + + function setPr(q, remote) { + const key = prStatusKey(q); + const prev = prs.get(key); + const version = (prev?.version ?? 0) + 1; + prs.set(key, { + q, + remote: { ...remote }, + version, + etag: `"v${version}-${remote.state}-${remote.head_sha}"`, + }); + } + + function updatePr(q, patch) { + const key = prStatusKey(q); + const cur = prs.get(key); + if (!cur) throw new Error(`Unknown PR ${key}`); + setPr(q, { ...cur.remote, ...patch }); + } + + function consumeExternalGraphql(targetRemaining) { + syncWindow(); + gqlRemaining = Math.max(0, Math.min(gqlRemaining, targetRemaining)); + return { remaining: gqlRemaining, limit: GQL_HOURLY_LIMIT, resetAt: windowResetAt }; + } + + const gateway = { + async graphqlSingle(q) { + syncWindow(); + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const entry = prs.get(prStatusKey(q)); + return { + remote: entry ? { ...entry.remote } : null, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async graphqlBatch({ owner, repo, prNumbers }) { + syncWindow(); + if (!Array.isArray(prNumbers) || prNumbers.length === 0 || prNumbers.length > 8) { + const err = new Error('Invalid batch size (must be 1..8)'); + err.status = 400; + throw err; + } + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const items = {}; + for (const prNumber of prNumbers) { + const entry = prs.get(prStatusKey({ owner, repo, prNumber })); + if (!entry) { + items[prNumber] = { ok: false, notFound: true }; + } else { + items[prNumber] = { ok: true, remote: { ...entry.remote } }; + } + } + return { + items, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async restGetPr(q, opts = {}) { + syncWindow(); + const entry = prs.get(prStatusKey(q)); + if (!entry) { + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + const err = new Error('NOT_FOUND'); + err.status = 404; + err.headers = makeHeaders('core', restRemaining, REST_HOURLY_LIMIT); + throw err; + } + if (opts?.etag && opts.etag === entry.etag) { + // Conditional GET 304 Not Modified costs 0 billable REST quota points. + stats.rest304Calls += 1; + return { + status: 304, + notModified: true, + etag: entry.etag, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + } + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + return { + status: 200, + notModified: false, + etag: entry.etag, + remote: { ...entry.remote }, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + }, + }; + + return { gateway, stats, setPr, updatePr, consumeExternalGraphql }; +} + +export async function runSimulation() { + let currentTime = T0; + const clock = { + now: () => currentTime, + set: (t) => { + currentTime = t; + }, + }; + + const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-gh-budget-bench-')); + try { + const rateLimitStore = createSharedRateLimitStore({ + stateDir, + writeThrottleMs: 30 * MINUTE, + }); + const sim = createDeterministicGateway(clock); + + const repoSpec = [ + { owner: 'acme', repo: 'core', baseNum: 100, count: 16 }, + { owner: 'acme', repo: 'desktop', baseNum: 200, count: 14 }, + { owner: 'acme', repo: 'web', baseNum: 300, count: 12 }, + { owner: 'acme', repo: 'cli', baseNum: 400, count: 8 }, + ]; + + const allQueries = []; + for (const r of repoSpec) { + for (let i = 1; i <= r.count; i += 1) { + allQueries.push({ owner: r.owner, repo: r.repo, prNumber: r.baseNum + i }); + } + } + + // Partition 50 PRs: + // 0..14 (15): pre-merged with completed post-merge run + // 15..16 (2): pre-merged with no post-merge run (tests 2h grace-window convergence) + // 17..21 (5): open at T0, merge during hours 2..20 + // 22..27 (6): pre-closed (unmerged); #22 reopens at hour 24 via refresh:true + // 28..29 (2): open at T0, close at hours 8 & 16 + // 30..49 (20): active open PRs throughout 48h + const schedules = new Map(); + const successfulRuns = new Map(); // scheduleId -> number[] + const busySessions = new Set(); + const queuedPrompts = new Set(); // `${sessionId}:${scheduleId}` + const mergedObservedAt = new Map(); // key -> ms + const deliveredEvents = new Map(); // `${key}#${eventId}` -> true + const expectedUpdates = []; + + for (let idx = 0; idx < allQueries.length; idx += 1) { + const q = allQueries[idx]; + const key = prStatusKey(q); + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + const scheduleId = `sched-${idx + 1}`; + + if (idx < 15) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-m-${idx}`, + title: `Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, [T0 - 2 * HOUR - 50 * MINUTE]); + } else if (idx < 17) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-mg-${idx}`, + title: `Grace Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + graceOnlyFail: true, + }); + successfulRuns.set(scheduleId, []); + } else if (idx >= 22 && idx < 28) { + sim.setPr(q, { + state: 'closed', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 4 * HOUR).toISOString(), + head_sha: `sha-c-${idx}`, + title: `Closed PR ${idx}`, + checks: 'failure', + unresolved_count: 0, + review_decision: null, + }); + if (idx === 22) { + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } else { + sim.setPr(q, { + state: 'open', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 30 * MINUTE).toISOString(), + head_sha: `sha-open-${idx}-0`, + title: `Open PR ${idx}`, + checks: 'pending', + unresolved_count: 0, + review_decision: null, + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 1 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } + + const prStatusService = new PrStatusService({ + gateway: sim.gateway, + rateLimitStore, + now: clock.now, + }); + + // Latest expected event marker per PR so we verify real updates are delivered. + const latestPrEventId = new Map(); + + const watch = new PrFollowWatch({ + now: clock.now, + prStatusService, + listSchedules: () => Array.from(schedules.values()), + isSessionBusy: (sessionId) => busySessions.has(sessionId), + hasQueuedPrompt: (sessionId, scheduleId) => queuedPrompts.has(`${sessionId}:${scheduleId}`), + hasSuccessfulRunSince: (scheduleId, sinceMs) => + (successfulRuns.get(scheduleId) ?? []).some((ts) => ts >= sinceMs), + expireSchedule: (scheduleId) => { + const s = schedules.get(scheduleId); + if (s) s.expired = true; + }, + runSchedule: async (schedule, info = {}) => { + // Runner preRunHook fetches fresh PR status from GitHub before checking session/merged state. + const [fresh] = await prStatusService.getStatuses([schedule.prQuery], { refresh: true }); + const now = clock.now(); + const isBusy = busySessions.has(schedule.targetSessionId); + const isQueued = queuedPrompts.has(`${schedule.targetSessionId}:${schedule.id}`); + if (isBusy || isQueued) { + sim.stats.wastedBusyCalls += 1; + return { deferred: true, reason: isQueued ? 'already-queued' : 'session-running' }; + } + if (fresh?.ok && fresh.status === 'merged' && fresh.mergedAt != null && schedule.createdAt < fresh.mergedAt) { + const alreadyRan = (successfulRuns.get(schedule.id) ?? []).some((ts) => ts >= fresh.mergedAt); + const obsAt = mergedObservedAt.get(schedule.prKey); + const pastGrace = + info.changeKind !== 'merged' && obsAt !== undefined && now - obsAt >= 2 * HOUR; + if (alreadyRan || pastGrace) { + sim.stats.wastedMergedCalls += 1; + return { deferred: false }; + } + if (schedule.graceOnlyFail) { + // Simulate a failed post-merge run so grace-window expiry is exercised. + return { deferred: false, failed: true }; + } + successfulRuns.get(schedule.id).push(now); + } + const evId = latestPrEventId.get(schedule.prKey); + if (evId) deliveredEvents.set(`${schedule.prKey}#${evId}`, true); + return { deferred: false }; + }, + }); + + // Build deterministic event timeline across 48 hours. + const prEventsByMinute = new Map(); + const addPrEvent = (minute, ev) => { + const list = prEventsByMinute.get(minute) ?? []; + list.push(ev); + prEventsByMinute.set(minute, list); + }; + + // 5 open PRs (17..21) merge at hours 2, 5, 9, 14, 20. + const mergeHours = [2, 5, 9, 14, 20]; + for (let i = 0; i < mergeHours.length; i += 1) { + const idx = 17 + i; + const m = mergeHours[i] * 60 + 4; + const evId = `merge-${idx}`; + addPrEvent(m, { + idx, + evId, + kind: 'merge', + patch: (now) => ({ + state: 'merged', + merged: true, + merged_at: new Date(now).toISOString(), + updated_at: new Date(now).toISOString(), + checks: 'success', + review_decision: 'APPROVED', + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // 2 open PRs (28, 29) close at hours 8 and 16. + addPrEvent(8 * 60 + 7, { + idx: 28, + evId: 'close-28', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + addPrEvent(16 * 60 + 7, { + idx: 29, + evId: 'close-29', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + + // Closed PR #22 reopens at hour 24 via explicit webhook refresh. + addPrEvent(24 * 60 + 5, { + idx: 22, + evId: 'reopen-22', + kind: 'reopen-webhook', + webhookRefresh: true, + patch: (now) => ({ + state: 'open', + merged: false, + head_sha: 'sha-reopen-22', + checks: 'pending', + updated_at: new Date(now).toISOString(), + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[22])}#reopen-22`); + + // 60 real updates (commits, comments/reviews, CI checks) on the 20 active open PRs (30..49). + for (let step = 0; step < 60; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; // spaced every 45 minutes across 48h + if (minute >= SIM_MINUTES - 60) continue; + const evId = `upd-${step}`; + const mod = step % 3; + addPrEvent(minute, { + idx, + evId, + kind: mod === 0 ? 'commit' : mod === 1 ? 'comment' : 'ci', + patch: (now) => { + if (mod === 0) { + return { head_sha: `sha-open-${idx}-${step + 1}`, checks: 'pending', updated_at: new Date(now).toISOString() }; + } + if (mod === 1) { + return { unresolved_count: (step % 4) + 1, review_decision: 'CHANGES_REQUESTED', updated_at: new Date(now).toISOString() }; + } + return { checks: step % 2 === 0 ? 'success' : 'failure', updated_at: new Date(now).toISOString() }; + }, + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // Busy session windows overlapping ~35 of those updates + merge #18 (at hour 5). + const busyWindows = []; + for (let step = 0; step < 36; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + if (step % 2 === 0) { + busyWindows.push({ start: minute - 2, end: minute + 28, sessionId, queuedScheduleId: null }); + } else { + busyWindows.push({ start: minute - 1, end: minute + 20, sessionId, queuedScheduleId: `sched-${idx + 1}` }); + } + } + // Also overlap merge of PR #18 (hour 5 = minute 304) with busy session. + busyWindows.push({ + start: 300, + end: 325, + sessionId: `session-${String((18 % 20) + 1).padStart(2, '0')}`, + queuedScheduleId: null, + }); + + const peakExternalHours = new Map([ + [4, 0], // exhausted + [12, 20], // critical (<= 50) + [20, 0], // exhausted + [28, 20], // critical + [36, 0], // exhausted + [44, 20], // critical + ]); + + // Step through 48 hours minute by minute. + for (let m = 0; m < SIM_MINUTES; m += 1) { + clock.set(T0 + m * MINUTE); + const now = clock.now(); + + // 1. Update busy/queued session states and notify idle transitions. + const prevBusy = new Set(busySessions); + const prevQueued = new Set(queuedPrompts); + busySessions.clear(); + queuedPrompts.clear(); + for (const w of busyWindows) { + if (m >= w.start && m < w.end) { + if (w.queuedScheduleId) queuedPrompts.add(`${w.sessionId}:${w.queuedScheduleId}`); + else busySessions.add(w.sessionId); + } + } + const becameIdle = new Set(); + for (const s of prevBusy) if (!busySessions.has(s)) becameIdle.add(s); + for (const qk of prevQueued) { + if (!queuedPrompts.has(qk)) becameIdle.add(qk.split(':')[0]); + } + for (const sessionId of becameIdle) { + await watch.notifySessionIdle(sessionId); + } + + // 2. Simulate external sibling process writing shared .rate-limit.json during peak hours. + if (m % 60 === 2) { + const hour = Math.floor(m / 60); + if (peakExternalHours.has(hour)) { + await rateLimitStore.flush(); + const targetRem = peakExternalHours.get(hour); + const ext = sim.consumeExternalGraphql(targetRem); + const peerStore = createSharedRateLimitStore({ stateDir }); + await peerStore.record({ + bucket: 'graphql', + remaining: ext.remaining, + limit: ext.limit, + resetAt: ext.resetAt, + ...(ext.remaining === 0 ? { until: ext.resetAt } : {}), + immediate: true, + now, + }); + await peerStore.flush(); + } + } + + // 3. Apply scheduled PR mutations. + const events = prEventsByMinute.get(m); + if (events) { + for (const ev of events) { + const q = allQueries[ev.idx]; + const key = prStatusKey(q); + sim.updatePr(q, ev.patch(now)); + latestPrEventId.set(key, ev.evId); + if (ev.webhookRefresh) { + const [res] = await prStatusService.getStatuses([q], { refresh: true }); + const obs = watch.observe(q, res); + if (obs.changed) await watch.triggerPr(q, obs); + } + } + } + + // 4. Periodic workspace PR status polling (every 3 minutes across all 50 PRs). + if (m % 3 === 0) { + const results = await prStatusService.getStatuses(allQueries); + for (let i = 0; i < allQueries.length; i += 1) { + const q = allQueries[i]; + const res = results[i]; + if (res?.ok && res.status === 'merged' && !mergedObservedAt.has(prStatusKey(q))) { + mergedObservedAt.set(prStatusKey(q), now); + } + const obs = watch.observe(q, res); + if (obs.changed) { + await watch.triggerPr(q, obs); + } + } + } + + // 5. Explicit user refresh on merged PRs at hours 12 and 36. + if (m === 12 * 60 + 10 || m === 36 * 60 + 10) { + await prStatusService.getStatuses([allQueries[0]], { refresh: true }); + } + + // 6. Recurring PR-follow cron ticks every 20 minutes on merged schedules (0..21). + if (m > 0 && m % 20 === 0) { + for (let idx = 0; idx <= 21; idx += 1) { + const schedule = schedules.get(`sched-${idx + 1}`); + if (schedule && schedule.active && !schedule.expired) { + const st = prStatusService.getCachedStatus(schedule.prQuery); + if (st?.ok && st.status === 'merged') { + await watch.handleScheduledTick(schedule); + } + } + } + } + + // 7. Drain due pending follow wakeups. + await watch.tick(now); + } + + await rateLimitStore.flush(); + const missedUpdates = expectedUpdates.filter((id) => !deliveredEvents.has(id)); + const api_quota_points = sim.stats.graphqlPoints + sim.stats.rest200Calls; + const wasted_busy_merged_calls = sim.stats.wastedBusyCalls + sim.stats.wastedMergedCalls; + const rate_limit_breaches = sim.stats.rateLimitBreaches; + + return { + api_quota_points, + wasted_busy_merged_calls, + rate_limit_breaches, + breakdown: { ...sim.stats }, + expectedUpdateCount: expectedUpdates.length, + missedUpdateCount: missedUpdates.length, + missedUpdates, + }; + } finally { + await fs.rm(stateDir, { recursive: true, force: true }); + } +} + +if (isMainModule()) { + const result = await runSimulation(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/package.json b/questions/perf-github-api-budget/v1/controls/incomplete/package.json new file mode 100644 index 0000000..c301e7f --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-github-api-budget", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-follow-watch.mjs b/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-follow-watch.mjs new file mode 100644 index 0000000..0e6a89e --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-follow-watch.mjs @@ -0,0 +1,113 @@ +import { prStatusKey } from './pr-status-service.mjs'; + +export const MIN_RETRIGGER_MS = 60_000; +export const MAX_DEFER_BACKOFF_MS = 15 * 60_000; +export const PR_FOLLOW_END_GRACE_MS = 2 * 60 * 60_000; + +export function computeDeferredBackoffMs(deferCount) { + if (deferCount <= 1) return MIN_RETRIGGER_MS; + return Math.min(MAX_DEFER_BACKOFF_MS, MIN_RETRIGGER_MS * 2 ** (deferCount - 1)); +} + +export function prStatusSignature(result) { + if (!result?.ok) return null; + return [ + result.status ?? '', + result.headSha ?? '', + result.checks ?? '', + String(result.unresolvedCount ?? 0), + result.reviewDecision ?? '', + result.updatedAt ?? '', + ].join('|'); +} + +export class PrFollowWatch { + constructor(deps) { + this.deps = deps; + this.now = deps.now ?? Date.now; + this.signatures = new Map(); + this.pending = new Map(); + } + + reset() { + this.signatures.clear(); + this.pending.clear(); + } + + observe(query, result) { + const fresh = prStatusSignature(result); + if (fresh === null) return { changed: false, changeKind: null }; + const key = prStatusKey(query); + const previous = this.signatures.get(key); + this.signatures.set(key, fresh); + if (previous === undefined || previous === fresh) { + return { changed: false, changeKind: null }; + } + const prevStatus = previous.split('|')[0]; + const changeKind = + result.status === 'merged' && prevStatus !== 'merged' + ? 'merged' + : result.status === 'open' && prevStatus === 'closed' + ? 'reopened' + : 'update'; + return { + changed: true, + changeKind, + ...(result.status === 'merged' && result.mergedAt != null ? { mergedAt: result.mergedAt } : {}), + }; + } + + async triggerPr(query, info = {}) { + const key = prStatusKey(query); + const schedules = (await this.deps.listSchedules()).filter( + (s) => s.active && !s.expired && s.prKey === key, + ); + for (const schedule of schedules) { + await this._dispatchSchedule(schedule, info); + } + } + + async handleScheduledTick(schedule) { + if (!schedule.active || schedule.expired) return { status: 'skipped' }; + // Baseline: no zero-network merged expiry, no busy/queued short-circuit before running preRunHook. + return this._dispatchSchedule(schedule, { changeKind: 'scheduled-tick' }); + } + + async _dispatchSchedule(schedule, info) { + const now = this.now(); + this.pending.delete(schedule.id); + const outcome = await this.deps.runSchedule(schedule, info); + if (outcome?.deferred) { + // Baseline: flat 1-minute retry loop with no exponential backoff. + this.pending.set(schedule.id, { + schedule, + info, + notBefore: now + MIN_RETRIGGER_MS, + }); + return { status: 'deferred' }; + } + return { status: 'ran' }; + } + + async notifySessionIdle(_sessionId) { + // Baseline: does not wake deferred schedules early on session idle. + } + + async tick(now = this.now()) { + const due = []; + for (const [id, entry] of this.pending.entries()) { + if (entry.notBefore <= now) { + due.push([id, entry]); + } + } + for (const [id, entry] of due) { + if (!this.pending.has(id)) continue; + const latest = (await this.deps.listSchedules()).find((s) => s.id === id); + if (!latest || !latest.active || latest.expired) { + this.pending.delete(id); + continue; + } + await this._dispatchSchedule(latest, entry.info); + } + } +} diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-status-service.mjs b/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-status-service.mjs new file mode 100644 index 0000000..9036711 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/src/pr-status-service.mjs @@ -0,0 +1,192 @@ +export const DEFAULT_OPEN_TTL_MS = 60_000; +export const DEFAULT_MERGED_TTL_MS = 24 * 60 * 60_000; +export const DEFAULT_CLOSED_TTL_MS = 30 * 60_000; +export const DEFAULT_MAX_CACHE_ENTRIES = 200; +export const PR_GRAPHQL_BATCH_MAX = 8; + +export function prStatusKey(q) { + return `${q.owner.toLowerCase()}/${q.repo.toLowerCase()}#${q.prNumber}`; +} + +function mapRemoteStatus(remote) { + if (remote.merged || remote.state === 'merged' || remote.state === 'MERGED') return 'merged'; + if (remote.state === 'closed' || remote.state === 'CLOSED') return 'closed'; + return 'open'; +} + +export class PrStatusService { + constructor(deps) { + this.deps = deps; + this.gateway = deps.gateway; + this.rateLimitStore = deps.rateLimitStore ?? null; + this.now = deps.now ?? Date.now; + this.openTtlMs = deps.openTtlMs ?? DEFAULT_OPEN_TTL_MS; + this.mergedTtlMs = Math.max(this.openTtlMs, deps.mergedTtlMs ?? DEFAULT_MERGED_TTL_MS); + this.closedTtlMs = Math.max(this.openTtlMs, deps.closedTtlMs ?? DEFAULT_CLOSED_TTL_MS); + this.maxCacheEntries = Math.max(1, Math.floor(deps.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES)); + this.cache = new Map(); + this.scope = null; + this.generation = 0; + } + + getCacheSize() { + return this.cache.size; + } + + getCachedStatus(q) { + return this.cache.get(prStatusKey(q))?.result; + } + + invalidate(nextScope = this.scope) { + this.generation += 1; + this.scope = nextScope; + this.cache.clear(); + this.rateLimitStore?.clearOnAccountSwitch(this.now()); + } + + _buildOkResult(q, remote) { + const status = mapRemoteStatus(remote); + const mergedAt = + remote.merged_at !== undefined && remote.merged_at !== null + ? typeof remote.merged_at === 'number' + ? remote.merged_at + : Date.parse(remote.merged_at) + : null; + return { + ok: true, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + status, + headSha: remote.head_sha ?? '', + title: remote.title ?? '', + checks: remote.checks ?? 'pending', + unresolvedCount: remote.unresolved_count ?? 0, + reviewDecision: remote.review_decision ?? null, + updatedAt: remote.updated_at ?? '', + mergedAt: Number.isFinite(mergedAt) ? mergedAt : null, + observedAt: this.now(), + }; + } + + _commitCachedResult(key, q, result) { + const fetchedAt = this.now(); + // Incomplete control: adds merged 24h TTL caching ONLY (no closed TTL, no GraphQL batching, no REST ETag fallback). + const ttl = result.ok && result.status === 'merged' ? this.mergedTtlMs : this.openTtlMs; + if (this.cache.size >= this.maxCacheEntries && !this.cache.has(key)) { + this.cache.delete(this.cache.keys().next().value); + } + this.cache.set(key, { + result, + fetchedAt, + expiresAt: fetchedAt + ttl, + }); + try { + this.deps.onObserved?.(q, result); + } catch { + // Observers are best-effort. + } + } + + async _checkScope() { + if (!this.deps.scope) return; + const nextScope = await this.deps.scope(); + if (this.scope === null) { + this.scope = nextScope; + return; + } + if (nextScope !== this.scope) { + this.invalidate(nextScope); + } + } + + async _fetchOne(q) { + try { + const res = await this.gateway.graphqlSingle(q); + if (!res?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + return this._buildOkResult(q, res.remote); + } catch (err) { + const status = err?.status; + if (status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + try { + const rest = await this.gateway.restGetPr(q, {}); + if (!rest?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + return this._buildOkResult(q, rest.remote); + } catch (restErr) { + if (restErr?.status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (restErr?.status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + if (restErr?.status === 429 || restErr?.code === 'GITHUB_RATE_LIMITED') { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'rate-limited' }; + } + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'fetch-failed' }; + } + } + } + + async getStatuses(queries, opts = {}) { + await this._checkScope(); + const generation = this.generation; + const refresh = opts.refresh === true; + const results = new Array(queries.length); + let aborted401 = false; + + for (let i = 0; i < queries.length; i += 1) { + const q = queries[i]; + const key = prStatusKey(q); + if (aborted401) { + results[i] = { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'gh-not-logged-in' }; + continue; + } + const now = this.now(); + const cached = this.cache.get(key); + if (!refresh && cached && cached.expiresAt > now) { + results[i] = cached.result; + continue; + } + const fetched = await this._fetchOne(q); + if (generation !== this.generation) { + results[i] = { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'gh-not-logged-in' }; + continue; + } + if (fetched._shortCircuit401) { + aborted401 = true; + const { _shortCircuit401: _, ...clean } = fetched; + results[i] = clean; + continue; + } + if (fetched.ok || fetched.reason === 'not-found') { + this._commitCachedResult(key, q, fetched); + } + results[i] = fetched; + } + + return results; + } +} diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/src/shared-rate-limit.mjs b/questions/perf-github-api-budget/v1/controls/incomplete/src/shared-rate-limit.mjs new file mode 100644 index 0000000..df50015 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/src/shared-rate-limit.mjs @@ -0,0 +1,387 @@ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export const MAX_SHARED_RATE_LIMIT_MS = 2 * 60 * 60_000; +export const DEFAULT_SHARED_READ_CACHE_MS = 5_000; +export const DEFAULT_SHARED_WRITE_THROTTLE_MS = 30_000; +const SIGNIFICANT_DROP_MIN_INTERVAL_MS = 5_000; +const SAME_WINDOW_TOLERANCE_MS = 60_000; +const RATE_LIMIT_FILENAME = '.rate-limit.json'; + +export function classifyQuotaPressure(remaining, limit) { + if (remaining === 0) return 'exhausted'; + if (remaining <= Math.max(50, Math.floor(limit * 0.05))) return 'critical'; + if (remaining <= Math.max(200, Math.floor(limit * 0.2))) return 'low'; + return 'normal'; +} + +function resolveRateLimitFilePath(configuredDir) { + if (configuredDir === null || configuredDir === undefined) return null; + if (typeof configuredDir === 'string') { + const trimmed = configuredDir.trim(); + return trimmed ? path.join(trimmed, RATE_LIMIT_FILENAME) : null; + } + return null; +} + +function clampTimestampMs(value, now) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return 0; + return Math.min(Math.floor(num), now + MAX_SHARED_RATE_LIMIT_MS); +} + +function parseNonNegativeInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num < 0) return undefined; + return Math.floor(num); +} + +function parsePositiveInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return undefined; + return Math.floor(num); +} + +function parseBucketState(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined; + const until = clampTimestampMs(raw.until, now); + const remaining = parseNonNegativeInt(raw.remaining); + const limit = parsePositiveInt(raw.limit); + const resetAt = clampTimestampMs(raw.resetAt, now) || undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? 0; + if (until === 0 && remaining === undefined && limit === undefined && resetAt === undefined) { + return undefined; + } + return { + until, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt, + }; +} + +export function parseSharedRateLimitPayload(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const topUntil = clampTimestampMs(raw.until, now); + const topBucket = raw.bucket === 'graphql' || raw.bucket === 'rest' ? raw.bucket : undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? parseNonNegativeInt(raw.reportedAt) ?? 0; + const reportedAt = parseNonNegativeInt(raw.reportedAt); + + const buckets = {}; + if (raw.buckets && typeof raw.buckets === 'object' && !Array.isArray(raw.buckets)) { + const gql = parseBucketState(raw.buckets.graphql, now); + const rest = parseBucketState(raw.buckets.rest, now); + if (gql) buckets.graphql = gql; + if (rest) buckets.rest = rest; + } + + if (topUntil > now) { + const targetBucket = topBucket ?? 'graphql'; + const existing = buckets[targetBucket]; + if (!existing || topUntil > existing.until) { + buckets[targetBucket] = { + ...existing, + until: topUntil, + updatedAt: Math.max(existing?.updatedAt ?? 0, updatedAt), + }; + } + } + + if (topUntil === 0 && !buckets.graphql && !buckets.rest) return null; + + return { + until: topUntil, + ...(topBucket ? { bucket: topBucket } : {}), + ...(reportedAt !== undefined ? { reportedAt } : {}), + updatedAt, + buckets, + }; +} + +async function readRateLimitFile(filePath, now) { + try { + const text = await fs.readFile(filePath, 'utf8'); + return parseSharedRateLimitPayload(JSON.parse(text), now); + } catch { + return null; + } +} + +async function writeRateLimitFileAtomic(filePath, payload) { + const dir = path.dirname(filePath); + const tmpFile = path.join( + dir, + `${RATE_LIMIT_FILENAME}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`, + ); + try { + const content = `${JSON.stringify(payload, null, 2)}\n`; + await fs.writeFile(tmpFile, content, { encoding: 'utf8', mode: 0o600 }); + await fs.chmod(tmpFile, 0o600).catch(() => undefined); + await fs.rename(tmpFile, filePath); + } catch { + await fs.unlink(tmpFile).catch(() => undefined); + } +} + +function mergeBucketState(existing, obs) { + const now = obs.now; + const obsUntil = obs.until !== undefined ? clampTimestampMs(obs.until, now) : undefined; + const obsResetAt = obs.resetAt !== undefined ? clampTimestampMs(obs.resetAt, now) : undefined; + const existingResetAt = existing?.resetAt ?? 0; + const windowAdvanced = + obsResetAt !== undefined && + obsResetAt > 0 && + existingResetAt > 0 && + obsResetAt > existingResetAt + SAME_WINDOW_TOLERANCE_MS; + if (!windowAdvanced && existing && existing.updatedAt > now) { + return existing; + } + const existingActiveUntil = !windowAdvanced && existing && existing.until > now ? existing.until : 0; + + let nextUntil = existingActiveUntil; + if (obsUntil !== undefined && obsUntil > now) { + nextUntil = Math.max(existingActiveUntil, obsUntil); + } else if (windowAdvanced) { + nextUntil = obsUntil && obsUntil > now ? obsUntil : 0; + } else if (obs.remaining !== undefined && obs.remaining > 0 && existingActiveUntil <= now) { + nextUntil = 0; + } + + const remaining = + obs.remaining !== undefined + ? Math.max(0, Math.floor(obs.remaining)) + : !windowAdvanced + ? existing?.remaining + : undefined; + const limit = + obs.limit !== undefined && obs.limit > 0 + ? Math.floor(obs.limit) + : !windowAdvanced + ? existing?.limit + : undefined; + const resetAt = + obsResetAt && obsResetAt > 0 + ? obsResetAt + : !windowAdvanced && existingResetAt > now + ? existingResetAt + : undefined; + + return { + until: nextUntil, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt: now, + }; +} + +function buildSnapshot(existing, obs, ignoreBefore) { + const otherBucket = obs.bucket === 'graphql' ? 'rest' : 'graphql'; + const mergedBuckets = {}; + const existingOther = existing?.buckets?.[otherBucket]; + if (existingOther && existingOther.updatedAt >= ignoreBefore) { + mergedBuckets[otherBucket] = existingOther; + } + const previousBucket = existing?.buckets?.[obs.bucket]; + mergedBuckets[obs.bucket] = mergeBucketState( + previousBucket && previousBucket.updatedAt >= ignoreBefore ? previousBucket : undefined, + obs, + ); + + const graphqlUntil = mergedBuckets.graphql?.until ?? 0; + const topUntil = graphqlUntil > obs.now ? graphqlUntil : 0; + return { + until: topUntil, + ...(topUntil > 0 + ? { + bucket: 'graphql', + reportedAt: + existing?.buckets?.graphql?.until === topUntil + ? existing?.reportedAt ?? obs.now + : obs.now, + reportedBy: 'cindy-desktop', + summary: 'GitHub GraphQL API rate limit reached', + } + : {}), + updatedAt: obs.now, + buckets: mergedBuckets, + }; +} + +export class SharedRateLimitStore { + constructor(options = {}) { + this.stateDir = options.stateDir ?? null; + this.readCacheMs = Math.max(0, options.readCacheMs ?? DEFAULT_SHARED_READ_CACHE_MS); + this.writeThrottleMs = Math.max(0, options.writeThrottleMs ?? DEFAULT_SHARED_WRITE_THROTTLE_MS); + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.inFlightRead = null; + this.writeQueue = Promise.resolve(); + this.ignoreBefore = 0; + this.generation = 0; + this.lastWritten = new Map(); + } + + isCacheFresh(now) { + return now - this.lastReadAt < this.readCacheMs; + } + + readCached(now) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (now - this.lastReadAt >= this.readCacheMs && !this.inFlightRead) { + void this.refresh(now).catch(() => undefined); + } + return this.cachedSnapshot; + } + + async refresh(now, force = false) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (!force && now - this.lastReadAt < this.readCacheMs) { + return this.cachedSnapshot; + } + if (this.inFlightRead) return this.inFlightRead; + const readGeneration = this.generation; + const op = readRateLimitFile(filePath, now) + .then((snap) => { + if (readGeneration !== this.generation) return null; + this.cachedSnapshot = snap; + this.lastReadAt = now; + return snap; + }) + .finally(() => { + if (this.inFlightRead === op) this.inFlightRead = null; + }); + this.inFlightRead = op; + return op; + } + + _shouldWrite(obs) { + if (obs.immediate) return true; + const prev = this.lastWritten.get(obs.bucket); + if (!prev) return true; + const elapsed = obs.now - prev.at; + const windowChanged = + obs.resetAt !== undefined && + prev.resetAt !== undefined && + Math.abs(obs.resetAt - prev.resetAt) > SAME_WINDOW_TOLERANCE_MS; + if (windowChanged) return true; + if ( + obs.remaining !== undefined && + prev.remaining !== undefined && + elapsed >= SIGNIFICANT_DROP_MIN_INTERVAL_MS + ) { + const dropThreshold = Math.max(100, Math.floor((obs.limit ?? 5000) * 0.05)); + if (prev.remaining - obs.remaining >= dropThreshold) return true; + } + if (elapsed >= this.writeThrottleMs && (obs.remaining !== prev.remaining || obs.resetAt !== prev.resetAt)) { + return true; + } + return false; + } + + record(obs) { + const nextInMemory = buildSnapshot(this.cachedSnapshot, obs, this.ignoreBefore); + this.cachedSnapshot = nextInMemory; + this.lastReadAt = obs.now; + + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath || !this._shouldWrite(obs)) return Promise.resolve(); + + this.lastWritten.set(obs.bucket, { + at: obs.now, + remaining: obs.remaining, + resetAt: obs.resetAt, + until: obs.until ?? 0, + }); + + const writeGeneration = this.generation; + const ignoreBefore = this.ignoreBefore; + const run = async () => { + if (writeGeneration !== this.generation) return; + const dir = path.dirname(filePath); + await fs.mkdir(dir, { recursive: true, mode: 0o700 }); + await fs.chmod(dir, 0o700).catch(() => undefined); + const existing = await readRateLimitFile(filePath, obs.now); + if (writeGeneration !== this.generation) return; + const snapshot = buildSnapshot(existing, obs, ignoreBefore); + await writeRateLimitFileAtomic(filePath, snapshot); + if (writeGeneration !== this.generation) return; + if (obs.now >= this.lastReadAt) { + this.cachedSnapshot = snapshot; + this.lastReadAt = obs.now; + } + }; + + this.writeQueue = this.writeQueue.then(run).catch(() => undefined); + return this.writeQueue; + } + + flush() { + return this.writeQueue; + } + + getBucket(bucket, now) { + const snap = this.readCached(now); + const entry = snap?.buckets?.[bucket]; + if (!entry) return undefined; + if (this.ignoreBefore > 0 && entry.updatedAt < this.ignoreBefore) return undefined; + return entry; + } + + isRateLimited(bucket, now) { + const entry = this.getBucket(bucket, now); + return Boolean(entry && entry.until > now); + } + + getPressure(bucket, now) { + const entry = this.getBucket(bucket, now); + if (this.isRateLimited(bucket, now)) { + return { + level: 'exhausted', + ...(entry?.remaining !== undefined ? { remaining: entry.remaining } : {}), + ...(entry?.limit !== undefined ? { limit: entry.limit } : {}), + ...(entry?.resetAt !== undefined ? { resetAt: entry.resetAt } : entry?.until ? { resetAt: entry.until } : {}), + }; + } + if ( + !entry || + entry.remaining === undefined || + entry.limit === undefined || + (entry.resetAt !== undefined && entry.resetAt <= now) + ) { + return { level: 'normal' }; + } + return { + level: classifyQuotaPressure(entry.remaining, entry.limit), + remaining: entry.remaining, + limit: entry.limit, + ...(entry.resetAt !== undefined ? { resetAt: entry.resetAt } : {}), + }; + } + + /** Baseline: does not proactively route away from GraphQL to REST ETag. */ + shouldPreferRest(_now) { + return false; + } + + clearMemoryCache(invalidatedAt) { + this.ignoreBefore = invalidatedAt; + this.generation += 1; + this.inFlightRead = null; + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.lastWritten.clear(); + } + + clearOnAccountSwitch(invalidatedAt) { + this.clearMemoryCache(invalidatedAt); + } +} + +export function createSharedRateLimitStore(options = {}) { + return new SharedRateLimitStore(options); +} diff --git a/questions/perf-github-api-budget/v1/controls/incomplete/tests/smoke.test.mjs b/questions/perf-github-api-budget/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..6e165e1 --- /dev/null +++ b/questions/perf-github-api-budget/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,130 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch, computeDeferredBackoffMs } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore, parseSharedRateLimitPayload } from '../src/shared-rate-limit.mjs'; + +function makeClock(start = 1_760_000_000_000) { + let t = start; + return { + now: () => t, + advance: (ms) => { + t += ms; + }, + }; +} + +test('PrStatusService fetches statuses, penetrates cache on refresh:true, and short-circuits 401', async () => { + const clock = makeClock(); + let calls = 0; + let restCalls = 0; + let title = 'Initial title'; + const gateway = { + async graphqlSingle(q) { + calls += 1; + if (q.prNumber === 401) { + const err = new Error('Unauthorized'); + err.status = 401; + throw err; + } + return { + remote: { + state: 'merged', + merged: true, + merged_at: new Date(clock.now() - 10_000).toISOString(), + head_sha: `sha-${calls}`, + title, + checks: 'success', + }, + }; + }, + async restGetPr() { + restCalls += 1; + throw new Error('should not call REST on 401'); + }, + }; + + const svc = new PrStatusService({ gateway, now: clock.now }); + const q = { owner: 'acme', repo: 'core', prNumber: 1 }; + const [first] = await svc.getStatuses([q]); + assert.equal(first.ok, true); + assert.equal(first.status, 'merged'); + + title = 'Updated after refresh'; + const [refreshed] = await svc.getStatuses([q], { refresh: true }); + assert.equal(refreshed.ok, true); + assert.equal(refreshed.title, 'Updated after refresh'); + + const authResults = await svc.getStatuses([ + { owner: 'acme', repo: 'core', prNumber: 401 }, + { owner: 'acme', repo: 'core', prNumber: 2 }, + ]); + assert.equal(authResults[0].ok, false); + assert.equal(authResults[0].reason, 'gh-not-logged-in'); + assert.equal(authResults[1].ok, false); + assert.equal(authResults[1].reason, 'gh-not-logged-in'); + assert.equal(restCalls, 0); +}); + +test('SharedRateLimitStore persists atomically, supports legacy until, and clears on account switch', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-rl-smoke-')); + try { + const now = 1_760_000_000_000; + const store = createSharedRateLimitStore({ stateDir: dir }); + await store.record({ + bucket: 'graphql', + remaining: 0, + limit: 5000, + resetAt: now + 300_000, + until: now + 300_000, + immediate: true, + now, + }); + await store.flush(); + + const files = await fs.readdir(dir); + assert.deepEqual(files, ['.rate-limit.json']); + const raw = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(raw.until, now + 300_000); + assert.equal(raw.buckets.graphql.remaining, 0); + + const legacy = parseSharedRateLimitPayload({ until: now + 120_000 }, now); + assert.equal(legacy.buckets.graphql.until, now + 120_000); + + store.clearOnAccountSwitch(now + 1000); + assert.equal(store.isRateLimited('graphql', now + 1000), false); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('PrFollowWatch observes changes and computes bounded exponential backoff', async () => { + assert.equal(computeDeferredBackoffMs(1), 60_000); + assert.equal(computeDeferredBackoffMs(2), 120_000); + assert.equal(computeDeferredBackoffMs(5), 15 * 60_000); + + const clock = makeClock(); + const q = { owner: 'acme', repo: 'core', prNumber: 7 }; + const ran = []; + const watch = new PrFollowWatch({ + now: clock.now, + listSchedules: () => [ + { id: 's1', prKey: prStatusKey(q), prQuery: q, targetSessionId: 'sess-1', createdAt: clock.now() - 10_000, active: true, expired: false }, + ], + runSchedule: async (s) => { + ran.push(s.id); + return { deferred: false }; + }, + }); + + const o1 = watch.observe(q, { ok: true, status: 'open', headSha: 'a', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '1' }); + assert.equal(o1.changed, false); + const o2 = watch.observe(q, { ok: true, status: 'open', headSha: 'b', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '2' }); + assert.equal(o2.changed, true); + await watch.triggerPr(q, o2); + assert.deepEqual(ran, ['s1']); +}); diff --git a/questions/perf-github-api-budget/v1/question.json b/questions/perf-github-api-budget/v1/question.json new file mode 100644 index 0000000..63913c2 --- /dev/null +++ b/questions/perf-github-api-budget/v1/question.json @@ -0,0 +1,87 @@ +{ + "id": "perf-github-api-budget", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "GitHub PR 状态轮询与跟进防限流优化", + "status": "calibrated", + "changeNote": "Eval Bank v2 quantitative performance question extracted from makecindy/cindy PR #14157 (325a0d39ff60).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "325a0d39ff60b9caacf434805061802269ada4d1", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "quota_efficiency", + "weight": "1/2", + "mode": "metric", + "gate": [ + "gate_real_updates", + "gate_refresh_penetrates", + "gate_partial_error_isolation", + "gate_auth_401_short_circuit", + "gate_account_switch_isolation", + "gate_atomic_rate_limit_write" + ], + "metric": { + "id": "api_quota_points", + "label": "48h billable API points", + "unit": "pts", + "direction": "lower", + "baseline": 50000, + "target": 200, + "scale": "log" + } + }, + { + "id": "waste_elimination", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_real_updates", + "gate_refresh_penetrates", + "gate_partial_error_isolation", + "gate_auth_401_short_circuit", + "gate_account_switch_isolation", + "gate_atomic_rate_limit_write" + ], + "metric": { + "id": "wasted_busy_merged_calls", + "label": "Wasted busy/merged calls", + "unit": "calls", + "direction": "lower", + "baseline": 4000, + "target": 10, + "scale": "log" + } + }, + { + "id": "rate_limit_safety", + "weight": "1/4", + "mode": "metric", + "gate": [ + "gate_real_updates", + "gate_refresh_penetrates", + "gate_partial_error_isolation", + "gate_auth_401_short_circuit", + "gate_account_switch_isolation", + "gate_atomic_rate_limit_write" + ], + "metric": { + "id": "rate_limit_breaches", + "label": "Rate-limit 429 breaches", + "unit": "hits", + "direction": "lower", + "baseline": 30000, + "target": 0, + "scale": "linear" + } + } + ] +} diff --git a/questions/perf-github-api-budget/v1/reference/CONTRACT.md b/questions/perf-github-api-budget/v1/reference/CONTRACT.md new file mode 100644 index 0000000..c1fadf6 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/CONTRACT.md @@ -0,0 +1,43 @@ +# Product & Protocol Contract + +This contract specifies required public module interfaces, gateway cost semantics, and correctness/safety invariants. Within these invariants, **you are free to design the optimal fetching, caching, conditional-ETag, batching, and polling/deferral strategy** to minimize total billable API quota usage. + +## 1. Shared Rate-Limit Store (`src/shared-rate-limit.mjs`) + +- Exports: `MAX_SHARED_RATE_LIMIT_MS` (`2 * 60 * 60_000`), `DEFAULT_SHARED_READ_CACHE_MS`, `DEFAULT_SHARED_WRITE_THROTTLE_MS`, `classifyQuotaPressure(remaining, limit)`, `parseSharedRateLimitPayload(raw, now)`, `SharedRateLimitStore`, `createSharedRateLimitStore(options)`. +- `options`: `{ stateDir?: string | null, readCacheMs?: number, writeThrottleMs?: number }` (persists to `/.rate-limit.json` when `stateDir` is set; memory-only otherwise). +- Public methods: `isCacheFresh(now)`, `readCached(now)`, `refresh(now, force = false)`, `record(obs)`, `flush()`, `getBucket(bucket, now)`, `getPressure(bucket, now)`, `isRateLimited(bucket, now)`, `shouldPreferRest(now)`, `clearOnAccountSwitch(invalidatedAt)`, `clearMemoryCache(invalidatedAt)`. +- **Persistence & safety invariants**: + - Writes are serialized, written atomically via temp file (`0o600` in `0o700` dir) + `rename`, clean up temp files on error, and never throw. + - **Privacy**: `.rate-limit.json` may contain ONLY numeric quota/reset timestamps and generic labels (`until`, `bucket`, `reportedAt`, `reportedBy`, `summary`, `updatedAt`, `buckets`) — never tokens, usernames, repo names, or raw errors. + - **Legacy compatibility**: `parseSharedRateLimitPayload` clamps `until`/`resetAt` to `<= now + MAX_SHARED_RATE_LIMIT_MS` and maps legacy top-level `until > now` onto `buckets[bucket ?? 'graphql']`. Written top-level `until` is `> 0` ONLY when `graphql` is rate-limited; a REST-only rate limit must keep top-level `until === 0`. + - **Account switch**: `clearOnAccountSwitch(invalidatedAt)` clears memory, advances generation, ignores pre-invalidation entries (`updatedAt < invalidatedAt`) even after `refresh()`, and drops them on subsequent merged disk writes. + - **Cross-process coordination**: Concurrent processes writing `.rate-limit.json` must observe peer rate-limit / critical-pressure updates without losing newer local or peer observations. + +## 2. PR Status Service (`src/pr-status-service.mjs`) + +- Exports: `DEFAULT_OPEN_TTL_MS`, `DEFAULT_MERGED_TTL_MS`, `DEFAULT_CLOSED_TTL_MS`, `DEFAULT_MAX_CACHE_ENTRIES`, `PR_GRAPHQL_BATCH_MAX` (`8`), `prStatusKey(q)`, `PrStatusService`. +- Constructor: `new PrStatusService({ gateway, rateLimitStore?, now?, openTtlMs?, mergedTtlMs?, closedTtlMs?, maxCacheEntries?, scope?, onObserved? })`. +- Public methods: `getStatuses(queries, opts?)`, `getCachedStatus(q)` (zero-network synchronous lookup), `getCacheSize()`, `invalidate(nextScope?)`. +- **Gateway interface & billing model**: + - `gateway.graphqlSingle(q)` → **1 GraphQL pt** (returns `{ remote, headers? }`). + - `gateway.graphqlBatch({ owner, repo, prNumbers })` (`1 <= prNumbers.length <= 8`, same repo) → **1 GraphQL pt total** (returns `{ items, headers? }`). + - `gateway.restGetPr(q, { etag? })` → **`0` pts** on `{ status: 304, notModified: true, etag, headers? }`; **1 REST pt** on `{ status: 200, notModified: false, etag, remote, headers? }`. +- **Correctness & freshness invariants**: + - `opts.refresh === true` always penetrates cache and fetches live remote state (including merged/closed PRs). + - Real PR updates on open PRs (commits, comments, CI status changes) must be observed promptly when polled (2-minute sequential transitions and 6-minute end-to-end delivery SLA). + - If `graphqlBatch` is used and an individual item fails with a non-`notFound` error, fall back ONLY that PR without poisoning valid siblings; clean `notFound` returns `{ ok: false, ..., reason: 'not-found' }` with zero fallback. + - On HTTP `401`, immediately short-circuit and return `{ ok: false, ..., reason: 'gh-not-logged-in' }` for all remaining queries in the call with **zero** fallback or subsequent gateway requests. + - Scope/account change (`invalidate()` or `scope()` changing) clears cached statuses, ETags, and calls `rateLimitStore?.clearOnAccountSwitch(now)`. + - Every gateway response/error with rate-limit headers must update `rateLimitStore` so quota pressure stays accurate across processes. + +## 3. PR Follow Watch (`src/pr-follow-watch.mjs`) + +- Exports: `MIN_RETRIGGER_MS`, `MAX_DEFER_BACKOFF_MS`, `PR_FOLLOW_END_GRACE_MS` (`2 * 60 * 60_000`), `computeDeferredBackoffMs(deferCount)`, `prStatusSignature(result)`, `PrFollowWatch`. +- Constructor: `new PrFollowWatch({ now?, prStatusService?, listSchedules, isSessionBusy?, hasQueuedPrompt?, hasSuccessfulRunSince?, expireSchedule?, runSchedule })`. +- Public methods: `reset()`, `observe(query, result)`, `triggerPr(query, info)`, `handleScheduledTick(schedule)`, `notifySessionIdle(sessionId)`, `tick(now)`. +- **Scheduling & delivery invariants**: + - Deliver 100% of real PR updates (commits, comments, CI transitions, merges, reopens) within the freshness SLA. + - Do not invoke `runSchedule` while `isSessionBusy(sessionId)` or `hasQueuedPrompt(sessionId, scheduleId)` is true; defer with bounded backoff and immediately drain pending wakeups on `notifySessionIdle(sessionId)`. + - Expire settled merged follow schedules via `expireSchedule` with **zero network calls** (using cached merged state): when `createdAt < mergedAt` and either a successful run already happened since `mergedAt` or a recurring follow's merge was observed `>= PR_FOLLOW_END_GRACE_MS` ago. + - Never prematurely expire schedules created at or after `mergedAt`, and ignore pre-creation merge events for them. diff --git a/questions/perf-github-api-budget/v1/reference/ENVIRONMENT.md b/questions/perf-github-api-budget/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..df2c3a7 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Determinism: All simulations use a virtual clock (`now()`) and an in-memory mock GitHub gateway — quota points, wasted calls, and rate-limit breaches are exact, hardware-independent integers. +- Public checks: + - `npm test` — functional correctness smoke tests + - `npm run bench` — deterministic 48-hour 50-PR workload benchmark reporting `api_quota_points`, `wasted_busy_merged_calls`, and `rate_limit_breaches` diff --git a/questions/perf-github-api-budget/v1/reference/TASK.md b/questions/perf-github-api-budget/v1/reference/TASK.md new file mode 100644 index 0000000..57b4f63 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/TASK.md @@ -0,0 +1,27 @@ +# Task + +You are optimizing Cindy's GitHub PR status polling, PR-follow scheduling, and cross-process rate-limit coordination pipeline extracted from production desktop operations. + +## Observed Production Symptoms + +1. **Severe GitHub API quota burn & repeated 429 breaches**: Polling 50 tracked PRs across 4 repositories over 48 hours burns >50,000 billable API points and triggers >30,000 HTTP 429 failures. Sibling processes share the same GitHub account quota via `.rate-limit.json`, yet quota pressure is not coordinated effectively across processes or transports. +2. **Wasted pre-run GitHub calls on busy sessions and settled merged PRs**: When a PR changes while its bound session is busy or already has a queued prompt, `PrFollowWatch` keeps firing the runner repeatedly only to defer—and recurring ticks continue polling already-merged PRs long after they have settled. +3. **Small FIFO cache**: The status cache evicts at 200 entries in FIFO order instead of keeping active multi-repo PRs warm. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral correctness, freshness, and safety invariants** defined in `CONTRACT.md`: + - Every real PR update (new commit, review/comment change, CI status transition, merge, reopen) must be detected and delivered promptly (within the freshness SLA; zero missed updates). + - Explicit `refresh: true` must always penetrate the cache (including merged PRs). + - Single-PR errors must not poison sibling PRs, clean 404s must not waste fallbacks, and HTTP 401 must immediately short-circuit with zero extra calls. + - Account switches must clear cached PR statuses, ETags, and stale rate-limit buckets. + - Cross-process rate-limit persistence must remain atomic, privacy-safe, and backward-compatible with legacy top-level `until` files. +- **Open-ended optimization goal**: You are free to choose the most effective transport selection (GraphQL batching vs conditional REST `ETag` / `304 Not Modified`), caching, invalidation, backoff, and scheduling strategy across `src/` to drive all three 48-hour simulation metrics as low as possible: + - `api_quota_points` (total billable API points — lower is better; `304 Not Modified` costs `0` points!) + - `wasted_busy_merged_calls` (calls wasted on busy/queued sessions or settled merged PRs — drive to `0`) + - `rate_limit_breaches` (429/exhausted failures — drive to `0`) +- Run `npm test` and `npm run bench` to verify correctness and compare before/after numbers. +- Record your analysis, design trade-offs, and verified metrics in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-github-api-budget/v1/reference/bench/workload.mjs b/questions/perf-github-api-budget/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..7c29d79 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/bench/workload.mjs @@ -0,0 +1,626 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore } from '../src/shared-rate-limit.mjs'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +function isMainModule() { + try { + return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +} + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const T0 = 1_760_000_000_000; +const SIM_MINUTES = 48 * 60; // 48 hours +const GQL_HOURLY_LIMIT = 500; +const REST_HOURLY_LIMIT = 1000; + +export function createDeterministicGateway(clock) { + const prs = new Map(); + let gqlRemaining = GQL_HOURLY_LIMIT; + let restRemaining = REST_HOURLY_LIMIT; + let windowResetAt = clock.now() + HOUR; + + const stats = { + graphqlCalls: 0, + graphqlPoints: 0, + rest200Calls: 0, + rest304Calls: 0, + rateLimitBreaches: 0, + wastedBusyCalls: 0, + wastedMergedCalls: 0, + }; + + function syncWindow() { + const now = clock.now(); + if (now >= windowResetAt) { + const hoursElapsed = Math.floor((now - windowResetAt) / HOUR) + 1; + windowResetAt += hoursElapsed * HOUR; + gqlRemaining = GQL_HOURLY_LIMIT; + restRemaining = REST_HOURLY_LIMIT; + } + } + + function makeHeaders(resource, remaining, limit) { + return { + 'x-ratelimit-resource': resource, + 'x-ratelimit-remaining': String(remaining), + 'x-ratelimit-limit': String(limit), + 'x-ratelimit-reset': String(Math.floor(windowResetAt / 1000)), + }; + } + + function rateLimitError(resource, remaining, limit) { + const err = new Error('GITHUB_RATE_LIMITED'); + err.status = 429; + err.code = 'GITHUB_RATE_LIMITED'; + err.headers = makeHeaders(resource, remaining, limit); + return err; + } + + function setPr(q, remote) { + const key = prStatusKey(q); + const prev = prs.get(key); + const version = (prev?.version ?? 0) + 1; + prs.set(key, { + q, + remote: { ...remote }, + version, + etag: `"v${version}-${remote.state}-${remote.head_sha}"`, + }); + } + + function updatePr(q, patch) { + const key = prStatusKey(q); + const cur = prs.get(key); + if (!cur) throw new Error(`Unknown PR ${key}`); + setPr(q, { ...cur.remote, ...patch }); + } + + function consumeExternalGraphql(targetRemaining) { + syncWindow(); + gqlRemaining = Math.max(0, Math.min(gqlRemaining, targetRemaining)); + return { remaining: gqlRemaining, limit: GQL_HOURLY_LIMIT, resetAt: windowResetAt }; + } + + const gateway = { + async graphqlSingle(q) { + syncWindow(); + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const entry = prs.get(prStatusKey(q)); + return { + remote: entry ? { ...entry.remote } : null, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async graphqlBatch({ owner, repo, prNumbers }) { + syncWindow(); + if (!Array.isArray(prNumbers) || prNumbers.length === 0 || prNumbers.length > 8) { + const err = new Error('Invalid batch size (must be 1..8)'); + err.status = 400; + throw err; + } + if (gqlRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('graphql', 0, GQL_HOURLY_LIMIT); + } + gqlRemaining -= 1; + stats.graphqlCalls += 1; + stats.graphqlPoints += 1; + const items = {}; + for (const prNumber of prNumbers) { + const entry = prs.get(prStatusKey({ owner, repo, prNumber })); + if (!entry) { + items[prNumber] = { ok: false, notFound: true }; + } else { + items[prNumber] = { ok: true, remote: { ...entry.remote } }; + } + } + return { + items, + headers: makeHeaders('graphql', gqlRemaining, GQL_HOURLY_LIMIT), + }; + }, + + async restGetPr(q, opts = {}) { + syncWindow(); + const entry = prs.get(prStatusKey(q)); + if (!entry) { + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + const err = new Error('NOT_FOUND'); + err.status = 404; + err.headers = makeHeaders('core', restRemaining, REST_HOURLY_LIMIT); + throw err; + } + if (opts?.etag && opts.etag === entry.etag) { + // Conditional GET 304 Not Modified costs 0 billable REST quota points. + stats.rest304Calls += 1; + return { + status: 304, + notModified: true, + etag: entry.etag, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + } + if (restRemaining <= 0) { + stats.rateLimitBreaches += 1; + throw rateLimitError('core', 0, REST_HOURLY_LIMIT); + } + restRemaining -= 1; + stats.rest200Calls += 1; + return { + status: 200, + notModified: false, + etag: entry.etag, + remote: { ...entry.remote }, + headers: makeHeaders('core', restRemaining, REST_HOURLY_LIMIT), + }; + }, + }; + + return { gateway, stats, setPr, updatePr, consumeExternalGraphql }; +} + +export async function runSimulation() { + let currentTime = T0; + const clock = { + now: () => currentTime, + set: (t) => { + currentTime = t; + }, + }; + + const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-gh-budget-bench-')); + try { + const rateLimitStore = createSharedRateLimitStore({ + stateDir, + writeThrottleMs: 30 * MINUTE, + }); + const sim = createDeterministicGateway(clock); + + const repoSpec = [ + { owner: 'acme', repo: 'core', baseNum: 100, count: 16 }, + { owner: 'acme', repo: 'desktop', baseNum: 200, count: 14 }, + { owner: 'acme', repo: 'web', baseNum: 300, count: 12 }, + { owner: 'acme', repo: 'cli', baseNum: 400, count: 8 }, + ]; + + const allQueries = []; + for (const r of repoSpec) { + for (let i = 1; i <= r.count; i += 1) { + allQueries.push({ owner: r.owner, repo: r.repo, prNumber: r.baseNum + i }); + } + } + + // Partition 50 PRs: + // 0..14 (15): pre-merged with completed post-merge run + // 15..16 (2): pre-merged with no post-merge run (tests 2h grace-window convergence) + // 17..21 (5): open at T0, merge during hours 2..20 + // 22..27 (6): pre-closed (unmerged); #22 reopens at hour 24 via refresh:true + // 28..29 (2): open at T0, close at hours 8 & 16 + // 30..49 (20): active open PRs throughout 48h + const schedules = new Map(); + const successfulRuns = new Map(); // scheduleId -> number[] + const busySessions = new Set(); + const queuedPrompts = new Set(); // `${sessionId}:${scheduleId}` + const mergedObservedAt = new Map(); // key -> ms + const deliveredEvents = new Map(); // `${key}#${eventId}` -> true + const expectedUpdates = []; + + for (let idx = 0; idx < allQueries.length; idx += 1) { + const q = allQueries[idx]; + const key = prStatusKey(q); + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + const scheduleId = `sched-${idx + 1}`; + + if (idx < 15) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-m-${idx}`, + title: `Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, [T0 - 2 * HOUR - 50 * MINUTE]); + } else if (idx < 17) { + sim.setPr(q, { + state: 'merged', + merged: true, + merged_at: new Date(T0 - 3 * HOUR).toISOString(), + updated_at: new Date(T0 - 3 * HOUR).toISOString(), + head_sha: `sha-mg-${idx}`, + title: `Grace Merged PR ${idx}`, + checks: 'success', + unresolved_count: 0, + review_decision: 'APPROVED', + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + graceOnlyFail: true, + }); + successfulRuns.set(scheduleId, []); + } else if (idx >= 22 && idx < 28) { + sim.setPr(q, { + state: 'closed', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 4 * HOUR).toISOString(), + head_sha: `sha-c-${idx}`, + title: `Closed PR ${idx}`, + checks: 'failure', + unresolved_count: 0, + review_decision: null, + }); + if (idx === 22) { + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 5 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } else { + sim.setPr(q, { + state: 'open', + merged: false, + merged_at: null, + updated_at: new Date(T0 - 30 * MINUTE).toISOString(), + head_sha: `sha-open-${idx}-0`, + title: `Open PR ${idx}`, + checks: 'pending', + unresolved_count: 0, + review_decision: null, + }); + schedules.set(scheduleId, { + id: scheduleId, + prKey: key, + prQuery: q, + targetSessionId: sessionId, + createdAt: T0 - 1 * HOUR, + active: true, + expired: false, + recurring: true, + manual: false, + }); + successfulRuns.set(scheduleId, []); + } + } + + const prStatusService = new PrStatusService({ + gateway: sim.gateway, + rateLimitStore, + now: clock.now, + }); + + // Latest expected event marker per PR so we verify real updates are delivered. + const latestPrEventId = new Map(); + + const watch = new PrFollowWatch({ + now: clock.now, + prStatusService, + listSchedules: () => Array.from(schedules.values()), + isSessionBusy: (sessionId) => busySessions.has(sessionId), + hasQueuedPrompt: (sessionId, scheduleId) => queuedPrompts.has(`${sessionId}:${scheduleId}`), + hasSuccessfulRunSince: (scheduleId, sinceMs) => + (successfulRuns.get(scheduleId) ?? []).some((ts) => ts >= sinceMs), + expireSchedule: (scheduleId) => { + const s = schedules.get(scheduleId); + if (s) s.expired = true; + }, + runSchedule: async (schedule, info = {}) => { + // Runner preRunHook fetches fresh PR status from GitHub before checking session/merged state. + const [fresh] = await prStatusService.getStatuses([schedule.prQuery], { refresh: true }); + const now = clock.now(); + const isBusy = busySessions.has(schedule.targetSessionId); + const isQueued = queuedPrompts.has(`${schedule.targetSessionId}:${schedule.id}`); + if (isBusy || isQueued) { + sim.stats.wastedBusyCalls += 1; + return { deferred: true, reason: isQueued ? 'already-queued' : 'session-running' }; + } + if (fresh?.ok && fresh.status === 'merged' && fresh.mergedAt != null && schedule.createdAt < fresh.mergedAt) { + const alreadyRan = (successfulRuns.get(schedule.id) ?? []).some((ts) => ts >= fresh.mergedAt); + const obsAt = mergedObservedAt.get(schedule.prKey); + const pastGrace = + info.changeKind !== 'merged' && obsAt !== undefined && now - obsAt >= 2 * HOUR; + if (alreadyRan || pastGrace) { + sim.stats.wastedMergedCalls += 1; + return { deferred: false }; + } + if (schedule.graceOnlyFail) { + // Simulate a failed post-merge run so grace-window expiry is exercised. + return { deferred: false, failed: true }; + } + successfulRuns.get(schedule.id).push(now); + } + const evId = latestPrEventId.get(schedule.prKey); + if (evId) deliveredEvents.set(`${schedule.prKey}#${evId}`, true); + return { deferred: false }; + }, + }); + + // Build deterministic event timeline across 48 hours. + const prEventsByMinute = new Map(); + const addPrEvent = (minute, ev) => { + const list = prEventsByMinute.get(minute) ?? []; + list.push(ev); + prEventsByMinute.set(minute, list); + }; + + // 5 open PRs (17..21) merge at hours 2, 5, 9, 14, 20. + const mergeHours = [2, 5, 9, 14, 20]; + for (let i = 0; i < mergeHours.length; i += 1) { + const idx = 17 + i; + const m = mergeHours[i] * 60 + 4; + const evId = `merge-${idx}`; + addPrEvent(m, { + idx, + evId, + kind: 'merge', + patch: (now) => ({ + state: 'merged', + merged: true, + merged_at: new Date(now).toISOString(), + updated_at: new Date(now).toISOString(), + checks: 'success', + review_decision: 'APPROVED', + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // 2 open PRs (28, 29) close at hours 8 and 16. + addPrEvent(8 * 60 + 7, { + idx: 28, + evId: 'close-28', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + addPrEvent(16 * 60 + 7, { + idx: 29, + evId: 'close-29', + kind: 'close', + patch: (now) => ({ state: 'closed', merged: false, updated_at: new Date(now).toISOString() }), + }); + + // Closed PR #22 reopens at hour 24 via explicit webhook refresh. + addPrEvent(24 * 60 + 5, { + idx: 22, + evId: 'reopen-22', + kind: 'reopen-webhook', + webhookRefresh: true, + patch: (now) => ({ + state: 'open', + merged: false, + head_sha: 'sha-reopen-22', + checks: 'pending', + updated_at: new Date(now).toISOString(), + }), + }); + expectedUpdates.push(`${prStatusKey(allQueries[22])}#reopen-22`); + + // 60 real updates (commits, comments/reviews, CI checks) on the 20 active open PRs (30..49). + for (let step = 0; step < 60; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; // spaced every 45 minutes across 48h + if (minute >= SIM_MINUTES - 60) continue; + const evId = `upd-${step}`; + const mod = step % 3; + addPrEvent(minute, { + idx, + evId, + kind: mod === 0 ? 'commit' : mod === 1 ? 'comment' : 'ci', + patch: (now) => { + if (mod === 0) { + return { head_sha: `sha-open-${idx}-${step + 1}`, checks: 'pending', updated_at: new Date(now).toISOString() }; + } + if (mod === 1) { + return { unresolved_count: (step % 4) + 1, review_decision: 'CHANGES_REQUESTED', updated_at: new Date(now).toISOString() }; + } + return { checks: step % 2 === 0 ? 'success' : 'failure', updated_at: new Date(now).toISOString() }; + }, + }); + expectedUpdates.push(`${prStatusKey(allQueries[idx])}#${evId}`); + } + + // Busy session windows overlapping ~35 of those updates + merge #18 (at hour 5). + const busyWindows = []; + for (let step = 0; step < 36; step += 1) { + const idx = 30 + (step % 20); + const minute = 45 + step * 45; + const sessionId = `session-${String((idx % 20) + 1).padStart(2, '0')}`; + if (step % 2 === 0) { + busyWindows.push({ start: minute - 2, end: minute + 28, sessionId, queuedScheduleId: null }); + } else { + busyWindows.push({ start: minute - 1, end: minute + 20, sessionId, queuedScheduleId: `sched-${idx + 1}` }); + } + } + // Also overlap merge of PR #18 (hour 5 = minute 304) with busy session. + busyWindows.push({ + start: 300, + end: 325, + sessionId: `session-${String((18 % 20) + 1).padStart(2, '0')}`, + queuedScheduleId: null, + }); + + const peakExternalHours = new Map([ + [4, 0], // exhausted + [12, 20], // critical (<= 50) + [20, 0], // exhausted + [28, 20], // critical + [36, 0], // exhausted + [44, 20], // critical + ]); + + // Step through 48 hours minute by minute. + for (let m = 0; m < SIM_MINUTES; m += 1) { + clock.set(T0 + m * MINUTE); + const now = clock.now(); + + // 1. Update busy/queued session states and notify idle transitions. + const prevBusy = new Set(busySessions); + const prevQueued = new Set(queuedPrompts); + busySessions.clear(); + queuedPrompts.clear(); + for (const w of busyWindows) { + if (m >= w.start && m < w.end) { + if (w.queuedScheduleId) queuedPrompts.add(`${w.sessionId}:${w.queuedScheduleId}`); + else busySessions.add(w.sessionId); + } + } + const becameIdle = new Set(); + for (const s of prevBusy) if (!busySessions.has(s)) becameIdle.add(s); + for (const qk of prevQueued) { + if (!queuedPrompts.has(qk)) becameIdle.add(qk.split(':')[0]); + } + for (const sessionId of becameIdle) { + await watch.notifySessionIdle(sessionId); + } + + // 2. Simulate external sibling process writing shared .rate-limit.json during peak hours. + if (m % 60 === 2) { + const hour = Math.floor(m / 60); + if (peakExternalHours.has(hour)) { + await rateLimitStore.flush(); + const targetRem = peakExternalHours.get(hour); + const ext = sim.consumeExternalGraphql(targetRem); + const peerStore = createSharedRateLimitStore({ stateDir }); + await peerStore.record({ + bucket: 'graphql', + remaining: ext.remaining, + limit: ext.limit, + resetAt: ext.resetAt, + ...(ext.remaining === 0 ? { until: ext.resetAt } : {}), + immediate: true, + now, + }); + await peerStore.flush(); + } + } + + // 3. Apply scheduled PR mutations. + const events = prEventsByMinute.get(m); + if (events) { + for (const ev of events) { + const q = allQueries[ev.idx]; + const key = prStatusKey(q); + sim.updatePr(q, ev.patch(now)); + latestPrEventId.set(key, ev.evId); + if (ev.webhookRefresh) { + const [res] = await prStatusService.getStatuses([q], { refresh: true }); + const obs = watch.observe(q, res); + if (obs.changed) await watch.triggerPr(q, obs); + } + } + } + + // 4. Periodic workspace PR status polling (every 3 minutes across all 50 PRs). + if (m % 3 === 0) { + const results = await prStatusService.getStatuses(allQueries); + for (let i = 0; i < allQueries.length; i += 1) { + const q = allQueries[i]; + const res = results[i]; + if (res?.ok && res.status === 'merged' && !mergedObservedAt.has(prStatusKey(q))) { + mergedObservedAt.set(prStatusKey(q), now); + } + const obs = watch.observe(q, res); + if (obs.changed) { + await watch.triggerPr(q, obs); + } + } + } + + // 5. Explicit user refresh on merged PRs at hours 12 and 36. + if (m === 12 * 60 + 10 || m === 36 * 60 + 10) { + await prStatusService.getStatuses([allQueries[0]], { refresh: true }); + } + + // 6. Recurring PR-follow cron ticks every 20 minutes on merged schedules (0..21). + if (m > 0 && m % 20 === 0) { + for (let idx = 0; idx <= 21; idx += 1) { + const schedule = schedules.get(`sched-${idx + 1}`); + if (schedule && schedule.active && !schedule.expired) { + const st = prStatusService.getCachedStatus(schedule.prQuery); + if (st?.ok && st.status === 'merged') { + await watch.handleScheduledTick(schedule); + } + } + } + } + + // 7. Drain due pending follow wakeups. + await watch.tick(now); + } + + await rateLimitStore.flush(); + const missedUpdates = expectedUpdates.filter((id) => !deliveredEvents.has(id)); + const api_quota_points = sim.stats.graphqlPoints + sim.stats.rest200Calls; + const wasted_busy_merged_calls = sim.stats.wastedBusyCalls + sim.stats.wastedMergedCalls; + const rate_limit_breaches = sim.stats.rateLimitBreaches; + + return { + api_quota_points, + wasted_busy_merged_calls, + rate_limit_breaches, + breakdown: { ...sim.stats }, + expectedUpdateCount: expectedUpdates.length, + missedUpdateCount: missedUpdates.length, + missedUpdates, + }; + } finally { + await fs.rm(stateDir, { recursive: true, force: true }); + } +} + +if (isMainModule()) { + const result = await runSimulation(); + console.log(JSON.stringify(result, null, 2)); +} diff --git a/questions/perf-github-api-budget/v1/reference/package.json b/questions/perf-github-api-budget/v1/reference/package.json new file mode 100644 index 0000000..c301e7f --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-github-api-budget", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-github-api-budget/v1/reference/src/pr-follow-watch.mjs b/questions/perf-github-api-budget/v1/reference/src/pr-follow-watch.mjs new file mode 100644 index 0000000..00eba7c --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/src/pr-follow-watch.mjs @@ -0,0 +1,256 @@ +import { prStatusKey } from './pr-status-service.mjs'; + +export const MIN_RETRIGGER_MS = 60_000; +export const MAX_DEFER_BACKOFF_MS = 15 * 60_000; +export const PR_FOLLOW_END_GRACE_MS = 2 * 60 * 60_000; +const MAX_TRACKED = 500; + +export function computeDeferredBackoffMs(deferCount) { + if (deferCount <= 1) return MIN_RETRIGGER_MS; + return Math.min(MAX_DEFER_BACKOFF_MS, MIN_RETRIGGER_MS * 2 ** (deferCount - 1)); +} + +export function prStatusSignature(result) { + if (!result?.ok) return null; + return [ + result.status ?? '', + result.headSha ?? '', + result.checks ?? '', + String(result.unresolvedCount ?? 0), + result.reviewDecision ?? '', + result.updatedAt ?? '', + ].join('|'); +} + +export class PrFollowWatch { + constructor(deps) { + this.deps = deps; + this.now = deps.now ?? Date.now; + this.signatures = new Map(); + this.mergedStateByKey = new Map(); + this.lastTriggered = new Map(); + this.consecutiveDeferrals = new Map(); + this.pending = new Map(); + } + + reset() { + this.signatures.clear(); + this.mergedStateByKey.clear(); + this.lastTriggered.clear(); + this.consecutiveDeferrals.clear(); + this.pending.clear(); + } + + _recordMergedState(key, result) { + if (!result?.ok) return; + if (result.status !== 'merged') { + this.mergedStateByKey.delete(key); + return; + } + const now = this.now(); + const existing = this.mergedStateByKey.get(key); + const mergedAt = + typeof result.mergedAt === 'number' && Number.isFinite(result.mergedAt) + ? result.mergedAt + : existing?.mergedAt; + if (mergedAt === undefined) return; + this.mergedStateByKey.delete(key); + this.mergedStateByKey.set(key, { + mergedAt, + observedAt: existing?.observedAt ?? now, + }); + if (this.mergedStateByKey.size > MAX_TRACKED) { + this.mergedStateByKey.delete(this.mergedStateByKey.keys().next().value); + } + } + + _resolveKnownMerge(schedule, explicitMergedAt) { + const now = this.now(); + if (explicitMergedAt !== undefined && Number.isFinite(explicitMergedAt)) { + const existing = this.mergedStateByKey.get(schedule.prKey); + return { mergedAt: explicitMergedAt, observedAt: existing?.observedAt ?? now }; + } + const tracked = this.mergedStateByKey.get(schedule.prKey); + if (tracked) return tracked; + + // Zero-network merged cache lookup via PrStatusService. + const cached = this.deps.prStatusService?.getCachedStatus?.(schedule.prQuery); + if (cached?.ok && cached.status === 'merged' && typeof cached.mergedAt === 'number' && Number.isFinite(cached.mergedAt)) { + const record = { mergedAt: cached.mergedAt, observedAt: cached.observedAt ?? now }; + this.mergedStateByKey.set(schedule.prKey, record); + return record; + } + return undefined; + } + + observe(query, result) { + const fresh = prStatusSignature(result); + if (fresh === null) return { changed: false, changeKind: null }; + const key = prStatusKey(query); + this._recordMergedState(key, result); + const previous = this.signatures.get(key); + this.signatures.set(key, fresh); + if (previous === undefined || previous === fresh) { + return { changed: false, changeKind: null }; + } + const prevStatus = previous.split('|')[0]; + const changeKind = + result.status === 'merged' && prevStatus !== 'merged' + ? 'merged' + : result.status === 'open' && prevStatus === 'closed' + ? 'reopened' + : 'update'; + return { + changed: true, + changeKind, + ...(result.status === 'merged' && result.mergedAt != null ? { mergedAt: result.mergedAt } : {}), + }; + } + + async triggerPr(query, info = {}) { + const key = prStatusKey(query); + const schedules = (await this.deps.listSchedules()).filter( + (s) => s.active && !s.expired && s.prKey === key, + ); + for (const schedule of schedules) { + await this._evaluateAndDispatch(schedule, info); + } + } + + async handleScheduledTick(schedule) { + if (!schedule.active || schedule.expired) { + this.consecutiveDeferrals.delete(schedule.id); + this.pending.delete(schedule.id); + return { status: 'skipped' }; + } + return this._evaluateAndDispatch(schedule, { changeKind: 'scheduled-tick' }); + } + + async _evaluateAndDispatch(schedule, info) { + const now = this.now(); + if (!schedule.active || schedule.expired) { + this.consecutiveDeferrals.delete(schedule.id); + this.pending.delete(schedule.id); + return { status: 'skipped' }; + } + + const explicitMergedAt = info.changeKind === 'merged' ? info.mergedAt : undefined; + const knownMerge = this._resolveKnownMerge(schedule, explicitMergedAt); + if (knownMerge) { + const createdAfterMerge = schedule.createdAt >= knownMerge.mergedAt; + if (explicitMergedAt !== undefined && createdAfterMerge) { + return { status: 'skipped' }; + } + if (!createdAfterMerge && (explicitMergedAt !== undefined || (schedule.recurring && !schedule.manual))) { + const ranSinceMerge = await this.deps.hasSuccessfulRunSince?.(schedule.id, knownMerge.mergedAt); + if (ranSinceMerge) { + this.consecutiveDeferrals.delete(schedule.id); + this.pending.delete(schedule.id); + await this.deps.expireSchedule?.(schedule.id, now); + return { status: 'expired' }; + } + if ( + explicitMergedAt === undefined && + schedule.recurring && + !schedule.manual && + now - knownMerge.observedAt >= PR_FOLLOW_END_GRACE_MS + ) { + this.consecutiveDeferrals.delete(schedule.id); + this.pending.delete(schedule.id); + await this.deps.expireSchedule?.(schedule.id, now); + return { status: 'expired' }; + } + } + } + + const targetSessionId = schedule.targetSessionId; + if ( + targetSessionId && + (this.deps.hasQueuedPrompt?.(targetSessionId, schedule.id) || + this.deps.isSessionBusy?.(targetSessionId)) + ) { + const deferCount = (this.consecutiveDeferrals.get(schedule.id) ?? 0) + 1; + this.consecutiveDeferrals.set(schedule.id, deferCount); + this.pending.set(schedule.id, { + schedule, + info, + notBefore: now + computeDeferredBackoffMs(deferCount), + targetSessionId, + busyDeferred: true, + }); + return { status: 'deferred', reason: 'busy-short-circuit' }; + } + + const last = this.lastTriggered.get(schedule.id); + const minDelay = computeDeferredBackoffMs(this.consecutiveDeferrals.get(schedule.id) ?? 0); + if (last !== undefined && now - last < minDelay) { + this.pending.set(schedule.id, { + schedule, + info, + notBefore: last + minDelay, + targetSessionId, + busyDeferred: false, + }); + return { status: 'deferred', reason: 'min-retrigger' }; + } + + this.pending.delete(schedule.id); + this.lastTriggered.set(schedule.id, now); + const outcome = await this.deps.runSchedule(schedule, info); + if (outcome?.deferred) { + const deferCount = (this.consecutiveDeferrals.get(schedule.id) ?? 0) + 1; + this.consecutiveDeferrals.set(schedule.id, deferCount); + this.pending.set(schedule.id, { + schedule, + info, + notBefore: this.now() + computeDeferredBackoffMs(deferCount), + targetSessionId, + busyDeferred: true, + }); + return { status: 'deferred', reason: outcome.reason ?? 'runner-deferred' }; + } + this.consecutiveDeferrals.delete(schedule.id); + return { status: 'ran' }; + } + + async notifySessionIdle(sessionId) { + if (!sessionId || this.pending.size === 0) return; + const now = this.now(); + let matched = false; + for (const [id, entry] of this.pending.entries()) { + if (entry.targetSessionId !== sessionId) continue; + matched = true; + this.consecutiveDeferrals.delete(id); + if (entry.busyDeferred) { + this.lastTriggered.delete(id); + } + entry.notBefore = now; + } + if (matched) { + await this.tick(now); + } + } + + async tick(now = this.now()) { + const due = []; + for (const [id, entry] of this.pending.entries()) { + if (entry.notBefore <= now) { + due.push([id, entry]); + } + } + if (due.length === 0) return; + const schedules = await this.deps.listSchedules(); + const byId = new Map(schedules.map((s) => [s.id, s])); + for (const [id, entry] of due) { + if (!this.pending.has(id)) continue; + const latest = byId.get(id); + if (!latest || !latest.active || latest.expired) { + this.pending.delete(id); + this.consecutiveDeferrals.delete(id); + continue; + } + this.pending.delete(id); + await this._evaluateAndDispatch(latest, entry.info); + } + } +} diff --git a/questions/perf-github-api-budget/v1/reference/src/pr-status-service.mjs b/questions/perf-github-api-budget/v1/reference/src/pr-status-service.mjs new file mode 100644 index 0000000..d4350a5 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/src/pr-status-service.mjs @@ -0,0 +1,477 @@ +import { classifyQuotaPressure } from './shared-rate-limit.mjs'; + +export const DEFAULT_OPEN_TTL_MS = 60_000; +export const DEFAULT_MERGED_TTL_MS = 24 * 60 * 60_000; +export const DEFAULT_CLOSED_TTL_MS = 30 * 60_000; +export const DEFAULT_MAX_CACHE_ENTRIES = 500; +export const PR_GRAPHQL_BATCH_MAX = 8; + +export function prStatusKey(q) { + return `${q.owner.toLowerCase()}/${q.repo.toLowerCase()}#${q.prNumber}`; +} + +function mapRemoteStatus(remote) { + if (remote.merged || remote.state === 'merged' || remote.state === 'MERGED') return 'merged'; + if (remote.state === 'closed' || remote.state === 'CLOSED') return 'closed'; + return 'open'; +} + +function readHeader(headers, name) { + if (!headers) return null; + if (typeof headers.get === 'function') return headers.get(name); + const lower = name.toLowerCase(); + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === lower) return v == null ? null : String(v); + } + return null; +} + +function bucketFromHeaders(headers, fallback) { + const res = readHeader(headers, 'x-ratelimit-resource')?.trim().toLowerCase(); + if (res === 'graphql') return 'graphql'; + if (res === 'core' || res === 'rest') return 'rest'; + return fallback; +} + +export class PrStatusService { + constructor(deps) { + this.deps = deps; + this.gateway = deps.gateway; + this.rateLimitStore = deps.rateLimitStore ?? null; + this.now = deps.now ?? Date.now; + this.openTtlMs = deps.openTtlMs ?? DEFAULT_OPEN_TTL_MS; + this.mergedTtlMs = Math.max(this.openTtlMs, deps.mergedTtlMs ?? DEFAULT_MERGED_TTL_MS); + this.closedTtlMs = Math.max(this.openTtlMs, deps.closedTtlMs ?? DEFAULT_CLOSED_TTL_MS); + this.maxCacheEntries = Math.max(1, Math.floor(deps.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES)); + this.cache = new Map(); + this.etagCache = new Map(); + this.scope = null; + this.generation = 0; + } + + getCacheSize() { + return this.cache.size; + } + + _touchCache(key, entry) { + this.cache.delete(key); + this.cache.set(key, entry); + } + + _putCache(key, entry) { + this.cache.delete(key); + while (this.cache.size >= this.maxCacheEntries) { + this.cache.delete(this.cache.keys().next().value); + } + this.cache.set(key, entry); + } + + _baseTtlForResult(result) { + if (!result.ok) return this.openTtlMs; + if (result.status === 'merged') return this.mergedTtlMs; + if (result.status === 'closed') return this.closedTtlMs; + return this.openTtlMs; + } + + getCachedStatus(q) { + const key = prStatusKey(q); + const entry = this.cache.get(key); + if (entry) this._touchCache(key, entry); + return entry?.result; + } + + invalidate(nextScope = this.scope) { + this.generation += 1; + this.scope = nextScope; + this.cache.clear(); + this.etagCache.clear(); + this.rateLimitStore?.clearOnAccountSwitch(this.now()); + } + + _recordQuotaHeaders(fallbackBucket, headers, isRateLimitErr = false, retryAfterMs = undefined) { + if (!this.rateLimitStore) return; + const now = this.now(); + const bucket = bucketFromHeaders(headers, fallbackBucket); + const rawRemaining = readHeader(headers, 'x-ratelimit-remaining'); + const rawLimit = readHeader(headers, 'x-ratelimit-limit'); + const rawReset = readHeader(headers, 'x-ratelimit-reset'); + const remaining = rawRemaining !== null ? Number(rawRemaining.trim()) : NaN; + const limit = rawLimit !== null ? Number(rawLimit.trim()) : NaN; + const resetSec = rawReset !== null ? Number(rawReset.trim()) : NaN; + + const hasQuota = + Number.isFinite(remaining) && + remaining >= 0 && + Number.isFinite(limit) && + limit > 0 && + Number.isFinite(resetSec) && + resetSec > 0; + + const resetAt = hasQuota ? Math.floor(resetSec) * 1000 : undefined; + const prevLevel = this.rateLimitStore.getPressure(bucket, now).level; + const nextLevel = hasQuota ? classifyQuotaPressure(Math.floor(remaining), Math.floor(limit)) : prevLevel; + const pressureChanged = nextLevel !== prevLevel; + + if (isRateLimitErr) { + const until = Math.max(resetAt ?? 0, retryAfterMs ? now + retryAfterMs : 0) || now + 60_000; + void this.rateLimitStore.record({ + bucket, + until, + ...(hasQuota + ? { remaining: Math.floor(remaining), limit: Math.floor(limit), resetAt } + : { remaining: 0, resetAt: until }), + immediate: true, + now, + }); + return; + } + + if (hasQuota) { + const exhausted = Math.floor(remaining) === 0; + void this.rateLimitStore.record({ + bucket, + remaining: Math.floor(remaining), + limit: Math.floor(limit), + resetAt, + ...(exhausted && resetAt && resetAt > now ? { until: resetAt } : {}), + immediate: pressureChanged || exhausted, + now, + }); + } + } + + _buildOkResult(q, remote) { + const status = mapRemoteStatus(remote); + const mergedAt = + remote.merged_at !== undefined && remote.merged_at !== null + ? typeof remote.merged_at === 'number' + ? remote.merged_at + : Date.parse(remote.merged_at) + : null; + return { + ok: true, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + status, + headSha: remote.head_sha ?? '', + title: remote.title ?? '', + checks: remote.checks ?? 'pending', + unresolvedCount: remote.unresolved_count ?? 0, + reviewDecision: remote.review_decision ?? null, + updatedAt: remote.updated_at ?? '', + mergedAt: Number.isFinite(mergedAt) ? mergedAt : null, + observedAt: this.now(), + }; + } + + _commitCachedResult(key, q, result) { + const fetchedAt = this.now(); + const ttl = this._baseTtlForResult(result); + this._putCache(key, { + result, + fetchedAt, + expiresAt: fetchedAt + ttl, + }); + try { + this.deps.onObserved?.(q, result); + } catch { + // Observers are best-effort. + } + } + + async _checkScope() { + if (!this.deps.scope) return; + const nextScope = await this.deps.scope(); + if (this.scope === null) { + this.scope = nextScope; + return; + } + if (nextScope !== this.scope) { + this.invalidate(nextScope); + } + } + + async _fetchViaRestEtag(q) { + const key = prStatusKey(q); + const cachedEtag = this.etagCache.get(key); + try { + const rest = await this.gateway.restGetPr( + q, + cachedEtag?.etag ? { etag: cachedEtag.etag } : {}, + ); + if (rest?.headers && rest.status !== 304) { + this._recordQuotaHeaders('rest', rest.headers, false); + } + if (rest?.status === 304 || rest?.notModified) { + const priorResult = this.cache.get(key)?.result ?? cachedEtag?.result; + if (priorResult && priorResult.ok) { + return { ...priorResult, observedAt: this.now() }; + } + // Fallback if ETag existed without cached payload: refetch unconditionally. + const fresh = await this.gateway.restGetPr(q, {}); + if (fresh?.headers) this._recordQuotaHeaders('rest', fresh.headers, false); + if (!fresh?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + const built = this._buildOkResult(q, fresh.remote); + if (fresh.etag) this.etagCache.set(key, { etag: fresh.etag, result: built }); + return built; + } + if (!rest?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + const built = this._buildOkResult(q, rest.remote); + if (rest.etag) { + if (this.etagCache.size >= this.maxCacheEntries && !this.etagCache.has(key)) { + this.etagCache.delete(this.etagCache.keys().next().value); + } + this.etagCache.set(key, { etag: rest.etag, result: built }); + } + return built; + } catch (err) { + const status = err?.status; + if (status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + if (status === 429 || err?.code === 'GITHUB_RATE_LIMITED') { + this._recordQuotaHeaders('rest', err?.headers, true, err?.retryAfterMs); + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'rate-limited' }; + } + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'fetch-failed' }; + } + } + + async _fetchSingle(q) { + if (this.rateLimitStore?.shouldPreferRest(this.now())) { + return this._fetchViaRestEtag(q); + } + try { + const res = await this.gateway.graphqlSingle(q); + if (res?.headers) this._recordQuotaHeaders('graphql', res.headers, false); + if (!res?.remote) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + return this._buildOkResult(q, res.remote); + } catch (err) { + const status = err?.status; + if (status === 401) { + return { + ok: false, + owner: q.owner, + repo: q.repo, + prNumber: q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }; + } + if (status === 404) { + return { ok: false, owner: q.owner, repo: q.repo, prNumber: q.prNumber, reason: 'not-found' }; + } + if (status === 429 || err?.code === 'GITHUB_RATE_LIMITED') { + this._recordQuotaHeaders('graphql', err?.headers, true, err?.retryAfterMs); + } + return this._fetchViaRestEtag(q); + } + } + + async _fetchRepoChunk(chunk) { + const out = new Map(); + if (this.rateLimitStore?.shouldPreferRest(this.now()) || chunk.length === 1 || !this.gateway.graphqlBatch) { + for (const { key, q } of chunk) { + const res = + this.rateLimitStore?.shouldPreferRest(this.now()) + ? await this._fetchViaRestEtag(q) + : await this._fetchSingle(q); + out.set(key, res); + if (res._shortCircuit401) return { results: out, aborted401: true }; + } + return { results: out, aborted401: false }; + } + + const { owner, repo } = chunk[0].q; + const prNumbers = chunk.map((c) => c.q.prNumber); + try { + const batchRes = await this.gateway.graphqlBatch({ owner, repo, prNumbers }); + if (batchRes?.headers) this._recordQuotaHeaders('graphql', batchRes.headers, false); + const items = batchRes?.items ?? {}; + const fallback = []; + + for (const entry of chunk) { + const item = items[entry.q.prNumber]; + if (item?.ok && item.remote) { + out.set(entry.key, this._buildOkResult(entry.q, item.remote)); + } else if (item && item.notFound) { + out.set(entry.key, { + ok: false, + owner: entry.q.owner, + repo: entry.q.repo, + prNumber: entry.q.prNumber, + reason: 'not-found', + }); + } else { + if (item?.error?.status === 401) { + out.set(entry.key, { + ok: false, + owner: entry.q.owner, + repo: entry.q.repo, + prNumber: entry.q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }); + return { results: out, aborted401: true }; + } + fallback.push(entry); + } + } + + for (const entry of fallback) { + const res = await this._fetchViaRestEtag(entry.q); + out.set(entry.key, res); + if (res._shortCircuit401) return { results: out, aborted401: true }; + } + return { results: out, aborted401: false }; + } catch (err) { + if (err?.status === 401) { + for (const entry of chunk) { + out.set(entry.key, { + ok: false, + owner: entry.q.owner, + repo: entry.q.repo, + prNumber: entry.q.prNumber, + reason: 'gh-not-logged-in', + _shortCircuit401: true, + }); + } + return { results: out, aborted401: true }; + } + if (err?.status === 429 || err?.code === 'GITHUB_RATE_LIMITED') { + this._recordQuotaHeaders('graphql', err?.headers, true, err?.retryAfterMs); + } + for (const entry of chunk) { + const res = await this._fetchViaRestEtag(entry.q); + out.set(entry.key, res); + if (res._shortCircuit401) return { results: out, aborted401: true }; + } + return { results: out, aborted401: false }; + } + } + + async getStatuses(queries, opts = {}) { + await this._checkScope(); + const generation = this.generation; + const refresh = opts.refresh === true; + const now = this.now(); + + const results = new Array(queries.length); + const missOrder = []; + const missMap = new Map(); + + for (let i = 0; i < queries.length; i += 1) { + const q = queries[i]; + const key = prStatusKey(q); + const cached = this.cache.get(key); + if (!refresh && cached && cached.expiresAt > now) { + this._touchCache(key, cached); + results[i] = cached.result; + continue; + } + if (!missMap.has(key)) { + const item = { key, q, indices: [i] }; + missMap.set(key, item); + missOrder.push(item); + } else { + missMap.get(key).indices.push(i); + } + } + + if (missOrder.length === 0) return results; + + if (this.rateLimitStore && !this.rateLimitStore.isCacheFresh(this.now())) { + await this.rateLimitStore.refresh(this.now()); + if (generation !== this.generation) { + for (const miss of missOrder) { + const errRes = { ok: false, owner: miss.q.owner, repo: miss.q.repo, prNumber: miss.q.prNumber, reason: 'gh-not-logged-in' }; + for (const idx of miss.indices) results[idx] = errRes; + } + return results; + } + } + + // Group cache misses by repository (case-insensitive) into chunks of at most PR_GRAPHQL_BATCH_MAX (8). + const repoGroups = new Map(); + for (const miss of missOrder) { + const repoKey = `${miss.q.owner.toLowerCase()}/${miss.q.repo.toLowerCase()}`; + let list = repoGroups.get(repoKey); + if (!list) { + list = []; + repoGroups.set(repoKey, list); + } + list.push(miss); + } + + const chunks = []; + for (const group of repoGroups.values()) { + for (let offset = 0; offset < group.length; offset += PR_GRAPHQL_BATCH_MAX) { + chunks.push(group.slice(offset, offset + PR_GRAPHQL_BATCH_MAX)); + } + } + + const fetchedByKey = new Map(); + let aborted401 = false; + + for (const chunk of chunks) { + if (aborted401) { + for (const miss of chunk) { + fetchedByKey.set(miss.key, { + ok: false, + owner: miss.q.owner, + repo: miss.q.repo, + prNumber: miss.q.prNumber, + reason: 'gh-not-logged-in', + }); + } + continue; + } + + const { results: chunkRes, aborted401: hit401 } = await this._fetchRepoChunk(chunk); + if (hit401) aborted401 = true; + for (const miss of chunk) { + const res = chunkRes.get(miss.key) ?? { + ok: false, + owner: miss.q.owner, + repo: miss.q.repo, + prNumber: miss.q.prNumber, + reason: aborted401 ? 'gh-not-logged-in' : 'fetch-failed', + }; + const { _shortCircuit401: _, ...clean } = res; + fetchedByKey.set(miss.key, clean); + if (generation === this.generation && (clean.ok || clean.reason === 'not-found')) { + this._commitCachedResult(miss.key, miss.q, clean); + } + } + } + + for (const miss of missOrder) { + const finalRes = + generation !== this.generation + ? { ok: false, owner: miss.q.owner, repo: miss.q.repo, prNumber: miss.q.prNumber, reason: 'gh-not-logged-in' } + : fetchedByKey.get(miss.key); + for (const idx of miss.indices) { + results[idx] = finalRes; + } + } + + return results; + } +} diff --git a/questions/perf-github-api-budget/v1/reference/src/shared-rate-limit.mjs b/questions/perf-github-api-budget/v1/reference/src/shared-rate-limit.mjs new file mode 100644 index 0000000..8aa24a3 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/src/shared-rate-limit.mjs @@ -0,0 +1,390 @@ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export const MAX_SHARED_RATE_LIMIT_MS = 2 * 60 * 60_000; +export const DEFAULT_SHARED_READ_CACHE_MS = 5_000; +export const DEFAULT_SHARED_WRITE_THROTTLE_MS = 30_000; +const SIGNIFICANT_DROP_MIN_INTERVAL_MS = 5_000; +const SAME_WINDOW_TOLERANCE_MS = 60_000; +const RATE_LIMIT_FILENAME = '.rate-limit.json'; + +export function classifyQuotaPressure(remaining, limit) { + if (remaining === 0) return 'exhausted'; + if (remaining <= Math.max(50, Math.floor(limit * 0.05))) return 'critical'; + if (remaining <= Math.max(200, Math.floor(limit * 0.2))) return 'low'; + return 'normal'; +} + +function resolveRateLimitFilePath(configuredDir) { + if (configuredDir === null || configuredDir === undefined) return null; + if (typeof configuredDir === 'string') { + const trimmed = configuredDir.trim(); + return trimmed ? path.join(trimmed, RATE_LIMIT_FILENAME) : null; + } + return null; +} + +function clampTimestampMs(value, now) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return 0; + return Math.min(Math.floor(num), now + MAX_SHARED_RATE_LIMIT_MS); +} + +function parseNonNegativeInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num < 0) return undefined; + return Math.floor(num); +} + +function parsePositiveInt(value) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) return undefined; + return Math.floor(num); +} + +function parseBucketState(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined; + const until = clampTimestampMs(raw.until, now); + const remaining = parseNonNegativeInt(raw.remaining); + const limit = parsePositiveInt(raw.limit); + const resetAt = clampTimestampMs(raw.resetAt, now) || undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? 0; + if (until === 0 && remaining === undefined && limit === undefined && resetAt === undefined) { + return undefined; + } + return { + until, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt, + }; +} + +export function parseSharedRateLimitPayload(raw, now) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const topUntil = clampTimestampMs(raw.until, now); + const topBucket = raw.bucket === 'graphql' || raw.bucket === 'rest' ? raw.bucket : undefined; + const updatedAt = parseNonNegativeInt(raw.updatedAt) ?? parseNonNegativeInt(raw.reportedAt) ?? 0; + const reportedAt = parseNonNegativeInt(raw.reportedAt); + + const buckets = {}; + if (raw.buckets && typeof raw.buckets === 'object' && !Array.isArray(raw.buckets)) { + const gql = parseBucketState(raw.buckets.graphql, now); + const rest = parseBucketState(raw.buckets.rest, now); + if (gql) buckets.graphql = gql; + if (rest) buckets.rest = rest; + } + + if (topUntil > now) { + const targetBucket = topBucket ?? 'graphql'; + const existing = buckets[targetBucket]; + if (!existing || topUntil > existing.until) { + buckets[targetBucket] = { + ...existing, + until: topUntil, + updatedAt: Math.max(existing?.updatedAt ?? 0, updatedAt), + }; + } + } + + if (topUntil === 0 && !buckets.graphql && !buckets.rest) return null; + + return { + until: topUntil, + ...(topBucket ? { bucket: topBucket } : {}), + ...(reportedAt !== undefined ? { reportedAt } : {}), + updatedAt, + buckets, + }; +} + +async function readRateLimitFile(filePath, now) { + try { + const text = await fs.readFile(filePath, 'utf8'); + return parseSharedRateLimitPayload(JSON.parse(text), now); + } catch { + return null; + } +} + +async function writeRateLimitFileAtomic(filePath, payload) { + const dir = path.dirname(filePath); + const tmpFile = path.join( + dir, + `${RATE_LIMIT_FILENAME}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`, + ); + try { + const content = `${JSON.stringify(payload, null, 2)}\n`; + await fs.writeFile(tmpFile, content, { encoding: 'utf8', mode: 0o600 }); + await fs.chmod(tmpFile, 0o600).catch(() => undefined); + await fs.rename(tmpFile, filePath); + } catch { + await fs.unlink(tmpFile).catch(() => undefined); + } +} + +function mergeBucketState(existing, obs) { + const now = obs.now; + const obsUntil = obs.until !== undefined ? clampTimestampMs(obs.until, now) : undefined; + const obsResetAt = obs.resetAt !== undefined ? clampTimestampMs(obs.resetAt, now) : undefined; + const existingResetAt = existing?.resetAt ?? 0; + const windowAdvanced = + obsResetAt !== undefined && + obsResetAt > 0 && + existingResetAt > 0 && + obsResetAt > existingResetAt + SAME_WINDOW_TOLERANCE_MS; + if (!windowAdvanced && existing && existing.updatedAt > now) { + return existing; + } + const existingActiveUntil = !windowAdvanced && existing && existing.until > now ? existing.until : 0; + + let nextUntil = existingActiveUntil; + if (obsUntil !== undefined && obsUntil > now) { + nextUntil = Math.max(existingActiveUntil, obsUntil); + } else if (windowAdvanced) { + nextUntil = obsUntil && obsUntil > now ? obsUntil : 0; + } else if (obs.remaining !== undefined && obs.remaining > 0 && existingActiveUntil <= now) { + nextUntil = 0; + } + + const remaining = + obs.remaining !== undefined + ? Math.max(0, Math.floor(obs.remaining)) + : !windowAdvanced + ? existing?.remaining + : undefined; + const limit = + obs.limit !== undefined && obs.limit > 0 + ? Math.floor(obs.limit) + : !windowAdvanced + ? existing?.limit + : undefined; + const resetAt = + obsResetAt && obsResetAt > 0 + ? obsResetAt + : !windowAdvanced && existingResetAt > now + ? existingResetAt + : undefined; + + return { + until: nextUntil, + ...(remaining !== undefined ? { remaining } : {}), + ...(limit !== undefined ? { limit } : {}), + ...(resetAt !== undefined ? { resetAt } : {}), + updatedAt: now, + }; +} + +function buildSnapshot(existing, obs, ignoreBefore) { + const otherBucket = obs.bucket === 'graphql' ? 'rest' : 'graphql'; + const mergedBuckets = {}; + const existingOther = existing?.buckets?.[otherBucket]; + if (existingOther && existingOther.updatedAt >= ignoreBefore) { + mergedBuckets[otherBucket] = existingOther; + } + const previousBucket = existing?.buckets?.[obs.bucket]; + mergedBuckets[obs.bucket] = mergeBucketState( + previousBucket && previousBucket.updatedAt >= ignoreBefore ? previousBucket : undefined, + obs, + ); + + const graphqlUntil = mergedBuckets.graphql?.until ?? 0; + const topUntil = graphqlUntil > obs.now ? graphqlUntil : 0; + return { + until: topUntil, + ...(topUntil > 0 + ? { + bucket: 'graphql', + reportedAt: + existing?.buckets?.graphql?.until === topUntil + ? existing?.reportedAt ?? obs.now + : obs.now, + reportedBy: 'cindy-desktop', + summary: 'GitHub GraphQL API rate limit reached', + } + : {}), + updatedAt: obs.now, + buckets: mergedBuckets, + }; +} + +export class SharedRateLimitStore { + constructor(options = {}) { + this.stateDir = options.stateDir ?? null; + this.readCacheMs = Math.max(0, options.readCacheMs ?? DEFAULT_SHARED_READ_CACHE_MS); + this.writeThrottleMs = Math.max(0, options.writeThrottleMs ?? DEFAULT_SHARED_WRITE_THROTTLE_MS); + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.inFlightRead = null; + this.writeQueue = Promise.resolve(); + this.ignoreBefore = 0; + this.generation = 0; + this.lastWritten = new Map(); + } + + isCacheFresh(now) { + return now - this.lastReadAt < this.readCacheMs; + } + + readCached(now) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (now - this.lastReadAt >= this.readCacheMs && !this.inFlightRead) { + void this.refresh(now).catch(() => undefined); + } + return this.cachedSnapshot; + } + + async refresh(now, force = false) { + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath) return this.cachedSnapshot; + if (!force && now - this.lastReadAt < this.readCacheMs) { + return this.cachedSnapshot; + } + if (this.inFlightRead) return this.inFlightRead; + const readGeneration = this.generation; + const op = readRateLimitFile(filePath, now) + .then((snap) => { + if (readGeneration !== this.generation) return null; + this.cachedSnapshot = snap; + this.lastReadAt = now; + return snap; + }) + .finally(() => { + if (this.inFlightRead === op) this.inFlightRead = null; + }); + this.inFlightRead = op; + return op; + } + + _shouldWrite(obs) { + if (obs.immediate) return true; + const prev = this.lastWritten.get(obs.bucket); + if (!prev) return true; + const elapsed = obs.now - prev.at; + const windowChanged = + obs.resetAt !== undefined && + prev.resetAt !== undefined && + Math.abs(obs.resetAt - prev.resetAt) > SAME_WINDOW_TOLERANCE_MS; + if (windowChanged) return true; + if ( + obs.remaining !== undefined && + prev.remaining !== undefined && + elapsed >= SIGNIFICANT_DROP_MIN_INTERVAL_MS + ) { + const dropThreshold = Math.max(100, Math.floor((obs.limit ?? 5000) * 0.05)); + if (prev.remaining - obs.remaining >= dropThreshold) return true; + } + if (elapsed >= this.writeThrottleMs && (obs.remaining !== prev.remaining || obs.resetAt !== prev.resetAt)) { + return true; + } + return false; + } + + record(obs) { + const nextInMemory = buildSnapshot(this.cachedSnapshot, obs, this.ignoreBefore); + this.cachedSnapshot = nextInMemory; + this.lastReadAt = obs.now; + + const filePath = resolveRateLimitFilePath(this.stateDir); + if (!filePath || !this._shouldWrite(obs)) return Promise.resolve(); + + this.lastWritten.set(obs.bucket, { + at: obs.now, + remaining: obs.remaining, + resetAt: obs.resetAt, + until: obs.until ?? 0, + }); + + const writeGeneration = this.generation; + const ignoreBefore = this.ignoreBefore; + const run = async () => { + if (writeGeneration !== this.generation) return; + const dir = path.dirname(filePath); + await fs.mkdir(dir, { recursive: true, mode: 0o700 }); + await fs.chmod(dir, 0o700).catch(() => undefined); + const existing = await readRateLimitFile(filePath, obs.now); + if (writeGeneration !== this.generation) return; + const snapshot = buildSnapshot(existing, obs, ignoreBefore); + await writeRateLimitFileAtomic(filePath, snapshot); + if (writeGeneration !== this.generation) return; + if (obs.now >= this.lastReadAt) { + this.cachedSnapshot = snapshot; + this.lastReadAt = obs.now; + } + }; + + this.writeQueue = this.writeQueue.then(run).catch(() => undefined); + return this.writeQueue; + } + + flush() { + return this.writeQueue; + } + + getBucket(bucket, now) { + const snap = this.readCached(now); + const entry = snap?.buckets?.[bucket]; + if (!entry) return undefined; + if (this.ignoreBefore > 0 && entry.updatedAt < this.ignoreBefore) return undefined; + return entry; + } + + isRateLimited(bucket, now) { + const entry = this.getBucket(bucket, now); + return Boolean(entry && entry.until > now); + } + + getPressure(bucket, now) { + const entry = this.getBucket(bucket, now); + if (this.isRateLimited(bucket, now)) { + return { + level: 'exhausted', + ...(entry?.remaining !== undefined ? { remaining: entry.remaining } : {}), + ...(entry?.limit !== undefined ? { limit: entry.limit } : {}), + ...(entry?.resetAt !== undefined ? { resetAt: entry.resetAt } : entry?.until ? { resetAt: entry.until } : {}), + }; + } + if ( + !entry || + entry.remaining === undefined || + entry.limit === undefined || + (entry.resetAt !== undefined && entry.resetAt <= now) + ) { + return { level: 'normal' }; + } + return { + level: classifyQuotaPressure(entry.remaining, entry.limit), + remaining: entry.remaining, + limit: entry.limit, + ...(entry.resetAt !== undefined ? { resetAt: entry.resetAt } : {}), + }; + } + + /** Proactively switch to REST ETag when GraphQL is critical/exhausted and REST remains available. */ + shouldPreferRest(now) { + const gql = this.getPressure('graphql', now); + if (gql.level !== 'critical' && gql.level !== 'exhausted') return false; + const rest = this.getPressure('rest', now); + return rest.level !== 'exhausted'; + } + + clearMemoryCache(invalidatedAt) { + this.ignoreBefore = invalidatedAt; + this.generation += 1; + this.inFlightRead = null; + this.cachedSnapshot = null; + this.lastReadAt = -Infinity; + this.lastWritten.clear(); + } + + clearOnAccountSwitch(invalidatedAt) { + this.clearMemoryCache(invalidatedAt); + } +} + +export function createSharedRateLimitStore(options = {}) { + return new SharedRateLimitStore(options); +} diff --git a/questions/perf-github-api-budget/v1/reference/tests/smoke.test.mjs b/questions/perf-github-api-budget/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..6e165e1 --- /dev/null +++ b/questions/perf-github-api-budget/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,130 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +import { PrFollowWatch, computeDeferredBackoffMs } from '../src/pr-follow-watch.mjs'; +import { PrStatusService, prStatusKey } from '../src/pr-status-service.mjs'; +import { createSharedRateLimitStore, parseSharedRateLimitPayload } from '../src/shared-rate-limit.mjs'; + +function makeClock(start = 1_760_000_000_000) { + let t = start; + return { + now: () => t, + advance: (ms) => { + t += ms; + }, + }; +} + +test('PrStatusService fetches statuses, penetrates cache on refresh:true, and short-circuits 401', async () => { + const clock = makeClock(); + let calls = 0; + let restCalls = 0; + let title = 'Initial title'; + const gateway = { + async graphqlSingle(q) { + calls += 1; + if (q.prNumber === 401) { + const err = new Error('Unauthorized'); + err.status = 401; + throw err; + } + return { + remote: { + state: 'merged', + merged: true, + merged_at: new Date(clock.now() - 10_000).toISOString(), + head_sha: `sha-${calls}`, + title, + checks: 'success', + }, + }; + }, + async restGetPr() { + restCalls += 1; + throw new Error('should not call REST on 401'); + }, + }; + + const svc = new PrStatusService({ gateway, now: clock.now }); + const q = { owner: 'acme', repo: 'core', prNumber: 1 }; + const [first] = await svc.getStatuses([q]); + assert.equal(first.ok, true); + assert.equal(first.status, 'merged'); + + title = 'Updated after refresh'; + const [refreshed] = await svc.getStatuses([q], { refresh: true }); + assert.equal(refreshed.ok, true); + assert.equal(refreshed.title, 'Updated after refresh'); + + const authResults = await svc.getStatuses([ + { owner: 'acme', repo: 'core', prNumber: 401 }, + { owner: 'acme', repo: 'core', prNumber: 2 }, + ]); + assert.equal(authResults[0].ok, false); + assert.equal(authResults[0].reason, 'gh-not-logged-in'); + assert.equal(authResults[1].ok, false); + assert.equal(authResults[1].reason, 'gh-not-logged-in'); + assert.equal(restCalls, 0); +}); + +test('SharedRateLimitStore persists atomically, supports legacy until, and clears on account switch', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-rl-smoke-')); + try { + const now = 1_760_000_000_000; + const store = createSharedRateLimitStore({ stateDir: dir }); + await store.record({ + bucket: 'graphql', + remaining: 0, + limit: 5000, + resetAt: now + 300_000, + until: now + 300_000, + immediate: true, + now, + }); + await store.flush(); + + const files = await fs.readdir(dir); + assert.deepEqual(files, ['.rate-limit.json']); + const raw = JSON.parse(await fs.readFile(path.join(dir, '.rate-limit.json'), 'utf8')); + assert.equal(raw.until, now + 300_000); + assert.equal(raw.buckets.graphql.remaining, 0); + + const legacy = parseSharedRateLimitPayload({ until: now + 120_000 }, now); + assert.equal(legacy.buckets.graphql.until, now + 120_000); + + store.clearOnAccountSwitch(now + 1000); + assert.equal(store.isRateLimited('graphql', now + 1000), false); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('PrFollowWatch observes changes and computes bounded exponential backoff', async () => { + assert.equal(computeDeferredBackoffMs(1), 60_000); + assert.equal(computeDeferredBackoffMs(2), 120_000); + assert.equal(computeDeferredBackoffMs(5), 15 * 60_000); + + const clock = makeClock(); + const q = { owner: 'acme', repo: 'core', prNumber: 7 }; + const ran = []; + const watch = new PrFollowWatch({ + now: clock.now, + listSchedules: () => [ + { id: 's1', prKey: prStatusKey(q), prQuery: q, targetSessionId: 'sess-1', createdAt: clock.now() - 10_000, active: true, expired: false }, + ], + runSchedule: async (s) => { + ran.push(s.id); + return { deferred: false }; + }, + }); + + const o1 = watch.observe(q, { ok: true, status: 'open', headSha: 'a', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '1' }); + assert.equal(o1.changed, false); + const o2 = watch.observe(q, { ok: true, status: 'open', headSha: 'b', checks: 'pending', unresolvedCount: 0, reviewDecision: null, updatedAt: '2' }); + assert.equal(o2.changed, true); + await watch.triggerPr(q, o2); + assert.deepEqual(ran, ['s1']); +}); diff --git a/questions/perf-jsonl-hotpaths/v1/author/editable.json b/questions/perf-jsonl-hotpaths/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/perf-jsonl-hotpaths/v1/author/evaluator.mjs b/questions/perf-jsonl-hotpaths/v1/author/evaluator.mjs new file mode 100644 index 0000000..803a15c --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/author/evaluator.mjs @@ -0,0 +1,264 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { performance } from 'node:perf_hooks'; +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir, baseDir] = process.argv.slice(2); +const load = async (dir) => { + const [acp, pi, payload] = await Promise.all([ + import(pathToFileURL(path.join(dir, 'acp-line-decoder.mjs')).href), + import(pathToFileURL(path.join(dir, 'pi-jsonl-reader.mjs')).href), + import(pathToFileURL(path.join(dir, 'payload-parser.mjs')).href), + ]); + return { acp, pi, payload }; +}; + +const sub = await load(subDir); +const base = await load(baseDir); + +function checkFramingCorrectness() { + // 1. ACP: multi-byte UTF-8 split across Uint8Array chunks, CRLF split across chunks, empty line skip, trailing flush. + { + const expected = []; + const actual = []; + const dBase = new base.acp.AcpLineDecoder((l) => expected.push(l), 64); + const dSub = new sub.acp.AcpLineDecoder((l) => actual.push(l), 64); + const utf8 = Buffer.from('{"msg":"你好🚀世界"}\r\n \r\n{"k":"v"}', 'utf8'); + // Split mid-emoji and right between \r and \n. + const cuts = [0, 10, 12, 14, 15, 19, 20, 21, 22, utf8.length]; + for (let i = 0; i < cuts.length - 1; i += 1) { + const slice = utf8.subarray(cuts[i], cuts[i + 1]); + dBase.push(slice); + dSub.push(slice); + } + dBase.flush(); + dSub.flush(); + assert.deepEqual(actual, expected); + assert.deepEqual(actual, ['{"msg":"你好🚀世界"}', '{"k":"v"}']); + } + + // 2. ACP: AcpLineTooLongError thrown across multiple newline-free chunks & clean recovery after error. + { + const lines = []; + const d = new sub.acp.AcpLineDecoder((l) => lines.push(l), 20); + d.push('1234567890'); + d.push('1234567890'); + assert.throws(() => d.push('X'), (e) => e instanceof sub.acp.AcpLineTooLongError && e.limit === 20); + // Recovery after oversized error. + d.push('{"recovered":true}\n'); + d.flush(); + assert.deepEqual(lines, ['{"recovered":true}']); + } + + // 3. ACP: exact limit with trailing \r\n should NOT throw. + { + const lines = []; + const d = new sub.acp.AcpLineDecoder((l) => lines.push(l), 20); + d.push('a'.repeat(19)); + d.push('\r\n'); + d.flush(); + assert.deepEqual(lines, ['a'.repeat(19)]); + } + + // 4. Pi: multi-byte UTF-8 split, CRLF split, empty lines preserved, oversized multi-chunk resync + decoder reset! + { + const runPiCase = (mod) => { + const s = new EventEmitter(); + const lines = []; + let oversized = 0; + mod.attachJsonlReader(s, (l) => lines.push(l), () => { oversized += 1; }, 24); + const first = Buffer.from('{"a":"中文🎯"}\r\n\n', 'utf8'); + s.emit('data', first.subarray(0, 8)); + s.emit('data', first.subarray(8, 15)); + s.emit('data', first.subarray(15)); + // Oversized line split across chunks ending with a truncated UTF-8 lead byte before newline! + const badTail = Buffer.concat([Buffer.from('x'.repeat(20)), Buffer.from([0xF0, 0x9F])]); + s.emit('data', Buffer.from('y'.repeat(15))); + s.emit('data', badTail); + s.emit('data', Buffer.from('zzz\n{"ok":"正常"}\n')); + // Single-chunk oversized complete line followed immediately by a valid line. + s.emit('data', Buffer.from('z'.repeat(30) + '\n{"after":2}\r')); + s.emit('data', Buffer.from('\n{"tail":3}')); + // Stream error must not throw. + s.emit('error', new Error('ignore')); + s.emit('end'); + return { lines, oversized }; + }; + const exp = runPiCase(base.pi); + const act = runPiCase(sub.pi); + assert.deepEqual(act, exp); + assert.equal(act.oversized, 2); + assert.ok(act.lines.includes('{"ok":"正常"}')); + assert.ok(act.lines.includes('{"tail":3}')); + } + + // 5. Pi: exact payload equality on a 2 MiB multi-chunk frame. + { + const body = `{"big":"${'ABCD'.repeat(512 * 1024)}"}`; + const buf = Buffer.from(body + '\r\n', 'utf8'); + const s = new EventEmitter(); + const out = []; + sub.pi.attachJsonlReader(s, (l) => out.push(l)); + for (let o = 0; o < buf.length; o += 65536) s.emit('data', buf.subarray(o, o + 65536)); + s.emit('end'); + assert.equal(out.length, 1); + assert.equal(out[0], body); + } +} + +function checkPayloadCorrectness() { + const cases = [ + undefined, + '', + ' \t\r\n ', + 'Exit code 0\nDone', + 'Task #3 created successfully: Step 3', + '[1, 2, 3]', + '"just a json string"', + '12345', + 'true', + 'null', + '{malformed json', + ' \t\r\n {"taskId":"42","status":"completed"} ', + '\f{"nonRfcWhitespace":true}', + '\uFEFF{"bom":true}', + JSON.stringify({ ok: true, result: { xdt_card_id: 'c-1', xdt_card_turn_end: true, _xdt_render_image: false, xdt_media_inline: true, xdt_image_url: 'xdt-image://inner', xdt_video_url: 'xdt-video://inner' } }), + JSON.stringify({ ok: true, xdt_image_url: 'xdt-image://outer', result: { xdt_media_inline: true, xdt_image_url: 'xdt-image://inner', xdt_video_url: 'xdt-video://inner' } }), + JSON.stringify({ ok: false, result: { xdt_card_id: 'should-not-unwrap', xdt_card_turn_end: true } }), + JSON.stringify({ ok: true, result: [1, 2, 3], xdt_card_id: 'outer-card', xdt_card_turn_end: true }), + JSON.stringify({ ok: true, result: { xdt_card_id: 'x'.repeat(129), xdt_card_turn_end: true } }), + JSON.stringify({ ok: true, result: { xdt_card_id: '', xdt_card_turn_end: true } }), + ]; + + for (const input of cases) { + assert.deepEqual(sub.payload.tryParseJsonRecord(input), base.payload.tryParseJsonRecord(input), `tryParseJsonRecord mismatch for ${JSON.stringify(input)}`); + if (typeof input === 'string') { + assert.deepEqual(sub.payload.parseToolResultPayload(input), base.payload.parseToolResultPayload(input), `parseToolResultPayload mismatch for ${JSON.stringify(input)}`); + assert.deepEqual(sub.payload.extractPayloadTurnEndCardIds(input), base.payload.extractPayloadTurnEndCardIds(input), `extractPayloadTurnEndCardIds mismatch for ${JSON.stringify(input)}`); + } + } +} + +let correctness_framing = false; +let correctness_payload = false; +const errors = []; + +try { checkFramingCorrectness(); correctness_framing = true; } catch (e) { errors.push('framing: ' + e.message); } +try { checkPayloadCorrectness(); correctness_payload = true; } catch (e) { errors.push('payload: ' + e.message); } + +// Build deterministic workloads. +const PIPE_CHUNK = 64 * 1024; +function chunked(buf, size) { + const out = []; + for (let o = 0; o < buf.length; o += size) out.push(buf.subarray(o, o + size)); + return out; +} +const frame12m = chunked(Buffer.from(`{"type":"response","data":"${'QUJD'.repeat(3 * 1024 * 1024)}"}\n`, 'utf8'), PIPE_CHUNK); +const small20k = (() => { + const rows = []; + for (let i = 0; i < 20000; i += 1) rows.push(`{"type":"message_update","seq":${i},"delta":"token-${i}"}`); + return chunked(Buffer.from(rows.join('\n') + '\n', 'utf8'), PIPE_CHUNK); +})(); +const toolResults = (() => { + const rows = []; + for (let i = 0; i < 1200; i += 1) { + if (i % 10 === 0) rows.push(JSON.stringify({ ok: true, result: { xdt_card_id: `card-${i}`, xdt_card_turn_end: i % 20 === 0, summary: 'Saved.' } })); + else if (i % 3 === 0) rows.push(` 1\timport { describe } from 'vitest';\n${' 2\tconst value = compute(input);\n'.repeat(60)}`); + else if (i % 3 === 1) rows.push(`Task #${i} created successfully: Step ${i}`); + else rows.push(`Exit code 0\n${'added 1 package, audited 812 packages in 2s\n'.repeat(10)}`); + } + return rows; +})(); + +const runPi = (mod, chunks) => { + const s = new EventEmitter(); + let total = 0; + mod.attachJsonlReader(s, (l) => { total += l.length; }); + for (const c of chunks) s.emit('data', c); + s.emit('end'); + return total; +}; +const runAcp = (mod, chunks) => { + let total = 0; + const d = new mod.AcpLineDecoder((l) => { total += l.length; }); + for (const c of chunks) d.push(c); + d.flush(); + return total; +}; +const runPayload = (mod) => { + let hits = 0; + for (let r = 0; r < 4; r += 1) { + for (const text of toolResults) { + if (mod.parseToolResultPayload(text)) hits += 1; + hits += mod.extractPayloadTurnEndCardIds(text).length; + if (mod.tryParseJsonRecord(text)) hits += 1; + } + } + return hits; +}; + +function interleavedSpeedup(baseFn, subFn, rounds = 7, warmups = 3) { + // Warmup both to stabilize V8 JIT tiers and avoid first-call GC jitter. + const bCheck = baseFn(); + const sCheck = subFn(); + assert.equal(sCheck, bCheck, 'Benchmark output checksum mismatch'); + for (let w = 1; w < warmups; w += 1) { + baseFn(); + subFn(); + } + const ratios = []; + for (let i = 0; i < rounds; i += 1) { + const order = i % 2 === 0; + let bMs, sMs; + if (order) { + const t0 = trusted.now(); baseFn(); bMs = trusted.now() - t0; + const t1 = trusted.now(); subFn(); sMs = trusted.now() - t1; + } else { + const t1 = trusted.now(); subFn(); sMs = trusted.now() - t1; + const t0 = trusted.now(); baseFn(); bMs = trusted.now() - t0; + } + ratios.push(bMs / Math.max(sMs, 0.01)); + } + ratios.sort((a, b) => a - b); + return Number(ratios[Math.floor(ratios.length / 2)].toFixed(2)); +} + +const runBatch = (fn, reps) => { + let acc = 0; + for (let i = 0; i < reps; i += 1) acc += fn(); + return acc; +}; + +let pi_12mb_speedup = 1; +let acp_12mb_speedup = 1; +let payload_speedup = 1; +let small_frame_guard = false; +let smallPiRatio = 0; +let smallAcpRatio = 0; + +if (correctness_framing && correctness_payload) { + try { + // Repeat small20k 40x per sample (~20-35 ms) so sub-ms JIT/GC jitter cannot false-fail the guard. + smallPiRatio = interleavedSpeedup(() => runBatch(() => runPi(base.pi, small20k), 40), () => runBatch(() => runPi(sub.pi, small20k), 40), 7, 3); + smallAcpRatio = interleavedSpeedup(() => runBatch(() => runAcp(base.acp, small20k), 40), () => runBatch(() => runAcp(sub.acp, small20k), 40), 7, 3); + // Allow up to ~35% margin on 20k tiny frames (ratio >= 0.65). + small_frame_guard = smallPiRatio >= 0.65 && smallAcpRatio >= 0.65; + pi_12mb_speedup = interleavedSpeedup(() => runPi(base.pi, frame12m), () => runPi(sub.pi, frame12m), 7, 2); + acp_12mb_speedup = interleavedSpeedup(() => runAcp(base.acp, frame12m), () => runAcp(sub.acp, frame12m), 7, 2); + payload_speedup = interleavedSpeedup(() => runBatch(() => runPayload(base.payload), 2), () => runBatch(() => runPayload(sub.payload), 2), 7, 3); + } catch (e) { + errors.push('bench: ' + e.message); + } +} + +trusted.emit(({ + status: 'graded', + items: { correctness_framing, correctness_payload, small_frame_guard }, + metrics: { pi_12mb_speedup, acp_12mb_speedup, payload_speedup }, + details: { errors, smallPiRatio, smallAcpRatio }, +})); diff --git a/questions/perf-jsonl-hotpaths/v1/author/grade.py b/questions/perf-jsonl-hotpaths/v1/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/perf-jsonl-hotpaths/v1/author/grade_impl.py b/questions/perf-jsonl-hotpaths/v1/author/grade_impl.py new file mode 100644 index 0000000..296ae37 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/author/grade_impl.py @@ -0,0 +1,42 @@ +"""Isolated pure-Node quantitative grader: runs correctness gates + interleaved A/B benchmarks.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-p2-grade-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + base_src = tmp / 'base_src' + shutil.copytree(submission_root / 'src', sub_src) + shutil.copytree(Q / 'candidate' / 'src', base_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src), str(base_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/perf-jsonl-hotpaths/v1/author/result-channel.mjs b/questions/perf-jsonl-hotpaths/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/CONTRACT.md b/questions/perf-jsonl-hotpaths/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..70f9167 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/CONTRACT.md @@ -0,0 +1,32 @@ +# Product & Protocol Contract + +## 1. ACP Line Decoder (`src/acp-line-decoder.mjs`) + +- Exports `ACP_DEFAULT_MAX_LINE_CHARS` (`32 * 1024 * 1024`), `AcpLineTooLongError`, and `AcpLineDecoder`. +- `new AcpLineDecoder(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS)` incrementally splits `string` or `Uint8Array` chunks on `\n`. +- Strips a single trailing `\r` before `\n` (including when `\r` and `\n` arrive in adjacent chunks). +- Handles multi-byte UTF-8 sequences split across `Uint8Array` chunk boundaries cleanly. +- Skips empty or whitespace-only lines (`line.trim().length === 0`). +- `flush()` decodes any buffered UTF-8 tail and emits the final non-empty line if present, clearing internal state. +- If a single incomplete line grows past `maxLineChars`, clears the pending buffer and throws `AcpLineTooLongError(maxLineChars)` so subsequent calls start cleanly. + +## 2. Pi JSONL Reader (`src/pi-jsonl-reader.mjs`) + +- Exports `MAX_JSONL_BUFFER_CHARS` (`16 * 1024 * 1024`) and `attachJsonlReader(stream, onLine, onOversizedFrame?, maxBufferChars = MAX_JSONL_BUFFER_CHARS)`. +- Listens to `data`, `end`, and `error` on a Node readable stream (`Buffer | string` chunks). +- Emits every newline-delimited line (stripping a single trailing `\r`), including empty lines between `\n` delimiters; on `end`, emits any non-empty trailing buffer `<= maxBufferChars` (stripping a trailing `\r`). +- Handles multi-byte UTF-8 sequences split across `Buffer` chunks. +- **Oversized frame handling**: + - If an incomplete line exceeds `maxBufferChars` without a newline, enters oversized-skip mode, invokes `onOversizedFrame?.()` once for that oversized line, discards buffered data until the next `\n`, and **resets the UTF-8 `StringDecoder`** so truncated multi-byte bytes from the discarded frame never corrupt subsequent valid frames. + - If a complete line ending in `\n` has length `> maxBufferChars`, invokes `onOversizedFrame?.()` and discards that line while continuing to emit subsequent lines in the same chunk. +- Attaches a no-op `error` listener on `stream` so unhandled stream errors do not crash the process. + +## 3. Tool & Task Payload Parser (`src/payload-parser.mjs`) + +- Exports `projectToolResultPresentation`, `parseToolResultPayload`, `extractPayloadTurnEndCardIds`, and `tryParseJsonRecord`. +- `tryParseJsonRecord(text)`: returns a plain non-array JSON object record when `text` parses as a JSON object; returns `null` for `undefined`, empty strings, plain text, JSON arrays, JSON primitives, or malformed JSON. +- `parseToolResultPayload(text)`: parses `text` as a JSON object and applies `projectToolResultPresentation(outer)`: + - When `outer.ok === true` and `outer.result` is a plain non-array object, merges `{ ...inner, ...outer }` (preserving `_xdt_render_image: false` if set on `inner`, and deleting `xdt_image_url`/`xdt_video_url` when `inner.xdt_media_inline === true` unless `outer` owns them directly). + - Otherwise returns `outer`. + - Returns `null` if `text` is not a valid JSON object (must handle leading RFC 8259 whitespace: space, `\t`, `\n`, `\r`). +- `extractPayloadTurnEndCardIds(text)`: returns `[parsed.xdt_card_id]` if `parsed.xdt_card_turn_end === true` and `parsed.xdt_card_id` is a non-empty string with length `<= 128`; otherwise `[]`. diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/ENVIRONMENT.md b/questions/perf-jsonl-hotpaths/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..688aa05 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,7 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke checks + - `npm run bench` — representative large-frame, small-frame, and payload-parsing workloads diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/TASK.md b/questions/perf-jsonl-hotpaths/v1/candidate/TASK.md new file mode 100644 index 0000000..6b62abb --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/TASK.md @@ -0,0 +1,18 @@ +# Task + +You are optimizing three hot paths extracted from Cindy's agent runtime and message projection pipeline. + +## Observed Production Symptoms + +1. **Large agent stdout frames stall the main thread**: Child agent processes emit newline-delimited JSON (JSONL) over stdout in ~64 KiB pipe chunks. When a single frame reaches 4–12 MiB (for example, history entries or tool outputs containing images/diffs), both the Pi JSONL reader (`src/pi-jsonl-reader.mjs`) and ACP line decoder (`src/acp-line-decoder.mjs`) stall the event loop for hundreds of milliseconds. +2. **Repeated plain-text payload parsing dominates long-session refreshes**: During live streaming flushes and transcript normalization, `src/payload-parser.mjs` scans hundreds to thousands of tool results and Task records where ~90% are plain text rather than JSON objects, consuming disproportionate CPU time. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with all framing, error, resync, UTF-8, whitespace, and payload-projection invariants defined in `CONTRACT.md`. +- Do not regress throughput on high-frequency small JSONL frames (e.g. 20,000 small lines). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/bench/workload.mjs b/questions/perf-jsonl-hotpaths/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..c3acfaf --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/bench/workload.mjs @@ -0,0 +1,76 @@ +import { EventEmitter } from 'node:events'; +import { performance } from 'node:perf_hooks'; + +import { AcpLineDecoder } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +const PIPE_CHUNK = 64 * 1024; +function chunked(payload, size) { + const out = []; + for (let offset = 0; offset < payload.length; offset += size) out.push(payload.subarray(offset, offset + size)); + return out; +} +function frame(chars) { + return Buffer.from(`{"type":"response","data":"${'QUJD'.repeat(Math.ceil(chars / 4)).slice(0, chars)}"}\n`, 'utf8'); +} +function toolResults(count) { + const rows = []; + for (let i = 0; i < count; i += 1) { + if (i % 10 === 0) rows.push(JSON.stringify({ ok: true, result: { xdt_card_id: `card-${i}`, xdt_card_turn_end: i % 20 === 0 } })); + else if (i % 3 === 0) rows.push(` 1\timport { describe } from 'vitest';\n${' 2\tconst value = compute(input);\n'.repeat(60)}`); + else if (i % 3 === 1) rows.push(`Task #${i} created successfully: Step ${i}`); + else rows.push(`Exit code 0\n${'added 1 package, audited 812 packages in 2s\n'.repeat(10)}`); + } + return rows; +} + +function measure(fn, runs = 3) { + fn(); + const times = []; + for (let i = 0; i < runs; i += 1) { + const t0 = performance.now(); + fn(); + times.push(performance.now() - t0); + } + times.sort((a, b) => a - b); + return times[Math.floor(times.length / 2)]; +} + +const chunks12m = chunked(frame(12 * 1024 * 1024), PIPE_CHUNK); +const payloads = toolResults(1200); + +const piMs = measure(() => { + const s = new EventEmitter(); + let total = 0; + attachJsonlReader(s, (l) => { total += l.length; }); + for (const c of chunks12m) s.emit('data', c); + s.emit('end'); + return total; +}); + +const acpMs = measure(() => { + let total = 0; + const d = new AcpLineDecoder((l) => { total += l.length; }); + for (const c of chunks12m) d.push(c); + d.flush(); + return total; +}); + +const payloadMs = measure(() => { + let hits = 0; + for (let round = 0; round < 4; round += 1) { + for (const text of payloads) { + if (parseToolResultPayload(text)) hits += 1; + hits += extractPayloadTurnEndCardIds(text).length; + if (tryParseJsonRecord(text)) hits += 1; + } + } + return hits; +}); + +console.log(JSON.stringify({ pi12MiB_ms: Number(piMs.toFixed(2)), acp12MiB_ms: Number(acpMs.toFixed(2)), payload_ms: Number(payloadMs.toFixed(2)) }, null, 2)); diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/package.json b/questions/perf-jsonl-hotpaths/v1/candidate/package.json new file mode 100644 index 0000000..a74c291 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-jsonl-hotpaths", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/src/acp-line-decoder.mjs b/questions/perf-jsonl-hotpaths/v1/candidate/src/acp-line-decoder.mjs new file mode 100644 index 0000000..9c7f9fa --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/src/acp-line-decoder.mjs @@ -0,0 +1,53 @@ +/** + * Extracted verbatim from makecindy/cindy (Apache-2.0), baseline before PR #15565: + * packages/maker-core/src/agents/acp/line-transport.ts + */ + +export const ACP_DEFAULT_MAX_LINE_CHARS = 32 * 1024 * 1024; + +export class AcpLineTooLongError extends Error { + constructor(limit) { + super(`ACP message exceeded ${limit} characters`); + this.name = 'AcpLineTooLongError'; + this.limit = limit; + } +} + +export class AcpLineDecoder { + #buffer = ''; + #decoder = new TextDecoder('utf-8'); + #onLine; + #maxLineChars; + + constructor(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS) { + this.#onLine = onLine; + this.#maxLineChars = maxLineChars; + } + + push(chunk) { + this.#buffer += typeof chunk === 'string' ? chunk : this.#decoder.decode(chunk, { stream: true }); + let newline = this.#buffer.indexOf('\n'); + while (newline !== -1) { + const line = this.#buffer.slice(0, newline); + this.#buffer = this.#buffer.slice(newline + 1); + this.#emit(line); + newline = this.#buffer.indexOf('\n'); + } + if (this.#buffer.length > this.#maxLineChars) { + this.#buffer = ''; + throw new AcpLineTooLongError(this.#maxLineChars); + } + } + + flush() { + this.#buffer += this.#decoder.decode(); + const rest = this.#buffer; + this.#buffer = ''; + this.#emit(rest); + } + + #emit(raw) { + const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw; + if (line.trim().length > 0) this.#onLine(line); + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/src/payload-parser.mjs b/questions/perf-jsonl-hotpaths/v1/candidate/src/payload-parser.mjs new file mode 100644 index 0000000..b4fe251 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/src/payload-parser.mjs @@ -0,0 +1,54 @@ +/** + * Extracted verbatim from makecindy/cindy (Apache-2.0), baseline before PR #15565: + * packages/maker-shared/src/payloadSummary.ts, toolResultCompaction.ts, messageRender.ts + */ + +function readRecord(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : null; +} + +export function projectToolResultPresentation(outer) { + const result = outer.result; + if (outer.ok !== true || result === null || typeof result !== 'object' || Array.isArray(result)) return outer; + const inner = result; + const projected = { + ...inner, + ...outer, + ...(inner._xdt_render_image === false ? { _xdt_render_image: false } : {}), + }; + if (inner.xdt_media_inline === true) { + if (!Object.hasOwn(outer, 'xdt_image_url')) delete projected.xdt_image_url; + if (!Object.hasOwn(outer, 'xdt_video_url')) delete projected.xdt_video_url; + } + return projected; +} + +function parsePayloadJsonObject(value) { + try { + return readRecord(JSON.parse(value)); + } catch { + return null; + } +} + +export function tryParseJsonRecord(text) { + if (!text) return null; + try { + return readRecord(JSON.parse(text)); + } catch { + return null; + } +} + +export function parseToolResultPayload(text) { + const outer = parsePayloadJsonObject(text); + return outer ? projectToolResultPresentation(outer) : null; +} + +export function extractPayloadTurnEndCardIds(text) { + const parsed = parseToolResultPayload(text); + return parsed?.xdt_card_turn_end === true && typeof parsed.xdt_card_id === 'string' + && parsed.xdt_card_id.length > 0 && parsed.xdt_card_id.length <= 128 + ? [parsed.xdt_card_id] + : []; +} diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/src/pi-jsonl-reader.mjs b/questions/perf-jsonl-hotpaths/v1/candidate/src/pi-jsonl-reader.mjs new file mode 100644 index 0000000..fb46d13 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/src/pi-jsonl-reader.mjs @@ -0,0 +1,78 @@ +/** + * Extracted verbatim from makecindy/cindy (Apache-2.0), baseline before PR #15565: + * packages/maker-core/src/agents/pi/transport.ts + */ +import { StringDecoder } from 'node:string_decoder'; + +export const MAX_JSONL_BUFFER_CHARS = 16 * 1024 * 1024; + +export function attachJsonlReader( + stream, + onLine, + onOversizedFrame, + maxBufferChars = MAX_JSONL_BUFFER_CHARS, +) { + let decoder = new StringDecoder('utf8'); + let buffer = ''; + let skippingOversizedLine = false; + + const resetDecoder = () => { + decoder = new StringDecoder('utf8'); + }; + + const dropThroughNewline = () => { + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + buffer = ''; + resetDecoder(); + return false; + } + buffer = buffer.slice(newlineIndex + 1); + skippingOversizedLine = false; + return true; + }; + + const emitCompleteLines = () => { + while (true) { + if (skippingOversizedLine) { + if (!dropThroughNewline()) return; + continue; + } + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + if (buffer.length > maxBufferChars) { + skippingOversizedLine = true; + onOversizedFrame?.(); + dropThroughNewline(); + } + return; + } + if (newlineIndex > maxBufferChars) { + onOversizedFrame?.(); + buffer = buffer.slice(newlineIndex + 1); + continue; + } + let line = buffer.slice(0, newlineIndex); + buffer = buffer.slice(newlineIndex + 1); + if (line.endsWith('\r')) line = line.slice(0, -1); + onLine(line); + } + }; + + stream.on('data', (chunk) => { + buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk); + emitCompleteLines(); + }); + + stream.on('end', () => { + buffer += decoder.end(); + emitCompleteLines(); + if (!skippingOversizedLine && buffer.length > 0 && buffer.length <= maxBufferChars) { + onLine(buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer); + } + }); + + stream.on('error', () => { + /* Handled by upper transport layer. */ + }); +} diff --git a/questions/perf-jsonl-hotpaths/v1/candidate/tests/smoke.test.mjs b/questions/perf-jsonl-hotpaths/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..b89b1ac --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; + +import { AcpLineDecoder, AcpLineTooLongError } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +test('AcpLineDecoder frames lines and handles CRLF and limit errors', () => { + const lines = []; + const decoder = new AcpLineDecoder((line) => lines.push(line), 32); + decoder.push(Buffer.from('{"a":1}\r\n\n{"b":2}')); + decoder.flush(); + assert.deepEqual(lines, ['{"a":1}', '{"b":2}']); + assert.throws(() => decoder.push('x'.repeat(40)), AcpLineTooLongError); +}); + +test('attachJsonlReader frames chunked UTF-8 and resyncs oversized lines', () => { + const stream = new EventEmitter(); + const lines = []; + let oversized = 0; + attachJsonlReader(stream, (l) => lines.push(l), () => { oversized += 1; }, 32); + stream.emit('data', Buffer.from('{"ok":true}\r\n')); + stream.emit('data', Buffer.from('x'.repeat(40) + '\n{"next":1}\n')); + stream.emit('end'); + assert.deepEqual(lines, ['{"ok":true}', '{"next":1}']); + assert.equal(oversized, 1); +}); + +test('payload parser handles envelopes, turn-end cards, and plain text', () => { + const env = JSON.stringify({ ok: true, result: { xdt_card_id: 'c1', xdt_card_turn_end: true } }); + assert.deepEqual(extractPayloadTurnEndCardIds(env), ['c1']); + assert.equal(parseToolResultPayload('Exit code 0\nDone'), null); + assert.deepEqual(tryParseJsonRecord(' {"taskId":"3"}'), { taskId: '3' }); + assert.equal(tryParseJsonRecord('Task #3 created successfully'), null); +}); diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/CONTRACT.md b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..70f9167 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,32 @@ +# Product & Protocol Contract + +## 1. ACP Line Decoder (`src/acp-line-decoder.mjs`) + +- Exports `ACP_DEFAULT_MAX_LINE_CHARS` (`32 * 1024 * 1024`), `AcpLineTooLongError`, and `AcpLineDecoder`. +- `new AcpLineDecoder(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS)` incrementally splits `string` or `Uint8Array` chunks on `\n`. +- Strips a single trailing `\r` before `\n` (including when `\r` and `\n` arrive in adjacent chunks). +- Handles multi-byte UTF-8 sequences split across `Uint8Array` chunk boundaries cleanly. +- Skips empty or whitespace-only lines (`line.trim().length === 0`). +- `flush()` decodes any buffered UTF-8 tail and emits the final non-empty line if present, clearing internal state. +- If a single incomplete line grows past `maxLineChars`, clears the pending buffer and throws `AcpLineTooLongError(maxLineChars)` so subsequent calls start cleanly. + +## 2. Pi JSONL Reader (`src/pi-jsonl-reader.mjs`) + +- Exports `MAX_JSONL_BUFFER_CHARS` (`16 * 1024 * 1024`) and `attachJsonlReader(stream, onLine, onOversizedFrame?, maxBufferChars = MAX_JSONL_BUFFER_CHARS)`. +- Listens to `data`, `end`, and `error` on a Node readable stream (`Buffer | string` chunks). +- Emits every newline-delimited line (stripping a single trailing `\r`), including empty lines between `\n` delimiters; on `end`, emits any non-empty trailing buffer `<= maxBufferChars` (stripping a trailing `\r`). +- Handles multi-byte UTF-8 sequences split across `Buffer` chunks. +- **Oversized frame handling**: + - If an incomplete line exceeds `maxBufferChars` without a newline, enters oversized-skip mode, invokes `onOversizedFrame?.()` once for that oversized line, discards buffered data until the next `\n`, and **resets the UTF-8 `StringDecoder`** so truncated multi-byte bytes from the discarded frame never corrupt subsequent valid frames. + - If a complete line ending in `\n` has length `> maxBufferChars`, invokes `onOversizedFrame?.()` and discards that line while continuing to emit subsequent lines in the same chunk. +- Attaches a no-op `error` listener on `stream` so unhandled stream errors do not crash the process. + +## 3. Tool & Task Payload Parser (`src/payload-parser.mjs`) + +- Exports `projectToolResultPresentation`, `parseToolResultPayload`, `extractPayloadTurnEndCardIds`, and `tryParseJsonRecord`. +- `tryParseJsonRecord(text)`: returns a plain non-array JSON object record when `text` parses as a JSON object; returns `null` for `undefined`, empty strings, plain text, JSON arrays, JSON primitives, or malformed JSON. +- `parseToolResultPayload(text)`: parses `text` as a JSON object and applies `projectToolResultPresentation(outer)`: + - When `outer.ok === true` and `outer.result` is a plain non-array object, merges `{ ...inner, ...outer }` (preserving `_xdt_render_image: false` if set on `inner`, and deleting `xdt_image_url`/`xdt_video_url` when `inner.xdt_media_inline === true` unless `outer` owns them directly). + - Otherwise returns `outer`. + - Returns `null` if `text` is not a valid JSON object (must handle leading RFC 8259 whitespace: space, `\t`, `\n`, `\r`). +- `extractPayloadTurnEndCardIds(text)`: returns `[parsed.xdt_card_id]` if `parsed.xdt_card_turn_end === true` and `parsed.xdt_card_id` is a non-empty string with length `<= 128`; otherwise `[]`. diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/ENVIRONMENT.md b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..688aa05 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,7 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke checks + - `npm run bench` — representative large-frame, small-frame, and payload-parsing workloads diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/TASK.md b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..6b62abb --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/TASK.md @@ -0,0 +1,18 @@ +# Task + +You are optimizing three hot paths extracted from Cindy's agent runtime and message projection pipeline. + +## Observed Production Symptoms + +1. **Large agent stdout frames stall the main thread**: Child agent processes emit newline-delimited JSON (JSONL) over stdout in ~64 KiB pipe chunks. When a single frame reaches 4–12 MiB (for example, history entries or tool outputs containing images/diffs), both the Pi JSONL reader (`src/pi-jsonl-reader.mjs`) and ACP line decoder (`src/acp-line-decoder.mjs`) stall the event loop for hundreds of milliseconds. +2. **Repeated plain-text payload parsing dominates long-session refreshes**: During live streaming flushes and transcript normalization, `src/payload-parser.mjs` scans hundreds to thousands of tool results and Task records where ~90% are plain text rather than JSON objects, consuming disproportionate CPU time. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with all framing, error, resync, UTF-8, whitespace, and payload-projection invariants defined in `CONTRACT.md`. +- Do not regress throughput on high-frequency small JSONL frames (e.g. 20,000 small lines). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/bench/workload.mjs b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..c3acfaf --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,76 @@ +import { EventEmitter } from 'node:events'; +import { performance } from 'node:perf_hooks'; + +import { AcpLineDecoder } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +const PIPE_CHUNK = 64 * 1024; +function chunked(payload, size) { + const out = []; + for (let offset = 0; offset < payload.length; offset += size) out.push(payload.subarray(offset, offset + size)); + return out; +} +function frame(chars) { + return Buffer.from(`{"type":"response","data":"${'QUJD'.repeat(Math.ceil(chars / 4)).slice(0, chars)}"}\n`, 'utf8'); +} +function toolResults(count) { + const rows = []; + for (let i = 0; i < count; i += 1) { + if (i % 10 === 0) rows.push(JSON.stringify({ ok: true, result: { xdt_card_id: `card-${i}`, xdt_card_turn_end: i % 20 === 0 } })); + else if (i % 3 === 0) rows.push(` 1\timport { describe } from 'vitest';\n${' 2\tconst value = compute(input);\n'.repeat(60)}`); + else if (i % 3 === 1) rows.push(`Task #${i} created successfully: Step ${i}`); + else rows.push(`Exit code 0\n${'added 1 package, audited 812 packages in 2s\n'.repeat(10)}`); + } + return rows; +} + +function measure(fn, runs = 3) { + fn(); + const times = []; + for (let i = 0; i < runs; i += 1) { + const t0 = performance.now(); + fn(); + times.push(performance.now() - t0); + } + times.sort((a, b) => a - b); + return times[Math.floor(times.length / 2)]; +} + +const chunks12m = chunked(frame(12 * 1024 * 1024), PIPE_CHUNK); +const payloads = toolResults(1200); + +const piMs = measure(() => { + const s = new EventEmitter(); + let total = 0; + attachJsonlReader(s, (l) => { total += l.length; }); + for (const c of chunks12m) s.emit('data', c); + s.emit('end'); + return total; +}); + +const acpMs = measure(() => { + let total = 0; + const d = new AcpLineDecoder((l) => { total += l.length; }); + for (const c of chunks12m) d.push(c); + d.flush(); + return total; +}); + +const payloadMs = measure(() => { + let hits = 0; + for (let round = 0; round < 4; round += 1) { + for (const text of payloads) { + if (parseToolResultPayload(text)) hits += 1; + hits += extractPayloadTurnEndCardIds(text).length; + if (tryParseJsonRecord(text)) hits += 1; + } + } + return hits; +}); + +console.log(JSON.stringify({ pi12MiB_ms: Number(piMs.toFixed(2)), acp12MiB_ms: Number(acpMs.toFixed(2)), payload_ms: Number(payloadMs.toFixed(2)) }, null, 2)); diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/package.json b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/package.json new file mode 100644 index 0000000..a74c291 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-jsonl-hotpaths", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/acp-line-decoder.mjs b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/acp-line-decoder.mjs new file mode 100644 index 0000000..f29dab2 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/acp-line-decoder.mjs @@ -0,0 +1,70 @@ +/** + * Reference solution from makecindy/cindy (Apache-2.0), PR #15565 (04b6fd217d88): + * packages/maker-core/src/agents/acp/line-transport.ts + */ + +export const ACP_DEFAULT_MAX_LINE_CHARS = 32 * 1024 * 1024; + +export class AcpLineTooLongError extends Error { + constructor(limit) { + super(`ACP message exceeded ${limit} characters`); + this.name = 'AcpLineTooLongError'; + this.limit = limit; + } +} + +export class AcpLineDecoder { + #buffer = ''; + #pendingParts = []; + #pendingChars = 0; + #decoder = new TextDecoder('utf-8'); + #onLine; + #maxLineChars; + + constructor(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS) { + this.#onLine = onLine; + this.#maxLineChars = maxLineChars; + } + + push(chunk) { + const text = typeof chunk === 'string' ? chunk : this.#decoder.decode(chunk, { stream: true }); + if (!text.includes('\n') && this.#buffer.length + this.#pendingChars + text.length <= this.#maxLineChars) { + if (text.length > 0) { + this.#pendingParts.push(text); + this.#pendingChars += text.length; + } + return; + } + this.#buffer = this.#takePending(text); + let newline = this.#buffer.indexOf('\n'); + while (newline !== -1) { + const line = this.#buffer.slice(0, newline); + this.#buffer = this.#buffer.slice(newline + 1); + this.#emit(line); + newline = this.#buffer.indexOf('\n'); + } + if (this.#buffer.length > this.#maxLineChars) { + this.#buffer = ''; + throw new AcpLineTooLongError(this.#maxLineChars); + } + } + + flush() { + const rest = this.#takePending(this.#decoder.decode()); + this.#buffer = ''; + this.#emit(rest); + } + + #takePending(text) { + if (this.#pendingParts.length === 0) return this.#buffer + text; + const joined = `${this.#buffer}${this.#pendingParts.join('')}${text}`; + this.#pendingParts = []; + this.#pendingChars = 0; + return joined; + } + + #emit(raw) { + const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw; + if (line.trim().length > 0) this.#onLine(line); + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/payload-parser.mjs b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/payload-parser.mjs new file mode 100644 index 0000000..b4fe251 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/payload-parser.mjs @@ -0,0 +1,54 @@ +/** + * Extracted verbatim from makecindy/cindy (Apache-2.0), baseline before PR #15565: + * packages/maker-shared/src/payloadSummary.ts, toolResultCompaction.ts, messageRender.ts + */ + +function readRecord(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : null; +} + +export function projectToolResultPresentation(outer) { + const result = outer.result; + if (outer.ok !== true || result === null || typeof result !== 'object' || Array.isArray(result)) return outer; + const inner = result; + const projected = { + ...inner, + ...outer, + ...(inner._xdt_render_image === false ? { _xdt_render_image: false } : {}), + }; + if (inner.xdt_media_inline === true) { + if (!Object.hasOwn(outer, 'xdt_image_url')) delete projected.xdt_image_url; + if (!Object.hasOwn(outer, 'xdt_video_url')) delete projected.xdt_video_url; + } + return projected; +} + +function parsePayloadJsonObject(value) { + try { + return readRecord(JSON.parse(value)); + } catch { + return null; + } +} + +export function tryParseJsonRecord(text) { + if (!text) return null; + try { + return readRecord(JSON.parse(text)); + } catch { + return null; + } +} + +export function parseToolResultPayload(text) { + const outer = parsePayloadJsonObject(text); + return outer ? projectToolResultPresentation(outer) : null; +} + +export function extractPayloadTurnEndCardIds(text) { + const parsed = parseToolResultPayload(text); + return parsed?.xdt_card_turn_end === true && typeof parsed.xdt_card_id === 'string' + && parsed.xdt_card_id.length > 0 && parsed.xdt_card_id.length <= 128 + ? [parsed.xdt_card_id] + : []; +} diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/pi-jsonl-reader.mjs b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/pi-jsonl-reader.mjs new file mode 100644 index 0000000..fb46d13 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/src/pi-jsonl-reader.mjs @@ -0,0 +1,78 @@ +/** + * Extracted verbatim from makecindy/cindy (Apache-2.0), baseline before PR #15565: + * packages/maker-core/src/agents/pi/transport.ts + */ +import { StringDecoder } from 'node:string_decoder'; + +export const MAX_JSONL_BUFFER_CHARS = 16 * 1024 * 1024; + +export function attachJsonlReader( + stream, + onLine, + onOversizedFrame, + maxBufferChars = MAX_JSONL_BUFFER_CHARS, +) { + let decoder = new StringDecoder('utf8'); + let buffer = ''; + let skippingOversizedLine = false; + + const resetDecoder = () => { + decoder = new StringDecoder('utf8'); + }; + + const dropThroughNewline = () => { + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + buffer = ''; + resetDecoder(); + return false; + } + buffer = buffer.slice(newlineIndex + 1); + skippingOversizedLine = false; + return true; + }; + + const emitCompleteLines = () => { + while (true) { + if (skippingOversizedLine) { + if (!dropThroughNewline()) return; + continue; + } + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + if (buffer.length > maxBufferChars) { + skippingOversizedLine = true; + onOversizedFrame?.(); + dropThroughNewline(); + } + return; + } + if (newlineIndex > maxBufferChars) { + onOversizedFrame?.(); + buffer = buffer.slice(newlineIndex + 1); + continue; + } + let line = buffer.slice(0, newlineIndex); + buffer = buffer.slice(newlineIndex + 1); + if (line.endsWith('\r')) line = line.slice(0, -1); + onLine(line); + } + }; + + stream.on('data', (chunk) => { + buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk); + emitCompleteLines(); + }); + + stream.on('end', () => { + buffer += decoder.end(); + emitCompleteLines(); + if (!skippingOversizedLine && buffer.length > 0 && buffer.length <= maxBufferChars) { + onLine(buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer); + } + }); + + stream.on('error', () => { + /* Handled by upper transport layer. */ + }); +} diff --git a/questions/perf-jsonl-hotpaths/v1/controls/incomplete/tests/smoke.test.mjs b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..b89b1ac --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; + +import { AcpLineDecoder, AcpLineTooLongError } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +test('AcpLineDecoder frames lines and handles CRLF and limit errors', () => { + const lines = []; + const decoder = new AcpLineDecoder((line) => lines.push(line), 32); + decoder.push(Buffer.from('{"a":1}\r\n\n{"b":2}')); + decoder.flush(); + assert.deepEqual(lines, ['{"a":1}', '{"b":2}']); + assert.throws(() => decoder.push('x'.repeat(40)), AcpLineTooLongError); +}); + +test('attachJsonlReader frames chunked UTF-8 and resyncs oversized lines', () => { + const stream = new EventEmitter(); + const lines = []; + let oversized = 0; + attachJsonlReader(stream, (l) => lines.push(l), () => { oversized += 1; }, 32); + stream.emit('data', Buffer.from('{"ok":true}\r\n')); + stream.emit('data', Buffer.from('x'.repeat(40) + '\n{"next":1}\n')); + stream.emit('end'); + assert.deepEqual(lines, ['{"ok":true}', '{"next":1}']); + assert.equal(oversized, 1); +}); + +test('payload parser handles envelopes, turn-end cards, and plain text', () => { + const env = JSON.stringify({ ok: true, result: { xdt_card_id: 'c1', xdt_card_turn_end: true } }); + assert.deepEqual(extractPayloadTurnEndCardIds(env), ['c1']); + assert.equal(parseToolResultPayload('Exit code 0\nDone'), null); + assert.deepEqual(tryParseJsonRecord(' {"taskId":"3"}'), { taskId: '3' }); + assert.equal(tryParseJsonRecord('Task #3 created successfully'), null); +}); diff --git a/questions/perf-jsonl-hotpaths/v1/question.json b/questions/perf-jsonl-hotpaths/v1/question.json new file mode 100644 index 0000000..73f1098 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/question.json @@ -0,0 +1,78 @@ +{ + "id": "perf-jsonl-hotpaths", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "大帧 JSONL 分帧与工具负载热路径性能优化", + "status": "calibrated", + "changeNote": "Eval Bank v2 quantitative performance question extracted from makecindy/cindy PR #15565 (04b6fd217d88).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "04b6fd217d88f8f613402555e1336a14036d30de", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "pi_framing", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_framing", + "correctness_payload", + "small_frame_guard" + ], + "metric": { + "id": "pi_12mb_speedup", + "label": "Pi 12 MiB speedup", + "unit": "×", + "direction": "higher", + "baseline": 1.5, + "target": 180, + "scale": "log" + } + }, + { + "id": "acp_framing", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_framing", + "correctness_payload", + "small_frame_guard" + ], + "metric": { + "id": "acp_12mb_speedup", + "label": "ACP 12 MiB speedup", + "unit": "×", + "direction": "higher", + "baseline": 1.5, + "target": 250, + "scale": "log" + } + }, + { + "id": "payload_parsing", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_framing", + "correctness_payload", + "small_frame_guard" + ], + "metric": { + "id": "payload_speedup", + "label": "Payload parse speedup", + "unit": "×", + "direction": "higher", + "baseline": 1.5, + "target": 80, + "scale": "log" + } + } + ] +} diff --git a/questions/perf-jsonl-hotpaths/v1/reference/CONTRACT.md b/questions/perf-jsonl-hotpaths/v1/reference/CONTRACT.md new file mode 100644 index 0000000..70f9167 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/CONTRACT.md @@ -0,0 +1,32 @@ +# Product & Protocol Contract + +## 1. ACP Line Decoder (`src/acp-line-decoder.mjs`) + +- Exports `ACP_DEFAULT_MAX_LINE_CHARS` (`32 * 1024 * 1024`), `AcpLineTooLongError`, and `AcpLineDecoder`. +- `new AcpLineDecoder(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS)` incrementally splits `string` or `Uint8Array` chunks on `\n`. +- Strips a single trailing `\r` before `\n` (including when `\r` and `\n` arrive in adjacent chunks). +- Handles multi-byte UTF-8 sequences split across `Uint8Array` chunk boundaries cleanly. +- Skips empty or whitespace-only lines (`line.trim().length === 0`). +- `flush()` decodes any buffered UTF-8 tail and emits the final non-empty line if present, clearing internal state. +- If a single incomplete line grows past `maxLineChars`, clears the pending buffer and throws `AcpLineTooLongError(maxLineChars)` so subsequent calls start cleanly. + +## 2. Pi JSONL Reader (`src/pi-jsonl-reader.mjs`) + +- Exports `MAX_JSONL_BUFFER_CHARS` (`16 * 1024 * 1024`) and `attachJsonlReader(stream, onLine, onOversizedFrame?, maxBufferChars = MAX_JSONL_BUFFER_CHARS)`. +- Listens to `data`, `end`, and `error` on a Node readable stream (`Buffer | string` chunks). +- Emits every newline-delimited line (stripping a single trailing `\r`), including empty lines between `\n` delimiters; on `end`, emits any non-empty trailing buffer `<= maxBufferChars` (stripping a trailing `\r`). +- Handles multi-byte UTF-8 sequences split across `Buffer` chunks. +- **Oversized frame handling**: + - If an incomplete line exceeds `maxBufferChars` without a newline, enters oversized-skip mode, invokes `onOversizedFrame?.()` once for that oversized line, discards buffered data until the next `\n`, and **resets the UTF-8 `StringDecoder`** so truncated multi-byte bytes from the discarded frame never corrupt subsequent valid frames. + - If a complete line ending in `\n` has length `> maxBufferChars`, invokes `onOversizedFrame?.()` and discards that line while continuing to emit subsequent lines in the same chunk. +- Attaches a no-op `error` listener on `stream` so unhandled stream errors do not crash the process. + +## 3. Tool & Task Payload Parser (`src/payload-parser.mjs`) + +- Exports `projectToolResultPresentation`, `parseToolResultPayload`, `extractPayloadTurnEndCardIds`, and `tryParseJsonRecord`. +- `tryParseJsonRecord(text)`: returns a plain non-array JSON object record when `text` parses as a JSON object; returns `null` for `undefined`, empty strings, plain text, JSON arrays, JSON primitives, or malformed JSON. +- `parseToolResultPayload(text)`: parses `text` as a JSON object and applies `projectToolResultPresentation(outer)`: + - When `outer.ok === true` and `outer.result` is a plain non-array object, merges `{ ...inner, ...outer }` (preserving `_xdt_render_image: false` if set on `inner`, and deleting `xdt_image_url`/`xdt_video_url` when `inner.xdt_media_inline === true` unless `outer` owns them directly). + - Otherwise returns `outer`. + - Returns `null` if `text` is not a valid JSON object (must handle leading RFC 8259 whitespace: space, `\t`, `\n`, `\r`). +- `extractPayloadTurnEndCardIds(text)`: returns `[parsed.xdt_card_id]` if `parsed.xdt_card_turn_end === true` and `parsed.xdt_card_id` is a non-empty string with length `<= 128`; otherwise `[]`. diff --git a/questions/perf-jsonl-hotpaths/v1/reference/ENVIRONMENT.md b/questions/perf-jsonl-hotpaths/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..688aa05 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/ENVIRONMENT.md @@ -0,0 +1,7 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — functional smoke checks + - `npm run bench` — representative large-frame, small-frame, and payload-parsing workloads diff --git a/questions/perf-jsonl-hotpaths/v1/reference/TASK.md b/questions/perf-jsonl-hotpaths/v1/reference/TASK.md new file mode 100644 index 0000000..6b62abb --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/TASK.md @@ -0,0 +1,18 @@ +# Task + +You are optimizing three hot paths extracted from Cindy's agent runtime and message projection pipeline. + +## Observed Production Symptoms + +1. **Large agent stdout frames stall the main thread**: Child agent processes emit newline-delimited JSON (JSONL) over stdout in ~64 KiB pipe chunks. When a single frame reaches 4–12 MiB (for example, history entries or tool outputs containing images/diffs), both the Pi JSONL reader (`src/pi-jsonl-reader.mjs`) and ACP line decoder (`src/acp-line-decoder.mjs`) stall the event loop for hundreds of milliseconds. +2. **Repeated plain-text payload parsing dominates long-session refreshes**: During live streaming flushes and transcript normalization, `src/payload-parser.mjs` scans hundreds to thousands of tool results and Task records where ~90% are plain text rather than JSON objects, consuming disproportionate CPU time. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with all framing, error, resync, UTF-8, whitespace, and payload-projection invariants defined in `CONTRACT.md`. +- Do not regress throughput on high-frequency small JSONL frames (e.g. 20,000 small lines). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-jsonl-hotpaths/v1/reference/bench/workload.mjs b/questions/perf-jsonl-hotpaths/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..c3acfaf --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/bench/workload.mjs @@ -0,0 +1,76 @@ +import { EventEmitter } from 'node:events'; +import { performance } from 'node:perf_hooks'; + +import { AcpLineDecoder } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +const PIPE_CHUNK = 64 * 1024; +function chunked(payload, size) { + const out = []; + for (let offset = 0; offset < payload.length; offset += size) out.push(payload.subarray(offset, offset + size)); + return out; +} +function frame(chars) { + return Buffer.from(`{"type":"response","data":"${'QUJD'.repeat(Math.ceil(chars / 4)).slice(0, chars)}"}\n`, 'utf8'); +} +function toolResults(count) { + const rows = []; + for (let i = 0; i < count; i += 1) { + if (i % 10 === 0) rows.push(JSON.stringify({ ok: true, result: { xdt_card_id: `card-${i}`, xdt_card_turn_end: i % 20 === 0 } })); + else if (i % 3 === 0) rows.push(` 1\timport { describe } from 'vitest';\n${' 2\tconst value = compute(input);\n'.repeat(60)}`); + else if (i % 3 === 1) rows.push(`Task #${i} created successfully: Step ${i}`); + else rows.push(`Exit code 0\n${'added 1 package, audited 812 packages in 2s\n'.repeat(10)}`); + } + return rows; +} + +function measure(fn, runs = 3) { + fn(); + const times = []; + for (let i = 0; i < runs; i += 1) { + const t0 = performance.now(); + fn(); + times.push(performance.now() - t0); + } + times.sort((a, b) => a - b); + return times[Math.floor(times.length / 2)]; +} + +const chunks12m = chunked(frame(12 * 1024 * 1024), PIPE_CHUNK); +const payloads = toolResults(1200); + +const piMs = measure(() => { + const s = new EventEmitter(); + let total = 0; + attachJsonlReader(s, (l) => { total += l.length; }); + for (const c of chunks12m) s.emit('data', c); + s.emit('end'); + return total; +}); + +const acpMs = measure(() => { + let total = 0; + const d = new AcpLineDecoder((l) => { total += l.length; }); + for (const c of chunks12m) d.push(c); + d.flush(); + return total; +}); + +const payloadMs = measure(() => { + let hits = 0; + for (let round = 0; round < 4; round += 1) { + for (const text of payloads) { + if (parseToolResultPayload(text)) hits += 1; + hits += extractPayloadTurnEndCardIds(text).length; + if (tryParseJsonRecord(text)) hits += 1; + } + } + return hits; +}); + +console.log(JSON.stringify({ pi12MiB_ms: Number(piMs.toFixed(2)), acp12MiB_ms: Number(acpMs.toFixed(2)), payload_ms: Number(payloadMs.toFixed(2)) }, null, 2)); diff --git a/questions/perf-jsonl-hotpaths/v1/reference/package.json b/questions/perf-jsonl-hotpaths/v1/reference/package.json new file mode 100644 index 0000000..a74c291 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-jsonl-hotpaths", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/reference/src/acp-line-decoder.mjs b/questions/perf-jsonl-hotpaths/v1/reference/src/acp-line-decoder.mjs new file mode 100644 index 0000000..f29dab2 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/src/acp-line-decoder.mjs @@ -0,0 +1,70 @@ +/** + * Reference solution from makecindy/cindy (Apache-2.0), PR #15565 (04b6fd217d88): + * packages/maker-core/src/agents/acp/line-transport.ts + */ + +export const ACP_DEFAULT_MAX_LINE_CHARS = 32 * 1024 * 1024; + +export class AcpLineTooLongError extends Error { + constructor(limit) { + super(`ACP message exceeded ${limit} characters`); + this.name = 'AcpLineTooLongError'; + this.limit = limit; + } +} + +export class AcpLineDecoder { + #buffer = ''; + #pendingParts = []; + #pendingChars = 0; + #decoder = new TextDecoder('utf-8'); + #onLine; + #maxLineChars; + + constructor(onLine, maxLineChars = ACP_DEFAULT_MAX_LINE_CHARS) { + this.#onLine = onLine; + this.#maxLineChars = maxLineChars; + } + + push(chunk) { + const text = typeof chunk === 'string' ? chunk : this.#decoder.decode(chunk, { stream: true }); + if (!text.includes('\n') && this.#buffer.length + this.#pendingChars + text.length <= this.#maxLineChars) { + if (text.length > 0) { + this.#pendingParts.push(text); + this.#pendingChars += text.length; + } + return; + } + this.#buffer = this.#takePending(text); + let newline = this.#buffer.indexOf('\n'); + while (newline !== -1) { + const line = this.#buffer.slice(0, newline); + this.#buffer = this.#buffer.slice(newline + 1); + this.#emit(line); + newline = this.#buffer.indexOf('\n'); + } + if (this.#buffer.length > this.#maxLineChars) { + this.#buffer = ''; + throw new AcpLineTooLongError(this.#maxLineChars); + } + } + + flush() { + const rest = this.#takePending(this.#decoder.decode()); + this.#buffer = ''; + this.#emit(rest); + } + + #takePending(text) { + if (this.#pendingParts.length === 0) return this.#buffer + text; + const joined = `${this.#buffer}${this.#pendingParts.join('')}${text}`; + this.#pendingParts = []; + this.#pendingChars = 0; + return joined; + } + + #emit(raw) { + const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw; + if (line.trim().length > 0) this.#onLine(line); + } +} diff --git a/questions/perf-jsonl-hotpaths/v1/reference/src/payload-parser.mjs b/questions/perf-jsonl-hotpaths/v1/reference/src/payload-parser.mjs new file mode 100644 index 0000000..f5c9fca --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/src/payload-parser.mjs @@ -0,0 +1,61 @@ +/** + * Reference solution from makecindy/cindy (Apache-2.0), PR #15565 (04b6fd217d88): + * packages/maker-shared/src/payloadSummary.ts, toolResultCompaction.ts, messageRender.ts + */ + +const FIRST_NON_JSON_WHITESPACE = /[^ \t\n\r]/; + +function readRecord(value) { + return value && typeof value === 'object' && !Array.isArray(value) ? value : null; +} + +export function projectToolResultPresentation(outer) { + const result = outer.result; + if (outer.ok !== true || result === null || typeof result !== 'object' || Array.isArray(result)) return outer; + const inner = result; + const projected = { + ...inner, + ...outer, + ...(inner._xdt_render_image === false ? { _xdt_render_image: false } : {}), + }; + if (inner.xdt_media_inline === true) { + if (!Object.hasOwn(outer, 'xdt_image_url')) delete projected.xdt_image_url; + if (!Object.hasOwn(outer, 'xdt_video_url')) delete projected.xdt_video_url; + } + return projected; +} + +function parsePayloadJsonObject(value) { + if (typeof value !== 'string') return null; + const first = FIRST_NON_JSON_WHITESPACE.exec(value); + if (!first || value[first.index] !== '{') return null; + try { + return readRecord(JSON.parse(value)); + } catch { + return null; + } +} + +export function tryParseJsonRecord(text) { + if (!text) return null; + const first = FIRST_NON_JSON_WHITESPACE.exec(text); + if (!first || text[first.index] !== '{') return null; + try { + return readRecord(JSON.parse(text)); + } catch { + return null; + } +} + +export function parseToolResultPayload(text) { + const outer = parsePayloadJsonObject(text); + return outer ? projectToolResultPresentation(outer) : null; +} + +export function extractPayloadTurnEndCardIds(text) { + const parsed = parseToolResultPayload(text); + return parsed?.xdt_card_turn_end === true && typeof parsed.xdt_card_id === 'string' + && parsed.xdt_card_id.length > 0 && parsed.xdt_card_id.length <= 128 + ? [parsed.xdt_card_id] + : []; +} diff --git a/questions/perf-jsonl-hotpaths/v1/reference/src/pi-jsonl-reader.mjs b/questions/perf-jsonl-hotpaths/v1/reference/src/pi-jsonl-reader.mjs new file mode 100644 index 0000000..4e2d510 --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/src/pi-jsonl-reader.mjs @@ -0,0 +1,100 @@ +/** + * Reference solution from makecindy/cindy (Apache-2.0), PR #15565 (04b6fd217d88): + * packages/maker-core/src/agents/pi/transport.ts + */ +import { StringDecoder } from 'node:string_decoder'; + +export const MAX_JSONL_BUFFER_CHARS = 16 * 1024 * 1024; + +export function attachJsonlReader( + stream, + onLine, + onOversizedFrame, + maxBufferChars = MAX_JSONL_BUFFER_CHARS, +) { + let decoder = new StringDecoder('utf8'); + let buffer = ''; + let pendingParts = []; + let pendingChars = 0; + let skippingOversizedLine = false; + + const takePending = (text) => { + if (pendingParts.length === 0) return buffer + text; + const joined = `${buffer}${pendingParts.join('')}${text}`; + pendingParts = []; + pendingChars = 0; + return joined; + }; + + const resetDecoder = () => { + decoder = new StringDecoder('utf8'); + }; + + const dropThroughNewline = () => { + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + buffer = ''; + resetDecoder(); + return false; + } + buffer = buffer.slice(newlineIndex + 1); + skippingOversizedLine = false; + return true; + }; + + const emitCompleteLines = () => { + while (true) { + if (skippingOversizedLine) { + if (!dropThroughNewline()) return; + continue; + } + const newlineIndex = buffer.indexOf('\n'); + if (newlineIndex === -1) { + if (buffer.length > maxBufferChars) { + skippingOversizedLine = true; + onOversizedFrame?.(); + dropThroughNewline(); + } + return; + } + if (newlineIndex > maxBufferChars) { + onOversizedFrame?.(); + buffer = buffer.slice(newlineIndex + 1); + continue; + } + let line = buffer.slice(0, newlineIndex); + buffer = buffer.slice(newlineIndex + 1); + if (line.endsWith('\r')) line = line.slice(0, -1); + onLine(line); + } + }; + + stream.on('data', (chunk) => { + const text = typeof chunk === 'string' ? chunk : decoder.write(chunk); + if ( + !skippingOversizedLine && + !text.includes('\n') && + buffer.length + pendingChars + text.length <= maxBufferChars + ) { + if (text.length > 0) { + pendingParts.push(text); + pendingChars += text.length; + } + return; + } + buffer = takePending(text); + emitCompleteLines(); + }); + + stream.on('end', () => { + buffer = takePending(decoder.end()); + emitCompleteLines(); + if (!skippingOversizedLine && buffer.length > 0 && buffer.length <= maxBufferChars) { + onLine(buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer); + } + }); + + stream.on('error', () => { + /* Handled by upper transport layer. */ + }); +} diff --git a/questions/perf-jsonl-hotpaths/v1/reference/tests/smoke.test.mjs b/questions/perf-jsonl-hotpaths/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..b89b1ac --- /dev/null +++ b/questions/perf-jsonl-hotpaths/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; + +import { AcpLineDecoder, AcpLineTooLongError } from '../src/acp-line-decoder.mjs'; +import { attachJsonlReader } from '../src/pi-jsonl-reader.mjs'; +import { + extractPayloadTurnEndCardIds, + parseToolResultPayload, + tryParseJsonRecord, +} from '../src/payload-parser.mjs'; + +test('AcpLineDecoder frames lines and handles CRLF and limit errors', () => { + const lines = []; + const decoder = new AcpLineDecoder((line) => lines.push(line), 32); + decoder.push(Buffer.from('{"a":1}\r\n\n{"b":2}')); + decoder.flush(); + assert.deepEqual(lines, ['{"a":1}', '{"b":2}']); + assert.throws(() => decoder.push('x'.repeat(40)), AcpLineTooLongError); +}); + +test('attachJsonlReader frames chunked UTF-8 and resyncs oversized lines', () => { + const stream = new EventEmitter(); + const lines = []; + let oversized = 0; + attachJsonlReader(stream, (l) => lines.push(l), () => { oversized += 1; }, 32); + stream.emit('data', Buffer.from('{"ok":true}\r\n')); + stream.emit('data', Buffer.from('x'.repeat(40) + '\n{"next":1}\n')); + stream.emit('end'); + assert.deepEqual(lines, ['{"ok":true}', '{"next":1}']); + assert.equal(oversized, 1); +}); + +test('payload parser handles envelopes, turn-end cards, and plain text', () => { + const env = JSON.stringify({ ok: true, result: { xdt_card_id: 'c1', xdt_card_turn_end: true } }); + assert.deepEqual(extractPayloadTurnEndCardIds(env), ['c1']); + assert.equal(parseToolResultPayload('Exit code 0\nDone'), null); + assert.deepEqual(tryParseJsonRecord(' {"taskId":"3"}'), { taskId: '3' }); + assert.equal(tryParseJsonRecord('Task #3 created successfully'), null); +}); diff --git a/questions/perf-mcp-hosttools-churn/v1/author/editable.json b/questions/perf-mcp-hosttools-churn/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/perf-mcp-hosttools-churn/v1/author/evaluator.mjs b/questions/perf-mcp-hosttools-churn/v1/author/evaluator.mjs new file mode 100644 index 0000000..b61a9cf --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/author/evaluator.mjs @@ -0,0 +1,478 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir, baseDir] = process.argv.slice(2); + +const load = async (dir) => { + const [sdk, sessionCtx, registry, servers, providers, caller] = await Promise.all([ + import(pathToFileURL(path.join(dir, 'lib', 'mcp-sdk.mjs')).href), + import(pathToFileURL(path.join(dir, 'src', 'session-context.mjs')).href), + import(pathToFileURL(path.join(dir, 'src', 'tool-registry.mjs')).href), + import(pathToFileURL(path.join(dir, 'src', 'servers.mjs')).href), + import(pathToFileURL(path.join(dir, 'src', 'providers.mjs')).href), + import(pathToFileURL(path.join(dir, 'src', 'host-tool-caller.mjs')).href), + ]); + return { sdk, sessionCtx, registry, servers, providers, caller }; +}; + +const sub = await load(subDir); +const base = await load(baseDir); + +function parsePayload(result) { + assert.ok(result && Array.isArray(result.content) && result.content[0]?.type === 'text'); + return JSON.parse(result.content[0].text); +} + +// --------------------------------------------------------------------------- +// 1. Measure deterministic schema_rebuilds BEFORE correctness tests pollute any global WeakMap +// --------------------------------------------------------------------------- +const BENCH_OWNER = { dataOwnerId: 'eval-owner', ownerGeneration: 1 }; +const BENCH_CALLER = { kind: 'plugin', pluginId: 'eval-plugin', ...BENCH_OWNER }; +const CALL_PLAN = [ + ['cindy_helper', 'storage_request', { op: 'call', provider: 'kv', request: { key: 'bench' } }], + ['cindy_docs', 'read_sheet', { path: 'metrics.csv', maxRows: 100 }], + ['cindy_scheduler', 'schedule_list', { status: 'active', summaryOnly: true }], + ['cindy_ssh', 'ssh_list_hosts', { includeOffline: false }], +]; + +function makeBenchProviders(mod) { + return mod.providers.createLiziMcpProviders({ + xdtHelper: { + storage: { call: async (ctx, req) => ({ ok: true, key: req.request?.key ?? null, dir: ctx.workingDir }) }, + machines: { list: async () => ({ ok: true, machines: ['m1'] }) }, + appModels: { models: async () => ({ ok: true, model: 'claude-sonnet' }) }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, file: `${ctx.workingDir}/${args.path}` }), + }, + scheduler: { + list: async (ctx) => ({ ok: true, caller: ctx.hostCaller?.pluginId ?? null, schedules: [] }), + }, + ssh: { + listHosts: async () => ({ ok: true, hosts: ['prod-1'] }), + }, + browser: {}, + }); +} + +async function runCallBatch(mod, count) { + let checksum = 0; + for (let i = 0; i < count; i += 1) { + const [server, tool, args] = CALL_PLAN[i % CALL_PLAN.length]; + const rt = mod.caller.createHostToolRuntime(server, BENCH_CALLER, `/tmp/eval-work-${i % 8}`); + assert.ok(rt, `Expected runtime for ${server}`); + const res = await rt.call(tool, args); + assert.equal(Boolean(res.isError), false, `Unexpected error from ${server}.${tool}`); + await rt.close(); + checksum += res.content[0].text.length; + } + return checksum; +} + +// Capture schema_rebuilds cleanly on fresh module state before running correctness tests. +let schema_rebuilds = 300; +let schema_bench_error = null; +try { + // Reset BEFORE makeBenchProviders so eager schema precompilation is counted fairly instead of falsely zeroed. + sub.sdk.resetSdkStats(); + sub.caller.setHostToolProviders(makeBenchProviders(sub), BENCH_OWNER); + await runCallBatch(sub, 300); + schema_rebuilds = sub.sdk.getSdkStats().strictSchemaBuilds; + sub.caller.clearHostToolProviders(); +} catch (e) { + schema_bench_error = e.message; + sub.caller.clearHostToolProviders(); +} + +// --------------------------------------------------------------------------- +// 2. Hard Correctness Gates +// --------------------------------------------------------------------------- +async function checkIsolationCorrectness() { + let releaseA; + let enteredAResolve; + const enteredA = new Promise((resolve) => { enteredAResolve = resolve; }); + const gateA = new Promise((resolve) => { releaseA = resolve; }); + const seenAuthCallers = []; + + const providers = sub.providers.createLiziMcpProviders({ + xdtHelper: { + authorizeCall: async (call) => { + if (call.caller?.kind === 'plugin') seenAuthCallers.push(call.caller.pluginId); + return { ok: true }; + }, + storage: { + call: async (ctx, request) => { + const key = request.request?.key; + if (key === 'a') { + enteredAResolve(); + await gateA; + } + return { + ok: true, + value: `${ctx.hostCaller?.pluginId ?? 'none'}@${ctx.workingDir}@${ctx.sessionId ?? 'no-session'}`, + }; + }, + }, + machines: { list: async () => ({ ok: true }), requestRemoteControl: async () => ({ ok: true }) }, + appModels: { models: async () => ({ ok: true }) }, + }, + docs: { + readSheet: async (ctx, args) => { + await Promise.resolve(); + return { ok: true, resolved: `${ctx.workingDir}/${args.path}`, sessionId: ctx.sessionId ?? null }; + }, + }, + scheduler: { + list: async (ctx) => { + await Promise.resolve(); + return { ok: true, caller: ctx.hostCaller?.pluginId ?? null, sessionId: ctx.sessionId ?? null }; + }, + }, + }); + + const helperProvider = providers.find((p) => p.name === 'cindy_helper'); + const docsProvider = providers.find((p) => p.name === 'cindy_docs'); + const schedProvider = providers.find((p) => p.name === 'cindy_scheduler'); + + const ctxA = { + agentKind: 'claude-code', + workingDir: '/work/alpha', + sessionId: 'sess-alpha', + hostCaller: { kind: 'plugin', pluginId: 'plugin-a', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxA.getSessionContext = () => ctxA; + + const ctxB = { + agentKind: 'claude-code', + workingDir: '/work/beta', + sessionId: 'sess-beta', + hostCaller: { kind: 'plugin', pluginId: 'plugin-b', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxB.getSessionContext = () => ctxB; + + const [resA, resB, docA, docB, scA, scB] = await sub.sessionCtx.runWithLiziMcpSessionContext( + { + agentKind: 'codex', + workingDir: '/work/ambient', + sessionId: 'ambient-task', + hostCaller: { kind: 'plugin', pluginId: 'ambient-plugin', dataOwnerId: 'o0', ownerGeneration: 0 }, + }, + async () => { + const rtA = helperProvider.toHostTools(ctxA); + const rtB = helperProvider.toHostTools(ctxB); + const dA = docsProvider.toHostTools(ctxA); + const dB = docsProvider.toHostTools(ctxB); + const sA = schedProvider.toHostTools(ctxA); + const sB = schedProvider.toHostTools(ctxB); + + const pA = rtA.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'a' } }); + await enteredA; + const pB = rtB.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'b' } }); + const pDocA = dA.call('read_sheet', { path: 'data.csv' }); + const pDocB = dB.call('read_sheet', { path: 'data.csv' }); + const pScA = sA.call('schedule_silence_current_run', { reason: 'quiet-a' }); + const pScB = sB.call('schedule_silence_current_run', { reason: 'quiet-b' }); + releaseA(); + + const out = await Promise.all([pA, pB, pDocA, pDocB, pScA, pScB]); + await Promise.all([rtA.close(), rtB.close(), dA.close(), dB.close(), sA.close(), sB.close()]); + return out.map(parsePayload); + }, + ); + + assert.equal(resA.value, 'plugin-a@/work/alpha@sess-alpha'); + assert.equal(resB.value, 'plugin-b@/work/beta@sess-beta'); + assert.deepEqual([...seenAuthCallers].sort(), ['plugin-a', 'plugin-b']); + assert.equal(docA.resolved, '/work/alpha/data.csv'); + assert.equal(docB.resolved, '/work/beta/data.csv'); + assert.equal(scA.sessionId, 'sess-alpha'); + assert.equal(scB.sessionId, 'sess-beta'); + + // Revoked getSessionContext must fail closed even inside an outer ambient ALS store. + const revokedCtx = { + agentKind: 'claude-code', + workingDir: '/work/alpha', + sessionId: 'sess-alpha', + getSessionContext: () => undefined, + }; + const revokedDocs = docsProvider.toHostTools(revokedCtx); + const revokedSched = schedProvider.toHostTools(revokedCtx); + const [revDocRes, revSchedRes] = await sub.sessionCtx.runWithLiziMcpSessionContext( + { agentKind: 'codex', workingDir: '/work/ambient', sessionId: 'ambient-task' }, + async () => { + const r1 = parsePayload(await revokedDocs.call('read_sheet', { path: 'data.csv' })); + const r2 = parsePayload(await revokedSched.call('schedule_silence_current_run', {})); + await Promise.all([revokedDocs.close(), revokedSched.close()]); + return [r1, r2]; + }, + ); + assert.equal(revDocRes.errorCode, 'NO_SESSION_CONTEXT', 'Revoked docs context leaked ambient ALS'); + assert.equal(revSchedRes.errorCode, 'NO_SESSION_CONTEXT', 'Revoked scheduler context leaked ambient ALS'); + + // Closing previous runtime handles must not break subsequent calls on the same provider. + const followUp = helperProvider.toHostTools(ctxB); + const followRes = parsePayload(await followUp.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'after-close' } })); + assert.equal(followRes.value, 'plugin-b@/work/beta@sess-beta'); + await followUp.close(); + + // Descriptor parity for local vs remote cindy_helper (PR #15602 invariant). + for (const ctx of [ + { agentKind: 'claude-code', workingDir: '' }, + { agentKind: 'claude-code', workingDir: '', remoteHostId: 'remote-host-1' }, + ]) { + const expectedCategory = ctx.remoteHostId ? 'bots' : 'settings'; + const ht = helperProvider.toHostTools(ctx); + const srv = helperProvider.toMcpServer(ctx); + try { + assert.deepEqual(ht.list(), srv.hostTools.list(), 'hostTools.list() drifted from McpServer.hostTools.list()'); + assert.deepEqual(ht.describe('request_remote_control'), { name: 'request_remote_control', category: 'cindy' }); + assert.deepEqual(ht.describe('get_app_default_model'), { name: 'get_app_default_model', category: expectedCategory }); + } finally { + await ht.close(); + await srv.close(); + } + } +} + +async function checkBrowserAndInvalidationCorrectness() { + // 1. cindy_browser MUST remain isolated per call (no cross-call cache or rulesBackend leakage). + const providers = sub.providers.createLiziMcpProviders({ browser: {} }); + const browserProvider = providers.find((p) => p.name === 'cindy_browser'); + const ctx1 = { agentKind: 'claude-code', workingDir: '/tmp/b1', sessionId: 'browser-sess-1' }; + const ctx2 = { agentKind: 'claude-code', workingDir: '/tmp/b2', sessionId: 'browser-sess-2' }; + + const rt1 = browserProvider.toHostTools(ctx1); + const rt2 = browserProvider.toHostTools(ctx2); + + await rt1.call('browser_set_rules_backend', { backend: 'cdp' }); + await rt1.call('browser_open', { url: 'https://private.session1', cacheKey: 'secret-page' }); + const hit1 = parsePayload(await rt1.call('browser_read_cache', { cacheKey: 'secret-page' })); + assert.equal(hit1.hit, true); + assert.equal(hit1.rulesBackend, 'cdp'); + + // While rt1 is STILL OPEN, rt2 must see clean empty cache, 'all' rulesBackend, and its own sessionId. + const miss2 = parsePayload(await rt2.call('browser_read_cache', { cacheKey: 'secret-page' })); + assert.equal(miss2.hit, false, 'cindy_browser leaked BrowserResultCache across calls'); + assert.equal(miss2.rulesBackend, 'all', 'cindy_browser leaked rulesBackend across calls'); + const snap2 = parsePayload(await rt2.call('browser_snapshot', {})); + assert.deepEqual(snap2.cachedKeys, []); + assert.equal(snap2.sessionId, 'browser-sess-2'); + await Promise.all([rt1.close(), rt2.close()]); + + // 2. setHostToolProviders / clearHostToolProviders immediately invalidate cached runtimes. + const makeLabeledProviders = (label) => sub.providers.createLiziMcpProviders({ + xdtHelper: { storage: { call: async () => ({ ok: true, value: label }) } }, + docs: { readSheet: async () => ({ ok: true, value: label }) }, + scheduler: { list: async () => ({ ok: true, value: label }) }, + ssh: { listHosts: async () => ({ ok: true, value: label }) }, + }); + const owner1 = { dataOwnerId: 'owner-1', ownerGeneration: 1 }; + const owner2 = { dataOwnerId: 'owner-2', ownerGeneration: 2 }; + const owner2Gen3 = { dataOwnerId: 'owner-2', ownerGeneration: 3 }; + const caller1 = { kind: 'plugin', pluginId: 'p1', ...owner1 }; + const caller2 = { kind: 'plugin', pluginId: 'p1', ...owner2 }; + const caller2Gen3 = { kind: 'plugin', pluginId: 'p1', ...owner2Gen3 }; + + try { + sub.caller.setHostToolProviders(makeLabeledProviders('from-owner-1'), owner1); + for (const [srv, tool, args] of [ + ['cindy_helper', 'storage_request', { op: 'providers' }], + ['cindy_docs', 'read_sheet', { path: 'a.csv' }], + ['cindy_scheduler', 'schedule_list', {}], + ['cindy_ssh', 'ssh_list_hosts', {}], + ]) { + const rt = sub.caller.createHostToolRuntime(srv, caller1, '/tmp/owner1'); + assert.ok(rt); + assert.equal(parsePayload(await rt.call(tool, args)).value, 'from-owner-1'); + await rt.close(); + } + + // Account switch: old owner immediately rejected; new owner sees new deps immediately. + sub.caller.setHostToolProviders(makeLabeledProviders('from-owner-2'), owner2); + assert.equal(sub.caller.createHostToolRuntime('cindy_helper', caller1, '/tmp/owner1'), null); + for (const [srv, tool, args] of [ + ['cindy_helper', 'storage_request', { op: 'providers' }], + ['cindy_docs', 'read_sheet', { path: 'a.csv' }], + ['cindy_scheduler', 'schedule_list', {}], + ['cindy_ssh', 'ssh_list_hosts', {}], + ]) { + const rt = sub.caller.createHostToolRuntime(srv, caller2, '/tmp/owner2'); + assert.ok(rt); + assert.equal(parsePayload(await rt.call(tool, args)).value, 'from-owner-2'); + await rt.close(); + } + + // Generation bump for same owner invalidates previous generation caller. + sub.caller.setHostToolProviders(makeLabeledProviders('from-owner-2-gen3'), owner2Gen3); + assert.equal(sub.caller.createHostToolRuntime('cindy_helper', caller2, '/tmp/owner2'), null); + const rt3 = sub.caller.createHostToolRuntime('cindy_helper', caller2Gen3, '/tmp/owner2'); + assert.ok(rt3); + assert.equal(parsePayload(await rt3.call('storage_request', { op: 'providers' })).value, 'from-owner-2-gen3'); + await rt3.close(); + + // clearHostToolProviders immediately rejects all callers. + sub.caller.clearHostToolProviders(); + assert.equal(sub.caller.createHostToolRuntime('cindy_helper', caller2Gen3, '/tmp/owner2'), null); + assert.equal(sub.caller.createHostToolRuntime('cindy_ssh', caller2Gen3, '/tmp/owner2'), null); + } finally { + sub.caller.clearHostToolProviders(); + } +} + +async function checkSchemaCorrectness() { + // 1. Fresh HostToolRegistry with unique shape verifies real use of lib/mcp-sdk.mjs z.strictObject. + sub.sdk.resetSdkStats(); + const reg = new sub.registry.HostToolRegistry('schema_gate'); + reg.register({ + name: 'strict_probe', + category: 'cindy', + description: 'Strict validation probe', + inputShape: { + id: sub.sdk.z.string({ min: 2, max: 16 }), + mode: sub.sdk.z.enum(['fast', 'full']), + count: sub.sdk.z.optional(sub.sdk.z.number({ min: 1, max: 10 })), + }, + handler: async (args) => sub.registry.jsonTextResult({ ok: true, args }), + }); + + const okRes = parsePayload(await reg.call('strict_probe', { id: 'ab', mode: 'fast', count: 3 })); + assert.deepEqual(okRes, { ok: true, args: { id: 'ab', mode: 'fast', count: 3 } }); + const buildsAfterFirst = sub.sdk.getSdkStats().strictSchemaBuilds; + assert.ok(buildsAfterFirst >= 1, 'HostToolRegistry must compile strict schema via lib/mcp-sdk.mjs z.strictObject'); + + // Unknown key MUST be rejected with structured INVALID_PARAMS + jsonSchema. + const extraKeyRes = parsePayload(await reg.call('strict_probe', { id: 'ab', mode: 'fast', rogue: true })); + assert.equal(extraKeyRes.ok, false); + assert.equal(extraKeyRes.errorCode, 'INVALID_PARAMS'); + assert.equal(extraKeyRes.jsonSchema?.additionalProperties, false); + assert.ok(extraKeyRes.issues.some((i) => i.message.includes('rogue'))); + + // Invalid enum & wrong type & missing required field MUST be rejected. + const badEnum = parsePayload(await reg.call('strict_probe', { id: 'ab', mode: 'invalid' })); + assert.equal(badEnum.errorCode, 'INVALID_PARAMS'); + const badType = parsePayload(await reg.call('strict_probe', { id: 'ab', mode: 'fast', count: 'not-a-num' })); + assert.equal(badType.errorCode, 'INVALID_PARAMS'); + const missingReq = parsePayload(await reg.call('strict_probe', { mode: 'fast' })); + assert.equal(missingReq.errorCode, 'INVALID_PARAMS'); + const shortStr = parsePayload(await reg.call('strict_probe', { id: 'x', mode: 'fast' })); + assert.equal(shortStr.errorCode, 'INVALID_PARAMS'); + const unknownTool = parsePayload(await reg.call('does_not_exist', {})); + assert.equal(unknownTool.errorCode, 'UNKNOWN_TOOL'); + + // Also ensure the 300-call benchmark genuinely compiled schemas via SDK (anti-bypass). + assert.equal(schema_bench_error, null, `Schema benchmark failed: ${schema_bench_error}`); + assert.ok(schema_rebuilds >= 4, `Expected >= 4 strict schema builds across 4 distinct tools, got ${schema_rebuilds}`); +} + +let correctness_isolation = false; +let correctness_browser_and_invalidation = false; +let correctness_schema = false; +const errors = []; + +try { await checkIsolationCorrectness(); correctness_isolation = true; } catch (e) { errors.push('isolation: ' + e.message); } +try { await checkBrowserAndInvalidationCorrectness(); correctness_browser_and_invalidation = true; } catch (e) { errors.push('browser/invalidation: ' + e.message); } +try { await checkSchemaCorrectness(); correctness_schema = true; } catch (e) { errors.push('schema: ' + e.message); } + +// --------------------------------------------------------------------------- +// 3. Quantitative Benchmarks (heap_alloc_kb_per_call + interleaved A/B call_speedup) +// --------------------------------------------------------------------------- +async function measureHeapKbPerCall(mod, calls = 200, rounds = 3) { + assert.equal(typeof globalThis.gc, 'function', '--expose-gc is required'); + mod.caller.setHostToolProviders(makeBenchProviders(mod), BENCH_OWNER); + try { + // Warmup JIT & lazy provider caches + await runCallBatch(mod, 24); + const samples = []; + for (let r = 0; r < rounds; r += 1) { + trusted.gc(); + trusted.gc(); + let totalBytes = 0; + let cleanCalls = 0; + let prev = trusted.memoryUsage().heapUsed; + for (let i = 0; i < calls; i += 1) { + const [server, tool, args] = CALL_PLAN[i % CALL_PLAN.length]; + const rt = mod.caller.createHostToolRuntime(server, BENCH_CALLER, `/tmp/eval-work-${i % 8}`); + await rt.call(tool, args); + await rt.close(); + const cur = trusted.memoryUsage().heapUsed; + if (cur >= prev) { + totalBytes += cur - prev; + cleanCalls += 1; + } + prev = cur; + } + samples.push(totalBytes / 1024 / Math.max(cleanCalls, 1)); + } + samples.sort((a, b) => a - b); + return Number(samples[Math.floor(samples.length / 2)].toFixed(2)); + } finally { + mod.caller.clearHostToolProviders(); + } +} + +async function measureInterleavedSpeedup(rounds = 7, callsPerRound = 600) { + base.caller.setHostToolProviders(makeBenchProviders(base), BENCH_OWNER); + sub.caller.setHostToolProviders(makeBenchProviders(sub), BENCH_OWNER); + try { + const bCheck = await runCallBatch(base, 40); + const sCheck = await runCallBatch(sub, 40); + assert.equal(sCheck, bCheck, 'Call benchmark output checksum mismatch'); + for (let w = 0; w < 2; w += 1) { + await runCallBatch(base, 40); + await runCallBatch(sub, 40); + } + + const ratios = []; + for (let i = 0; i < rounds; i += 1) { + const baseFirst = i % 2 === 0; + let bMs; + let sMs; + if (baseFirst) { + const t0 = trusted.now(); await runCallBatch(base, callsPerRound); bMs = trusted.now() - t0; + const t1 = trusted.now(); await runCallBatch(sub, callsPerRound); sMs = trusted.now() - t1; + } else { + const t1 = trusted.now(); await runCallBatch(sub, callsPerRound); sMs = trusted.now() - t1; + const t0 = trusted.now(); await runCallBatch(base, callsPerRound); bMs = trusted.now() - t0; + } + ratios.push(bMs / Math.max(sMs, 0.05)); + } + ratios.sort((a, b) => a - b); + return Number(ratios[Math.floor(ratios.length / 2)].toFixed(2)); + } finally { + base.caller.clearHostToolProviders(); + sub.caller.clearHostToolProviders(); + } +} + +let heap_alloc_kb_per_call = 350; +let call_speedup = 1; + +if (correctness_isolation && correctness_browser_and_invalidation && correctness_schema) { + try { + heap_alloc_kb_per_call = await measureHeapKbPerCall(sub, 200, 3); + call_speedup = await measureInterleavedSpeedup(7, 600); + } catch (e) { + errors.push('bench: ' + e.message); + } +} + +trusted.emit(({ + status: 'graded', + items: { + correctness_isolation, + correctness_browser_and_invalidation, + correctness_schema, + }, + metrics: { + schema_rebuilds, + heap_alloc_kb_per_call, + call_speedup, + }, + details: { errors }, +})); diff --git a/questions/perf-mcp-hosttools-churn/v1/author/grade.py b/questions/perf-mcp-hosttools-churn/v1/author/grade.py new file mode 100644 index 0000000..ab28533 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks/SDK cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/perf-mcp-hosttools-churn/v1/author/grade_impl.py b/questions/perf-mcp-hosttools-churn/v1/author/grade_impl.py new file mode 100644 index 0000000..4db16d6 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/author/grade_impl.py @@ -0,0 +1,44 @@ +"""Isolated pure-Node quantitative grader with --expose-gc: runs isolation/schema gates + churn/speedup benchmarks.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-mcp-churn-') as td: + tmp = pathlib.Path(td) + sub_dir = tmp / 'sub' + base_dir = tmp / 'base' + shutil.copytree(submission_root / 'src', sub_dir / 'src') + shutil.copytree(Q / 'candidate' / 'lib', sub_dir / 'lib') + shutil.copytree(Q / 'candidate' / 'src', base_dir / 'src') + shutil.copytree(Q / 'candidate' / 'lib', base_dir / 'lib') + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', '--expose-gc', str(HERE / 'evaluator.mjs'), str(sub_dir), str(base_dir)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/perf-mcp-hosttools-churn/v1/author/result-channel.mjs b/questions/perf-mcp-hosttools-churn/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/CONTRACT.md b/questions/perf-mcp-hosttools-churn/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..5d5e0c0 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/CONTRACT.md @@ -0,0 +1,34 @@ +# Product & Security Contract + +## 1. Immutable SDK Layer (`lib/mcp-sdk.mjs` — Protected, Do Not Modify) + +- Provides `z` (`string`, `number`, `boolean`, `enum`, `array`, `record`, `object`, `optional`, `strictObject`), `McpServer`, `getSdkStats()`, and `resetSdkStats()`. +- `z.strictObject(shape)` builds a strict validator + JSON Schema descriptor and increments `strictSchemaBuilds`. +- `new McpServer(...)` constructs full MCP protocol tables and increments `mcpServerBuilds`. +- Tool registries must validate incoming arguments via `z.strictObject(def.inputShape)` and return the structured `INVALID_PARAMS` error (including `issues` and `jsonSchema`) on validation failures. + +## 2. Session Context & ALS Isolation (`src/session-context.mjs`) + +- Exports `runWithLiziMcpSessionContext(ctx, fn)`, `getLiziMcpSessionContext()`, and `resolveLiziMcpSessionContext(fallback)`. +- Uses `AsyncLocalStorage` from `node:async_hooks`. +- Fail-closed resolution: + - When `fallback.getSessionContext` is present, its return value is authoritative; returning `undefined` strips all session attribution (`workingDir: ''`, `sessionId: undefined`, `remoteHostId: undefined`, `hostCaller: undefined`, `vendorOptions: undefined`) and MUST NOT inherit an outer ambient `AsyncLocalStorage` store. + - Concrete attribution on `fallback` takes precedence over ambient storage; only an empty placeholder consults `getLiziMcpSessionContext()`. + +## 3. Tool Registry & Servers (`src/tool-registry.mjs`, `src/servers.mjs`) + +- `HostToolRegistry` registers tools (`name`, `category`, `description`, `inputShape`, `handler`, `hidden?`) and aliases, lists non-hidden tools, describes tools by name/alias, and strictly validates arguments on `call(name, rawArgs, signal)`. +- Re-registering or replacing a tool invalidates any cached compiled schema for that tool name. +- `src/servers.mjs` exposes server constructors (`createXdtHelperMcpServer`, `createCindyDocsMcpServer`, `createSchedulerMcpServer`, `createSshMcpServer`, `createBrowserMcpServer`) and may expose lightweight `create*HostTools` factories that build a `HostToolRuntime` without constructing `McpServer`. +- Tool descriptors (`list()` and `describe(name)`) on `hostTools` must remain identical to `create*McpServer(...).hostTools`: + - `cindy_helper`: `get_app_default_model` has category `'settings'` when `!ctx.remoteHostId` and category `'bots'` when `ctx.remoteHostId` is truthy; `request_remote_control` has `{ name: 'request_remote_control', category: 'cindy' }`. + - `cindy_docs`: fails closed with `{ ok: false, errorCode: 'NO_SESSION_CONTEXT' }` when resolved `workingDir` is empty. + - `cindy_browser`: maintains per-call mutable browser cache (`browser_open` / `browser_read_cache`) and `rulesBackend` (`browser_set_rules_backend`), which MUST NOT leak between separate `toHostTools(ctx)` calls. + +## 4. Provider Registry & Host Tool Slot (`src/providers.mjs`, `src/host-tool-caller.mjs`) + +- `createLiziMcpProviders(opts)` returns provider descriptors `{ name, toHostTools(ctx), toMcpServer(ctx), isEnabled?(ctx) }`. +- `setHostToolProviders(providers, owner)`, `clearHostToolProviders()`, and `createHostToolRuntime(server, caller, workingDir?)`: + - `createHostToolRuntime` checks `owner.dataOwnerId` and `owner.ownerGeneration` strictly against `caller`; mismatches return `null`. + - Replacing or clearing providers immediately invalidates cached provider runtimes so subsequent calls reflect the new owner's deps (or return `null` after clear). + - Closing a returned `HostToolRuntime` (`await rt.close()`) must not break subsequent calls obtained from the same provider. diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/ENVIRONMENT.md b/questions/perf-mcp-hosttools-churn/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..d0ee8ef --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Heap measurement: `npm run bench` runs Node with `--expose-gc` so heap allocation per call (`KB/call`) is measured cleanly via `process.memoryUsage().heapUsed` deltas. +- Public checks: + - `npm test` — functional and concurrency-isolation smoke tests + - `npm run bench` — representative 300-call schema rebuild count, 200-call heap allocation per call, and throughput benchmark diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/TASK.md b/questions/perf-mcp-hosttools-churn/v1/candidate/TASK.md new file mode 100644 index 0000000..b6817c2 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/TASK.md @@ -0,0 +1,22 @@ +# Task + +You are optimizing Cindy's MCP `hostTools` dispatch and strict schema validation pipeline, extracted from `packages/lizi-mcps` and `hostToolCaller`. + +## Observed Production Symptoms + +Plugin host tool calls (`cindy_helper`, `cindy_docs`, `cindy_scheduler`, `cindy_ssh`, `cindy_browser`) currently reconstruct an entire `McpServer`, re-register dozens of tools across registries, and re-compile strict input schemas (`z.strictObject`) on **every single tool call**, causing heavy per-call heap allocation churn, GC pauses, and high CPU overhead. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Eliminate per-call `McpServer` reconstruction, repeated tool registry construction, and repeated strict schema compilation for stateless providers while preserving **100% behavioral and security isolation**: + - Concurrent interleaved async tool calls MUST NEVER leak `hostCaller`, `workingDir`, `sessionId`, or `remoteHostId` across callers or from an outer ambient `AsyncLocalStorage` context. + - A revoked `getSessionContext: () => undefined` MUST fail closed (never falling back to an ambient session context). + - `cindy_browser` MUST remain isolated per call (no cross-call browser session/cache/rules leakage). + - `setHostToolProviders` and `clearHostToolProviders` MUST immediately invalidate previously cached provider runtimes so old account owners are rejected and new account owners never observe stale deps. + - Closing one call's `HostToolRuntime` handle MUST NOT break subsequent calls on the same provider. + - Tool registries MUST continue validating arguments strictly through `z.strictObject` from `../lib/mcp-sdk.mjs` (rejecting unknown keys and invalid types with the exact structured `INVALID_PARAMS` payload and JSON schema). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/bench/workload.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..9e8e942 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/bench/workload.mjs @@ -0,0 +1,93 @@ +import { performance } from 'node:perf_hooks'; + +import { getSdkStats, resetSdkStats } from '../lib/mcp-sdk.mjs'; +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; + +const owner = { dataOwnerId: 'bench-owner', ownerGeneration: 1 }; +const caller = { kind: 'plugin', pluginId: 'bench-plugin', ...owner }; + +const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { call: async (ctx, req) => ({ ok: true, key: req.request?.key ?? null, dir: ctx.workingDir }) }, + machines: { list: async () => ({ ok: true, machines: [] }) }, + appModels: { models: async () => ({ ok: true, model: 'claude-sonnet' }) }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, file: `${ctx.workingDir}/${args.path}` }), + }, + scheduler: { + list: async (ctx) => ({ ok: true, caller: ctx.hostCaller?.pluginId ?? null, schedules: [] }), + }, + ssh: { + listHosts: async () => ({ ok: true, hosts: ['prod-1'] }), + }, + browser: {}, +}); + +setHostToolProviders(providers, owner); + +const CALL_PLAN = [ + ['cindy_helper', 'storage_request', { op: 'call', provider: 'kv', request: { key: 'k1' } }], + ['cindy_docs', 'read_sheet', { path: 'report.csv', maxRows: 50 }], + ['cindy_scheduler', 'schedule_list', { status: 'active', summaryOnly: true }], + ['cindy_ssh', 'ssh_list_hosts', { includeOffline: false }], +]; + +async function invokeOne(i) { + const [server, tool, args] = CALL_PLAN[i % CALL_PLAN.length]; + const rt = createHostToolRuntime(server, caller, `/tmp/work-${i % 8}`); + const res = await rt.call(tool, args); + await rt.close(); + return res.content[0].text.length; +} + +// 1. Deterministic schema rebuild count across 300 calls +resetSdkStats(); +let totalLen = 0; +for (let i = 0; i < 300; i += 1) { + totalLen += await invokeOne(i); +} +const { strictSchemaBuilds: schemaRebuilds300, mcpServerBuilds: mcpServerBuilds300 } = getSdkStats(); + +// 2. Heap allocation per call across 200 calls (requires --expose-gc) +let heapAllocKbPerCall = null; +if (typeof globalThis.gc === 'function') { + for (let w = 0; w < 20; w += 1) await invokeOne(w); + globalThis.gc(); + globalThis.gc(); + let bytes = 0; + let clean = 0; + let prev = process.memoryUsage().heapUsed; + for (let i = 0; i < 200; i += 1) { + await invokeOne(i); + const cur = process.memoryUsage().heapUsed; + if (cur >= prev) { + bytes += cur - prev; + clean += 1; + } + prev = cur; + } + heapAllocKbPerCall = Number((bytes / 1024 / Math.max(clean, 1)).toFixed(2)); +} + +// 3. Throughput across 300 calls +const t0 = performance.now(); +for (let i = 0; i < 300; i += 1) { + await invokeOne(i); +} +const calls300Ms = Number((performance.now() - t0).toFixed(2)); + +clearHostToolProviders(); + +console.log(JSON.stringify({ + schemaRebuilds300, + mcpServerBuilds300, + heapAllocKbPerCall, + calls300Ms, + checksum: totalLen, +}, null, 2)); diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/lib/mcp-sdk.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/lib/mcp-sdk.mjs new file mode 100644 index 0000000..1b79835 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/lib/mcp-sdk.mjs @@ -0,0 +1,318 @@ +/** + * Protected stand-in for external `zod` strict schema compilation + `@modelcontextprotocol/sdk` McpServer. + * Do not modify this file; optimize `src/` instead. + */ + +const sdkStats = { + strictSchemaBuilds: 0, + mcpServerBuilds: 0, +}; + +export function getSdkStats() { + return { ...sdkStats }; +} + +export function resetSdkStats() { + sdkStats.strictSchemaBuilds = 0; + sdkStats.mcpServerBuilds = 0; +} + +function makeField(kind, opts = {}) { + return { + __zodField: true, + kind, + optional: false, + description: opts.description ?? '', + min: opts.min, + max: opts.max, + pattern: opts.pattern, + values: opts.values, + item: opts.item, + shape: opts.shape, + optionalize() { + return { ...this, optional: true }; + }, + }; +} + +function fieldToJsonSchema(field) { + const base = {}; + if (field.description) base.description = field.description; + switch (field.kind) { + case 'string': + base.type = 'string'; + if (field.min !== undefined) base.minLength = field.min; + if (field.max !== undefined) base.maxLength = field.max; + if (field.pattern) base.pattern = field.pattern.source; + return base; + case 'number': + base.type = 'number'; + if (field.min !== undefined) base.minimum = field.min; + if (field.max !== undefined) base.maximum = field.max; + return base; + case 'boolean': + return { ...base, type: 'boolean' }; + case 'enum': + return { ...base, type: 'string', enum: [...field.values] }; + case 'array': + return { ...base, type: 'array', items: fieldToJsonSchema(field.item) }; + case 'record': + return { ...base, type: 'object', additionalProperties: true }; + case 'object': { + const properties = {}; + const required = []; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + properties[k] = fieldToJsonSchema(sub); + if (!sub.optional) required.push(k); + } + return { ...base, type: 'object', properties, required, additionalProperties: false }; + } + default: + return base; + } +} + +function validateField(field, value, pathStr, issues) { + if (value === undefined) { + if (!field.optional) issues.push({ path: pathStr, message: 'Required' }); + return undefined; + } + switch (field.kind) { + case 'string': + if (typeof value !== 'string') { + issues.push({ path: pathStr, message: 'Expected string' }); + return value; + } + if (field.min !== undefined && value.length < field.min) { + issues.push({ path: pathStr, message: `String must contain at least ${field.min} character(s)` }); + } + if (field.max !== undefined && value.length > field.max) { + issues.push({ path: pathStr, message: `String must contain at most ${field.max} character(s)` }); + } + if (field.pattern && !field.pattern.test(value)) { + issues.push({ path: pathStr, message: 'Invalid string pattern' }); + } + return value; + case 'number': + if (typeof value !== 'number' || !Number.isFinite(value)) { + issues.push({ path: pathStr, message: 'Expected finite number' }); + return value; + } + if (field.min !== undefined && value < field.min) { + issues.push({ path: pathStr, message: `Number must be >= ${field.min}` }); + } + if (field.max !== undefined && value > field.max) { + issues.push({ path: pathStr, message: `Number must be <= ${field.max}` }); + } + return value; + case 'boolean': + if (typeof value !== 'boolean') issues.push({ path: pathStr, message: 'Expected boolean' }); + return value; + case 'enum': + if (!field.values.includes(value)) { + issues.push({ path: pathStr, message: `Invalid enum value; expected one of ${field.values.join(', ')}` }); + } + return value; + case 'array': + if (!Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected array' }); + return value; + } + return value.map((item, idx) => validateField(field.item, item, `${pathStr}[${idx}]`, issues)); + case 'record': + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object record' }); + return value; + } + return { ...value }; + case 'object': { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object' }); + return value; + } + const allowedKeys = new Set(Object.keys(field.shape ?? {})); + const unknown = Object.keys(value).filter((k) => !allowedKeys.has(k)); + if (unknown.length > 0) { + issues.push({ path: pathStr, message: `Unrecognized key(s) in object: ${unknown.join(', ')}` }); + } + const out = {}; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + const parsed = validateField(sub, value[k], pathStr ? `${pathStr}.${k}` : k, issues); + if (parsed !== undefined) out[k] = parsed; + } + return out; + } + default: + return value; + } +} + +/** + * Compiles a strict object schema (mirroring Zod v4 `z.strictObject` + JSON Schema metadata graph). + * Rebuilding this on every tool invocation allocates AST descriptors, JSON Schema tables, and validators. + */ +function compileStrictObject(shape, countStats = true) { + if (countStats) sdkStats.strictSchemaBuilds += 1; + const entries = Object.entries(shape ?? {}); + const allowedKeys = new Set(); + const properties = {}; + const required = []; + const compiledFields = []; + const diagnosticCatalog = new Map(); + + for (const [key, field] of entries) { + allowedKeys.add(key); + const jsonDef = fieldToJsonSchema(field); + properties[key] = jsonDef; + if (!field.optional) required.push(key); + compiledFields.push({ + key, + field, + jsonDef, + validator: (val, issues) => validateField(field, val, key, issues), + }); + // Build eager diagnostic hints & schema draft nodes mirroring Zod v4 schema metadata tables. + diagnosticCatalog.set(key, { + key, + kind: field.kind, + optional: field.optional, + schemaFragment: JSON.stringify(jsonDef), + examples: Array.from({ length: 12 }, (_, idx) => `${key}:${field.kind}:hint_${idx}`), + }); + } + + const jsonSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties, + required, + additionalProperties: false, + }; + const serializedSchema = JSON.stringify(jsonSchema); + + return { + jsonSchema, + serializedSchema, + diagnosticCatalog, + toJsonSchema() { + return jsonSchema; + }, + safeParse(rawArgs) { + if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues: [{ path: '', message: 'Expected object arguments' }], + jsonSchema, + }, + }; + } + const issues = []; + const unknownKeys = []; + for (const key of Object.keys(rawArgs)) { + if (!allowedKeys.has(key)) unknownKeys.push(key); + } + if (unknownKeys.length > 0) { + issues.push({ + path: '', + message: `Unrecognized key(s) in object: ${unknownKeys.join(', ')}`, + }); + } + const data = {}; + for (let i = 0; i < compiledFields.length; i += 1) { + const entry = compiledFields[i]; + const parsed = entry.validator(rawArgs[entry.key], issues); + if (parsed !== undefined) data[entry.key] = parsed; + } + if (issues.length > 0) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues, + jsonSchema, + }, + }; + } + return { success: true, data }; + }, + }; +} + +export const z = { + string: (opts) => makeField('string', opts), + number: (opts) => makeField('number', opts), + boolean: (opts) => makeField('boolean', opts), + enum: (values, opts) => makeField('enum', { ...opts, values }), + array: (item, opts) => makeField('array', { ...opts, item }), + record: (opts) => makeField('record', opts), + object: (shape, opts) => makeField('object', { ...opts, shape }), + optional: (field) => field.optionalize(), + strictObject: (shape) => compileStrictObject(shape, true), +}; + +/** + * Stand-in for `@modelcontextprotocol/sdk` McpServer. + * Constructing an McpServer allocates protocol request/notification handler tables, + * capability manifests, and eager entry tool schemas for stdio/SSE transport. + */ +export class McpServer { + constructor({ name, version = '1.0.0', instructions = '' }) { + sdkStats.mcpServerBuilds += 1; + this.name = name; + this.version = version; + this.instructions = instructions; + this.closed = false; + this._tools = new Map(); + this._requestHandlers = new Map(); + this._notificationHandlers = new Map(); + this._protocolTables = Array.from({ length: 160 }, (_, idx) => ({ + method: `mcp/${name}/op_${idx}`, + schemaDraft: `https://modelcontextprotocol.io/schema/2025-03-26/${name}/${idx}`, + capabilities: { listChanged: true, subscribe: true, progress: true, sampling: idx % 2 === 0 }, + inputEnvelope: { type: 'object', additionalProperties: false, slot: idx, required: ['jsonrpc', 'id', 'method'] }, + metadata: `${name}:${version}:protocol_slot_${idx}:`.repeat(12), + })); + // Eagerly serialize initialization capability manifest for MCP stdio/SSE handshake. + this._manifestJson = JSON.stringify({ + serverInfo: { name, version }, + instructions, + protocolTables: this._protocolTables, + }); + this._capabilities = { + tools: { listChanged: true }, + logging: {}, + prompts: { listChanged: false }, + resources: { subscribe: false, listChanged: false }, + }; + } + + registerTool(name, config, handler) { + const compiledEntry = compileStrictObject(config.inputSchema ?? {}, false); + this._tools.set(name, { + name, + description: config.description ?? '', + inputSchema: compiledEntry.jsonSchema, + serialized: compiledEntry.serializedSchema, + diagnosticCatalog: compiledEntry.diagnosticCatalog, + handler, + }); + this._requestHandlers.set(`tools/call:${name}`, handler); + } + + listRegisteredTools() { + return [...this._tools.values()].map(({ name, description, inputSchema }) => ({ + name, + description, + inputSchema, + })); + } + + async close() { + this.closed = true; + this._tools.clear(); + this._requestHandlers.clear(); + this._notificationHandlers.clear(); + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/package.json b/questions/perf-mcp-hosttools-churn/v1/candidate/package.json new file mode 100644 index 0000000..76ed3c8 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mcp-hosttools-churn", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node --expose-gc bench/workload.mjs" + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/src/host-tool-caller.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/src/host-tool-caller.mjs new file mode 100644 index 0000000..4c26c5e --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/src/host-tool-caller.mjs @@ -0,0 +1,39 @@ +let providers = []; +let providerOwner = null; + +export function setHostToolProviders(current, owner) { + providers = [...current]; + providerOwner = owner ? { ...owner } : null; +} + +export function clearHostToolProviders() { + providers = []; + providerOwner = null; +} + +function pluginContext(caller, workingDir) { + const context = { + agentKind: 'claude-code', + workingDir, + hostCaller: caller, + }; + context.getSessionContext = () => context; + return context; +} + +export function createHostToolRuntime(server, caller, workingDir = '') { + if ( + !providerOwner + || !caller + || providerOwner.dataOwnerId !== caller.dataOwnerId + || providerOwner.ownerGeneration !== caller.ownerGeneration + ) { + return null; + } + const context = pluginContext(caller, workingDir); + const provider = providers.find((item) => item.name === server && typeof item.toHostTools === 'function'); + if (!provider || provider.isEnabled?.(context) === false) { + return null; + } + return provider.toHostTools(context); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/src/providers.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/src/providers.mjs new file mode 100644 index 0000000..c797197 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/src/providers.mjs @@ -0,0 +1,88 @@ +import { + createBrowserMcpServer, + createCindyDocsMcpServer, + createSchedulerMcpServer, + createSshMcpServer, + createXdtHelperMcpServer, +} from './servers.mjs'; +import { resolveLiziMcpSessionContext } from './session-context.mjs'; + +function selected(enabled, id) { + return enabled === null || enabled.has(id); +} + +export function createLiziMcpProviders(opts = {}) { + const enabled = opts.enabled ? new Set(opts.enabled) : null; + const providers = []; + + if (opts.browser && selected(enabled, 'cindy_browser')) { + const buildDeps = (ctx) => ({ + ...opts.browser, + getSessionId: () => resolveLiziMcpSessionContext(ctx).sessionId ?? null, + }); + providers.push({ + name: 'cindy_browser', + toHostTools: (ctx) => createBrowserMcpServer(buildDeps(ctx)).hostTools, + toMcpServer: (ctx) => createBrowserMcpServer(buildDeps(ctx)), + }); + } + + if (opts.scheduler && selected(enabled, 'cindy_scheduler')) { + const createServer = (ctx) => createSchedulerMcpServer(opts.scheduler, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_scheduler', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.ssh && selected(enabled, 'cindy_ssh')) { + providers.push({ + name: 'cindy_ssh', + toHostTools: () => createSshMcpServer(opts.ssh).hostTools, + toMcpServer: () => createSshMcpServer(opts.ssh), + }); + } + + if (opts.xdtHelper && selected(enabled, 'cindy_helper')) { + const createServer = (ctx) => createXdtHelperMcpServer(opts.xdtHelper, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + remoteHostId: ctx.remoteHostId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_helper', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.docs && selected(enabled, 'cindy_docs')) { + const createServer = (ctx) => createCindyDocsMcpServer(opts.docs, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_docs', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + return providers; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/src/servers.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/src/servers.mjs new file mode 100644 index 0000000..0f52ed7 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/src/servers.mjs @@ -0,0 +1,659 @@ +import { McpServer, z } from '../lib/mcp-sdk.mjs'; +import { HostToolRegistry, jsonTextResult } from './tool-registry.mjs'; +import { resolveLiziMcpSessionContext } from './session-context.mjs'; + +// --------------------------------------------------------------------------- +// Module-level tool input shapes (~34 tools across 5 MCP servers) +// --------------------------------------------------------------------------- +const SHAPES = { + // cindy_helper (16 tools) + storage_request: { + op: z.enum(['providers', 'call']), + provider: z.optional(z.string({ min: 1, max: 64 })), + request: z.optional(z.record()), + }, + get_capabilities: { + includeExperimental: z.optional(z.boolean()), + }, + get_current_session_id: {}, + list_machines: { + onlineOnly: z.optional(z.boolean()), + }, + request_remote_control: { + deviceId: z.string({ min: 1, max: 128 }), + reason: z.optional(z.string({ max: 256 })), + }, + get_app_default_model: { + scope: z.optional(z.enum(['default', 'fast', 'reasoning'])), + }, + set_app_default_model: { + modelId: z.string({ min: 1, max: 128 }), + providerId: z.optional(z.string({ min: 1, max: 64 })), + }, + list_sessions: { + workingDir: z.optional(z.string()), + limit: z.optional(z.number({ min: 1, max: 200 })), + status: z.optional(z.enum(['active', 'archived', 'all'])), + }, + search_chat_history: { + query: z.string({ min: 1, max: 256 }), + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + send_to_session: { + targetSessionId: z.string({ min: 1, max: 128 }), + message: z.string({ min: 1, max: 16384 }), + delivery: z.optional(z.enum(['queue', 'steer'])), + }, + set_current_session_title: { + title: z.string({ min: 1, max: 200 }), + }, + archive_sessions: { + sessionIds: z.array(z.string({ min: 1 })), + }, + list_workdirs: { + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + list_workers: { + includeIdle: z.optional(z.boolean()), + }, + create_worker: { + label: z.string({ min: 1, max: 64 }), + prompt: z.string({ min: 1, max: 8192 }), + workingDir: z.optional(z.string()), + }, + host_diagnostics: { + section: z.optional(z.enum(['summary', 'memory', 'providers'])), + }, + + // cindy_docs (6 tools) + read_sheet: { + path: z.string({ min: 1, max: 512 }), + sheet: z.optional(z.string()), + maxRows: z.optional(z.number({ min: 1, max: 5000 })), + }, + inspect_pdf: { + path: z.string({ min: 1, max: 512 }), + pages: z.optional(z.string()), + }, + make_docx: { + outputPath: z.string({ min: 1, max: 512 }), + markdown: z.string({ min: 1 }), + }, + make_xlsx: { + outputPath: z.string({ min: 1, max: 512 }), + rows: z.array(z.array(z.string())), + }, + make_pptx: { + outputPath: z.string({ min: 1, max: 512 }), + slides: z.array(z.record()), + }, + render_pdf: { + outputPath: z.string({ min: 1, max: 512 }), + html: z.string({ min: 1 }), + }, + + // cindy_scheduler (6 tools) + schedule_list: { + status: z.optional(z.enum(['active', 'paused', 'all'])), + summaryOnly: z.optional(z.boolean()), + }, + schedule_create: { + name: z.string({ min: 1, max: 128 }), + cron: z.string({ min: 1, max: 128 }), + prompt: z.string({ min: 1, max: 4096 }), + }, + schedule_update: { + scheduleId: z.string({ min: 1, max: 128 }), + name: z.optional(z.string({ min: 1, max: 128 })), + cron: z.optional(z.string({ min: 1, max: 128 })), + }, + schedule_delete: { + scheduleId: z.string({ min: 1, max: 128 }), + }, + schedule_silence_current_run: { + reason: z.optional(z.string({ max: 256 })), + }, + schedule_notify_current_run: { + message: z.string({ min: 1, max: 1024 }), + }, + + // cindy_ssh (5 tools) + ssh_list_hosts: { + includeOffline: z.optional(z.boolean()), + }, + ssh_exec: { + host: z.string({ min: 1, max: 128 }), + command: z.string({ min: 1, max: 8192 }), + timeoutMs: z.optional(z.number({ min: 100, max: 120_000 })), + }, + ssh_host_status: { + host: z.string({ min: 1, max: 128 }), + }, + ssh_add_host: { + alias: z.string({ min: 1, max: 64 }), + hostname: z.string({ min: 1, max: 256 }), + user: z.optional(z.string({ min: 1, max: 64 })), + }, + ssh_reload_config: {}, + + // cindy_browser (5 tools) + browser_open: { + url: z.string({ min: 1, max: 2048 }), + cacheKey: z.optional(z.string({ min: 1, max: 128 })), + }, + browser_snapshot: { + includeLinks: z.optional(z.boolean()), + }, + browser_click: { + ref: z.string({ min: 1, max: 64 }), + }, + browser_read_cache: { + cacheKey: z.string({ min: 1, max: 128 }), + }, + browser_set_rules_backend: { + backend: z.enum(['all', 'playwright', 'cdp']), + }, +}; + +function registerEntryTools(server, registry) { + server.registerTool('list_tools', { + description: `Discover tools on ${registry.serverName}`, + inputSchema: { category: z.optional(z.string()) }, + }, async (args) => jsonTextResult({ ok: true, tools: registry.list(args?.category) })); + + server.registerTool('call_tool', { + description: `Invoke a tool on ${registry.serverName}`, + inputSchema: { name: z.string({ min: 1 }), args: z.optional(z.record()) }, + }, async (args, signal) => registry.call(args.name, args.args, signal)); +} + +// --------------------------------------------------------------------------- +// 1. cindy_helper (16 tools) +// --------------------------------------------------------------------------- +function registerXdtHelperTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'storage_request', + category: 'storage', + description: 'Invoke host-managed plugin storage provider.', + inputShape: SHAPES.storage_request, + handler: async (args) => { + const ctx = ctxNow(); + if (deps.authorizeCall) { + const auth = await deps.authorizeCall({ + server: 'cindy_helper', + tool: 'storage_request', + args, + caller: ctx.hostCaller, + sessionId: ctx.sessionId, + }); + if (!auth?.ok) return jsonTextResult({ ok: false, errorCode: auth?.errorCode ?? 'PERMISSION_DENIED' }, true); + } + if (!deps.storage?.call) return jsonTextResult({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' }, true); + const out = await deps.storage.call(ctx, args); + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'get_capabilities', + category: 'cindy', + description: 'Inspect Cindy host capabilities.', + inputShape: SHAPES.get_capabilities, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ + ok: true, + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + sessionId: ctx.sessionId ?? null, + caller: ctx.hostCaller?.pluginId ?? null, + }); + }, + }); + + registry.register({ + name: 'get_current_session_id', + category: 'cindy', + description: 'Return the active session identifier.', + inputShape: SHAPES.get_current_session_id, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, sessionId: ctx.sessionId ?? null, workingDir: ctx.workingDir }); + }, + }); + + registry.register({ + name: 'list_machines', + category: 'cindy', + description: 'List paired desktop machines.', + inputShape: SHAPES.list_machines, + handler: async (args) => { + const res = deps.machines?.list ? await deps.machines.list(ctxNow(), args) : { ok: true, machines: [] }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'request_remote_control', + category: 'cindy', + description: 'Request remote control approval for a device.', + inputShape: SHAPES.request_remote_control, + handler: async (args) => { + const res = deps.machines?.requestRemoteControl + ? await deps.machines.requestRemoteControl(ctxNow(), args) + : { ok: true, deviceId: args.deviceId }; + return jsonTextResult(res); + }, + }); + + const isRemote = Boolean(sessionCtx?.remoteHostId); + registry.register({ + name: 'get_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Read default model configuration.', + inputShape: SHAPES.get_app_default_model, + handler: async (args) => { + const ctx = ctxNow(); + const res = deps.appModels?.models + ? await deps.appModels.models(ctx, args) + : { ok: true, scope: args.scope ?? 'default', remote: isRemote }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'set_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Update default model configuration.', + inputShape: SHAPES.set_app_default_model, + handler: async (args) => jsonTextResult({ ok: true, modelId: args.modelId }), + }); + + registry.register({ + name: 'list_sessions', + category: 'history', + description: 'List sessions for the active account.', + inputShape: SHAPES.list_sessions, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, workingDir: args.workingDir ?? ctx.workingDir, sessions: [] }); + }, + }); + + registry.register({ + name: 'search_chat_history', + category: 'history', + description: 'Search past session transcripts.', + inputShape: SHAPES.search_chat_history, + handler: async (args) => jsonTextResult({ ok: true, query: args.query, hits: [] }), + }); + + registry.register({ + name: 'send_to_session', + category: 'handoff', + description: 'Send a handoff message to another session.', + inputShape: SHAPES.send_to_session, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, from: ctx.sessionId ?? null, to: args.targetSessionId }); + }, + }); + + registry.register({ + name: 'set_current_session_title', + category: 'control', + description: 'Rename the active session.', + inputShape: SHAPES.set_current_session_title, + handler: async (args) => jsonTextResult({ ok: true, title: args.title, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'archive_sessions', + category: 'control', + description: 'Archive one or more sessions.', + inputShape: SHAPES.archive_sessions, + handler: async (args) => jsonTextResult({ ok: true, archived: args.sessionIds.length }), + }); + + registry.register({ + name: 'list_workdirs', + category: 'history', + description: 'List known project working directories.', + inputShape: SHAPES.list_workdirs, + handler: async () => jsonTextResult({ ok: true, workdirs: [] }), + }); + + registry.register({ + name: 'list_workers', + category: 'control', + description: 'List active background workers.', + inputShape: SHAPES.list_workers, + handler: async () => jsonTextResult({ ok: true, workers: [] }), + }); + + registry.register({ + name: 'create_worker', + category: 'control', + description: 'Create a delegated worker session.', + inputShape: SHAPES.create_worker, + handler: async (args) => jsonTextResult({ ok: true, label: args.label, workingDir: args.workingDir ?? ctxNow().workingDir }), + }); + + registry.register({ + name: 'host_diagnostics', + category: 'cindy', + description: 'Read non-sensitive host runtime diagnostics.', + inputShape: SHAPES.host_diagnostics, + handler: async (args) => jsonTextResult({ ok: true, section: args.section ?? 'summary', caller: ctxNow().hostCaller?.pluginId ?? null }), + }); +} + +export function createXdtHelperMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_helper', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_helper'); + registerXdtHelperTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 2. cindy_docs (6 tools) +// --------------------------------------------------------------------------- +function registerCindyDocsTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'read_sheet', + category: 'docs', + description: 'Read a CSV or spreadsheet inside the active working directory.', + inputShape: SHAPES.read_sheet, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + const data = deps.readSheet + ? await deps.readSheet(ctx, args) + : { ok: true, workingDir: ctx.workingDir, path: args.path }; + return jsonTextResult(data); + }, + }); + + registry.register({ + name: 'inspect_pdf', + category: 'docs', + description: 'Inspect PDF metadata and page outlines.', + inputShape: SHAPES.inspect_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, path: args.path, pages: 1 }); + }, + }); + + registry.register({ + name: 'make_docx', + category: 'docs', + description: 'Generate a DOCX file.', + inputShape: SHAPES.make_docx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); + + registry.register({ + name: 'make_xlsx', + category: 'docs', + description: 'Generate an XLSX spreadsheet.', + inputShape: SHAPES.make_xlsx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, rows: args.rows.length }); + }, + }); + + registry.register({ + name: 'make_pptx', + category: 'docs', + description: 'Generate a PPTX deck.', + inputShape: SHAPES.make_pptx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, slides: args.slides.length }); + }, + }); + + registry.register({ + name: 'render_pdf', + category: 'docs', + description: 'Render HTML to PDF.', + inputShape: SHAPES.render_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); +} + +export function createCindyDocsMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_docs', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_docs'); + registerCindyDocsTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 3. cindy_scheduler (6 tools) +// --------------------------------------------------------------------------- +function registerSchedulerTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'schedule_list', + category: 'scheduler', + description: 'List configured schedules.', + inputShape: SHAPES.schedule_list, + handler: async (args) => { + const ctx = ctxNow(); + const out = deps.list + ? await deps.list(ctx, args) + : { ok: true, schedules: [], caller: ctx.hostCaller?.pluginId ?? null, sessionId: ctx.sessionId ?? null }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'schedule_create', + category: 'scheduler', + description: 'Create a recurring schedule.', + inputShape: SHAPES.schedule_create, + handler: async (args) => jsonTextResult({ ok: true, created: args.name, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'schedule_update', + category: 'scheduler', + description: 'Update an existing schedule.', + inputShape: SHAPES.schedule_update, + handler: async (args) => jsonTextResult({ ok: true, updated: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_delete', + category: 'scheduler', + description: 'Delete a schedule.', + inputShape: SHAPES.schedule_delete, + handler: async (args) => jsonTextResult({ ok: true, deleted: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_silence_current_run', + category: 'scheduler', + description: 'Silence notifications for the current scheduled run.', + inputShape: SHAPES.schedule_silence_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, silenced: true, sessionId: ctx.sessionId, reason: args.reason ?? null }); + }, + }); + + registry.register({ + name: 'schedule_notify_current_run', + category: 'scheduler', + description: 'Emit a user notification for the current scheduled run.', + inputShape: SHAPES.schedule_notify_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, notified: true, sessionId: ctx.sessionId, message: args.message }); + }, + }); +} + +export function createSchedulerMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_scheduler', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_scheduler'); + registerSchedulerTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 4. cindy_ssh (5 tools) +// --------------------------------------------------------------------------- +function registerSshTools(registry, deps) { + registry.register({ + name: 'ssh_list_hosts', + category: 'ssh', + description: 'List configured SSH hosts.', + inputShape: SHAPES.ssh_list_hosts, + handler: async (args) => { + const out = deps.listHosts ? await deps.listHosts(args) : { ok: true, hosts: [] }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_exec', + category: 'ssh', + description: 'Execute a command over SSH.', + inputShape: SHAPES.ssh_exec, + handler: async (args) => { + const out = deps.exec ? await deps.exec(args) : { ok: true, host: args.host, stdout: '' }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_host_status', + category: 'ssh', + description: 'Check SSH host reachability.', + inputShape: SHAPES.ssh_host_status, + handler: async (args) => jsonTextResult({ ok: true, host: args.host, online: true }), + }); + + registry.register({ + name: 'ssh_add_host', + category: 'ssh', + description: 'Register an SSH host alias.', + inputShape: SHAPES.ssh_add_host, + handler: async (args) => jsonTextResult({ ok: true, alias: args.alias }), + }); + + registry.register({ + name: 'ssh_reload_config', + category: 'ssh', + description: 'Reload SSH configuration.', + inputShape: SHAPES.ssh_reload_config, + handler: async () => jsonTextResult({ ok: true, reloaded: true }), + }); +} + +export function createSshMcpServer(deps) { + const server = new McpServer({ name: 'cindy_ssh', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_ssh'); + registerSshTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 5. cindy_browser (5 tools — stateful per-call registry isolation!) +// --------------------------------------------------------------------------- +function registerBrowserTools(registry, deps) { + // Per-runtime mutable BrowserResultCache and rulesBackend (must never leak across calls). + const resultCache = new Map(); + let rulesBackend = 'all'; + + registry.register({ + name: 'browser_open', + category: 'browser', + description: 'Navigate to a URL and optionally cache its snapshot in this browser runtime.', + inputShape: SHAPES.browser_open, + handler: async (args) => { + const res = deps.open + ? await deps.open(args) + : { ok: true, url: args.url, sessionId: deps.getSessionId?.() ?? null }; + if (args.cacheKey) resultCache.set(args.cacheKey, { url: args.url, rulesBackend, res }); + return jsonTextResult({ ...res, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_snapshot', + category: 'browser', + description: 'Take a snapshot of the active browser tab.', + inputShape: SHAPES.browser_snapshot, + handler: async () => jsonTextResult({ + ok: true, + rulesBackend, + cachedKeys: [...resultCache.keys()], + sessionId: deps.getSessionId?.() ?? null, + }), + }); + + registry.register({ + name: 'browser_click', + category: 'browser', + description: 'Click an element reference.', + inputShape: SHAPES.browser_click, + handler: async (args) => jsonTextResult({ ok: true, clicked: args.ref, rulesBackend }), + }); + + registry.register({ + name: 'browser_read_cache', + category: 'browser', + description: 'Read a cached result from this browser runtime.', + inputShape: SHAPES.browser_read_cache, + handler: async (args) => { + const entry = resultCache.get(args.cacheKey); + return jsonTextResult({ ok: true, hit: Boolean(entry), entry: entry ?? null, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_set_rules_backend', + category: 'browser', + description: 'Tailor workflow rules backend for this browser runtime.', + inputShape: SHAPES.browser_set_rules_backend, + handler: async (args) => { + rulesBackend = args.backend; + return jsonTextResult({ ok: true, rulesBackend }); + }, + }); +} + +export function createBrowserMcpServer(deps) { + const server = new McpServer({ name: 'cindy_browser', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_browser'); + registerBrowserTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/src/session-context.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/src/session-context.mjs new file mode 100644 index 0000000..575c191 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/src/session-context.mjs @@ -0,0 +1,40 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; + +const storage = new AsyncLocalStorage(); + +export function runWithLiziMcpSessionContext(ctx, fn) { + return storage.run(ctx, fn); +} + +export function getLiziMcpSessionContext() { + return storage.getStore(); +} + +function withoutSessionAttribution(fallback) { + return { + ...fallback, + workingDir: '', + sessionId: undefined, + sessionInstanceId: undefined, + remoteHostId: undefined, + vendorOptions: undefined, + hostCaller: undefined, + }; +} + +export function resolveLiziMcpSessionContext(fallback) { + if (fallback.getSessionContext) { + return fallback.getSessionContext() ?? withoutSessionAttribution(fallback); + } + if ( + fallback.sessionId + || fallback.hostCaller + || fallback.sessionInstanceId + || fallback.workingDir + || fallback.remoteHostId + || (fallback.vendorOptions && Object.keys(fallback.vendorOptions).length > 0) + ) { + return fallback; + } + return storage.getStore() ?? fallback; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/src/tool-registry.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/src/tool-registry.mjs new file mode 100644 index 0000000..d3e1d4c --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/src/tool-registry.mjs @@ -0,0 +1,86 @@ +import { z } from '../lib/mcp-sdk.mjs'; + +export function jsonTextResult(payload, isError = false) { + return { + isError, + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; +} + +export class HostToolRegistry { + constructor(serverName) { + this.serverName = serverName; + this.tools = new Map(); + this.aliases = new Map(); + } + + register(def) { + if (this.tools.has(def.name) || this.aliases.has(def.name)) { + throw new Error(`[${this.serverName} registry] duplicate tool name: ${def.name}`); + } + this.tools.set(def.name, def); + } + + registerAlias(alias, name) { + if (this.tools.has(alias) || this.aliases.has(alias) || !this.tools.has(name)) { + throw new Error(`[${this.serverName} registry] invalid tool alias: ${alias}`); + } + this.aliases.set(alias, name); + } + + has(name) { + return this.get(name) !== undefined; + } + + get(name) { + return this.tools.get(this.aliases.get(name) ?? name); + } + + list(category) { + const out = []; + for (const tool of this.tools.values()) { + if (tool.hidden) continue; + if (category && tool.category !== category) continue; + out.push({ + name: tool.name, + category: tool.category, + description: tool.description, + }); + } + return out; + } + + describe(name) { + const tool = this.get(name); + if (!tool) return undefined; + return { name: tool.name, category: tool.category }; + } + + async call(name, rawArgs, signal) { + const def = this.get(name); + if (!def) { + return jsonTextResult({ ok: false, errorCode: 'UNKNOWN_TOOL', tool: name }, true); + } + // Baseline: compiles a brand-new strict object schema & JSON schema metadata on every call. + const objSchema = z.strictObject(def.inputShape); + const parsed = objSchema.safeParse(rawArgs ?? {}); + if (!parsed.success) { + return jsonTextResult({ + ok: false, + errorCode: 'INVALID_PARAMS', + issues: parsed.error.issues, + jsonSchema: parsed.error.jsonSchema, + }, true); + } + return def.handler(parsed.data, signal); + } + + buildHostTools(close = async () => {}) { + return { + list: () => this.list().map(({ name, category }) => ({ name, category })), + describe: (name) => this.describe(name), + call: (name, args, signal) => this.call(name, args, signal), + close, + }; + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/candidate/tests/smoke.test.mjs b/questions/perf-mcp-hosttools-churn/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..2054eac --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,137 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; +import { runWithLiziMcpSessionContext } from '../src/session-context.mjs'; + +function parsePayload(result) { + return JSON.parse(result.content[0].text); +} + +test('concurrent async hostTool calls remain isolated per caller and workingDir', async () => { + let releaseA; + let enteredA; + const enteredPromise = new Promise((resolve) => { enteredA = resolve; }); + const gateA = new Promise((resolve) => { releaseA = resolve; }); + + const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { + call: async (ctx, req) => { + if (req.request?.key === 'a') { + enteredA(); + await gateA; + } + return { ok: true, value: `${ctx.hostCaller?.pluginId}@${ctx.workingDir}` }; + }, + }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, path: `${ctx.workingDir}/${args.path}` }), + }, + }); + + const helper = providers.find((p) => p.name === 'cindy_helper'); + const docs = providers.find((p) => p.name === 'cindy_docs'); + + const ctxA = { + agentKind: 'claude-code', + workingDir: '/tmp/root-a', + hostCaller: { kind: 'plugin', pluginId: 'plugin-a', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxA.getSessionContext = () => ctxA; + + const ctxB = { + agentKind: 'claude-code', + workingDir: '/tmp/root-b', + hostCaller: { kind: 'plugin', pluginId: 'plugin-b', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxB.getSessionContext = () => ctxB; + + const [resA, resB, docA, docB] = await runWithLiziMcpSessionContext( + { agentKind: 'codex', workingDir: '/tmp/ambient', sessionId: 'ambient-sess' }, + async () => { + const rtA = helper.toHostTools(ctxA); + const rtB = helper.toHostTools(ctxB); + const dA = docs.toHostTools(ctxA); + const dB = docs.toHostTools(ctxB); + + const pA = rtA.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'a' } }); + await enteredPromise; + const pB = rtB.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'b' } }); + const pDocA = dA.call('read_sheet', { path: 'data.csv' }); + const pDocB = dB.call('read_sheet', { path: 'data.csv' }); + releaseA(); + + const out = await Promise.all([pA, pB, pDocA, pDocB]); + await Promise.all([rtA.close(), rtB.close(), dA.close(), dB.close()]); + return out.map(parsePayload); + }, + ); + + assert.equal(resA.value, 'plugin-a@/tmp/root-a'); + assert.equal(resB.value, 'plugin-b@/tmp/root-b'); + assert.equal(docA.path, '/tmp/root-a/data.csv'); + assert.equal(docB.path, '/tmp/root-b/data.csv'); +}); + +test('cindy_browser stays isolated per call and strict schema rejects unknown keys', async () => { + const providers = createLiziMcpProviders({ + browser: {}, + }); + const browser = providers.find((p) => p.name === 'cindy_browser'); + const ctx = { agentKind: 'claude-code', workingDir: '/tmp/b', sessionId: 's-1' }; + + const rt1 = browser.toHostTools(ctx); + await rt1.call('browser_set_rules_backend', { backend: 'cdp' }); + await rt1.call('browser_open', { url: 'https://example.test', cacheKey: 'k1' }); + assert.equal(parsePayload(await rt1.call('browser_read_cache', { cacheKey: 'k1' })).hit, true); + + // Strict schema rejects unknown keys. + const invalid = parsePayload(await rt1.call('browser_open', { url: 'https://example.test', extraBadKey: 1 })); + assert.equal(invalid.ok, false); + assert.equal(invalid.errorCode, 'INVALID_PARAMS'); + await rt1.close(); + + // Second call gets a clean isolated browser registry. + const rt2 = browser.toHostTools(ctx); + const miss = parsePayload(await rt2.call('browser_read_cache', { cacheKey: 'k1' })); + assert.equal(miss.hit, false); + assert.equal(miss.rulesBackend, 'all'); + await rt2.close(); +}); + +test('setHostToolProviders and clearHostToolProviders invalidate cached runtimes immediately', async () => { + const makeProviders = (label) => createLiziMcpProviders({ + xdtHelper: { storage: { call: async () => ({ ok: true, value: label }) } }, + }); + const owner1 = { dataOwnerId: 'owner-1', ownerGeneration: 1 }; + const owner2 = { dataOwnerId: 'owner-2', ownerGeneration: 2 }; + const caller1 = { kind: 'plugin', pluginId: 'p1', ...owner1 }; + const caller2 = { kind: 'plugin', pluginId: 'p1', ...owner2 }; + + try { + setHostToolProviders(makeProviders('from-owner-1'), owner1); + const rt1 = createHostToolRuntime('cindy_helper', caller1, '/tmp/1'); + assert.ok(rt1); + assert.equal(parsePayload(await rt1.call('storage_request', { op: 'providers' })).value, 'from-owner-1'); + await rt1.close(); + + setHostToolProviders(makeProviders('from-owner-2'), owner2); + assert.equal(createHostToolRuntime('cindy_helper', caller1, '/tmp/1'), null); + const rt2 = createHostToolRuntime('cindy_helper', caller2, '/tmp/2'); + assert.ok(rt2); + assert.equal(parsePayload(await rt2.call('storage_request', { op: 'providers' })).value, 'from-owner-2'); + await rt2.close(); + + clearHostToolProviders(); + assert.equal(createHostToolRuntime('cindy_helper', caller2, '/tmp/2'), null); + } finally { + clearHostToolProviders(); + } +}); diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/CONTRACT.md b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..5d5e0c0 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,34 @@ +# Product & Security Contract + +## 1. Immutable SDK Layer (`lib/mcp-sdk.mjs` — Protected, Do Not Modify) + +- Provides `z` (`string`, `number`, `boolean`, `enum`, `array`, `record`, `object`, `optional`, `strictObject`), `McpServer`, `getSdkStats()`, and `resetSdkStats()`. +- `z.strictObject(shape)` builds a strict validator + JSON Schema descriptor and increments `strictSchemaBuilds`. +- `new McpServer(...)` constructs full MCP protocol tables and increments `mcpServerBuilds`. +- Tool registries must validate incoming arguments via `z.strictObject(def.inputShape)` and return the structured `INVALID_PARAMS` error (including `issues` and `jsonSchema`) on validation failures. + +## 2. Session Context & ALS Isolation (`src/session-context.mjs`) + +- Exports `runWithLiziMcpSessionContext(ctx, fn)`, `getLiziMcpSessionContext()`, and `resolveLiziMcpSessionContext(fallback)`. +- Uses `AsyncLocalStorage` from `node:async_hooks`. +- Fail-closed resolution: + - When `fallback.getSessionContext` is present, its return value is authoritative; returning `undefined` strips all session attribution (`workingDir: ''`, `sessionId: undefined`, `remoteHostId: undefined`, `hostCaller: undefined`, `vendorOptions: undefined`) and MUST NOT inherit an outer ambient `AsyncLocalStorage` store. + - Concrete attribution on `fallback` takes precedence over ambient storage; only an empty placeholder consults `getLiziMcpSessionContext()`. + +## 3. Tool Registry & Servers (`src/tool-registry.mjs`, `src/servers.mjs`) + +- `HostToolRegistry` registers tools (`name`, `category`, `description`, `inputShape`, `handler`, `hidden?`) and aliases, lists non-hidden tools, describes tools by name/alias, and strictly validates arguments on `call(name, rawArgs, signal)`. +- Re-registering or replacing a tool invalidates any cached compiled schema for that tool name. +- `src/servers.mjs` exposes server constructors (`createXdtHelperMcpServer`, `createCindyDocsMcpServer`, `createSchedulerMcpServer`, `createSshMcpServer`, `createBrowserMcpServer`) and may expose lightweight `create*HostTools` factories that build a `HostToolRuntime` without constructing `McpServer`. +- Tool descriptors (`list()` and `describe(name)`) on `hostTools` must remain identical to `create*McpServer(...).hostTools`: + - `cindy_helper`: `get_app_default_model` has category `'settings'` when `!ctx.remoteHostId` and category `'bots'` when `ctx.remoteHostId` is truthy; `request_remote_control` has `{ name: 'request_remote_control', category: 'cindy' }`. + - `cindy_docs`: fails closed with `{ ok: false, errorCode: 'NO_SESSION_CONTEXT' }` when resolved `workingDir` is empty. + - `cindy_browser`: maintains per-call mutable browser cache (`browser_open` / `browser_read_cache`) and `rulesBackend` (`browser_set_rules_backend`), which MUST NOT leak between separate `toHostTools(ctx)` calls. + +## 4. Provider Registry & Host Tool Slot (`src/providers.mjs`, `src/host-tool-caller.mjs`) + +- `createLiziMcpProviders(opts)` returns provider descriptors `{ name, toHostTools(ctx), toMcpServer(ctx), isEnabled?(ctx) }`. +- `setHostToolProviders(providers, owner)`, `clearHostToolProviders()`, and `createHostToolRuntime(server, caller, workingDir?)`: + - `createHostToolRuntime` checks `owner.dataOwnerId` and `owner.ownerGeneration` strictly against `caller`; mismatches return `null`. + - Replacing or clearing providers immediately invalidates cached provider runtimes so subsequent calls reflect the new owner's deps (or return `null` after clear). + - Closing a returned `HostToolRuntime` (`await rt.close()`) must not break subsequent calls obtained from the same provider. diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/ENVIRONMENT.md b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..d0ee8ef --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Heap measurement: `npm run bench` runs Node with `--expose-gc` so heap allocation per call (`KB/call`) is measured cleanly via `process.memoryUsage().heapUsed` deltas. +- Public checks: + - `npm test` — functional and concurrency-isolation smoke tests + - `npm run bench` — representative 300-call schema rebuild count, 200-call heap allocation per call, and throughput benchmark diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/TASK.md b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..b6817c2 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/TASK.md @@ -0,0 +1,22 @@ +# Task + +You are optimizing Cindy's MCP `hostTools` dispatch and strict schema validation pipeline, extracted from `packages/lizi-mcps` and `hostToolCaller`. + +## Observed Production Symptoms + +Plugin host tool calls (`cindy_helper`, `cindy_docs`, `cindy_scheduler`, `cindy_ssh`, `cindy_browser`) currently reconstruct an entire `McpServer`, re-register dozens of tools across registries, and re-compile strict input schemas (`z.strictObject`) on **every single tool call**, causing heavy per-call heap allocation churn, GC pauses, and high CPU overhead. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Eliminate per-call `McpServer` reconstruction, repeated tool registry construction, and repeated strict schema compilation for stateless providers while preserving **100% behavioral and security isolation**: + - Concurrent interleaved async tool calls MUST NEVER leak `hostCaller`, `workingDir`, `sessionId`, or `remoteHostId` across callers or from an outer ambient `AsyncLocalStorage` context. + - A revoked `getSessionContext: () => undefined` MUST fail closed (never falling back to an ambient session context). + - `cindy_browser` MUST remain isolated per call (no cross-call browser session/cache/rules leakage). + - `setHostToolProviders` and `clearHostToolProviders` MUST immediately invalidate previously cached provider runtimes so old account owners are rejected and new account owners never observe stale deps. + - Closing one call's `HostToolRuntime` handle MUST NOT break subsequent calls on the same provider. + - Tool registries MUST continue validating arguments strictly through `z.strictObject` from `../lib/mcp-sdk.mjs` (rejecting unknown keys and invalid types with the exact structured `INVALID_PARAMS` payload and JSON schema). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/bench/workload.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..9e8e942 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,93 @@ +import { performance } from 'node:perf_hooks'; + +import { getSdkStats, resetSdkStats } from '../lib/mcp-sdk.mjs'; +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; + +const owner = { dataOwnerId: 'bench-owner', ownerGeneration: 1 }; +const caller = { kind: 'plugin', pluginId: 'bench-plugin', ...owner }; + +const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { call: async (ctx, req) => ({ ok: true, key: req.request?.key ?? null, dir: ctx.workingDir }) }, + machines: { list: async () => ({ ok: true, machines: [] }) }, + appModels: { models: async () => ({ ok: true, model: 'claude-sonnet' }) }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, file: `${ctx.workingDir}/${args.path}` }), + }, + scheduler: { + list: async (ctx) => ({ ok: true, caller: ctx.hostCaller?.pluginId ?? null, schedules: [] }), + }, + ssh: { + listHosts: async () => ({ ok: true, hosts: ['prod-1'] }), + }, + browser: {}, +}); + +setHostToolProviders(providers, owner); + +const CALL_PLAN = [ + ['cindy_helper', 'storage_request', { op: 'call', provider: 'kv', request: { key: 'k1' } }], + ['cindy_docs', 'read_sheet', { path: 'report.csv', maxRows: 50 }], + ['cindy_scheduler', 'schedule_list', { status: 'active', summaryOnly: true }], + ['cindy_ssh', 'ssh_list_hosts', { includeOffline: false }], +]; + +async function invokeOne(i) { + const [server, tool, args] = CALL_PLAN[i % CALL_PLAN.length]; + const rt = createHostToolRuntime(server, caller, `/tmp/work-${i % 8}`); + const res = await rt.call(tool, args); + await rt.close(); + return res.content[0].text.length; +} + +// 1. Deterministic schema rebuild count across 300 calls +resetSdkStats(); +let totalLen = 0; +for (let i = 0; i < 300; i += 1) { + totalLen += await invokeOne(i); +} +const { strictSchemaBuilds: schemaRebuilds300, mcpServerBuilds: mcpServerBuilds300 } = getSdkStats(); + +// 2. Heap allocation per call across 200 calls (requires --expose-gc) +let heapAllocKbPerCall = null; +if (typeof globalThis.gc === 'function') { + for (let w = 0; w < 20; w += 1) await invokeOne(w); + globalThis.gc(); + globalThis.gc(); + let bytes = 0; + let clean = 0; + let prev = process.memoryUsage().heapUsed; + for (let i = 0; i < 200; i += 1) { + await invokeOne(i); + const cur = process.memoryUsage().heapUsed; + if (cur >= prev) { + bytes += cur - prev; + clean += 1; + } + prev = cur; + } + heapAllocKbPerCall = Number((bytes / 1024 / Math.max(clean, 1)).toFixed(2)); +} + +// 3. Throughput across 300 calls +const t0 = performance.now(); +for (let i = 0; i < 300; i += 1) { + await invokeOne(i); +} +const calls300Ms = Number((performance.now() - t0).toFixed(2)); + +clearHostToolProviders(); + +console.log(JSON.stringify({ + schemaRebuilds300, + mcpServerBuilds300, + heapAllocKbPerCall, + calls300Ms, + checksum: totalLen, +}, null, 2)); diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/lib/mcp-sdk.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/lib/mcp-sdk.mjs new file mode 100644 index 0000000..1b79835 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/lib/mcp-sdk.mjs @@ -0,0 +1,318 @@ +/** + * Protected stand-in for external `zod` strict schema compilation + `@modelcontextprotocol/sdk` McpServer. + * Do not modify this file; optimize `src/` instead. + */ + +const sdkStats = { + strictSchemaBuilds: 0, + mcpServerBuilds: 0, +}; + +export function getSdkStats() { + return { ...sdkStats }; +} + +export function resetSdkStats() { + sdkStats.strictSchemaBuilds = 0; + sdkStats.mcpServerBuilds = 0; +} + +function makeField(kind, opts = {}) { + return { + __zodField: true, + kind, + optional: false, + description: opts.description ?? '', + min: opts.min, + max: opts.max, + pattern: opts.pattern, + values: opts.values, + item: opts.item, + shape: opts.shape, + optionalize() { + return { ...this, optional: true }; + }, + }; +} + +function fieldToJsonSchema(field) { + const base = {}; + if (field.description) base.description = field.description; + switch (field.kind) { + case 'string': + base.type = 'string'; + if (field.min !== undefined) base.minLength = field.min; + if (field.max !== undefined) base.maxLength = field.max; + if (field.pattern) base.pattern = field.pattern.source; + return base; + case 'number': + base.type = 'number'; + if (field.min !== undefined) base.minimum = field.min; + if (field.max !== undefined) base.maximum = field.max; + return base; + case 'boolean': + return { ...base, type: 'boolean' }; + case 'enum': + return { ...base, type: 'string', enum: [...field.values] }; + case 'array': + return { ...base, type: 'array', items: fieldToJsonSchema(field.item) }; + case 'record': + return { ...base, type: 'object', additionalProperties: true }; + case 'object': { + const properties = {}; + const required = []; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + properties[k] = fieldToJsonSchema(sub); + if (!sub.optional) required.push(k); + } + return { ...base, type: 'object', properties, required, additionalProperties: false }; + } + default: + return base; + } +} + +function validateField(field, value, pathStr, issues) { + if (value === undefined) { + if (!field.optional) issues.push({ path: pathStr, message: 'Required' }); + return undefined; + } + switch (field.kind) { + case 'string': + if (typeof value !== 'string') { + issues.push({ path: pathStr, message: 'Expected string' }); + return value; + } + if (field.min !== undefined && value.length < field.min) { + issues.push({ path: pathStr, message: `String must contain at least ${field.min} character(s)` }); + } + if (field.max !== undefined && value.length > field.max) { + issues.push({ path: pathStr, message: `String must contain at most ${field.max} character(s)` }); + } + if (field.pattern && !field.pattern.test(value)) { + issues.push({ path: pathStr, message: 'Invalid string pattern' }); + } + return value; + case 'number': + if (typeof value !== 'number' || !Number.isFinite(value)) { + issues.push({ path: pathStr, message: 'Expected finite number' }); + return value; + } + if (field.min !== undefined && value < field.min) { + issues.push({ path: pathStr, message: `Number must be >= ${field.min}` }); + } + if (field.max !== undefined && value > field.max) { + issues.push({ path: pathStr, message: `Number must be <= ${field.max}` }); + } + return value; + case 'boolean': + if (typeof value !== 'boolean') issues.push({ path: pathStr, message: 'Expected boolean' }); + return value; + case 'enum': + if (!field.values.includes(value)) { + issues.push({ path: pathStr, message: `Invalid enum value; expected one of ${field.values.join(', ')}` }); + } + return value; + case 'array': + if (!Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected array' }); + return value; + } + return value.map((item, idx) => validateField(field.item, item, `${pathStr}[${idx}]`, issues)); + case 'record': + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object record' }); + return value; + } + return { ...value }; + case 'object': { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object' }); + return value; + } + const allowedKeys = new Set(Object.keys(field.shape ?? {})); + const unknown = Object.keys(value).filter((k) => !allowedKeys.has(k)); + if (unknown.length > 0) { + issues.push({ path: pathStr, message: `Unrecognized key(s) in object: ${unknown.join(', ')}` }); + } + const out = {}; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + const parsed = validateField(sub, value[k], pathStr ? `${pathStr}.${k}` : k, issues); + if (parsed !== undefined) out[k] = parsed; + } + return out; + } + default: + return value; + } +} + +/** + * Compiles a strict object schema (mirroring Zod v4 `z.strictObject` + JSON Schema metadata graph). + * Rebuilding this on every tool invocation allocates AST descriptors, JSON Schema tables, and validators. + */ +function compileStrictObject(shape, countStats = true) { + if (countStats) sdkStats.strictSchemaBuilds += 1; + const entries = Object.entries(shape ?? {}); + const allowedKeys = new Set(); + const properties = {}; + const required = []; + const compiledFields = []; + const diagnosticCatalog = new Map(); + + for (const [key, field] of entries) { + allowedKeys.add(key); + const jsonDef = fieldToJsonSchema(field); + properties[key] = jsonDef; + if (!field.optional) required.push(key); + compiledFields.push({ + key, + field, + jsonDef, + validator: (val, issues) => validateField(field, val, key, issues), + }); + // Build eager diagnostic hints & schema draft nodes mirroring Zod v4 schema metadata tables. + diagnosticCatalog.set(key, { + key, + kind: field.kind, + optional: field.optional, + schemaFragment: JSON.stringify(jsonDef), + examples: Array.from({ length: 12 }, (_, idx) => `${key}:${field.kind}:hint_${idx}`), + }); + } + + const jsonSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties, + required, + additionalProperties: false, + }; + const serializedSchema = JSON.stringify(jsonSchema); + + return { + jsonSchema, + serializedSchema, + diagnosticCatalog, + toJsonSchema() { + return jsonSchema; + }, + safeParse(rawArgs) { + if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues: [{ path: '', message: 'Expected object arguments' }], + jsonSchema, + }, + }; + } + const issues = []; + const unknownKeys = []; + for (const key of Object.keys(rawArgs)) { + if (!allowedKeys.has(key)) unknownKeys.push(key); + } + if (unknownKeys.length > 0) { + issues.push({ + path: '', + message: `Unrecognized key(s) in object: ${unknownKeys.join(', ')}`, + }); + } + const data = {}; + for (let i = 0; i < compiledFields.length; i += 1) { + const entry = compiledFields[i]; + const parsed = entry.validator(rawArgs[entry.key], issues); + if (parsed !== undefined) data[entry.key] = parsed; + } + if (issues.length > 0) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues, + jsonSchema, + }, + }; + } + return { success: true, data }; + }, + }; +} + +export const z = { + string: (opts) => makeField('string', opts), + number: (opts) => makeField('number', opts), + boolean: (opts) => makeField('boolean', opts), + enum: (values, opts) => makeField('enum', { ...opts, values }), + array: (item, opts) => makeField('array', { ...opts, item }), + record: (opts) => makeField('record', opts), + object: (shape, opts) => makeField('object', { ...opts, shape }), + optional: (field) => field.optionalize(), + strictObject: (shape) => compileStrictObject(shape, true), +}; + +/** + * Stand-in for `@modelcontextprotocol/sdk` McpServer. + * Constructing an McpServer allocates protocol request/notification handler tables, + * capability manifests, and eager entry tool schemas for stdio/SSE transport. + */ +export class McpServer { + constructor({ name, version = '1.0.0', instructions = '' }) { + sdkStats.mcpServerBuilds += 1; + this.name = name; + this.version = version; + this.instructions = instructions; + this.closed = false; + this._tools = new Map(); + this._requestHandlers = new Map(); + this._notificationHandlers = new Map(); + this._protocolTables = Array.from({ length: 160 }, (_, idx) => ({ + method: `mcp/${name}/op_${idx}`, + schemaDraft: `https://modelcontextprotocol.io/schema/2025-03-26/${name}/${idx}`, + capabilities: { listChanged: true, subscribe: true, progress: true, sampling: idx % 2 === 0 }, + inputEnvelope: { type: 'object', additionalProperties: false, slot: idx, required: ['jsonrpc', 'id', 'method'] }, + metadata: `${name}:${version}:protocol_slot_${idx}:`.repeat(12), + })); + // Eagerly serialize initialization capability manifest for MCP stdio/SSE handshake. + this._manifestJson = JSON.stringify({ + serverInfo: { name, version }, + instructions, + protocolTables: this._protocolTables, + }); + this._capabilities = { + tools: { listChanged: true }, + logging: {}, + prompts: { listChanged: false }, + resources: { subscribe: false, listChanged: false }, + }; + } + + registerTool(name, config, handler) { + const compiledEntry = compileStrictObject(config.inputSchema ?? {}, false); + this._tools.set(name, { + name, + description: config.description ?? '', + inputSchema: compiledEntry.jsonSchema, + serialized: compiledEntry.serializedSchema, + diagnosticCatalog: compiledEntry.diagnosticCatalog, + handler, + }); + this._requestHandlers.set(`tools/call:${name}`, handler); + } + + listRegisteredTools() { + return [...this._tools.values()].map(({ name, description, inputSchema }) => ({ + name, + description, + inputSchema, + })); + } + + async close() { + this.closed = true; + this._tools.clear(); + this._requestHandlers.clear(); + this._notificationHandlers.clear(); + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/package.json b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/package.json new file mode 100644 index 0000000..76ed3c8 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mcp-hosttools-churn", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node --expose-gc bench/workload.mjs" + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/host-tool-caller.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/host-tool-caller.mjs new file mode 100644 index 0000000..4c26c5e --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/host-tool-caller.mjs @@ -0,0 +1,39 @@ +let providers = []; +let providerOwner = null; + +export function setHostToolProviders(current, owner) { + providers = [...current]; + providerOwner = owner ? { ...owner } : null; +} + +export function clearHostToolProviders() { + providers = []; + providerOwner = null; +} + +function pluginContext(caller, workingDir) { + const context = { + agentKind: 'claude-code', + workingDir, + hostCaller: caller, + }; + context.getSessionContext = () => context; + return context; +} + +export function createHostToolRuntime(server, caller, workingDir = '') { + if ( + !providerOwner + || !caller + || providerOwner.dataOwnerId !== caller.dataOwnerId + || providerOwner.ownerGeneration !== caller.ownerGeneration + ) { + return null; + } + const context = pluginContext(caller, workingDir); + const provider = providers.find((item) => item.name === server && typeof item.toHostTools === 'function'); + if (!provider || provider.isEnabled?.(context) === false) { + return null; + } + return provider.toHostTools(context); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/providers.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/providers.mjs new file mode 100644 index 0000000..c797197 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/providers.mjs @@ -0,0 +1,88 @@ +import { + createBrowserMcpServer, + createCindyDocsMcpServer, + createSchedulerMcpServer, + createSshMcpServer, + createXdtHelperMcpServer, +} from './servers.mjs'; +import { resolveLiziMcpSessionContext } from './session-context.mjs'; + +function selected(enabled, id) { + return enabled === null || enabled.has(id); +} + +export function createLiziMcpProviders(opts = {}) { + const enabled = opts.enabled ? new Set(opts.enabled) : null; + const providers = []; + + if (opts.browser && selected(enabled, 'cindy_browser')) { + const buildDeps = (ctx) => ({ + ...opts.browser, + getSessionId: () => resolveLiziMcpSessionContext(ctx).sessionId ?? null, + }); + providers.push({ + name: 'cindy_browser', + toHostTools: (ctx) => createBrowserMcpServer(buildDeps(ctx)).hostTools, + toMcpServer: (ctx) => createBrowserMcpServer(buildDeps(ctx)), + }); + } + + if (opts.scheduler && selected(enabled, 'cindy_scheduler')) { + const createServer = (ctx) => createSchedulerMcpServer(opts.scheduler, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_scheduler', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.ssh && selected(enabled, 'cindy_ssh')) { + providers.push({ + name: 'cindy_ssh', + toHostTools: () => createSshMcpServer(opts.ssh).hostTools, + toMcpServer: () => createSshMcpServer(opts.ssh), + }); + } + + if (opts.xdtHelper && selected(enabled, 'cindy_helper')) { + const createServer = (ctx) => createXdtHelperMcpServer(opts.xdtHelper, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + remoteHostId: ctx.remoteHostId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_helper', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.docs && selected(enabled, 'cindy_docs')) { + const createServer = (ctx) => createCindyDocsMcpServer(opts.docs, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + providers.push({ + name: 'cindy_docs', + toHostTools: (ctx) => createServer(ctx).hostTools, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + return providers; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/servers.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/servers.mjs new file mode 100644 index 0000000..0f52ed7 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/servers.mjs @@ -0,0 +1,659 @@ +import { McpServer, z } from '../lib/mcp-sdk.mjs'; +import { HostToolRegistry, jsonTextResult } from './tool-registry.mjs'; +import { resolveLiziMcpSessionContext } from './session-context.mjs'; + +// --------------------------------------------------------------------------- +// Module-level tool input shapes (~34 tools across 5 MCP servers) +// --------------------------------------------------------------------------- +const SHAPES = { + // cindy_helper (16 tools) + storage_request: { + op: z.enum(['providers', 'call']), + provider: z.optional(z.string({ min: 1, max: 64 })), + request: z.optional(z.record()), + }, + get_capabilities: { + includeExperimental: z.optional(z.boolean()), + }, + get_current_session_id: {}, + list_machines: { + onlineOnly: z.optional(z.boolean()), + }, + request_remote_control: { + deviceId: z.string({ min: 1, max: 128 }), + reason: z.optional(z.string({ max: 256 })), + }, + get_app_default_model: { + scope: z.optional(z.enum(['default', 'fast', 'reasoning'])), + }, + set_app_default_model: { + modelId: z.string({ min: 1, max: 128 }), + providerId: z.optional(z.string({ min: 1, max: 64 })), + }, + list_sessions: { + workingDir: z.optional(z.string()), + limit: z.optional(z.number({ min: 1, max: 200 })), + status: z.optional(z.enum(['active', 'archived', 'all'])), + }, + search_chat_history: { + query: z.string({ min: 1, max: 256 }), + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + send_to_session: { + targetSessionId: z.string({ min: 1, max: 128 }), + message: z.string({ min: 1, max: 16384 }), + delivery: z.optional(z.enum(['queue', 'steer'])), + }, + set_current_session_title: { + title: z.string({ min: 1, max: 200 }), + }, + archive_sessions: { + sessionIds: z.array(z.string({ min: 1 })), + }, + list_workdirs: { + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + list_workers: { + includeIdle: z.optional(z.boolean()), + }, + create_worker: { + label: z.string({ min: 1, max: 64 }), + prompt: z.string({ min: 1, max: 8192 }), + workingDir: z.optional(z.string()), + }, + host_diagnostics: { + section: z.optional(z.enum(['summary', 'memory', 'providers'])), + }, + + // cindy_docs (6 tools) + read_sheet: { + path: z.string({ min: 1, max: 512 }), + sheet: z.optional(z.string()), + maxRows: z.optional(z.number({ min: 1, max: 5000 })), + }, + inspect_pdf: { + path: z.string({ min: 1, max: 512 }), + pages: z.optional(z.string()), + }, + make_docx: { + outputPath: z.string({ min: 1, max: 512 }), + markdown: z.string({ min: 1 }), + }, + make_xlsx: { + outputPath: z.string({ min: 1, max: 512 }), + rows: z.array(z.array(z.string())), + }, + make_pptx: { + outputPath: z.string({ min: 1, max: 512 }), + slides: z.array(z.record()), + }, + render_pdf: { + outputPath: z.string({ min: 1, max: 512 }), + html: z.string({ min: 1 }), + }, + + // cindy_scheduler (6 tools) + schedule_list: { + status: z.optional(z.enum(['active', 'paused', 'all'])), + summaryOnly: z.optional(z.boolean()), + }, + schedule_create: { + name: z.string({ min: 1, max: 128 }), + cron: z.string({ min: 1, max: 128 }), + prompt: z.string({ min: 1, max: 4096 }), + }, + schedule_update: { + scheduleId: z.string({ min: 1, max: 128 }), + name: z.optional(z.string({ min: 1, max: 128 })), + cron: z.optional(z.string({ min: 1, max: 128 })), + }, + schedule_delete: { + scheduleId: z.string({ min: 1, max: 128 }), + }, + schedule_silence_current_run: { + reason: z.optional(z.string({ max: 256 })), + }, + schedule_notify_current_run: { + message: z.string({ min: 1, max: 1024 }), + }, + + // cindy_ssh (5 tools) + ssh_list_hosts: { + includeOffline: z.optional(z.boolean()), + }, + ssh_exec: { + host: z.string({ min: 1, max: 128 }), + command: z.string({ min: 1, max: 8192 }), + timeoutMs: z.optional(z.number({ min: 100, max: 120_000 })), + }, + ssh_host_status: { + host: z.string({ min: 1, max: 128 }), + }, + ssh_add_host: { + alias: z.string({ min: 1, max: 64 }), + hostname: z.string({ min: 1, max: 256 }), + user: z.optional(z.string({ min: 1, max: 64 })), + }, + ssh_reload_config: {}, + + // cindy_browser (5 tools) + browser_open: { + url: z.string({ min: 1, max: 2048 }), + cacheKey: z.optional(z.string({ min: 1, max: 128 })), + }, + browser_snapshot: { + includeLinks: z.optional(z.boolean()), + }, + browser_click: { + ref: z.string({ min: 1, max: 64 }), + }, + browser_read_cache: { + cacheKey: z.string({ min: 1, max: 128 }), + }, + browser_set_rules_backend: { + backend: z.enum(['all', 'playwright', 'cdp']), + }, +}; + +function registerEntryTools(server, registry) { + server.registerTool('list_tools', { + description: `Discover tools on ${registry.serverName}`, + inputSchema: { category: z.optional(z.string()) }, + }, async (args) => jsonTextResult({ ok: true, tools: registry.list(args?.category) })); + + server.registerTool('call_tool', { + description: `Invoke a tool on ${registry.serverName}`, + inputSchema: { name: z.string({ min: 1 }), args: z.optional(z.record()) }, + }, async (args, signal) => registry.call(args.name, args.args, signal)); +} + +// --------------------------------------------------------------------------- +// 1. cindy_helper (16 tools) +// --------------------------------------------------------------------------- +function registerXdtHelperTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'storage_request', + category: 'storage', + description: 'Invoke host-managed plugin storage provider.', + inputShape: SHAPES.storage_request, + handler: async (args) => { + const ctx = ctxNow(); + if (deps.authorizeCall) { + const auth = await deps.authorizeCall({ + server: 'cindy_helper', + tool: 'storage_request', + args, + caller: ctx.hostCaller, + sessionId: ctx.sessionId, + }); + if (!auth?.ok) return jsonTextResult({ ok: false, errorCode: auth?.errorCode ?? 'PERMISSION_DENIED' }, true); + } + if (!deps.storage?.call) return jsonTextResult({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' }, true); + const out = await deps.storage.call(ctx, args); + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'get_capabilities', + category: 'cindy', + description: 'Inspect Cindy host capabilities.', + inputShape: SHAPES.get_capabilities, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ + ok: true, + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + sessionId: ctx.sessionId ?? null, + caller: ctx.hostCaller?.pluginId ?? null, + }); + }, + }); + + registry.register({ + name: 'get_current_session_id', + category: 'cindy', + description: 'Return the active session identifier.', + inputShape: SHAPES.get_current_session_id, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, sessionId: ctx.sessionId ?? null, workingDir: ctx.workingDir }); + }, + }); + + registry.register({ + name: 'list_machines', + category: 'cindy', + description: 'List paired desktop machines.', + inputShape: SHAPES.list_machines, + handler: async (args) => { + const res = deps.machines?.list ? await deps.machines.list(ctxNow(), args) : { ok: true, machines: [] }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'request_remote_control', + category: 'cindy', + description: 'Request remote control approval for a device.', + inputShape: SHAPES.request_remote_control, + handler: async (args) => { + const res = deps.machines?.requestRemoteControl + ? await deps.machines.requestRemoteControl(ctxNow(), args) + : { ok: true, deviceId: args.deviceId }; + return jsonTextResult(res); + }, + }); + + const isRemote = Boolean(sessionCtx?.remoteHostId); + registry.register({ + name: 'get_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Read default model configuration.', + inputShape: SHAPES.get_app_default_model, + handler: async (args) => { + const ctx = ctxNow(); + const res = deps.appModels?.models + ? await deps.appModels.models(ctx, args) + : { ok: true, scope: args.scope ?? 'default', remote: isRemote }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'set_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Update default model configuration.', + inputShape: SHAPES.set_app_default_model, + handler: async (args) => jsonTextResult({ ok: true, modelId: args.modelId }), + }); + + registry.register({ + name: 'list_sessions', + category: 'history', + description: 'List sessions for the active account.', + inputShape: SHAPES.list_sessions, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, workingDir: args.workingDir ?? ctx.workingDir, sessions: [] }); + }, + }); + + registry.register({ + name: 'search_chat_history', + category: 'history', + description: 'Search past session transcripts.', + inputShape: SHAPES.search_chat_history, + handler: async (args) => jsonTextResult({ ok: true, query: args.query, hits: [] }), + }); + + registry.register({ + name: 'send_to_session', + category: 'handoff', + description: 'Send a handoff message to another session.', + inputShape: SHAPES.send_to_session, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, from: ctx.sessionId ?? null, to: args.targetSessionId }); + }, + }); + + registry.register({ + name: 'set_current_session_title', + category: 'control', + description: 'Rename the active session.', + inputShape: SHAPES.set_current_session_title, + handler: async (args) => jsonTextResult({ ok: true, title: args.title, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'archive_sessions', + category: 'control', + description: 'Archive one or more sessions.', + inputShape: SHAPES.archive_sessions, + handler: async (args) => jsonTextResult({ ok: true, archived: args.sessionIds.length }), + }); + + registry.register({ + name: 'list_workdirs', + category: 'history', + description: 'List known project working directories.', + inputShape: SHAPES.list_workdirs, + handler: async () => jsonTextResult({ ok: true, workdirs: [] }), + }); + + registry.register({ + name: 'list_workers', + category: 'control', + description: 'List active background workers.', + inputShape: SHAPES.list_workers, + handler: async () => jsonTextResult({ ok: true, workers: [] }), + }); + + registry.register({ + name: 'create_worker', + category: 'control', + description: 'Create a delegated worker session.', + inputShape: SHAPES.create_worker, + handler: async (args) => jsonTextResult({ ok: true, label: args.label, workingDir: args.workingDir ?? ctxNow().workingDir }), + }); + + registry.register({ + name: 'host_diagnostics', + category: 'cindy', + description: 'Read non-sensitive host runtime diagnostics.', + inputShape: SHAPES.host_diagnostics, + handler: async (args) => jsonTextResult({ ok: true, section: args.section ?? 'summary', caller: ctxNow().hostCaller?.pluginId ?? null }), + }); +} + +export function createXdtHelperMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_helper', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_helper'); + registerXdtHelperTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 2. cindy_docs (6 tools) +// --------------------------------------------------------------------------- +function registerCindyDocsTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'read_sheet', + category: 'docs', + description: 'Read a CSV or spreadsheet inside the active working directory.', + inputShape: SHAPES.read_sheet, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + const data = deps.readSheet + ? await deps.readSheet(ctx, args) + : { ok: true, workingDir: ctx.workingDir, path: args.path }; + return jsonTextResult(data); + }, + }); + + registry.register({ + name: 'inspect_pdf', + category: 'docs', + description: 'Inspect PDF metadata and page outlines.', + inputShape: SHAPES.inspect_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, path: args.path, pages: 1 }); + }, + }); + + registry.register({ + name: 'make_docx', + category: 'docs', + description: 'Generate a DOCX file.', + inputShape: SHAPES.make_docx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); + + registry.register({ + name: 'make_xlsx', + category: 'docs', + description: 'Generate an XLSX spreadsheet.', + inputShape: SHAPES.make_xlsx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, rows: args.rows.length }); + }, + }); + + registry.register({ + name: 'make_pptx', + category: 'docs', + description: 'Generate a PPTX deck.', + inputShape: SHAPES.make_pptx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, slides: args.slides.length }); + }, + }); + + registry.register({ + name: 'render_pdf', + category: 'docs', + description: 'Render HTML to PDF.', + inputShape: SHAPES.render_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); +} + +export function createCindyDocsMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_docs', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_docs'); + registerCindyDocsTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 3. cindy_scheduler (6 tools) +// --------------------------------------------------------------------------- +function registerSchedulerTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'schedule_list', + category: 'scheduler', + description: 'List configured schedules.', + inputShape: SHAPES.schedule_list, + handler: async (args) => { + const ctx = ctxNow(); + const out = deps.list + ? await deps.list(ctx, args) + : { ok: true, schedules: [], caller: ctx.hostCaller?.pluginId ?? null, sessionId: ctx.sessionId ?? null }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'schedule_create', + category: 'scheduler', + description: 'Create a recurring schedule.', + inputShape: SHAPES.schedule_create, + handler: async (args) => jsonTextResult({ ok: true, created: args.name, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'schedule_update', + category: 'scheduler', + description: 'Update an existing schedule.', + inputShape: SHAPES.schedule_update, + handler: async (args) => jsonTextResult({ ok: true, updated: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_delete', + category: 'scheduler', + description: 'Delete a schedule.', + inputShape: SHAPES.schedule_delete, + handler: async (args) => jsonTextResult({ ok: true, deleted: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_silence_current_run', + category: 'scheduler', + description: 'Silence notifications for the current scheduled run.', + inputShape: SHAPES.schedule_silence_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, silenced: true, sessionId: ctx.sessionId, reason: args.reason ?? null }); + }, + }); + + registry.register({ + name: 'schedule_notify_current_run', + category: 'scheduler', + description: 'Emit a user notification for the current scheduled run.', + inputShape: SHAPES.schedule_notify_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, notified: true, sessionId: ctx.sessionId, message: args.message }); + }, + }); +} + +export function createSchedulerMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_scheduler', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_scheduler'); + registerSchedulerTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 4. cindy_ssh (5 tools) +// --------------------------------------------------------------------------- +function registerSshTools(registry, deps) { + registry.register({ + name: 'ssh_list_hosts', + category: 'ssh', + description: 'List configured SSH hosts.', + inputShape: SHAPES.ssh_list_hosts, + handler: async (args) => { + const out = deps.listHosts ? await deps.listHosts(args) : { ok: true, hosts: [] }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_exec', + category: 'ssh', + description: 'Execute a command over SSH.', + inputShape: SHAPES.ssh_exec, + handler: async (args) => { + const out = deps.exec ? await deps.exec(args) : { ok: true, host: args.host, stdout: '' }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_host_status', + category: 'ssh', + description: 'Check SSH host reachability.', + inputShape: SHAPES.ssh_host_status, + handler: async (args) => jsonTextResult({ ok: true, host: args.host, online: true }), + }); + + registry.register({ + name: 'ssh_add_host', + category: 'ssh', + description: 'Register an SSH host alias.', + inputShape: SHAPES.ssh_add_host, + handler: async (args) => jsonTextResult({ ok: true, alias: args.alias }), + }); + + registry.register({ + name: 'ssh_reload_config', + category: 'ssh', + description: 'Reload SSH configuration.', + inputShape: SHAPES.ssh_reload_config, + handler: async () => jsonTextResult({ ok: true, reloaded: true }), + }); +} + +export function createSshMcpServer(deps) { + const server = new McpServer({ name: 'cindy_ssh', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_ssh'); + registerSshTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 5. cindy_browser (5 tools — stateful per-call registry isolation!) +// --------------------------------------------------------------------------- +function registerBrowserTools(registry, deps) { + // Per-runtime mutable BrowserResultCache and rulesBackend (must never leak across calls). + const resultCache = new Map(); + let rulesBackend = 'all'; + + registry.register({ + name: 'browser_open', + category: 'browser', + description: 'Navigate to a URL and optionally cache its snapshot in this browser runtime.', + inputShape: SHAPES.browser_open, + handler: async (args) => { + const res = deps.open + ? await deps.open(args) + : { ok: true, url: args.url, sessionId: deps.getSessionId?.() ?? null }; + if (args.cacheKey) resultCache.set(args.cacheKey, { url: args.url, rulesBackend, res }); + return jsonTextResult({ ...res, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_snapshot', + category: 'browser', + description: 'Take a snapshot of the active browser tab.', + inputShape: SHAPES.browser_snapshot, + handler: async () => jsonTextResult({ + ok: true, + rulesBackend, + cachedKeys: [...resultCache.keys()], + sessionId: deps.getSessionId?.() ?? null, + }), + }); + + registry.register({ + name: 'browser_click', + category: 'browser', + description: 'Click an element reference.', + inputShape: SHAPES.browser_click, + handler: async (args) => jsonTextResult({ ok: true, clicked: args.ref, rulesBackend }), + }); + + registry.register({ + name: 'browser_read_cache', + category: 'browser', + description: 'Read a cached result from this browser runtime.', + inputShape: SHAPES.browser_read_cache, + handler: async (args) => { + const entry = resultCache.get(args.cacheKey); + return jsonTextResult({ ok: true, hit: Boolean(entry), entry: entry ?? null, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_set_rules_backend', + category: 'browser', + description: 'Tailor workflow rules backend for this browser runtime.', + inputShape: SHAPES.browser_set_rules_backend, + handler: async (args) => { + rulesBackend = args.backend; + return jsonTextResult({ ok: true, rulesBackend }); + }, + }); +} + +export function createBrowserMcpServer(deps) { + const server = new McpServer({ name: 'cindy_browser', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_browser'); + registerBrowserTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/session-context.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/session-context.mjs new file mode 100644 index 0000000..575c191 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/session-context.mjs @@ -0,0 +1,40 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; + +const storage = new AsyncLocalStorage(); + +export function runWithLiziMcpSessionContext(ctx, fn) { + return storage.run(ctx, fn); +} + +export function getLiziMcpSessionContext() { + return storage.getStore(); +} + +function withoutSessionAttribution(fallback) { + return { + ...fallback, + workingDir: '', + sessionId: undefined, + sessionInstanceId: undefined, + remoteHostId: undefined, + vendorOptions: undefined, + hostCaller: undefined, + }; +} + +export function resolveLiziMcpSessionContext(fallback) { + if (fallback.getSessionContext) { + return fallback.getSessionContext() ?? withoutSessionAttribution(fallback); + } + if ( + fallback.sessionId + || fallback.hostCaller + || fallback.sessionInstanceId + || fallback.workingDir + || fallback.remoteHostId + || (fallback.vendorOptions && Object.keys(fallback.vendorOptions).length > 0) + ) { + return fallback; + } + return storage.getStore() ?? fallback; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/tool-registry.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/tool-registry.mjs new file mode 100644 index 0000000..c3db04e --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/src/tool-registry.mjs @@ -0,0 +1,93 @@ +import { z } from '../lib/mcp-sdk.mjs'; + +// Incomplete optimization: caches compiled schemas by shape only, while providers still rebuild +// McpServer and all tool registries on every call. +const globalCompiledSchemas = new WeakMap(); + +export function jsonTextResult(payload, isError = false) { + return { + isError, + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; +} + +export class HostToolRegistry { + constructor(serverName) { + this.serverName = serverName; + this.tools = new Map(); + this.aliases = new Map(); + } + + register(def) { + if (this.tools.has(def.name) || this.aliases.has(def.name)) { + throw new Error(`[${this.serverName} registry] duplicate tool name: ${def.name}`); + } + this.tools.set(def.name, def); + } + + registerAlias(alias, name) { + if (this.tools.has(alias) || this.aliases.has(alias) || !this.tools.has(name)) { + throw new Error(`[${this.serverName} registry] invalid tool alias: ${alias}`); + } + this.aliases.set(alias, name); + } + + has(name) { + return this.get(name) !== undefined; + } + + get(name) { + return this.tools.get(this.aliases.get(name) ?? name); + } + + list(category) { + const out = []; + for (const tool of this.tools.values()) { + if (tool.hidden) continue; + if (category && tool.category !== category) continue; + out.push({ + name: tool.name, + category: tool.category, + description: tool.description, + }); + } + return out; + } + + describe(name) { + const tool = this.get(name); + if (!tool) return undefined; + return { name: tool.name, category: tool.category }; + } + + async call(name, rawArgs, signal) { + const def = this.get(name); + if (!def) { + return jsonTextResult({ ok: false, errorCode: 'UNKNOWN_TOOL', tool: name }, true); + } + let objSchema = globalCompiledSchemas.get(def.inputShape); + if (!objSchema) { + objSchema = z.strictObject(def.inputShape); + globalCompiledSchemas.set(def.inputShape, objSchema); + } + const parsed = objSchema.safeParse(rawArgs ?? {}); + if (!parsed.success) { + return jsonTextResult({ + ok: false, + errorCode: 'INVALID_PARAMS', + issues: parsed.error.issues, + jsonSchema: parsed.error.jsonSchema, + }, true); + } + return def.handler(parsed.data, signal); + } + + buildHostTools(close = async () => {}) { + return { + list: () => this.list().map(({ name, category }) => ({ name, category })), + describe: (name) => this.describe(name), + call: (name, args, signal) => this.call(name, args, signal), + close, + }; + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/tests/smoke.test.mjs b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..2054eac --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,137 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; +import { runWithLiziMcpSessionContext } from '../src/session-context.mjs'; + +function parsePayload(result) { + return JSON.parse(result.content[0].text); +} + +test('concurrent async hostTool calls remain isolated per caller and workingDir', async () => { + let releaseA; + let enteredA; + const enteredPromise = new Promise((resolve) => { enteredA = resolve; }); + const gateA = new Promise((resolve) => { releaseA = resolve; }); + + const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { + call: async (ctx, req) => { + if (req.request?.key === 'a') { + enteredA(); + await gateA; + } + return { ok: true, value: `${ctx.hostCaller?.pluginId}@${ctx.workingDir}` }; + }, + }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, path: `${ctx.workingDir}/${args.path}` }), + }, + }); + + const helper = providers.find((p) => p.name === 'cindy_helper'); + const docs = providers.find((p) => p.name === 'cindy_docs'); + + const ctxA = { + agentKind: 'claude-code', + workingDir: '/tmp/root-a', + hostCaller: { kind: 'plugin', pluginId: 'plugin-a', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxA.getSessionContext = () => ctxA; + + const ctxB = { + agentKind: 'claude-code', + workingDir: '/tmp/root-b', + hostCaller: { kind: 'plugin', pluginId: 'plugin-b', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxB.getSessionContext = () => ctxB; + + const [resA, resB, docA, docB] = await runWithLiziMcpSessionContext( + { agentKind: 'codex', workingDir: '/tmp/ambient', sessionId: 'ambient-sess' }, + async () => { + const rtA = helper.toHostTools(ctxA); + const rtB = helper.toHostTools(ctxB); + const dA = docs.toHostTools(ctxA); + const dB = docs.toHostTools(ctxB); + + const pA = rtA.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'a' } }); + await enteredPromise; + const pB = rtB.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'b' } }); + const pDocA = dA.call('read_sheet', { path: 'data.csv' }); + const pDocB = dB.call('read_sheet', { path: 'data.csv' }); + releaseA(); + + const out = await Promise.all([pA, pB, pDocA, pDocB]); + await Promise.all([rtA.close(), rtB.close(), dA.close(), dB.close()]); + return out.map(parsePayload); + }, + ); + + assert.equal(resA.value, 'plugin-a@/tmp/root-a'); + assert.equal(resB.value, 'plugin-b@/tmp/root-b'); + assert.equal(docA.path, '/tmp/root-a/data.csv'); + assert.equal(docB.path, '/tmp/root-b/data.csv'); +}); + +test('cindy_browser stays isolated per call and strict schema rejects unknown keys', async () => { + const providers = createLiziMcpProviders({ + browser: {}, + }); + const browser = providers.find((p) => p.name === 'cindy_browser'); + const ctx = { agentKind: 'claude-code', workingDir: '/tmp/b', sessionId: 's-1' }; + + const rt1 = browser.toHostTools(ctx); + await rt1.call('browser_set_rules_backend', { backend: 'cdp' }); + await rt1.call('browser_open', { url: 'https://example.test', cacheKey: 'k1' }); + assert.equal(parsePayload(await rt1.call('browser_read_cache', { cacheKey: 'k1' })).hit, true); + + // Strict schema rejects unknown keys. + const invalid = parsePayload(await rt1.call('browser_open', { url: 'https://example.test', extraBadKey: 1 })); + assert.equal(invalid.ok, false); + assert.equal(invalid.errorCode, 'INVALID_PARAMS'); + await rt1.close(); + + // Second call gets a clean isolated browser registry. + const rt2 = browser.toHostTools(ctx); + const miss = parsePayload(await rt2.call('browser_read_cache', { cacheKey: 'k1' })); + assert.equal(miss.hit, false); + assert.equal(miss.rulesBackend, 'all'); + await rt2.close(); +}); + +test('setHostToolProviders and clearHostToolProviders invalidate cached runtimes immediately', async () => { + const makeProviders = (label) => createLiziMcpProviders({ + xdtHelper: { storage: { call: async () => ({ ok: true, value: label }) } }, + }); + const owner1 = { dataOwnerId: 'owner-1', ownerGeneration: 1 }; + const owner2 = { dataOwnerId: 'owner-2', ownerGeneration: 2 }; + const caller1 = { kind: 'plugin', pluginId: 'p1', ...owner1 }; + const caller2 = { kind: 'plugin', pluginId: 'p1', ...owner2 }; + + try { + setHostToolProviders(makeProviders('from-owner-1'), owner1); + const rt1 = createHostToolRuntime('cindy_helper', caller1, '/tmp/1'); + assert.ok(rt1); + assert.equal(parsePayload(await rt1.call('storage_request', { op: 'providers' })).value, 'from-owner-1'); + await rt1.close(); + + setHostToolProviders(makeProviders('from-owner-2'), owner2); + assert.equal(createHostToolRuntime('cindy_helper', caller1, '/tmp/1'), null); + const rt2 = createHostToolRuntime('cindy_helper', caller2, '/tmp/2'); + assert.ok(rt2); + assert.equal(parsePayload(await rt2.call('storage_request', { op: 'providers' })).value, 'from-owner-2'); + await rt2.close(); + + clearHostToolProviders(); + assert.equal(createHostToolRuntime('cindy_helper', caller2, '/tmp/2'), null); + } finally { + clearHostToolProviders(); + } +}); diff --git a/questions/perf-mcp-hosttools-churn/v1/question.json b/questions/perf-mcp-hosttools-churn/v1/question.json new file mode 100644 index 0000000..f4c0440 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/question.json @@ -0,0 +1,78 @@ +{ + "id": "perf-mcp-hosttools-churn", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "MCP hostTools 按 provider 复用运行时与编译后严格 Schema 性能优化", + "status": "calibrated", + "changeNote": "Eval Bank v2 quantitative performance question extracted from makecindy/cindy PR #15602 (ca8c88794cdb).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "ca8c88794cdbdfaad6950b7f1160bb1b271f2ba4", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "schema_caching", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_isolation", + "correctness_browser_and_invalidation", + "correctness_schema" + ], + "metric": { + "id": "schema_rebuilds", + "label": "Strict schema rebuilds (300 calls)", + "unit": "builds", + "direction": "lower", + "baseline": 300, + "target": 4, + "scale": "log" + } + }, + { + "id": "heap_churn", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_isolation", + "correctness_browser_and_invalidation", + "correctness_schema" + ], + "metric": { + "id": "heap_alloc_kb_per_call", + "label": "Heap allocation per call", + "unit": "KB/call", + "direction": "lower", + "baseline": 300, + "target": 2, + "scale": "log" + } + }, + { + "id": "call_throughput", + "weight": "1/3", + "mode": "metric", + "gate": [ + "correctness_isolation", + "correctness_browser_and_invalidation", + "correctness_schema" + ], + "metric": { + "id": "call_speedup", + "label": "Host tool call speedup", + "unit": "×", + "direction": "higher", + "baseline": 1.5, + "target": 180, + "scale": "log" + } + } + ] +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/CONTRACT.md b/questions/perf-mcp-hosttools-churn/v1/reference/CONTRACT.md new file mode 100644 index 0000000..5d5e0c0 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/CONTRACT.md @@ -0,0 +1,34 @@ +# Product & Security Contract + +## 1. Immutable SDK Layer (`lib/mcp-sdk.mjs` — Protected, Do Not Modify) + +- Provides `z` (`string`, `number`, `boolean`, `enum`, `array`, `record`, `object`, `optional`, `strictObject`), `McpServer`, `getSdkStats()`, and `resetSdkStats()`. +- `z.strictObject(shape)` builds a strict validator + JSON Schema descriptor and increments `strictSchemaBuilds`. +- `new McpServer(...)` constructs full MCP protocol tables and increments `mcpServerBuilds`. +- Tool registries must validate incoming arguments via `z.strictObject(def.inputShape)` and return the structured `INVALID_PARAMS` error (including `issues` and `jsonSchema`) on validation failures. + +## 2. Session Context & ALS Isolation (`src/session-context.mjs`) + +- Exports `runWithLiziMcpSessionContext(ctx, fn)`, `getLiziMcpSessionContext()`, and `resolveLiziMcpSessionContext(fallback)`. +- Uses `AsyncLocalStorage` from `node:async_hooks`. +- Fail-closed resolution: + - When `fallback.getSessionContext` is present, its return value is authoritative; returning `undefined` strips all session attribution (`workingDir: ''`, `sessionId: undefined`, `remoteHostId: undefined`, `hostCaller: undefined`, `vendorOptions: undefined`) and MUST NOT inherit an outer ambient `AsyncLocalStorage` store. + - Concrete attribution on `fallback` takes precedence over ambient storage; only an empty placeholder consults `getLiziMcpSessionContext()`. + +## 3. Tool Registry & Servers (`src/tool-registry.mjs`, `src/servers.mjs`) + +- `HostToolRegistry` registers tools (`name`, `category`, `description`, `inputShape`, `handler`, `hidden?`) and aliases, lists non-hidden tools, describes tools by name/alias, and strictly validates arguments on `call(name, rawArgs, signal)`. +- Re-registering or replacing a tool invalidates any cached compiled schema for that tool name. +- `src/servers.mjs` exposes server constructors (`createXdtHelperMcpServer`, `createCindyDocsMcpServer`, `createSchedulerMcpServer`, `createSshMcpServer`, `createBrowserMcpServer`) and may expose lightweight `create*HostTools` factories that build a `HostToolRuntime` without constructing `McpServer`. +- Tool descriptors (`list()` and `describe(name)`) on `hostTools` must remain identical to `create*McpServer(...).hostTools`: + - `cindy_helper`: `get_app_default_model` has category `'settings'` when `!ctx.remoteHostId` and category `'bots'` when `ctx.remoteHostId` is truthy; `request_remote_control` has `{ name: 'request_remote_control', category: 'cindy' }`. + - `cindy_docs`: fails closed with `{ ok: false, errorCode: 'NO_SESSION_CONTEXT' }` when resolved `workingDir` is empty. + - `cindy_browser`: maintains per-call mutable browser cache (`browser_open` / `browser_read_cache`) and `rulesBackend` (`browser_set_rules_backend`), which MUST NOT leak between separate `toHostTools(ctx)` calls. + +## 4. Provider Registry & Host Tool Slot (`src/providers.mjs`, `src/host-tool-caller.mjs`) + +- `createLiziMcpProviders(opts)` returns provider descriptors `{ name, toHostTools(ctx), toMcpServer(ctx), isEnabled?(ctx) }`. +- `setHostToolProviders(providers, owner)`, `clearHostToolProviders()`, and `createHostToolRuntime(server, caller, workingDir?)`: + - `createHostToolRuntime` checks `owner.dataOwnerId` and `owner.ownerGeneration` strictly against `caller`; mismatches return `null`. + - Replacing or clearing providers immediately invalidates cached provider runtimes so subsequent calls reflect the new owner's deps (or return `null` after clear). + - Closing a returned `HostToolRuntime` (`await rt.close()`) must not break subsequent calls obtained from the same provider. diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/ENVIRONMENT.md b/questions/perf-mcp-hosttools-churn/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..d0ee8ef --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Heap measurement: `npm run bench` runs Node with `--expose-gc` so heap allocation per call (`KB/call`) is measured cleanly via `process.memoryUsage().heapUsed` deltas. +- Public checks: + - `npm test` — functional and concurrency-isolation smoke tests + - `npm run bench` — representative 300-call schema rebuild count, 200-call heap allocation per call, and throughput benchmark diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/TASK.md b/questions/perf-mcp-hosttools-churn/v1/reference/TASK.md new file mode 100644 index 0000000..b6817c2 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/TASK.md @@ -0,0 +1,22 @@ +# Task + +You are optimizing Cindy's MCP `hostTools` dispatch and strict schema validation pipeline, extracted from `packages/lizi-mcps` and `hostToolCaller`. + +## Observed Production Symptoms + +Plugin host tool calls (`cindy_helper`, `cindy_docs`, `cindy_scheduler`, `cindy_ssh`, `cindy_browser`) currently reconstruct an entire `McpServer`, re-register dozens of tools across registries, and re-compile strict input schemas (`z.strictObject`) on **every single tool call**, causing heavy per-call heap allocation churn, GC pauses, and high CPU overhead. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Eliminate per-call `McpServer` reconstruction, repeated tool registry construction, and repeated strict schema compilation for stateless providers while preserving **100% behavioral and security isolation**: + - Concurrent interleaved async tool calls MUST NEVER leak `hostCaller`, `workingDir`, `sessionId`, or `remoteHostId` across callers or from an outer ambient `AsyncLocalStorage` context. + - A revoked `getSessionContext: () => undefined` MUST fail closed (never falling back to an ambient session context). + - `cindy_browser` MUST remain isolated per call (no cross-call browser session/cache/rules leakage). + - `setHostToolProviders` and `clearHostToolProviders` MUST immediately invalidate previously cached provider runtimes so old account owners are rejected and new account owners never observe stale deps. + - Closing one call's `HostToolRuntime` handle MUST NOT break subsequent calls on the same provider. + - Tool registries MUST continue validating arguments strictly through `z.strictObject` from `../lib/mcp-sdk.mjs` (rejecting unknown keys and invalid types with the exact structured `INVALID_PARAMS` payload and JSON schema). +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/bench/workload.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..9e8e942 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/bench/workload.mjs @@ -0,0 +1,93 @@ +import { performance } from 'node:perf_hooks'; + +import { getSdkStats, resetSdkStats } from '../lib/mcp-sdk.mjs'; +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; + +const owner = { dataOwnerId: 'bench-owner', ownerGeneration: 1 }; +const caller = { kind: 'plugin', pluginId: 'bench-plugin', ...owner }; + +const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { call: async (ctx, req) => ({ ok: true, key: req.request?.key ?? null, dir: ctx.workingDir }) }, + machines: { list: async () => ({ ok: true, machines: [] }) }, + appModels: { models: async () => ({ ok: true, model: 'claude-sonnet' }) }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, file: `${ctx.workingDir}/${args.path}` }), + }, + scheduler: { + list: async (ctx) => ({ ok: true, caller: ctx.hostCaller?.pluginId ?? null, schedules: [] }), + }, + ssh: { + listHosts: async () => ({ ok: true, hosts: ['prod-1'] }), + }, + browser: {}, +}); + +setHostToolProviders(providers, owner); + +const CALL_PLAN = [ + ['cindy_helper', 'storage_request', { op: 'call', provider: 'kv', request: { key: 'k1' } }], + ['cindy_docs', 'read_sheet', { path: 'report.csv', maxRows: 50 }], + ['cindy_scheduler', 'schedule_list', { status: 'active', summaryOnly: true }], + ['cindy_ssh', 'ssh_list_hosts', { includeOffline: false }], +]; + +async function invokeOne(i) { + const [server, tool, args] = CALL_PLAN[i % CALL_PLAN.length]; + const rt = createHostToolRuntime(server, caller, `/tmp/work-${i % 8}`); + const res = await rt.call(tool, args); + await rt.close(); + return res.content[0].text.length; +} + +// 1. Deterministic schema rebuild count across 300 calls +resetSdkStats(); +let totalLen = 0; +for (let i = 0; i < 300; i += 1) { + totalLen += await invokeOne(i); +} +const { strictSchemaBuilds: schemaRebuilds300, mcpServerBuilds: mcpServerBuilds300 } = getSdkStats(); + +// 2. Heap allocation per call across 200 calls (requires --expose-gc) +let heapAllocKbPerCall = null; +if (typeof globalThis.gc === 'function') { + for (let w = 0; w < 20; w += 1) await invokeOne(w); + globalThis.gc(); + globalThis.gc(); + let bytes = 0; + let clean = 0; + let prev = process.memoryUsage().heapUsed; + for (let i = 0; i < 200; i += 1) { + await invokeOne(i); + const cur = process.memoryUsage().heapUsed; + if (cur >= prev) { + bytes += cur - prev; + clean += 1; + } + prev = cur; + } + heapAllocKbPerCall = Number((bytes / 1024 / Math.max(clean, 1)).toFixed(2)); +} + +// 3. Throughput across 300 calls +const t0 = performance.now(); +for (let i = 0; i < 300; i += 1) { + await invokeOne(i); +} +const calls300Ms = Number((performance.now() - t0).toFixed(2)); + +clearHostToolProviders(); + +console.log(JSON.stringify({ + schemaRebuilds300, + mcpServerBuilds300, + heapAllocKbPerCall, + calls300Ms, + checksum: totalLen, +}, null, 2)); diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/lib/mcp-sdk.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/lib/mcp-sdk.mjs new file mode 100644 index 0000000..1b79835 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/lib/mcp-sdk.mjs @@ -0,0 +1,318 @@ +/** + * Protected stand-in for external `zod` strict schema compilation + `@modelcontextprotocol/sdk` McpServer. + * Do not modify this file; optimize `src/` instead. + */ + +const sdkStats = { + strictSchemaBuilds: 0, + mcpServerBuilds: 0, +}; + +export function getSdkStats() { + return { ...sdkStats }; +} + +export function resetSdkStats() { + sdkStats.strictSchemaBuilds = 0; + sdkStats.mcpServerBuilds = 0; +} + +function makeField(kind, opts = {}) { + return { + __zodField: true, + kind, + optional: false, + description: opts.description ?? '', + min: opts.min, + max: opts.max, + pattern: opts.pattern, + values: opts.values, + item: opts.item, + shape: opts.shape, + optionalize() { + return { ...this, optional: true }; + }, + }; +} + +function fieldToJsonSchema(field) { + const base = {}; + if (field.description) base.description = field.description; + switch (field.kind) { + case 'string': + base.type = 'string'; + if (field.min !== undefined) base.minLength = field.min; + if (field.max !== undefined) base.maxLength = field.max; + if (field.pattern) base.pattern = field.pattern.source; + return base; + case 'number': + base.type = 'number'; + if (field.min !== undefined) base.minimum = field.min; + if (field.max !== undefined) base.maximum = field.max; + return base; + case 'boolean': + return { ...base, type: 'boolean' }; + case 'enum': + return { ...base, type: 'string', enum: [...field.values] }; + case 'array': + return { ...base, type: 'array', items: fieldToJsonSchema(field.item) }; + case 'record': + return { ...base, type: 'object', additionalProperties: true }; + case 'object': { + const properties = {}; + const required = []; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + properties[k] = fieldToJsonSchema(sub); + if (!sub.optional) required.push(k); + } + return { ...base, type: 'object', properties, required, additionalProperties: false }; + } + default: + return base; + } +} + +function validateField(field, value, pathStr, issues) { + if (value === undefined) { + if (!field.optional) issues.push({ path: pathStr, message: 'Required' }); + return undefined; + } + switch (field.kind) { + case 'string': + if (typeof value !== 'string') { + issues.push({ path: pathStr, message: 'Expected string' }); + return value; + } + if (field.min !== undefined && value.length < field.min) { + issues.push({ path: pathStr, message: `String must contain at least ${field.min} character(s)` }); + } + if (field.max !== undefined && value.length > field.max) { + issues.push({ path: pathStr, message: `String must contain at most ${field.max} character(s)` }); + } + if (field.pattern && !field.pattern.test(value)) { + issues.push({ path: pathStr, message: 'Invalid string pattern' }); + } + return value; + case 'number': + if (typeof value !== 'number' || !Number.isFinite(value)) { + issues.push({ path: pathStr, message: 'Expected finite number' }); + return value; + } + if (field.min !== undefined && value < field.min) { + issues.push({ path: pathStr, message: `Number must be >= ${field.min}` }); + } + if (field.max !== undefined && value > field.max) { + issues.push({ path: pathStr, message: `Number must be <= ${field.max}` }); + } + return value; + case 'boolean': + if (typeof value !== 'boolean') issues.push({ path: pathStr, message: 'Expected boolean' }); + return value; + case 'enum': + if (!field.values.includes(value)) { + issues.push({ path: pathStr, message: `Invalid enum value; expected one of ${field.values.join(', ')}` }); + } + return value; + case 'array': + if (!Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected array' }); + return value; + } + return value.map((item, idx) => validateField(field.item, item, `${pathStr}[${idx}]`, issues)); + case 'record': + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object record' }); + return value; + } + return { ...value }; + case 'object': { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + issues.push({ path: pathStr, message: 'Expected object' }); + return value; + } + const allowedKeys = new Set(Object.keys(field.shape ?? {})); + const unknown = Object.keys(value).filter((k) => !allowedKeys.has(k)); + if (unknown.length > 0) { + issues.push({ path: pathStr, message: `Unrecognized key(s) in object: ${unknown.join(', ')}` }); + } + const out = {}; + for (const [k, sub] of Object.entries(field.shape ?? {})) { + const parsed = validateField(sub, value[k], pathStr ? `${pathStr}.${k}` : k, issues); + if (parsed !== undefined) out[k] = parsed; + } + return out; + } + default: + return value; + } +} + +/** + * Compiles a strict object schema (mirroring Zod v4 `z.strictObject` + JSON Schema metadata graph). + * Rebuilding this on every tool invocation allocates AST descriptors, JSON Schema tables, and validators. + */ +function compileStrictObject(shape, countStats = true) { + if (countStats) sdkStats.strictSchemaBuilds += 1; + const entries = Object.entries(shape ?? {}); + const allowedKeys = new Set(); + const properties = {}; + const required = []; + const compiledFields = []; + const diagnosticCatalog = new Map(); + + for (const [key, field] of entries) { + allowedKeys.add(key); + const jsonDef = fieldToJsonSchema(field); + properties[key] = jsonDef; + if (!field.optional) required.push(key); + compiledFields.push({ + key, + field, + jsonDef, + validator: (val, issues) => validateField(field, val, key, issues), + }); + // Build eager diagnostic hints & schema draft nodes mirroring Zod v4 schema metadata tables. + diagnosticCatalog.set(key, { + key, + kind: field.kind, + optional: field.optional, + schemaFragment: JSON.stringify(jsonDef), + examples: Array.from({ length: 12 }, (_, idx) => `${key}:${field.kind}:hint_${idx}`), + }); + } + + const jsonSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties, + required, + additionalProperties: false, + }; + const serializedSchema = JSON.stringify(jsonSchema); + + return { + jsonSchema, + serializedSchema, + diagnosticCatalog, + toJsonSchema() { + return jsonSchema; + }, + safeParse(rawArgs) { + if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues: [{ path: '', message: 'Expected object arguments' }], + jsonSchema, + }, + }; + } + const issues = []; + const unknownKeys = []; + for (const key of Object.keys(rawArgs)) { + if (!allowedKeys.has(key)) unknownKeys.push(key); + } + if (unknownKeys.length > 0) { + issues.push({ + path: '', + message: `Unrecognized key(s) in object: ${unknownKeys.join(', ')}`, + }); + } + const data = {}; + for (let i = 0; i < compiledFields.length; i += 1) { + const entry = compiledFields[i]; + const parsed = entry.validator(rawArgs[entry.key], issues); + if (parsed !== undefined) data[entry.key] = parsed; + } + if (issues.length > 0) { + return { + success: false, + error: { + code: 'INVALID_PARAMS', + issues, + jsonSchema, + }, + }; + } + return { success: true, data }; + }, + }; +} + +export const z = { + string: (opts) => makeField('string', opts), + number: (opts) => makeField('number', opts), + boolean: (opts) => makeField('boolean', opts), + enum: (values, opts) => makeField('enum', { ...opts, values }), + array: (item, opts) => makeField('array', { ...opts, item }), + record: (opts) => makeField('record', opts), + object: (shape, opts) => makeField('object', { ...opts, shape }), + optional: (field) => field.optionalize(), + strictObject: (shape) => compileStrictObject(shape, true), +}; + +/** + * Stand-in for `@modelcontextprotocol/sdk` McpServer. + * Constructing an McpServer allocates protocol request/notification handler tables, + * capability manifests, and eager entry tool schemas for stdio/SSE transport. + */ +export class McpServer { + constructor({ name, version = '1.0.0', instructions = '' }) { + sdkStats.mcpServerBuilds += 1; + this.name = name; + this.version = version; + this.instructions = instructions; + this.closed = false; + this._tools = new Map(); + this._requestHandlers = new Map(); + this._notificationHandlers = new Map(); + this._protocolTables = Array.from({ length: 160 }, (_, idx) => ({ + method: `mcp/${name}/op_${idx}`, + schemaDraft: `https://modelcontextprotocol.io/schema/2025-03-26/${name}/${idx}`, + capabilities: { listChanged: true, subscribe: true, progress: true, sampling: idx % 2 === 0 }, + inputEnvelope: { type: 'object', additionalProperties: false, slot: idx, required: ['jsonrpc', 'id', 'method'] }, + metadata: `${name}:${version}:protocol_slot_${idx}:`.repeat(12), + })); + // Eagerly serialize initialization capability manifest for MCP stdio/SSE handshake. + this._manifestJson = JSON.stringify({ + serverInfo: { name, version }, + instructions, + protocolTables: this._protocolTables, + }); + this._capabilities = { + tools: { listChanged: true }, + logging: {}, + prompts: { listChanged: false }, + resources: { subscribe: false, listChanged: false }, + }; + } + + registerTool(name, config, handler) { + const compiledEntry = compileStrictObject(config.inputSchema ?? {}, false); + this._tools.set(name, { + name, + description: config.description ?? '', + inputSchema: compiledEntry.jsonSchema, + serialized: compiledEntry.serializedSchema, + diagnosticCatalog: compiledEntry.diagnosticCatalog, + handler, + }); + this._requestHandlers.set(`tools/call:${name}`, handler); + } + + listRegisteredTools() { + return [...this._tools.values()].map(({ name, description, inputSchema }) => ({ + name, + description, + inputSchema, + })); + } + + async close() { + this.closed = true; + this._tools.clear(); + this._requestHandlers.clear(); + this._notificationHandlers.clear(); + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/package.json b/questions/perf-mcp-hosttools-churn/v1/reference/package.json new file mode 100644 index 0000000..76ed3c8 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mcp-hosttools-churn", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node --expose-gc bench/workload.mjs" + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/src/host-tool-caller.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/src/host-tool-caller.mjs new file mode 100644 index 0000000..4c26c5e --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/src/host-tool-caller.mjs @@ -0,0 +1,39 @@ +let providers = []; +let providerOwner = null; + +export function setHostToolProviders(current, owner) { + providers = [...current]; + providerOwner = owner ? { ...owner } : null; +} + +export function clearHostToolProviders() { + providers = []; + providerOwner = null; +} + +function pluginContext(caller, workingDir) { + const context = { + agentKind: 'claude-code', + workingDir, + hostCaller: caller, + }; + context.getSessionContext = () => context; + return context; +} + +export function createHostToolRuntime(server, caller, workingDir = '') { + if ( + !providerOwner + || !caller + || providerOwner.dataOwnerId !== caller.dataOwnerId + || providerOwner.ownerGeneration !== caller.ownerGeneration + ) { + return null; + } + const context = pluginContext(caller, workingDir); + const provider = providers.find((item) => item.name === server && typeof item.toHostTools === 'function'); + if (!provider || provider.isEnabled?.(context) === false) { + return null; + } + return provider.toHostTools(context); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/src/providers.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/src/providers.mjs new file mode 100644 index 0000000..506178f --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/src/providers.mjs @@ -0,0 +1,141 @@ +import { + createBrowserHostTools, + createBrowserMcpServer, + createCindyDocsHostTools, + createCindyDocsMcpServer, + createSchedulerHostTools, + createSchedulerMcpServer, + createSshHostTools, + createSshMcpServer, + createXdtHelperHostTools, + createXdtHelperMcpServer, +} from './servers.mjs'; +import { + getLiziMcpSessionContext, + resolveLiziMcpSessionContext, + runWithLiziMcpSessionContext, +} from './session-context.mjs'; + +function selected(enabled, id) { + return enabled === null || enabled.has(id); +} + +/** + * Authoritative per-call ALS context for cached stateless HostToolRuntimes. + * `bindHostToolRuntime` installs each invocation's caller context via + * `runWithLiziMcpSessionContext`; outside an active call this returns + * `undefined` so `resolveLiziMcpSessionContext` fails closed. + */ +const HOST_TOOLS_ALS_CTX = { + agentKind: 'claude-code', + workingDir: '', + getSessionContext() { + const active = getLiziMcpSessionContext(); + return active?.getSessionContext ? active.getSessionContext() : active; + }, +}; + +function bindHostToolRuntime(shared, ctx) { + return { + ...(shared.list ? { list: shared.list } : {}), + describe: shared.describe, + call(name, args, signal) { + const scopedCtx = ctx.getSessionContext ? ctx : resolveLiziMcpSessionContext(ctx); + return runWithLiziMcpSessionContext(scopedCtx, () => shared.call(name, args, signal)); + }, + close: async () => {}, + }; +} + +export function createLiziMcpProviders(opts = {}) { + const enabled = opts.enabled ? new Set(opts.enabled) : null; + const providers = []; + + if (opts.browser && selected(enabled, 'cindy_browser')) { + const buildDeps = (ctx) => ({ + ...opts.browser, + getSessionId: () => resolveLiziMcpSessionContext(ctx).sessionId ?? null, + }); + providers.push({ + name: 'cindy_browser', + // Keep per-call registry isolation so BrowserResultCache & rulesBackend never leak. + toHostTools: (ctx) => createBrowserHostTools(buildDeps(ctx)), + toMcpServer: (ctx) => createBrowserMcpServer(buildDeps(ctx)), + }); + } + + if (opts.scheduler && selected(enabled, 'cindy_scheduler')) { + const createServer = (ctx) => createSchedulerMcpServer(opts.scheduler, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + let sharedHostTools; + providers.push({ + name: 'cindy_scheduler', + toHostTools: (ctx) => { + sharedHostTools ??= createSchedulerHostTools(opts.scheduler, HOST_TOOLS_ALS_CTX); + return bindHostToolRuntime(sharedHostTools, ctx); + }, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.ssh && selected(enabled, 'cindy_ssh')) { + let sharedHostTools; + providers.push({ + name: 'cindy_ssh', + toHostTools: () => (sharedHostTools ??= createSshHostTools(opts.ssh)), + toMcpServer: () => createSshMcpServer(opts.ssh), + }); + } + + if (opts.xdtHelper && selected(enabled, 'cindy_helper')) { + const createServer = (ctx) => createXdtHelperMcpServer(opts.xdtHelper, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + remoteHostId: ctx.remoteHostId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + let localHostTools; + let remoteHostTools; + providers.push({ + name: 'cindy_helper', + toHostTools: (ctx) => { + const shared = ctx.remoteHostId + ? (remoteHostTools ??= createXdtHelperHostTools(opts.xdtHelper, { ...HOST_TOOLS_ALS_CTX, remoteHostId: '__remote__' })) + : (localHostTools ??= createXdtHelperHostTools(opts.xdtHelper, HOST_TOOLS_ALS_CTX)); + return bindHostToolRuntime(shared, ctx); + }, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + if (opts.docs && selected(enabled, 'cindy_docs')) { + const createServer = (ctx) => createCindyDocsMcpServer(opts.docs, { + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}), + sessionId: ctx.sessionId, + vendorOptions: ctx.vendorOptions, + hostCaller: ctx.hostCaller, + }); + let sharedHostTools; + providers.push({ + name: 'cindy_docs', + toHostTools: (ctx) => { + sharedHostTools ??= createCindyDocsHostTools(opts.docs, HOST_TOOLS_ALS_CTX); + return bindHostToolRuntime(sharedHostTools, ctx); + }, + toMcpServer: (ctx) => createServer(ctx), + }); + } + + return providers; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/src/servers.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/src/servers.mjs new file mode 100644 index 0000000..d89afce --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/src/servers.mjs @@ -0,0 +1,685 @@ +import { McpServer, z } from '../lib/mcp-sdk.mjs'; +import { HostToolRegistry, jsonTextResult } from './tool-registry.mjs'; +import { resolveLiziMcpSessionContext } from './session-context.mjs'; + +const SHAPES = { + // cindy_helper (16 tools) + storage_request: { + op: z.enum(['providers', 'call']), + provider: z.optional(z.string({ min: 1, max: 64 })), + request: z.optional(z.record()), + }, + get_capabilities: { + includeExperimental: z.optional(z.boolean()), + }, + get_current_session_id: {}, + list_machines: { + onlineOnly: z.optional(z.boolean()), + }, + request_remote_control: { + deviceId: z.string({ min: 1, max: 128 }), + reason: z.optional(z.string({ max: 256 })), + }, + get_app_default_model: { + scope: z.optional(z.enum(['default', 'fast', 'reasoning'])), + }, + set_app_default_model: { + modelId: z.string({ min: 1, max: 128 }), + providerId: z.optional(z.string({ min: 1, max: 64 })), + }, + list_sessions: { + workingDir: z.optional(z.string()), + limit: z.optional(z.number({ min: 1, max: 200 })), + status: z.optional(z.enum(['active', 'archived', 'all'])), + }, + search_chat_history: { + query: z.string({ min: 1, max: 256 }), + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + send_to_session: { + targetSessionId: z.string({ min: 1, max: 128 }), + message: z.string({ min: 1, max: 16384 }), + delivery: z.optional(z.enum(['queue', 'steer'])), + }, + set_current_session_title: { + title: z.string({ min: 1, max: 200 }), + }, + archive_sessions: { + sessionIds: z.array(z.string({ min: 1 })), + }, + list_workdirs: { + limit: z.optional(z.number({ min: 1, max: 100 })), + }, + list_workers: { + includeIdle: z.optional(z.boolean()), + }, + create_worker: { + label: z.string({ min: 1, max: 64 }), + prompt: z.string({ min: 1, max: 8192 }), + workingDir: z.optional(z.string()), + }, + host_diagnostics: { + section: z.optional(z.enum(['summary', 'memory', 'providers'])), + }, + + // cindy_docs (6 tools) + read_sheet: { + path: z.string({ min: 1, max: 512 }), + sheet: z.optional(z.string()), + maxRows: z.optional(z.number({ min: 1, max: 5000 })), + }, + inspect_pdf: { + path: z.string({ min: 1, max: 512 }), + pages: z.optional(z.string()), + }, + make_docx: { + outputPath: z.string({ min: 1, max: 512 }), + markdown: z.string({ min: 1 }), + }, + make_xlsx: { + outputPath: z.string({ min: 1, max: 512 }), + rows: z.array(z.array(z.string())), + }, + make_pptx: { + outputPath: z.string({ min: 1, max: 512 }), + slides: z.array(z.record()), + }, + render_pdf: { + outputPath: z.string({ min: 1, max: 512 }), + html: z.string({ min: 1 }), + }, + + // cindy_scheduler (6 tools) + schedule_list: { + status: z.optional(z.enum(['active', 'paused', 'all'])), + summaryOnly: z.optional(z.boolean()), + }, + schedule_create: { + name: z.string({ min: 1, max: 128 }), + cron: z.string({ min: 1, max: 128 }), + prompt: z.string({ min: 1, max: 4096 }), + }, + schedule_update: { + scheduleId: z.string({ min: 1, max: 128 }), + name: z.optional(z.string({ min: 1, max: 128 })), + cron: z.optional(z.string({ min: 1, max: 128 })), + }, + schedule_delete: { + scheduleId: z.string({ min: 1, max: 128 }), + }, + schedule_silence_current_run: { + reason: z.optional(z.string({ max: 256 })), + }, + schedule_notify_current_run: { + message: z.string({ min: 1, max: 1024 }), + }, + + // cindy_ssh (5 tools) + ssh_list_hosts: { + includeOffline: z.optional(z.boolean()), + }, + ssh_exec: { + host: z.string({ min: 1, max: 128 }), + command: z.string({ min: 1, max: 8192 }), + timeoutMs: z.optional(z.number({ min: 100, max: 120_000 })), + }, + ssh_host_status: { + host: z.string({ min: 1, max: 128 }), + }, + ssh_add_host: { + alias: z.string({ min: 1, max: 64 }), + hostname: z.string({ min: 1, max: 256 }), + user: z.optional(z.string({ min: 1, max: 64 })), + }, + ssh_reload_config: {}, + + // cindy_browser (5 tools) + browser_open: { + url: z.string({ min: 1, max: 2048 }), + cacheKey: z.optional(z.string({ min: 1, max: 128 })), + }, + browser_snapshot: { + includeLinks: z.optional(z.boolean()), + }, + browser_click: { + ref: z.string({ min: 1, max: 64 }), + }, + browser_read_cache: { + cacheKey: z.string({ min: 1, max: 128 }), + }, + browser_set_rules_backend: { + backend: z.enum(['all', 'playwright', 'cdp']), + }, +}; + +function registerEntryTools(server, registry) { + server.registerTool('list_tools', { + description: `Discover tools on ${registry.serverName}`, + inputSchema: { category: z.optional(z.string()) }, + }, async (args) => jsonTextResult({ ok: true, tools: registry.list(args?.category) })); + + server.registerTool('call_tool', { + description: `Invoke a tool on ${registry.serverName}`, + inputSchema: { name: z.string({ min: 1 }), args: z.optional(z.record()) }, + }, async (args, signal) => registry.call(args.name, args.args, signal)); +} + +// --------------------------------------------------------------------------- +// 1. cindy_helper +// --------------------------------------------------------------------------- +function registerXdtHelperTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'storage_request', + category: 'storage', + description: 'Invoke host-managed plugin storage provider.', + inputShape: SHAPES.storage_request, + handler: async (args) => { + const ctx = ctxNow(); + if (deps.authorizeCall) { + const auth = await deps.authorizeCall({ + server: 'cindy_helper', + tool: 'storage_request', + args, + caller: ctx.hostCaller, + sessionId: ctx.sessionId, + }); + if (!auth?.ok) return jsonTextResult({ ok: false, errorCode: auth?.errorCode ?? 'PERMISSION_DENIED' }, true); + } + if (!deps.storage?.call) return jsonTextResult({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' }, true); + const out = await deps.storage.call(ctx, args); + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'get_capabilities', + category: 'cindy', + description: 'Inspect Cindy host capabilities.', + inputShape: SHAPES.get_capabilities, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ + ok: true, + agentKind: ctx.agentKind, + workingDir: ctx.workingDir, + sessionId: ctx.sessionId ?? null, + caller: ctx.hostCaller?.pluginId ?? null, + }); + }, + }); + + registry.register({ + name: 'get_current_session_id', + category: 'cindy', + description: 'Return the active session identifier.', + inputShape: SHAPES.get_current_session_id, + handler: async () => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, sessionId: ctx.sessionId ?? null, workingDir: ctx.workingDir }); + }, + }); + + registry.register({ + name: 'list_machines', + category: 'cindy', + description: 'List paired desktop machines.', + inputShape: SHAPES.list_machines, + handler: async (args) => { + const res = deps.machines?.list ? await deps.machines.list(ctxNow(), args) : { ok: true, machines: [] }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'request_remote_control', + category: 'cindy', + description: 'Request remote control approval for a device.', + inputShape: SHAPES.request_remote_control, + handler: async (args) => { + const res = deps.machines?.requestRemoteControl + ? await deps.machines.requestRemoteControl(ctxNow(), args) + : { ok: true, deviceId: args.deviceId }; + return jsonTextResult(res); + }, + }); + + const isRemote = Boolean(sessionCtx?.remoteHostId); + registry.register({ + name: 'get_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Read default model configuration.', + inputShape: SHAPES.get_app_default_model, + handler: async (args) => { + const ctx = ctxNow(); + const res = deps.appModels?.models + ? await deps.appModels.models(ctx, args) + : { ok: true, scope: args.scope ?? 'default', remote: isRemote }; + return jsonTextResult(res); + }, + }); + + registry.register({ + name: 'set_app_default_model', + category: isRemote ? 'bots' : 'settings', + description: 'Update default model configuration.', + inputShape: SHAPES.set_app_default_model, + handler: async (args) => jsonTextResult({ ok: true, modelId: args.modelId }), + }); + + registry.register({ + name: 'list_sessions', + category: 'history', + description: 'List sessions for the active account.', + inputShape: SHAPES.list_sessions, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, workingDir: args.workingDir ?? ctx.workingDir, sessions: [] }); + }, + }); + + registry.register({ + name: 'search_chat_history', + category: 'history', + description: 'Search past session transcripts.', + inputShape: SHAPES.search_chat_history, + handler: async (args) => jsonTextResult({ ok: true, query: args.query, hits: [] }), + }); + + registry.register({ + name: 'send_to_session', + category: 'handoff', + description: 'Send a handoff message to another session.', + inputShape: SHAPES.send_to_session, + handler: async (args) => { + const ctx = ctxNow(); + return jsonTextResult({ ok: true, from: ctx.sessionId ?? null, to: args.targetSessionId }); + }, + }); + + registry.register({ + name: 'set_current_session_title', + category: 'control', + description: 'Rename the active session.', + inputShape: SHAPES.set_current_session_title, + handler: async (args) => jsonTextResult({ ok: true, title: args.title, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'archive_sessions', + category: 'control', + description: 'Archive one or more sessions.', + inputShape: SHAPES.archive_sessions, + handler: async (args) => jsonTextResult({ ok: true, archived: args.sessionIds.length }), + }); + + registry.register({ + name: 'list_workdirs', + category: 'history', + description: 'List known project working directories.', + inputShape: SHAPES.list_workdirs, + handler: async () => jsonTextResult({ ok: true, workdirs: [] }), + }); + + registry.register({ + name: 'list_workers', + category: 'control', + description: 'List active background workers.', + inputShape: SHAPES.list_workers, + handler: async () => jsonTextResult({ ok: true, workers: [] }), + }); + + registry.register({ + name: 'create_worker', + category: 'control', + description: 'Create a delegated worker session.', + inputShape: SHAPES.create_worker, + handler: async (args) => jsonTextResult({ ok: true, label: args.label, workingDir: args.workingDir ?? ctxNow().workingDir }), + }); + + registry.register({ + name: 'host_diagnostics', + category: 'cindy', + description: 'Read non-sensitive host runtime diagnostics.', + inputShape: SHAPES.host_diagnostics, + handler: async (args) => jsonTextResult({ ok: true, section: args.section ?? 'summary', caller: ctxNow().hostCaller?.pluginId ?? null }), + }); +} + +export function createXdtHelperHostTools(deps, sessionCtx) { + const registry = new HostToolRegistry('cindy_helper'); + registerXdtHelperTools(registry, deps, sessionCtx); + return registry.buildHostTools(async () => {}); +} + +export function createXdtHelperMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_helper', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_helper'); + registerXdtHelperTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 2. cindy_docs +// --------------------------------------------------------------------------- +function registerCindyDocsTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'read_sheet', + category: 'docs', + description: 'Read a CSV or spreadsheet inside the active working directory.', + inputShape: SHAPES.read_sheet, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + const data = deps.readSheet + ? await deps.readSheet(ctx, args) + : { ok: true, workingDir: ctx.workingDir, path: args.path }; + return jsonTextResult(data); + }, + }); + + registry.register({ + name: 'inspect_pdf', + category: 'docs', + description: 'Inspect PDF metadata and page outlines.', + inputShape: SHAPES.inspect_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, path: args.path, pages: 1 }); + }, + }); + + registry.register({ + name: 'make_docx', + category: 'docs', + description: 'Generate a DOCX file.', + inputShape: SHAPES.make_docx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); + + registry.register({ + name: 'make_xlsx', + category: 'docs', + description: 'Generate an XLSX spreadsheet.', + inputShape: SHAPES.make_xlsx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, rows: args.rows.length }); + }, + }); + + registry.register({ + name: 'make_pptx', + category: 'docs', + description: 'Generate a PPTX deck.', + inputShape: SHAPES.make_pptx, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, slides: args.slides.length }); + }, + }); + + registry.register({ + name: 'render_pdf', + category: 'docs', + description: 'Render HTML to PDF.', + inputShape: SHAPES.render_pdf, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.workingDir) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, workingDir: ctx.workingDir, outputPath: args.outputPath }); + }, + }); +} + +export function createCindyDocsHostTools(deps, sessionCtx) { + const registry = new HostToolRegistry('cindy_docs'); + registerCindyDocsTools(registry, deps, sessionCtx); + return registry.buildHostTools(async () => {}); +} + +export function createCindyDocsMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_docs', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_docs'); + registerCindyDocsTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 3. cindy_scheduler +// --------------------------------------------------------------------------- +function registerSchedulerTools(registry, deps, sessionCtx) { + const ctxNow = () => resolveLiziMcpSessionContext(sessionCtx); + + registry.register({ + name: 'schedule_list', + category: 'scheduler', + description: 'List configured schedules.', + inputShape: SHAPES.schedule_list, + handler: async (args) => { + const ctx = ctxNow(); + const out = deps.list + ? await deps.list(ctx, args) + : { ok: true, schedules: [], caller: ctx.hostCaller?.pluginId ?? null, sessionId: ctx.sessionId ?? null }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'schedule_create', + category: 'scheduler', + description: 'Create a recurring schedule.', + inputShape: SHAPES.schedule_create, + handler: async (args) => jsonTextResult({ ok: true, created: args.name, sessionId: ctxNow().sessionId ?? null }), + }); + + registry.register({ + name: 'schedule_update', + category: 'scheduler', + description: 'Update an existing schedule.', + inputShape: SHAPES.schedule_update, + handler: async (args) => jsonTextResult({ ok: true, updated: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_delete', + category: 'scheduler', + description: 'Delete a schedule.', + inputShape: SHAPES.schedule_delete, + handler: async (args) => jsonTextResult({ ok: true, deleted: args.scheduleId }), + }); + + registry.register({ + name: 'schedule_silence_current_run', + category: 'scheduler', + description: 'Silence notifications for the current scheduled run.', + inputShape: SHAPES.schedule_silence_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, silenced: true, sessionId: ctx.sessionId, reason: args.reason ?? null }); + }, + }); + + registry.register({ + name: 'schedule_notify_current_run', + category: 'scheduler', + description: 'Emit a user notification for the current scheduled run.', + inputShape: SHAPES.schedule_notify_current_run, + handler: async (args) => { + const ctx = ctxNow(); + if (!ctx.sessionId) return jsonTextResult({ ok: false, errorCode: 'NO_SESSION_CONTEXT' }, true); + return jsonTextResult({ ok: true, notified: true, sessionId: ctx.sessionId, message: args.message }); + }, + }); +} + +export function createSchedulerHostTools(deps, sessionCtx) { + const registry = new HostToolRegistry('cindy_scheduler'); + registerSchedulerTools(registry, deps, sessionCtx); + return registry.buildHostTools(async () => {}); +} + +export function createSchedulerMcpServer(deps, sessionCtx) { + const server = new McpServer({ name: 'cindy_scheduler', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_scheduler'); + registerSchedulerTools(registry, deps, sessionCtx); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 4. cindy_ssh +// --------------------------------------------------------------------------- +function registerSshTools(registry, deps) { + registry.register({ + name: 'ssh_list_hosts', + category: 'ssh', + description: 'List configured SSH hosts.', + inputShape: SHAPES.ssh_list_hosts, + handler: async (args) => { + const out = deps.listHosts ? await deps.listHosts(args) : { ok: true, hosts: [] }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_exec', + category: 'ssh', + description: 'Execute a command over SSH.', + inputShape: SHAPES.ssh_exec, + handler: async (args) => { + const out = deps.exec ? await deps.exec(args) : { ok: true, host: args.host, stdout: '' }; + return jsonTextResult(out); + }, + }); + + registry.register({ + name: 'ssh_host_status', + category: 'ssh', + description: 'Check SSH host reachability.', + inputShape: SHAPES.ssh_host_status, + handler: async (args) => jsonTextResult({ ok: true, host: args.host, online: true }), + }); + + registry.register({ + name: 'ssh_add_host', + category: 'ssh', + description: 'Register an SSH host alias.', + inputShape: SHAPES.ssh_add_host, + handler: async (args) => jsonTextResult({ ok: true, alias: args.alias }), + }); + + registry.register({ + name: 'ssh_reload_config', + category: 'ssh', + description: 'Reload SSH configuration.', + inputShape: SHAPES.ssh_reload_config, + handler: async () => jsonTextResult({ ok: true, reloaded: true }), + }); +} + +export function createSshHostTools(deps) { + const registry = new HostToolRegistry('cindy_ssh'); + registerSshTools(registry, deps); + return registry.buildHostTools(async () => {}); +} + +export function createSshMcpServer(deps) { + const server = new McpServer({ name: 'cindy_ssh', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_ssh'); + registerSshTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} + +// --------------------------------------------------------------------------- +// 5. cindy_browser (per-call isolated registry, no McpServer on hostTools path) +// --------------------------------------------------------------------------- +function registerBrowserTools(registry, deps) { + const resultCache = new Map(); + let rulesBackend = 'all'; + + registry.register({ + name: 'browser_open', + category: 'browser', + description: 'Navigate to a URL and optionally cache its snapshot in this browser runtime.', + inputShape: SHAPES.browser_open, + handler: async (args) => { + const res = deps.open + ? await deps.open(args) + : { ok: true, url: args.url, sessionId: deps.getSessionId?.() ?? null }; + if (args.cacheKey) resultCache.set(args.cacheKey, { url: args.url, rulesBackend, res }); + return jsonTextResult({ ...res, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_snapshot', + category: 'browser', + description: 'Take a snapshot of the active browser tab.', + inputShape: SHAPES.browser_snapshot, + handler: async () => jsonTextResult({ + ok: true, + rulesBackend, + cachedKeys: [...resultCache.keys()], + sessionId: deps.getSessionId?.() ?? null, + }), + }); + + registry.register({ + name: 'browser_click', + category: 'browser', + description: 'Click an element reference.', + inputShape: SHAPES.browser_click, + handler: async (args) => jsonTextResult({ ok: true, clicked: args.ref, rulesBackend }), + }); + + registry.register({ + name: 'browser_read_cache', + category: 'browser', + description: 'Read a cached result from this browser runtime.', + inputShape: SHAPES.browser_read_cache, + handler: async (args) => { + const entry = resultCache.get(args.cacheKey); + return jsonTextResult({ ok: true, hit: Boolean(entry), entry: entry ?? null, rulesBackend }); + }, + }); + + registry.register({ + name: 'browser_set_rules_backend', + category: 'browser', + description: 'Tailor workflow rules backend for this browser runtime.', + inputShape: SHAPES.browser_set_rules_backend, + handler: async (args) => { + rulesBackend = args.backend; + return jsonTextResult({ ok: true, rulesBackend }); + }, + }); +} + +export function createBrowserHostTools(deps) { + const registry = new HostToolRegistry('cindy_browser'); + registerBrowserTools(registry, deps); + return registry.buildHostTools(async () => {}); +} + +export function createBrowserMcpServer(deps) { + const server = new McpServer({ name: 'cindy_browser', version: '1.0.0' }); + const registry = new HostToolRegistry('cindy_browser'); + registerBrowserTools(registry, deps); + registerEntryTools(server, registry); + return Object.assign(server, { hostTools: registry.buildHostTools(() => server.close()) }); +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/src/session-context.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/src/session-context.mjs new file mode 100644 index 0000000..575c191 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/src/session-context.mjs @@ -0,0 +1,40 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; + +const storage = new AsyncLocalStorage(); + +export function runWithLiziMcpSessionContext(ctx, fn) { + return storage.run(ctx, fn); +} + +export function getLiziMcpSessionContext() { + return storage.getStore(); +} + +function withoutSessionAttribution(fallback) { + return { + ...fallback, + workingDir: '', + sessionId: undefined, + sessionInstanceId: undefined, + remoteHostId: undefined, + vendorOptions: undefined, + hostCaller: undefined, + }; +} + +export function resolveLiziMcpSessionContext(fallback) { + if (fallback.getSessionContext) { + return fallback.getSessionContext() ?? withoutSessionAttribution(fallback); + } + if ( + fallback.sessionId + || fallback.hostCaller + || fallback.sessionInstanceId + || fallback.workingDir + || fallback.remoteHostId + || (fallback.vendorOptions && Object.keys(fallback.vendorOptions).length > 0) + ) { + return fallback; + } + return storage.getStore() ?? fallback; +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/src/tool-registry.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/src/tool-registry.mjs new file mode 100644 index 0000000..708a126 --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/src/tool-registry.mjs @@ -0,0 +1,91 @@ +import { z } from '../lib/mcp-sdk.mjs'; + +export function jsonTextResult(payload, isError = false) { + return { + isError, + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; +} + +export class HostToolRegistry { + constructor(serverName) { + this.serverName = serverName; + this.tools = new Map(); + this.aliases = new Map(); + this.compiledSchemas = new Map(); + } + + register(def) { + if (this.tools.has(def.name) || this.aliases.has(def.name)) { + throw new Error(`[${this.serverName} registry] duplicate tool name: ${def.name}`); + } + this.compiledSchemas.delete(def.name); + this.tools.set(def.name, def); + } + + registerAlias(alias, name) { + if (this.tools.has(alias) || this.aliases.has(alias) || !this.tools.has(name)) { + throw new Error(`[${this.serverName} registry] invalid tool alias: ${alias}`); + } + this.aliases.set(alias, name); + } + + has(name) { + return this.get(name) !== undefined; + } + + get(name) { + return this.tools.get(this.aliases.get(name) ?? name); + } + + list(category) { + const out = []; + for (const tool of this.tools.values()) { + if (tool.hidden) continue; + if (category && tool.category !== category) continue; + out.push({ + name: tool.name, + category: tool.category, + description: tool.description, + }); + } + return out; + } + + describe(name) { + const tool = this.get(name); + if (!tool) return undefined; + return { name: tool.name, category: tool.category }; + } + + async call(name, rawArgs, signal) { + const def = this.get(name); + if (!def) { + return jsonTextResult({ ok: false, errorCode: 'UNKNOWN_TOOL', tool: name }, true); + } + let objSchema = this.compiledSchemas.get(def.name); + if (!objSchema) { + objSchema = z.strictObject(def.inputShape); + this.compiledSchemas.set(def.name, objSchema); + } + const parsed = objSchema.safeParse(rawArgs ?? {}); + if (!parsed.success) { + return jsonTextResult({ + ok: false, + errorCode: 'INVALID_PARAMS', + issues: parsed.error.issues, + jsonSchema: parsed.error.jsonSchema, + }, true); + } + return def.handler(parsed.data, signal); + } + + buildHostTools(close = async () => {}) { + return { + list: () => this.list().map(({ name, category }) => ({ name, category })), + describe: (name) => this.describe(name), + call: (name, args, signal) => this.call(name, args, signal), + close, + }; + } +} diff --git a/questions/perf-mcp-hosttools-churn/v1/reference/tests/smoke.test.mjs b/questions/perf-mcp-hosttools-churn/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..2054eac --- /dev/null +++ b/questions/perf-mcp-hosttools-churn/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,137 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { createLiziMcpProviders } from '../src/providers.mjs'; +import { + clearHostToolProviders, + createHostToolRuntime, + setHostToolProviders, +} from '../src/host-tool-caller.mjs'; +import { runWithLiziMcpSessionContext } from '../src/session-context.mjs'; + +function parsePayload(result) { + return JSON.parse(result.content[0].text); +} + +test('concurrent async hostTool calls remain isolated per caller and workingDir', async () => { + let releaseA; + let enteredA; + const enteredPromise = new Promise((resolve) => { enteredA = resolve; }); + const gateA = new Promise((resolve) => { releaseA = resolve; }); + + const providers = createLiziMcpProviders({ + xdtHelper: { + storage: { + call: async (ctx, req) => { + if (req.request?.key === 'a') { + enteredA(); + await gateA; + } + return { ok: true, value: `${ctx.hostCaller?.pluginId}@${ctx.workingDir}` }; + }, + }, + }, + docs: { + readSheet: async (ctx, args) => ({ ok: true, path: `${ctx.workingDir}/${args.path}` }), + }, + }); + + const helper = providers.find((p) => p.name === 'cindy_helper'); + const docs = providers.find((p) => p.name === 'cindy_docs'); + + const ctxA = { + agentKind: 'claude-code', + workingDir: '/tmp/root-a', + hostCaller: { kind: 'plugin', pluginId: 'plugin-a', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxA.getSessionContext = () => ctxA; + + const ctxB = { + agentKind: 'claude-code', + workingDir: '/tmp/root-b', + hostCaller: { kind: 'plugin', pluginId: 'plugin-b', dataOwnerId: 'o1', ownerGeneration: 1 }, + }; + ctxB.getSessionContext = () => ctxB; + + const [resA, resB, docA, docB] = await runWithLiziMcpSessionContext( + { agentKind: 'codex', workingDir: '/tmp/ambient', sessionId: 'ambient-sess' }, + async () => { + const rtA = helper.toHostTools(ctxA); + const rtB = helper.toHostTools(ctxB); + const dA = docs.toHostTools(ctxA); + const dB = docs.toHostTools(ctxB); + + const pA = rtA.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'a' } }); + await enteredPromise; + const pB = rtB.call('storage_request', { op: 'call', provider: 'kv', request: { key: 'b' } }); + const pDocA = dA.call('read_sheet', { path: 'data.csv' }); + const pDocB = dB.call('read_sheet', { path: 'data.csv' }); + releaseA(); + + const out = await Promise.all([pA, pB, pDocA, pDocB]); + await Promise.all([rtA.close(), rtB.close(), dA.close(), dB.close()]); + return out.map(parsePayload); + }, + ); + + assert.equal(resA.value, 'plugin-a@/tmp/root-a'); + assert.equal(resB.value, 'plugin-b@/tmp/root-b'); + assert.equal(docA.path, '/tmp/root-a/data.csv'); + assert.equal(docB.path, '/tmp/root-b/data.csv'); +}); + +test('cindy_browser stays isolated per call and strict schema rejects unknown keys', async () => { + const providers = createLiziMcpProviders({ + browser: {}, + }); + const browser = providers.find((p) => p.name === 'cindy_browser'); + const ctx = { agentKind: 'claude-code', workingDir: '/tmp/b', sessionId: 's-1' }; + + const rt1 = browser.toHostTools(ctx); + await rt1.call('browser_set_rules_backend', { backend: 'cdp' }); + await rt1.call('browser_open', { url: 'https://example.test', cacheKey: 'k1' }); + assert.equal(parsePayload(await rt1.call('browser_read_cache', { cacheKey: 'k1' })).hit, true); + + // Strict schema rejects unknown keys. + const invalid = parsePayload(await rt1.call('browser_open', { url: 'https://example.test', extraBadKey: 1 })); + assert.equal(invalid.ok, false); + assert.equal(invalid.errorCode, 'INVALID_PARAMS'); + await rt1.close(); + + // Second call gets a clean isolated browser registry. + const rt2 = browser.toHostTools(ctx); + const miss = parsePayload(await rt2.call('browser_read_cache', { cacheKey: 'k1' })); + assert.equal(miss.hit, false); + assert.equal(miss.rulesBackend, 'all'); + await rt2.close(); +}); + +test('setHostToolProviders and clearHostToolProviders invalidate cached runtimes immediately', async () => { + const makeProviders = (label) => createLiziMcpProviders({ + xdtHelper: { storage: { call: async () => ({ ok: true, value: label }) } }, + }); + const owner1 = { dataOwnerId: 'owner-1', ownerGeneration: 1 }; + const owner2 = { dataOwnerId: 'owner-2', ownerGeneration: 2 }; + const caller1 = { kind: 'plugin', pluginId: 'p1', ...owner1 }; + const caller2 = { kind: 'plugin', pluginId: 'p1', ...owner2 }; + + try { + setHostToolProviders(makeProviders('from-owner-1'), owner1); + const rt1 = createHostToolRuntime('cindy_helper', caller1, '/tmp/1'); + assert.ok(rt1); + assert.equal(parsePayload(await rt1.call('storage_request', { op: 'providers' })).value, 'from-owner-1'); + await rt1.close(); + + setHostToolProviders(makeProviders('from-owner-2'), owner2); + assert.equal(createHostToolRuntime('cindy_helper', caller1, '/tmp/1'), null); + const rt2 = createHostToolRuntime('cindy_helper', caller2, '/tmp/2'); + assert.ok(rt2); + assert.equal(parsePayload(await rt2.call('storage_request', { op: 'providers' })).value, 'from-owner-2'); + await rt2.close(); + + clearHostToolProviders(); + assert.equal(createHostToolRuntime('cindy_helper', caller2, '/tmp/2'), null); + } finally { + clearHostToolProviders(); + } +}); diff --git a/questions/perf-mobile-home-heat/v1/author/editable.json b/questions/perf-mobile-home-heat/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/perf-mobile-home-heat/v1/author/evaluator.mjs b/questions/perf-mobile-home-heat/v1/author/evaluator.mjs new file mode 100644 index 0000000..01f4f16 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/author/evaluator.mjs @@ -0,0 +1,833 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import { performance } from 'node:perf_hooks'; +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir, baseDir] = process.argv.slice(2); +const load = async (dir) => { + const [home, cache, schedule, activity] = await Promise.all([ + import(pathToFileURL(path.join(dir, 'mobile-home.mjs')).href), + import(pathToFileURL(path.join(dir, 'remote-resource-cache.mjs')).href), + import(pathToFileURL(path.join(dir, 'schedule-index.mjs')).href), + import(pathToFileURL(path.join(dir, 'foreground-task-activity.mjs')).href), + ]); + return { home, cache, schedule, activity }; +}; + +const sub = await load(subDir); +const base = await load(baseDir); + +function createVirtualClock(startMs = 5_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + pendingCount: () => timers.size, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async flushMicrotasks() { + for (let i = 0; i < 6; i += 1) await Promise.resolve(); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await this.flushMicrotasks(); + } + time = target; + await this.flushMicrotasks(); + }, + }; +} + +function buildHomeWorkload() { + const devices = [ + { deviceId: 'dev-mac-1', name: 'Studio Mac', state: 'online', canOpen: true }, + { deviceId: 'dev-mac-2', name: 'Travel Air', state: 'online', canOpen: true }, + { deviceId: 'dev-linux', name: 'Build Box', state: 'online', canOpen: true }, + { deviceId: 'dev-win', name: 'Gaming PC', state: 'offline', canOpen: false }, + { deviceId: 'dev-dup-1', name: 'Shared Lab', state: 'online', canOpen: true }, + { deviceId: 'dev-dup-2', name: 'Shared Lab', state: 'offline', canOpen: false }, + ]; + const sessions = []; + const pendingInteractionIndex = new Map(); + const scheduleIndex = new Map(); + const messagePreviewIndex = new Map(); + + for (let i = 0; i < 600; i += 1) { + const dev = devices[i % 4]; + const ts = new Date(Date.UTC(2026, 10, 1, 0, 0, 0) + ((i * 104729) % 2_000_000) * 1000).toISOString(); + const isWin = dev.deviceId === 'dev-win'; + const workingDir = i % 7 === 0 + ? null + : isWin + ? (i % 2 === 0 ? `C:\\Work\\Proj-${i % 10}\\` : `c:/work/proj-${i % 10}`) + : `/Users/dev/repos/project-${i % 16}`; + sessions.push({ + id: `sess-${i}`, + title: i % 15 === 0 ? `[Schedule] Nightly Check ${i}` : `Feature Task #${i}`, + status: i % 29 === 0 ? 'deleted' : i % 6 === 0 ? 'archived' : 'active', + createdAt: '2026-10-01T00:00:00.000Z', + updatedAt: ts, + lastActivityAt: ts, + workingDir, + workspaceKind: i % 7 === 0 ? 'dialogue' : 'project', + source: i % 15 === 0 ? 'scheduler' : 'user', + pinnedAt: i < 5 ? ts : null, + deviceLinkDeviceId: dev.deviceId, + deviceLinkDeviceName: dev.name, + canonicalDeviceId: dev.deviceId, + preview: `Preview text for task ${i}`, + model: i % 2 === 0 ? 'claude-sonnet' : 'gpt-5', + agentKind: i % 2 === 0 ? 'cc' : 'codex', + }); + if (i % 17 === 0) pendingInteractionIndex.set(`sess-${i}`, 1 + (i % 3)); + if (i % 15 === 0) scheduleIndex.set(`sess-${i}`, { scheduleId: `sc-${i}`, scheduleName: `Cron ${i}` }); + if (i % 11 === 0) messagePreviewIndex.set(`sess-${i}`, `Live delta ${i}`); + } + + return { devices, sessions, pendingInteractionIndex, scheduleIndex, messagePreviewIndex }; +} + +function checkHomeCorrectness() { + const edgeDevices = [ + { deviceId: 'dev-mac', name: 'Studio Mac', state: 'online', canOpen: true }, + { deviceId: 'dev-dup-a', name: 'Dup Machine', state: 'online', canOpen: true }, + { deviceId: 'dev-dup-b', name: 'Dup Machine', state: 'online', canOpen: true }, + { deviceId: 'dev-ambig', name: 'Ambig Stale', state: 'online', canOpen: true }, + { deviceId: 'dev-unknown', name: 'unknown', state: 'online', canOpen: true }, + { deviceId: 'dev-no', name: 'No', state: 'online', canOpen: true }, + ]; + const edgeSessions = [ + // Unique stale match -> claimed to dev-mac while preserving deviceLinkDeviceId + { + id: 's1', title: 'Claimed stale', status: 'active', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T10:00:00.000Z', + workingDir: '/repo/a/', deviceLinkDeviceId: 'stale-mac-old', deviceLinkDeviceName: 'Studio Mac', + }, + // Duplicate current name -> must NOT claim + { + id: 's2', title: 'Dup current name', status: 'active', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T11:00:00.000Z', + workingDir: '/repo/b', deviceLinkDeviceId: 'stale-dup', deviceLinkDeviceName: 'Dup Machine', + }, + // Ambiguous stale names (2 distinct stale IDs with same name) -> must NOT claim + { + id: 's3', title: 'Ambig 1', status: 'active', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T09:00:00.000Z', + workingDir: '/repo/c', deviceLinkDeviceId: 'stale-ambig-1', deviceLinkDeviceName: 'Ambig Stale', + }, + { + id: 's4', title: 'Ambig 2', status: 'archived', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T15:00:00.000Z', + workingDir: '/repo/c', deviceLinkDeviceId: 'stale-ambig-2', deviceLinkDeviceName: 'Ambig Stale', + }, + // Placeholder names ('unknown' / 'NO') -> must NOT claim + { + id: 's5', title: 'Placeholder unknown', status: 'active', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T08:00:00.000Z', + workingDir: null, workspaceKind: 'dialogue', deviceLinkDeviceId: 'stale-u', deviceLinkDeviceName: 'UNKNOWN', + }, + { + id: 's6', title: 'Placeholder no', status: 'active', + createdAt: '2026-12-01T00:00:00.000Z', lastActivityAt: '2026-12-04T07:00:00.000Z', + workingDir: 'C:\\Project\\Sub\\', deviceLinkDeviceId: 'stale-n', deviceLinkDeviceName: 'no', + pinnedAt: '2026-12-04T07:00:00.000Z', + }, + // Non-ISO fallback activity timestamp + deleted session + { + id: 's7', title: 'Non-ISO time', status: 'active', + createdAt: '2026-12-02 12:30:00', workingDir: 'c:/project/sub', + deviceLinkDeviceId: 'dev-mac', deviceLinkDeviceName: 'Studio Mac', + }, + { + id: 's8', title: 'Deleted task', status: 'deleted', + createdAt: '2026-12-05T00:00:00.000Z', workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-mac', deviceLinkDeviceName: 'Studio Mac', + }, + ]; + const pending = new Map([['s1', 2], ['s4', 1]]); + const sched = new Map([['s2', { scheduleId: 'sc-2', scheduleName: 'Hourly Sync' }]]); + const previews = new Map([['s7', 'special search token alpha']]); + + const scenarios = [ + { statusFilter: 'all', selectedDeviceId: null, searchQuery: '', inboxMode: false }, + { statusFilter: 'active', selectedDeviceId: 'dev-mac', searchQuery: '', inboxMode: false }, + { statusFilter: 'archived', selectedDeviceId: null, searchQuery: '', inboxMode: false }, + { statusFilter: 'waiting', selectedDeviceId: null, searchQuery: '', inboxMode: true }, + { statusFilter: 'automation', selectedDeviceId: null, searchQuery: '', inboxMode: false }, + { statusFilter: 'all', selectedDeviceId: 'nonexistent-device', searchQuery: 'alpha', inboxMode: false }, + { statusFilter: 'all', selectedDeviceId: null, searchQuery: 'waiting', inboxMode: false }, + ]; + for (const sc of scenarios) { + const input = { + devices: edgeDevices, + sessions: edgeSessions, + pendingInteractionIndex: pending, + scheduleIndex: sched, + messagePreviewIndex: previews, + ...sc, + }; + const expected = base.home.buildMobileHomePresentation(input); + const actual = sub.home.buildMobileHomePresentation(input); + assert.deepEqual(actual, expected, `Home presentation mismatch for ${JSON.stringify(sc)}`); + } + // Ensure physicalDeviceId wasn't mutated on claimed stale session. + const allRes = sub.home.buildMobileHomePresentation({ devices: edgeDevices, sessions: edgeSessions, statusFilter: 'all' }); + const s1 = allRes.items.find((i) => i.id === 's1'); + assert.equal(s1.deviceId, 'dev-mac'); + assert.equal(s1.physicalDeviceId, 'stale-mac-old'); + assert.equal(s1.session.deviceLinkDeviceId, 'stale-mac-old'); + + // Verify exact parity on the full 600-session dataset. + const big = buildHomeWorkload(); + assert.deepEqual( + sub.home.buildMobileHomePresentation({ ...big, statusFilter: 'all' }), + base.home.buildMobileHomePresentation({ ...big, statusFilter: 'all' }), + '600-session parity mismatch', + ); +} + +async function checkCacheCorrectness() { + const disk = new Map(); + let setItemCount = 0; + let failNextSet = false; + let gateRelease = null; + let gateArmed = false; + const storage = { + async getItem(k) { return disk.get(k) ?? null; }, + async setItem(k, v) { + setItemCount += 1; + if (failNextSet) { + failNextSet = false; + throw new Error('disk full'); + } + disk.set(k, v); + if (gateArmed) { + gateArmed = false; + await new Promise((resolve) => { gateRelease = resolve; }); + } + }, + async removeItem(k) { disk.delete(k); }, + async getAllKeys() { return [...disk.keys()]; }, + }; + const cache = sub.cache.createRemoteResourceCache({ storage }); + let emissions = 0; + const unsub = cache.subscribeRemoteResourceCache(() => { emissions += 1; }); + + const makeItems = (replyAt, avatarSize = 0) => [{ + host: { deviceId: 'dev-a', name: 'Mac A' }, + item: { + ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, + display: { + title: 'Writer', + preview: `msg-${replyAt}`, + lastReplyAt: replyAt, + ...(avatarSize > 0 ? { avatar: 'A'.repeat(avatarSize) } : {}), + }, + }, + }]; + + // 1. Seed + silent no-op verification. + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + const writesAfterSeed = setItemCount; + const emitsAfterSeed = emissions; + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + assert.equal(setItemCount, writesAfterSeed, 'Unchanged update must not write to storage'); + assert.equal(emissions, emitsAfterSeed, 'Unchanged update must stay silent'); + + // 2. Concurrent mutations preserve submission order and latest state. + gateArmed = true; + const p1 = cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(200)); + await Promise.resolve(); + await Promise.resolve(); + const p2 = cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(300)); + const p3 = cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(450)); + const p4 = cache.markRemoteResourceRead('alice', 'dev-a', 'writer', 450, '42'); + const p5 = cache.markRemoteResourceRead('alice', 'dev-a', 'writer', 300, '9'); // older must not regress + const p6 = cache.cacheRemoteResourceHome('alice', [{ id: 'teammates', title: 'Team', resourceKind: 'bot', targets: [{ deviceId: 'dev-a', name: 'Mac A' }] }]); + gateRelease(); + await Promise.all([p1, p2, p3, p4, p5, p6]); + + const snap = await cache.readRemoteResourceSnapshot('alice'); + assert.equal(snap.items.teammates[0].item.display.lastReplyAt, 450); + assert.equal(snap.home.length, 1); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-a', 'writer', 450), false); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-a', 'writer', 451), true); + assert.equal(snap.readSequences[sub.cache.remoteResourceReadKey('dev-a', 'writer')], '42'); + // Disk must contain the latest state too. + const persisted = JSON.parse(disk.get(sub.cache.CACHE_STORAGE_PREFIX + 'alice')); + assert.equal(persisted.items.teammates[0].item.display.lastReplyAt, 450); + assert.equal(persisted.home.length, 1); + + // 3. Failed disk write marks unsaved and retries on next unchanged update. + failNextSet = true; + await cache.markRemoteResourceRead('alice', 'dev-a', 'writer', 500, '50'); + const writesAfterFail = setItemCount; + await cache.markRemoteResourceRead('alice', 'dev-a', 'writer', 500, '50'); + assert.equal(setItemCount, writesAfterFail + 1, 'Unsaved snapshot must retry disk write even when unchanged'); + + // 4. Disk budget <= MAX_DISK_CHARS. + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(600, 300 * 1024)); + const rawDisk = disk.get(sub.cache.CACHE_STORAGE_PREFIX + 'alice'); + assert.ok(rawDisk.length <= sub.cache.MAX_DISK_CHARS, 'Persisted snapshot exceeded MAX_DISK_CHARS'); + assert.doesNotThrow(() => JSON.parse(rawDisk)); + + // 5. Epoch cancellation on clearRemoteResourceCache during in-flight write. + gateArmed = true; + const staleInFlight = cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(700)); + await Promise.resolve(); + await Promise.resolve(); + const staleQueued = cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(800)); + const clearPromise = cache.clearRemoteResourceCache(); + gateRelease(); + await Promise.all([staleInFlight, staleQueued, clearPromise]); + assert.equal(disk.has(sub.cache.CACHE_STORAGE_PREFIX + 'alice'), false, 'Stale write resurrected disk key after clear'); + const afterClear = await cache.readRemoteResourceSnapshot('alice'); + assert.deepEqual(afterClear.items, {}, 'Stale write resurrected memory after clear'); + unsub(); +} + +async function checkScheduleCorrectness() { + const clock = createVirtualClock(); + const store = sub.schedule.createScheduleIndexStore({ + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + let calls = 0; + let version = 1; + const makeInvoke = (tag) => async (_dev, ch) => { + calls += 1; + if (ch === 'maker:schedule:list') { + return [{ id: 's1', name: `Job-${tag}-${version}`, status: 'active', targetSessionId: 't1' }]; + } + return { runs: [{ id: `r-${version}`, scheduleId: 's1', startedAt: clock.now(), status: 'completed', unread: true }] }; + }; + + // 1. First load is ALWAYS immediate (no timer wait). + const first = await store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('init')); + assert.equal(first.get('t1')?.scheduleName, 'Job-init-1'); + assert.equal(calls, 2); + assert.equal(store.hasCurrentScheduleIndexRecord('dev-1'), true); + assert.equal(store.sessionMayHaveScheduleRuns('dev-1', 't1'), true); + assert.equal(store.sessionMayHaveScheduleRuns('dev-1', 'other-task'), false); + + // 2. TTL cache hit within 30s does not invoke RPCs. + await clock.advanceBy(5_000); + const cached = await store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('cached')); + assert.equal(cached.get('t1')?.scheduleName, 'Job-init-1'); + assert.equal(calls, 2); + + // 3. Manual refresh (invalidateScheduleIndexForDevice) MUST bypass any coalesce window and fire immediately! + version = 2; + await clock.advanceBy(200); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't2', scheduleListChanged: false }); + store.invalidateScheduleIndexForDevice('dev-1'); + let manualDone = false; + const manualP = store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('manual')).then((m) => { + manualDone = true; + return m; + }); + await clock.flushMicrotasks(); + assert.equal(manualDone, true, 'Manual refresh must fire immediately without waiting for coalesce window'); + assert.equal((await manualP).get('t1')?.scheduleName, 'Job-manual-2'); + assert.equal(calls, 4); + + // 4. Link recovery MUST bypass coalesce window and fire immediately! + version = 3; + await clock.advanceBy(150); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + store.invalidateScheduleIndexesAfterLinkRecovery('dev-1'); + let recoveryDone = false; + const recoveryP = store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('recovery')).then((m) => { + recoveryDone = true; + return m; + }); + await clock.flushMicrotasks(); + assert.equal(recoveryDone, true, 'Link recovery refresh must fire immediately'); + assert.equal((await recoveryP).get('t1')?.scheduleName, 'Job-recovery-3'); + assert.equal(calls, 6); + + // 5. Event burst resolves every caller with fresh version-4 data (never stale pre-event data). + version = 4; + await clock.advanceBy(200); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + const b1 = store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('first-invoker')); + await clock.advanceBy(200); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + const b2 = store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('latest-invoker')); + await clock.advanceBy(sub.schedule.SCHEDULE_INDEX_EVENT_COALESCE_MS + 50); + const [r1, r2] = await Promise.all([b1, b2]); + assert.ok( + r1.get('t1')?.scheduleName === 'Job-first-invoker-4' || r1.get('t1')?.scheduleName === 'Job-latest-invoker-4', + `Unexpected first burst result: ${r1.get('t1')?.scheduleName}`, + ); + assert.equal(r2.get('t1')?.scheduleName, 'Job-latest-invoker-4'); + + // 6. canStart=false fails cleanly; clearSessionScheduleIndexCache cancels pending timers cleanly. + store.invalidateScheduleIndexForDevice('dev-1'); + await assert.rejects( + () => store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('inactive'), () => false), + /inactive/i, + ); + await clock.advanceBy(100); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + let settledAfterClear = false; + const pendingP = store.loadDeviceSessionScheduleIndex('dev-1', makeInvoke('cancelled')); + pendingP.then(() => { settledAfterClear = true; }, () => { settledAfterClear = true; }); + store.clearSessionScheduleIndexCache(); + await clock.flushMicrotasks(); + assert.equal( + settledAfterClear, + true, + 'clearSessionScheduleIndexCache must settle pending coalesced load promises', + ); + assert.equal(clock.pendingCount(), 0, 'clearSessionScheduleIndexCache must clear pending timers'); +} + +async function checkActivityCorrectness() { + const clock = createVirtualClock(); + const written = []; + const subIds = new Map([['mac-a', 1], ['mac-b', 1]]); + const snapshots = new Map([ + ['mac-a', { schemaVersion: 1, revision: 1, waitingCount: 0, unreadCount: 0, runningCount: 1, selected: { sessionId: 'sa', title: 'Build A', status: 'running' } }], + ['mac-b', { schemaVersion: 1, revision: 1, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null }], + ]); + const source = { + async readDeviceList() { + return { + devices: [ + { deviceId: 'mac-a', online: true, remoteControlEnabled: true, platform: 'darwin' }, + { deviceId: 'mac-b', online: true, remoteControlEnabled: true, platform: 'linux' }, + ], + }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke(device) { return snapshots.get(device); }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity(device) { return subIds.get(device) ?? null; }, + }; + + const ctrl = sub.activity.startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Attention', completed: 'Completed', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: (state, observedAt) => written.push({ state, observedAt, at: clock.now() }), + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await ctrl.ready; + assert.equal(written.length, 1, 'Initial snapshot must publish immediately'); + assert.equal(written[0].state?.status, 'running'); + + // Out-of-order stale revision ignored. + await clock.advanceBy(100); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 1, waitingCount: 1, unreadCount: 0, runningCount: 0, + selected: { sessionId: 'sa', title: 'Stale', status: 'attention' }, + }, clock.now() - 500); + assert.equal(written.length, 1); + + // Urgent transition: running -> attention MUST write immediately even within 2.5s window. + await clock.advanceBy(200); + const tAttention = clock.now(); + sub.activity.receiveHostTaskActivity('mac-b', { + schemaVersion: 1, revision: 2, waitingCount: 1, unreadCount: 0, runningCount: 0, + selected: { sessionId: 'sb', title: 'Approve deploy', status: 'attention', companion: { hue: 'teal', glyph: 'C', glyphIsInitial: true } }, + }, tAttention); + assert.equal(written.at(-1)?.state?.status, 'attention', 'Attention transition must publish immediately'); + assert.equal(written.at(-1)?.at, tAttention); + assert.deepEqual(written.at(-1)?.state?.companion, { hue: 'teal', glyph: 'C', glyphIsInitial: true }); + + // Urgent transition: attention -> attention (count change) MUST also write immediately. + await clock.advanceBy(150); + const tAttention2 = clock.now(); + sub.activity.receiveHostTaskActivity('mac-b', { + schemaVersion: 1, revision: 3, waitingCount: 2, unreadCount: 0, runningCount: 0, + selected: { sessionId: 'sb', title: 'Approve 2 items', status: 'attention' }, + }, tAttention2); + assert.equal(written.at(-1)?.state?.attentionCount, 2); + assert.equal(written.at(-1)?.at, tAttention2); + + // Urgent status change: attention -> running MUST write immediately. + await clock.advanceBy(150); + const tBackToRunning = clock.now(); + sub.activity.receiveHostTaskActivity('mac-b', { + schemaVersion: 1, revision: 4, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null, + }, tBackToRunning); + assert.equal(written.at(-1)?.state?.status, 'running'); + assert.equal(written.at(-1)?.at, tBackToRunning); + + // Rapid running -> running updates MUST eventually flush the LATEST title after coalesce window. + await clock.advanceBy(200); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 2, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 'sa', title: 'Step 2', status: 'running' }, + }, clock.now()); + await clock.advanceBy(200); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 3, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 'sa', title: 'Step 3 final', status: 'running' }, + }, clock.now()); + await clock.advanceBy(sub.activity.FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + assert.equal(written.at(-1)?.state?.title, 'Step 3 final', 'Trailing write must flush latest running state'); + + // Revert back to previous state cancels pending write. + const countBeforeRevert = written.length; + await clock.advanceBy(200); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 4, waitingCount: 0, unreadCount: 0, runningCount: 2, + selected: { sessionId: 'sa', title: 'Transient spike', status: 'running' }, + }, clock.now()); + await clock.advanceBy(100); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 5, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 'sa', title: 'Step 3 final', status: 'running' }, + }, clock.now()); + await clock.advanceBy(sub.activity.FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + // Either baseline wrote both (countBeforeRevert+2) or optimized cancelled timer (countBeforeRevert). + // Both end up with title === 'Step 3 final' and no dangling timers! + assert.equal(written.at(-1)?.state?.title, 'Step 3 final'); + assert.equal(clock.pendingCount(), 0); + + // Urgent ending (state -> null) MUST publish immediately! + await clock.advanceBy(100); + const tEnd = clock.now(); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 6, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null, + }, tEnd); + assert.equal(written.at(-1)?.state, null, 'Ending must publish immediately'); + assert.equal(written.at(-1)?.at, tEnd); + + // dispose() cancels pending timers and stops further writes. + const countBeforeDispose = written.length; + await clock.advanceBy(100); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 7, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 'sa', title: 'Restart', status: 'running' }, + }, clock.now()); + await clock.advanceBy(100); + sub.activity.receiveHostTaskActivity('mac-a', { + schemaVersion: 1, revision: 8, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 'sa', title: 'Should not write after dispose', status: 'running' }, + }, clock.now()); + ctrl.dispose(); + const countAtDispose = written.length; + assert.ok(countAtDispose >= countBeforeDispose + 1); + await clock.advanceBy(sub.activity.FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + assert.equal(written.length, countAtDispose, 'No writes may occur after dispose'); + assert.equal(clock.pendingCount(), 0, 'dispose must clear pending coalesce timers'); +} + +// Deterministic metric workloads +async function measureStorageWrites(cacheMod) { + const disk = new Map(); + let setItemCalls = 0; + let gateRelease = null; + let gateArmed = false; + const storage = { + async getItem(k) { return disk.get(k) ?? null; }, + async setItem(k, v) { + setItemCalls += 1; + disk.set(k, v); + if (gateArmed) { + gateArmed = false; + await new Promise((resolve) => { gateRelease = resolve; }); + } + }, + async removeItem(k) { disk.delete(k); }, + async getAllKeys() { return [...disk.keys()]; }, + }; + const cache = cacheMod.createRemoteResourceCache({ storage }); + const makeItems = (ver) => Array.from({ length: 40 }, (_, i) => ({ + host: { deviceId: `dev-${i % 4}`, name: `Host ${i % 4}` }, + item: { + ref: { collectionId: 'teammates', kind: 'bot', id: `bot-${i}` }, + display: { title: `Bot ${i}`, preview: 'x'.repeat(300), lastReplyAt: ver + i }, + }, + })); + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + setItemCalls = 0; + + // Wave 1: 30 concurrent mutations while first setItem is in-flight + gateArmed = true; + const w1 = [cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(200))]; + await Promise.resolve(); + await Promise.resolve(); + for (let i = 1; i <= 29; i += 1) { + w1.push(cache.markRemoteResourceRead('alice', `dev-${i % 4}`, `bot-${i}`, 300 + i)); + } + gateRelease?.(); + await Promise.all(w1); + + // 5 silent no-ops + for (let i = 0; i < 5; i += 1) { + await cache.markRemoteResourceRead('alice', 'dev-1', 'bot-1', 301); + } + + // Wave 2: 20 concurrent mutations while first setItem is in-flight + gateArmed = true; + const w2 = [cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(400))]; + await Promise.resolve(); + await Promise.resolve(); + for (let i = 1; i <= 19; i += 1) { + w2.push(cache.markRemoteResourceRead('alice', `dev-${i % 4}`, `bot-${i}`, 500 + i)); + } + gateRelease?.(); + await Promise.all(w2); + + // Verify final persisted value to ensure mutations weren't dropped. + const persisted = JSON.parse(disk.get(cacheMod.CACHE_STORAGE_PREFIX + 'alice')); + assert.equal(persisted.read[cacheMod.remoteResourceReadKey('dev-3', 'bot-19')], 519); + return setItemCalls; +} + +async function measureScheduleRpcCalls(schedMod) { + const clock = createVirtualClock(); + const store = schedMod.createScheduleIndexStore({ + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + let rpcCalls = 0; + let seq = 0; + const invoke = async (dev, ch) => { + rpcCalls += 1; + if (ch === 'maker:schedule:list') { + return [{ id: `s-${dev}`, name: `Sync ${dev} #${seq}`, status: 'active', targetSessionId: `t-${dev}` }]; + } + return { runs: [] }; + }; + // Initial loads for 2 devices (4 RPCs) + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + await store.loadDeviceSessionScheduleIndex('dev-2', invoke); + + // Burst 1: 15 rapid live events per device over 1.35s + const waiters1 = []; + for (let i = 1; i <= 15; i += 1) { + seq = i; + await clock.advanceBy(90); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't-dev-1', scheduleListChanged: false }); + store.noteScheduleEventInIndexCache('dev-2', { invalidate: true, sessionId: 't-dev-2', scheduleListChanged: false }); + waiters1.push(store.loadDeviceSessionScheduleIndex('dev-1', invoke)); + waiters1.push(store.loadDeviceSessionScheduleIndex('dev-2', invoke)); + } + await clock.advanceBy(schedMod.SCHEDULE_INDEX_EVENT_COALESCE_MS + 200); + await Promise.all(waiters1); + + // Burst 2: 10 rapid live events on dev-1 over 0.9s + const waiters2 = []; + for (let i = 16; i <= 25; i += 1) { + seq = i; + await clock.advanceBy(90); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't-dev-1', scheduleListChanged: false }); + waiters2.push(store.loadDeviceSessionScheduleIndex('dev-1', invoke)); + } + await clock.advanceBy(schedMod.SCHEDULE_INDEX_EVENT_COALESCE_MS + 200); + await Promise.all(waiters2); + + // 1 manual refresh on dev-1 (2 RPCs) + seq = 26; + store.invalidateScheduleIndexForDevice('dev-1'); + const finalMap = await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(finalMap.get('t-dev-1')?.scheduleName, 'Sync dev-1 #26'); + return rpcCalls; +} + +async function measureWidgetWrites(actMod) { + const clock = createVirtualClock(); + let writes = 0; + let lastState = undefined; + const source = { + async readDeviceList() { + return { + devices: [ + { deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }, + { deviceId: 'mac-2', online: true, remoteControlEnabled: true, platform: 'linux' }, + ], + }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke(device) { + if (device === 'mac-1') { + return { schemaVersion: 1, revision: 1, waitingCount: 0, unreadCount: 0, runningCount: 1, selected: { sessionId: 's1', title: 'Init', status: 'running' } }; + } + return { schemaVersion: 1, revision: 1, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const ctrl = actMod.startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Attention', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: (state) => { writes += 1; lastState = state; }, + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await ctrl.ready; + + let rev = 2; + // 24 rapid running -> running updates spaced 200ms apart (4.8s total) + for (let i = 0; i < 24; i += 1) { + await clock.advanceBy(200); + actMod.receiveHostTaskActivity('mac-1', { + schemaVersion: 1, revision: rev++, waitingCount: 0, unreadCount: 0, runningCount: 1 + (i % 3), + selected: { sessionId: 's1', title: `Running step ${i}`, status: 'running' }, + }, clock.now()); + } + await clock.advanceBy(400); + // Urgent transition: attention + actMod.receiveHostTaskActivity('mac-2', { + schemaVersion: 1, revision: 2, waitingCount: 1, unreadCount: 0, runningCount: 0, + selected: { sessionId: 's2', title: 'Need approval', status: 'attention' }, + }, clock.now()); + assert.equal(lastState?.status, 'attention'); + + // Urgent transition back to running + await clock.advanceBy(200); + actMod.receiveHostTaskActivity('mac-2', { + schemaVersion: 1, revision: 3, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null, + }, clock.now()); + assert.equal(lastState?.status, 'running'); + + // 12 more rapid running -> running updates (2.4s) + for (let i = 0; i < 12; i += 1) { + await clock.advanceBy(200); + actMod.receiveHostTaskActivity('mac-1', { + schemaVersion: 1, revision: rev++, waitingCount: 0, unreadCount: 0, runningCount: 1, + selected: { sessionId: 's1', title: `Phase 2 step ${i}`, status: 'running' }, + }, clock.now()); + } + await clock.advanceBy(actMod.FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + assert.equal(lastState?.title, 'Phase 2 step 11'); + + // Urgent ending (null) + await clock.advanceBy(200); + actMod.receiveHostTaskActivity('mac-1', { + schemaVersion: 1, revision: rev++, waitingCount: 0, unreadCount: 0, runningCount: 0, selected: null, + }, clock.now()); + assert.equal(lastState, null); + ctrl.dispose(); + return writes; +} + +function runHomeWorkload(homeMod, data) { + let checksum = 0; + for (let r = 0; r < 30; r += 1) { + const res = homeMod.buildMobileHomePresentation({ + devices: data.devices, + sessions: data.sessions, + pendingInteractionIndex: data.pendingInteractionIndex, + scheduleIndex: data.scheduleIndex, + messagePreviewIndex: data.messagePreviewIndex, + statusFilter: r % 3 === 0 ? 'all' : 'active', + }); + checksum += res.items.length + res.projects.length + res.overview.waiting; + } + return checksum; +} + +function interleavedSpeedup(baseFn, subFn, rounds = 7, warmups = 3) { + const bCheck = baseFn(); + const sCheck = subFn(); + assert.equal(sCheck, bCheck, 'Home benchmark output checksum mismatch'); + for (let w = 1; w < warmups; w += 1) { + baseFn(); + subFn(); + } + const ratios = []; + for (let i = 0; i < rounds; i += 1) { + const order = i % 2 === 0; + let bMs, sMs; + if (order) { + const t0 = trusted.now(); baseFn(); bMs = trusted.now() - t0; + const t1 = trusted.now(); subFn(); sMs = trusted.now() - t1; + } else { + const t1 = trusted.now(); subFn(); sMs = trusted.now() - t1; + const t0 = trusted.now(); baseFn(); bMs = trusted.now() - t0; + } + ratios.push(bMs / Math.max(sMs, 0.01)); + } + ratios.sort((a, b) => a - b); + return Number(ratios[Math.floor(ratios.length / 2)].toFixed(2)); +} + +let correctness_home = false; +let correctness_cache = false; +let correctness_schedule = false; +let correctness_activity = false; +const errors = []; + +try { checkHomeCorrectness(); correctness_home = true; } catch (e) { errors.push('home: ' + e.message); } +try { await checkCacheCorrectness(); correctness_cache = true; } catch (e) { errors.push('cache: ' + e.message); } +try { await checkScheduleCorrectness(); correctness_schedule = true; } catch (e) { errors.push('schedule: ' + e.message); } +try { await checkActivityCorrectness(); correctness_activity = true; } catch (e) { errors.push('activity: ' + e.message); } + +let home_sort_speedup = 1; +let storage_writes = 50; +let schedule_rpc_calls = 86; +let widget_writes = 40; + +if (correctness_home && correctness_cache && correctness_schedule && correctness_activity) { + try { + const homeData = buildHomeWorkload(); + home_sort_speedup = interleavedSpeedup( + () => runHomeWorkload(base.home, homeData), + () => runHomeWorkload(sub.home, homeData), + 7, + 3, + ); + storage_writes = await measureStorageWrites(sub.cache); + schedule_rpc_calls = await measureScheduleRpcCalls(sub.schedule); + widget_writes = await measureWidgetWrites(sub.activity); + } catch (e) { + errors.push('bench: ' + e.message); + } +} + +trusted.emit(({ + status: 'graded', + items: { + correctness_home, + correctness_cache, + correctness_schedule, + correctness_activity, + }, + metrics: { + home_sort_speedup, + storage_writes, + schedule_rpc_calls, + widget_writes, + }, + details: { errors }, +})); diff --git a/questions/perf-mobile-home-heat/v1/author/grade.py b/questions/perf-mobile-home-heat/v1/author/grade.py new file mode 100644 index 0000000..db20241 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests/benchmarks cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=300 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/perf-mobile-home-heat/v1/author/grade_impl.py b/questions/perf-mobile-home-heat/v1/author/grade_impl.py new file mode 100644 index 0000000..a3e0cbb --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/author/grade_impl.py @@ -0,0 +1,42 @@ +"""Isolated pure-Node quantitative grader: runs correctness gates + deterministic & interleaved A/B benchmarks.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent +Q = HERE.parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-mobile-heat-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + base_src = tmp / 'base_src' + shutil.copytree(submission_root / 'src', sub_src) + shutil.copytree(Q / 'candidate' / 'src', base_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src), str(base_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=180 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/perf-mobile-home-heat/v1/author/result-channel.mjs b/questions/perf-mobile-home-heat/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/CONTRACT.md b/questions/perf-mobile-home-heat/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..c8a493a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/CONTRACT.md @@ -0,0 +1,50 @@ +# Product & Runtime Contract + +## 1. Mobile Home Presentation (`src/mobile-home.mjs`) + +- Exports `MOBILE_HOME_ALL_DEVICES` (`'all'`), `buildDeviceIdentity`, `resolveCanonicalDeviceId`, `compareSessionsByStatusThenActivityDesc`, and `buildMobileHomePresentation`. +- Device identity canonicalization: + - Known device IDs (trimmed non-empty `device.deviceId` from `devices`) remain unchanged. + - Unknown (stale) session `deviceLinkDeviceId` values whose `deviceLinkDeviceName` uniquely matches exactly one current device (and has no conflicting stale device IDs sharing the same name) are claimed to that device's canonical `deviceId`. + - Placeholder names (`'unknown'`, `'no'`, case-insensitive) never participate in name-based claiming. + - Canonicalization sets `canonicalDeviceId` without ever mutating `deviceLinkDeviceId`. +- Filtering & sorting parity: + - Filters by `selectedDeviceId` (normalized against available device filters), `statusFilter` (`'active' | 'archived' | 'waiting' | 'automation' | 'all'`), and case-insensitive `searchQuery`. + - Sorts matched sessions by status rank (`active` < `archived` < others) and then descending by `lastActivityAt ?? userSendAt ?? updatedAt ?? createdAt`. + - Output (`items`, `pinned`, `chats`, `projects`, `deviceFilters`, `overview`, `selectedDeviceId`) must match baseline semantics exactly for all inputs. + +## 2. Remote Resource Cache (`src/remote-resource-cache.mjs`) + +- Exports `CACHE_STORAGE_PREFIX` (`'cindy.remoteResources.v1.'`), `MAX_DISK_CHARS` (`256 * 1024`), `remoteResourceReadKey`, and `createRemoteResourceCache({ storage })`. +- Returned cache API: `readRemoteResourceSnapshot`, `cacheRemoteResourceHome`, `cacheRemoteResourceItems`, `markRemoteResourceRead`, `isRemoteResourceUnread`, `clearRemoteResourceCache`, `subscribeRemoteResourceCache`, `remoteResourceCacheRevision`. +- Concurrency & coalescing invariants: + - Concurrent updates for the same `userId` must apply every mutation in submission order and never drop the latest mutation. + - Queued mutations waiting behind an in-flight hydration or disk write should coalesce into a single trailing persist instead of issuing one `storage.setItem` per call. + - Unchanged snapshots (when `unsaved` is not set for that `userId`) stay completely silent: no `storage.setItem` and no subscriber emission. + - If `storage.setItem` rejects, that `userId` is marked unsaved so the next update retries disk persistence even if snapshot contents are unchanged. + - `clearRemoteResourceCache()` advances the internal epoch, clears memory, emits, awaits in-flight writes, and deletes all `CACHE_STORAGE_PREFIX` keys; stale pre-clear writes must never resurrect data in memory or storage. + - Persisted JSON is bounded to `MAX_DISK_CHARS`. + +## 3. Device Schedule Index (`src/schedule-index.mjs`) + +- Exports `SCHEDULE_INDEX_TTL_MS` (`30_000`), `SCHEDULE_INDEX_EVENT_COALESCE_MS` (`1_500`), and `createScheduleIndexStore({ now?, setTimer?, clearTimer?, ttlMs?, coalesceMs? })`. +- Returned store API: `loadDeviceSessionScheduleIndex`, `noteScheduleEventInIndexCache`, `invalidateScheduleIndexForDevice`, `invalidateScheduleIndexesAfterLinkRecovery`, `getScheduleIndexInvalidationVersion`, `hasCurrentScheduleIndexRecord`, `sessionMayHaveScheduleRuns`, `clearSessionScheduleIndexCache`. +- Freshness & coalescing invariants: + - Uses injected `now`, `setTimer`, `clearTimer` exclusively (no un-injected global wall-clock/timer assumptions). + - First load for a device is always immediate. + - Within `ttlMs` without invalidation, cached results are returned without issuing RPCs; concurrent in-flight loads for the same device share one request. + - Rapid live-event invalidations (`noteScheduleEventInIndexCache(deviceId, { invalidate: true, ... })` followed by `loadDeviceSessionScheduleIndex`) within `coalesceMs` (`1500ms`) of the previous load coalesce per device into a single trailing refresh, sharing one Promise across callers and using the latest `invoke` and `canStart`. + - **Bypass boundaries**: direct manual refresh (`invalidateScheduleIndexForDevice(deviceId)`) and link recovery (`invalidateScheduleIndexesAfterLinkRecovery(deviceId?)`) clear the event-coalesce marker so the following load executes immediately without waiting for `coalesceMs`. + - `clearSessionScheduleIndexCache()` cancels any pending coalesce timers, settles (rejects) any pending coalesced load promises, and resets all state. + +## 4. Foreground Task Activity (`src/foreground-task-activity.mjs`) + +- Exports `FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS` (`2_500`), `TASK_ACTIVITY_SNAPSHOT`, `receiveHostTaskActivity`, and `startForegroundTaskActivity(source, options)`. +- `options` accepts `{ active, labels, staleDetail, url, write, now?, setTimer?, clearTimer?, minWriteIntervalMs? }`. +- Uses injected `now`, `setTimer`, `clearTimer` exclusively. +- Aggregates verified host reports across online desktop peers (`darwin`, `win32`, `linux`), ranking `attention` > `completed`/`error` > `running`, rejecting out-of-order older revisions, and suppressing identical serialized payloads. +- Trailing throttle & urgency invariants: + - Rapid same-status non-urgent updates (e.g. `running -> running`) within `minWriteIntervalMs` (`2500ms`) of the last write coalesce onto one trailing write emitting the latest state. + - Urgent transitions — initial write, ending (`state === null`), `attention`, and any status transition (`nextStatus !== lastWrittenStatus`) — cancel any pending coalesce timer and write **immediately**. + - If the aggregated state returns to the previously written snapshot before a pending coalesce timer fires, the pending timer is cleared and no redundant write occurs. + - `recheck()` clears any pending timer and resets `previous` / `lastWrittenStatus` before re-reading peers; `dispose()` clears any pending timer and unsubscribes. diff --git a/questions/perf-mobile-home-heat/v1/candidate/ENVIRONMENT.md b/questions/perf-mobile-home-heat/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..29b467a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Virtual time: Time-sensitive modules accept injected `{ now, setTimer, clearTimer }` so tests and benchmarks run deterministically without real multi-second sleeps. +- Public checks: + - `npm test` — functional smoke tests covering all four modules + - `npm run bench` — representative workload reporting home presentation timing, coalesced storage writes, schedule RPC calls, and widget writes diff --git a/questions/perf-mobile-home-heat/v1/candidate/TASK.md b/questions/perf-mobile-home-heat/v1/candidate/TASK.md new file mode 100644 index 0000000..225d34e --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/TASK.md @@ -0,0 +1,19 @@ +# Task + +You are optimizing four performance hotspots extracted from Cindy's mobile Home screen and live-activity pipeline that caused sustained device overheating, high CPU usage, disk write amplification, and ActivityKit/WidgetKit wake storms. + +## Observed Production Symptoms + +1. **Mobile Home presentation churns CPU and GC on every refresh (`src/mobile-home.mjs`)**: `buildMobileHomePresentation` re-maps every session into device identity inputs, clones every session object even when `canonicalDeviceId` is already canonical, performs repeated `.filter()` / `O(D × N)` passes, and runs uncached locale/sort-key computations inside `O(N log N)` sorting. +2. **Concurrent remote-resource cache writes cause AsyncStorage write amplification (`src/remote-resource-cache.mjs`)**: `update()` chains every concurrent mutation into a serial `Promise` chain, causing each mutation in a burst to re-normalize, re-serialize up to 256 KiB, and invoke `storage.setItem` independently instead of coalescing queued mutations per `userId`. +3. **Live schedule event bursts penetrate the 30s schedule-index TTL (`src/schedule-index.mjs`)**: Every `maker:schedule:event` invalidates the per-device cache so rapid event bursts immediately trigger repeated full `maker:schedule:list` + `maker:schedule:list-sidebar-index-runs` RPC pairs, even when events arrive milliseconds apart. +4. **Foreground task activity wakes WidgetKit/ActivityKit on every `running -> running` tick (`src/foreground-task-activity.mjs`)**: Rapid same-status progress updates from multiple desktop hosts immediately flush native widget writes instead of trailing-throttling same-status bursts while preserving immediate delivery for urgent transitions. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with every ordering, canonicalization, concurrency, epoch cancellation, manual-refresh/link-recovery bypass, and urgent-transition invariant defined in `CONTRACT.md`. +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mobile-home-heat/v1/candidate/bench/workload.mjs b/questions/perf-mobile-home-heat/v1/candidate/bench/workload.mjs new file mode 100644 index 0000000..5dfcebd --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/bench/workload.mjs @@ -0,0 +1,207 @@ +import { performance } from 'node:perf_hooks'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { SCHEDULE_INDEX_EVENT_COALESCE_MS, createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 2_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +// 1. Mobile Home presentation benchmark: 600 sessions x 30 refreshes +const devices = [ + { deviceId: 'dev-1', name: 'MacBook Pro', state: 'online', canOpen: true }, + { deviceId: 'dev-2', name: 'Mac Studio', state: 'online', canOpen: true }, + { deviceId: 'dev-3', name: 'Linux Workstation', state: 'online', canOpen: true }, + { deviceId: 'dev-4', name: 'Office Mini', state: 'offline', canOpen: false }, +]; +const sessions = []; +const pendingInteractionIndex = new Map(); +for (let i = 0; i < 600; i += 1) { + const dev = devices[i % devices.length]; + const ts = new Date(Date.UTC(2026, 11, 1, 0, 0, 0) + ((i * 7919) % 500_000) * 1000).toISOString(); + sessions.push({ + id: `sess-${i}`, + title: `Task ${i} feature work`, + status: i % 5 === 0 ? 'archived' : 'active', + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: ts, + lastActivityAt: ts, + workingDir: i % 6 === 0 ? null : `/Users/dev/work/project-${i % 18}`, + workspaceKind: i % 6 === 0 ? 'dialogue' : 'project', + pinnedAt: i < 4 ? ts : null, + deviceLinkDeviceId: dev.deviceId, + deviceLinkDeviceName: dev.name, + canonicalDeviceId: dev.deviceId, + preview: `Latest message preview for session ${i}`, + }); + if (i % 19 === 0) pendingInteractionIndex.set(`sess-${i}`, 1); +} + +buildMobileHomePresentation({ devices, sessions, pendingInteractionIndex, statusFilter: 'all' }); +const t0 = performance.now(); +for (let r = 0; r < 30; r += 1) { + buildMobileHomePresentation({ + devices, + sessions, + pendingInteractionIndex, + statusFilter: r % 3 === 0 ? 'all' : 'active', + }); +} +const home30RefreshesMs = Number((performance.now() - t0).toFixed(2)); + +// 2. Remote resource cache burst writes +async function benchCache() { + const disk = new Map(); + let setItemCalls = 0; + let gateRelease = null; + let gateArmed = false; + const storage = { + async getItem(k) { return disk.get(k) ?? null; }, + async setItem(k, v) { + setItemCalls += 1; + disk.set(k, v); + if (gateArmed) { + gateArmed = false; + await new Promise((resolve) => { gateRelease = resolve; }); + } + }, + async removeItem(k) { disk.delete(k); }, + async getAllKeys() { return [...disk.keys()]; }, + }; + const cache = createRemoteResourceCache({ storage }); + const makeItems = (ver) => Array.from({ length: 40 }, (_, i) => ({ + host: { deviceId: `dev-${i % 4}`, name: `Host ${i % 4}` }, + item: { + ref: { collectionId: 'teammates', kind: 'bot', id: `bot-${i}` }, + display: { title: `Bot ${i}`, preview: 'p'.repeat(400), lastReplyAt: ver + i }, + }, + })); + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + setItemCalls = 0; + gateArmed = true; + const burst = [cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(200))]; + await Promise.resolve(); + await Promise.resolve(); + for (let i = 1; i <= 29; i += 1) { + burst.push(cache.markRemoteResourceRead('alice', `dev-${i % 4}`, `bot-${i}`, 300 + i)); + } + gateRelease?.(); + await Promise.all(burst); + return setItemCalls; +} + +// 3. Schedule index burst RPC calls +async function benchSchedule() { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let rpcCalls = 0; + const invoke = async (_dev, ch) => { + rpcCalls += 1; + if (ch === 'maker:schedule:list') return [{ id: 's1', name: 'Sync', status: 'active', targetSessionId: 't1' }]; + return { runs: [] }; + }; + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + const waiters = []; + for (let i = 0; i < 15; i += 1) { + await clock.advanceBy(80); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + waiters.push(store.loadDeviceSessionScheduleIndex('dev-1', invoke)); + } + await clock.advanceBy(SCHEDULE_INDEX_EVENT_COALESCE_MS + 100); + await Promise.all(waiters); + return rpcCalls; +} + +// 4. Foreground task activity widget writes +async function benchActivity() { + const clock = createVirtualClock(); + let writes = 0; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke() { + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Step 0', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const ctrl = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: () => { writes += 1; }, + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await ctrl.ready; + for (let i = 2; i <= 25; i += 1) { + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: i, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: `Step ${i}`, status: 'running' }, + }, clock.now()); + } + await clock.advanceBy(FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + ctrl.dispose(); + return writes; +} + +const storageWrites = await benchCache(); +const scheduleRpcCalls = await benchSchedule(); +const widgetWrites = await benchActivity(); +console.log(JSON.stringify({ home30RefreshesMs, storageWrites, scheduleRpcCalls, widgetWrites }, null, 2)); diff --git a/questions/perf-mobile-home-heat/v1/candidate/package.json b/questions/perf-mobile-home-heat/v1/candidate/package.json new file mode 100644 index 0000000..25908c4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mobile-home-heat", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/src/foreground-task-activity.mjs b/questions/perf-mobile-home-heat/v1/candidate/src/foreground-task-activity.mjs new file mode 100644 index 0000000..f172f3b --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/src/foreground-task-activity.mjs @@ -0,0 +1,212 @@ +export const FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS = 2_500; +export const TASK_ACTIVITY_SNAPSHOT = 'maker:task-activity:snapshot'; + +const COMPANION_JPEG_MAX = 2048; +const RANK = { attention: 0, completed: 1, error: 1, running: 2 }; +const listeners = new Set(); + +export function receiveHostTaskActivity(device, value, observedAt) { + for (const listener of listeners) listener(device, value, observedAt); +} + +function parseReport(value) { + if (!value || typeof value !== 'object') return null; + const { schemaVersion, revision, waitingCount, unreadCount, runningCount, selected } = value; + const counts = [waitingCount, unreadCount, runningCount]; + if ( + schemaVersion !== 1 + || !Number.isSafeInteger(revision) + || revision < 1 + || !counts.every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 1_000_000) + ) return null; + if (!waitingCount && !unreadCount && !runningCount) { + return selected === null ? value : null; + } + if ( + !selected + || typeof selected.sessionId !== 'string' + || !selected.sessionId + || selected.sessionId.length > 256 + || typeof selected.title !== 'string' + || [...selected.title].length > 100 + || !Object.hasOwn(RANK, selected.status) + || RANK[selected.status] !== (waitingCount ? 0 : unreadCount ? 1 : 2) + ) return null; + return value; +} + +function parseCompanion(value, status) { + if (status === 'running' || !value || typeof value !== 'object') return undefined; + const { hue, glyph, glyphIsInitial, imageJpeg } = value; + if ( + typeof hue !== 'string' || !/^[a-z]{1,16}$/.test(hue) + || typeof glyph !== 'string' || !glyph || glyph.length > 32 + || typeof glyphIsInitial !== 'boolean' + ) return undefined; + const image = typeof imageJpeg === 'string' + && imageJpeg.length <= COMPANION_JPEG_MAX + && /^[A-Za-z0-9+/]+={0,2}$/.test(imageJpeg) + ? imageJpeg + : undefined; + return { hue, glyph, glyphIsInitial, ...(image ? { imageJpeg: image } : {}) }; +} + +let nextOwner = 0; + +export function startForegroundTaskActivity(source, options) { + const now = options.now ?? Date.now; + const setTimer = options.setTimer ?? setTimeout; + const clearTimer = options.clearTimer ?? clearTimeout; + const minWriteIntervalMs = options.minWriteIntervalMs ?? FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS; + void setTimer; + void clearTimer; + void minWriteIntervalMs; + + const owner = 'live-activity-' + ++nextOwner; + let disposed = false; + let devices = []; + const peers = new Map(); + const active = () => !disposed && options.active(); + let previous; + + function publish() { + if (!active() || !peers.size) return; + let observedAt = 0; + let count = 0; + let runningCount = 0; + let attentionCount = 0; + let selected; + for (const [device, peer] of peers) { + if ( + source.getPresenceAvailability(device) === false + || !peer.verified + || !peer.report + || peer.subscription == null + || peer.subscription !== source.getSubscriptionIdentity?.(device, ['sessions']) + ) return; + const { waitingCount, unreadCount, runningCount: running, selected: top } = peer.report; + observedAt = Math.max(observedAt, peer.observedAt); + count += waitingCount + unreadCount + running; + runningCount += running; + attentionCount += waitingCount; + if (top && (!selected || RANK[top.status] < RANK[selected.status])) { + selected = { ...top, device }; + } + } + if (!selected && devices.some((device) => !peers.has(device.deviceId))) return; + const companion = selected ? parseCompanion(selected.companion, selected.status) : undefined; + const state = selected + ? { + status: selected.status, + title: selected.title, + detail: options.labels[selected.status], + count, + runningCount, + attentionCount, + staleDetail: options.staleDetail, + url: options.url(selected.device, selected.sessionId), + ...(companion ? { companion } : {}), + } + : null; + const key = JSON.stringify(state); + if (key === previous) return; + previous = key; + options.write(state, observedAt); + } + + function receive(device, value, observedAt = now()) { + const peer = peers.get(device); + const identity = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || !peer || identity == null) return; + const report = parseReport(value); + if ( + report + && peer.subscription === identity + && peer.report + && (report.revision < peer.report.revision + || (report.revision === peer.report.revision && observedAt < peer.observedAt)) + ) return; + peer.verified = Boolean(report); + peer.subscription = identity; + peer.report = report; + peer.observedAt = observedAt; + publish(); + } + + let readGeneration = 0; + async function readPeer(device, generation) { + const subscription = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || subscription == null) return; + const current = () => active() + && generation === readGeneration + && subscription === source.getSubscriptionIdentity?.(device, ['sessions']); + const started = now(); + try { + const report = await source.invoke(device, TASK_ACTIVITY_SNAPSHOT, [], { + noResultCache: true, + preSend() { + if (!current()) throw new Error('Foreground activity read superseded'); + }, + }); + if (current()) receive(device, report, started); + } catch { + // Unreachable peer leaves APNs in charge. + } + } + + listeners.add(receive); + const ready = (async () => { + const roster = await source.readDeviceList(); + if (!active() || roster.stale) return; + devices = roster.devices.filter( + (device) => !device.isSelf && ['darwin', 'win32', 'linux'].includes(device.platform ?? ''), + ); + const online = devices + .filter((device) => device.online) + .sort((a, b) => (a.deviceId < b.deviceId ? -1 : 1)); + if (online.some((device) => !device.remoteControlEnabled)) return; + for (const { deviceId } of online) { + peers.set(deviceId, { report: null, subscription: null, observedAt: 0, verified: false }); + } + await Promise.all(online.map(async ({ deviceId }) => { + try { + await source.subscribe(owner, deviceId, ['sessions']); + await readPeer(deviceId, readGeneration); + } catch { + // Ignore unavailable peer. + } + })); + })().catch(() => {}); + + let rechecking = false; + return { + ready, + receive, + async recheck() { + if (!active() || rechecking || !peers.size) return; + rechecking = true; + const generation = ++readGeneration; + previous = undefined; + for (const peer of peers.values()) peer.verified = false; + try { + await Promise.all([...peers.keys()].map((device) => readPeer(device, generation))); + } finally { + rechecking = false; + } + }, + rosterChanged(device) { + if (!['darwin', 'win32', 'linux'].includes(device.platform)) return false; + const known = devices.find((row) => row.deviceId === device.deviceId); + return known + ? known.online !== device.online || (device.online && known.remoteControlEnabled !== device.remoteControlEnabled) + : device.online; + }, + dispose() { + disposed = true; + listeners.delete(receive); + for (const device of peers.keys()) { + void source.unsubscribe(owner, device, ['sessions']).catch(() => {}); + } + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/src/mobile-home.mjs b/questions/perf-mobile-home-heat/v1/candidate/src/mobile-home.mjs new file mode 100644 index 0000000..c8c7226 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/src/mobile-home.mjs @@ -0,0 +1,314 @@ +export const MOBILE_HOME_ALL_DEVICES = 'all'; + +function normalizeDeviceNameKey(value) { + const trimmed = (value ?? '').trim(); + const lower = trimmed.toLowerCase(); + return lower === 'unknown' || lower === 'no' ? '' : trimmed; +} + +export function buildDeviceIdentity(devices, rawIdentities) { + const knownDeviceIds = new Set(); + const deviceIdsByName = new Map(); + for (const device of devices) { + const deviceId = (device.deviceId ?? '').trim(); + if (!deviceId) continue; + knownDeviceIds.add(deviceId); + const name = normalizeDeviceNameKey(device.name); + if (!name) continue; + const ids = deviceIdsByName.get(name) ?? []; + ids.push(deviceId); + deviceIdsByName.set(name, ids); + } + + const staleIdsByName = new Map(); + for (const raw of rawIdentities) { + const deviceId = raw.deviceId?.trim(); + if (!deviceId || knownDeviceIds.has(deviceId)) continue; + const name = normalizeDeviceNameKey(raw.name); + if (!name) continue; + const ids = staleIdsByName.get(name) ?? new Set(); + ids.add(deviceId); + staleIdsByName.set(name, ids); + } + + const uniqueDeviceIdByName = new Map(); + for (const [name, ids] of deviceIdsByName) { + if (ids.length !== 1) continue; + if ((staleIdsByName.get(name)?.size ?? 0) > 1) continue; + uniqueDeviceIdByName.set(name, ids[0]); + } + return { knownDeviceIds, uniqueDeviceIdByName }; +} + +export function resolveCanonicalDeviceId(rawDeviceId, deviceName, identity) { + const raw = rawDeviceId?.trim() ?? ''; + if (raw && !identity.knownDeviceIds.has(raw)) { + const name = normalizeDeviceNameKey(deviceName); + const claimed = name ? identity.uniqueDeviceIdByName.get(name) : undefined; + if (claimed) return claimed; + } + return raw || rawDeviceId; +} + +function canonicalizeSessionDevice(session, identity) { + return { + ...session, + canonicalDeviceId: resolveCanonicalDeviceId(session.deviceLinkDeviceId, session.deviceLinkDeviceName, identity), + }; +} + +function sessionDeviceKey(session) { + return session.canonicalDeviceId ?? session.deviceLinkDeviceId ?? null; +} + +function sessionStatusRank(status) { + if (status === 'active') return 0; + if (status === 'archived') return 1; + return 2; +} + +function lastActivityTime(session) { + return session.lastActivityAt ?? session.userSendAt ?? session.updatedAt ?? session.createdAt ?? ''; +} + +function compareStrings(left, right) { + return new Intl.Collator('en').compare(left, right); +} + +export function compareSessionsByStatusThenActivityDesc(a, b) { + const statusDiff = sessionStatusRank(a.status) - sessionStatusRank(b.status); + if (statusDiff !== 0) return statusDiff; + return compareStrings(lastActivityTime(b), lastActivityTime(a)); +} + +function isDialogueSession(session) { + return session.workspaceKind === 'dialogue' || !session.workingDir; +} + +function isAutomationSession(session, scheduleIndex) { + return session.source === 'scheduler' + || (typeof session.title === 'string' && session.title.startsWith('[Schedule] ')) + || Boolean(scheduleIndex?.get(session.id)); +} + +function normalizeProjectDir(value) { + const trimmed = (value ?? '').trim(); + let end = trimmed.length; + while (end > 0 && (trimmed[end - 1] === '/' || trimmed[end - 1] === '\\')) end -= 1; + const cleaned = end > 0 ? trimmed.slice(0, end) : trimmed; + if (/^[a-z]:[\\/]/i.test(cleaned) || cleaned.includes('\\')) { + return cleaned.replace(/\\/g, '/').toLowerCase(); + } + return cleaned || '__unknown_project__'; +} + +function buildDeviceFilters(devices, sessions, pendingInteractionIndex, selectedDeviceId) { + const nonDeleted = sessions.filter((session) => session.status !== 'deleted'); + const allWaiting = nonDeleted.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + const filters = [ + { + id: MOBILE_HOME_ALL_DEVICES, + deviceId: null, + label: 'All devices', + available: true, + state: 'online', + sessionCount: nonDeleted.length, + waitingCount: allWaiting, + selected: false, + }, + ]; + for (const device of devices) { + const devId = device.deviceId.trim(); + const owned = nonDeleted.filter((session) => sessionDeviceKey(session) === devId); + const waitingCount = owned.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + filters.push({ + id: devId, + deviceId: devId, + label: device.name, + available: Boolean(device.canOpen ?? device.state === 'online'), + state: device.state ?? 'offline', + sessionCount: owned.length, + waitingCount, + selected: false, + }); + } + const normalizedSelected = selectedDeviceId && filters.some((f) => f.deviceId === selectedDeviceId) + ? selectedDeviceId + : null; + return { + normalizedSelectedDeviceId: normalizedSelected, + deviceFilters: filters.map((item) => ({ + ...item, + selected: normalizedSelected === null + ? item.id === MOBILE_HOME_ALL_DEVICES + : item.deviceId === normalizedSelected, + })), + }; +} + +function matchesSelectedDevice(session, selectedDeviceId) { + return !selectedDeviceId || sessionDeviceKey(session) === selectedDeviceId; +} + +function matchesStatusFilter(session, filter, pendingInteractionIndex, scheduleIndex) { + if (filter === 'all') return session.status !== 'deleted'; + if (filter === 'waiting') { + return session.status !== 'deleted' && (pendingInteractionIndex?.get(session.id) ?? 0) > 0; + } + if (filter === 'automation') { + return session.status !== 'deleted' && isAutomationSession(session, scheduleIndex); + } + return session.status === filter; +} + +function matchesSearchQuery(session, query, messagePreviewIndex, pendingInteractionIndex, scheduleIndex) { + if (!query) return true; + const scheduleInfo = scheduleIndex?.get(session.id); + const haystack = [ + session.title, + session.workingDir, + session.model, + session.agentKind, + session.status, + session.deviceLinkDeviceName, + scheduleInfo?.scheduleName, + (pendingInteractionIndex?.get(session.id) ?? 0) > 0 ? 'waiting pending attention' : null, + messagePreviewIndex?.get(session.id) ?? session.preview, + ].filter(Boolean).join(' ').toLowerCase(); + return haystack.includes(query); +} + +function toListItem(session, pendingInteractionIndex, scheduleIndex, messagePreviewIndex) { + const waitingCount = pendingInteractionIndex?.get(session.id) ?? 0; + return { + id: session.id, + title: session.title || 'Untitled session', + status: session.status, + activityAt: lastActivityTime(session), + deviceId: sessionDeviceKey(session), + physicalDeviceId: session.deviceLinkDeviceId ?? null, + workingDir: session.workingDir ?? null, + pinned: Boolean(session.pinnedAt), + waitingCount, + preview: messagePreviewIndex?.get(session.id) ?? session.preview ?? null, + scheduleName: scheduleIndex?.get(session.id)?.scheduleName ?? null, + isDialogue: isDialogueSession(session), + session, + }; +} + +function buildProjectGroups(projectItems) { + const groups = new Map(); + for (const item of projectItems) { + const dirKey = normalizeProjectDir(item.workingDir); + const key = `${item.deviceId ?? ''}::${dirKey}`; + let group = groups.get(key); + if (!group) { + group = { + key, + deviceId: item.deviceId, + workingDir: item.workingDir ?? '__unknown_project__', + latestActivityAt: item.activityAt, + sessionCount: 0, + pendingInteractionCount: 0, + sessions: [], + }; + groups.set(key, group); + } + group.sessions.push(item); + group.sessionCount += 1; + group.pendingInteractionCount += item.waitingCount; + if (compareStrings(item.activityAt, group.latestActivityAt) > 0) { + group.latestActivityAt = item.activityAt; + } + } + return [...groups.values()].sort((a, b) => { + const timeDiff = compareStrings(b.latestActivityAt, a.latestActivityAt); + if (timeDiff !== 0) return timeDiff; + return compareStrings(a.key, b.key); + }); +} + +function summarizeOverview(sessions, projects, pendingInteractionIndex, selectedDeviceId) { + const scoped = sessions.filter( + (session) => session.status !== 'deleted' && matchesSelectedDevice(session, selectedDeviceId), + ); + const chats = scoped.filter(isDialogueSession).length; + const pinned = scoped.filter((session) => Boolean(session.pinnedAt)).length; + const waiting = scoped.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + const devices = new Set(scoped.map((session) => sessionDeviceKey(session)).filter(Boolean)).size; + return { + all: scoped.length, + chats, + devices, + pinned, + projects: projects.length, + waiting, + }; +} + +export function buildMobileHomePresentation({ + devices = [], + sessions = [], + selectedDeviceId = null, + statusFilter = 'active', + searchQuery = '', + inboxMode = false, + pendingInteractionIndex, + scheduleIndex, + messagePreviewIndex, +} = {}) { + const deviceIdentity = buildDeviceIdentity( + devices, + sessions.map((session) => ({ + deviceId: session.deviceLinkDeviceId, + name: session.deviceLinkDeviceName, + })), + ); + const normalizedSessions = sessions.map((session) => canonicalizeSessionDevice(session, deviceIdentity)); + const { deviceFilters, normalizedSelectedDeviceId } = buildDeviceFilters( + devices, + normalizedSessions, + pendingInteractionIndex, + selectedDeviceId, + ); + const query = searchQuery.trim().toLowerCase(); + const filteredSessions = normalizedSessions + .filter((session) => matchesSelectedDevice(session, normalizedSelectedDeviceId)) + .filter((session) => matchesStatusFilter(session, statusFilter, pendingInteractionIndex, scheduleIndex)) + .filter((session) => matchesSearchQuery( + session, + query, + messagePreviewIndex, + pendingInteractionIndex, + scheduleIndex, + )) + .sort(compareSessionsByStatusThenActivityDesc); + + const items = filteredSessions.map((session) => toListItem( + session, + pendingInteractionIndex, + scheduleIndex, + messagePreviewIndex, + )); + const pinned = items.filter((item) => item.pinned); + const groupedItems = inboxMode ? items : items.filter((item) => !item.pinned); + const chats = groupedItems.filter((item) => item.isDialogue); + const projects = buildProjectGroups(groupedItems.filter((item) => !item.isDialogue)); + const overview = summarizeOverview( + normalizedSessions, + projects, + pendingInteractionIndex, + normalizedSelectedDeviceId, + ); + + return { + chats, + deviceFilters, + items, + overview, + pinned, + projects, + selectedDeviceId: normalizedSelectedDeviceId, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/src/remote-resource-cache.mjs b/questions/perf-mobile-home-heat/v1/candidate/src/remote-resource-cache.mjs new file mode 100644 index 0000000..81b8ae4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/src/remote-resource-cache.mjs @@ -0,0 +1,218 @@ +export const CACHE_STORAGE_PREFIX = 'cindy.remoteResources.v1.'; +export const MAX_DISK_CHARS = 256 * 1024; + +const emptySnapshot = () => ({ home: [], items: {}, read: {}, readSequences: {} }); +const validSequence = (value) => typeof value === 'string' && /^\d{1,30}$/.test(value); + +export const remoteResourceReadKey = (deviceId, resourceId) => JSON.stringify([deviceId, resourceId]); + +function normalize(raw) { + const out = emptySnapshot(); + if (!raw || typeof raw !== 'object') return out; + if (Array.isArray(raw.home)) { + for (const row of raw.home.slice(0, 32)) { + if (!row || typeof row.id !== 'string' || row.id.length > 160 || typeof row.title !== 'string') continue; + out.home.push({ + id: row.id, + title: row.title.slice(0, 512), + resourceKind: typeof row.resourceKind === 'string' ? row.resourceKind.slice(0, 160) : 'collection', + targets: Array.isArray(row.targets) ? row.targets.map((t) => ({ deviceId: String(t.deviceId), name: String(t.name ?? '') })) : [], + }); + } + } + if (raw.items && typeof raw.items === 'object') { + for (const [id, rows] of Object.entries(raw.items).slice(0, 32)) { + if (id.length > 160 || !Array.isArray(rows)) continue; + out.items[id] = rows.slice(0, 200).flatMap((row) => { + if (!row || !row.host || !row.item || !row.item.ref) return []; + const host = { deviceId: String(row.host.deviceId), name: String(row.host.name ?? '') }; + const ref = { + collectionId: String(row.item.ref.collectionId ?? id), + kind: String(row.item.ref.kind ?? 'bot'), + id: String(row.item.ref.id), + }; + const display = { + title: String(row.item.display?.title ?? ''), + preview: typeof row.item.display?.preview === 'string' ? row.item.display.preview.slice(0, 4096) : '', + ...(typeof row.item.display?.avatar === 'string' ? { avatar: row.item.display.avatar } : {}), + ...(typeof row.item.display?.lastReplyAt === 'number' ? { lastReplyAt: row.item.display.lastReplyAt } : {}), + ...(typeof row.item.display?.lastReadAt === 'number' ? { lastReadAt: row.item.display.lastReadAt } : {}), + }; + return [{ + host, + item: { ref, display }, + key: JSON.stringify([host.deviceId, ref.collectionId, ref.kind, ref.id]), + }]; + }); + } + } + if (raw.read && typeof raw.read === 'object') { + for (const [key, at] of Object.entries(raw.read).slice(-2000)) { + if (key.length <= 600 && typeof at === 'number' && Number.isFinite(at) && at >= 0) out.read[key] = at; + } + } + if (raw.readSequences && typeof raw.readSequences === 'object') { + for (const [key, seq] of Object.entries(raw.readSequences).slice(-2000)) { + if (key.length <= 600 && validSequence(seq)) out.readSequences[key] = seq; + } + } + return out; +} + +function diskSnapshot(raw) { + if (raw.length <= MAX_DISK_CHARS) return raw; + const copy = JSON.parse(raw); + let remaining = raw.length - MAX_DISK_CHARS; + // Strip bulky avatars first before evicting items or read markers. + for (const rows of Object.values(copy.items)) { + for (const row of rows) { + if (remaining <= 0) break; + const avatar = row.item?.display?.avatar; + if (typeof avatar === 'string' && avatar.length > 0) { + remaining -= avatar.length + 12; + delete row.item.display.avatar; + } + } + } + for (const rows of Object.values(copy.items)) { + while (remaining > 0 && rows.length > 0) { + remaining -= JSON.stringify(rows.pop()).length + 1; + } + } + for (const map of [copy.read, copy.readSequences ?? {}]) { + for (const key of Object.keys(map)) { + if (remaining <= 0) break; + remaining -= JSON.stringify(key).length + JSON.stringify(map[key]).length + 2; + delete map[key]; + } + } + while (remaining > 0 && copy.home.length > 0) { + remaining -= JSON.stringify(copy.home.pop()).length + 1; + } + return JSON.stringify(copy); +} + +export function createRemoteResourceCache({ storage }) { + let epoch = 0; + let revision = 0; + const writes = new Map(); + const snapshots = new Map(); + const unsaved = new Set(); + const listeners = new Set(); + + const emit = () => { + revision += 1; + for (const fn of listeners) fn(); + }; + + async function readRemoteResourceSnapshot(userId) { + if (!userId) return emptySnapshot(); + const cached = snapshots.get(userId); + if (cached) return cached; + const expected = epoch; + const raw = await storage.getItem(CACHE_STORAGE_PREFIX + userId).catch(() => null); + let parsed = emptySnapshot(); + if (typeof raw === 'string' && raw.length > 0) { + try { + parsed = normalize(JSON.parse(raw)); + } catch { + parsed = emptySnapshot(); + } + } + if (expected === epoch) snapshots.set(userId, parsed); + return parsed; + } + + async function update(userId, change) { + if (!userId) return; + const expected = epoch; + const previous = writes.get(userId) ?? Promise.resolve(); + const next = previous.then(async () => { + const snapshot = await readRemoteResourceSnapshot(userId); + if (expected !== epoch) return; + const before = JSON.stringify(snapshot); + change(snapshot); + const cleaned = normalize(snapshot); + const raw = JSON.stringify(cleaned); + snapshots.set(userId, cleaned); + if (raw === before && !unsaved.has(userId)) return; + if (raw !== before) emit(); + const saved = await storage + .setItem(CACHE_STORAGE_PREFIX + userId, diskSnapshot(raw)) + .then(() => true, () => false); + if (expected !== epoch) { + await storage.removeItem(CACHE_STORAGE_PREFIX + userId).catch(() => undefined); + return; + } + if (saved) unsaved.delete(userId); + else unsaved.add(userId); + }); + writes.set(userId, next); + await next.finally(() => { + if (writes.get(userId) === next) writes.delete(userId); + }); + } + + return { + readRemoteResourceSnapshot, + cacheRemoteResourceHome(userId, home) { + return update(userId, (s) => { s.home = home; }); + }, + cacheRemoteResourceItems(userId, collectionId, items) { + return update(userId, (s) => { + s.items[collectionId] = items; + for (const row of items) { + const key = remoteResourceReadKey(row.host.deviceId, row.item.ref.id); + if ((row.item.ref.kind === 'bot' || row.item.ref.kind === 'bot-group') && s.read[key] === undefined) { + s.read[key] = row.item.display?.lastReplyAt ?? 0; + } + const hostRead = row.item.display?.lastReadAt; + if (typeof hostRead === 'number' && hostRead > (s.read[key] ?? 0)) { + s.read[key] = hostRead; + } + } + }); + }, + markRemoteResourceRead(userId, deviceId, resourceId, at, sequence) { + return update(userId, (s) => { + const key = remoteResourceReadKey(deviceId, resourceId); + if (Number.isFinite(at) && at >= 0) { + s.read[key] = Math.max(s.read[key] ?? 0, at); + } + if (validSequence(sequence)) { + s.readSequences ??= {}; + if (s.readSequences[key] === undefined || BigInt(sequence) > BigInt(s.readSequences[key])) { + s.readSequences[key] = sequence; + } + } + }); + }, + isRemoteResourceUnread(userId, deviceId, resourceId, lastReplyAt) { + if (!userId || typeof lastReplyAt !== 'number' || lastReplyAt <= 0) return false; + const snapshot = snapshots.get(userId); + if (!snapshot) return false; + const readAt = snapshot.read[remoteResourceReadKey(deviceId, resourceId)] ?? 0; + return lastReplyAt > readAt; + }, + async clearRemoteResourceCache() { + epoch += 1; + snapshots.clear(); + unsaved.clear(); + emit(); + await Promise.allSettled([...writes.values()]); + const keys = await storage.getAllKeys().catch(() => []); + for (const key of keys) { + if (key.startsWith(CACHE_STORAGE_PREFIX)) { + await storage.removeItem(key).catch(() => undefined); + } + } + }, + subscribeRemoteResourceCache(fn) { + listeners.add(fn); + return () => { listeners.delete(fn); }; + }, + remoteResourceCacheRevision() { + return revision; + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/src/schedule-index.mjs b/questions/perf-mobile-home-heat/v1/candidate/src/schedule-index.mjs new file mode 100644 index 0000000..e7d5142 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/src/schedule-index.mjs @@ -0,0 +1,196 @@ +export const SCHEDULE_INDEX_TTL_MS = 30_000; +export const SCHEDULE_INDEX_EVENT_COALESCE_MS = 1_500; + +function buildIndexMap(schedules, runsPayload) { + const runsBySchedule = new Map(); + const runs = Array.isArray(runsPayload?.runs) ? runsPayload.runs : []; + for (const run of runs) { + if (!run || typeof run.scheduleId !== 'string') continue; + let bucket = runsBySchedule.get(run.scheduleId); + if (!bucket) { + bucket = []; + runsBySchedule.set(run.scheduleId, bucket); + } + bucket.push(run); + } + const index = new Map(); + for (const schedule of Array.isArray(schedules) ? schedules : []) { + if (!schedule || !schedule.targetSessionId) continue; + const schedRuns = runsBySchedule.get(schedule.id) ?? []; + let latestRunAt = 0; + let running = false; + let hasUnreadFailedRun = false; + const unreadRunIds = []; + for (const r of schedRuns) { + if (typeof r.startedAt === 'number' && r.startedAt > latestRunAt) latestRunAt = r.startedAt; + if (r.status === 'running') running = true; + if (r.unread) { + unreadRunIds.push(r.id); + if (r.status === 'failed') hasUnreadFailedRun = true; + } + } + index.set(schedule.targetSessionId, { + scheduleId: schedule.id, + scheduleName: schedule.name ?? 'Automation', + status: schedule.status ?? 'active', + latestRunAt, + running, + unreadCount: unreadRunIds.length, + unreadRunIds, + hasUnreadFailedRun, + }); + } + return index; +} + +export function createScheduleIndexStore({ + now = Date.now, + setTimer = setTimeout, + clearTimer = clearTimeout, + ttlMs = SCHEDULE_INDEX_TTL_MS, + coalesceMs = SCHEDULE_INDEX_EVENT_COALESCE_MS, +} = {}) { + // Keep injected timer references available for event coalescing implementations. + void setTimer; + void clearTimer; + void coalesceMs; + + let cacheGeneration = 0; + const throttleEntries = new Map(); + const invalidationVersions = new Map(); + const boundSessionsByDevice = new Map(); + + function getScheduleIndexInvalidationVersion(deviceId) { + return invalidationVersions.get(deviceId) ?? 0; + } + + function invalidateScheduleIndexForDevice(deviceId) { + if (!deviceId) return; + const entry = throttleEntries.get(deviceId); + if (entry?.pending) entry.invalidated = true; + else throttleEntries.delete(deviceId); + invalidationVersions.set(deviceId, getScheduleIndexInvalidationVersion(deviceId) + 1); + } + + function invalidateScheduleIndexesAfterLinkRecovery(deviceId) { + const keys = deviceId === undefined ? [...throttleEntries.keys()] : [deviceId]; + for (const key of keys) { + const entry = throttleEntries.get(key); + if (!entry || entry.failedAt === null || entry.failedTransient) { + invalidateScheduleIndexForDevice(key); + } + } + } + + function noteScheduleEventInIndexCache(deviceId, change) { + if (!deviceId) return; + const known = boundSessionsByDevice.get(deviceId); + const wasCurrent = known !== undefined + && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + if (change.invalidate) invalidateScheduleIndexForDevice(deviceId); + if (!known) return; + if (!wasCurrent || change.scheduleListChanged) { + boundSessionsByDevice.delete(deviceId); + return; + } + boundSessionsByDevice.set(deviceId, { + sessionIds: change.sessionId && !known.sessionIds.has(change.sessionId) + ? new Set([...known.sessionIds, change.sessionId]) + : known.sessionIds, + failedScheduleIds: known.failedScheduleIds, + invalidationVersion: getScheduleIndexInvalidationVersion(deviceId), + }); + } + + function hasCurrentScheduleIndexRecord(deviceId) { + if (!deviceId) return false; + const known = boundSessionsByDevice.get(deviceId); + return known !== undefined && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + } + + function sessionMayHaveScheduleRuns(deviceId, sessionId, source) { + if (source === 'scheduler') return true; + const known = boundSessionsByDevice.get(deviceId); + if (!known || known.invalidationVersion !== getScheduleIndexInvalidationVersion(deviceId)) return true; + return known.sessionIds.has(sessionId); + } + + function clearSessionScheduleIndexCache() { + cacheGeneration += 1; + throttleEntries.clear(); + invalidationVersions.clear(); + boundSessionsByDevice.clear(); + } + + function loadSharedSessionScheduleIndex(deviceId, invoke, canStart = () => true) { + const existing = throttleEntries.get(deviceId); + const currentNow = now(); + if (existing) { + if (existing.pending) return existing.pending; + if (!existing.invalidated && existing.value && (currentNow - existing.loadedAt) < ttlMs) { + return Promise.resolve(existing.value); + } + } + if (!canStart()) return Promise.reject(new Error('Schedule index consumer inactive')); + + const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId); + const gen = cacheGeneration; + const entry = { + pending: null, + value: null, + loadedAt: 0, + invalidated: false, + failedAt: null, + failedTransient: false, + }; + const promise = Promise.all([ + invoke(deviceId, 'maker:schedule:list', [null, { summaryOnly: true }]), + invoke(deviceId, 'maker:schedule:list-sidebar-index-runs', []), + ]).then(([schedules, runsPayload]) => { + const index = buildIndexMap(schedules, runsPayload); + entry.pending = null; + if (gen === cacheGeneration && !entry.invalidated && throttleEntries.get(deviceId) === entry) { + entry.value = index; + entry.loadedAt = now(); + const failedScheduleIds = new Set(); + for (const info of index.values()) { + if (info.hasUnreadFailedRun) failedScheduleIds.add(info.scheduleId); + } + boundSessionsByDevice.set(deviceId, { + sessionIds: new Set(index.keys()), + failedScheduleIds, + invalidationVersion, + }); + } else if (throttleEntries.get(deviceId) === entry) { + throttleEntries.delete(deviceId); + } + return index; + }, (error) => { + entry.pending = null; + if (throttleEntries.get(deviceId) === entry) { + entry.failedAt = now(); + entry.failedTransient = error?.code === 'LOCAL_LINK_DOWN'; + if (entry.invalidated) throttleEntries.delete(deviceId); + } + throw error; + }); + entry.pending = promise; + throttleEntries.set(deviceId, entry); + return promise; + } + + function loadDeviceSessionScheduleIndex(deviceId, invoke, canStart) { + return loadSharedSessionScheduleIndex(deviceId, invoke, canStart); + } + + return { + loadDeviceSessionScheduleIndex, + noteScheduleEventInIndexCache, + invalidateScheduleIndexForDevice, + invalidateScheduleIndexesAfterLinkRecovery, + getScheduleIndexInvalidationVersion, + hasCurrentScheduleIndexRecord, + sessionMayHaveScheduleRuns, + clearSessionScheduleIndexCache, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/candidate/tests/smoke.test.mjs b/questions/perf-mobile-home-heat/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..95f8338 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,181 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + TASK_ACTIVITY_SNAPSHOT, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 1_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +function createMemoryStorage() { + const map = new Map(); + return { + map, + writes: 0, + async getItem(k) { return map.get(k) ?? null; }, + async setItem(k, v) { this.writes += 1; map.set(k, v); }, + async removeItem(k) { map.delete(k); }, + async getAllKeys() { return [...map.keys()]; }, + }; +} + +test('buildMobileHomePresentation canonicalizes stale devices and sorts active before archived', () => { + const devices = [ + { deviceId: 'dev-mac', name: 'Studio Mac', state: 'online', canOpen: true }, + { deviceId: 'dev-linux', name: 'Build Box', state: 'online', canOpen: true }, + ]; + const sessions = [ + { + id: 's-arch', + title: 'Old Task', + status: 'archived', + createdAt: '2026-12-01T10:00:00.000Z', + updatedAt: '2026-12-04T10:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + { + id: 's-stale', + title: 'Relinked Task', + status: 'active', + createdAt: '2026-12-01T10:00:00.000Z', + lastActivityAt: '2026-12-04T12:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-old-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + ]; + const res = buildMobileHomePresentation({ devices, sessions, statusFilter: 'all' }); + assert.deepEqual(res.items.map((i) => i.id), ['s-stale', 's-arch']); + assert.equal(res.items[0].deviceId, 'dev-mac'); + assert.equal(res.items[0].physicalDeviceId, 'dev-old-mac'); + assert.equal(res.projects.length, 1); + assert.equal(res.projects[0].sessionCount, 2); +}); + +test('remoteResourceCache persists mutations and stays silent on no-ops', async () => { + const storage = createMemoryStorage(); + const cache = createRemoteResourceCache({ storage }); + const row = (replyAt) => [{ + host: { deviceId: 'dev-1', name: 'Mac' }, + item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt: replyAt } }, + }]; + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + const writesAfterSeed = storage.writes; + const revAfterSeed = cache.remoteResourceCacheRevision(); + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + assert.equal(storage.writes, writesAfterSeed); + assert.equal(cache.remoteResourceCacheRevision(), revAfterSeed); + await cache.markRemoteResourceRead('alice', 'dev-1', 'writer', 200); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 150), false); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 250), true); +}); + +test('scheduleIndex caches within TTL and reloads after invalidation', async () => { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let calls = 0; + const invoke = async (_dev, channel) => { + calls += 1; + if (channel === 'maker:schedule:list') return [{ id: 'sc-1', name: 'Nightly', status: 'active', targetSessionId: 'task-1' }]; + return { runs: [{ id: 'r-1', scheduleId: 'sc-1', startedAt: 500, status: 'completed', unread: true }] }; + }; + const first = await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(first.get('task-1')?.scheduleName, 'Nightly'); + assert.equal(calls, 2); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 2); + store.invalidateScheduleIndexForDevice('dev-1'); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 4); +}); + +test('foregroundTaskActivity publishes initial snapshot and urgent endings immediately', async () => { + const clock = createVirtualClock(); + const written = []; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke(_dev, channel) { + assert.equal(channel, TASK_ACTIVITY_SNAPSHOT); + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Building app', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const controller = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: (state, observedAt) => written.push({ state, observedAt }), + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await controller.ready; + assert.equal(written.length, 1); + assert.equal(written[0].state?.status, 'running'); + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: 2, + waitingCount: 0, + unreadCount: 0, + runningCount: 0, + selected: null, + }, clock.now()); + assert.equal(written.at(-1)?.state, null); + controller.dispose(); +}); diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/CONTRACT.md b/questions/perf-mobile-home-heat/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..c8a493a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,50 @@ +# Product & Runtime Contract + +## 1. Mobile Home Presentation (`src/mobile-home.mjs`) + +- Exports `MOBILE_HOME_ALL_DEVICES` (`'all'`), `buildDeviceIdentity`, `resolveCanonicalDeviceId`, `compareSessionsByStatusThenActivityDesc`, and `buildMobileHomePresentation`. +- Device identity canonicalization: + - Known device IDs (trimmed non-empty `device.deviceId` from `devices`) remain unchanged. + - Unknown (stale) session `deviceLinkDeviceId` values whose `deviceLinkDeviceName` uniquely matches exactly one current device (and has no conflicting stale device IDs sharing the same name) are claimed to that device's canonical `deviceId`. + - Placeholder names (`'unknown'`, `'no'`, case-insensitive) never participate in name-based claiming. + - Canonicalization sets `canonicalDeviceId` without ever mutating `deviceLinkDeviceId`. +- Filtering & sorting parity: + - Filters by `selectedDeviceId` (normalized against available device filters), `statusFilter` (`'active' | 'archived' | 'waiting' | 'automation' | 'all'`), and case-insensitive `searchQuery`. + - Sorts matched sessions by status rank (`active` < `archived` < others) and then descending by `lastActivityAt ?? userSendAt ?? updatedAt ?? createdAt`. + - Output (`items`, `pinned`, `chats`, `projects`, `deviceFilters`, `overview`, `selectedDeviceId`) must match baseline semantics exactly for all inputs. + +## 2. Remote Resource Cache (`src/remote-resource-cache.mjs`) + +- Exports `CACHE_STORAGE_PREFIX` (`'cindy.remoteResources.v1.'`), `MAX_DISK_CHARS` (`256 * 1024`), `remoteResourceReadKey`, and `createRemoteResourceCache({ storage })`. +- Returned cache API: `readRemoteResourceSnapshot`, `cacheRemoteResourceHome`, `cacheRemoteResourceItems`, `markRemoteResourceRead`, `isRemoteResourceUnread`, `clearRemoteResourceCache`, `subscribeRemoteResourceCache`, `remoteResourceCacheRevision`. +- Concurrency & coalescing invariants: + - Concurrent updates for the same `userId` must apply every mutation in submission order and never drop the latest mutation. + - Queued mutations waiting behind an in-flight hydration or disk write should coalesce into a single trailing persist instead of issuing one `storage.setItem` per call. + - Unchanged snapshots (when `unsaved` is not set for that `userId`) stay completely silent: no `storage.setItem` and no subscriber emission. + - If `storage.setItem` rejects, that `userId` is marked unsaved so the next update retries disk persistence even if snapshot contents are unchanged. + - `clearRemoteResourceCache()` advances the internal epoch, clears memory, emits, awaits in-flight writes, and deletes all `CACHE_STORAGE_PREFIX` keys; stale pre-clear writes must never resurrect data in memory or storage. + - Persisted JSON is bounded to `MAX_DISK_CHARS`. + +## 3. Device Schedule Index (`src/schedule-index.mjs`) + +- Exports `SCHEDULE_INDEX_TTL_MS` (`30_000`), `SCHEDULE_INDEX_EVENT_COALESCE_MS` (`1_500`), and `createScheduleIndexStore({ now?, setTimer?, clearTimer?, ttlMs?, coalesceMs? })`. +- Returned store API: `loadDeviceSessionScheduleIndex`, `noteScheduleEventInIndexCache`, `invalidateScheduleIndexForDevice`, `invalidateScheduleIndexesAfterLinkRecovery`, `getScheduleIndexInvalidationVersion`, `hasCurrentScheduleIndexRecord`, `sessionMayHaveScheduleRuns`, `clearSessionScheduleIndexCache`. +- Freshness & coalescing invariants: + - Uses injected `now`, `setTimer`, `clearTimer` exclusively (no un-injected global wall-clock/timer assumptions). + - First load for a device is always immediate. + - Within `ttlMs` without invalidation, cached results are returned without issuing RPCs; concurrent in-flight loads for the same device share one request. + - Rapid live-event invalidations (`noteScheduleEventInIndexCache(deviceId, { invalidate: true, ... })` followed by `loadDeviceSessionScheduleIndex`) within `coalesceMs` (`1500ms`) of the previous load coalesce per device into a single trailing refresh, sharing one Promise across callers and using the latest `invoke` and `canStart`. + - **Bypass boundaries**: direct manual refresh (`invalidateScheduleIndexForDevice(deviceId)`) and link recovery (`invalidateScheduleIndexesAfterLinkRecovery(deviceId?)`) clear the event-coalesce marker so the following load executes immediately without waiting for `coalesceMs`. + - `clearSessionScheduleIndexCache()` cancels any pending coalesce timers, settles (rejects) any pending coalesced load promises, and resets all state. + +## 4. Foreground Task Activity (`src/foreground-task-activity.mjs`) + +- Exports `FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS` (`2_500`), `TASK_ACTIVITY_SNAPSHOT`, `receiveHostTaskActivity`, and `startForegroundTaskActivity(source, options)`. +- `options` accepts `{ active, labels, staleDetail, url, write, now?, setTimer?, clearTimer?, minWriteIntervalMs? }`. +- Uses injected `now`, `setTimer`, `clearTimer` exclusively. +- Aggregates verified host reports across online desktop peers (`darwin`, `win32`, `linux`), ranking `attention` > `completed`/`error` > `running`, rejecting out-of-order older revisions, and suppressing identical serialized payloads. +- Trailing throttle & urgency invariants: + - Rapid same-status non-urgent updates (e.g. `running -> running`) within `minWriteIntervalMs` (`2500ms`) of the last write coalesce onto one trailing write emitting the latest state. + - Urgent transitions — initial write, ending (`state === null`), `attention`, and any status transition (`nextStatus !== lastWrittenStatus`) — cancel any pending coalesce timer and write **immediately**. + - If the aggregated state returns to the previously written snapshot before a pending coalesce timer fires, the pending timer is cleared and no redundant write occurs. + - `recheck()` clears any pending timer and resets `previous` / `lastWrittenStatus` before re-reading peers; `dispose()` clears any pending timer and unsubscribes. diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/ENVIRONMENT.md b/questions/perf-mobile-home-heat/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..29b467a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Virtual time: Time-sensitive modules accept injected `{ now, setTimer, clearTimer }` so tests and benchmarks run deterministically without real multi-second sleeps. +- Public checks: + - `npm test` — functional smoke tests covering all four modules + - `npm run bench` — representative workload reporting home presentation timing, coalesced storage writes, schedule RPC calls, and widget writes diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/TASK.md b/questions/perf-mobile-home-heat/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..225d34e --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/TASK.md @@ -0,0 +1,19 @@ +# Task + +You are optimizing four performance hotspots extracted from Cindy's mobile Home screen and live-activity pipeline that caused sustained device overheating, high CPU usage, disk write amplification, and ActivityKit/WidgetKit wake storms. + +## Observed Production Symptoms + +1. **Mobile Home presentation churns CPU and GC on every refresh (`src/mobile-home.mjs`)**: `buildMobileHomePresentation` re-maps every session into device identity inputs, clones every session object even when `canonicalDeviceId` is already canonical, performs repeated `.filter()` / `O(D × N)` passes, and runs uncached locale/sort-key computations inside `O(N log N)` sorting. +2. **Concurrent remote-resource cache writes cause AsyncStorage write amplification (`src/remote-resource-cache.mjs`)**: `update()` chains every concurrent mutation into a serial `Promise` chain, causing each mutation in a burst to re-normalize, re-serialize up to 256 KiB, and invoke `storage.setItem` independently instead of coalescing queued mutations per `userId`. +3. **Live schedule event bursts penetrate the 30s schedule-index TTL (`src/schedule-index.mjs`)**: Every `maker:schedule:event` invalidates the per-device cache so rapid event bursts immediately trigger repeated full `maker:schedule:list` + `maker:schedule:list-sidebar-index-runs` RPC pairs, even when events arrive milliseconds apart. +4. **Foreground task activity wakes WidgetKit/ActivityKit on every `running -> running` tick (`src/foreground-task-activity.mjs`)**: Rapid same-status progress updates from multiple desktop hosts immediately flush native widget writes instead of trailing-throttling same-status bursts while preserving immediate delivery for urgent transitions. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with every ordering, canonicalization, concurrency, epoch cancellation, manual-refresh/link-recovery bypass, and urgent-transition invariant defined in `CONTRACT.md`. +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/bench/workload.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/bench/workload.mjs new file mode 100644 index 0000000..5dfcebd --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/bench/workload.mjs @@ -0,0 +1,207 @@ +import { performance } from 'node:perf_hooks'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { SCHEDULE_INDEX_EVENT_COALESCE_MS, createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 2_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +// 1. Mobile Home presentation benchmark: 600 sessions x 30 refreshes +const devices = [ + { deviceId: 'dev-1', name: 'MacBook Pro', state: 'online', canOpen: true }, + { deviceId: 'dev-2', name: 'Mac Studio', state: 'online', canOpen: true }, + { deviceId: 'dev-3', name: 'Linux Workstation', state: 'online', canOpen: true }, + { deviceId: 'dev-4', name: 'Office Mini', state: 'offline', canOpen: false }, +]; +const sessions = []; +const pendingInteractionIndex = new Map(); +for (let i = 0; i < 600; i += 1) { + const dev = devices[i % devices.length]; + const ts = new Date(Date.UTC(2026, 11, 1, 0, 0, 0) + ((i * 7919) % 500_000) * 1000).toISOString(); + sessions.push({ + id: `sess-${i}`, + title: `Task ${i} feature work`, + status: i % 5 === 0 ? 'archived' : 'active', + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: ts, + lastActivityAt: ts, + workingDir: i % 6 === 0 ? null : `/Users/dev/work/project-${i % 18}`, + workspaceKind: i % 6 === 0 ? 'dialogue' : 'project', + pinnedAt: i < 4 ? ts : null, + deviceLinkDeviceId: dev.deviceId, + deviceLinkDeviceName: dev.name, + canonicalDeviceId: dev.deviceId, + preview: `Latest message preview for session ${i}`, + }); + if (i % 19 === 0) pendingInteractionIndex.set(`sess-${i}`, 1); +} + +buildMobileHomePresentation({ devices, sessions, pendingInteractionIndex, statusFilter: 'all' }); +const t0 = performance.now(); +for (let r = 0; r < 30; r += 1) { + buildMobileHomePresentation({ + devices, + sessions, + pendingInteractionIndex, + statusFilter: r % 3 === 0 ? 'all' : 'active', + }); +} +const home30RefreshesMs = Number((performance.now() - t0).toFixed(2)); + +// 2. Remote resource cache burst writes +async function benchCache() { + const disk = new Map(); + let setItemCalls = 0; + let gateRelease = null; + let gateArmed = false; + const storage = { + async getItem(k) { return disk.get(k) ?? null; }, + async setItem(k, v) { + setItemCalls += 1; + disk.set(k, v); + if (gateArmed) { + gateArmed = false; + await new Promise((resolve) => { gateRelease = resolve; }); + } + }, + async removeItem(k) { disk.delete(k); }, + async getAllKeys() { return [...disk.keys()]; }, + }; + const cache = createRemoteResourceCache({ storage }); + const makeItems = (ver) => Array.from({ length: 40 }, (_, i) => ({ + host: { deviceId: `dev-${i % 4}`, name: `Host ${i % 4}` }, + item: { + ref: { collectionId: 'teammates', kind: 'bot', id: `bot-${i}` }, + display: { title: `Bot ${i}`, preview: 'p'.repeat(400), lastReplyAt: ver + i }, + }, + })); + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + setItemCalls = 0; + gateArmed = true; + const burst = [cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(200))]; + await Promise.resolve(); + await Promise.resolve(); + for (let i = 1; i <= 29; i += 1) { + burst.push(cache.markRemoteResourceRead('alice', `dev-${i % 4}`, `bot-${i}`, 300 + i)); + } + gateRelease?.(); + await Promise.all(burst); + return setItemCalls; +} + +// 3. Schedule index burst RPC calls +async function benchSchedule() { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let rpcCalls = 0; + const invoke = async (_dev, ch) => { + rpcCalls += 1; + if (ch === 'maker:schedule:list') return [{ id: 's1', name: 'Sync', status: 'active', targetSessionId: 't1' }]; + return { runs: [] }; + }; + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + const waiters = []; + for (let i = 0; i < 15; i += 1) { + await clock.advanceBy(80); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + waiters.push(store.loadDeviceSessionScheduleIndex('dev-1', invoke)); + } + await clock.advanceBy(SCHEDULE_INDEX_EVENT_COALESCE_MS + 100); + await Promise.all(waiters); + return rpcCalls; +} + +// 4. Foreground task activity widget writes +async function benchActivity() { + const clock = createVirtualClock(); + let writes = 0; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke() { + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Step 0', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const ctrl = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: () => { writes += 1; }, + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await ctrl.ready; + for (let i = 2; i <= 25; i += 1) { + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: i, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: `Step ${i}`, status: 'running' }, + }, clock.now()); + } + await clock.advanceBy(FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + ctrl.dispose(); + return writes; +} + +const storageWrites = await benchCache(); +const scheduleRpcCalls = await benchSchedule(); +const widgetWrites = await benchActivity(); +console.log(JSON.stringify({ home30RefreshesMs, storageWrites, scheduleRpcCalls, widgetWrites }, null, 2)); diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/package.json b/questions/perf-mobile-home-heat/v1/controls/incomplete/package.json new file mode 100644 index 0000000..25908c4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mobile-home-heat", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/src/foreground-task-activity.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/foreground-task-activity.mjs new file mode 100644 index 0000000..ffaf5e4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/foreground-task-activity.mjs @@ -0,0 +1,243 @@ +export const FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS = 2_500; +export const TASK_ACTIVITY_SNAPSHOT = 'maker:task-activity:snapshot'; + +const COMPANION_JPEG_MAX = 2048; +const RANK = { attention: 0, completed: 1, error: 1, running: 2 }; +const listeners = new Set(); + +export function receiveHostTaskActivity(device, value, observedAt) { + for (const listener of listeners) listener(device, value, observedAt); +} + +function parseReport(value) { + if (!value || typeof value !== 'object') return null; + const { schemaVersion, revision, waitingCount, unreadCount, runningCount, selected } = value; + const counts = [waitingCount, unreadCount, runningCount]; + if ( + schemaVersion !== 1 + || !Number.isSafeInteger(revision) + || revision < 1 + || !counts.every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 1_000_000) + ) return null; + if (!waitingCount && !unreadCount && !runningCount) { + return selected === null ? value : null; + } + if ( + !selected + || typeof selected.sessionId !== 'string' + || !selected.sessionId + || selected.sessionId.length > 256 + || typeof selected.title !== 'string' + || [...selected.title].length > 100 + || !Object.hasOwn(RANK, selected.status) + || RANK[selected.status] !== (waitingCount ? 0 : unreadCount ? 1 : 2) + ) return null; + return value; +} + +function parseCompanion(value, status) { + if (status === 'running' || !value || typeof value !== 'object') return undefined; + const { hue, glyph, glyphIsInitial, imageJpeg } = value; + if ( + typeof hue !== 'string' || !/^[a-z]{1,16}$/.test(hue) + || typeof glyph !== 'string' || !glyph || glyph.length > 32 + || typeof glyphIsInitial !== 'boolean' + ) return undefined; + const image = typeof imageJpeg === 'string' + && imageJpeg.length <= COMPANION_JPEG_MAX + && /^[A-Za-z0-9+/]+={0,2}$/.test(imageJpeg) + ? imageJpeg + : undefined; + return { hue, glyph, glyphIsInitial, ...(image ? { imageJpeg: image } : {}) }; +} + +let nextOwner = 0; + +export function startForegroundTaskActivity(source, options) { + const now = options.now ?? Date.now; + const setTimer = options.setTimer ?? setTimeout; + const clearTimer = options.clearTimer ?? clearTimeout; + const minWriteIntervalMs = options.minWriteIntervalMs ?? FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS; + + const owner = 'live-activity-' + ++nextOwner; + let disposed = false; + let devices = []; + const peers = new Map(); + const active = () => !disposed && options.active(); + let previous; + let lastWrittenStatus; + let lastWriteAt = -Infinity; + let coalesceTimer; + + const clearCoalesceTimer = () => { + if (coalesceTimer !== undefined) { + clearTimer(coalesceTimer); + coalesceTimer = undefined; + } + }; + + function publish() { + if (!active() || !peers.size) return; + let observedAt = 0; + let count = 0; + let runningCount = 0; + let attentionCount = 0; + let selected; + for (const [device, peer] of peers) { + if ( + source.getPresenceAvailability(device) === false + || !peer.verified + || !peer.report + || peer.subscription == null + || peer.subscription !== source.getSubscriptionIdentity?.(device, ['sessions']) + ) return; + const { waitingCount, unreadCount, runningCount: running, selected: top } = peer.report; + observedAt = Math.max(observedAt, peer.observedAt); + count += waitingCount + unreadCount + running; + runningCount += running; + attentionCount += waitingCount; + if (top && (!selected || RANK[top.status] < RANK[selected.status])) { + selected = { ...top, device }; + } + } + if (!selected && devices.some((device) => !peers.has(device.deviceId))) return; + const companion = selected ? parseCompanion(selected.companion, selected.status) : undefined; + const state = selected + ? { + status: selected.status, + title: selected.title, + detail: options.labels[selected.status], + count, + runningCount, + attentionCount, + staleDetail: options.staleDetail, + url: options.url(selected.device, selected.sessionId), + ...(companion ? { companion } : {}), + } + : null; + const key = JSON.stringify(state); + if (key === previous) { + clearCoalesceTimer(); + return; + } + const nextStatus = state ? state.status : null; + const urgent = lastWrittenStatus === undefined + || nextStatus === null + || nextStatus === 'attention' + || nextStatus !== lastWrittenStatus; + const elapsed = now() - lastWriteAt; + if (!urgent && elapsed < minWriteIntervalMs) { + if (coalesceTimer === undefined) { + coalesceTimer = setTimer(() => { + coalesceTimer = undefined; + publish(); + }, minWriteIntervalMs - elapsed); + } + return; + } + clearCoalesceTimer(); + previous = key; + lastWrittenStatus = nextStatus; + lastWriteAt = now(); + options.write(state, observedAt); + } + + function receive(device, value, observedAt = now()) { + const peer = peers.get(device); + const identity = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || !peer || identity == null) return; + const report = parseReport(value); + if ( + report + && peer.subscription === identity + && peer.report + && (report.revision < peer.report.revision + || (report.revision === peer.report.revision && observedAt < peer.observedAt)) + ) return; + peer.verified = Boolean(report); + peer.subscription = identity; + peer.report = report; + peer.observedAt = observedAt; + publish(); + } + + let readGeneration = 0; + async function readPeer(device, generation) { + const subscription = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || subscription == null) return; + const current = () => active() + && generation === readGeneration + && subscription === source.getSubscriptionIdentity?.(device, ['sessions']); + const started = now(); + try { + const report = await source.invoke(device, TASK_ACTIVITY_SNAPSHOT, [], { + noResultCache: true, + preSend() { + if (!current()) throw new Error('Foreground activity read superseded'); + }, + }); + if (current()) receive(device, report, started); + } catch { + // Unreachable peer leaves APNs in charge. + } + } + + listeners.add(receive); + const ready = (async () => { + const roster = await source.readDeviceList(); + if (!active() || roster.stale) return; + devices = roster.devices.filter( + (device) => !device.isSelf && ['darwin', 'win32', 'linux'].includes(device.platform ?? ''), + ); + const online = devices + .filter((device) => device.online) + .sort((a, b) => (a.deviceId < b.deviceId ? -1 : 1)); + if (online.some((device) => !device.remoteControlEnabled)) return; + for (const { deviceId } of online) { + peers.set(deviceId, { report: null, subscription: null, observedAt: 0, verified: false }); + } + await Promise.all(online.map(async ({ deviceId }) => { + try { + await source.subscribe(owner, deviceId, ['sessions']); + await readPeer(deviceId, readGeneration); + } catch { + // Ignore unavailable peer. + } + })); + })().catch(() => {}); + + let rechecking = false; + return { + ready, + receive, + async recheck() { + if (!active() || rechecking || !peers.size) return; + rechecking = true; + const generation = ++readGeneration; + clearCoalesceTimer(); + previous = undefined; + lastWrittenStatus = undefined; + for (const peer of peers.values()) peer.verified = false; + try { + await Promise.all([...peers.keys()].map((device) => readPeer(device, generation))); + } finally { + rechecking = false; + } + }, + rosterChanged(device) { + if (!['darwin', 'win32', 'linux'].includes(device.platform)) return false; + const known = devices.find((row) => row.deviceId === device.deviceId); + return known + ? known.online !== device.online || (device.online && known.remoteControlEnabled !== device.remoteControlEnabled) + : device.online; + }, + dispose() { + disposed = true; + clearCoalesceTimer(); + listeners.delete(receive); + for (const device of peers.keys()) { + void source.unsubscribe(owner, device, ['sessions']).catch(() => {}); + } + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/src/mobile-home.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/mobile-home.mjs new file mode 100644 index 0000000..c8c7226 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/mobile-home.mjs @@ -0,0 +1,314 @@ +export const MOBILE_HOME_ALL_DEVICES = 'all'; + +function normalizeDeviceNameKey(value) { + const trimmed = (value ?? '').trim(); + const lower = trimmed.toLowerCase(); + return lower === 'unknown' || lower === 'no' ? '' : trimmed; +} + +export function buildDeviceIdentity(devices, rawIdentities) { + const knownDeviceIds = new Set(); + const deviceIdsByName = new Map(); + for (const device of devices) { + const deviceId = (device.deviceId ?? '').trim(); + if (!deviceId) continue; + knownDeviceIds.add(deviceId); + const name = normalizeDeviceNameKey(device.name); + if (!name) continue; + const ids = deviceIdsByName.get(name) ?? []; + ids.push(deviceId); + deviceIdsByName.set(name, ids); + } + + const staleIdsByName = new Map(); + for (const raw of rawIdentities) { + const deviceId = raw.deviceId?.trim(); + if (!deviceId || knownDeviceIds.has(deviceId)) continue; + const name = normalizeDeviceNameKey(raw.name); + if (!name) continue; + const ids = staleIdsByName.get(name) ?? new Set(); + ids.add(deviceId); + staleIdsByName.set(name, ids); + } + + const uniqueDeviceIdByName = new Map(); + for (const [name, ids] of deviceIdsByName) { + if (ids.length !== 1) continue; + if ((staleIdsByName.get(name)?.size ?? 0) > 1) continue; + uniqueDeviceIdByName.set(name, ids[0]); + } + return { knownDeviceIds, uniqueDeviceIdByName }; +} + +export function resolveCanonicalDeviceId(rawDeviceId, deviceName, identity) { + const raw = rawDeviceId?.trim() ?? ''; + if (raw && !identity.knownDeviceIds.has(raw)) { + const name = normalizeDeviceNameKey(deviceName); + const claimed = name ? identity.uniqueDeviceIdByName.get(name) : undefined; + if (claimed) return claimed; + } + return raw || rawDeviceId; +} + +function canonicalizeSessionDevice(session, identity) { + return { + ...session, + canonicalDeviceId: resolveCanonicalDeviceId(session.deviceLinkDeviceId, session.deviceLinkDeviceName, identity), + }; +} + +function sessionDeviceKey(session) { + return session.canonicalDeviceId ?? session.deviceLinkDeviceId ?? null; +} + +function sessionStatusRank(status) { + if (status === 'active') return 0; + if (status === 'archived') return 1; + return 2; +} + +function lastActivityTime(session) { + return session.lastActivityAt ?? session.userSendAt ?? session.updatedAt ?? session.createdAt ?? ''; +} + +function compareStrings(left, right) { + return new Intl.Collator('en').compare(left, right); +} + +export function compareSessionsByStatusThenActivityDesc(a, b) { + const statusDiff = sessionStatusRank(a.status) - sessionStatusRank(b.status); + if (statusDiff !== 0) return statusDiff; + return compareStrings(lastActivityTime(b), lastActivityTime(a)); +} + +function isDialogueSession(session) { + return session.workspaceKind === 'dialogue' || !session.workingDir; +} + +function isAutomationSession(session, scheduleIndex) { + return session.source === 'scheduler' + || (typeof session.title === 'string' && session.title.startsWith('[Schedule] ')) + || Boolean(scheduleIndex?.get(session.id)); +} + +function normalizeProjectDir(value) { + const trimmed = (value ?? '').trim(); + let end = trimmed.length; + while (end > 0 && (trimmed[end - 1] === '/' || trimmed[end - 1] === '\\')) end -= 1; + const cleaned = end > 0 ? trimmed.slice(0, end) : trimmed; + if (/^[a-z]:[\\/]/i.test(cleaned) || cleaned.includes('\\')) { + return cleaned.replace(/\\/g, '/').toLowerCase(); + } + return cleaned || '__unknown_project__'; +} + +function buildDeviceFilters(devices, sessions, pendingInteractionIndex, selectedDeviceId) { + const nonDeleted = sessions.filter((session) => session.status !== 'deleted'); + const allWaiting = nonDeleted.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + const filters = [ + { + id: MOBILE_HOME_ALL_DEVICES, + deviceId: null, + label: 'All devices', + available: true, + state: 'online', + sessionCount: nonDeleted.length, + waitingCount: allWaiting, + selected: false, + }, + ]; + for (const device of devices) { + const devId = device.deviceId.trim(); + const owned = nonDeleted.filter((session) => sessionDeviceKey(session) === devId); + const waitingCount = owned.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + filters.push({ + id: devId, + deviceId: devId, + label: device.name, + available: Boolean(device.canOpen ?? device.state === 'online'), + state: device.state ?? 'offline', + sessionCount: owned.length, + waitingCount, + selected: false, + }); + } + const normalizedSelected = selectedDeviceId && filters.some((f) => f.deviceId === selectedDeviceId) + ? selectedDeviceId + : null; + return { + normalizedSelectedDeviceId: normalizedSelected, + deviceFilters: filters.map((item) => ({ + ...item, + selected: normalizedSelected === null + ? item.id === MOBILE_HOME_ALL_DEVICES + : item.deviceId === normalizedSelected, + })), + }; +} + +function matchesSelectedDevice(session, selectedDeviceId) { + return !selectedDeviceId || sessionDeviceKey(session) === selectedDeviceId; +} + +function matchesStatusFilter(session, filter, pendingInteractionIndex, scheduleIndex) { + if (filter === 'all') return session.status !== 'deleted'; + if (filter === 'waiting') { + return session.status !== 'deleted' && (pendingInteractionIndex?.get(session.id) ?? 0) > 0; + } + if (filter === 'automation') { + return session.status !== 'deleted' && isAutomationSession(session, scheduleIndex); + } + return session.status === filter; +} + +function matchesSearchQuery(session, query, messagePreviewIndex, pendingInteractionIndex, scheduleIndex) { + if (!query) return true; + const scheduleInfo = scheduleIndex?.get(session.id); + const haystack = [ + session.title, + session.workingDir, + session.model, + session.agentKind, + session.status, + session.deviceLinkDeviceName, + scheduleInfo?.scheduleName, + (pendingInteractionIndex?.get(session.id) ?? 0) > 0 ? 'waiting pending attention' : null, + messagePreviewIndex?.get(session.id) ?? session.preview, + ].filter(Boolean).join(' ').toLowerCase(); + return haystack.includes(query); +} + +function toListItem(session, pendingInteractionIndex, scheduleIndex, messagePreviewIndex) { + const waitingCount = pendingInteractionIndex?.get(session.id) ?? 0; + return { + id: session.id, + title: session.title || 'Untitled session', + status: session.status, + activityAt: lastActivityTime(session), + deviceId: sessionDeviceKey(session), + physicalDeviceId: session.deviceLinkDeviceId ?? null, + workingDir: session.workingDir ?? null, + pinned: Boolean(session.pinnedAt), + waitingCount, + preview: messagePreviewIndex?.get(session.id) ?? session.preview ?? null, + scheduleName: scheduleIndex?.get(session.id)?.scheduleName ?? null, + isDialogue: isDialogueSession(session), + session, + }; +} + +function buildProjectGroups(projectItems) { + const groups = new Map(); + for (const item of projectItems) { + const dirKey = normalizeProjectDir(item.workingDir); + const key = `${item.deviceId ?? ''}::${dirKey}`; + let group = groups.get(key); + if (!group) { + group = { + key, + deviceId: item.deviceId, + workingDir: item.workingDir ?? '__unknown_project__', + latestActivityAt: item.activityAt, + sessionCount: 0, + pendingInteractionCount: 0, + sessions: [], + }; + groups.set(key, group); + } + group.sessions.push(item); + group.sessionCount += 1; + group.pendingInteractionCount += item.waitingCount; + if (compareStrings(item.activityAt, group.latestActivityAt) > 0) { + group.latestActivityAt = item.activityAt; + } + } + return [...groups.values()].sort((a, b) => { + const timeDiff = compareStrings(b.latestActivityAt, a.latestActivityAt); + if (timeDiff !== 0) return timeDiff; + return compareStrings(a.key, b.key); + }); +} + +function summarizeOverview(sessions, projects, pendingInteractionIndex, selectedDeviceId) { + const scoped = sessions.filter( + (session) => session.status !== 'deleted' && matchesSelectedDevice(session, selectedDeviceId), + ); + const chats = scoped.filter(isDialogueSession).length; + const pinned = scoped.filter((session) => Boolean(session.pinnedAt)).length; + const waiting = scoped.filter((session) => (pendingInteractionIndex?.get(session.id) ?? 0) > 0).length; + const devices = new Set(scoped.map((session) => sessionDeviceKey(session)).filter(Boolean)).size; + return { + all: scoped.length, + chats, + devices, + pinned, + projects: projects.length, + waiting, + }; +} + +export function buildMobileHomePresentation({ + devices = [], + sessions = [], + selectedDeviceId = null, + statusFilter = 'active', + searchQuery = '', + inboxMode = false, + pendingInteractionIndex, + scheduleIndex, + messagePreviewIndex, +} = {}) { + const deviceIdentity = buildDeviceIdentity( + devices, + sessions.map((session) => ({ + deviceId: session.deviceLinkDeviceId, + name: session.deviceLinkDeviceName, + })), + ); + const normalizedSessions = sessions.map((session) => canonicalizeSessionDevice(session, deviceIdentity)); + const { deviceFilters, normalizedSelectedDeviceId } = buildDeviceFilters( + devices, + normalizedSessions, + pendingInteractionIndex, + selectedDeviceId, + ); + const query = searchQuery.trim().toLowerCase(); + const filteredSessions = normalizedSessions + .filter((session) => matchesSelectedDevice(session, normalizedSelectedDeviceId)) + .filter((session) => matchesStatusFilter(session, statusFilter, pendingInteractionIndex, scheduleIndex)) + .filter((session) => matchesSearchQuery( + session, + query, + messagePreviewIndex, + pendingInteractionIndex, + scheduleIndex, + )) + .sort(compareSessionsByStatusThenActivityDesc); + + const items = filteredSessions.map((session) => toListItem( + session, + pendingInteractionIndex, + scheduleIndex, + messagePreviewIndex, + )); + const pinned = items.filter((item) => item.pinned); + const groupedItems = inboxMode ? items : items.filter((item) => !item.pinned); + const chats = groupedItems.filter((item) => item.isDialogue); + const projects = buildProjectGroups(groupedItems.filter((item) => !item.isDialogue)); + const overview = summarizeOverview( + normalizedSessions, + projects, + pendingInteractionIndex, + normalizedSelectedDeviceId, + ); + + return { + chats, + deviceFilters, + items, + overview, + pinned, + projects, + selectedDeviceId: normalizedSelectedDeviceId, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/src/remote-resource-cache.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/remote-resource-cache.mjs new file mode 100644 index 0000000..424e2f8 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/remote-resource-cache.mjs @@ -0,0 +1,252 @@ +export const CACHE_STORAGE_PREFIX = 'cindy.remoteResources.v1.'; +export const MAX_DISK_CHARS = 256 * 1024; + +const emptySnapshot = () => ({ home: [], items: {}, read: {}, readSequences: {} }); +const validSequence = (value) => typeof value === 'string' && /^\d{1,30}$/.test(value); + +export const remoteResourceReadKey = (deviceId, resourceId) => JSON.stringify([deviceId, resourceId]); + +function normalize(raw) { + const out = emptySnapshot(); + if (!raw || typeof raw !== 'object') return out; + if (Array.isArray(raw.home)) { + for (const row of raw.home.slice(0, 32)) { + if (!row || typeof row.id !== 'string' || row.id.length > 160 || typeof row.title !== 'string') continue; + out.home.push({ + id: row.id, + title: row.title.slice(0, 512), + resourceKind: typeof row.resourceKind === 'string' ? row.resourceKind.slice(0, 160) : 'collection', + targets: Array.isArray(row.targets) ? row.targets.map((t) => ({ deviceId: String(t.deviceId), name: String(t.name ?? '') })) : [], + }); + } + } + if (raw.items && typeof raw.items === 'object') { + for (const [id, rows] of Object.entries(raw.items).slice(0, 32)) { + if (id.length > 160 || !Array.isArray(rows)) continue; + out.items[id] = rows.slice(0, 200).flatMap((row) => { + if (!row || !row.host || !row.item || !row.item.ref) return []; + const host = { deviceId: String(row.host.deviceId), name: String(row.host.name ?? '') }; + const ref = { + collectionId: String(row.item.ref.collectionId ?? id), + kind: String(row.item.ref.kind ?? 'bot'), + id: String(row.item.ref.id), + }; + const display = { + title: String(row.item.display?.title ?? ''), + preview: typeof row.item.display?.preview === 'string' ? row.item.display.preview.slice(0, 4096) : '', + ...(typeof row.item.display?.avatar === 'string' ? { avatar: row.item.display.avatar } : {}), + ...(typeof row.item.display?.lastReplyAt === 'number' ? { lastReplyAt: row.item.display.lastReplyAt } : {}), + ...(typeof row.item.display?.lastReadAt === 'number' ? { lastReadAt: row.item.display.lastReadAt } : {}), + }; + return [{ + host, + item: { ref, display }, + key: JSON.stringify([host.deviceId, ref.collectionId, ref.kind, ref.id]), + }]; + }); + } + } + if (raw.read && typeof raw.read === 'object') { + for (const [key, at] of Object.entries(raw.read).slice(-2000)) { + if (key.length <= 600 && typeof at === 'number' && Number.isFinite(at) && at >= 0) out.read[key] = at; + } + } + if (raw.readSequences && typeof raw.readSequences === 'object') { + for (const [key, seq] of Object.entries(raw.readSequences).slice(-2000)) { + if (key.length <= 600 && validSequence(seq)) out.readSequences[key] = seq; + } + } + return out; +} + +function diskSnapshot(raw) { + if (raw.length <= MAX_DISK_CHARS) return raw; + const copy = JSON.parse(raw); + let remaining = raw.length - MAX_DISK_CHARS; + for (const rows of Object.values(copy.items)) { + for (const row of rows) { + if (remaining <= 0) break; + const avatar = row.item?.display?.avatar; + if (typeof avatar === 'string' && avatar.length > 0) { + remaining -= avatar.length + 12; + delete row.item.display.avatar; + } + } + } + for (const rows of Object.values(copy.items)) { + while (remaining > 0 && rows.length > 0) { + remaining -= JSON.stringify(rows.pop()).length + 1; + } + } + for (const map of [copy.read, copy.readSequences ?? {}]) { + for (const key of Object.keys(map)) { + if (remaining <= 0) break; + remaining -= JSON.stringify(key).length + JSON.stringify(map[key]).length + 2; + delete map[key]; + } + } + while (remaining > 0 && copy.home.length > 0) { + remaining -= JSON.stringify(copy.home.pop()).length + 1; + } + return JSON.stringify(copy); +} + +export function createRemoteResourceCache({ storage }) { + let epoch = 0; + let revision = 0; + const writeQueues = new Map(); + const snapshots = new Map(); + const unsaved = new Set(); + const listeners = new Set(); + + const emit = () => { + revision += 1; + for (const fn of listeners) fn(); + }; + + async function readRemoteResourceSnapshot(userId) { + if (!userId) return emptySnapshot(); + const cached = snapshots.get(userId); + if (cached) return cached; + const expected = epoch; + const raw = await storage.getItem(CACHE_STORAGE_PREFIX + userId).catch(() => null); + let parsed = emptySnapshot(); + if (typeof raw === 'string' && raw.length > 0) { + try { + parsed = normalize(JSON.parse(raw)); + } catch { + parsed = emptySnapshot(); + } + } + if (expected === epoch) snapshots.set(userId, parsed); + return parsed; + } + + async function drainWriteQueue(userId, queue) { + try { + while (queue.pending.length > 0) { + const firstBatch = queue.pending.splice(0); + const valid = firstBatch.filter((item) => { + if (item.expected !== epoch) { + item.resolve(); + return false; + } + return true; + }); + if (valid.length === 0) continue; + const expected = valid[0].expected; + const snapshot = await readRemoteResourceSnapshot(userId); + // Coalesce any additional mutations that arrived while disk hydration was in flight. + while (queue.pending.length > 0 && queue.pending[0].expected === expected) { + valid.push(queue.pending.shift()); + } + if (expected !== epoch) { + for (const item of valid) item.resolve(); + continue; + } + const before = JSON.stringify(snapshot); + for (const item of valid) item.change(snapshot); + const cleaned = normalize(snapshot); + const raw = JSON.stringify(cleaned); + snapshots.set(userId, cleaned); + if (raw !== before || unsaved.has(userId)) { + if (raw !== before) emit(); + const saved = await storage + .setItem(CACHE_STORAGE_PREFIX + userId, diskSnapshot(raw)) + .then(() => true, () => false); + if (expected !== epoch) { + await storage.removeItem(CACHE_STORAGE_PREFIX + userId).catch(() => undefined); + for (const item of valid) item.resolve(); + continue; + } + if (saved) unsaved.delete(userId); + else unsaved.add(userId); + } + for (const item of valid) item.resolve(); + } + } finally { + for (const item of queue.pending.splice(0)) item.resolve(); + if (writeQueues.get(userId) === queue) writeQueues.delete(userId); + } + } + + function update(userId, change) { + if (!userId) return Promise.resolve(); + const expected = epoch; + return new Promise((resolve) => { + let queue = writeQueues.get(userId); + if (!queue) { + const pending = [{ expected, change, resolve }]; + const created = { pending, running: Promise.resolve() }; + writeQueues.set(userId, created); + created.running = drainWriteQueue(userId, created); + queue = created; + } else { + queue.pending.push({ expected, change, resolve }); + } + }); + } + + return { + readRemoteResourceSnapshot, + cacheRemoteResourceHome(userId, home) { + return update(userId, (s) => { s.home = home; }); + }, + cacheRemoteResourceItems(userId, collectionId, items) { + return update(userId, (s) => { + s.items[collectionId] = items; + for (const row of items) { + const key = remoteResourceReadKey(row.host.deviceId, row.item.ref.id); + if ((row.item.ref.kind === 'bot' || row.item.ref.kind === 'bot-group') && s.read[key] === undefined) { + s.read[key] = row.item.display?.lastReplyAt ?? 0; + } + const hostRead = row.item.display?.lastReadAt; + if (typeof hostRead === 'number' && hostRead > (s.read[key] ?? 0)) { + s.read[key] = hostRead; + } + } + }); + }, + markRemoteResourceRead(userId, deviceId, resourceId, at, sequence) { + return update(userId, (s) => { + const key = remoteResourceReadKey(deviceId, resourceId); + if (Number.isFinite(at) && at >= 0) { + s.read[key] = Math.max(s.read[key] ?? 0, at); + } + if (validSequence(sequence)) { + s.readSequences ??= {}; + if (s.readSequences[key] === undefined || BigInt(sequence) > BigInt(s.readSequences[key])) { + s.readSequences[key] = sequence; + } + } + }); + }, + isRemoteResourceUnread(userId, deviceId, resourceId, lastReplyAt) { + if (!userId || typeof lastReplyAt !== 'number' || lastReplyAt <= 0) return false; + const snapshot = snapshots.get(userId); + if (!snapshot) return false; + const readAt = snapshot.read[remoteResourceReadKey(deviceId, resourceId)] ?? 0; + return lastReplyAt > readAt; + }, + async clearRemoteResourceCache() { + epoch += 1; + snapshots.clear(); + unsaved.clear(); + emit(); + await Promise.allSettled([...writeQueues.values()].map((q) => q.running)); + const keys = await storage.getAllKeys().catch(() => []); + for (const key of keys) { + if (key.startsWith(CACHE_STORAGE_PREFIX)) { + await storage.removeItem(key).catch(() => undefined); + } + } + }, + subscribeRemoteResourceCache(fn) { + listeners.add(fn); + return () => { listeners.delete(fn); }; + }, + remoteResourceCacheRevision() { + return revision; + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/src/schedule-index.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/schedule-index.mjs new file mode 100644 index 0000000..e7d5142 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/src/schedule-index.mjs @@ -0,0 +1,196 @@ +export const SCHEDULE_INDEX_TTL_MS = 30_000; +export const SCHEDULE_INDEX_EVENT_COALESCE_MS = 1_500; + +function buildIndexMap(schedules, runsPayload) { + const runsBySchedule = new Map(); + const runs = Array.isArray(runsPayload?.runs) ? runsPayload.runs : []; + for (const run of runs) { + if (!run || typeof run.scheduleId !== 'string') continue; + let bucket = runsBySchedule.get(run.scheduleId); + if (!bucket) { + bucket = []; + runsBySchedule.set(run.scheduleId, bucket); + } + bucket.push(run); + } + const index = new Map(); + for (const schedule of Array.isArray(schedules) ? schedules : []) { + if (!schedule || !schedule.targetSessionId) continue; + const schedRuns = runsBySchedule.get(schedule.id) ?? []; + let latestRunAt = 0; + let running = false; + let hasUnreadFailedRun = false; + const unreadRunIds = []; + for (const r of schedRuns) { + if (typeof r.startedAt === 'number' && r.startedAt > latestRunAt) latestRunAt = r.startedAt; + if (r.status === 'running') running = true; + if (r.unread) { + unreadRunIds.push(r.id); + if (r.status === 'failed') hasUnreadFailedRun = true; + } + } + index.set(schedule.targetSessionId, { + scheduleId: schedule.id, + scheduleName: schedule.name ?? 'Automation', + status: schedule.status ?? 'active', + latestRunAt, + running, + unreadCount: unreadRunIds.length, + unreadRunIds, + hasUnreadFailedRun, + }); + } + return index; +} + +export function createScheduleIndexStore({ + now = Date.now, + setTimer = setTimeout, + clearTimer = clearTimeout, + ttlMs = SCHEDULE_INDEX_TTL_MS, + coalesceMs = SCHEDULE_INDEX_EVENT_COALESCE_MS, +} = {}) { + // Keep injected timer references available for event coalescing implementations. + void setTimer; + void clearTimer; + void coalesceMs; + + let cacheGeneration = 0; + const throttleEntries = new Map(); + const invalidationVersions = new Map(); + const boundSessionsByDevice = new Map(); + + function getScheduleIndexInvalidationVersion(deviceId) { + return invalidationVersions.get(deviceId) ?? 0; + } + + function invalidateScheduleIndexForDevice(deviceId) { + if (!deviceId) return; + const entry = throttleEntries.get(deviceId); + if (entry?.pending) entry.invalidated = true; + else throttleEntries.delete(deviceId); + invalidationVersions.set(deviceId, getScheduleIndexInvalidationVersion(deviceId) + 1); + } + + function invalidateScheduleIndexesAfterLinkRecovery(deviceId) { + const keys = deviceId === undefined ? [...throttleEntries.keys()] : [deviceId]; + for (const key of keys) { + const entry = throttleEntries.get(key); + if (!entry || entry.failedAt === null || entry.failedTransient) { + invalidateScheduleIndexForDevice(key); + } + } + } + + function noteScheduleEventInIndexCache(deviceId, change) { + if (!deviceId) return; + const known = boundSessionsByDevice.get(deviceId); + const wasCurrent = known !== undefined + && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + if (change.invalidate) invalidateScheduleIndexForDevice(deviceId); + if (!known) return; + if (!wasCurrent || change.scheduleListChanged) { + boundSessionsByDevice.delete(deviceId); + return; + } + boundSessionsByDevice.set(deviceId, { + sessionIds: change.sessionId && !known.sessionIds.has(change.sessionId) + ? new Set([...known.sessionIds, change.sessionId]) + : known.sessionIds, + failedScheduleIds: known.failedScheduleIds, + invalidationVersion: getScheduleIndexInvalidationVersion(deviceId), + }); + } + + function hasCurrentScheduleIndexRecord(deviceId) { + if (!deviceId) return false; + const known = boundSessionsByDevice.get(deviceId); + return known !== undefined && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + } + + function sessionMayHaveScheduleRuns(deviceId, sessionId, source) { + if (source === 'scheduler') return true; + const known = boundSessionsByDevice.get(deviceId); + if (!known || known.invalidationVersion !== getScheduleIndexInvalidationVersion(deviceId)) return true; + return known.sessionIds.has(sessionId); + } + + function clearSessionScheduleIndexCache() { + cacheGeneration += 1; + throttleEntries.clear(); + invalidationVersions.clear(); + boundSessionsByDevice.clear(); + } + + function loadSharedSessionScheduleIndex(deviceId, invoke, canStart = () => true) { + const existing = throttleEntries.get(deviceId); + const currentNow = now(); + if (existing) { + if (existing.pending) return existing.pending; + if (!existing.invalidated && existing.value && (currentNow - existing.loadedAt) < ttlMs) { + return Promise.resolve(existing.value); + } + } + if (!canStart()) return Promise.reject(new Error('Schedule index consumer inactive')); + + const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId); + const gen = cacheGeneration; + const entry = { + pending: null, + value: null, + loadedAt: 0, + invalidated: false, + failedAt: null, + failedTransient: false, + }; + const promise = Promise.all([ + invoke(deviceId, 'maker:schedule:list', [null, { summaryOnly: true }]), + invoke(deviceId, 'maker:schedule:list-sidebar-index-runs', []), + ]).then(([schedules, runsPayload]) => { + const index = buildIndexMap(schedules, runsPayload); + entry.pending = null; + if (gen === cacheGeneration && !entry.invalidated && throttleEntries.get(deviceId) === entry) { + entry.value = index; + entry.loadedAt = now(); + const failedScheduleIds = new Set(); + for (const info of index.values()) { + if (info.hasUnreadFailedRun) failedScheduleIds.add(info.scheduleId); + } + boundSessionsByDevice.set(deviceId, { + sessionIds: new Set(index.keys()), + failedScheduleIds, + invalidationVersion, + }); + } else if (throttleEntries.get(deviceId) === entry) { + throttleEntries.delete(deviceId); + } + return index; + }, (error) => { + entry.pending = null; + if (throttleEntries.get(deviceId) === entry) { + entry.failedAt = now(); + entry.failedTransient = error?.code === 'LOCAL_LINK_DOWN'; + if (entry.invalidated) throttleEntries.delete(deviceId); + } + throw error; + }); + entry.pending = promise; + throttleEntries.set(deviceId, entry); + return promise; + } + + function loadDeviceSessionScheduleIndex(deviceId, invoke, canStart) { + return loadSharedSessionScheduleIndex(deviceId, invoke, canStart); + } + + return { + loadDeviceSessionScheduleIndex, + noteScheduleEventInIndexCache, + invalidateScheduleIndexForDevice, + invalidateScheduleIndexesAfterLinkRecovery, + getScheduleIndexInvalidationVersion, + hasCurrentScheduleIndexRecord, + sessionMayHaveScheduleRuns, + clearSessionScheduleIndexCache, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/controls/incomplete/tests/smoke.test.mjs b/questions/perf-mobile-home-heat/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..95f8338 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,181 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + TASK_ACTIVITY_SNAPSHOT, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 1_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +function createMemoryStorage() { + const map = new Map(); + return { + map, + writes: 0, + async getItem(k) { return map.get(k) ?? null; }, + async setItem(k, v) { this.writes += 1; map.set(k, v); }, + async removeItem(k) { map.delete(k); }, + async getAllKeys() { return [...map.keys()]; }, + }; +} + +test('buildMobileHomePresentation canonicalizes stale devices and sorts active before archived', () => { + const devices = [ + { deviceId: 'dev-mac', name: 'Studio Mac', state: 'online', canOpen: true }, + { deviceId: 'dev-linux', name: 'Build Box', state: 'online', canOpen: true }, + ]; + const sessions = [ + { + id: 's-arch', + title: 'Old Task', + status: 'archived', + createdAt: '2026-12-01T10:00:00.000Z', + updatedAt: '2026-12-04T10:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + { + id: 's-stale', + title: 'Relinked Task', + status: 'active', + createdAt: '2026-12-01T10:00:00.000Z', + lastActivityAt: '2026-12-04T12:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-old-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + ]; + const res = buildMobileHomePresentation({ devices, sessions, statusFilter: 'all' }); + assert.deepEqual(res.items.map((i) => i.id), ['s-stale', 's-arch']); + assert.equal(res.items[0].deviceId, 'dev-mac'); + assert.equal(res.items[0].physicalDeviceId, 'dev-old-mac'); + assert.equal(res.projects.length, 1); + assert.equal(res.projects[0].sessionCount, 2); +}); + +test('remoteResourceCache persists mutations and stays silent on no-ops', async () => { + const storage = createMemoryStorage(); + const cache = createRemoteResourceCache({ storage }); + const row = (replyAt) => [{ + host: { deviceId: 'dev-1', name: 'Mac' }, + item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt: replyAt } }, + }]; + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + const writesAfterSeed = storage.writes; + const revAfterSeed = cache.remoteResourceCacheRevision(); + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + assert.equal(storage.writes, writesAfterSeed); + assert.equal(cache.remoteResourceCacheRevision(), revAfterSeed); + await cache.markRemoteResourceRead('alice', 'dev-1', 'writer', 200); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 150), false); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 250), true); +}); + +test('scheduleIndex caches within TTL and reloads after invalidation', async () => { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let calls = 0; + const invoke = async (_dev, channel) => { + calls += 1; + if (channel === 'maker:schedule:list') return [{ id: 'sc-1', name: 'Nightly', status: 'active', targetSessionId: 'task-1' }]; + return { runs: [{ id: 'r-1', scheduleId: 'sc-1', startedAt: 500, status: 'completed', unread: true }] }; + }; + const first = await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(first.get('task-1')?.scheduleName, 'Nightly'); + assert.equal(calls, 2); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 2); + store.invalidateScheduleIndexForDevice('dev-1'); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 4); +}); + +test('foregroundTaskActivity publishes initial snapshot and urgent endings immediately', async () => { + const clock = createVirtualClock(); + const written = []; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke(_dev, channel) { + assert.equal(channel, TASK_ACTIVITY_SNAPSHOT); + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Building app', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const controller = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: (state, observedAt) => written.push({ state, observedAt }), + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await controller.ready; + assert.equal(written.length, 1); + assert.equal(written[0].state?.status, 'running'); + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: 2, + waitingCount: 0, + unreadCount: 0, + runningCount: 0, + selected: null, + }, clock.now()); + assert.equal(written.at(-1)?.state, null); + controller.dispose(); +}); diff --git a/questions/perf-mobile-home-heat/v1/question.json b/questions/perf-mobile-home-heat/v1/question.json new file mode 100644 index 0000000..1e41255 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/question.json @@ -0,0 +1,101 @@ +{ + "id": "perf-mobile-home-heat", + "revision": "v1", + "scoringVersion": "metric-v1", + "title": "移动端首页高频推送、全量排序与缓存落盘热路径性能优化", + "status": "calibrated", + "changeNote": "Eval Bank v2 quantitative performance question extracted from makecindy/cindy PR #15544 (3a8ae6d6cdf5).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "3a8ae6d6cdf55432f6f99852075a99af19abcfd6", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "home_presentation", + "weight": "2/5", + "mode": "metric", + "gate": [ + "correctness_home", + "correctness_cache", + "correctness_schedule", + "correctness_activity" + ], + "metric": { + "id": "home_sort_speedup", + "label": "Home presentation speedup", + "unit": "×", + "direction": "higher", + "baseline": 1.5, + "target": 50, + "scale": "log" + } + }, + { + "id": "cache_writes", + "weight": "1/5", + "mode": "metric", + "gate": [ + "correctness_home", + "correctness_cache", + "correctness_schedule", + "correctness_activity" + ], + "metric": { + "id": "storage_writes", + "label": "Coalesced storage writes", + "unit": "writes", + "direction": "lower", + "baseline": 45, + "target": 6, + "scale": "log" + } + }, + { + "id": "schedule_rpc", + "weight": "1/5", + "mode": "metric", + "gate": [ + "correctness_home", + "correctness_cache", + "correctness_schedule", + "correctness_activity" + ], + "metric": { + "id": "schedule_rpc_calls", + "label": "Schedule index RPC calls", + "unit": "calls", + "direction": "lower", + "baseline": 75, + "target": 16, + "scale": "log" + } + }, + { + "id": "widget_activity", + "weight": "1/5", + "mode": "metric", + "gate": [ + "correctness_home", + "correctness_cache", + "correctness_schedule", + "correctness_activity" + ], + "metric": { + "id": "widget_writes", + "label": "Foreground widget writes", + "unit": "writes", + "direction": "lower", + "baseline": 36, + "target": 9, + "scale": "log" + } + } + ] +} diff --git a/questions/perf-mobile-home-heat/v1/reference/CONTRACT.md b/questions/perf-mobile-home-heat/v1/reference/CONTRACT.md new file mode 100644 index 0000000..c8a493a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/CONTRACT.md @@ -0,0 +1,50 @@ +# Product & Runtime Contract + +## 1. Mobile Home Presentation (`src/mobile-home.mjs`) + +- Exports `MOBILE_HOME_ALL_DEVICES` (`'all'`), `buildDeviceIdentity`, `resolveCanonicalDeviceId`, `compareSessionsByStatusThenActivityDesc`, and `buildMobileHomePresentation`. +- Device identity canonicalization: + - Known device IDs (trimmed non-empty `device.deviceId` from `devices`) remain unchanged. + - Unknown (stale) session `deviceLinkDeviceId` values whose `deviceLinkDeviceName` uniquely matches exactly one current device (and has no conflicting stale device IDs sharing the same name) are claimed to that device's canonical `deviceId`. + - Placeholder names (`'unknown'`, `'no'`, case-insensitive) never participate in name-based claiming. + - Canonicalization sets `canonicalDeviceId` without ever mutating `deviceLinkDeviceId`. +- Filtering & sorting parity: + - Filters by `selectedDeviceId` (normalized against available device filters), `statusFilter` (`'active' | 'archived' | 'waiting' | 'automation' | 'all'`), and case-insensitive `searchQuery`. + - Sorts matched sessions by status rank (`active` < `archived` < others) and then descending by `lastActivityAt ?? userSendAt ?? updatedAt ?? createdAt`. + - Output (`items`, `pinned`, `chats`, `projects`, `deviceFilters`, `overview`, `selectedDeviceId`) must match baseline semantics exactly for all inputs. + +## 2. Remote Resource Cache (`src/remote-resource-cache.mjs`) + +- Exports `CACHE_STORAGE_PREFIX` (`'cindy.remoteResources.v1.'`), `MAX_DISK_CHARS` (`256 * 1024`), `remoteResourceReadKey`, and `createRemoteResourceCache({ storage })`. +- Returned cache API: `readRemoteResourceSnapshot`, `cacheRemoteResourceHome`, `cacheRemoteResourceItems`, `markRemoteResourceRead`, `isRemoteResourceUnread`, `clearRemoteResourceCache`, `subscribeRemoteResourceCache`, `remoteResourceCacheRevision`. +- Concurrency & coalescing invariants: + - Concurrent updates for the same `userId` must apply every mutation in submission order and never drop the latest mutation. + - Queued mutations waiting behind an in-flight hydration or disk write should coalesce into a single trailing persist instead of issuing one `storage.setItem` per call. + - Unchanged snapshots (when `unsaved` is not set for that `userId`) stay completely silent: no `storage.setItem` and no subscriber emission. + - If `storage.setItem` rejects, that `userId` is marked unsaved so the next update retries disk persistence even if snapshot contents are unchanged. + - `clearRemoteResourceCache()` advances the internal epoch, clears memory, emits, awaits in-flight writes, and deletes all `CACHE_STORAGE_PREFIX` keys; stale pre-clear writes must never resurrect data in memory or storage. + - Persisted JSON is bounded to `MAX_DISK_CHARS`. + +## 3. Device Schedule Index (`src/schedule-index.mjs`) + +- Exports `SCHEDULE_INDEX_TTL_MS` (`30_000`), `SCHEDULE_INDEX_EVENT_COALESCE_MS` (`1_500`), and `createScheduleIndexStore({ now?, setTimer?, clearTimer?, ttlMs?, coalesceMs? })`. +- Returned store API: `loadDeviceSessionScheduleIndex`, `noteScheduleEventInIndexCache`, `invalidateScheduleIndexForDevice`, `invalidateScheduleIndexesAfterLinkRecovery`, `getScheduleIndexInvalidationVersion`, `hasCurrentScheduleIndexRecord`, `sessionMayHaveScheduleRuns`, `clearSessionScheduleIndexCache`. +- Freshness & coalescing invariants: + - Uses injected `now`, `setTimer`, `clearTimer` exclusively (no un-injected global wall-clock/timer assumptions). + - First load for a device is always immediate. + - Within `ttlMs` without invalidation, cached results are returned without issuing RPCs; concurrent in-flight loads for the same device share one request. + - Rapid live-event invalidations (`noteScheduleEventInIndexCache(deviceId, { invalidate: true, ... })` followed by `loadDeviceSessionScheduleIndex`) within `coalesceMs` (`1500ms`) of the previous load coalesce per device into a single trailing refresh, sharing one Promise across callers and using the latest `invoke` and `canStart`. + - **Bypass boundaries**: direct manual refresh (`invalidateScheduleIndexForDevice(deviceId)`) and link recovery (`invalidateScheduleIndexesAfterLinkRecovery(deviceId?)`) clear the event-coalesce marker so the following load executes immediately without waiting for `coalesceMs`. + - `clearSessionScheduleIndexCache()` cancels any pending coalesce timers, settles (rejects) any pending coalesced load promises, and resets all state. + +## 4. Foreground Task Activity (`src/foreground-task-activity.mjs`) + +- Exports `FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS` (`2_500`), `TASK_ACTIVITY_SNAPSHOT`, `receiveHostTaskActivity`, and `startForegroundTaskActivity(source, options)`. +- `options` accepts `{ active, labels, staleDetail, url, write, now?, setTimer?, clearTimer?, minWriteIntervalMs? }`. +- Uses injected `now`, `setTimer`, `clearTimer` exclusively. +- Aggregates verified host reports across online desktop peers (`darwin`, `win32`, `linux`), ranking `attention` > `completed`/`error` > `running`, rejecting out-of-order older revisions, and suppressing identical serialized payloads. +- Trailing throttle & urgency invariants: + - Rapid same-status non-urgent updates (e.g. `running -> running`) within `minWriteIntervalMs` (`2500ms`) of the last write coalesce onto one trailing write emitting the latest state. + - Urgent transitions — initial write, ending (`state === null`), `attention`, and any status transition (`nextStatus !== lastWrittenStatus`) — cancel any pending coalesce timer and write **immediately**. + - If the aggregated state returns to the previously written snapshot before a pending coalesce timer fires, the pending timer is cleared and no redundant write occurs. + - `recheck()` clears any pending timer and resets `previous` / `lastWrittenStatus` before re-reading peers; `dispose()` clears any pending timer and unsubscribes. diff --git a/questions/perf-mobile-home-heat/v1/reference/ENVIRONMENT.md b/questions/perf-mobile-home-heat/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..29b467a --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/ENVIRONMENT.md @@ -0,0 +1,8 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows). +- Virtual time: Time-sensitive modules accept injected `{ now, setTimer, clearTimer }` so tests and benchmarks run deterministically without real multi-second sleeps. +- Public checks: + - `npm test` — functional smoke tests covering all four modules + - `npm run bench` — representative workload reporting home presentation timing, coalesced storage writes, schedule RPC calls, and widget writes diff --git a/questions/perf-mobile-home-heat/v1/reference/TASK.md b/questions/perf-mobile-home-heat/v1/reference/TASK.md new file mode 100644 index 0000000..225d34e --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/TASK.md @@ -0,0 +1,19 @@ +# Task + +You are optimizing four performance hotspots extracted from Cindy's mobile Home screen and live-activity pipeline that caused sustained device overheating, high CPU usage, disk write amplification, and ActivityKit/WidgetKit wake storms. + +## Observed Production Symptoms + +1. **Mobile Home presentation churns CPU and GC on every refresh (`src/mobile-home.mjs`)**: `buildMobileHomePresentation` re-maps every session into device identity inputs, clones every session object even when `canonicalDeviceId` is already canonical, performs repeated `.filter()` / `O(D × N)` passes, and runs uncached locale/sort-key computations inside `O(N log N)` sorting. +2. **Concurrent remote-resource cache writes cause AsyncStorage write amplification (`src/remote-resource-cache.mjs`)**: `update()` chains every concurrent mutation into a serial `Promise` chain, causing each mutation in a burst to re-normalize, re-serialize up to 256 KiB, and invoke `storage.setItem` independently instead of coalescing queued mutations per `userId`. +3. **Live schedule event bursts penetrate the 30s schedule-index TTL (`src/schedule-index.mjs`)**: Every `maker:schedule:event` invalidates the per-device cache so rapid event bursts immediately trigger repeated full `maker:schedule:list` + `maker:schedule:list-sidebar-index-runs` RPC pairs, even when events arrive milliseconds apart. +4. **Foreground task activity wakes WidgetKit/ActivityKit on every `running -> running` tick (`src/foreground-task-activity.mjs`)**: Rapid same-status progress updates from multiple desktop hosts immediately flush native widget writes instead of trailing-throttling same-status bursts while preserving immediate delivery for urgent transitions. + +## Requirements + +- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes. +- Preserve **100% behavioral compatibility** with every ordering, canonicalization, concurrency, epoch cancellation, manual-refresh/link-recovery bypass, and urgent-transition invariant defined in `CONTRACT.md`. +- Run `npm test` and `npm run bench` to verify correctness and measure before/after performance. +- Summarize your findings, changes, and before/after measurements in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、运行环境和题面。 diff --git a/questions/perf-mobile-home-heat/v1/reference/bench/workload.mjs b/questions/perf-mobile-home-heat/v1/reference/bench/workload.mjs new file mode 100644 index 0000000..5dfcebd --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/bench/workload.mjs @@ -0,0 +1,207 @@ +import { performance } from 'node:perf_hooks'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { SCHEDULE_INDEX_EVENT_COALESCE_MS, createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 2_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +// 1. Mobile Home presentation benchmark: 600 sessions x 30 refreshes +const devices = [ + { deviceId: 'dev-1', name: 'MacBook Pro', state: 'online', canOpen: true }, + { deviceId: 'dev-2', name: 'Mac Studio', state: 'online', canOpen: true }, + { deviceId: 'dev-3', name: 'Linux Workstation', state: 'online', canOpen: true }, + { deviceId: 'dev-4', name: 'Office Mini', state: 'offline', canOpen: false }, +]; +const sessions = []; +const pendingInteractionIndex = new Map(); +for (let i = 0; i < 600; i += 1) { + const dev = devices[i % devices.length]; + const ts = new Date(Date.UTC(2026, 11, 1, 0, 0, 0) + ((i * 7919) % 500_000) * 1000).toISOString(); + sessions.push({ + id: `sess-${i}`, + title: `Task ${i} feature work`, + status: i % 5 === 0 ? 'archived' : 'active', + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: ts, + lastActivityAt: ts, + workingDir: i % 6 === 0 ? null : `/Users/dev/work/project-${i % 18}`, + workspaceKind: i % 6 === 0 ? 'dialogue' : 'project', + pinnedAt: i < 4 ? ts : null, + deviceLinkDeviceId: dev.deviceId, + deviceLinkDeviceName: dev.name, + canonicalDeviceId: dev.deviceId, + preview: `Latest message preview for session ${i}`, + }); + if (i % 19 === 0) pendingInteractionIndex.set(`sess-${i}`, 1); +} + +buildMobileHomePresentation({ devices, sessions, pendingInteractionIndex, statusFilter: 'all' }); +const t0 = performance.now(); +for (let r = 0; r < 30; r += 1) { + buildMobileHomePresentation({ + devices, + sessions, + pendingInteractionIndex, + statusFilter: r % 3 === 0 ? 'all' : 'active', + }); +} +const home30RefreshesMs = Number((performance.now() - t0).toFixed(2)); + +// 2. Remote resource cache burst writes +async function benchCache() { + const disk = new Map(); + let setItemCalls = 0; + let gateRelease = null; + let gateArmed = false; + const storage = { + async getItem(k) { return disk.get(k) ?? null; }, + async setItem(k, v) { + setItemCalls += 1; + disk.set(k, v); + if (gateArmed) { + gateArmed = false; + await new Promise((resolve) => { gateRelease = resolve; }); + } + }, + async removeItem(k) { disk.delete(k); }, + async getAllKeys() { return [...disk.keys()]; }, + }; + const cache = createRemoteResourceCache({ storage }); + const makeItems = (ver) => Array.from({ length: 40 }, (_, i) => ({ + host: { deviceId: `dev-${i % 4}`, name: `Host ${i % 4}` }, + item: { + ref: { collectionId: 'teammates', kind: 'bot', id: `bot-${i}` }, + display: { title: `Bot ${i}`, preview: 'p'.repeat(400), lastReplyAt: ver + i }, + }, + })); + await cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(100)); + setItemCalls = 0; + gateArmed = true; + const burst = [cache.cacheRemoteResourceItems('alice', 'teammates', makeItems(200))]; + await Promise.resolve(); + await Promise.resolve(); + for (let i = 1; i <= 29; i += 1) { + burst.push(cache.markRemoteResourceRead('alice', `dev-${i % 4}`, `bot-${i}`, 300 + i)); + } + gateRelease?.(); + await Promise.all(burst); + return setItemCalls; +} + +// 3. Schedule index burst RPC calls +async function benchSchedule() { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let rpcCalls = 0; + const invoke = async (_dev, ch) => { + rpcCalls += 1; + if (ch === 'maker:schedule:list') return [{ id: 's1', name: 'Sync', status: 'active', targetSessionId: 't1' }]; + return { runs: [] }; + }; + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + const waiters = []; + for (let i = 0; i < 15; i += 1) { + await clock.advanceBy(80); + store.noteScheduleEventInIndexCache('dev-1', { invalidate: true, sessionId: 't1', scheduleListChanged: false }); + waiters.push(store.loadDeviceSessionScheduleIndex('dev-1', invoke)); + } + await clock.advanceBy(SCHEDULE_INDEX_EVENT_COALESCE_MS + 100); + await Promise.all(waiters); + return rpcCalls; +} + +// 4. Foreground task activity widget writes +async function benchActivity() { + const clock = createVirtualClock(); + let writes = 0; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke() { + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Step 0', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const ctrl = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: () => { writes += 1; }, + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await ctrl.ready; + for (let i = 2; i <= 25; i += 1) { + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: i, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: `Step ${i}`, status: 'running' }, + }, clock.now()); + } + await clock.advanceBy(FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS + 100); + ctrl.dispose(); + return writes; +} + +const storageWrites = await benchCache(); +const scheduleRpcCalls = await benchSchedule(); +const widgetWrites = await benchActivity(); +console.log(JSON.stringify({ home30RefreshesMs, storageWrites, scheduleRpcCalls, widgetWrites }, null, 2)); diff --git a/questions/perf-mobile-home-heat/v1/reference/package.json b/questions/perf-mobile-home-heat/v1/reference/package.json new file mode 100644 index 0000000..25908c4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/package.json @@ -0,0 +1,10 @@ +{ + "name": "cindy-perf-mobile-home-heat", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs", + "bench": "node bench/workload.mjs" + } +} diff --git a/questions/perf-mobile-home-heat/v1/reference/src/foreground-task-activity.mjs b/questions/perf-mobile-home-heat/v1/reference/src/foreground-task-activity.mjs new file mode 100644 index 0000000..ffaf5e4 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/src/foreground-task-activity.mjs @@ -0,0 +1,243 @@ +export const FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS = 2_500; +export const TASK_ACTIVITY_SNAPSHOT = 'maker:task-activity:snapshot'; + +const COMPANION_JPEG_MAX = 2048; +const RANK = { attention: 0, completed: 1, error: 1, running: 2 }; +const listeners = new Set(); + +export function receiveHostTaskActivity(device, value, observedAt) { + for (const listener of listeners) listener(device, value, observedAt); +} + +function parseReport(value) { + if (!value || typeof value !== 'object') return null; + const { schemaVersion, revision, waitingCount, unreadCount, runningCount, selected } = value; + const counts = [waitingCount, unreadCount, runningCount]; + if ( + schemaVersion !== 1 + || !Number.isSafeInteger(revision) + || revision < 1 + || !counts.every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 1_000_000) + ) return null; + if (!waitingCount && !unreadCount && !runningCount) { + return selected === null ? value : null; + } + if ( + !selected + || typeof selected.sessionId !== 'string' + || !selected.sessionId + || selected.sessionId.length > 256 + || typeof selected.title !== 'string' + || [...selected.title].length > 100 + || !Object.hasOwn(RANK, selected.status) + || RANK[selected.status] !== (waitingCount ? 0 : unreadCount ? 1 : 2) + ) return null; + return value; +} + +function parseCompanion(value, status) { + if (status === 'running' || !value || typeof value !== 'object') return undefined; + const { hue, glyph, glyphIsInitial, imageJpeg } = value; + if ( + typeof hue !== 'string' || !/^[a-z]{1,16}$/.test(hue) + || typeof glyph !== 'string' || !glyph || glyph.length > 32 + || typeof glyphIsInitial !== 'boolean' + ) return undefined; + const image = typeof imageJpeg === 'string' + && imageJpeg.length <= COMPANION_JPEG_MAX + && /^[A-Za-z0-9+/]+={0,2}$/.test(imageJpeg) + ? imageJpeg + : undefined; + return { hue, glyph, glyphIsInitial, ...(image ? { imageJpeg: image } : {}) }; +} + +let nextOwner = 0; + +export function startForegroundTaskActivity(source, options) { + const now = options.now ?? Date.now; + const setTimer = options.setTimer ?? setTimeout; + const clearTimer = options.clearTimer ?? clearTimeout; + const minWriteIntervalMs = options.minWriteIntervalMs ?? FOREGROUND_ACTIVITY_MIN_WRITE_INTERVAL_MS; + + const owner = 'live-activity-' + ++nextOwner; + let disposed = false; + let devices = []; + const peers = new Map(); + const active = () => !disposed && options.active(); + let previous; + let lastWrittenStatus; + let lastWriteAt = -Infinity; + let coalesceTimer; + + const clearCoalesceTimer = () => { + if (coalesceTimer !== undefined) { + clearTimer(coalesceTimer); + coalesceTimer = undefined; + } + }; + + function publish() { + if (!active() || !peers.size) return; + let observedAt = 0; + let count = 0; + let runningCount = 0; + let attentionCount = 0; + let selected; + for (const [device, peer] of peers) { + if ( + source.getPresenceAvailability(device) === false + || !peer.verified + || !peer.report + || peer.subscription == null + || peer.subscription !== source.getSubscriptionIdentity?.(device, ['sessions']) + ) return; + const { waitingCount, unreadCount, runningCount: running, selected: top } = peer.report; + observedAt = Math.max(observedAt, peer.observedAt); + count += waitingCount + unreadCount + running; + runningCount += running; + attentionCount += waitingCount; + if (top && (!selected || RANK[top.status] < RANK[selected.status])) { + selected = { ...top, device }; + } + } + if (!selected && devices.some((device) => !peers.has(device.deviceId))) return; + const companion = selected ? parseCompanion(selected.companion, selected.status) : undefined; + const state = selected + ? { + status: selected.status, + title: selected.title, + detail: options.labels[selected.status], + count, + runningCount, + attentionCount, + staleDetail: options.staleDetail, + url: options.url(selected.device, selected.sessionId), + ...(companion ? { companion } : {}), + } + : null; + const key = JSON.stringify(state); + if (key === previous) { + clearCoalesceTimer(); + return; + } + const nextStatus = state ? state.status : null; + const urgent = lastWrittenStatus === undefined + || nextStatus === null + || nextStatus === 'attention' + || nextStatus !== lastWrittenStatus; + const elapsed = now() - lastWriteAt; + if (!urgent && elapsed < minWriteIntervalMs) { + if (coalesceTimer === undefined) { + coalesceTimer = setTimer(() => { + coalesceTimer = undefined; + publish(); + }, minWriteIntervalMs - elapsed); + } + return; + } + clearCoalesceTimer(); + previous = key; + lastWrittenStatus = nextStatus; + lastWriteAt = now(); + options.write(state, observedAt); + } + + function receive(device, value, observedAt = now()) { + const peer = peers.get(device); + const identity = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || !peer || identity == null) return; + const report = parseReport(value); + if ( + report + && peer.subscription === identity + && peer.report + && (report.revision < peer.report.revision + || (report.revision === peer.report.revision && observedAt < peer.observedAt)) + ) return; + peer.verified = Boolean(report); + peer.subscription = identity; + peer.report = report; + peer.observedAt = observedAt; + publish(); + } + + let readGeneration = 0; + async function readPeer(device, generation) { + const subscription = source.getSubscriptionIdentity?.(device, ['sessions']); + if (!active() || subscription == null) return; + const current = () => active() + && generation === readGeneration + && subscription === source.getSubscriptionIdentity?.(device, ['sessions']); + const started = now(); + try { + const report = await source.invoke(device, TASK_ACTIVITY_SNAPSHOT, [], { + noResultCache: true, + preSend() { + if (!current()) throw new Error('Foreground activity read superseded'); + }, + }); + if (current()) receive(device, report, started); + } catch { + // Unreachable peer leaves APNs in charge. + } + } + + listeners.add(receive); + const ready = (async () => { + const roster = await source.readDeviceList(); + if (!active() || roster.stale) return; + devices = roster.devices.filter( + (device) => !device.isSelf && ['darwin', 'win32', 'linux'].includes(device.platform ?? ''), + ); + const online = devices + .filter((device) => device.online) + .sort((a, b) => (a.deviceId < b.deviceId ? -1 : 1)); + if (online.some((device) => !device.remoteControlEnabled)) return; + for (const { deviceId } of online) { + peers.set(deviceId, { report: null, subscription: null, observedAt: 0, verified: false }); + } + await Promise.all(online.map(async ({ deviceId }) => { + try { + await source.subscribe(owner, deviceId, ['sessions']); + await readPeer(deviceId, readGeneration); + } catch { + // Ignore unavailable peer. + } + })); + })().catch(() => {}); + + let rechecking = false; + return { + ready, + receive, + async recheck() { + if (!active() || rechecking || !peers.size) return; + rechecking = true; + const generation = ++readGeneration; + clearCoalesceTimer(); + previous = undefined; + lastWrittenStatus = undefined; + for (const peer of peers.values()) peer.verified = false; + try { + await Promise.all([...peers.keys()].map((device) => readPeer(device, generation))); + } finally { + rechecking = false; + } + }, + rosterChanged(device) { + if (!['darwin', 'win32', 'linux'].includes(device.platform)) return false; + const known = devices.find((row) => row.deviceId === device.deviceId); + return known + ? known.online !== device.online || (device.online && known.remoteControlEnabled !== device.remoteControlEnabled) + : device.online; + }, + dispose() { + disposed = true; + clearCoalesceTimer(); + listeners.delete(receive); + for (const device of peers.keys()) { + void source.unsubscribe(owner, device, ['sessions']).catch(() => {}); + } + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/reference/src/mobile-home.mjs b/questions/perf-mobile-home-heat/v1/reference/src/mobile-home.mjs new file mode 100644 index 0000000..9296466 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/src/mobile-home.mjs @@ -0,0 +1,408 @@ +export const MOBILE_HOME_ALL_DEVICES = 'all'; + +let cachedCollator; +const ISO_UTC_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/; + +function compareStrings(left, right) { + if (left === right) return 0; + if ( + left.length === right.length + && (left.length === 24 || left.length === 20) + && ISO_UTC_RE.test(left) + && ISO_UTC_RE.test(right) + ) { + return left < right ? -1 : 1; + } + cachedCollator ??= new Intl.Collator('en'); + return cachedCollator.compare(left, right); +} + +function normalizeDeviceNameKey(value) { + const trimmed = (value ?? '').trim(); + const lower = trimmed.toLowerCase(); + return lower === 'unknown' || lower === 'no' ? '' : trimmed; +} + +export function buildDeviceIdentity(devices, rawIdentities) { + const knownDeviceIds = new Set(); + const deviceIdsByName = new Map(); + for (const device of devices) { + const deviceId = (device.deviceId ?? '').trim(); + if (!deviceId) continue; + knownDeviceIds.add(deviceId); + const name = normalizeDeviceNameKey(device.name); + if (!name) continue; + let ids = deviceIdsByName.get(name); + if (!ids) { + ids = []; + deviceIdsByName.set(name, ids); + } + ids.push(deviceId); + } + + const staleIdsByName = new Map(); + for (const raw of rawIdentities) { + const deviceId = raw.deviceId?.trim(); + if (!deviceId || knownDeviceIds.has(deviceId)) continue; + const name = normalizeDeviceNameKey(raw.name); + if (!name) continue; + let ids = staleIdsByName.get(name); + if (!ids) { + ids = new Set(); + staleIdsByName.set(name, ids); + } + ids.add(deviceId); + } + + const uniqueDeviceIdByName = new Map(); + for (const [name, ids] of deviceIdsByName) { + if (ids.length !== 1) continue; + if ((staleIdsByName.get(name)?.size ?? 0) > 1) continue; + uniqueDeviceIdByName.set(name, ids[0]); + } + return { knownDeviceIds, uniqueDeviceIdByName }; +} + +export function resolveCanonicalDeviceId(rawDeviceId, deviceName, identity) { + const raw = rawDeviceId?.trim() ?? ''; + if (raw && !identity.knownDeviceIds.has(raw)) { + const name = normalizeDeviceNameKey(deviceName); + const claimed = name ? identity.uniqueDeviceIdByName.get(name) : undefined; + if (claimed) return claimed; + } + return raw || rawDeviceId; +} + +function canonicalizeSessionDevice(session, identity) { + const canonicalDeviceId = resolveCanonicalDeviceId( + session.deviceLinkDeviceId, + session.deviceLinkDeviceName, + identity, + ); + if (canonicalDeviceId === session.canonicalDeviceId) return session; + return { + ...session, + canonicalDeviceId, + }; +} + +function sessionDeviceKey(session) { + return session.canonicalDeviceId ?? session.deviceLinkDeviceId ?? null; +} + +function sessionStatusRank(status) { + if (status === 'active') return 0; + if (status === 'archived') return 1; + return 2; +} + +function lastActivityTime(session) { + return session.lastActivityAt ?? session.userSendAt ?? session.updatedAt ?? session.createdAt ?? ''; +} + +export function compareSessionsByStatusThenActivityDesc(a, b) { + const statusDiff = sessionStatusRank(a.status) - sessionStatusRank(b.status); + if (statusDiff !== 0) return statusDiff; + return compareStrings(lastActivityTime(b), lastActivityTime(a)); +} + +function isDialogueSession(session) { + return session.workspaceKind === 'dialogue' || !session.workingDir; +} + +function isAutomationSession(session, scheduleIndex) { + return session.source === 'scheduler' + || (typeof session.title === 'string' && session.title.startsWith('[Schedule] ')) + || Boolean(scheduleIndex?.get(session.id)); +} + +function normalizeProjectDir(value) { + const trimmed = (value ?? '').trim(); + let end = trimmed.length; + while (end > 0 && (trimmed[end - 1] === '/' || trimmed[end - 1] === '\\')) end -= 1; + const cleaned = end > 0 ? trimmed.slice(0, end) : trimmed; + if (/^[a-z]:[\\/]/i.test(cleaned) || cleaned.includes('\\')) { + return cleaned.replace(/\\/g, '/').toLowerCase(); + } + return cleaned || '__unknown_project__'; +} + +function buildDeviceFilters(devices, sessions, pendingInteractionIndex, selectedDeviceId) { + const sessionCounts = new Map(); + const waitingCounts = new Map(); + let totalSessions = 0; + let totalWaiting = 0; + + for (let i = 0; i < sessions.length; i += 1) { + const session = sessions[i]; + if (session.status === 'deleted') continue; + totalSessions += 1; + const isWaiting = (pendingInteractionIndex?.get(session.id) ?? 0) > 0; + if (isWaiting) totalWaiting += 1; + const devKey = sessionDeviceKey(session); + if (devKey) { + sessionCounts.set(devKey, (sessionCounts.get(devKey) ?? 0) + 1); + if (isWaiting) waitingCounts.set(devKey, (waitingCounts.get(devKey) ?? 0) + 1); + } + } + + let normalizedSelected = null; + if (selectedDeviceId) { + for (let i = 0; i < devices.length; i += 1) { + if (devices[i].deviceId.trim() === selectedDeviceId) { + normalizedSelected = selectedDeviceId; + break; + } + } + } + + const deviceFilters = new Array(devices.length + 1); + deviceFilters[0] = { + id: MOBILE_HOME_ALL_DEVICES, + deviceId: null, + label: 'All devices', + available: true, + state: 'online', + sessionCount: totalSessions, + waitingCount: totalWaiting, + selected: normalizedSelected === null, + }; + for (let i = 0; i < devices.length; i += 1) { + const device = devices[i]; + const devId = device.deviceId.trim(); + deviceFilters[i + 1] = { + id: devId, + deviceId: devId, + label: device.name, + available: Boolean(device.canOpen ?? device.state === 'online'), + state: device.state ?? 'offline', + sessionCount: sessionCounts.get(devId) ?? 0, + waitingCount: waitingCounts.get(devId) ?? 0, + selected: normalizedSelected === devId, + }; + } + return { normalizedSelectedDeviceId: normalizedSelected, deviceFilters }; +} + +function matchesSelectedDevice(session, selectedDeviceId) { + return !selectedDeviceId || sessionDeviceKey(session) === selectedDeviceId; +} + +function matchesStatusFilter(session, filter, pendingInteractionIndex, scheduleIndex) { + if (filter === 'all') return session.status !== 'deleted'; + if (filter === 'waiting') { + return session.status !== 'deleted' && (pendingInteractionIndex?.get(session.id) ?? 0) > 0; + } + if (filter === 'automation') { + return session.status !== 'deleted' && isAutomationSession(session, scheduleIndex); + } + return session.status === filter; +} + +function matchesSearchQuery(session, query, messagePreviewIndex, pendingInteractionIndex, scheduleIndex) { + const scheduleInfo = scheduleIndex?.get(session.id); + const haystack = [ + session.title, + session.workingDir, + session.model, + session.agentKind, + session.status, + session.deviceLinkDeviceName, + scheduleInfo?.scheduleName, + (pendingInteractionIndex?.get(session.id) ?? 0) > 0 ? 'waiting pending attention' : null, + messagePreviewIndex?.get(session.id) ?? session.preview, + ].filter(Boolean).join(' ').toLowerCase(); + return haystack.includes(query); +} + +function toListItem(session, activityAt, pendingInteractionIndex, scheduleIndex, messagePreviewIndex) { + const waitingCount = pendingInteractionIndex?.get(session.id) ?? 0; + return { + id: session.id, + title: session.title || 'Untitled session', + status: session.status, + activityAt, + deviceId: sessionDeviceKey(session), + physicalDeviceId: session.deviceLinkDeviceId ?? null, + workingDir: session.workingDir ?? null, + pinned: Boolean(session.pinnedAt), + waitingCount, + preview: messagePreviewIndex?.get(session.id) ?? session.preview ?? null, + scheduleName: scheduleIndex?.get(session.id)?.scheduleName ?? null, + isDialogue: isDialogueSession(session), + session, + }; +} + +function buildProjectGroups(projectItems) { + const groups = new Map(); + for (let i = 0; i < projectItems.length; i += 1) { + const item = projectItems[i]; + const dirKey = normalizeProjectDir(item.workingDir); + const key = `${item.deviceId ?? ''}::${dirKey}`; + let group = groups.get(key); + if (!group) { + group = { + key, + deviceId: item.deviceId, + workingDir: item.workingDir ?? '__unknown_project__', + latestActivityAt: item.activityAt, + sessionCount: 0, + pendingInteractionCount: 0, + sessions: [], + }; + groups.set(key, group); + } + group.sessions.push(item); + group.sessionCount += 1; + group.pendingInteractionCount += item.waitingCount; + if (compareStrings(item.activityAt, group.latestActivityAt) > 0) { + group.latestActivityAt = item.activityAt; + } + } + const result = [...groups.values()]; + result.sort((a, b) => { + const timeDiff = compareStrings(b.latestActivityAt, a.latestActivityAt); + if (timeDiff !== 0) return timeDiff; + return compareStrings(a.key, b.key); + }); + return result; +} + +function summarizeOverview(sessions, projectsCount, pendingInteractionIndex, selectedDeviceId) { + let all = 0; + let chats = 0; + let pinned = 0; + let waiting = 0; + const deviceSet = new Set(); + + for (let i = 0; i < sessions.length; i += 1) { + const session = sessions[i]; + if (session.status === 'deleted') continue; + if (!matchesSelectedDevice(session, selectedDeviceId)) continue; + all += 1; + if (isDialogueSession(session)) chats += 1; + if (session.pinnedAt) pinned += 1; + if ((pendingInteractionIndex?.get(session.id) ?? 0) > 0) waiting += 1; + const devKey = sessionDeviceKey(session); + if (devKey) deviceSet.add(devKey); + } + return { + all, + chats, + devices: deviceSet.size, + pinned, + projects: projectsCount, + waiting, + }; +} + +export function buildMobileHomePresentation({ + devices = [], + sessions = [], + selectedDeviceId = null, + statusFilter = 'active', + searchQuery = '', + inboxMode = false, + pendingInteractionIndex, + scheduleIndex, + messagePreviewIndex, +} = {}) { + const knownDeviceIdSet = new Set(); + for (let i = 0; i < devices.length; i += 1) { + const id = (devices[i].deviceId ?? '').trim(); + if (id) knownDeviceIdSet.add(id); + } + const staleIdentities = []; + for (let i = 0; i < sessions.length; i += 1) { + const session = sessions[i]; + const rawId = session.deviceLinkDeviceId?.trim(); + if (rawId && !knownDeviceIdSet.has(rawId)) { + staleIdentities.push({ + deviceId: session.deviceLinkDeviceId, + name: session.deviceLinkDeviceName, + }); + } + } + const deviceIdentity = buildDeviceIdentity(devices, staleIdentities); + let allCanonical = true; + for (let i = 0; i < sessions.length; i += 1) { + const session = sessions[i]; + if ( + resolveCanonicalDeviceId(session.deviceLinkDeviceId, session.deviceLinkDeviceName, deviceIdentity) + !== session.canonicalDeviceId + ) { + allCanonical = false; + break; + } + } + const normalizedSessions = allCanonical + ? sessions + : sessions.map((session) => canonicalizeSessionDevice(session, deviceIdentity)); + + const { deviceFilters, normalizedSelectedDeviceId } = buildDeviceFilters( + devices, + normalizedSessions, + pendingInteractionIndex, + selectedDeviceId, + ); + const query = searchQuery.trim().toLowerCase(); + + const matched = []; + for (let i = 0; i < normalizedSessions.length; i += 1) { + const session = normalizedSessions[i]; + if (!matchesSelectedDevice(session, normalizedSelectedDeviceId)) continue; + if (!matchesStatusFilter(session, statusFilter, pendingInteractionIndex, scheduleIndex)) continue; + if (query && !matchesSearchQuery( + session, + query, + messagePreviewIndex, + pendingInteractionIndex, + scheduleIndex, + )) continue; + matched.push({ + session, + statusRank: sessionStatusRank(session.status), + activityTime: lastActivityTime(session), + }); + } + + matched.sort((a, b) => { + const statusDiff = a.statusRank - b.statusRank; + if (statusDiff !== 0) return statusDiff; + return compareStrings(b.activityTime, a.activityTime); + }); + + const items = new Array(matched.length); + const pinned = []; + const chats = []; + const projectItems = []; + for (let i = 0; i < matched.length; i += 1) { + const { session, activityTime } = matched[i]; + const item = toListItem(session, activityTime, pendingInteractionIndex, scheduleIndex, messagePreviewIndex); + items[i] = item; + if (item.pinned) pinned.push(item); + if (inboxMode || !item.pinned) { + if (item.isDialogue) chats.push(item); + else projectItems.push(item); + } + } + + const projects = buildProjectGroups(projectItems); + const overview = summarizeOverview( + normalizedSessions, + projects.length, + pendingInteractionIndex, + normalizedSelectedDeviceId, + ); + + return { + chats, + deviceFilters, + items, + overview, + pinned, + projects, + selectedDeviceId: normalizedSelectedDeviceId, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/reference/src/remote-resource-cache.mjs b/questions/perf-mobile-home-heat/v1/reference/src/remote-resource-cache.mjs new file mode 100644 index 0000000..424e2f8 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/src/remote-resource-cache.mjs @@ -0,0 +1,252 @@ +export const CACHE_STORAGE_PREFIX = 'cindy.remoteResources.v1.'; +export const MAX_DISK_CHARS = 256 * 1024; + +const emptySnapshot = () => ({ home: [], items: {}, read: {}, readSequences: {} }); +const validSequence = (value) => typeof value === 'string' && /^\d{1,30}$/.test(value); + +export const remoteResourceReadKey = (deviceId, resourceId) => JSON.stringify([deviceId, resourceId]); + +function normalize(raw) { + const out = emptySnapshot(); + if (!raw || typeof raw !== 'object') return out; + if (Array.isArray(raw.home)) { + for (const row of raw.home.slice(0, 32)) { + if (!row || typeof row.id !== 'string' || row.id.length > 160 || typeof row.title !== 'string') continue; + out.home.push({ + id: row.id, + title: row.title.slice(0, 512), + resourceKind: typeof row.resourceKind === 'string' ? row.resourceKind.slice(0, 160) : 'collection', + targets: Array.isArray(row.targets) ? row.targets.map((t) => ({ deviceId: String(t.deviceId), name: String(t.name ?? '') })) : [], + }); + } + } + if (raw.items && typeof raw.items === 'object') { + for (const [id, rows] of Object.entries(raw.items).slice(0, 32)) { + if (id.length > 160 || !Array.isArray(rows)) continue; + out.items[id] = rows.slice(0, 200).flatMap((row) => { + if (!row || !row.host || !row.item || !row.item.ref) return []; + const host = { deviceId: String(row.host.deviceId), name: String(row.host.name ?? '') }; + const ref = { + collectionId: String(row.item.ref.collectionId ?? id), + kind: String(row.item.ref.kind ?? 'bot'), + id: String(row.item.ref.id), + }; + const display = { + title: String(row.item.display?.title ?? ''), + preview: typeof row.item.display?.preview === 'string' ? row.item.display.preview.slice(0, 4096) : '', + ...(typeof row.item.display?.avatar === 'string' ? { avatar: row.item.display.avatar } : {}), + ...(typeof row.item.display?.lastReplyAt === 'number' ? { lastReplyAt: row.item.display.lastReplyAt } : {}), + ...(typeof row.item.display?.lastReadAt === 'number' ? { lastReadAt: row.item.display.lastReadAt } : {}), + }; + return [{ + host, + item: { ref, display }, + key: JSON.stringify([host.deviceId, ref.collectionId, ref.kind, ref.id]), + }]; + }); + } + } + if (raw.read && typeof raw.read === 'object') { + for (const [key, at] of Object.entries(raw.read).slice(-2000)) { + if (key.length <= 600 && typeof at === 'number' && Number.isFinite(at) && at >= 0) out.read[key] = at; + } + } + if (raw.readSequences && typeof raw.readSequences === 'object') { + for (const [key, seq] of Object.entries(raw.readSequences).slice(-2000)) { + if (key.length <= 600 && validSequence(seq)) out.readSequences[key] = seq; + } + } + return out; +} + +function diskSnapshot(raw) { + if (raw.length <= MAX_DISK_CHARS) return raw; + const copy = JSON.parse(raw); + let remaining = raw.length - MAX_DISK_CHARS; + for (const rows of Object.values(copy.items)) { + for (const row of rows) { + if (remaining <= 0) break; + const avatar = row.item?.display?.avatar; + if (typeof avatar === 'string' && avatar.length > 0) { + remaining -= avatar.length + 12; + delete row.item.display.avatar; + } + } + } + for (const rows of Object.values(copy.items)) { + while (remaining > 0 && rows.length > 0) { + remaining -= JSON.stringify(rows.pop()).length + 1; + } + } + for (const map of [copy.read, copy.readSequences ?? {}]) { + for (const key of Object.keys(map)) { + if (remaining <= 0) break; + remaining -= JSON.stringify(key).length + JSON.stringify(map[key]).length + 2; + delete map[key]; + } + } + while (remaining > 0 && copy.home.length > 0) { + remaining -= JSON.stringify(copy.home.pop()).length + 1; + } + return JSON.stringify(copy); +} + +export function createRemoteResourceCache({ storage }) { + let epoch = 0; + let revision = 0; + const writeQueues = new Map(); + const snapshots = new Map(); + const unsaved = new Set(); + const listeners = new Set(); + + const emit = () => { + revision += 1; + for (const fn of listeners) fn(); + }; + + async function readRemoteResourceSnapshot(userId) { + if (!userId) return emptySnapshot(); + const cached = snapshots.get(userId); + if (cached) return cached; + const expected = epoch; + const raw = await storage.getItem(CACHE_STORAGE_PREFIX + userId).catch(() => null); + let parsed = emptySnapshot(); + if (typeof raw === 'string' && raw.length > 0) { + try { + parsed = normalize(JSON.parse(raw)); + } catch { + parsed = emptySnapshot(); + } + } + if (expected === epoch) snapshots.set(userId, parsed); + return parsed; + } + + async function drainWriteQueue(userId, queue) { + try { + while (queue.pending.length > 0) { + const firstBatch = queue.pending.splice(0); + const valid = firstBatch.filter((item) => { + if (item.expected !== epoch) { + item.resolve(); + return false; + } + return true; + }); + if (valid.length === 0) continue; + const expected = valid[0].expected; + const snapshot = await readRemoteResourceSnapshot(userId); + // Coalesce any additional mutations that arrived while disk hydration was in flight. + while (queue.pending.length > 0 && queue.pending[0].expected === expected) { + valid.push(queue.pending.shift()); + } + if (expected !== epoch) { + for (const item of valid) item.resolve(); + continue; + } + const before = JSON.stringify(snapshot); + for (const item of valid) item.change(snapshot); + const cleaned = normalize(snapshot); + const raw = JSON.stringify(cleaned); + snapshots.set(userId, cleaned); + if (raw !== before || unsaved.has(userId)) { + if (raw !== before) emit(); + const saved = await storage + .setItem(CACHE_STORAGE_PREFIX + userId, diskSnapshot(raw)) + .then(() => true, () => false); + if (expected !== epoch) { + await storage.removeItem(CACHE_STORAGE_PREFIX + userId).catch(() => undefined); + for (const item of valid) item.resolve(); + continue; + } + if (saved) unsaved.delete(userId); + else unsaved.add(userId); + } + for (const item of valid) item.resolve(); + } + } finally { + for (const item of queue.pending.splice(0)) item.resolve(); + if (writeQueues.get(userId) === queue) writeQueues.delete(userId); + } + } + + function update(userId, change) { + if (!userId) return Promise.resolve(); + const expected = epoch; + return new Promise((resolve) => { + let queue = writeQueues.get(userId); + if (!queue) { + const pending = [{ expected, change, resolve }]; + const created = { pending, running: Promise.resolve() }; + writeQueues.set(userId, created); + created.running = drainWriteQueue(userId, created); + queue = created; + } else { + queue.pending.push({ expected, change, resolve }); + } + }); + } + + return { + readRemoteResourceSnapshot, + cacheRemoteResourceHome(userId, home) { + return update(userId, (s) => { s.home = home; }); + }, + cacheRemoteResourceItems(userId, collectionId, items) { + return update(userId, (s) => { + s.items[collectionId] = items; + for (const row of items) { + const key = remoteResourceReadKey(row.host.deviceId, row.item.ref.id); + if ((row.item.ref.kind === 'bot' || row.item.ref.kind === 'bot-group') && s.read[key] === undefined) { + s.read[key] = row.item.display?.lastReplyAt ?? 0; + } + const hostRead = row.item.display?.lastReadAt; + if (typeof hostRead === 'number' && hostRead > (s.read[key] ?? 0)) { + s.read[key] = hostRead; + } + } + }); + }, + markRemoteResourceRead(userId, deviceId, resourceId, at, sequence) { + return update(userId, (s) => { + const key = remoteResourceReadKey(deviceId, resourceId); + if (Number.isFinite(at) && at >= 0) { + s.read[key] = Math.max(s.read[key] ?? 0, at); + } + if (validSequence(sequence)) { + s.readSequences ??= {}; + if (s.readSequences[key] === undefined || BigInt(sequence) > BigInt(s.readSequences[key])) { + s.readSequences[key] = sequence; + } + } + }); + }, + isRemoteResourceUnread(userId, deviceId, resourceId, lastReplyAt) { + if (!userId || typeof lastReplyAt !== 'number' || lastReplyAt <= 0) return false; + const snapshot = snapshots.get(userId); + if (!snapshot) return false; + const readAt = snapshot.read[remoteResourceReadKey(deviceId, resourceId)] ?? 0; + return lastReplyAt > readAt; + }, + async clearRemoteResourceCache() { + epoch += 1; + snapshots.clear(); + unsaved.clear(); + emit(); + await Promise.allSettled([...writeQueues.values()].map((q) => q.running)); + const keys = await storage.getAllKeys().catch(() => []); + for (const key of keys) { + if (key.startsWith(CACHE_STORAGE_PREFIX)) { + await storage.removeItem(key).catch(() => undefined); + } + } + }, + subscribeRemoteResourceCache(fn) { + listeners.add(fn); + return () => { listeners.delete(fn); }; + }, + remoteResourceCacheRevision() { + return revision; + }, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/reference/src/schedule-index.mjs b/questions/perf-mobile-home-heat/v1/reference/src/schedule-index.mjs new file mode 100644 index 0000000..8aa27cc --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/src/schedule-index.mjs @@ -0,0 +1,256 @@ +export const SCHEDULE_INDEX_TTL_MS = 30_000; +export const SCHEDULE_INDEX_EVENT_COALESCE_MS = 1_500; + +function buildIndexMap(schedules, runsPayload) { + const runsBySchedule = new Map(); + const runs = Array.isArray(runsPayload?.runs) ? runsPayload.runs : []; + for (const run of runs) { + if (!run || typeof run.scheduleId !== 'string') continue; + let bucket = runsBySchedule.get(run.scheduleId); + if (!bucket) { + bucket = []; + runsBySchedule.set(run.scheduleId, bucket); + } + bucket.push(run); + } + const index = new Map(); + for (const schedule of Array.isArray(schedules) ? schedules : []) { + if (!schedule || !schedule.targetSessionId) continue; + const schedRuns = runsBySchedule.get(schedule.id) ?? []; + let latestRunAt = 0; + let running = false; + let hasUnreadFailedRun = false; + const unreadRunIds = []; + for (const r of schedRuns) { + if (typeof r.startedAt === 'number' && r.startedAt > latestRunAt) latestRunAt = r.startedAt; + if (r.status === 'running') running = true; + if (r.unread) { + unreadRunIds.push(r.id); + if (r.status === 'failed') hasUnreadFailedRun = true; + } + } + index.set(schedule.targetSessionId, { + scheduleId: schedule.id, + scheduleName: schedule.name ?? 'Automation', + status: schedule.status ?? 'active', + latestRunAt, + running, + unreadCount: unreadRunIds.length, + unreadRunIds, + hasUnreadFailedRun, + }); + } + return index; +} + +export function createScheduleIndexStore({ + now = Date.now, + setTimer = setTimeout, + clearTimer = clearTimeout, + ttlMs = SCHEDULE_INDEX_TTL_MS, + coalesceMs = SCHEDULE_INDEX_EVENT_COALESCE_MS, +} = {}) { + let cacheGeneration = 0; + const throttleEntries = new Map(); + const invalidationVersions = new Map(); + const boundSessionsByDevice = new Map(); + const eventInvalidatedScheduleDevices = new Set(); + const lastDeviceScheduleIndexLoadAt = new Map(); + const pendingDeviceScheduleIndexCoalesce = new Map(); + + function cancelPendingDeviceScheduleCoalesce(deviceId) { + if (deviceId !== undefined) { + const pending = pendingDeviceScheduleIndexCoalesce.get(deviceId); + if (!pending) return; + clearTimer(pending.timer); + pendingDeviceScheduleIndexCoalesce.delete(deviceId); + pending.cancel(); + return; + } + for (const pending of pendingDeviceScheduleIndexCoalesce.values()) { + clearTimer(pending.timer); + pending.cancel(); + } + pendingDeviceScheduleIndexCoalesce.clear(); + } + + function getScheduleIndexInvalidationVersion(deviceId) { + return invalidationVersions.get(deviceId) ?? 0; + } + + function invalidateScheduleIndexForDevice(deviceId) { + if (!deviceId) return; + eventInvalidatedScheduleDevices.delete(deviceId); + const entry = throttleEntries.get(deviceId); + if (entry?.pending) entry.invalidated = true; + else throttleEntries.delete(deviceId); + invalidationVersions.set(deviceId, getScheduleIndexInvalidationVersion(deviceId) + 1); + } + + function invalidateScheduleIndexesAfterLinkRecovery(deviceId) { + const keys = deviceId === undefined ? [...throttleEntries.keys()] : [deviceId]; + for (const key of keys) { + const entry = throttleEntries.get(key); + if (!entry || entry.failedAt === null || entry.failedTransient) { + invalidateScheduleIndexForDevice(key); + } + } + } + + function noteScheduleEventInIndexCache(deviceId, change) { + if (!deviceId) return; + const known = boundSessionsByDevice.get(deviceId); + const wasCurrent = known !== undefined + && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + if (change.invalidate) { + invalidateScheduleIndexForDevice(deviceId); + eventInvalidatedScheduleDevices.add(deviceId); + } + if (!known) return; + if (!wasCurrent || change.scheduleListChanged) { + boundSessionsByDevice.delete(deviceId); + return; + } + boundSessionsByDevice.set(deviceId, { + sessionIds: change.sessionId && !known.sessionIds.has(change.sessionId) + ? new Set([...known.sessionIds, change.sessionId]) + : known.sessionIds, + failedScheduleIds: known.failedScheduleIds, + invalidationVersion: getScheduleIndexInvalidationVersion(deviceId), + }); + } + + function hasCurrentScheduleIndexRecord(deviceId) { + if (!deviceId) return false; + const known = boundSessionsByDevice.get(deviceId); + return known !== undefined && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId); + } + + function sessionMayHaveScheduleRuns(deviceId, sessionId, source) { + if (source === 'scheduler') return true; + const known = boundSessionsByDevice.get(deviceId); + if (!known || known.invalidationVersion !== getScheduleIndexInvalidationVersion(deviceId)) return true; + return known.sessionIds.has(sessionId); + } + + function clearSessionScheduleIndexCache() { + cacheGeneration += 1; + throttleEntries.clear(); + invalidationVersions.clear(); + boundSessionsByDevice.clear(); + eventInvalidatedScheduleDevices.clear(); + lastDeviceScheduleIndexLoadAt.clear(); + cancelPendingDeviceScheduleCoalesce(); + } + + function loadSharedSessionScheduleIndex(deviceId, invoke, canStart = () => true) { + const existing = throttleEntries.get(deviceId); + const currentNow = now(); + if (existing) { + if (existing.pending) return existing.pending; + if (!existing.invalidated && existing.value && (currentNow - existing.loadedAt) < ttlMs) { + return Promise.resolve(existing.value); + } + } + if (!canStart()) return Promise.reject(new Error('Schedule index consumer inactive')); + + const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId); + const gen = cacheGeneration; + const entry = { + pending: null, + value: null, + loadedAt: 0, + invalidated: false, + failedAt: null, + failedTransient: false, + }; + const promise = Promise.all([ + invoke(deviceId, 'maker:schedule:list', [null, { summaryOnly: true }]), + invoke(deviceId, 'maker:schedule:list-sidebar-index-runs', []), + ]).then(([schedules, runsPayload]) => { + const index = buildIndexMap(schedules, runsPayload); + entry.pending = null; + if (gen === cacheGeneration && !entry.invalidated && throttleEntries.get(deviceId) === entry) { + entry.value = index; + entry.loadedAt = now(); + const failedScheduleIds = new Set(); + for (const info of index.values()) { + if (info.hasUnreadFailedRun) failedScheduleIds.add(info.scheduleId); + } + boundSessionsByDevice.set(deviceId, { + sessionIds: new Set(index.keys()), + failedScheduleIds, + invalidationVersion, + }); + } else if (throttleEntries.get(deviceId) === entry) { + throttleEntries.delete(deviceId); + } + return index; + }, (error) => { + entry.pending = null; + if (throttleEntries.get(deviceId) === entry) { + entry.failedAt = now(); + entry.failedTransient = error?.code === 'LOCAL_LINK_DOWN'; + if (entry.invalidated) throttleEntries.delete(deviceId); + } + throw error; + }); + entry.pending = promise; + throttleEntries.set(deviceId, entry); + return promise; + } + + function loadDeviceSessionScheduleIndex(deviceId, invoke, canStart) { + const pendingCoalesce = pendingDeviceScheduleIndexCoalesce.get(deviceId); + if (pendingCoalesce) { + pendingCoalesce.invoke = invoke; + pendingCoalesce.canStart = canStart; + return pendingCoalesce.promise; + } + const lastLoadAt = lastDeviceScheduleIndexLoadAt.get(deviceId); + const elapsed = lastLoadAt !== undefined ? now() - lastLoadAt : Number.POSITIVE_INFINITY; + if ( + eventInvalidatedScheduleDevices.has(deviceId) + && elapsed >= 0 + && elapsed < coalesceMs + && !throttleEntries.get(deviceId)?.pending + ) { + let entry; + const promise = new Promise((resolve, reject) => { + const timer = setTimer(() => { + if (pendingDeviceScheduleIndexCoalesce.get(deviceId) === entry) { + pendingDeviceScheduleIndexCoalesce.delete(deviceId); + } + eventInvalidatedScheduleDevices.delete(deviceId); + lastDeviceScheduleIndexLoadAt.set(deviceId, now()); + loadSharedSessionScheduleIndex(deviceId, entry.invoke, entry.canStart).then(resolve, reject); + }, coalesceMs - elapsed); + entry = { + timer, + promise: null, + invoke, + canStart, + cancel: () => reject(new Error('Schedule index cache cleared')), + }; + }); + entry.promise = promise; + void promise.catch(() => undefined); + pendingDeviceScheduleIndexCoalesce.set(deviceId, entry); + return promise; + } + eventInvalidatedScheduleDevices.delete(deviceId); + lastDeviceScheduleIndexLoadAt.set(deviceId, now()); + return loadSharedSessionScheduleIndex(deviceId, invoke, canStart); + } + + return { + loadDeviceSessionScheduleIndex, + noteScheduleEventInIndexCache, + invalidateScheduleIndexForDevice, + invalidateScheduleIndexesAfterLinkRecovery, + getScheduleIndexInvalidationVersion, + hasCurrentScheduleIndexRecord, + sessionMayHaveScheduleRuns, + clearSessionScheduleIndexCache, + }; +} diff --git a/questions/perf-mobile-home-heat/v1/reference/tests/smoke.test.mjs b/questions/perf-mobile-home-heat/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..95f8338 --- /dev/null +++ b/questions/perf-mobile-home-heat/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,181 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { buildMobileHomePresentation } from '../src/mobile-home.mjs'; +import { createRemoteResourceCache } from '../src/remote-resource-cache.mjs'; +import { createScheduleIndexStore } from '../src/schedule-index.mjs'; +import { + TASK_ACTIVITY_SNAPSHOT, + receiveHostTaskActivity, + startForegroundTaskActivity, +} from '../src/foreground-task-activity.mjs'; + +function createVirtualClock(startMs = 1_000_000) { + let time = startMs; + let nextId = 1; + const timers = new Map(); + return { + now: () => time, + setTimer(fn, delay) { + const id = nextId++; + timers.set(id, { at: time + Math.max(0, delay), fn }); + return id; + }, + clearTimer(id) { + timers.delete(id); + }, + async advanceBy(ms) { + const target = time + ms; + while (true) { + let earliestId = null; + let earliest = null; + for (const [id, entry] of timers) { + if (entry.at <= target && (!earliest || entry.at < earliest.at)) { + earliest = entry; + earliestId = id; + } + } + if (!earliest) break; + timers.delete(earliestId); + time = earliest.at; + earliest.fn(); + await Promise.resolve(); + } + time = target; + await Promise.resolve(); + }, + }; +} + +function createMemoryStorage() { + const map = new Map(); + return { + map, + writes: 0, + async getItem(k) { return map.get(k) ?? null; }, + async setItem(k, v) { this.writes += 1; map.set(k, v); }, + async removeItem(k) { map.delete(k); }, + async getAllKeys() { return [...map.keys()]; }, + }; +} + +test('buildMobileHomePresentation canonicalizes stale devices and sorts active before archived', () => { + const devices = [ + { deviceId: 'dev-mac', name: 'Studio Mac', state: 'online', canOpen: true }, + { deviceId: 'dev-linux', name: 'Build Box', state: 'online', canOpen: true }, + ]; + const sessions = [ + { + id: 's-arch', + title: 'Old Task', + status: 'archived', + createdAt: '2026-12-01T10:00:00.000Z', + updatedAt: '2026-12-04T10:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + { + id: 's-stale', + title: 'Relinked Task', + status: 'active', + createdAt: '2026-12-01T10:00:00.000Z', + lastActivityAt: '2026-12-04T12:00:00.000Z', + workingDir: '/repo/a', + deviceLinkDeviceId: 'dev-old-mac', + deviceLinkDeviceName: 'Studio Mac', + }, + ]; + const res = buildMobileHomePresentation({ devices, sessions, statusFilter: 'all' }); + assert.deepEqual(res.items.map((i) => i.id), ['s-stale', 's-arch']); + assert.equal(res.items[0].deviceId, 'dev-mac'); + assert.equal(res.items[0].physicalDeviceId, 'dev-old-mac'); + assert.equal(res.projects.length, 1); + assert.equal(res.projects[0].sessionCount, 2); +}); + +test('remoteResourceCache persists mutations and stays silent on no-ops', async () => { + const storage = createMemoryStorage(); + const cache = createRemoteResourceCache({ storage }); + const row = (replyAt) => [{ + host: { deviceId: 'dev-1', name: 'Mac' }, + item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt: replyAt } }, + }]; + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + const writesAfterSeed = storage.writes; + const revAfterSeed = cache.remoteResourceCacheRevision(); + await cache.cacheRemoteResourceItems('alice', 'teammates', row(100)); + assert.equal(storage.writes, writesAfterSeed); + assert.equal(cache.remoteResourceCacheRevision(), revAfterSeed); + await cache.markRemoteResourceRead('alice', 'dev-1', 'writer', 200); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 150), false); + assert.equal(cache.isRemoteResourceUnread('alice', 'dev-1', 'writer', 250), true); +}); + +test('scheduleIndex caches within TTL and reloads after invalidation', async () => { + const clock = createVirtualClock(); + const store = createScheduleIndexStore({ now: clock.now, setTimer: clock.setTimer, clearTimer: clock.clearTimer }); + let calls = 0; + const invoke = async (_dev, channel) => { + calls += 1; + if (channel === 'maker:schedule:list') return [{ id: 'sc-1', name: 'Nightly', status: 'active', targetSessionId: 'task-1' }]; + return { runs: [{ id: 'r-1', scheduleId: 'sc-1', startedAt: 500, status: 'completed', unread: true }] }; + }; + const first = await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(first.get('task-1')?.scheduleName, 'Nightly'); + assert.equal(calls, 2); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 2); + store.invalidateScheduleIndexForDevice('dev-1'); + await store.loadDeviceSessionScheduleIndex('dev-1', invoke); + assert.equal(calls, 4); +}); + +test('foregroundTaskActivity publishes initial snapshot and urgent endings immediately', async () => { + const clock = createVirtualClock(); + const written = []; + const source = { + async readDeviceList() { + return { devices: [{ deviceId: 'mac-1', online: true, remoteControlEnabled: true, platform: 'darwin' }] }; + }, + async subscribe() {}, + async unsubscribe() {}, + async invoke(_dev, channel) { + assert.equal(channel, TASK_ACTIVITY_SNAPSHOT); + return { + schemaVersion: 1, + revision: 1, + waitingCount: 0, + unreadCount: 0, + runningCount: 1, + selected: { sessionId: 's1', title: 'Building app', status: 'running' }, + }; + }, + getPresenceAvailability() { return true; }, + getSubscriptionIdentity() { return 1; }, + }; + const controller = startForegroundTaskActivity(source, { + active: () => true, + labels: { attention: 'Needs input', completed: 'Done', error: 'Error', running: 'Running' }, + staleDetail: 'Stale', + url: (d, s) => `cindy://${d}/${s}`, + write: (state, observedAt) => written.push({ state, observedAt }), + now: clock.now, + setTimer: clock.setTimer, + clearTimer: clock.clearTimer, + }); + await controller.ready; + assert.equal(written.length, 1); + assert.equal(written[0].state?.status, 'running'); + await clock.advanceBy(200); + receiveHostTaskActivity('mac-1', { + schemaVersion: 1, + revision: 2, + waitingCount: 0, + unreadCount: 0, + runningCount: 0, + selected: null, + }, clock.now()); + assert.equal(written.at(-1)?.state, null); + controller.dispose(); +}); diff --git a/questions/smart-routing-three-tiers/v1/author/editable.json b/questions/smart-routing-three-tiers/v1/author/editable.json new file mode 100644 index 0000000..890cc09 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/author/editable.json @@ -0,0 +1 @@ +["src/"] diff --git a/questions/smart-routing-three-tiers/v1/author/evaluator.mjs b/questions/smart-routing-three-tiers/v1/author/evaluator.mjs new file mode 100644 index 0000000..5b28b8a --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/author/evaluator.mjs @@ -0,0 +1,955 @@ +import { takeResultChannel } from './result-channel.mjs'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +// Taken before any submission code loads; see result-channel.mjs. +const trusted = takeResultChannel(); + +const [subDir] = process.argv.slice(2); +const load = async (file) => import(pathToFileURL(path.join(subDir, file)).href); + +const [mg, pqs, pickMod, sr, resolverMod, remoteMod, profileMod, schedMod] = await Promise.all([ + load('model-groups.mjs'), + load('provider-quota-source.mjs'), + load('pick.mjs'), + load('source-routes.mjs'), + load('resolver.mjs'), + load('remote-catalog.mjs'), + load('auto-usage-profile.mjs'), + load('scheduler.mjs'), +]); + +const { + expandMergedSources, + normalizeModelGroupsConfig, + modelGroupResolveResultForRemote, + modelGroupResolveResultFromRemote, +} = mg; +const { + defaultModelGroupSourceTier, + resolveSourceDefaultTier, + resolveTierControlState, + applyTierControlSelection, + retargetCandidateWithTier, +} = pqs; +const { pickModelGroupCandidate } = pickMod; +const { effectiveModelGroupsConfig } = sr; +const { createModelGroupResolver } = resolverMod; +const { redactProviderCatalogForTunnel } = remoteMod; +const { buildAutoUsageProfile } = profileMod; +const { applyRouteWeightStep } = schedMod; + +const NOW = Date.UTC(2026, 11, 3, 14, 0, 0); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +const week = (usedPercent, resetHours) => ({ + usedPercent, + resetAtMs: NOW + resetHours * HOUR, + windowMs: 7 * DAY, +}); + +const fiveHour = (usedPercent, resetHours = 4) => ({ + usedPercent, + resetAtMs: NOW + resetHours * HOUR, + windowMs: 5 * HOUR, +}); + +const fact = (windows, extra = {}) => ({ + available: true, + modelName: 'Model', + sourceName: 'Source', + windows, + ...extra, +}); + +const makeView = (id, name, agent, modelIds, extra = {}) => ({ + id, + name, + source: 'builtin', + connected: true, + agents: [agent], + models: { [agent]: modelIds.map((m) => ({ id: m, name: m.toUpperCase(), mode: 'chat' })) }, + routing: { [agent]: { enabled: true } }, + ...extra, +}); + +// True when any key or string value in `value` names `host`, either as the +// hostname of a parseable URL or as a bare host token such as "host:443". +const mentionsHost = (value, host) => { + const strings = []; + const walk = (v) => { + if (typeof v === 'string') strings.push(v); + else if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + strings.push(k); + walk(x); + } + } + }; + walk(value); + return strings.some((s) => { + try { + if (new URL(s).hostname === host) return true; + } catch {} + return (s.toLowerCase().match(/[a-z0-9-]+(?:\.[a-z0-9-]+)+/g) ?? []).some((t) => t === host); + }); +}; + +const childrenOf = (config, parentId) => (config.routes ?? []).filter((r) => r.parent?.id === parentId); + +async function runItem(name, fn, items, errors) { + try { + await fn(); + items[name] = true; + } catch (err) { + items[name] = false; + errors.push(`${name}: ${err?.message ?? String(err)}`); + } +} + +const items = {}; +const errors = []; + +// Group 1: static_three_tier_defaults +await runItem('default_tier_classification', async () => { + const zhipuLocal = { + id: 'zhipu-coding', + source: 'user', + connected: true, + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + routing: { 'claude-code': { upstream: 'https://open.bigmodel.cn/api/coding/paas/v4' } }, + }; + const ollamaLocal = { + id: 'ollama', + source: 'user', + connected: true, + auth: { method: 'none' }, + access: { kind: 'api' }, + routing: { pi: { upstream: 'http://127.0.0.1:11434/v1' } }, + }; + const oauthSub = { + id: 'openai', + source: 'builtin', + connected: true, + auth: { method: 'oauth' }, + access: { kind: 'subscription' }, + }; + const orgByok = { + id: 'byok-openai-codex', + source: 'organization', + connected: true, + auth: { method: 'managed' }, + access: { kind: 'managed' }, + }; + const managedOther = { + id: 'corp-gateway', + source: 'user', + connected: true, + access: { kind: 'managed' }, + }; + const paygKey = { + id: 'openai-api', + source: 'user', + connected: true, + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + }; + const xdView = { id: 'xd', source: 'builtin', connected: true, access: { kind: 'api' } }; + + assert.equal(defaultModelGroupSourceTier({ providerId: 'openai', provider: oauthSub }), 'primary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'zhipu-coding', provider: zhipuLocal }), 'primary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'ollama', provider: ollamaLocal }), 'primary'); + assert.equal(defaultModelGroupSourceTier({ agentKind: 'acp', providerId: 'acp-plugin:antigravity:agy' }), 'primary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'byok-openai-codex', provider: orgByok }), 'secondary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'byok-only-id' }), 'secondary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'openai', agentDeviceId: 'share:s1', provider: oauthSub }), 'secondary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'corp-gateway', provider: managedOther }), 'secondary'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'openai-api', provider: paygKey }), 'fallback'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'xd', provider: xdView }), 'fallback'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'xd' }), 'fallback'); + assert.equal(defaultModelGroupSourceTier({ providerId: 'openai', provider: oauthSub, accountPayAsYouGo: true }), 'fallback'); +}, items, errors); + +await runItem('byok_vs_healthy_subscription', async () => { + const subView = makeView('openai', 'OpenAI', 'codex', ['gpt-6.2-astra'], { + access: { kind: 'subscription' }, + auth: { method: 'oauth' }, + }); + const byokView = makeView('byok-openai-codex', 'OpenAI-Codex', 'codex', ['byok-openai-codex/gpt-6.2-astra'], { + source: 'organization', + auth: { method: 'managed' }, + access: { kind: 'managed' }, + }); + const apiView = makeView('openai-api', 'OpenAI API', 'codex', ['gpt-6.2-astra'], { + source: 'user', + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + }); + const ollamaView = makeView('ollama', 'Ollama', 'pi', ['qwen3'], { + source: 'user', + auth: { method: 'none' }, + access: { kind: 'api' }, + }); + const zhipuView = makeView('zhipu-coding', 'Zhipu Coding', 'claude-code', ['glm-5'], { + source: 'user', + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + routing: { 'claude-code': { upstream: 'https://open.bigmodel.cn/api/coding/paas/v4' } }, + }); + + const byokHeavyProfile = buildAutoUsageProfile([ + { providerId: 'byok-openai-codex', model: 'byok-openai-codex/gpt-6.2-astra', atMs: NOW - HOUR, tokens: 120_000 }, + { providerId: 'byok-openai-codex', model: 'byok-openai-codex/gpt-6.2-astra', atMs: NOW - DAY, tokens: 120_000 }, + { providerId: 'byok-openai-codex', model: 'byok-openai-codex/gpt-6.2-astra', atMs: NOW - 2 * DAY, tokens: 120_000 }, + ], NOW); + + let route = { + id: 'r-tiers', + name: 'GPT-6.2-Astra', + strategy: 'expiring', + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'gpt-6.2-astra' }, + { agentKind: 'codex', providerId: 'byok-openai-codex', model: 'byok-openai-codex/gpt-6.2-astra' }, + { agentKind: 'codex', providerId: 'openai-api', model: 'gpt-6.2-astra' }, + ], + }; + const subWindows = [week(27, Math.round(6.15 * 24))]; + const resolver = createModelGroupResolver({ + config: () => ({ routes: [route] }), + views: async () => [subView, byokView, apiView, ollamaView, zhipuView], + agents: () => ['claude-code', 'codex', 'pi'], + quotaWindows: async () => new Map([['openai', subWindows]]), + usageProfile: () => byokHeavyProfile, + now: () => NOW, + }); + + // Default 3 tiers: primary sub beats heavily-used BYOK even when sub urgency (~0.83) < old 0.85 + const def = await resolver.resolve({ selection: { type: 'route', id: 'r-tiers' } }); + assert.equal(def.outcome, 'routed'); + assert.equal(def.route.providerId, 'openai'); + assert.deepEqual(def.trace.map((e) => [e.providerId, e.state, e.why]), [ + ['openai', 'picked', 'expiring'], + ['byok-openai-codex', 'standby', 'secondaryReserve'], + ['openai-api', 'standby', 'paygReserve'], + ]); + + // Inverted via user overrides: BYOK -> primary, sub -> fallback (sub gets tierReserve, NOT paygReserve) + route = { + ...route, + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'gpt-6.2-astra', tier: 'fallback' }, + { agentKind: 'codex', providerId: 'byok-openai-codex', model: 'byok-openai-codex/gpt-6.2-astra', tier: 'primary' }, + { agentKind: 'codex', providerId: 'openai-api', model: 'gpt-6.2-astra' }, + ], + }; + const inverted = await resolver.resolve({ selection: { type: 'route', id: 'r-tiers' } }); + assert.equal(inverted.route.providerId, 'byok-openai-codex'); + assert.equal(inverted.trace[0].state, 'standby'); + assert.equal(inverted.trace[0].why, 'tierReserve'); + assert.equal(inverted.trace[2].why, 'paygReserve'); + + // Local Ollama demoted to fallback also gets tierReserve (NOT paygReserve) + route = { + id: 'r-tiers', + name: 'Local Fallback', + strategy: 'expiring', + candidates: [ + { agentKind: 'cc', providerId: 'zhipu-coding', model: 'glm-5' }, + { agentKind: 'pi', providerId: 'ollama', model: 'qwen3', tier: 'fallback' }, + ], + }; + const localRes = await resolver.resolve({ selection: { type: 'route', id: 'r-tiers' } }); + assert.equal(localRes.route.providerId, 'zhipu-coding'); + assert.equal(localRes.trace[1].state, 'standby'); + assert.equal(localRes.trace[1].why, 'tierReserve'); + + // Normalization preserves tier on candidates and sources + const normalized = normalizeModelGroupsConfig({ + routes: [route], + sourceRoutes: [{ id: 'sr1', name: 'SR', strategy: 'expiring', sources: [{ providerId: 'byok-1', tier: 'primary' }, { providerId: 'bad', tier: 'invalid' }] }], + autoSources: { 'auto:openai': [{ providerId: 'byok-1', tier: 'primary' }] }, + }); + assert.equal(normalized.routes[0].candidates[1].tier, 'fallback'); + assert.equal(normalized.sourceRoutes[0].sources[0].tier, 'primary'); + assert.equal(normalized.sourceRoutes[0].sources[1].tier, undefined); + assert.equal(normalized.autoSources['auto:openai'][0].tier, 'primary'); +}, items, errors); + +// Group 2: six_level_tight_placement +await runItem('six_level_order', async () => { + const candidates = [ + { agentKind: 'codex', providerId: 'p1', model: 'm' }, + { agentKind: 'codex', providerId: 's1', model: 'm' }, + { agentKind: 'codex', providerId: 'f1', model: 'm' }, + { agentKind: 'codex', providerId: 'f2', model: 'm' }, + ]; + const route = { id: 'r-six', name: 'Six', strategy: 'expiring', candidates }; + + // Level 1: primary roomy > secondary roomy + { + const res = pickModelGroupCandidate(route, [ + fact([week(27, Math.round(6.15 * 24))], { defaultTier: 'primary' }), + fact(null, { defaultTier: 'secondary' }), + fact(null, { defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 0); + assert.equal(res.trace[1].why, 'secondaryReserve'); + assert.equal(res.trace[2].why, 'paygReserve'); + } + + // Level 2: secondary roomy > primary 5h-tight (and primary marked skipped/tight) + { + const res = pickModelGroupCandidate(route, [ + fact([week(27, Math.round(6.15 * 24)), fiveHour(92)], { defaultTier: 'primary' }), + fact(null, { defaultTier: 'secondary' }), + fact(null, { defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 1); + assert.equal(res.trace[0].state, 'skipped'); + assert.equal(res.trace[0].why, 'tight'); + assert.equal(res.trace[1].why, 'secondaryFallback'); + assert.equal(res.trace[2].why, 'paygReserve'); + } + + // Level 3: primary 5h-tight > secondary 5h-tight & fallback roomy (do not burn PAYG!) + { + const res = pickModelGroupCandidate(route, [ + fact([week(27, Math.round(6.15 * 24)), fiveHour(92)], { defaultTier: 'primary' }), + fact([week(30, 120), fiveHour(90)], { defaultTier: 'secondary' }), + fact(null, { defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 0); + assert.equal(res.trace[1].state, 'standby'); + assert.equal(res.trace[1].why, 'secondaryReserve'); + assert.equal(res.trace[2].why, 'paygReserve'); + } + + // Level 4: secondary 5h-tight > fallback roomy + { + const res = pickModelGroupCandidate(route, [ + fact([week(100, 12)], { defaultTier: 'primary' }), + fact([week(30, 120), fiveHour(90)], { defaultTier: 'secondary' }), + fact(null, { defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 1); + assert.equal(res.trace[1].why, 'secondaryFallback'); + assert.equal(res.trace[2].why, 'paygReserve'); + } + + // Level 5: fallback roomy > fallback 5h-tight + { + const res = pickModelGroupCandidate(route, [ + fact([week(100, 12)], { defaultTier: 'primary' }), + fact([week(100, 12)], { defaultTier: 'secondary' }), + fact(null, { defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 2); + assert.equal(res.trace[2].why, 'paygFallback'); + assert.equal(res.trace[3].state, 'skipped'); + assert.equal(res.trace[3].why, 'tight'); + } + + // Level 6: fallback 5h-tight when only tight fallback remains + { + const res = pickModelGroupCandidate(route, [ + fact([week(100, 12)], { defaultTier: 'primary' }), + fact([week(100, 12)], { defaultTier: 'secondary' }), + fact(null, { available: false, defaultTier: 'fallback', payAsYouGo: true }), + fact([week(20, 120), fiveHour(92)], { defaultTier: 'fallback' }), + ], { now: NOW }); + assert.equal(res.index, 3); + assert.equal(res.trace[3].why, 'tierFallback'); + } +}, items, errors); + +await runItem('disconnected_primary_and_remote_compat', async () => { + const subView = makeView('openai', 'OpenAI', 'codex', ['gpt-6'], { access: { kind: 'subscription' }, auth: { method: 'oauth' } }); + const byokView = makeView('byok-1', 'BYOK', 'codex', ['gpt-6'], { source: 'organization', access: { kind: 'managed' } }); + const apiView = makeView('openai-api', 'API', 'codex', ['gpt-6'], { source: 'user', auth: { method: 'apiKey' }, access: { kind: 'api' } }); + + // Disconnected primary (enabled, available=false) -> secondary wins with secondaryFallback + let views = [{ ...subView, connected: false }, byokView, apiView]; + let route = { + id: 'r-disc', + name: 'Disc', + strategy: 'expiring', + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'byok-1', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'openai-api', model: 'gpt-6' }, + ], + }; + const resolver = createModelGroupResolver({ + config: () => ({ routes: [route] }), + views: async () => views, + agents: () => ['codex'], + quotaWindows: async () => new Map([['openai', [week(20, 120)]]]), + now: () => NOW, + }); + + const secRes = await resolver.resolve({ selection: { type: 'route', id: 'r-disc' } }); + assert.equal(secRes.route.providerId, 'byok-1'); + assert.equal(secRes.why, 'secondaryFallback'); + const remoteSec = modelGroupResolveResultForRemote(secRes); + assert.equal(remoteSec.why, 'order'); + assert.equal(remoteSec.pickWhy, 'secondaryFallback'); + assert.equal(modelGroupResolveResultFromRemote(remoteSec).why, 'secondaryFallback'); + + // Disconnected primary BYOK + demoted non-PAYG subscription in fallback -> tierFallback + remote round-trip + views = [subView, { ...byokView, connected: false }, apiView]; + route = { + ...route, + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'gpt-6', tier: 'fallback' }, + { agentKind: 'codex', providerId: 'byok-1', model: 'gpt-6', tier: 'primary' }, + { agentKind: 'codex', providerId: 'openai-api', model: 'gpt-6' }, + ], + }; + const tierRes = await resolver.resolve({ selection: { type: 'route', id: 'r-disc' } }); + assert.equal(tierRes.route.providerId, 'openai'); + assert.equal(tierRes.why, 'tierFallback'); + const remoteTier = modelGroupResolveResultForRemote(tierRes); + assert.equal(remoteTier.why, 'order'); + assert.equal(modelGroupResolveResultFromRemote(remoteTier).why, 'tierFallback'); + + // Remote round-trip for secondaryReserve & tierReserve in trace entries + const sampleTrace = { + outcome: 'routed', + route: route.candidates[0], + why: 'expiring', + trace: [ + { agentKind: 'codex', providerId: 'a', model: 'm', modelName: 'M', sourceName: 'A', quota: null, state: 'picked', why: 'expiring' }, + { agentKind: 'codex', providerId: 'b', model: 'm', modelName: 'M', sourceName: 'B', quota: null, state: 'standby', why: 'secondaryReserve' }, + { agentKind: 'codex', providerId: 'c', model: 'm', modelName: 'M', sourceName: 'C', quota: null, state: 'standby', why: 'tierReserve' }, + ], + }; + const wire = modelGroupResolveResultForRemote(sampleTrace); + assert.equal(wire.trace[1].why, 'standby'); + assert.equal(wire.trace[2].why, 'standby'); + const back = modelGroupResolveResultFromRemote(wire); + assert.equal(back.trace[1].why, 'secondaryReserve'); + assert.equal(back.trace[2].why, 'tierReserve'); +}, items, errors); + +// Group 3: merged_provider_tiers +await runItem('merged_follow_source_tier', async () => { + const config = { + sourceRoutes: [ + { id: 'auto:anthropic', name: 'Anthropic', strategy: 'expiring', sources: [{ providerId: 'anthropic' }] }, + { id: 'auto:openai', name: 'OpenAI', strategy: 'expiring', sources: [{ providerId: 'openai' }, { providerId: 'byok-1' }] }, + ], + routes: [ + { + id: 'src:anthropic-opus', + name: 'Opus', + strategy: 'expiring', + parent: { id: 'auto:anthropic', name: 'Anthropic', model: 'opus' }, + candidates: [{ agentKind: 'cc', providerId: 'anthropic', model: 'opus' }], + }, + { + id: 'src:openai-astra', + name: 'Astra', + strategy: 'expiring', + parent: { id: 'auto:openai', name: 'OpenAI', model: 'astra' }, + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'astra' }, + { agentKind: 'codex', providerId: 'byok-1', model: 'byok-codex/astra' }, + ], + }, + ], + }; + const outer = { + id: 'work-main', + name: 'Work', + strategy: 'expiring', + candidates: [ + { agentKind: 'cc', providerId: 'anthropic', model: 'opus', merged: { id: 'auto:anthropic', model: 'opus' } }, + { agentKind: 'codex', providerId: 'openai', model: 'astra', merged: { id: 'auto:openai', model: 'astra' } }, + ], + }; + const expanded = expandMergedSources(outer, config); + const picked = pickModelGroupCandidate( + expanded, + [ + fact([week(35, Math.round(6.1 * 24))], { defaultTier: 'primary' }), + fact([week(100, 12)], { defaultTier: 'primary' }), + fact(null, { defaultTier: 'secondary' }), + ], + { now: NOW }, + ); + assert.equal(picked.index, 0); + assert.equal(picked.trace[2].state, 'standby'); + assert.equal(picked.trace[2].why, 'secondaryReserve'); +}, items, errors); + +await runItem('merged_fixed_outer_tier_and_bench_inherit', async () => { + const config = { + sourceRoutes: [ + { id: 'auto:anthropic', name: 'Anthropic', strategy: 'expiring', sources: [{ providerId: 'anthropic' }] }, + { id: 'auto:openai', name: 'OpenAI', strategy: 'expiring', sources: [{ providerId: 'openai' }, { providerId: 'byok-1' }] }, + ], + routes: [ + { + id: 'src:anthropic-opus', + name: 'Opus', + strategy: 'expiring', + parent: { id: 'auto:anthropic', name: 'Anthropic', model: 'opus' }, + candidates: [{ agentKind: 'cc', providerId: 'anthropic', model: 'opus' }], + }, + { + id: 'src:openai-astra', + name: 'Astra', + strategy: 'expiring', + parent: { id: 'auto:openai', name: 'OpenAI', model: 'astra' }, + candidates: [ + { agentKind: 'codex', providerId: 'openai', model: 'astra' }, + { agentKind: 'codex', providerId: 'byok-1', model: 'byok-codex/astra' }, + ], + }, + ], + }; + const outer = { + id: 'work-main', + name: 'Work', + strategy: 'expiring', + candidates: [ + { agentKind: 'cc', providerId: 'anthropic', model: 'opus', merged: { id: 'auto:anthropic', model: 'opus' } }, + { agentKind: 'codex', providerId: 'openai', model: 'astra', merged: { id: 'auto:openai', model: 'astra' } }, + ], + }; + + // Downgrade auto:openai row to fallback: both rep and benched inner member inherit tierReserve + const downgraded = expandMergedSources({ + ...outer, + candidates: [outer.candidates[0], { ...outer.candidates[1], tier: 'fallback' }], + }, config); + const resDown = pickModelGroupCandidate( + downgraded, + [ + fact([week(35, Math.round(6.1 * 24))], { defaultTier: 'primary' }), + fact([week(25, Math.round(5.5 * 24))], { defaultTier: 'primary' }), + fact(null, { defaultTier: 'secondary' }), + ], + { now: NOW }, + ); + assert.equal(resDown.index, 0); + assert.equal(resDown.trace[1].state, 'standby'); + assert.equal(resDown.trace[1].why, 'tierReserve'); + assert.equal(resDown.trace[2].state, 'standby'); + assert.equal(resDown.trace[2].why, 'tierReserve'); + + // Pin auto:anthropic to secondary and auto:openai to primary -> byok-1 wins when openai sub is exhausted + const overridden = expandMergedSources({ + ...outer, + candidates: [ + { ...outer.candidates[0], tier: 'secondary' }, + { ...outer.candidates[1], tier: 'primary' }, + ], + }, config); + const resOver = pickModelGroupCandidate( + overridden, + [ + fact([week(35, Math.round(6.1 * 24))], { defaultTier: 'primary' }), + fact([week(100, 12)], { defaultTier: 'primary' }), + fact(null, { defaultTier: 'secondary' }), + ], + { now: NOW }, + ); + assert.equal(resOver.index, 2); + assert.equal(resOver.trace[0].state, 'standby'); + assert.equal(resOver.trace[0].why, 'secondaryReserve'); +}, items, errors); + +// Group 4: per_engine_coding_plan_and_mixed_overrides +await runItem('per_engine_coding_plan_routing', async () => { + const cases = [ + ['Kimi Coding', 'https://api.kimi.com/coding/v1'], + ['OpenCode Go', 'https://opencode.ai/zen/go/v1'], + ['GLM Coding Plan', 'https://open.bigmodel.cn/api/coding/paas/v4'], + ]; + for (const [name, upstream] of cases) { + const model = { id: 'test-model', name: 'Test Model', mode: 'chat' }; + const mixed = { + id: 'mixed', + name, + source: 'user', + connected: true, + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + agents: ['claude-code', 'pi'], + models: { 'claude-code': [model], pi: [model] }, + routing: { 'claude-code': { upstream }, pi: { upstream: 'https://payg.example/v1' } }, + }; + const byok = { ...mixed, id: 'byok-backup', source: 'organization', access: { kind: 'managed' } }; + const candidate = { agentKind: 'pi', providerId: mixed.id, model: model.id }; + let route = { id: 'r-mixed', name: 'Mixed', strategy: 'expiring', candidates: [candidate, { ...candidate, providerId: byok.id }] }; + const resolver = createModelGroupResolver({ + config: () => ({ routes: [route] }), + views: async () => [mixed, byok], + agents: () => ['claude-code', 'pi'], + quotaWindows: async () => new Map(), + now: () => NOW, + }); + + // Provider-wide summary is primary, but pi candidate is fallback so BYOK wins + assert.equal(defaultModelGroupSourceTier({ providerId: mixed.id, provider: mixed }), 'primary'); + const piRes = await resolver.resolve({ selection: { type: 'route', id: 'r-mixed' } }); + assert.equal(piRes.route.providerId, byok.id); + + // Adding cc candidate (which uses coding-plan endpoint) beats BYOK + route = { ...route, candidates: [...route.candidates, { ...candidate, agentKind: 'cc' }] }; + const ccRes = await resolver.resolve({ selection: { type: 'route', id: 'r-mixed' } }); + assert.equal(ccRes.route.providerId, mixed.id); + assert.equal(ccRes.route.agentKind, 'cc'); + } + + // Redacted GLM hints: legacy boolean vs per-engine zhipuCodingPlanUsageAgents + const legacy = { + id: 'glm', + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + routing: { 'claude-code': { wireProtocol: 'anthropic-messages' }, pi: { wireProtocol: 'openai-chat' } }, + zhipuCodingPlanUsage: true, + }; + const current = { ...legacy, zhipuCodingPlanUsageAgents: ['claude-code'] }; + const single = { ...legacy, routing: { 'claude-code': legacy.routing['claude-code'] } }; + const tier = (provider, agentKind) => defaultModelGroupSourceTier({ providerId: provider.id, provider, agentKind }); + + assert.equal(tier(legacy), 'primary'); + assert.equal(tier(legacy, 'pi'), 'fallback'); + assert.equal(tier(legacy, 'cc'), 'fallback'); + assert.equal(tier(single, 'cc'), 'primary'); + assert.equal(tier(current, 'cc'), 'primary'); + assert.equal(tier(current, 'pi'), 'fallback'); +}, items, errors); + +await runItem('mixed_payg_override_preservation', async () => { + const coding = { upstream: 'https://api.kimi.com/coding/v1' }; + const mixed = { + id: 'mixed', + name: 'Mixed Kimi', + source: 'user', + connected: true, + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + agents: ['claude-code', 'pi'], + routing: { 'claude-code': coding, pi: { upstream: 'https://api.kimi.com/v1' } }, + }; + // Heterogeneous provider -> defaultTier is undefined (follow source) + const mixedDefault = resolveSourceDefaultTier({ providerId: 'mixed' }, mixed); + assert.equal(mixedDefault, undefined); + + let savedTier = undefined; + let state = resolveTierControlState({ value: savedTier, defaultTier: mixedDefault }); + assert.equal(state.effective, 'follow'); + assert.equal(state.showFollow, true); + assert.deepEqual(state.options, ['follow', 'primary', 'secondary', 'fallback']); + + // Can pin any of the 3 tiers on a mixed source + for (const tier of ['primary', 'fallback', 'secondary', 'primary']) { + savedTier = applyTierControlSelection({ value: savedTier, defaultTier: mixedDefault }, tier); + assert.equal(savedTier, tier); + } + + // Catalog changes so both engines now use coding plan -> uniform defaultTier = 'primary' catches up to savedTier = 'primary' + const uniform = { ...mixed, routing: { 'claude-code': coding, pi: coding } }; + const uniformDefault = resolveSourceDefaultTier({ providerId: 'mixed' }, uniform); + assert.equal(uniformDefault, 'primary'); + + // Saved explicit override is preserved AND 'follow' stays offered so user can explicitly clear it + state = resolveTierControlState({ value: savedTier, defaultTier: uniformDefault }); + assert.equal(state.effective, 'primary'); + assert.equal(state.showFollow, true); + assert.ok(state.options.includes('follow')); + + // Selecting 'follow' clears the override; afterwards homogeneous default hides 'follow' + savedTier = applyTierControlSelection({ value: savedTier, defaultTier: uniformDefault }, 'follow'); + assert.equal(savedTier, undefined); + state = resolveTierControlState({ value: savedTier, defaultTier: uniformDefault }); + assert.equal(state.effective, 'primary'); + assert.equal(state.showFollow, false); + assert.deepEqual(state.options, ['primary', 'secondary', 'fallback']); + + // Homogeneous override cleared when user picks defaultTier directly + savedTier = applyTierControlSelection({ value: undefined, defaultTier: 'secondary' }, 'primary'); + assert.equal(savedTier, 'primary'); + savedTier = applyTierControlSelection({ value: savedTier, defaultTier: 'secondary' }, 'secondary'); + assert.equal(savedTier, undefined); + + // Retargeting candidate preserves tier only on same (providerId, agentDeviceId, accountId) + const prev = { agentKind: 'codex', providerId: 'openai', accountId: 'a1', model: 'gpt-6', tier: 'secondary', effort: 'high' }; + const sameSrc = retargetCandidateWithTier(prev, { agentKind: 'codex', providerId: 'openai', accountId: 'a1', model: 'gpt-6.2' }); + assert.equal(sameSrc.tier, 'secondary'); + assert.equal(sameSrc.effort, 'high'); + const diffAcct = retargetCandidateWithTier(prev, { agentKind: 'codex', providerId: 'openai', accountId: 'a2', model: 'gpt-6.2' }); + assert.equal(diffAcct.tier, undefined); + assert.equal(diffAcct.effort, 'high'); + const diffProv = retargetCandidateWithTier(prev, { agentKind: 'codex', providerId: 'byok-1', model: 'gpt-6.2' }); + assert.equal(diffProv.tier, undefined); +}, items, errors); + +// Group 5: legacy_pool_tier_isolation +await runItem('auto_route_default_tier_sort_and_override', async () => { + const localOpenAi = makeView('openai', 'OpenAI', 'codex', ['gpt-6.2-sol'], { + logoKind: 'openai', + auth: { method: 'oauth' }, + access: { kind: 'subscription' }, + subscriptionAccountKeys: ['acct-a', 'acct-b'], + }); + const byok = makeView('byok-1', 'OpenAI BYOK', 'codex', ['byok-1/gpt-6.2-sol'], { + source: 'organization', + logoKind: 'openai', + auth: { method: 'managed' }, + access: { kind: 'managed' }, + }); + const apiKey = makeView('openai-api', 'OpenAI API', 'codex', ['gpt-6.2-sol'], { + source: 'user', + logoKind: 'openai', + auth: { method: 'apiKey' }, + access: { kind: 'api' }, + }); + const localAccounts = new Map([['openai', [ + { id: 'default', label: 'a@example.com', accountKey: 'acct-a', usable: true }, + { id: 'second', label: 'b@example.com', accountKey: 'acct-b', usable: true }, + ]]]); + + // Even when catalog lists [apiKey, byok, localOpenAi], auto route sorts primary -> secondary -> fallback + const defaultSorted = effectiveModelGroupsConfig({ routes: [] }, { + views: [apiKey, byok, localOpenAi], + localAccounts, + agents: ['codex'], + available: () => true, + }); + assert.deepEqual(defaultSorted.sourceRoutes[0].sources, [ + { providerId: 'openai', accountId: 'default' }, + { providerId: 'openai', accountId: 'second' }, + { providerId: 'byok-1' }, + { providerId: 'openai-api' }, + ]); + + // Explicit autoSources overrides order + tier and propagates tier into expanded model candidates + const reordered = effectiveModelGroupsConfig({ + routes: [], + autoSources: { + 'auto:openai': [ + { providerId: 'byok-1', tier: 'primary' }, + { providerId: 'openai', accountId: 'default', tier: 'secondary' }, + ], + }, + }, { + views: [apiKey, byok, localOpenAi], + localAccounts, + agents: ['codex'], + available: () => true, + }); + assert.deepEqual(reordered.sourceRoutes[0].sources, [ + { providerId: 'byok-1', tier: 'primary' }, + { providerId: 'openai', accountId: 'default', tier: 'secondary' }, + { providerId: 'openai', accountId: 'second' }, + { providerId: 'openai-api' }, + ]); + const expandedCandidates = childrenOf(reordered, 'auto:openai').find((r) => r.parent.model === 'gpt-6.2-sol')?.candidates; + assert.deepEqual(expandedCandidates?.map((c) => [c.providerId, c.accountId ?? null, c.tier ?? null]), [ + ['byok-1', null, 'primary'], + ['openai', 'default', 'secondary'], + ['openai', 'second', null], + ['openai-api', null, null], + ]); +}, items, errors); + +await runItem('legacy_whole_provider_tier_pool_isolation', async () => { + const localOpenAi = makeView('openai', 'OpenAI', 'codex', ['gpt-6-luna'], { + logoKind: 'openai', + auth: { method: 'oauth' }, + access: { kind: 'subscription' }, + subscriptionAccountKeys: ['acct-a'], + }); + const localAccounts = new Map([['openai', [ + { id: 'default', label: 'first@example.com', accountKey: 'acct-a', usable: true }, + { id: 'key-member', label: 'API Key', apiConnectionId: 'openai-api', usable: true }, + ]]]); + + // Auto route with legacy whole-provider tier: only subscription account inherits tier, PAYG key stays clean + const autoConfig = effectiveModelGroupsConfig({ + routes: [], + autoSources: { 'auto:openai': [{ providerId: 'openai', tier: 'primary' }] }, + }, { + views: [localOpenAi], + localAccounts, + agents: ['codex'], + available: () => true, + }); + assert.deepEqual(autoConfig.sourceRoutes.find((r) => r.id === 'auto:openai')?.sources, [ + { providerId: 'openai', accountId: 'default', tier: 'primary' }, + { providerId: 'openai', accountId: 'key-member' }, + ]); + + // Manual source route with legacy whole-provider tier: same isolation + const manualConfig = effectiveModelGroupsConfig({ + routes: [], + sourceRoutes: [{ + id: 'manual-openai', + name: 'Manual OpenAI', + strategy: 'expiring', + sources: [{ providerId: 'openai', tier: 'primary' }], + }], + }, { + views: [localOpenAi], + localAccounts, + agents: ['codex'], + available: () => true, + }); + assert.deepEqual(manualConfig.sourceRoutes.find((r) => r.id === 'manual-openai')?.sources, [ + { providerId: 'openai', accountId: 'default', tier: 'primary' }, + { providerId: 'openai', accountId: 'key-member' }, + ]); + + // Exact per-account override on PAYG pool member IS honored + const exactConfig = effectiveModelGroupsConfig({ + routes: [], + autoSources: { + 'auto:openai': [ + { providerId: 'openai', accountId: 'key-member', tier: 'secondary' }, + ], + }, + }, { + views: [localOpenAi], + localAccounts, + agents: ['codex'], + available: () => true, + }); + assert.deepEqual(exactConfig.sourceRoutes.find((r) => r.id === 'auto:openai')?.sources, [ + { providerId: 'openai', accountId: 'key-member', tier: 'secondary' }, + { providerId: 'openai', accountId: 'default' }, + ]); +}, items, errors); + +// Group 6: remote_catalog_redaction +await runItem('redacts_routes_and_emits_per_engine_hints', async () => { + const input = { + providers: [ + { + id: 'glm', + connected: true, + remoteInvocationEnabled: true, + auth: { method: 'apiKey' }, + routing: { + 'claude-code': { upstream: 'https://api.z.ai/api/anthropic', wireProtocol: 'anthropic-messages' }, + codex: { upstream: 'https://api.z.ai/api/coding/paas/v4', disabled: true }, + pi: { upstream: 'https://api.z.ai/api/paas/v4', wireProtocol: 'openai-chat' }, + }, + }, + { + id: 'kimi', + name: 'Kimi', + auth: { method: 'apiKey' }, + agents: ['pi'], + routing: { pi: { upstream: 'https://api.kimi.com/coding/v1', authStrategy: 'api-key-header' } }, + }, + { + id: 'proxy', + name: 'Proxy', + connected: true, + remoteInvocationEnabled: true, + auth: { method: 'apiKey' }, + agents: ['pi'], + kimiCodingUsageAgents: ['pi'], + zhipuCodingPlanUsage: true, + zhipuCodingPlanUsageAgents: ['pi'], + routing: { pi: { upstream: 'https://proxy.example/coding/v1' } }, + }, + { + id: 'opencode-go', + name: 'OpenCode Go', + source: 'user', + auth: { method: 'apiKey' }, + agents: ['codex'], + routing: { codex: { upstream: 'https://opencode.ai/zen/go/v1', authStrategy: 'api-key-header' } }, + }, + { + id: 'fake-opencode', + name: 'Fake OpenCode', + source: 'user', + auth: { method: 'apiKey' }, + agents: ['codex'], + opencodeGoUsageAgents: ['codex'], + routing: { codex: { upstream: 'https://proxy.example/zen/go/v1' } }, + }, + ], + }; + + const out = redactProviderCatalogForTunnel(input, { sameAccountController: true, readZhipuCodingPlanAccountUsage: true }); + const byId = Object.fromEntries(out.providers.map((p) => [p.id, p])); + assert.equal(byId.glm.zhipuCodingPlanUsage, true); + assert.deepEqual(byId.glm.zhipuCodingPlanUsageAgents, ['claude-code']); + assert.deepEqual(byId.kimi.kimiCodingUsageAgents, ['pi']); + assert.deepEqual(byId['opencode-go'].opencodeGoUsageAgents, ['codex']); + assert.equal('zhipuCodingPlanUsage' in byId.proxy, false); + assert.equal('zhipuCodingPlanUsageAgents' in byId.proxy, false); + assert.equal('kimiCodingUsageAgents' in byId.proxy, false); + assert.equal('opencodeGoUsageAgents' in byId['fake-opencode'], false); + + for (const host of ['api.z.ai', 'api.kimi.com', 'opencode.ai', 'proxy.example']) { + assert.equal(mentionsHost(out, host), false, `redacted catalog exposes ${host}`); + } + + // Guest / non-same-account controller never receives Zhipu coding-plan usage hints + const guestOut = redactProviderCatalogForTunnel(input, { sameAccountController: false, readZhipuCodingPlanAccountUsage: true }); + const guestGlm = guestOut.providers.find((p) => p.id === 'glm'); + assert.equal('zhipuCodingPlanUsage' in guestGlm, false); + assert.equal('zhipuCodingPlanUsageAgents' in guestGlm, false); +}, items, errors); + +// Group 7: baseline_regression_guard +await runItem('non_auto_strategies_and_same_tier_scoring', async () => { + const candidates = [ + { agentKind: 'codex', providerId: 'a', model: 'm', weight: 2 }, + { agentKind: 'codex', providerId: 'b', model: 'm', weight: 1 }, + ]; + // order, rotate, drain, headroom, cheapest, weighted, needsImage + assert.equal(pickModelGroupCandidate({ id: 'o', name: 'O', strategy: 'order', candidates }, [fact(null), fact(null)], { now: NOW }).index, 0); + assert.equal(pickModelGroupCandidate({ id: 'r', name: 'R', strategy: 'rotate', candidates }, [fact(null), fact(null)], { now: NOW, lastPickedKey: 'codex\u0000a\u0000m' }).index, 1); + assert.equal(pickModelGroupCandidate({ id: 'd', name: 'D', strategy: 'drain', candidates }, [fact(null), fact(null)], { now: NOW, lastPickedKey: 'codex\u0000a\u0000m' }).index, 0); + assert.equal(pickModelGroupCandidate({ id: 'h', name: 'H', strategy: 'headroom', candidates }, [fact([week(60, 100)]), fact([week(20, 100)])], { now: NOW }).index, 1); + assert.equal(pickModelGroupCandidate({ id: 'c', name: 'C', strategy: 'cheapest', candidates }, [fact(null, { price: 10 }), fact(null, { price: 2 })], { now: NOW }).index, 1); + const w1 = pickModelGroupCandidate({ id: 'w', name: 'W', strategy: 'weighted', candidates }, [fact(null), fact(null)], { now: NOW }); + const w2 = pickModelGroupCandidate({ id: 'w', name: 'W', strategy: 'weighted', candidates }, [fact(null), fact(null)], { now: NOW, weightCounters: applyRouteWeightStep(new Map(), w1.weightStep) }); + const w3 = pickModelGroupCandidate({ id: 'w', name: 'W', strategy: 'weighted', candidates }, [fact(null), fact(null)], { now: NOW, weightCounters: applyRouteWeightStep(applyRouteWeightStep(new Map(), w1.weightStep), w2.weightStep) }); + assert.deepEqual([w1.index, w2.index, w3.index], [0, 1, 0]); + + const img = pickModelGroupCandidate({ id: 'i', name: 'I', strategy: 'order', candidates }, [fact(null, { acceptsImage: false }), fact(null, { acceptsImage: true })], { now: NOW, needsImage: true }); + assert.equal(img.index, 1); + assert.equal(img.image, 'applied'); + + // Within-tier expiring sprint & concurrency load avoidance + const sprint = pickModelGroupCandidate( + { id: 's', name: 'S', strategy: 'expiring', candidates }, + [fact([week(20, 120)], { defaultTier: 'primary' }), fact([week(40, 18)], { defaultTier: 'primary' })], + { now: NOW }, + ); + assert.equal(sprint.index, 1); + assert.equal(sprint.trace[1].why, 'expiring'); + + const busy = pickModelGroupCandidate( + { id: 'b', name: 'B', strategy: 'expiring', candidates }, + [fact([week(20, 120)], { defaultTier: 'primary', running: 3 }), fact([week(25, 120)], { defaultTier: 'primary', running: 0 })], + { now: NOW }, + ); + assert.equal(busy.index, 1); + assert.equal(busy.trace[1].why, 'lessBusy'); +}, items, errors); + +trusted.emit(({ + status: 'graded', + items, + details: { errors }, +})); diff --git a/questions/smart-routing-three-tiers/v1/author/grade.py b/questions/smart-routing-three-tiers/v1/author/grade.py new file mode 100644 index 0000000..4f6d478 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/author/grade.py @@ -0,0 +1,48 @@ +"""Trusted submission gate: protected inputs/tests cannot be altered.""" +from pathlib import Path +import sys, json, filecmp, subprocess, os + +Q = Path(__file__).resolve().parent.parent +root = Path(sys.argv[1]).resolve() +output = Path(sys.argv[2]).resolve() +allowed = json.loads((Q / 'author/editable.json').read_text()) + +def editable(rel): + return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel + +errors = [] +if not root.is_dir(): + errors.append('source root missing') +else: + for base in (Q / 'candidate').rglob('*'): + if not base.is_file(): + continue + rel = base.relative_to(Q / 'candidate').as_posix() + if editable(rel): + continue + if rel.startswith(('.build/', '.work/')): + continue + other = root / rel + if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False): + errors.append(rel) + +if errors: + result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors} +else: + try: + p = subprocess.run( + [sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)], + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + capture_output=True, text=True, timeout=180 + ) + if p.returncode or not output.exists(): + result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]} + else: + result = json.loads(output.read_text()) + result['submissionGate'] = 'passed' + except subprocess.TimeoutExpired: + result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'} + +output.parent.mkdir(parents=True, exist_ok=True) +output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n') +print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False)) diff --git a/questions/smart-routing-three-tiers/v1/author/grade_impl.py b/questions/smart-routing-three-tiers/v1/author/grade_impl.py new file mode 100644 index 0000000..e3d2c4c --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/author/grade_impl.py @@ -0,0 +1,39 @@ +"""Isolated pure-Node capability grader for smart-routing-three-tiers.""" +import pathlib, secrets, shutil, tempfile, subprocess, json, sys + +HERE = pathlib.Path(__file__).resolve().parent + +RESULT_TAG = 'EVAL-RESULT ' + + +def read_result(stdout, nonce): + """Only the evaluator knows the per-run nonce (read from stdin before any submission code + loads), so a line printed by the submission cannot pass as the result.""" + prefix = f'{RESULT_TAG}{nonce} ' + found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)] + if len(found) != 1: + return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'} + return json.loads(found[0]) + + +def grade(submission_root): + submission_root = pathlib.Path(submission_root).resolve() + with tempfile.TemporaryDirectory(prefix='eval-smart-routing-') as td: + tmp = pathlib.Path(td) + sub_src = tmp / 'sub_src' + shutil.copytree(submission_root / 'src', sub_src) + nonce = secrets.token_hex(16) + p = subprocess.run( + ['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)], + input=nonce + '\n', capture_output=True, text=True, timeout=120 + ) + if p.returncode != 0: + return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'} + return read_result(p.stdout, nonce) + +if __name__ == '__main__': + try: + res = grade(sys.argv[1]) + except Exception as exc: + res = {'status': 'environment_invalid', 'reason': str(exc)} + pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n') diff --git a/questions/smart-routing-three-tiers/v1/author/result-channel.mjs b/questions/smart-routing-three-tiers/v1/author/result-channel.mjs new file mode 100644 index 0000000..cb3a46e --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/author/result-channel.mjs @@ -0,0 +1,45 @@ +/** + * Trusted result channel (author side, loaded before any submission code). + * + * The grader passes a fresh random nonce on stdin. This module reads it before the evaluator + * imports the submission, captures the clock / memory / GC functions the evaluator measures + * with, and hands them out exactly once. The evaluator writes its result as the only line + * tagged with the nonce; the grader accepts exactly one such line. A submission therefore + * cannot print a result of its own, re-import this module to reuse the emitter, or patch + * `performance.now` / `process.memoryUsage` to bend measurements. Run under + * `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either. + * Reading process memory through a debugger is outside this guard (see docs/versioning.md). + */ +import { readFileSync, writeSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; + +const nonce = (() => { + if (process.stdin.isTTY) return ''; + try { + return readFileSync(0, 'utf8').trim(); + } catch { + return ''; + } +})(); +const write = writeSync; +const stringify = JSON.stringify; +const now = performance.now.bind(performance); +const memoryUsage = process.memoryUsage.bind(process); +const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null; +let taken = false; + +export function takeResultChannel() { + if (taken) throw new Error('result channel already taken'); + taken = true; + return { + now, + memoryUsage, + gc() { + if (!gc) throw new Error('gc is not exposed'); + gc(); + }, + emit(result) { + write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`); + }, + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/CONTRACT.md b/questions/smart-routing-three-tiers/v1/candidate/CONTRACT.md new file mode 100644 index 0000000..b06fe60 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/CONTRACT.md @@ -0,0 +1,58 @@ +# Product & Protocol Contract + +This contract defines the authoritative three-tier Smart Routing (`expiring` / Auto) semantics and public interfaces across `src/`. + +## 1. Static Three-Tier Default Classification (`src/provider-quota-source.mjs`) + +- Exports `MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']`, `modelGroupTierRank(tier)` (`0`/`1`/`2`), `defaultModelGroupSourceTier({ agentKind?, providerId, agentDeviceId?, provider?, accountPayAsYouGo? })`, and `isZhipuCodingPlanProviderView(view, agent?)`. +- Static default tier rules (never changing tier due to transient quota timeouts): + - Merged pay-as-you-go API key accounts (`accountPayAsYouGo`) → `'fallback'`. + - Shared providers (`agentDeviceId` starting with `share:`) → `'secondary'`. + - Organization-managed providers (`provider.source === 'organization'`) or BYOK IDs (`byok-*`) → `'secondary'`. + - ACP plugin engines (`agentKind === 'acp'` or `acp-plugin:*` provider IDs) → `'primary'`. + - Standard providers (evaluated per engine when `agentKind` is given, mapping `'cc'` → `'claude-code'`; when `agentKind` is omitted, a provider is treated as a coding plan if any configured engine uses an official coding plan): + - Official coding plans (Kimi Coding, OpenCode Go, Zhipu/Z.AI GLM Coding Plan) or local no-auth (`auth.method === 'none'`) → `'primary'`. + - Pay-as-you-go (`access.kind === 'api'` or `providerId === 'xd'`) → `'fallback'`. + - Subscriptions (`access.kind === 'subscription'` or `auth.method === 'oauth'`) → `'primary'`. + - Managed (`access.kind === 'managed'`) → `'secondary'`; otherwise `'primary'`. +- `isZhipuCodingPlanProviderView(view, agent?)`: requires `auth.method === 'apiKey'`; prefers per-engine `zhipuCodingPlanUsageAgents` when present, falls back to per-engine routing inspection, and honors legacy boolean `zhipuCodingPlanUsage` for a specific `agent` ONLY when that agent is the sole enabled route without an explicit `upstream` (never promoting multi-engine redacted views blindly). + +## 2. Six-Level Auto Selection & Wire Compatibility (`src/pick.mjs`, `src/model-groups.mjs`) + +- Neutral unknown-quota score within a tier is `AUTO_UNKNOWN_QUOTA_SCORE = 0.78`. +- For `strategy === 'expiring'`, pick among ready candidates in strict 6-level priority order: + 1. `primary` roomy → 2. `secondary` roomy → 3. `primary` 5h-tight → 4. `secondary` 5h-tight → 5. `fallback` roomy → 6. `fallback` 5h-tight. +- Within a tier, preserve expiring-surplus sprint (`>= 2.0×`), `quotaScore + usageBonus - running * 0.30`, and `0.06` soft rotation. +- **Trace reasons (`state` / `why`)**: + - When a `secondary` winner is chosen while any enabled (`!off`) `primary` peer exists (even disconnected or limited) → `why: 'secondaryFallback'`. + - When a `fallback` winner is chosen while any enabled non-`fallback` peer exists → `why: 'paygFallback'` (if PAYG) or `'tierFallback'` (otherwise). + - Non-picked ready candidates report `standby` (`paygReserve` / `tierReserve` for `fallback` below non-`fallback`; `secondaryReserve` for `secondary` below `primary`; otherwise `standby`) or `skipped` (`why: 'tight'` when 5h-tight and a roomy peer with higher priority in the 6-level order is ready — e.g. `secondary` roomy over `primary` 5h-tight, or `fallback` roomy over `fallback` 5h-tight). +- `normalizeModelGroupsConfig` validates and retains `tier` on route candidates, `sourceRoutes[].sources`, and `autoSources[id]`. +- `modelGroupResolveResultForRemote` downgrades new reasons for older peers while storing the true reason in `pickWhy`: `secondaryFallback` / `tierFallback` → `'order'`, `secondaryReserve` / `tierReserve` → `'standby'` (alongside existing `payg*` mappings); `modelGroupResolveResultFromRemote` restores `why` from recognized `pickWhy` and deletes `pickWhy`. + +## 3. Merged-Provider Routes (`src/model-groups.mjs`, `src/pick.mjs`) + +- `expandMergedSources` preserves an outer row's explicit `tier` on `via.tier`. +- Merged rows select an inner representative using each member's effective tier, then compete in the outer route at `via.tier` (fixed tier) if set or the representative's effective tier ("follow source") otherwise. +- When the row's representative is not picked in an `'expiring'` outer route and receives an outer `standby` reserve reason ranked higher (`paygReserve`/`tierReserve` = 2, `secondaryReserve` = 1) than a benched inner member's `standby` reason, the benched member inherits the outer reserve reason (mapping `paygReserve` → `tierReserve` for non-PAYG members). + +## 4. Per-Engine Tiering & Tier Controls (`src/resolver.mjs`, `src/provider-quota-source.mjs`) + +- `createModelGroupResolver` computes `defaultTier` per candidate using its `agentKind` (and sets `payAsYouGo = defaultTier === 'fallback'`), so mixed coding-plan/PAYG providers route each engine at its own tier. +- `resolveSourceDefaultTier(source, provider)`: returns the uniform default tier across `provider.agents`, or `undefined` ("follow source") when engines disagree. +- `resolveTierControlState({ value, defaultTier })`: returns `{ effective, showFollow, options }`; shows `'follow'` whenever `defaultTier === undefined` OR an explicit saved override `value` now equals `defaultTier` (preserving an explicit clear path). +- `applyTierControlSelection({ value, defaultTier }, next)`: no-op if `next === effective`; returns `undefined` when clearing to `'follow'` or matching default without `'follow'` shown; otherwise returns `next`. +- `retargetCandidateWithTier(previous, selected)`: preserves `previous.tier` only when `providerId`, `agentDeviceId`, and `accountId` are all unchanged; otherwise clears `tier`. + +## 5. Source Routes & Multi-Account Pool Isolation (`src/source-routes.mjs`) + +- `buildAutoSourceRoutes` stably orders default members by default tier rank before applying saved `autoSources` overrides. +- Exact `(providerId, accountId)` saved overrides apply to that exact account (including merged PAYG keys). Legacy whole-provider `{ providerId, tier }` overrides inherit ONLY onto subscription accounts (`!account.apiConnectionId`) in both `buildAutoSourceRoutes` and `flattenManualSourceRoute` — never onto merged PAYG API key pool members. +- `expandSourceRouteDetail` / `runnableProviderModels` propagates `source.tier` onto expanded candidates. + +## 6. Remote Catalog Redaction (`src/remote-catalog.mjs`) + +- `redactProviderCatalogForTunnel(result, { sameAccountController, readZhipuCodingPlanAccountUsage })`: + - Always strips untrusted incoming `zhipuCodingPlanUsage`, `zhipuCodingPlanUsageAgents`, `kimiCodingUsageAgents`, `opencodeGoUsageAgents` before recomputing. + - Emits `zhipuCodingPlanUsage: true` and per-engine `zhipuCodingPlanUsageAgents` ONLY when `sameAccountController && readZhipuCodingPlanAccountUsage` and the provider is active, remote-enabled, connected, API-key authenticated, and has at least one official GLM coding-plan engine route. + - Emits `kimiCodingUsageAgents` / `opencodeGoUsageAgents` per engine when non-empty, and projects `routing` for display without leaking `upstream` URLs or credentials. diff --git a/questions/smart-routing-three-tiers/v1/candidate/ENVIRONMENT.md b/questions/smart-routing-three-tiers/v1/candidate/ENVIRONMENT.md new file mode 100644 index 0000000..a837bde --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering core strategies, quota scheduling, and route display redaction diff --git a/questions/smart-routing-three-tiers/v1/candidate/TASK.md b/questions/smart-routing-three-tiers/v1/candidate/TASK.md new file mode 100644 index 0000000..c046f5f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/TASK.md @@ -0,0 +1,10 @@ +# Task + +Cindy's Smart Routing (`expiring` / Auto strategy) is being upgraded from a two-pool picker to a full three-tier priority model (`primary` / `secondary` / `fallback`), and production reports have surfaced several regressions across tier classification, merged routes, mixed coding-plan/PAYG providers, flattened multi-account pools, and remote catalog redaction. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and implement the complete three-tier Smart Routing behavior so every product invariant holds while preserving all existing non-auto strategies, image-capability filtering, within-tier scoring, and redaction privacy guarantees. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/smart-routing-three-tiers/v1/candidate/package.json b/questions/smart-routing-three-tiers/v1/candidate/package.json new file mode 100644 index 0000000..2586868 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-smart-routing-three-tiers", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/auto-usage-profile.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/auto-usage-profile.mjs new file mode 100644 index 0000000..5750a1e --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/auto-usage-profile.mjs @@ -0,0 +1,150 @@ +export const AUTO_USAGE_WINDOW_DAYS = 14; +const AUTO_USAGE_WINDOW_MS = AUTO_USAGE_WINDOW_DAYS * 86_400_000; +const MAX_PRIORITY_MODELS = 128; + +function localDayKey(ms) { + const d = new Date(ms); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +export function canonicalUsageModelId(model) { + const trimmed = String(model ?? '').trim().toLowerCase(); + if (!trimmed) return ''; + const slash = trimmed.lastIndexOf('/'); + return slash >= 0 && slash < trimmed.length - 1 ? trimmed.slice(slash + 1) : trimmed; +} + +export function autoUsageSourceKey(agentDeviceId, providerId) { + return `${agentDeviceId ?? ''}\u0000${providerId}`; +} + +export function autoUsageCandidateKey(agentDeviceId, providerId, model) { + return `${agentDeviceId ?? ''}\u0000${providerId}\u0000${canonicalUsageModelId(model)}`; +} + +function recencyDecay(ageMs) { + const days = Math.max(0, ageMs / 86_400_000); + if (days <= 3) return 1.0; + if (days <= 7) return 0.7; + if (days <= AUTO_USAGE_WINDOW_DAYS) return 0.4; + return 0; +} + +function sampleWeight(ageMs, tokens) { + const decay = recencyDecay(ageMs); + if (decay <= 0) return 0; + const safeTokens = Number.isFinite(tokens) && tokens > 0 ? tokens : 0; + const volumeBoost = safeTokens > 0 ? Math.min(3, Math.log10(1 + safeTokens / 10_000)) : 0; + return decay * (1 + volumeBoost); +} + +function addStats(map, key, weight, tokens, atMs) { + const existing = map.get(key); + if (existing) { + existing.weight += weight; + existing.sessions += 1; + existing.tokens += tokens; + if (atMs > existing.lastActiveAt) existing.lastActiveAt = atMs; + } else { + map.set(key, { weight, sessions: 1, tokens, lastActiveAt: atMs }); + } +} + +function computeModelPriorities(byModel) { + const modelEntries = [...byModel.entries()] + .filter(([, stats]) => stats.weight > 0) + .sort((a, b) => b[1].weight - a[1].weight || b[1].lastActiveAt - a[1].lastActiveAt) + .slice(0, MAX_PRIORITY_MODELS); + const topModelWeight = modelEntries[0]?.[1].weight ?? 0; + const modelPriorities = {}; + if (topModelWeight > 0) { + for (const [modelId, stats] of modelEntries) { + modelPriorities[modelId] = Math.max(0.001, Math.round((stats.weight / topModelWeight) * 1000) / 1000); + } + } + return modelPriorities; +} + +export function buildAutoUsageProfile(samples, nowMs) { + const cutoffMs = nowMs - AUTO_USAGE_WINDOW_MS; + const bySource = new Map(); + const byCandidate = new Map(); + const byModel = new Map(); + const sessionRoutes = new Map(); + const activeDayKeys = new Set(); + const weekdayKeys = new Set(); + const weekendKeys = new Set(); + + for (const sample of samples) { + if (!sample.providerId || !Number.isFinite(sample.atMs)) continue; + const providerId = sample.providerId.trim(); + const agentDeviceId = sample.agentDeviceId?.trim() || null; + if (sample.sessionId) { + sessionRoutes.set(sample.sessionId, { providerId, agentDeviceId }); + } + if (sample.atMs < cutoffMs || sample.atMs > nowMs + 60_000) continue; + const tokens = typeof sample.tokens === 'number' && Number.isFinite(sample.tokens) && sample.tokens > 0 ? sample.tokens : 0; + const weight = sampleWeight(nowMs - sample.atMs, tokens); + if (weight <= 0) continue; + + const dayKey = localDayKey(sample.atMs); + activeDayKeys.add(dayKey); + const dow = new Date(sample.atMs).getDay(); + if (dow === 0 || dow === 6) weekendKeys.add(dayKey); + else weekdayKeys.add(dayKey); + + const srcKey = autoUsageSourceKey(agentDeviceId, providerId); + addStats(bySource, srcKey, weight, tokens, sample.atMs); + + const canonicalModel = canonicalUsageModelId(sample.model); + if (canonicalModel) { + addStats(byCandidate, `${srcKey}\u0000${canonicalModel}`, weight, tokens, sample.atMs); + addStats(byModel, canonicalModel, weight, tokens, sample.atMs); + } + } + + return { + computedAtMs: nowMs, + activeDays: activeDayKeys.size, + weekdayActiveDays: weekdayKeys.size, + weekendActiveDays: weekendKeys.size, + bySource, + byCandidate, + byModel, + modelPriorities: computeModelPriorities(byModel), + sessionRoutes, + }; +} + +export function autoUsageCandidateWeight(profile, candidate) { + if (!profile) return 0; + const exact = profile.byCandidate.get(autoUsageCandidateKey(candidate.agentDeviceId, candidate.providerId, candidate.model))?.weight ?? 0; + const source = profile.bySource.get(autoUsageSourceKey(candidate.agentDeviceId, candidate.providerId))?.weight ?? 0; + if (exact <= 0 && source <= 0) return 0; + return exact * 0.7 + source * 0.3; +} + +export function effectiveRemainingTimeFactor(profile, nowMs, resetAtMs) { + if (!profile || profile.activeDays < 4 || resetAtMs === null || resetAtMs <= nowMs) return 1; + const remainingDays = (resetAtMs - nowMs) / 86_400_000; + if (remainingDays < 0.25 || remainingDays > 7.5) return 1; + const weekdayRate = profile.weekdayActiveDays / 10; + const weekendRate = profile.weekendActiveDays / 4; + const avgRate = (weekdayRate * 5 + weekendRate * 2) / 7; + if (avgRate <= 0.05) return 1; + + const steps = Math.max(1, Math.min(28, Math.ceil(remainingDays * 4))); + const stepMs = (resetAtMs - nowMs) / steps; + let expectedRateSum = 0; + for (let i = 0; i < steps; i += 1) { + const mid = nowMs + stepMs * (i + 0.5); + const dow = new Date(mid).getDay(); + expectedRateSum += dow === 0 || dow === 6 ? weekendRate : weekdayRate; + } + const remainingAvgRate = expectedRateSum / steps; + const ratio = remainingAvgRate / avgRate; + return Math.max(0.75, Math.min(1.25, ratio)); +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/model-groups.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/model-groups.mjs new file mode 100644 index 0000000..bab46fe --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/model-groups.mjs @@ -0,0 +1,231 @@ +export const MODEL_GROUP_AUTO_PREFIX = 'auto:'; +export const MODEL_GROUP_EXPANDED_PREFIX = 'src:'; +export const MODEL_GROUP_LIMITS = { + id: 80, + name: 80, + candidates: 32, + routes: 64, + effort: 32, + deviceId: 128, + accountId: 128, +}; + +export const MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']; + +export function modelGroupTier(value) { + return value === 'primary' || value === 'secondary' || value === 'fallback' ? value : undefined; +} + +export function modelGroupTierRank(tier) { + if (tier === 'primary') return 0; + if (tier === 'secondary') return 1; + return 2; +} + +export function modelGroupWeight(value) { + const n = typeof value === 'number' ? Math.floor(value) : NaN; + return Number.isFinite(n) && n >= 1 ? Math.min(1000, n) : 1; +} + +export function modelGroupCandidateKey(candidate) { + const base = `${candidate.agentKind}\u0000${candidate.providerId}\u0000${candidate.model}`; + const loc = candidate.agentDeviceId ? `\u0000@${candidate.agentDeviceId}` : ''; + const acct = candidate.accountId ? `\u0000#${candidate.accountId}` : ''; + const merged = candidate.merged ? `\u0000M:${candidate.merged.id}\u0000${candidate.merged.model}` : ''; + return `${base}${loc}${acct}${merged}`; +} + +export function modelGroupCandidateBaseKey(key) { + return key.replace(/\u0000#[^\u0000]+/, ''); +} + +export function modelGroupCandidateRowKey(candidate) { + return candidate.via?.key ?? modelGroupCandidateKey(candidate); +} + +export function modelGroupSourceKey(source) { + const loc = source.agentDeviceId ? `\u0000@${source.agentDeviceId}` : ''; + const acct = source.accountId ? `\u0000#${source.accountId}` : ''; + return `${source.providerId}${loc}${acct}`; +} + +const LEGACY_WHY = { + drain: 'order', + drainNext: 'order', + headroom: 'expiring', + weighted: 'rotate', + usageHabit: 'expiring', + autoBalance: 'expiring', + lessBusy: 'expiring', + paygFallback: 'order', + paygReserve: 'standby', +}; + +function legacyWhy(entry) { + const legacy = LEGACY_WHY[entry.why]; + return legacy ? { ...entry, why: legacy, pickWhy: entry.why } : entry; +} + +function realWhy(entry) { + const { pickWhy, ...rest } = entry; + const known = typeof pickWhy === 'string' && Object.hasOwn(LEGACY_WHY, pickWhy); + return known ? { ...rest, why: pickWhy } : rest; +} + +export function modelGroupResolveResultForRemote(result) { + const trace = (result.trace ?? []).map(legacyWhy); + return result.outcome === 'routed' ? { ...legacyWhy(result), trace } : { ...result, trace }; +} + +export function modelGroupResolveResultFromRemote(result) { + const trace = (result.trace ?? []).map(realWhy); + return result.outcome === 'routed' ? { ...realWhy(result), trace } : { ...result, trace }; +} + +function text(value, max) { + if (typeof value !== 'string') return ''; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= max ? trimmed : ''; +} + +function normalizeCandidate(raw) { + if (!raw || typeof raw !== 'object') return null; + const agentKind = ['cc', 'codex', 'pi', 'acp'].includes(raw.agentKind) ? raw.agentKind : null; + const providerId = text(raw.providerId, MODEL_GROUP_LIMITS.id); + const model = text(raw.model, 160); + if (!agentKind || !providerId || !model) return null; + const agentDeviceId = raw.agentDeviceId ? text(raw.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const accountId = raw.accountId ? text(raw.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const weight = modelGroupWeight(raw.weight); + const effort = text(raw.effort, MODEL_GROUP_LIMITS.effort); + const mergedRaw = raw.merged && typeof raw.merged === 'object' ? raw.merged : null; + const mergedId = mergedRaw ? text(mergedRaw.id, MODEL_GROUP_LIMITS.id) : ''; + const mergedModel = mergedRaw ? text(mergedRaw.model, 160) : ''; + return { + agentKind, + providerId, + model, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + ...(mergedId && mergedModel ? { merged: { id: mergedId, model: mergedModel } } : {}), + ...(raw.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(effort ? { effort } : {}), + }; +} + +function normalizeSources(raw) { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const out = []; + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const providerId = text(entry.providerId, MODEL_GROUP_LIMITS.id); + if (!providerId) continue; + const location = entry.agentDeviceId ? text(entry.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const account = entry.accountId ? text(entry.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const key = modelGroupSourceKey({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + }); + if (seen.has(key)) continue; + seen.add(key); + const weight = modelGroupWeight(entry.weight); + out.push({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + ...(entry.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(entry.sameModelsOnly === true ? { sameModelsOnly: true } : {}), + }); + } + return out.slice(0, MODEL_GROUP_LIMITS.candidates); +} + +export function normalizeModelGroupsConfig(raw) { + if (!raw || typeof raw !== 'object') return { routes: [] }; + const routes = Array.isArray(raw.routes) + ? raw.routes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + candidates: Array.isArray(r.candidates) ? r.candidates.map(normalizeCandidate).filter(Boolean) : [], + })) + : []; + const sourceRoutes = Array.isArray(raw.sourceRoutes) + ? raw.sourceRoutes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + sources: normalizeSources(r.sources), + })) + : []; + const autoSources = raw.autoSources && typeof raw.autoSources === 'object' + ? Object.fromEntries( + Object.entries(raw.autoSources) + .filter(([id]) => id.startsWith(MODEL_GROUP_AUTO_PREFIX)) + .map(([id, list]) => [id, normalizeSources(list)]) + .filter(([, list]) => list.length > 0), + ) + : {}; + return { + routes, + ...(sourceRoutes.length > 0 ? { sourceRoutes } : {}), + ...(Object.keys(autoSources).length > 0 ? { autoSources } : {}), + ...(raw.autoStrategy ? { autoStrategy: raw.autoStrategy } : {}), + ...(raw.hiddenAuto ? { hiddenAuto: raw.hiddenAuto } : {}), + }; +} + +export function expandMergedSources(route, config) { + if (route.parent || !route.candidates.some((candidate) => candidate.merged)) return route; + const seen = new Set(); + const localPools = new Set(); + const localAccounts = new Set(); + const out = []; + const push = (candidate) => { + const key = modelGroupCandidateKey(candidate); + if (seen.has(key)) return; + if (!candidate.agentDeviceId && !candidate.merged) { + const baseKey = modelGroupCandidateBaseKey(key); + if (candidate.accountId) { + if (localPools.has(baseKey)) return; + localAccounts.add(baseKey); + } else { + if (localAccounts.has(baseKey)) return; + localPools.add(baseKey); + } + } + seen.add(key); + out.push(candidate); + }; + for (const candidate of route.candidates) { + const { merged, ...row } = candidate; + if (!merged) { + push(candidate); + continue; + } + const owner = (config.sourceRoutes ?? []).find((item) => item.id === merged.id); + const child = config.routes.find((item) => item.parent?.id === merged.id && (item.parent.model ?? item.id) === merged.model); + if (!owner || !child || child.candidates.length === 0) { + push({ ...candidate, off: true }); + continue; + } + const via = { + key: modelGroupCandidateKey(candidate), + strategy: child.strategy, + name: owner.name, + ...(row.weight !== undefined ? { weight: row.weight } : {}), + }; + for (const member of child.candidates) { + const { merged: _nested, via: _via, ...plain } = member; + const effort = row.effort ?? member.effort; + push({ ...plain, ...(row.off || member.off ? { off: true } : {}), ...(effort ? { effort } : {}), via }); + } + } + return { ...route, candidates: out }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/pick.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/pick.mjs new file mode 100644 index 0000000..9622a10 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/pick.mjs @@ -0,0 +1,367 @@ +import { + modelGroupCandidateKey, + modelGroupCandidateRowKey, + modelGroupWeight, +} from './model-groups.mjs'; +import { pickRouteMember, PROVIDER_GROUP_SIMILAR_URGENCY } from './scheduler.mjs'; +import { FIVE_HOURS_MS, quotaWindowsScheduleState } from './usage.mjs'; +import { + autoUsageCandidateWeight, + effectiveRemainingTimeFactor, +} from './auto-usage-profile.mjs'; + +export function modelGroupHeadroom(windows, now) { + const live = (windows ?? []).filter((window) => window.resetAtMs === null || window.resetAtMs > now); + const long = live.filter((window) => window.windowMs > FIVE_HOURS_MS); + let tightest = null; + for (const window of long.length > 0 ? long : live) { + const left = Math.max(0, 100 - window.usedPercent); + if (!tightest || left < tightest.left) tightest = { left, window }; + } + return tightest; +} + +function keepsCurrent(strategy, keep, picked, facts) { + switch (strategy) { + case 'rotate': + case 'weighted': + case 'drain': + return true; + case 'cheapest': + return costOf(facts[keep.index]) <= costOf(facts[picked.index]); + case 'headroom': + if (picked.headroom === null) return true; + return keep.headroom !== null && picked.headroom - keep.headroom < KEEP_HEADROOM_GAP; + default: + return false; + } +} + +function costOf(fact) { + if (fact?.windows) return 0; + return typeof fact?.price === 'number' && Number.isFinite(fact.price) && fact.price >= 0 + ? fact.price + : Number.POSITIVE_INFINITY; +} + +const AUTO_EXPIRING_SURPLUS_URGENCY = 2.0; +const AUTO_UNKNOWN_QUOTA_SCORE = 0.85; +const AUTO_USAGE_MAX_BONUS = 0.45; +const AUTO_USAGE_FULL_CONFIDENCE = 2.5; +const AUTO_RUNNING_PENALTY = 0.30; +const AUTO_SOFT_ROTATE_GAP = 0.06; +const AUTO_KEEP_QUOTA_GAP = 0.25; +const KEEP_HEADROOM_GAP = 20; + +function nextAutoCandidate(band, lastPickedKey) { + const previous = band.findIndex(({ row }) => row.key === lastPickedKey); + return band[(previous + 1) % band.length]; +} + +function pickAutoCandidate(ready, usable, options) { + const { now, lastPickedKey, usageProfile } = options; + const keep = options.keepKey ? ready.find((row) => row.key === options.keepKey) : undefined; + const nonPayg = ready.filter((row) => !row.payAsYouGo); + const nonTightNonPayg = nonPayg.filter((row) => !row.tight); + + // Legacy two-pool fallback: non-tight non-PAYG vs tight non-PAYG vs PAYG + if (nonTightNonPayg.length === 0) { + if (nonPayg.length > 0) { + if (keep && !keep.payAsYouGo) return { picked: keep, why: 'autoBalance' }; + const scored = nonPayg.map((row) => ({ + row, + urgency: row.urgency ?? AUTO_UNKNOWN_QUOTA_SCORE, + })); + const best = scored.reduce((top, cur) => { + if (!options.keepKey && cur.row.running !== top.row.running) { + return cur.row.running < top.row.running ? cur : top; + } + return cur.urgency > top.urgency ? cur : top; + }); + const why = best.row.urgency !== null ? 'expiring' : 'autoBalance'; + return { picked: best.row, why }; + } + if (keep) return { picked: keep, why: 'paygFallback' }; + const bestPayg = ready.reduce((top, cur) => (cur.running < top.running ? cur : top)); + const hadNonPayg = usable.some((row) => !row.payAsYouGo); + return { picked: bestPayg, why: hadNonPayg ? 'paygFallback' : 'order' }; + } + + const primary = nonTightNonPayg; + const enriched = primary.map((row) => { + const timeFactor = row.urgency !== null + ? effectiveRemainingTimeFactor(usageProfile, now, row.quota?.resetAtMs ?? null) + : 1; + const effectiveUrgency = row.urgency !== null ? row.urgency / timeFactor : null; + const isExpiringSurplus = effectiveUrgency !== null && effectiveUrgency >= AUTO_EXPIRING_SURPLUS_URGENCY; + const usageWeight = autoUsageCandidateWeight(usageProfile, row.candidate); + return { row, effectiveUrgency, isExpiringSurplus, usageWeight }; + }); + + const expiring = enriched.filter((item) => item.isExpiringSurplus); + if (expiring.length > 0) { + const topUrgency = Math.max(...expiring.map((item) => item.effectiveUrgency)); + const band = expiring.filter((item) => item.effectiveUrgency >= topUrgency * PROVIDER_GROUP_SIMILAR_URGENCY); + const byUrgency = [...band].sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index)[0]; + if (options.keepKey) { + const kept = band.find((item) => item.row === keep); + return { picked: (kept ?? byUrgency).row, why: 'expiring' }; + } + const minRunning = Math.min(...band.map((item) => item.row.running)); + const idleBand = band.filter((item) => item.row.running === minRunning); + const topUsage = Math.max(...idleBand.map((item) => item.usageWeight)); + const rotationBand = idleBand + .filter((item) => topUsage - item.usageWeight <= 0.05) + .sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + let why = 'expiring'; + if (byUrgency.row !== winner.row && byUrgency.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + idleBand.length > 1 + && winner.usageWeight >= 0.5 + && topUsage - byUrgency.usageWeight > 0.05 + ) { + why = 'usageHabit'; + } + return { picked: winner.row, why }; + } + + const totalUsageWeight = enriched.reduce((sum, item) => sum + item.usageWeight, 0); + const confidence = totalUsageWeight > 0 ? Math.min(1, totalUsageWeight / AUTO_USAGE_FULL_CONFIDENCE) : 0; + const scored = enriched.map((item) => { + const quotaScore = item.effectiveUrgency !== null + ? item.effectiveUrgency <= 1.0 + ? Math.max(0.05, item.effectiveUrgency) + : 1.0 + Math.min(1.0, item.effectiveUrgency - 1.0) * 0.12 + : AUTO_UNKNOWN_QUOTA_SCORE; + const usageShare = totalUsageWeight > 0 ? item.usageWeight / totalUsageWeight : 0; + const usageBonus = AUTO_USAGE_MAX_BONUS * confidence * usageShare; + const busyPenalty = item.row.running * AUTO_RUNNING_PENALTY; + const baseScore = quotaScore + usageBonus; + const totalScore = baseScore - busyPenalty; + return { ...item, quotaScore, usageBonus, busyPenalty, baseScore, totalScore }; + }); + + if (options.keepKey) { + const best = scored.reduce((top, item) => (item.quotaScore > top.quotaScore ? item : top)); + const kept = scored.find((item) => item.row === keep); + const winner = kept && best.quotaScore - kept.quotaScore <= AUTO_KEEP_QUOTA_GAP ? kept : best; + return { picked: winner.row, why: winner.effectiveUrgency === null ? 'autoBalance' : 'expiring' }; + } + + const sorted = [...scored].sort((a, b) => b.totalScore - a.totalScore || a.row.index - b.row.index); + const [leader] = sorted; + const rotationBand = sorted.filter((item) => leader.totalScore - item.totalScore <= AUTO_SOFT_ROTATE_GAP + && item.row.running <= leader.row.running); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + const rotated = winner !== leader; + const bestWithoutBusy = scored.reduce((top, cur) => (cur.baseScore > top.baseScore ? cur : top)); + const bestWithoutUsage = scored.reduce((top, cur) => + (cur.quotaScore - cur.busyPenalty) > (top.quotaScore - top.busyPenalty) ? cur : top); + const secondUsageBonus = Math.max(0, ...scored.filter((item) => item !== winner).map((item) => item.usageBonus)); + + let why; + if (bestWithoutBusy !== winner && bestWithoutBusy.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + winner.usageBonus >= 0.08 + && (bestWithoutUsage !== winner || winner.usageBonus >= secondUsageBonus + 0.05) + ) { + why = 'usageHabit'; + } else if ( + rotated + || (winner.effectiveUrgency === null && scored.some((item) => item.effectiveUrgency !== null && item.effectiveUrgency < AUTO_UNKNOWN_QUOTA_SCORE)) + ) { + why = 'autoBalance'; + } else if (scored.every((item) => item.effectiveUrgency === null) && totalUsageWeight === 0) { + why = 'order'; + } else if (winner.effectiveUrgency === null) { + why = 'autoBalance'; + } else { + why = 'expiring'; + } + return { picked: winner.row, why }; +} + +export function pickModelGroupCandidate(route, facts, options) { + const { now } = options; + const anyVision = !!options.needsImage && route.candidates.some((candidate, index) => + !candidate.off && facts[index]?.available === true && facts[index]?.acceptsImage === true); + const rows = route.candidates.map((candidate, index) => { + const fact = facts[index]; + const state = fact?.windows ? quotaWindowsScheduleState(fact.windows, now) : null; + const outerUsesHeadroom = route.strategy === 'headroom'; + const innerUsesHeadroom = candidate.via?.strategy === 'headroom'; + const headroom = outerUsesHeadroom || innerUsesHeadroom ? modelGroupHeadroom(fact?.windows ?? null, now) : null; + const remaining = fact?.inner ? fact.inner.headroom : headroom?.left ?? null; + const quota = headroom?.window ?? state?.quota ?? null; + const running = typeof fact?.running === 'number' && Number.isFinite(fact.running) && fact.running > 0 + ? Math.floor(fact.running) + : 0; + return { + candidate, + index, + key: modelGroupCandidateKey(candidate), + noVision: anyVision && fact?.acceptsImage !== true, + usable: !candidate.off && fact?.available === true && !(anyVision && fact?.acceptsImage !== true), + limited: fact?.inner ? fact.inner.limited : state?.limited ?? false, + limitedUntilMs: fact?.inner ? null : state?.resetAtMs ?? null, + tight: fact?.inner ? fact.inner.fiveHourTight : state?.fiveHourTight ?? false, + urgency: fact?.inner ? fact.inner.urgency : state?.urgency ?? null, + quota, + headroom: outerUsesHeadroom ? remaining : null, + weight: modelGroupWeight(candidate.via ? candidate.via.weight : candidate.weight), + group: candidate.via?.key ?? null, + innerHeadroom: innerUsesHeadroom ? remaining : null, + payAsYouGo: fact?.payAsYouGo === true && quota === null && !fact?.inner, + running, + }; + }); + + const benched = new Set(); + const innerWhy = new Map(); + const groupSize = new Map(); + const groups = new Map(); + for (const row of rows) if (row.group) groups.set(row.group, [...(groups.get(row.group) ?? []), row]); + for (const [group, members] of groups) { + const inUsable = members.filter((row) => row.usable); + const inReady = inUsable.filter((row) => !row.limited); + groupSize.set(group, inUsable.length); + if (inReady.length === 0) continue; + const strategy = members[0].candidate.via.strategy; + let winner = inReady[0]; + let reason = strategy; + if (strategy === 'expiring') { + const auto = pickAutoCandidate(inReady, inUsable, { + now, + lastPickedKey: options.lastPickedKey, + usageProfile: options.usageProfile, + keepKey: options.keepKey, + }); + winner = auto.picked; + reason = auto.why; + } else { + const result = pickRouteMember(members.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: row.key, + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: modelGroupWeight(row.candidate.weight), + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.innerHeadroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), strategy, { lastPicked: options.lastPickedKey ?? null }); + winner = inReady.find((row) => row.key === result.key) ?? inReady[0]; + const keep = options.keepKey ? inReady.find((row) => row.key === options.keepKey) : undefined; + if (keep && keep !== winner && keepsCurrent( + strategy, + { index: keep.index, headroom: keep.innerHeadroom }, + { index: winner.index, headroom: winner.innerHeadroom }, + facts, + )) winner = keep; + if (result.plain) reason = 'order'; + } + innerWhy.set(group, reason); + for (const row of members) if (row !== winner) benched.add(row.index); + } + + const entryKey = (row) => modelGroupCandidateRowKey(row.candidate); + const lastRow = options.lastPickedKey ? rows.find((row) => row.key === options.lastPickedKey) : undefined; + const outerLast = options.lastPickedRowKey ?? (lastRow ? entryKey(lastRow) : options.lastPickedKey ?? null); + const usable = rows.filter((row) => row.usable && !benched.has(row.index)); + const ready = usable.filter((row) => !row.limited); + const current = options.keepKey ? rows.find((row) => row.key === options.keepKey) : undefined; + const keep = current ? ready.find((row) => entryKey(row) === entryKey(current)) : undefined; + + let picked = null; + let why = 'only'; + let weightStep; + let strategyWhy = route.strategy; + if (ready.length > 0) { + if (route.strategy === 'expiring') { + const auto = pickAutoCandidate(ready, usable, { + now, + lastPickedKey: ready.find((row) => entryKey(row) === outerLast)?.key, + usageProfile: options.usageProfile, + keepKey: keep?.key ?? options.keepKey, + }); + picked = auto.picked; + strategyWhy = auto.why; + why = usable.length === 1 ? 'only' : strategyWhy; + } else { + const entries = rows.filter((row) => !benched.has(row.index) + && (!row.group || innerWhy.has(row.group) || row === groups.get(row.group)[0])); + const result = pickRouteMember(entries.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: entryKey(row), + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: row.weight, + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.headroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), route.strategy, { lastPicked: outerLast, weightCounters: options.weightCounters }); + picked = ready.find((row) => entryKey(row) === result.key) ?? ready[0]; + weightStep = result.weightStep; + if (keep && keep !== picked && keepsCurrent(route.strategy, keep, picked, facts)) { + picked = keep; + weightStep = undefined; + } + if (result.plain) strategyWhy = 'order'; + else if (route.strategy === 'drain' && entryKey(picked) !== outerLast && entries.some((row) => entryKey(row) === outerLast)) { + strategyWhy = 'drainNext'; + } + why = usable.length === 1 ? 'only' : strategyWhy; + if (why === 'cheapest') { + const cost = costOf(facts[picked.index]); + why = cost === 0 && facts[picked.index]?.windows ? 'cheapestFree' : Number.isFinite(cost) ? 'cheapest' : 'order'; + } + } + } else if (usable.length > 0) { + picked = usable.reduce((best, row) => + (row.limitedUntilMs ?? Number.POSITIVE_INFINITY) < (best.limitedUntilMs ?? Number.POSITIVE_INFINITY) ? row : best); + why = usable.length === 1 ? 'only' : 'soonest'; + } + + if (picked?.group && why === 'only' && (groupSize.get(picked.group) ?? 0) > 1) why = innerWhy.get(picked.group) ?? why; + + const trace = rows.map((row) => { + const fact = facts[row.index]; + const base = { + agentKind: row.candidate.agentKind, + providerId: row.candidate.providerId, + model: row.candidate.model, + ...(row.candidate.agentDeviceId ? { agentDeviceId: row.candidate.agentDeviceId } : {}), + ...(row.candidate.accountId ? { accountId: row.candidate.accountId } : {}), + modelName: fact?.modelName || row.candidate.model, + sourceName: fact?.sourceName || row.candidate.providerId, + quota: row.quota, + }; + if (row === picked) return { ...base, state: 'picked', why, ...(row.limited ? { limitedUntilMs: row.limitedUntilMs } : {}) }; + if (row.candidate.off) return { ...base, state: 'skipped', why: 'off' }; + if (fact?.available !== true) return { ...base, state: 'skipped', why: 'unavailable' }; + if (row.noVision) return { ...base, state: 'skipped', why: 'noVision' }; + if (row.limited) return { ...base, state: 'skipped', why: 'limited', limitedUntilMs: row.limitedUntilMs }; + if (row.tight && route.strategy === 'expiring' && ready.some((other) => !other.tight)) return { ...base, state: 'skipped', why: 'tight' }; + if (row.payAsYouGo && route.strategy === 'expiring' && ready.some((other) => !other.payAsYouGo)) return { ...base, state: 'standby', why: 'paygReserve' }; + return { ...base, state: 'standby', why: 'standby' }; + }); + + return { + index: picked?.index ?? null, + trace, + ...(options.needsImage ? { image: anyVision ? 'applied' : 'fallback' } : {}), + ...(weightStep ? { weightStep } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/provider-identity.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/provider-identity.mjs new file mode 100644 index 0000000..84156b4 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/provider-identity.mjs @@ -0,0 +1,107 @@ +export const PLUGIN_ENGINE_PROVIDER_PREFIX = 'acp-plugin:'; +export const PROVIDER_SHARE_AGENT_DEVICE_PREFIX = 'share:'; + +export function isByokProviderId(value) { + return typeof value === 'string' && /^byok-[a-z0-9][a-z0-9-]{0,185}$/.test(value); +} + +export function isOrganizationManagedProvider(provider) { + return provider?.source === 'organization'; +} + +export function isProviderShareAgentDeviceId(value) { + return typeof value === 'string' && value.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX); +} + +export function pluginEngineKeyFromProviderId(providerId) { + if (!providerId || !providerId.startsWith(PLUGIN_ENGINE_PROVIDER_PREFIX)) return null; + const key = providerId.slice(PLUGIN_ENGINE_PROVIDER_PREFIX.length); + const separator = key.lastIndexOf(':'); + return separator > 0 && separator < key.length - 1 ? key : null; +} + +/** Exact product scope, not brand/name matching. Never send a proxy's credential to Kimi. */ +export function kimiCodingUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (!['https://api.kimi.com', 'https://api.kimi.ai'].includes(url.origin)) return null; + if (!['/coding', '/coding/', '/coding/v1', '/coding/v1/'].includes(url.pathname)) return null; + return `${url.origin}/coding/v1/usages`; + } catch { + return null; + } +} + +export function isKimiCodingProvider(provider, agent) { + if (!provider || !['apiKey', 'oauth'].includes(provider.auth?.method)) return false; + if ( + provider.auth.method === 'oauth' + && !['https://auth.kimi.com/api/oauth/token', 'https://auth.kimi.ai/api/oauth/token'].includes( + provider.auth.oauth?.tokenUrl ?? '', + ) + ) { + return false; + } + return (agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {})).some( + (route) => route && !route.disabled && kimiCodingUsageEndpoint(route.upstream) !== null, + ); +} + +export function isKimiCodingProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.kimiCodingUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isKimiCodingProvider(provider, agent); +} + +/** Resolve only OpenCode Go's official inference route, never a user proxy. */ +export function opencodeGoUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (url.origin !== 'https://opencode.ai') return null; + if (!['/zen/go', '/zen/go/v1'].includes(url.pathname.replace(/\/+$/, ''))) return null; + return 'https://opencode.ai/zen/go/v1/usage'; + } catch { + return null; + } +} + +export function isOpenCodeGoProvider(provider, agent) { + if (!provider || provider.auth?.method !== 'apiKey') return false; + const routes = agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {}); + return routes.some( + (route) => route && !route.disabled && opencodeGoUsageEndpoint(route.upstream) !== null, + ); +} + +export function isOpenCodeGoProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.opencodeGoUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isOpenCodeGoProvider(provider, agent); +} + +export const ZHIPU_CODING_PLAN_ORIGINS = ['https://open.bigmodel.cn', 'https://api.z.ai']; + +export function isZhipuCodingPlanPath(pathname) { + return pathname === '/api/anthropic' || pathname.startsWith('/api/anthropic/') || pathname.startsWith('/api/coding/'); +} + +export function isZhipuCodingPlanRoute(route) { + if (!route?.upstream || route.disabled) return false; + let url; + try { + url = new URL(route.upstream); + } catch { + return false; + } + return ZHIPU_CODING_PLAN_ORIGINS.includes(url.origin) && isZhipuCodingPlanPath(url.pathname); +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/provider-quota-source.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/provider-quota-source.mjs new file mode 100644 index 0000000..07ac22f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/provider-quota-source.mjs @@ -0,0 +1,79 @@ +import { MODEL_GROUP_TIERS } from './model-groups.mjs'; +import { + isKimiCodingProviderView, + isOpenCodeGoProviderView, + isZhipuCodingPlanRoute, +} from './provider-identity.mjs'; + +export function isPayAsYouGoProvider(provider) { + return provider?.access?.kind === 'api' || provider?.id === 'xd'; +} + +export function isZhipuCodingPlanProviderView(view) { + if (!view || view.auth?.method !== 'apiKey') return false; + return view.zhipuCodingPlanUsage === true || Object.values(view.routing ?? {}).some(isZhipuCodingPlanRoute); +} + +/** + * Legacy pre-3-tier classifier: only splits personal pay-as-you-go (fallback) from everything else (primary). + */ +export function defaultModelGroupSourceTier(input) { + if (input.accountPayAsYouGo) return 'fallback'; + const view = input.provider ?? null; + if (view) { + if (isKimiCodingProviderView(view) || isOpenCodeGoProviderView(view) || isZhipuCodingPlanProviderView(view)) { + return 'primary'; + } + if (isPayAsYouGoProvider(view)) return 'fallback'; + } + if (input.providerId === 'xd') return 'fallback'; + return 'primary'; +} + +/** + * Resolve the single default tier shown for a source row. + * Pre-fix naive version computes only the provider-wide summary without checking per-engine disagreement. + */ +export function resolveSourceDefaultTier(source, provider) { + return defaultModelGroupSourceTier({ + agentKind: source.agentKind, + providerId: source.providerId, + agentDeviceId: source.agentDeviceId, + provider, + accountPayAsYouGo: source.accountPayAsYouGo, + }); +} + +/** + * Compute select control state for a source row's tier dropdown. + */ +export function resolveTierControlState({ value, defaultTier }) { + const effective = value ?? defaultTier ?? 'primary'; + return { + effective, + showFollow: false, + options: [...MODEL_GROUP_TIERS], + }; +} + +/** + * Apply a user's selection in the tier dropdown and return the persisted `tier` field (`undefined` clears override). + */ +export function applyTierControlSelection({ value, defaultTier }, next) { + const state = resolveTierControlState({ value, defaultTier }); + if (next === state.effective) return value; + return next === defaultTier ? undefined : next; +} + +/** + * Retarget a custom-route candidate row when the user edits its model/source. + */ +export function retargetCandidateWithTier(previous, selected) { + return { + ...selected, + ...(previous.off ? { off: previous.off } : {}), + ...(previous.weight !== undefined ? { weight: previous.weight } : {}), + ...(previous.tier ? { tier: previous.tier } : {}), + ...(previous.effort ? { effort: previous.effort } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/remote-catalog.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/remote-catalog.mjs new file mode 100644 index 0000000..230886d --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/remote-catalog.mjs @@ -0,0 +1,90 @@ +import { + isKimiCodingProvider, + isOpenCodeGoProvider, + isZhipuCodingPlanRoute, +} from './provider-identity.mjs'; + +const VALID_WIRE_PROTOCOLS = new Set([ + 'openai-chat', + 'openai-responses', + 'google-generative-ai', + 'anthropic-messages', +]); + +export function projectRoutingForDisplay(routing) { + if (!routing || typeof routing !== 'object' || Array.isArray(routing)) return undefined; + const out = {}; + for (const [agent, value] of Object.entries(routing)) { + const route = value && typeof value === 'object' && !Array.isArray(value) ? value : null; + const wireProtocol = VALID_WIRE_PROTOCOLS.has(route?.wireProtocol) + ? route.wireProtocol + : route?.authStrategy && route.wireProtocol === undefined + ? agent === 'codex' + ? 'openai-responses' + : agent === 'claude-code' + ? 'anthropic-messages' + : undefined + : undefined; + out[agent] = { + ...(wireProtocol ? { wireProtocol } : {}), + ...(route?.disabled === true ? { disabled: true } : {}), + }; + } + return out; +} + +/** + * Redact a provider list payload before returning it over the remote device-link tunnel. + * Pre-PR #15050 version: omits per-engine `zhipuCodingPlanUsageAgents` and does not strip stored `zhipuCodingPlanUsageAgents`. + */ +export function redactProviderCatalogForTunnel(result, options = {}) { + if (!result || typeof result !== 'object' || !Array.isArray(result.providers)) return result; + const { + sameAccountController = false, + readZhipuCodingPlanAccountUsage = true, + } = options; + const runtimeAgents = ['claude-code', 'codex', 'pi']; + + const providers = result.providers.map((p) => { + const rest = { ...p }; + delete rest.runLocation; + if (!sameAccountController) { + delete rest.subscriptionPoolTarget; + delete rest.subscriptionAccountKeys; + if (rest.openAiAccount && typeof rest.openAiAccount === 'object') { + const { accountKey: _key, ...account } = rest.openAiAccount; + rest.openAiAccount = account; + } + } + delete rest.remoteInvocationEnabled; + if (typeof p.remoteInvocationEnabled === 'boolean') rest.remoteInvocationEnabled = p.remoteInvocationEnabled; + + delete rest.zhipuCodingPlanUsage; + if ( + sameAccountController + && readZhipuCodingPlanAccountUsage + && p.remoteInvocationEnabled === true + && p.connected && !p.suspended && !p.removed + && p.auth?.method === 'apiKey' + && Object.values(p.routing ?? {}).some(isZhipuCodingPlanRoute) + ) { + rest.zhipuCodingPlanUsage = true; + } + + delete rest.kimiCodingUsageAgents; + const kimiAgents = runtimeAgents.filter((agent) => isKimiCodingProvider(p, agent)); + if (kimiAgents.length > 0) rest.kimiCodingUsageAgents = kimiAgents; + + delete rest.opencodeGoUsageAgents; + const opencodeGoAgents = runtimeAgents.filter((agent) => isOpenCodeGoProvider(p, agent)); + if (opencodeGoAgents.length > 0) rest.opencodeGoUsageAgents = opencodeGoAgents; + + rest.routing = projectRoutingForDisplay(p.routing); + return rest; + }); + + return { + ...result, + providers, + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/resolver.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/resolver.mjs new file mode 100644 index 0000000..cce6f9d --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/resolver.mjs @@ -0,0 +1,105 @@ +import { expandMergedSources } from './model-groups.mjs'; +import { pickModelGroupCandidate } from './pick.mjs'; +import { isProviderShareAgentDeviceId, pluginEngineKeyFromProviderId } from './provider-identity.mjs'; +import { isPayAsYouGoProvider } from './provider-quota-source.mjs'; +import { effectiveModelGroupsConfig } from './source-routes.mjs'; + +const AGENT_FOR_KIND = { cc: 'claude-code', codex: 'codex', pi: 'pi' }; + +export function createModelGroupResolver(deps) { + const now = deps.now ?? Date.now; + + async function resolve(request) { + const rawConfig = deps.config(); + const views = await deps.views(); + const agents = deps.agents ? deps.agents() : ['claude-code', 'codex', 'pi']; + const effectiveConfig = deps.catalog + ? effectiveModelGroupsConfig(rawConfig, deps.catalog(views, agents)) + : rawConfig; + + const rawRoute = (effectiveConfig.routes ?? []).find((r) => r.id === request.selection?.id); + if (!rawRoute) { + return { outcome: 'unavailable', reason: 'route_not_found', trace: [] }; + } + const route = expandMergedSources(rawRoute, effectiveConfig); + const windowsMap = deps.quotaWindows ? await deps.quotaWindows() : new Map(); + const usageProfile = deps.usageProfile ? deps.usageProfile() : null; + + const facts = await Promise.all(route.candidates.map(async (candidate) => { + const agentDeviceId = candidate.agentDeviceId ?? null; + const isAcp = candidate.agentKind === 'acp' || pluginEngineKeyFromProviderId(candidate.providerId) !== null; + if (isAcp) { + const engine = deps.pluginEngines ? (await deps.pluginEngines()).find((e) => e.providerId === candidate.providerId) : null; + const available = engine ? !engine.suspended && engine.availability?.state !== 'unavailable' : false; + const windows = windowsMap.get(candidate.providerId) ?? null; + return { + available, + modelName: candidate.model, + sourceName: engine?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + acceptsImage: true, + }; + } + + const locationViews = agentDeviceId && deps.remoteViews + ? (await deps.remoteViews(agentDeviceId)) + : views; + const view = locationViews.find((v) => v.id === candidate.providerId) ?? null; + const agent = AGENT_FOR_KIND[candidate.agentKind]; + const modelEntry = view?.models?.[agent]?.find((m) => m.id === candidate.model) ?? null; + const installed = deps.harnessInstalled ? await deps.harnessInstalled(agent, agentDeviceId) : true; + const accountFact = !agentDeviceId && candidate.accountId && deps.localAccount + ? deps.localAccount(candidate.providerId, candidate.accountId, candidate.model, candidate.agentKind) + : null; + const available = Boolean( + view && view.connected && !view.suspended && !view.removed + && installed + && modelEntry && !modelEntry.disabled + && (!accountFact || accountFact.usable !== false), + ); + const isShare = !!agentDeviceId && isProviderShareAgentDeviceId(agentDeviceId); + const payAsYouGo = accountFact?.payAsYouGo ?? (!isShare && isPayAsYouGoProvider(view)); + const keyForQuota = candidate.accountId ? `${candidate.providerId}#${candidate.accountId}` : candidate.providerId; + const windows = accountFact?.windows ?? windowsMap.get(keyForQuota) ?? windowsMap.get(candidate.providerId) ?? null; + const running = candidate.accountId + ? (accountFact?.running ?? 0) + : (deps.runningCount ? deps.runningCount(candidate.providerId, agentDeviceId) : 0); + + return { + available, + modelName: modelEntry?.name ?? candidate.model, + sourceName: view?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + ...(payAsYouGo ? { payAsYouGo: true } : {}), + ...(running > 0 ? { running } : {}), + acceptsImage: modelEntry?.imageInput !== false, + ...(typeof modelEntry?.price === 'number' ? { price: modelEntry.price } : {}), + }; + })); + + const picked = pickModelGroupCandidate(route, facts, { + now: now(), + lastPickedKey: request.lastPickedKey ?? null, + lastPickedRowKey: request.lastPickedRowKey ?? null, + needsImage: request.needsImage === true, + weightCounters: request.weightCounters, + usageProfile, + keepKey: request.keepKey ?? null, + }); + + if (picked.index === null) { + return { outcome: 'unavailable', reason: 'no_available_candidate', trace: picked.trace }; + } + const chosen = route.candidates[picked.index]; + const pickedEntry = picked.trace[picked.index]; + return { + outcome: 'routed', + route: chosen, + why: pickedEntry.why, + trace: picked.trace, + ...(picked.weightStep ? { weightStep: picked.weightStep } : {}), + }; + } + + return { resolve }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/scheduler.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/scheduler.mjs new file mode 100644 index 0000000..664190f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/scheduler.mjs @@ -0,0 +1,119 @@ +export const PROVIDER_GROUP_SIMILAR_URGENCY = 0.9; +export const ROUTE_FIVE_HOUR_SHARE_PERCENT = 15; + +export function fiveHourTightFor(member) { + if (typeof member.fiveHourLeft === 'number' && Number.isFinite(member.fiveHourLeft)) { + return member.fiveHourLeft / (Math.max(0, member.running) + 1) <= ROUTE_FIVE_HOUR_SHARE_PERCENT; + } + return member.fiveHourTight === true; +} + +export function applyRouteWeightStep(counters, step) { + const next = new Map(counters); + let total = 0; + for (const { key, weight } of step.participants) { + next.set(key, (next.get(key) ?? 0) + weight); + total += weight; + } + next.set(step.pickedKey, (next.get(step.pickedKey) ?? 0) - total); + return next; +} + +function eligibleMembers(members, options) { + return members.filter((m) => m.usable && !m.paused && !options.exclude?.has(m.key)); +} + +function openMembers(members, options) { + return eligibleMembers(members, options).filter((m) => m.running < m.limit); +} + +function byQuota(open, keepUnknown) { + const roomy = open.filter((member) => !fiveHourTightFor(member)); + const pool = roomy.length > 0 ? roomy : open; + const known = (member) => typeof member.urgency === 'number' && Number.isFinite(member.urgency); + const urgencies = pool.filter(known).map((member) => member.urgency); + if (urgencies.length === 0) return pool; + const top = Math.max(...urgencies); + return pool.filter((member) => (known(member) ? member.urgency >= top * PROVIDER_GROUP_SIMILAR_URGENCY : keepUnknown)); +} + +export function routeSchedulingCandidates(members, strategy, options = {}) { + const reachable = openMembers(members, options); + const withPlan = reachable.filter((m) => !m.quotaSpent); + const open = withPlan.length > 0 ? withPlan : reachable; + return strategy === 'expiring' ? byQuota(open, options.keepUnknownQuota === true) : open; +} + +function activeLoadOf(member) { + const value = member.selectionRunning ?? member.running; + return Number.isFinite(value) ? value : Number.POSITIVE_INFINITY; +} + +function residentOf(member) { + return typeof member.residentLoad === 'number' && Number.isFinite(member.residentLoad) && member.residentLoad > 0 + ? member.residentLoad + : 0; +} + +function leastBusy(open, allMembers, lastIndex, rotateTies) { + let minRunning = Number.POSITIVE_INFINITY; + for (const m of open) { + const load = activeLoadOf(m); + if (load < minRunning) minRunning = load; + } + const leastRunning = open.filter((m) => activeLoadOf(m) === minRunning); + let minResident = Number.POSITIVE_INFINITY; + for (const m of leastRunning) { + const res = residentOf(m); + if (res < minResident) minResident = res; + } + const tied = leastRunning.filter((m) => residentOf(m) === minResident); + if (rotateTies && lastIndex >= 0 && tied.length > 1) { + return tied.find((m) => allMembers.indexOf(m) > lastIndex) ?? tied[0]; + } + return tied[0]; +} + +function costOf(member) { + return typeof member.cost === 'number' && Number.isFinite(member.cost) && member.cost >= 0 + ? member.cost + : Number.POSITIVE_INFINITY; +} + +export function pickRouteMember(members, strategy, options = {}) { + const open = routeSchedulingCandidates(members, strategy, options); + if (open.length === 0) return { key: null }; + const lastIndex = options.lastPicked ? members.findIndex((m) => m.key === options.lastPicked) : -1; + const after = () => open.find((m) => members.indexOf(m) > lastIndex) ?? open[0]; + switch (strategy) { + case 'order': + return { key: open[0].key }; + case 'rotate': { + const last = open.find((m) => m.key === options.lastPicked); + if (last && (options.roundPicks ?? 1) < (last.roundSlots ?? 1)) return { key: last.key }; + return { key: after().key }; + } + case 'drain': { + const last = open.find((m) => m.key === options.lastPicked); + return { key: (last ?? after()).key }; + } + case 'weighted': { + const rows = open.map((m) => ({ key: m.key, weight: Math.max(1, m.weight) })); + const score = (row) => (options.weightCounters?.get(row.key) ?? 0) + row.weight; + const best = rows.reduce((top, row) => (score(row) > score(top) ? row : top)); + return { key: best.key, weightStep: { participants: rows, pickedKey: best.key } }; + } + case 'headroom': { + const known = open.filter((m) => typeof m.headroom === 'number' && Number.isFinite(m.headroom)); + if (known.length === 0) return { key: open[0].key, plain: true }; + return { key: known.reduce((best, m) => (m.headroom > best.headroom ? m : best)).key }; + } + case 'cheapest': { + const priced = open.filter((m) => Number.isFinite(costOf(m))); + if (priced.length === 0) return { key: open[0].key, plain: true }; + return { key: priced.reduce((best, m) => (costOf(m) < costOf(best) ? m : best)).key }; + } + default: + return { key: leastBusy(open, members, lastIndex, options.rotateTies === true).key }; + } +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/source-routes.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/source-routes.mjs new file mode 100644 index 0000000..709c022 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/source-routes.mjs @@ -0,0 +1,255 @@ +import { createHash } from 'node:crypto'; +import { + MODEL_GROUP_AUTO_PREFIX, + MODEL_GROUP_EXPANDED_PREFIX, + MODEL_GROUP_LIMITS, + modelGroupSourceKey, +} from './model-groups.mjs'; +import { isProviderShareAgentDeviceId } from './provider-identity.mjs'; + +const GROUP_KIND = { 'claude-code': 'cc', codex: 'codex', pi: 'pi' }; +const NOT_A_FAMILY = new Set(['xd', 'cindy']); +const FAMILY_OF = { 'openai-spectrum': 'openai' }; + +export function providerFamily(view) { + const kind = view.logoKind ?? (['openai', 'anthropic', 'google', 'xai', 'deepseek', 'kimi', 'glm'].includes(view.id) ? view.id : null); + if (!kind || NOT_A_FAMILY.has(kind)) return null; + return FAMILY_OF[kind] ?? kind; +} + +const usable = (view) => view.connected && !view.suspended && !view.removed && !view.subscriptionPoolAlias; + +function locationViews(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.views; + return catalog.remote?.get(agentDeviceId)?.providers ?? []; +} + +function locationAgents(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.agents; + return catalog.remote?.get(agentDeviceId)?.agents ?? catalog.agents; +} + +function flattenableAccounts(catalog, providerId) { + const all = catalog.localAccounts?.get(providerId); + const active = all?.filter((account) => account.paused !== true); + return all && all.length >= 2 && active && active.length > 0 ? active : null; +} + +export function sourceModelKey(view, agent, modelId) { + const declared = view.routing?.[agent]?.modelIdRewrite?.stripPrefix; + const id = (declared && modelId.startsWith(declared) ? modelId.slice(declared.length) : modelId).toLowerCase(); + return id.replace(/^[a-z0-9][a-z0-9._-]*\/([^/]+)$/, '$1'); +} + +function expandedId(routeId, modelKey) { + return `${MODEL_GROUP_EXPANDED_PREFIX}${createHash('sha256').update(`${routeId}\u0000${modelKey}`).digest('hex').slice(0, 40)}`; +} + +function runnableProviderModels(catalog, view, source, account) { + if (!usable(view)) return []; + const views = locationViews(catalog, source.agentDeviceId); + const agents = locationAgents(catalog, source.agentDeviceId); + const allowed = agents.filter((agent) => agent in GROUP_KIND); + const seen = new Set(); + const out = []; + for (const agent of allowed) { + for (const model of view.models?.[agent] ?? []) { + const key = sourceModelKey(view, agent, model.id); + if (model.disabled || seen.has(key)) continue; + if (account?.supportedModelIds && !account.supportedModelIds.has(model.id.replace(/^chatgpt\//, ''))) continue; + const agentKind = GROUP_KIND[agent]; + const candidate = { + agentKind, + providerId: view.id, + model: model.id, + ...(source.agentDeviceId ? { agentDeviceId: source.agentDeviceId } : {}), + ...(source.accountId ? { accountId: source.accountId } : {}), + ...(source.off ? { off: true } : {}), + ...(source.weight ? { weight: source.weight } : {}), + }; + if (catalog.available && !catalog.available(candidate, views, agents)) continue; + seen.add(key); + out.push({ + key, + name: model.name ?? key, + candidate, + }); + } + } + return out; +} + +function memberSourceKey(member) { + return modelGroupSourceKey({ + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }); +} + +function accountKeysFor(view, accountId, account) { + if (accountId) return account?.accountKey ? [account.accountKey] : []; + return view?.subscriptionAccountKeys ?? []; +} + +function withoutRepeatedAccounts(members, catalog, offKeys) { + const localActiveKeys = new Set(); + const localModelKeys = new Set(); + for (const m of members) { + if (m.agentDeviceId || offKeys.has(memberSourceKey(m))) continue; + for (const k of accountKeysFor(m.view, m.accountId, m.account)) localActiveKeys.add(k); + if (m.view) { + for (const item of runnableProviderModels(catalog, m.view, { accountId: m.accountId }, m.account)) { + localModelKeys.add(item.key); + } + } + } + return members.filter((m) => { + if (!m.agentDeviceId || isProviderShareAgentDeviceId(m.agentDeviceId)) return true; + const keys = accountKeysFor(m.view, m.accountId, m.account); + if (keys.length === 0 || !keys.every((k) => localActiveKeys.has(k))) return true; + const models = m.view ? runnableProviderModels(catalog, m.view, { agentDeviceId: m.agentDeviceId }) : []; + return models.length > 0 && models.some((item) => !localModelKeys.has(item.key)); + }); +} + +export function buildAutoSourceRoutes(config, catalog) { + const families = new Map(); + const add = (view, agentDeviceId) => { + if (!usable(view)) return; + const family = providerFamily(view); + if (!family) return; + const accounts = !agentDeviceId ? flattenableAccounts(catalog, view.id) : null; + if (accounts) { + const expanded = accounts.map((account) => ({ + id: view.id, + name: view.name ?? family, + accountId: account.id, + account, + view, + })); + families.set(family, [...(families.get(family) ?? []), ...expanded]); + } else { + families.set(family, [ + ...(families.get(family) ?? []), + { id: view.id, name: view.name ?? family, ...(agentDeviceId ? { agentDeviceId } : {}), view }, + ]); + } + }; + for (const view of catalog.views ?? []) add(view); + for (const [deviceId, entry] of catalog.remote ?? []) { + for (const view of entry.providers ?? []) add(view, deviceId); + } + + const hidden = new Set(config.hiddenAuto ?? []); + const routes = []; + for (const [family, found] of families) { + const id = `${MODEL_GROUP_AUTO_PREFIX}${family}`.slice(0, MODEL_GROUP_LIMITS.id); + const saved = config.autoSources?.[id] ?? []; + const rank = new Map(saved.map((source, index) => [modelGroupSourceKey(source), { index, source }])); + const savedFor = (source) => + rank.get(modelGroupSourceKey(source)) + ?? (source.accountId ? rank.get(modelGroupSourceKey({ providerId: source.providerId })) : undefined); + const offKeys = new Set(); + for (const member of found) { + const source = { + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }; + if (savedFor(source)?.source.off) offKeys.add(memberSourceKey(member)); + } + const own = withoutRepeatedAccounts(found, catalog, offKeys); + if (own.length < 2) continue; + const detected = own.map(({ id: providerId, agentDeviceId, accountId }) => ({ + providerId, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + })); + const ordered = detected + .map((source, index) => ({ source, index, saved: savedFor(source) })) + .sort((a, b) => (a.saved ? a.saved.index : saved.length + a.index) - (b.saved ? b.saved.index : saved.length + b.index) || a.index - b.index) + .map(({ source, saved: kept }) => ({ + ...source, + ...(kept?.source.off ? { off: true } : {}), + ...(kept?.source.weight ? { weight: kept.source.weight } : {}), + })); + routes.push({ + id, + name: own[0].name, + strategy: config.autoStrategy?.[id] ?? 'expiring', + sources: ordered.slice(0, MODEL_GROUP_LIMITS.candidates), + auto: true, + ...(hidden.has(id) ? { hidden: true } : {}), + }); + } + return routes; +} + +export function flattenManualSourceRoute(route, catalog) { + let changed = false; + const seen = new Set(); + const flattened = []; + for (const source of route.sources) { + if (!source.agentDeviceId && !source.accountId) { + const accounts = flattenableAccounts(catalog, source.providerId); + if (accounts) { + changed = true; + for (const account of accounts) { + const item = { ...source, accountId: account.id }; + const key = modelGroupSourceKey(item); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(item); + } + continue; + } + } + const key = modelGroupSourceKey(source); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(source); + } + return changed ? { ...route, sources: flattened.slice(0, MODEL_GROUP_LIMITS.candidates) } : route; +} + +export function expandSourceRouteDetail(route, catalog) { + const byModel = new Map(); + for (const source of route.sources) { + const views = locationViews(catalog, source.agentDeviceId); + const view = views.find((item) => item.id === source.providerId); + if (!view || !usable(view)) continue; + const account = !source.agentDeviceId && source.accountId + ? catalog.localAccounts?.get(source.providerId)?.find((item) => item.id === source.accountId) + : undefined; + for (const item of runnableProviderModels(catalog, view, source, account)) { + const entry = byModel.get(item.key) ?? { name: item.name, items: [] }; + entry.items.push(item.candidate); + byModel.set(item.key, entry); + } + } + const routes = []; + for (const [modelKey, { name, items }] of byModel) { + if (items.length === 0) continue; + routes.push({ + id: expandedId(route.id, modelKey), + name, + strategy: route.strategy, + parent: { id: route.id, name: route.name, model: modelKey }, + candidates: items, + }); + } + return { routes }; +} + +export function effectiveModelGroupsConfig(config, catalog) { + const autoRoutes = buildAutoSourceRoutes(config, catalog); + const manualRoutes = (config.sourceRoutes ?? []).map((route) => flattenManualSourceRoute(route, catalog)); + const sourceRoutes = [...autoRoutes, ...manualRoutes]; + const expanded = sourceRoutes.flatMap((route) => expandSourceRouteDetail(route, catalog).routes); + return { + ...config, + sourceRoutes, + routes: [...(config.routes ?? []), ...expanded], + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/src/usage.mjs b/questions/smart-routing-three-tiers/v1/candidate/src/usage.mjs new file mode 100644 index 0000000..c8d91ad --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/src/usage.mjs @@ -0,0 +1,64 @@ +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT = 85; +export const PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS = 60 * 60_000; + +function fiveHourTight(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || usedPercent < PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT) return false; + if (resetAtMs === null) return true; + return resetAtMs > now && resetAtMs - now > PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS; +} + +function fiveHourLeft(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || !Number.isFinite(usedPercent)) return null; + if (resetAtMs !== null && (resetAtMs <= now || resetAtMs - now <= PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS)) return null; + return Math.max(0, Math.min(100, 100 - usedPercent)); +} + +function tightestLeft(values) { + const known = values.filter((value) => value !== null); + return known.length > 0 ? Math.min(...known) : null; +} + +function timeLeftPercent(window, now) { + if (window.resetAtMs === null) return window.usedPercent > 0 ? null : 100; + const left = window.resetAtMs - now; + return left > 0 ? Math.min(100, (left / window.windowMs) * 100) : null; +} + +function quotaUrgency(window, now) { + const left = timeLeftPercent(window, now); + return left === null ? null : Math.max(0, 100 - window.usedPercent) / left; +} + +function paceOf(windows, now) { + let pace = null; + for (const window of windows) { + const urgency = quotaUrgency(window, now); + if (urgency === null) return null; + if (!pace || urgency < pace.urgency) pace = { urgency, window }; + } + return pace; +} + +function paceState(windows, now) { + const pace = windows ? paceOf(windows, now) : null; + return { + urgency: pace?.urgency ?? null, + quota: pace?.window ?? null, + headroom: windows && windows.length > 0 ? Math.max(0, 100 - Math.max(...windows.map((w) => w.usedPercent))) : null, + }; +} + +export function quotaWindowsScheduleState(windows, now) { + const live = windows.filter((w) => w.resetAtMs === null || w.resetAtMs > now); + const full = live.filter((w) => w.usedPercent >= 100); + const long = live.filter((w) => w.windowMs > FIVE_HOURS_MS); + const paced = long.length > 0 ? long : live; + return { + limited: full.length > 0, + resetAtMs: full.length > 0 && full.every((w) => w.resetAtMs !== null) ? Math.max(...full.map((w) => w.resetAtMs)) : null, + fiveHourTight: live.some((w) => w.windowMs <= FIVE_HOURS_MS && fiveHourTight(w.usedPercent, w.resetAtMs, now)), + fiveHourLeft: tightestLeft(live.filter((w) => w.windowMs <= FIVE_HOURS_MS).map((w) => fiveHourLeft(w.usedPercent, w.resetAtMs, now))), + ...paceState(paced.length > 0 ? paced : null, now), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/candidate/tests/smoke.test.mjs b/questions/smart-routing-three-tiers/v1/candidate/tests/smoke.test.mjs new file mode 100644 index 0000000..5fcb834 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/candidate/tests/smoke.test.mjs @@ -0,0 +1,116 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { pickModelGroupCandidate } from '../src/pick.mjs'; +import { applyRouteWeightStep } from '../src/scheduler.mjs'; +import { redactProviderCatalogForTunnel } from '../src/remote-catalog.mjs'; + +const NOW = Date.UTC(2026, 11, 3, 10, 0, 0); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +const week = (usedPercent, resetHours) => ({ + usedPercent, + resetAtMs: NOW + resetHours * HOUR, + windowMs: 7 * DAY, +}); + +const fact = (windows, extra = {}) => ({ + available: true, + modelName: 'Model', + sourceName: 'Source', + windows, + ...extra, +}); + +// True when any key or string value in `value` names `host`, either as the +// hostname of a parseable URL or as a bare host token such as "host:443". +const mentionsHost = (value, host) => { + const strings = []; + const walk = (v) => { + if (typeof v === 'string') strings.push(v); + else if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + strings.push(k); + walk(x); + } + } + }; + walk(value); + return strings.some((s) => { + try { + if (new URL(s).hostname === host) return true; + } catch {} + return (s.toLowerCase().match(/[a-z0-9-]+(?:\.[a-z0-9-]+)+/g) ?? []).some((t) => t === host); + }); +}; + +test('supports deterministic order, rotate, cheapest, and weighted strategies', () => { + const candidates = [ + { agentKind: 'codex', providerId: 'a', model: 'm1', weight: 3 }, + { agentKind: 'codex', providerId: 'b', model: 'm1', weight: 1 }, + ]; + const facts = [fact(null, { price: 15 }), fact(null, { price: 5 })]; + + const ordered = pickModelGroupCandidate({ id: 'r1', name: 'R1', strategy: 'order', candidates }, facts, { now: NOW }); + assert.equal(ordered.index, 0); + + const cheapest = pickModelGroupCandidate({ id: 'r2', name: 'R2', strategy: 'cheapest', candidates }, facts, { now: NOW }); + assert.equal(cheapest.index, 1); + assert.equal(cheapest.trace[1].why, 'cheapest'); + + let counters = new Map(); + const picks = []; + for (let i = 0; i < 4; i += 1) { + const res = pickModelGroupCandidate({ id: 'r3', name: 'R3', strategy: 'weighted', candidates }, facts, { now: NOW, weightCounters: counters }); + picks.push(res.index); + counters = applyRouteWeightStep(counters, res.weightStep); + } + assert.deepEqual(picks, [0, 0, 1, 0]); +}); + +test('auto strategy sprints expiring surplus subscriptions and skips exhausted sources', () => { + const route = { + id: 'r-auto', + name: 'Auto', + strategy: 'expiring', + candidates: [ + { agentKind: 'codex', providerId: 'sub-a', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-b', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-c', model: 'gpt-6' }, + ], + }; + const res = pickModelGroupCandidate( + route, + [ + fact([week(100, 12)]), + fact([week(20, 6 * 24)]), + fact([week(40, 18)]), // urgency = 60 / (18/168*100) = 5.6 >= 2.0 + ], + { now: NOW }, + ); + assert.equal(res.index, 2); + assert.equal(res.trace[0].state, 'skipped'); + assert.equal(res.trace[0].why, 'limited'); + assert.equal(res.trace[2].why, 'expiring'); +}); + +test('redactProviderCatalogForTunnel strips upstream URLs while preserving display wireProtocol', () => { + const redacted = redactProviderCatalogForTunnel({ + providers: [ + { + id: 'kimi', + name: 'Kimi', + connected: true, + auth: { method: 'apiKey' }, + routing: { + pi: { upstream: 'https://api.kimi.com/coding/v1', wireProtocol: 'openai-chat' }, + }, + }, + ], + }, { sameAccountController: true }); + assert.equal(mentionsHost(redacted, 'api.kimi.com'), false); + assert.deepEqual(redacted.providers[0].kimiCodingUsageAgents, ['pi']); + assert.equal(redacted.providers[0].routing.pi.wireProtocol, 'openai-chat'); +}); diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/CONTRACT.md b/questions/smart-routing-three-tiers/v1/controls/incomplete/CONTRACT.md new file mode 100644 index 0000000..b06fe60 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/CONTRACT.md @@ -0,0 +1,58 @@ +# Product & Protocol Contract + +This contract defines the authoritative three-tier Smart Routing (`expiring` / Auto) semantics and public interfaces across `src/`. + +## 1. Static Three-Tier Default Classification (`src/provider-quota-source.mjs`) + +- Exports `MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']`, `modelGroupTierRank(tier)` (`0`/`1`/`2`), `defaultModelGroupSourceTier({ agentKind?, providerId, agentDeviceId?, provider?, accountPayAsYouGo? })`, and `isZhipuCodingPlanProviderView(view, agent?)`. +- Static default tier rules (never changing tier due to transient quota timeouts): + - Merged pay-as-you-go API key accounts (`accountPayAsYouGo`) → `'fallback'`. + - Shared providers (`agentDeviceId` starting with `share:`) → `'secondary'`. + - Organization-managed providers (`provider.source === 'organization'`) or BYOK IDs (`byok-*`) → `'secondary'`. + - ACP plugin engines (`agentKind === 'acp'` or `acp-plugin:*` provider IDs) → `'primary'`. + - Standard providers (evaluated per engine when `agentKind` is given, mapping `'cc'` → `'claude-code'`; when `agentKind` is omitted, a provider is treated as a coding plan if any configured engine uses an official coding plan): + - Official coding plans (Kimi Coding, OpenCode Go, Zhipu/Z.AI GLM Coding Plan) or local no-auth (`auth.method === 'none'`) → `'primary'`. + - Pay-as-you-go (`access.kind === 'api'` or `providerId === 'xd'`) → `'fallback'`. + - Subscriptions (`access.kind === 'subscription'` or `auth.method === 'oauth'`) → `'primary'`. + - Managed (`access.kind === 'managed'`) → `'secondary'`; otherwise `'primary'`. +- `isZhipuCodingPlanProviderView(view, agent?)`: requires `auth.method === 'apiKey'`; prefers per-engine `zhipuCodingPlanUsageAgents` when present, falls back to per-engine routing inspection, and honors legacy boolean `zhipuCodingPlanUsage` for a specific `agent` ONLY when that agent is the sole enabled route without an explicit `upstream` (never promoting multi-engine redacted views blindly). + +## 2. Six-Level Auto Selection & Wire Compatibility (`src/pick.mjs`, `src/model-groups.mjs`) + +- Neutral unknown-quota score within a tier is `AUTO_UNKNOWN_QUOTA_SCORE = 0.78`. +- For `strategy === 'expiring'`, pick among ready candidates in strict 6-level priority order: + 1. `primary` roomy → 2. `secondary` roomy → 3. `primary` 5h-tight → 4. `secondary` 5h-tight → 5. `fallback` roomy → 6. `fallback` 5h-tight. +- Within a tier, preserve expiring-surplus sprint (`>= 2.0×`), `quotaScore + usageBonus - running * 0.30`, and `0.06` soft rotation. +- **Trace reasons (`state` / `why`)**: + - When a `secondary` winner is chosen while any enabled (`!off`) `primary` peer exists (even disconnected or limited) → `why: 'secondaryFallback'`. + - When a `fallback` winner is chosen while any enabled non-`fallback` peer exists → `why: 'paygFallback'` (if PAYG) or `'tierFallback'` (otherwise). + - Non-picked ready candidates report `standby` (`paygReserve` / `tierReserve` for `fallback` below non-`fallback`; `secondaryReserve` for `secondary` below `primary`; otherwise `standby`) or `skipped` (`why: 'tight'` when 5h-tight and a roomy peer with higher priority in the 6-level order is ready — e.g. `secondary` roomy over `primary` 5h-tight, or `fallback` roomy over `fallback` 5h-tight). +- `normalizeModelGroupsConfig` validates and retains `tier` on route candidates, `sourceRoutes[].sources`, and `autoSources[id]`. +- `modelGroupResolveResultForRemote` downgrades new reasons for older peers while storing the true reason in `pickWhy`: `secondaryFallback` / `tierFallback` → `'order'`, `secondaryReserve` / `tierReserve` → `'standby'` (alongside existing `payg*` mappings); `modelGroupResolveResultFromRemote` restores `why` from recognized `pickWhy` and deletes `pickWhy`. + +## 3. Merged-Provider Routes (`src/model-groups.mjs`, `src/pick.mjs`) + +- `expandMergedSources` preserves an outer row's explicit `tier` on `via.tier`. +- Merged rows select an inner representative using each member's effective tier, then compete in the outer route at `via.tier` (fixed tier) if set or the representative's effective tier ("follow source") otherwise. +- When the row's representative is not picked in an `'expiring'` outer route and receives an outer `standby` reserve reason ranked higher (`paygReserve`/`tierReserve` = 2, `secondaryReserve` = 1) than a benched inner member's `standby` reason, the benched member inherits the outer reserve reason (mapping `paygReserve` → `tierReserve` for non-PAYG members). + +## 4. Per-Engine Tiering & Tier Controls (`src/resolver.mjs`, `src/provider-quota-source.mjs`) + +- `createModelGroupResolver` computes `defaultTier` per candidate using its `agentKind` (and sets `payAsYouGo = defaultTier === 'fallback'`), so mixed coding-plan/PAYG providers route each engine at its own tier. +- `resolveSourceDefaultTier(source, provider)`: returns the uniform default tier across `provider.agents`, or `undefined` ("follow source") when engines disagree. +- `resolveTierControlState({ value, defaultTier })`: returns `{ effective, showFollow, options }`; shows `'follow'` whenever `defaultTier === undefined` OR an explicit saved override `value` now equals `defaultTier` (preserving an explicit clear path). +- `applyTierControlSelection({ value, defaultTier }, next)`: no-op if `next === effective`; returns `undefined` when clearing to `'follow'` or matching default without `'follow'` shown; otherwise returns `next`. +- `retargetCandidateWithTier(previous, selected)`: preserves `previous.tier` only when `providerId`, `agentDeviceId`, and `accountId` are all unchanged; otherwise clears `tier`. + +## 5. Source Routes & Multi-Account Pool Isolation (`src/source-routes.mjs`) + +- `buildAutoSourceRoutes` stably orders default members by default tier rank before applying saved `autoSources` overrides. +- Exact `(providerId, accountId)` saved overrides apply to that exact account (including merged PAYG keys). Legacy whole-provider `{ providerId, tier }` overrides inherit ONLY onto subscription accounts (`!account.apiConnectionId`) in both `buildAutoSourceRoutes` and `flattenManualSourceRoute` — never onto merged PAYG API key pool members. +- `expandSourceRouteDetail` / `runnableProviderModels` propagates `source.tier` onto expanded candidates. + +## 6. Remote Catalog Redaction (`src/remote-catalog.mjs`) + +- `redactProviderCatalogForTunnel(result, { sameAccountController, readZhipuCodingPlanAccountUsage })`: + - Always strips untrusted incoming `zhipuCodingPlanUsage`, `zhipuCodingPlanUsageAgents`, `kimiCodingUsageAgents`, `opencodeGoUsageAgents` before recomputing. + - Emits `zhipuCodingPlanUsage: true` and per-engine `zhipuCodingPlanUsageAgents` ONLY when `sameAccountController && readZhipuCodingPlanAccountUsage` and the provider is active, remote-enabled, connected, API-key authenticated, and has at least one official GLM coding-plan engine route. + - Emits `kimiCodingUsageAgents` / `opencodeGoUsageAgents` per engine when non-empty, and projects `routing` for display without leaking `upstream` URLs or credentials. diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/ENVIRONMENT.md b/questions/smart-routing-three-tiers/v1/controls/incomplete/ENVIRONMENT.md new file mode 100644 index 0000000..a837bde --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering core strategies, quota scheduling, and route display redaction diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/TASK.md b/questions/smart-routing-three-tiers/v1/controls/incomplete/TASK.md new file mode 100644 index 0000000..c046f5f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/TASK.md @@ -0,0 +1,10 @@ +# Task + +Cindy's Smart Routing (`expiring` / Auto strategy) is being upgraded from a two-pool picker to a full three-tier priority model (`primary` / `secondary` / `fallback`), and production reports have surfaced several regressions across tier classification, merged routes, mixed coding-plan/PAYG providers, flattened multi-account pools, and remote catalog redaction. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and implement the complete three-tier Smart Routing behavior so every product invariant holds while preserving all existing non-auto strategies, image-capability filtering, within-tier scoring, and redaction privacy guarantees. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/package.json b/questions/smart-routing-three-tiers/v1/controls/incomplete/package.json new file mode 100644 index 0000000..2586868 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-smart-routing-three-tiers", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/auto-usage-profile.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/auto-usage-profile.mjs new file mode 100644 index 0000000..5750a1e --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/auto-usage-profile.mjs @@ -0,0 +1,150 @@ +export const AUTO_USAGE_WINDOW_DAYS = 14; +const AUTO_USAGE_WINDOW_MS = AUTO_USAGE_WINDOW_DAYS * 86_400_000; +const MAX_PRIORITY_MODELS = 128; + +function localDayKey(ms) { + const d = new Date(ms); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +export function canonicalUsageModelId(model) { + const trimmed = String(model ?? '').trim().toLowerCase(); + if (!trimmed) return ''; + const slash = trimmed.lastIndexOf('/'); + return slash >= 0 && slash < trimmed.length - 1 ? trimmed.slice(slash + 1) : trimmed; +} + +export function autoUsageSourceKey(agentDeviceId, providerId) { + return `${agentDeviceId ?? ''}\u0000${providerId}`; +} + +export function autoUsageCandidateKey(agentDeviceId, providerId, model) { + return `${agentDeviceId ?? ''}\u0000${providerId}\u0000${canonicalUsageModelId(model)}`; +} + +function recencyDecay(ageMs) { + const days = Math.max(0, ageMs / 86_400_000); + if (days <= 3) return 1.0; + if (days <= 7) return 0.7; + if (days <= AUTO_USAGE_WINDOW_DAYS) return 0.4; + return 0; +} + +function sampleWeight(ageMs, tokens) { + const decay = recencyDecay(ageMs); + if (decay <= 0) return 0; + const safeTokens = Number.isFinite(tokens) && tokens > 0 ? tokens : 0; + const volumeBoost = safeTokens > 0 ? Math.min(3, Math.log10(1 + safeTokens / 10_000)) : 0; + return decay * (1 + volumeBoost); +} + +function addStats(map, key, weight, tokens, atMs) { + const existing = map.get(key); + if (existing) { + existing.weight += weight; + existing.sessions += 1; + existing.tokens += tokens; + if (atMs > existing.lastActiveAt) existing.lastActiveAt = atMs; + } else { + map.set(key, { weight, sessions: 1, tokens, lastActiveAt: atMs }); + } +} + +function computeModelPriorities(byModel) { + const modelEntries = [...byModel.entries()] + .filter(([, stats]) => stats.weight > 0) + .sort((a, b) => b[1].weight - a[1].weight || b[1].lastActiveAt - a[1].lastActiveAt) + .slice(0, MAX_PRIORITY_MODELS); + const topModelWeight = modelEntries[0]?.[1].weight ?? 0; + const modelPriorities = {}; + if (topModelWeight > 0) { + for (const [modelId, stats] of modelEntries) { + modelPriorities[modelId] = Math.max(0.001, Math.round((stats.weight / topModelWeight) * 1000) / 1000); + } + } + return modelPriorities; +} + +export function buildAutoUsageProfile(samples, nowMs) { + const cutoffMs = nowMs - AUTO_USAGE_WINDOW_MS; + const bySource = new Map(); + const byCandidate = new Map(); + const byModel = new Map(); + const sessionRoutes = new Map(); + const activeDayKeys = new Set(); + const weekdayKeys = new Set(); + const weekendKeys = new Set(); + + for (const sample of samples) { + if (!sample.providerId || !Number.isFinite(sample.atMs)) continue; + const providerId = sample.providerId.trim(); + const agentDeviceId = sample.agentDeviceId?.trim() || null; + if (sample.sessionId) { + sessionRoutes.set(sample.sessionId, { providerId, agentDeviceId }); + } + if (sample.atMs < cutoffMs || sample.atMs > nowMs + 60_000) continue; + const tokens = typeof sample.tokens === 'number' && Number.isFinite(sample.tokens) && sample.tokens > 0 ? sample.tokens : 0; + const weight = sampleWeight(nowMs - sample.atMs, tokens); + if (weight <= 0) continue; + + const dayKey = localDayKey(sample.atMs); + activeDayKeys.add(dayKey); + const dow = new Date(sample.atMs).getDay(); + if (dow === 0 || dow === 6) weekendKeys.add(dayKey); + else weekdayKeys.add(dayKey); + + const srcKey = autoUsageSourceKey(agentDeviceId, providerId); + addStats(bySource, srcKey, weight, tokens, sample.atMs); + + const canonicalModel = canonicalUsageModelId(sample.model); + if (canonicalModel) { + addStats(byCandidate, `${srcKey}\u0000${canonicalModel}`, weight, tokens, sample.atMs); + addStats(byModel, canonicalModel, weight, tokens, sample.atMs); + } + } + + return { + computedAtMs: nowMs, + activeDays: activeDayKeys.size, + weekdayActiveDays: weekdayKeys.size, + weekendActiveDays: weekendKeys.size, + bySource, + byCandidate, + byModel, + modelPriorities: computeModelPriorities(byModel), + sessionRoutes, + }; +} + +export function autoUsageCandidateWeight(profile, candidate) { + if (!profile) return 0; + const exact = profile.byCandidate.get(autoUsageCandidateKey(candidate.agentDeviceId, candidate.providerId, candidate.model))?.weight ?? 0; + const source = profile.bySource.get(autoUsageSourceKey(candidate.agentDeviceId, candidate.providerId))?.weight ?? 0; + if (exact <= 0 && source <= 0) return 0; + return exact * 0.7 + source * 0.3; +} + +export function effectiveRemainingTimeFactor(profile, nowMs, resetAtMs) { + if (!profile || profile.activeDays < 4 || resetAtMs === null || resetAtMs <= nowMs) return 1; + const remainingDays = (resetAtMs - nowMs) / 86_400_000; + if (remainingDays < 0.25 || remainingDays > 7.5) return 1; + const weekdayRate = profile.weekdayActiveDays / 10; + const weekendRate = profile.weekendActiveDays / 4; + const avgRate = (weekdayRate * 5 + weekendRate * 2) / 7; + if (avgRate <= 0.05) return 1; + + const steps = Math.max(1, Math.min(28, Math.ceil(remainingDays * 4))); + const stepMs = (resetAtMs - nowMs) / steps; + let expectedRateSum = 0; + for (let i = 0; i < steps; i += 1) { + const mid = nowMs + stepMs * (i + 0.5); + const dow = new Date(mid).getDay(); + expectedRateSum += dow === 0 || dow === 6 ? weekendRate : weekdayRate; + } + const remainingAvgRate = expectedRateSum / steps; + const ratio = remainingAvgRate / avgRate; + return Math.max(0.75, Math.min(1.25, ratio)); +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/model-groups.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/model-groups.mjs new file mode 100644 index 0000000..329fe0b --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/model-groups.mjs @@ -0,0 +1,240 @@ +export const MODEL_GROUP_AUTO_PREFIX = 'auto:'; +export const MODEL_GROUP_EXPANDED_PREFIX = 'src:'; +export const MODEL_GROUP_LIMITS = { + id: 80, + name: 80, + candidates: 32, + routes: 64, + effort: 32, + deviceId: 128, + accountId: 128, +}; + +export const MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']; + +export function modelGroupTier(value) { + return value === 'primary' || value === 'secondary' || value === 'fallback' ? value : undefined; +} + +export function modelGroupTierRank(tier) { + if (tier === 'primary') return 0; + if (tier === 'secondary') return 1; + return 2; +} + +export function modelGroupWeight(value) { + const n = typeof value === 'number' ? Math.floor(value) : NaN; + return Number.isFinite(n) && n >= 1 ? Math.min(1000, n) : 1; +} + +export function modelGroupCandidateKey(candidate) { + const base = `${candidate.agentKind}\u0000${candidate.providerId}\u0000${candidate.model}`; + const loc = candidate.agentDeviceId ? `\u0000@${candidate.agentDeviceId}` : ''; + const acct = candidate.accountId ? `\u0000#${candidate.accountId}` : ''; + const merged = candidate.merged ? `\u0000M:${candidate.merged.id}\u0000${candidate.merged.model}` : ''; + return `${base}${loc}${acct}${merged}`; +} + +export function modelGroupCandidateBaseKey(key) { + return key.replace(/\u0000#[^\u0000]+/, ''); +} + +export function modelGroupCandidateRowKey(candidate) { + return candidate.via?.key ?? modelGroupCandidateKey(candidate); +} + +export function modelGroupSourceKey(source) { + const loc = source.agentDeviceId ? `\u0000@${source.agentDeviceId}` : ''; + const acct = source.accountId ? `\u0000#${source.accountId}` : ''; + return `${source.providerId}${loc}${acct}`; +} + +const LEGACY_WHY = { + drain: 'order', + drainNext: 'order', + headroom: 'expiring', + weighted: 'rotate', + usageHabit: 'expiring', + autoBalance: 'expiring', + lessBusy: 'expiring', + paygFallback: 'order', + paygReserve: 'standby', + secondaryFallback: 'order', + secondaryReserve: 'standby', + tierFallback: 'order', + tierReserve: 'standby', +}; + +function legacyWhy(entry) { + const legacy = LEGACY_WHY[entry.why]; + return legacy ? { ...entry, why: legacy, pickWhy: entry.why } : entry; +} + +function realWhy(entry) { + const { pickWhy, ...rest } = entry; + const known = typeof pickWhy === 'string' && Object.hasOwn(LEGACY_WHY, pickWhy); + return known ? { ...rest, why: pickWhy } : rest; +} + +export function modelGroupResolveResultForRemote(result) { + const trace = (result.trace ?? []).map(legacyWhy); + return result.outcome === 'routed' ? { ...legacyWhy(result), trace } : { ...result, trace }; +} + +export function modelGroupResolveResultFromRemote(result) { + const trace = (result.trace ?? []).map(realWhy); + return result.outcome === 'routed' ? { ...realWhy(result), trace } : { ...result, trace }; +} + +function text(value, max) { + if (typeof value !== 'string') return ''; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= max ? trimmed : ''; +} + +function normalizeCandidate(raw) { + if (!raw || typeof raw !== 'object') return null; + const agentKind = ['cc', 'codex', 'pi', 'acp'].includes(raw.agentKind) ? raw.agentKind : null; + const providerId = text(raw.providerId, MODEL_GROUP_LIMITS.id); + const model = text(raw.model, 160); + if (!agentKind || !providerId || !model) return null; + const agentDeviceId = raw.agentDeviceId ? text(raw.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const accountId = raw.accountId ? text(raw.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const weight = modelGroupWeight(raw.weight); + const tier = modelGroupTier(raw.tier); + const effort = text(raw.effort, MODEL_GROUP_LIMITS.effort); + const mergedRaw = raw.merged && typeof raw.merged === 'object' ? raw.merged : null; + const mergedId = mergedRaw ? text(mergedRaw.id, MODEL_GROUP_LIMITS.id) : ''; + const mergedModel = mergedRaw ? text(mergedRaw.model, 160) : ''; + return { + agentKind, + providerId, + model, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + ...(mergedId && mergedModel ? { merged: { id: mergedId, model: mergedModel } } : {}), + ...(raw.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(tier ? { tier } : {}), + ...(effort ? { effort } : {}), + }; +} + +function normalizeSources(raw) { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const out = []; + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const providerId = text(entry.providerId, MODEL_GROUP_LIMITS.id); + if (!providerId) continue; + const location = entry.agentDeviceId ? text(entry.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const account = entry.accountId ? text(entry.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const key = modelGroupSourceKey({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + }); + if (seen.has(key)) continue; + seen.add(key); + const weight = modelGroupWeight(entry.weight); + const tier = modelGroupTier(entry.tier); + out.push({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + ...(entry.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(tier ? { tier } : {}), + ...(entry.sameModelsOnly === true ? { sameModelsOnly: true } : {}), + }); + } + return out.slice(0, MODEL_GROUP_LIMITS.candidates); +} + +export function normalizeModelGroupsConfig(raw) { + if (!raw || typeof raw !== 'object') return { routes: [] }; + const routes = Array.isArray(raw.routes) + ? raw.routes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + candidates: Array.isArray(r.candidates) ? r.candidates.map(normalizeCandidate).filter(Boolean) : [], + })) + : []; + const sourceRoutes = Array.isArray(raw.sourceRoutes) + ? raw.sourceRoutes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + sources: normalizeSources(r.sources), + })) + : []; + const autoSources = raw.autoSources && typeof raw.autoSources === 'object' + ? Object.fromEntries( + Object.entries(raw.autoSources) + .filter(([id]) => id.startsWith(MODEL_GROUP_AUTO_PREFIX)) + .map(([id, list]) => [id, normalizeSources(list)]) + .filter(([, list]) => list.length > 0), + ) + : {}; + return { + routes, + ...(sourceRoutes.length > 0 ? { sourceRoutes } : {}), + ...(Object.keys(autoSources).length > 0 ? { autoSources } : {}), + ...(raw.autoStrategy ? { autoStrategy: raw.autoStrategy } : {}), + ...(raw.hiddenAuto ? { hiddenAuto: raw.hiddenAuto } : {}), + }; +} + +// Incomplete: omits propagating `row.tier` onto `via.tier`. +export function expandMergedSources(route, config) { + if (route.parent || !route.candidates.some((candidate) => candidate.merged)) return route; + const seen = new Set(); + const localPools = new Set(); + const localAccounts = new Set(); + const out = []; + const push = (candidate) => { + const key = modelGroupCandidateKey(candidate); + if (seen.has(key)) return; + if (!candidate.agentDeviceId && !candidate.merged) { + const baseKey = modelGroupCandidateBaseKey(key); + if (candidate.accountId) { + if (localPools.has(baseKey)) return; + localAccounts.add(baseKey); + } else { + if (localAccounts.has(baseKey)) return; + localPools.add(baseKey); + } + } + seen.add(key); + out.push(candidate); + }; + for (const candidate of route.candidates) { + const { merged, ...row } = candidate; + if (!merged) { + push(candidate); + continue; + } + const owner = (config.sourceRoutes ?? []).find((item) => item.id === merged.id); + const child = config.routes.find((item) => item.parent?.id === merged.id && (item.parent.model ?? item.id) === merged.model); + if (!owner || !child || child.candidates.length === 0) { + push({ ...candidate, off: true }); + continue; + } + const via = { + key: modelGroupCandidateKey(candidate), + strategy: child.strategy, + name: owner.name, + ...(row.weight !== undefined ? { weight: row.weight } : {}), + }; + for (const member of child.candidates) { + const { merged: _nested, via: _via, ...plain } = member; + const effort = row.effort ?? member.effort; + push({ ...plain, ...(row.off || member.off ? { off: true } : {}), ...(effort ? { effort } : {}), via }); + } + } + return { ...route, candidates: out }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/pick.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/pick.mjs new file mode 100644 index 0000000..669c492 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/pick.mjs @@ -0,0 +1,451 @@ +import { + modelGroupCandidateKey, + modelGroupCandidateRowKey, + modelGroupWeight, +} from './model-groups.mjs'; +import { pickRouteMember, PROVIDER_GROUP_SIMILAR_URGENCY } from './scheduler.mjs'; +import { FIVE_HOURS_MS, quotaWindowsScheduleState } from './usage.mjs'; +import { + autoUsageCandidateWeight, + effectiveRemainingTimeFactor, +} from './auto-usage-profile.mjs'; + +export function modelGroupHeadroom(windows, now) { + const live = (windows ?? []).filter((window) => window.resetAtMs === null || window.resetAtMs > now); + const long = live.filter((window) => window.windowMs > FIVE_HOURS_MS); + let tightest = null; + for (const window of long.length > 0 ? long : live) { + const left = Math.max(0, 100 - window.usedPercent); + if (!tightest || left < tightest.left) tightest = { left, window }; + } + return tightest; +} + +function keepsCurrent(strategy, keep, picked, facts) { + switch (strategy) { + case 'rotate': + case 'weighted': + case 'drain': + return true; + case 'cheapest': + return costOf(facts[keep.index]) <= costOf(facts[picked.index]); + case 'headroom': + if (picked.headroom === null) return true; + return keep.headroom !== null && picked.headroom - keep.headroom < KEEP_HEADROOM_GAP; + default: + return false; + } +} + +function costOf(fact) { + if (fact?.windows) return 0; + return typeof fact?.price === 'number' && Number.isFinite(fact.price) && fact.price >= 0 + ? fact.price + : Number.POSITIVE_INFINITY; +} + +const AUTO_EXPIRING_SURPLUS_URGENCY = 2.0; +const AUTO_UNKNOWN_QUOTA_SCORE = 0.78; +const AUTO_USAGE_MAX_BONUS = 0.45; +const AUTO_USAGE_FULL_CONFIDENCE = 2.5; +const AUTO_RUNNING_PENALTY = 0.30; +const AUTO_SOFT_ROTATE_GAP = 0.06; +const AUTO_KEEP_QUOTA_GAP = 0.25; +const KEEP_HEADROOM_GAP = 20; + +function nextAutoCandidate(band, lastPickedKey) { + const previous = band.findIndex(({ row }) => row.key === lastPickedKey); + return band[(previous + 1) % band.length]; +} + +function pickWithinTier(pool, options) { + const { now, lastPickedKey, usageProfile, keep } = options; + const enriched = pool.map((row) => { + const timeFactor = row.urgency !== null + ? effectiveRemainingTimeFactor(usageProfile, now, row.quota?.resetAtMs ?? null) + : 1; + const effectiveUrgency = row.urgency !== null ? row.urgency / timeFactor : null; + const isExpiringSurplus = effectiveUrgency !== null && effectiveUrgency >= AUTO_EXPIRING_SURPLUS_URGENCY; + const usageWeight = autoUsageCandidateWeight(usageProfile, row.candidate); + return { row, effectiveUrgency, isExpiringSurplus, usageWeight }; + }); + + const expiring = enriched.filter((item) => item.isExpiringSurplus); + if (expiring.length > 0) { + const topUrgency = Math.max(...expiring.map((item) => item.effectiveUrgency)); + const band = expiring.filter((item) => item.effectiveUrgency >= topUrgency * PROVIDER_GROUP_SIMILAR_URGENCY); + const byUrgency = [...band].sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index)[0]; + if (options.keepKey) { + const kept = band.find((item) => item.row === keep); + return { picked: (kept ?? byUrgency).row, why: 'expiring' }; + } + const minRunning = Math.min(...band.map((item) => item.row.running)); + const idleBand = band.filter((item) => item.row.running === minRunning); + const topUsage = Math.max(...idleBand.map((item) => item.usageWeight)); + const rotationBand = idleBand + .filter((item) => topUsage - item.usageWeight <= 0.05) + .sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + let why = 'expiring'; + if (byUrgency.row !== winner.row && byUrgency.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + idleBand.length > 1 + && winner.usageWeight >= 0.5 + && topUsage - byUrgency.usageWeight > 0.05 + ) { + why = 'usageHabit'; + } + return { picked: winner.row, why }; + } + + const totalUsageWeight = enriched.reduce((sum, item) => sum + item.usageWeight, 0); + const confidence = totalUsageWeight > 0 ? Math.min(1, totalUsageWeight / AUTO_USAGE_FULL_CONFIDENCE) : 0; + const scored = enriched.map((item) => { + const quotaScore = item.effectiveUrgency !== null + ? item.effectiveUrgency <= 1.0 + ? Math.max(0.05, item.effectiveUrgency) + : 1.0 + Math.min(1.0, item.effectiveUrgency - 1.0) * 0.12 + : AUTO_UNKNOWN_QUOTA_SCORE; + const usageShare = totalUsageWeight > 0 ? item.usageWeight / totalUsageWeight : 0; + const usageBonus = AUTO_USAGE_MAX_BONUS * confidence * usageShare; + const busyPenalty = item.row.running * AUTO_RUNNING_PENALTY; + const baseScore = quotaScore + usageBonus; + const totalScore = baseScore - busyPenalty; + return { ...item, quotaScore, usageBonus, busyPenalty, baseScore, totalScore }; + }); + + if (options.keepKey) { + const best = scored.reduce((top, item) => (item.quotaScore > top.quotaScore ? item : top)); + const kept = scored.find((item) => item.row === keep); + const winner = kept && best.quotaScore - kept.quotaScore <= AUTO_KEEP_QUOTA_GAP ? kept : best; + return { picked: winner.row, why: winner.effectiveUrgency === null ? 'autoBalance' : 'expiring' }; + } + + const sorted = [...scored].sort((a, b) => b.totalScore - a.totalScore || a.row.index - b.row.index); + const [leader] = sorted; + const rotationBand = sorted.filter((item) => leader.totalScore - item.totalScore <= AUTO_SOFT_ROTATE_GAP + && item.row.running <= leader.row.running); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + const rotated = winner !== leader; + const bestWithoutBusy = scored.reduce((top, cur) => (cur.baseScore > top.baseScore ? cur : top)); + const bestWithoutUsage = scored.reduce((top, cur) => + (cur.quotaScore - cur.busyPenalty) > (top.quotaScore - top.busyPenalty) ? cur : top); + const secondUsageBonus = Math.max(0, ...scored.filter((item) => item !== winner).map((item) => item.usageBonus)); + + let why; + if (bestWithoutBusy !== winner && bestWithoutBusy.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + winner.usageBonus >= 0.08 + && (bestWithoutUsage !== winner || winner.usageBonus >= secondUsageBonus + 0.05) + ) { + why = 'usageHabit'; + } else if ( + rotated + || (winner.effectiveUrgency === null && scored.some((item) => item.effectiveUrgency !== null && item.effectiveUrgency < AUTO_UNKNOWN_QUOTA_SCORE)) + ) { + why = 'autoBalance'; + } else if (scored.every((item) => item.effectiveUrgency === null) && totalUsageWeight === 0) { + why = 'order'; + } else if (winner.effectiveUrgency === null) { + why = 'autoBalance'; + } else { + why = 'expiring'; + } + return { picked: winner.row, why }; +} + +function pickTightPool(pool, options) { + if (options.keep && pool.includes(options.keep)) return { picked: options.keep, why: 'autoBalance' }; + const scored = pool.map((row) => ({ + row, + urgency: row.urgency ?? AUTO_UNKNOWN_QUOTA_SCORE, + })); + const best = scored.reduce((top, cur) => { + if (!options.keepKey && cur.row.running !== top.row.running) { + return cur.row.running < top.row.running ? cur : top; + } + return cur.urgency > top.urgency ? cur : top; + }); + const why = best.row.urgency !== null ? 'expiring' : 'autoBalance'; + return { picked: best.row, why }; +} + +function pickAutoCandidate(ready, enabled, options) { + const { now, lastPickedKey, usageProfile } = options; + const keep = options.keepKey ? ready.find((row) => row.key === options.keepKey) : undefined; + const primary = ready.filter((row) => row.tier === 'primary'); + const secondary = ready.filter((row) => row.tier === 'secondary'); + const fallback = ready.filter((row) => row.tier === 'fallback'); + + const primaryRoomy = primary.filter((row) => !row.tight); + const secondaryRoomy = secondary.filter((row) => !row.tight); + const fallbackRoomy = fallback.filter((row) => !row.tight); + + // 1. Primary (not 5h-tight) + if (primaryRoomy.length > 0) { + return pickWithinTier(primaryRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + } + // 2. Secondary (not 5h-tight) + if (secondaryRoomy.length > 0) { + const result = pickWithinTier(secondaryRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + const hadPrimary = enabled.some((row) => row.tier === 'primary'); + return hadPrimary ? { picked: result.picked, why: 'secondaryFallback' } : result; + } + // 3. Primary (5h-tight) + if (primary.length > 0) { + return pickTightPool(primary, { keepKey: options.keepKey, keep }); + } + // 4. Secondary (5h-tight) + if (secondary.length > 0) { + const result = pickTightPool(secondary, { keepKey: options.keepKey, keep }); + const hadPrimary = enabled.some((row) => row.tier === 'primary'); + return hadPrimary ? { picked: result.picked, why: 'secondaryFallback' } : result; + } + // 5 & 6. Fallback (roomy then 5h-tight) + const hadHigherTier = enabled.some((row) => row.tier !== 'fallback'); + if (fallbackRoomy.length > 0) { + const result = pickWithinTier(fallbackRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + if (!hadHigherTier) return result; + return { picked: result.picked, why: result.picked.payAsYouGo ? 'paygFallback' : 'tierFallback' }; + } + const result = pickTightPool(fallback, { keepKey: options.keepKey, keep }); + if (!hadHigherTier) return result; + return { picked: result.picked, why: result.picked.payAsYouGo ? 'paygFallback' : 'tierFallback' }; +} + +export function pickModelGroupCandidate(route, facts, options) { + const { now } = options; + const anyVision = !!options.needsImage && route.candidates.some((candidate, index) => + !candidate.off && facts[index]?.available === true && facts[index]?.acceptsImage === true); + const rows = route.candidates.map((candidate, index) => { + const fact = facts[index]; + const state = fact?.windows ? quotaWindowsScheduleState(fact.windows, now) : null; + const outerUsesHeadroom = route.strategy === 'headroom'; + const innerUsesHeadroom = candidate.via?.strategy === 'headroom'; + const headroom = outerUsesHeadroom || innerUsesHeadroom ? modelGroupHeadroom(fact?.windows ?? null, now) : null; + const remaining = fact?.inner ? fact.inner.headroom : headroom?.left ?? null; + const quota = headroom?.window ?? state?.quota ?? null; + const running = typeof fact?.running === 'number' && Number.isFinite(fact.running) && fact.running > 0 + ? Math.floor(fact.running) + : 0; + const payAsYouGo = fact?.payAsYouGo === true && quota === null && !fact?.inner; + const defaultTier = fact?.defaultTier ?? (payAsYouGo ? 'fallback' : 'primary'); + const innerTier = candidate.tier ?? defaultTier; + const outerTier = candidate.via?.tier ?? innerTier; + return { + candidate, + index, + key: modelGroupCandidateKey(candidate), + noVision: anyVision && fact?.acceptsImage !== true, + usable: !candidate.off && fact?.available === true && !(anyVision && fact?.acceptsImage !== true), + limited: fact?.inner ? fact.inner.limited : state?.limited ?? false, + limitedUntilMs: fact?.inner ? null : state?.resetAtMs ?? null, + tight: fact?.inner ? fact.inner.fiveHourTight : state?.fiveHourTight ?? false, + urgency: fact?.inner ? fact.inner.urgency : state?.urgency ?? null, + quota, + headroom: outerUsesHeadroom ? remaining : null, + weight: modelGroupWeight(candidate.via ? candidate.via.weight : candidate.weight), + group: candidate.via?.key ?? null, + innerHeadroom: innerUsesHeadroom ? remaining : null, + payAsYouGo, + innerTier, + outerTier, + tier: outerTier, + running, + }; + }); + + const benched = new Set(); + const innerWhy = new Map(); + const groupRep = new Map(); + const groupSize = new Map(); + const groups = new Map(); + for (const row of rows) if (row.group) groups.set(row.group, [...(groups.get(row.group) ?? []), row]); + for (const [group, members] of groups) { + const inUsable = members.filter((row) => row.usable); + const inReady = inUsable.filter((row) => !row.limited); + groupSize.set(group, inUsable.length); + if (inReady.length === 0) continue; + const strategy = members[0].candidate.via.strategy; + let winner = inReady[0]; + let reason = strategy; + if (strategy === 'expiring') { + const innerReady = inReady.map((row) => ({ ...row, tier: row.innerTier })); + const innerEnabled = members.filter((row) => !row.candidate.off).map((row) => ({ ...row, tier: row.innerTier })); + const auto = pickAutoCandidate(innerReady, innerEnabled, { + now, + lastPickedKey: options.lastPickedKey, + usageProfile: options.usageProfile, + keepKey: options.keepKey, + }); + winner = inReady.find((row) => row.index === auto.picked.index) ?? inReady[0]; + reason = auto.why; + } else { + const result = pickRouteMember(members.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: row.key, + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: modelGroupWeight(row.candidate.weight), + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.innerHeadroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), strategy, { lastPicked: options.lastPickedKey ?? null }); + winner = inReady.find((row) => row.key === result.key) ?? inReady[0]; + const keep = options.keepKey ? inReady.find((row) => row.key === options.keepKey) : undefined; + if (keep && keep !== winner && keepsCurrent( + strategy, + { index: keep.index, headroom: keep.innerHeadroom }, + { index: winner.index, headroom: winner.innerHeadroom }, + facts, + )) winner = keep; + if (result.plain) reason = 'order'; + } + innerWhy.set(group, reason); + groupRep.set(group, winner); + for (const row of members) if (row !== winner) benched.add(row.index); + } + + const entryKey = (row) => modelGroupCandidateRowKey(row.candidate); + const lastRow = options.lastPickedKey ? rows.find((row) => row.key === options.lastPickedKey) : undefined; + const outerLast = options.lastPickedRowKey ?? (lastRow ? entryKey(lastRow) : options.lastPickedKey ?? null); + const enabledOuter = rows.filter((row) => !row.candidate.off && !benched.has(row.index)); + const usable = rows.filter((row) => row.usable && !benched.has(row.index)); + const ready = usable.filter((row) => !row.limited); + const current = options.keepKey ? rows.find((row) => row.key === options.keepKey) : undefined; + const keep = current ? ready.find((row) => entryKey(row) === entryKey(current)) : undefined; + + let picked = null; + let why = 'only'; + let weightStep; + let strategyWhy = route.strategy; + if (ready.length > 0) { + if (route.strategy === 'expiring') { + const auto = pickAutoCandidate(ready, enabledOuter, { + now, + lastPickedKey: ready.find((row) => entryKey(row) === outerLast)?.key, + usageProfile: options.usageProfile, + keepKey: keep?.key ?? options.keepKey, + }); + picked = auto.picked; + strategyWhy = auto.why; + why = usable.length === 1 ? 'only' : strategyWhy; + } else { + const entries = rows.filter((row) => !benched.has(row.index) + && (!row.group || innerWhy.has(row.group) || row === groups.get(row.group)[0])); + const result = pickRouteMember(entries.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: entryKey(row), + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: row.weight, + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.headroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), route.strategy, { lastPicked: outerLast, weightCounters: options.weightCounters }); + picked = ready.find((row) => entryKey(row) === result.key) ?? ready[0]; + weightStep = result.weightStep; + if (keep && keep !== picked && keepsCurrent(route.strategy, keep, picked, facts)) { + picked = keep; + weightStep = undefined; + } + if (result.plain) strategyWhy = 'order'; + else if (route.strategy === 'drain' && entryKey(picked) !== outerLast && entries.some((row) => entryKey(row) === outerLast)) { + strategyWhy = 'drainNext'; + } + why = usable.length === 1 ? 'only' : strategyWhy; + if (why === 'cheapest') { + const cost = costOf(facts[picked.index]); + why = cost === 0 && facts[picked.index]?.windows ? 'cheapestFree' : Number.isFinite(cost) ? 'cheapest' : 'order'; + } + } + } else if (usable.length > 0) { + picked = usable.reduce((best, row) => + (row.limitedUntilMs ?? Number.POSITIVE_INFINITY) < (best.limitedUntilMs ?? Number.POSITIVE_INFINITY) ? row : best); + why = usable.length === 1 ? 'only' : 'soonest'; + } + + if (picked?.group && why === 'only' && (groupSize.get(picked.group) ?? 0) > 1) why = innerWhy.get(picked.group) ?? why; + + const trace = rows.map((row) => { + const fact = facts[row.index]; + const base = { + agentKind: row.candidate.agentKind, + providerId: row.candidate.providerId, + model: row.candidate.model, + ...(row.candidate.agentDeviceId ? { agentDeviceId: row.candidate.agentDeviceId } : {}), + ...(row.candidate.accountId ? { accountId: row.candidate.accountId } : {}), + modelName: fact?.modelName || row.candidate.model, + sourceName: fact?.sourceName || row.candidate.providerId, + quota: row.quota, + }; + if (row === picked) return { ...base, state: 'picked', why, ...(row.limited ? { limitedUntilMs: row.limitedUntilMs } : {}) }; + if (row.candidate.off) return { ...base, state: 'skipped', why: 'off' }; + if (fact?.available !== true) return { ...base, state: 'skipped', why: 'unavailable' }; + if (row.noVision) return { ...base, state: 'skipped', why: 'noVision' }; + if (row.limited) return { ...base, state: 'skipped', why: 'limited', limitedUntilMs: row.limitedUntilMs }; + + const isBenchedMember = !!row.group && benched.has(row.index); + const effectiveStrategy = isBenchedMember ? row.candidate.via.strategy : route.strategy; + const reserveRank = (reason) => ( + reason === 'paygReserve' || reason === 'tierReserve' ? 2 + : reason === 'secondaryReserve' ? 1 + : 0 + ); + const standbyReasonFor = (entry, peers, tierOf) => { + const rowTier = tierOf(entry); + if (rowTier === 'fallback' && peers.some((other) => tierOf(other) !== 'fallback')) { + return { state: 'standby', why: entry.payAsYouGo ? 'paygReserve' : 'tierReserve' }; + } + if (rowTier === 'secondary' && peers.some((other) => tierOf(other) === 'primary' && !other.tight)) { + return { state: 'standby', why: 'secondaryReserve' }; + } + if (entry.tight && peers.some((other) => !other.tight && (rowTier === 'fallback' || tierOf(other) !== 'fallback'))) { + return { state: 'skipped', why: 'tight' }; + } + if (rowTier === 'secondary' && peers.some((other) => tierOf(other) === 'primary')) { + return { state: 'standby', why: 'secondaryReserve' }; + } + return { state: 'standby', why: 'standby' }; + }; + const innerOutcome = effectiveStrategy === 'expiring' + ? standbyReasonFor( + row, + isBenchedMember ? groups.get(row.group).filter((other) => other.usable && !other.limited) : ready, + (entry) => (isBenchedMember ? entry.innerTier : entry.outerTier), + ) + : { state: 'standby', why: 'standby' }; + + if (isBenchedMember && innerOutcome.state === 'standby' && route.strategy === 'expiring') { + const rep = groupRep.get(row.group); + if (rep && rep !== picked) { + const repOuter = standbyReasonFor(rep, ready, (entry) => entry.outerTier); + if (repOuter.state === 'standby' && reserveRank(repOuter.why) > reserveRank(innerOutcome.why)) { + const inheritedWhy = repOuter.why === 'paygReserve' && !row.payAsYouGo ? 'tierReserve' : repOuter.why; + return { ...base, state: 'standby', why: inheritedWhy }; + } + } + } + if (effectiveStrategy === 'expiring') return { ...base, ...innerOutcome }; + return { ...base, state: 'standby', why: 'standby' }; + }); + + return { + index: picked?.index ?? null, + trace, + ...(options.needsImage ? { image: anyVision ? 'applied' : 'fallback' } : {}), + ...(weightStep ? { weightStep } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-identity.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-identity.mjs new file mode 100644 index 0000000..84156b4 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-identity.mjs @@ -0,0 +1,107 @@ +export const PLUGIN_ENGINE_PROVIDER_PREFIX = 'acp-plugin:'; +export const PROVIDER_SHARE_AGENT_DEVICE_PREFIX = 'share:'; + +export function isByokProviderId(value) { + return typeof value === 'string' && /^byok-[a-z0-9][a-z0-9-]{0,185}$/.test(value); +} + +export function isOrganizationManagedProvider(provider) { + return provider?.source === 'organization'; +} + +export function isProviderShareAgentDeviceId(value) { + return typeof value === 'string' && value.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX); +} + +export function pluginEngineKeyFromProviderId(providerId) { + if (!providerId || !providerId.startsWith(PLUGIN_ENGINE_PROVIDER_PREFIX)) return null; + const key = providerId.slice(PLUGIN_ENGINE_PROVIDER_PREFIX.length); + const separator = key.lastIndexOf(':'); + return separator > 0 && separator < key.length - 1 ? key : null; +} + +/** Exact product scope, not brand/name matching. Never send a proxy's credential to Kimi. */ +export function kimiCodingUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (!['https://api.kimi.com', 'https://api.kimi.ai'].includes(url.origin)) return null; + if (!['/coding', '/coding/', '/coding/v1', '/coding/v1/'].includes(url.pathname)) return null; + return `${url.origin}/coding/v1/usages`; + } catch { + return null; + } +} + +export function isKimiCodingProvider(provider, agent) { + if (!provider || !['apiKey', 'oauth'].includes(provider.auth?.method)) return false; + if ( + provider.auth.method === 'oauth' + && !['https://auth.kimi.com/api/oauth/token', 'https://auth.kimi.ai/api/oauth/token'].includes( + provider.auth.oauth?.tokenUrl ?? '', + ) + ) { + return false; + } + return (agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {})).some( + (route) => route && !route.disabled && kimiCodingUsageEndpoint(route.upstream) !== null, + ); +} + +export function isKimiCodingProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.kimiCodingUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isKimiCodingProvider(provider, agent); +} + +/** Resolve only OpenCode Go's official inference route, never a user proxy. */ +export function opencodeGoUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (url.origin !== 'https://opencode.ai') return null; + if (!['/zen/go', '/zen/go/v1'].includes(url.pathname.replace(/\/+$/, ''))) return null; + return 'https://opencode.ai/zen/go/v1/usage'; + } catch { + return null; + } +} + +export function isOpenCodeGoProvider(provider, agent) { + if (!provider || provider.auth?.method !== 'apiKey') return false; + const routes = agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {}); + return routes.some( + (route) => route && !route.disabled && opencodeGoUsageEndpoint(route.upstream) !== null, + ); +} + +export function isOpenCodeGoProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.opencodeGoUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isOpenCodeGoProvider(provider, agent); +} + +export const ZHIPU_CODING_PLAN_ORIGINS = ['https://open.bigmodel.cn', 'https://api.z.ai']; + +export function isZhipuCodingPlanPath(pathname) { + return pathname === '/api/anthropic' || pathname.startsWith('/api/anthropic/') || pathname.startsWith('/api/coding/'); +} + +export function isZhipuCodingPlanRoute(route) { + if (!route?.upstream || route.disabled) return false; + let url; + try { + url = new URL(route.upstream); + } catch { + return false; + } + return ZHIPU_CODING_PLAN_ORIGINS.includes(url.origin) && isZhipuCodingPlanPath(url.pathname); +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-quota-source.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-quota-source.mjs new file mode 100644 index 0000000..6482e76 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/provider-quota-source.mjs @@ -0,0 +1,77 @@ +import { MODEL_GROUP_TIERS } from './model-groups.mjs'; +import { + isByokProviderId, + isKimiCodingProviderView, + isOpenCodeGoProviderView, + isOrganizationManagedProvider, + isProviderShareAgentDeviceId, + isZhipuCodingPlanRoute, + pluginEngineKeyFromProviderId, +} from './provider-identity.mjs'; + +export function isPayAsYouGoProvider(provider) { + return provider?.access?.kind === 'api' || provider?.id === 'xd'; +} + +// Incomplete: checks provider-wide coding plan only, ignoring per-engine distinction. +export function isZhipuCodingPlanProviderView(view) { + if (!view || view.auth?.method !== 'apiKey') return false; + return view.zhipuCodingPlanUsage === true || Object.values(view.routing ?? {}).some(isZhipuCodingPlanRoute); +} + +// Incomplete: implements 3-tier static defaults at provider level, missing per-engine coding plan awareness. +export function defaultModelGroupSourceTier(input) { + if (input.accountPayAsYouGo) return 'fallback'; + if (input.agentDeviceId && isProviderShareAgentDeviceId(input.agentDeviceId)) return 'secondary'; + const view = input.provider ?? null; + if ((view && isOrganizationManagedProvider(view)) || isByokProviderId(input.providerId)) return 'secondary'; + if (input.agentKind === 'acp' || pluginEngineKeyFromProviderId(input.providerId) !== null) return 'primary'; + if (view) { + if (isKimiCodingProviderView(view) || isOpenCodeGoProviderView(view) || isZhipuCodingPlanProviderView(view)) { + return 'primary'; + } + if (view.auth?.method === 'none') return 'primary'; + if (isPayAsYouGoProvider(view)) return 'fallback'; + if (view.access?.kind === 'subscription' || view.auth?.method === 'oauth') return 'primary'; + if (view.access?.kind === 'managed') return 'secondary'; + return 'primary'; + } + if (input.providerId === 'xd') return 'fallback'; + return 'primary'; +} + +// Incomplete: omits per-engine mixed-tier follow-source and override preservation. +export function resolveSourceDefaultTier(source, provider) { + return defaultModelGroupSourceTier({ + agentKind: source.agentKind, + providerId: source.providerId, + agentDeviceId: source.agentDeviceId, + provider, + accountPayAsYouGo: source.accountPayAsYouGo, + }); +} + +export function resolveTierControlState({ value, defaultTier }) { + const effective = value ?? defaultTier ?? 'primary'; + return { + effective, + showFollow: false, + options: [...MODEL_GROUP_TIERS], + }; +} + +export function applyTierControlSelection({ value, defaultTier }, next) { + const state = resolveTierControlState({ value, defaultTier }); + if (next === state.effective) return value; + return next === defaultTier ? undefined : next; +} + +export function retargetCandidateWithTier(previous, selected) { + return { + ...selected, + ...(previous.off ? { off: previous.off } : {}), + ...(previous.weight !== undefined ? { weight: previous.weight } : {}), + ...(previous.tier ? { tier: previous.tier } : {}), + ...(previous.effort ? { effort: previous.effort } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/remote-catalog.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/remote-catalog.mjs new file mode 100644 index 0000000..230886d --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/remote-catalog.mjs @@ -0,0 +1,90 @@ +import { + isKimiCodingProvider, + isOpenCodeGoProvider, + isZhipuCodingPlanRoute, +} from './provider-identity.mjs'; + +const VALID_WIRE_PROTOCOLS = new Set([ + 'openai-chat', + 'openai-responses', + 'google-generative-ai', + 'anthropic-messages', +]); + +export function projectRoutingForDisplay(routing) { + if (!routing || typeof routing !== 'object' || Array.isArray(routing)) return undefined; + const out = {}; + for (const [agent, value] of Object.entries(routing)) { + const route = value && typeof value === 'object' && !Array.isArray(value) ? value : null; + const wireProtocol = VALID_WIRE_PROTOCOLS.has(route?.wireProtocol) + ? route.wireProtocol + : route?.authStrategy && route.wireProtocol === undefined + ? agent === 'codex' + ? 'openai-responses' + : agent === 'claude-code' + ? 'anthropic-messages' + : undefined + : undefined; + out[agent] = { + ...(wireProtocol ? { wireProtocol } : {}), + ...(route?.disabled === true ? { disabled: true } : {}), + }; + } + return out; +} + +/** + * Redact a provider list payload before returning it over the remote device-link tunnel. + * Pre-PR #15050 version: omits per-engine `zhipuCodingPlanUsageAgents` and does not strip stored `zhipuCodingPlanUsageAgents`. + */ +export function redactProviderCatalogForTunnel(result, options = {}) { + if (!result || typeof result !== 'object' || !Array.isArray(result.providers)) return result; + const { + sameAccountController = false, + readZhipuCodingPlanAccountUsage = true, + } = options; + const runtimeAgents = ['claude-code', 'codex', 'pi']; + + const providers = result.providers.map((p) => { + const rest = { ...p }; + delete rest.runLocation; + if (!sameAccountController) { + delete rest.subscriptionPoolTarget; + delete rest.subscriptionAccountKeys; + if (rest.openAiAccount && typeof rest.openAiAccount === 'object') { + const { accountKey: _key, ...account } = rest.openAiAccount; + rest.openAiAccount = account; + } + } + delete rest.remoteInvocationEnabled; + if (typeof p.remoteInvocationEnabled === 'boolean') rest.remoteInvocationEnabled = p.remoteInvocationEnabled; + + delete rest.zhipuCodingPlanUsage; + if ( + sameAccountController + && readZhipuCodingPlanAccountUsage + && p.remoteInvocationEnabled === true + && p.connected && !p.suspended && !p.removed + && p.auth?.method === 'apiKey' + && Object.values(p.routing ?? {}).some(isZhipuCodingPlanRoute) + ) { + rest.zhipuCodingPlanUsage = true; + } + + delete rest.kimiCodingUsageAgents; + const kimiAgents = runtimeAgents.filter((agent) => isKimiCodingProvider(p, agent)); + if (kimiAgents.length > 0) rest.kimiCodingUsageAgents = kimiAgents; + + delete rest.opencodeGoUsageAgents; + const opencodeGoAgents = runtimeAgents.filter((agent) => isOpenCodeGoProvider(p, agent)); + if (opencodeGoAgents.length > 0) rest.opencodeGoUsageAgents = opencodeGoAgents; + + rest.routing = projectRoutingForDisplay(p.routing); + return rest; + }); + + return { + ...result, + providers, + }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/resolver.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/resolver.mjs new file mode 100644 index 0000000..05c9312 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/resolver.mjs @@ -0,0 +1,118 @@ +import { expandMergedSources } from './model-groups.mjs'; +import { pickModelGroupCandidate } from './pick.mjs'; +import { pluginEngineKeyFromProviderId } from './provider-identity.mjs'; +import { defaultModelGroupSourceTier } from './provider-quota-source.mjs'; +import { effectiveModelGroupsConfig } from './source-routes.mjs'; + +const AGENT_FOR_KIND = { cc: 'claude-code', codex: 'codex', pi: 'pi' }; + +export function createModelGroupResolver(deps) { + const now = deps.now ?? Date.now; + + async function resolve(request) { + const rawConfig = deps.config(); + const views = await deps.views(); + const agents = deps.agents ? deps.agents() : ['claude-code', 'codex', 'pi']; + const effectiveConfig = deps.catalog + ? effectiveModelGroupsConfig(rawConfig, deps.catalog(views, agents)) + : rawConfig; + + const rawRoute = (effectiveConfig.routes ?? []).find((r) => r.id === request.selection?.id); + if (!rawRoute) { + return { outcome: 'unavailable', reason: 'route_not_found', trace: [] }; + } + const route = expandMergedSources(rawRoute, effectiveConfig); + const windowsMap = deps.quotaWindows ? await deps.quotaWindows() : new Map(); + const usageProfile = deps.usageProfile ? deps.usageProfile() : null; + + const facts = await Promise.all(route.candidates.map(async (candidate) => { + const agentDeviceId = candidate.agentDeviceId ?? null; + const isAcp = candidate.agentKind === 'acp' || pluginEngineKeyFromProviderId(candidate.providerId) !== null; + if (isAcp) { + const engine = deps.pluginEngines ? (await deps.pluginEngines()).find((e) => e.providerId === candidate.providerId) : null; + const available = engine ? !engine.suspended && engine.availability?.state !== 'unavailable' : false; + const windows = windowsMap.get(candidate.providerId) ?? null; + const defaultTier = defaultModelGroupSourceTier({ + agentKind: 'acp', + providerId: candidate.providerId, + agentDeviceId, + }); + return { + available, + modelName: candidate.model, + sourceName: engine?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + defaultTier, + acceptsImage: true, + }; + } + + const locationViews = agentDeviceId && deps.remoteViews + ? (await deps.remoteViews(agentDeviceId)) + : views; + const view = locationViews.find((v) => v.id === candidate.providerId) ?? null; + const agent = AGENT_FOR_KIND[candidate.agentKind]; + const modelEntry = view?.models?.[agent]?.find((m) => m.id === candidate.model) ?? null; + const installed = deps.harnessInstalled ? await deps.harnessInstalled(agent, agentDeviceId) : true; + const accountFact = !agentDeviceId && candidate.accountId && deps.localAccount + ? deps.localAccount(candidate.providerId, candidate.accountId, candidate.model, candidate.agentKind) + : null; + const available = Boolean( + view && view.connected && !view.suspended && !view.removed + && installed + && modelEntry && !modelEntry.disabled + && (!accountFact || accountFact.usable !== false), + ); + const defaultTier = defaultModelGroupSourceTier({ + agentKind: candidate.agentKind, + providerId: candidate.providerId, + agentDeviceId, + provider: view, + accountPayAsYouGo: accountFact?.payAsYouGo, + }); + const payAsYouGo = defaultTier === 'fallback'; + const keyForQuota = candidate.accountId ? `${candidate.providerId}#${candidate.accountId}` : candidate.providerId; + const windows = accountFact?.windows ?? windowsMap.get(keyForQuota) ?? windowsMap.get(candidate.providerId) ?? null; + const running = candidate.accountId + ? (accountFact?.running ?? 0) + : (deps.runningCount ? deps.runningCount(candidate.providerId, agentDeviceId) : 0); + + return { + available, + modelName: modelEntry?.name ?? candidate.model, + sourceName: view?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + ...(payAsYouGo ? { payAsYouGo: true } : {}), + defaultTier, + ...(running > 0 ? { running } : {}), + acceptsImage: modelEntry?.imageInput !== false, + ...(typeof modelEntry?.price === 'number' ? { price: modelEntry.price } : {}), + }; + })); + + const picked = pickModelGroupCandidate(route, facts, { + now: now(), + lastPickedKey: request.lastPickedKey ?? null, + lastPickedRowKey: request.lastPickedRowKey ?? null, + needsImage: request.needsImage === true, + weightCounters: request.weightCounters, + usageProfile, + keepKey: request.keepKey ?? null, + }); + + if (picked.index === null) { + return { outcome: 'unavailable', reason: 'no_available_candidate', trace: picked.trace }; + } + const chosen = route.candidates[picked.index]; + const pickedEntry = picked.trace[picked.index]; + return { + outcome: 'routed', + route: chosen, + why: pickedEntry.why, + trace: picked.trace, + ...(picked.weightStep ? { weightStep: picked.weightStep } : {}), + }; + } + + return { resolve }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/scheduler.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/scheduler.mjs new file mode 100644 index 0000000..664190f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/scheduler.mjs @@ -0,0 +1,119 @@ +export const PROVIDER_GROUP_SIMILAR_URGENCY = 0.9; +export const ROUTE_FIVE_HOUR_SHARE_PERCENT = 15; + +export function fiveHourTightFor(member) { + if (typeof member.fiveHourLeft === 'number' && Number.isFinite(member.fiveHourLeft)) { + return member.fiveHourLeft / (Math.max(0, member.running) + 1) <= ROUTE_FIVE_HOUR_SHARE_PERCENT; + } + return member.fiveHourTight === true; +} + +export function applyRouteWeightStep(counters, step) { + const next = new Map(counters); + let total = 0; + for (const { key, weight } of step.participants) { + next.set(key, (next.get(key) ?? 0) + weight); + total += weight; + } + next.set(step.pickedKey, (next.get(step.pickedKey) ?? 0) - total); + return next; +} + +function eligibleMembers(members, options) { + return members.filter((m) => m.usable && !m.paused && !options.exclude?.has(m.key)); +} + +function openMembers(members, options) { + return eligibleMembers(members, options).filter((m) => m.running < m.limit); +} + +function byQuota(open, keepUnknown) { + const roomy = open.filter((member) => !fiveHourTightFor(member)); + const pool = roomy.length > 0 ? roomy : open; + const known = (member) => typeof member.urgency === 'number' && Number.isFinite(member.urgency); + const urgencies = pool.filter(known).map((member) => member.urgency); + if (urgencies.length === 0) return pool; + const top = Math.max(...urgencies); + return pool.filter((member) => (known(member) ? member.urgency >= top * PROVIDER_GROUP_SIMILAR_URGENCY : keepUnknown)); +} + +export function routeSchedulingCandidates(members, strategy, options = {}) { + const reachable = openMembers(members, options); + const withPlan = reachable.filter((m) => !m.quotaSpent); + const open = withPlan.length > 0 ? withPlan : reachable; + return strategy === 'expiring' ? byQuota(open, options.keepUnknownQuota === true) : open; +} + +function activeLoadOf(member) { + const value = member.selectionRunning ?? member.running; + return Number.isFinite(value) ? value : Number.POSITIVE_INFINITY; +} + +function residentOf(member) { + return typeof member.residentLoad === 'number' && Number.isFinite(member.residentLoad) && member.residentLoad > 0 + ? member.residentLoad + : 0; +} + +function leastBusy(open, allMembers, lastIndex, rotateTies) { + let minRunning = Number.POSITIVE_INFINITY; + for (const m of open) { + const load = activeLoadOf(m); + if (load < minRunning) minRunning = load; + } + const leastRunning = open.filter((m) => activeLoadOf(m) === minRunning); + let minResident = Number.POSITIVE_INFINITY; + for (const m of leastRunning) { + const res = residentOf(m); + if (res < minResident) minResident = res; + } + const tied = leastRunning.filter((m) => residentOf(m) === minResident); + if (rotateTies && lastIndex >= 0 && tied.length > 1) { + return tied.find((m) => allMembers.indexOf(m) > lastIndex) ?? tied[0]; + } + return tied[0]; +} + +function costOf(member) { + return typeof member.cost === 'number' && Number.isFinite(member.cost) && member.cost >= 0 + ? member.cost + : Number.POSITIVE_INFINITY; +} + +export function pickRouteMember(members, strategy, options = {}) { + const open = routeSchedulingCandidates(members, strategy, options); + if (open.length === 0) return { key: null }; + const lastIndex = options.lastPicked ? members.findIndex((m) => m.key === options.lastPicked) : -1; + const after = () => open.find((m) => members.indexOf(m) > lastIndex) ?? open[0]; + switch (strategy) { + case 'order': + return { key: open[0].key }; + case 'rotate': { + const last = open.find((m) => m.key === options.lastPicked); + if (last && (options.roundPicks ?? 1) < (last.roundSlots ?? 1)) return { key: last.key }; + return { key: after().key }; + } + case 'drain': { + const last = open.find((m) => m.key === options.lastPicked); + return { key: (last ?? after()).key }; + } + case 'weighted': { + const rows = open.map((m) => ({ key: m.key, weight: Math.max(1, m.weight) })); + const score = (row) => (options.weightCounters?.get(row.key) ?? 0) + row.weight; + const best = rows.reduce((top, row) => (score(row) > score(top) ? row : top)); + return { key: best.key, weightStep: { participants: rows, pickedKey: best.key } }; + } + case 'headroom': { + const known = open.filter((m) => typeof m.headroom === 'number' && Number.isFinite(m.headroom)); + if (known.length === 0) return { key: open[0].key, plain: true }; + return { key: known.reduce((best, m) => (m.headroom > best.headroom ? m : best)).key }; + } + case 'cheapest': { + const priced = open.filter((m) => Number.isFinite(costOf(m))); + if (priced.length === 0) return { key: open[0].key, plain: true }; + return { key: priced.reduce((best, m) => (costOf(m) < costOf(best) ? m : best)).key }; + } + default: + return { key: leastBusy(open, members, lastIndex, options.rotateTies === true).key }; + } +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/source-routes.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/source-routes.mjs new file mode 100644 index 0000000..2a97d2d --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/source-routes.mjs @@ -0,0 +1,272 @@ +import { createHash } from 'node:crypto'; +import { + MODEL_GROUP_AUTO_PREFIX, + MODEL_GROUP_EXPANDED_PREFIX, + MODEL_GROUP_LIMITS, + modelGroupSourceKey, + modelGroupTierRank, +} from './model-groups.mjs'; +import { isProviderShareAgentDeviceId } from './provider-identity.mjs'; +import { defaultModelGroupSourceTier } from './provider-quota-source.mjs'; + +const GROUP_KIND = { 'claude-code': 'cc', codex: 'codex', pi: 'pi' }; +const NOT_A_FAMILY = new Set(['xd', 'cindy']); +const FAMILY_OF = { 'openai-spectrum': 'openai' }; + +export function providerFamily(view) { + const kind = view.logoKind ?? (['openai', 'anthropic', 'google', 'xai', 'deepseek', 'kimi', 'glm'].includes(view.id) ? view.id : null); + if (!kind || NOT_A_FAMILY.has(kind)) return null; + return FAMILY_OF[kind] ?? kind; +} + +const usable = (view) => view.connected && !view.suspended && !view.removed && !view.subscriptionPoolAlias; + +function locationViews(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.views; + return catalog.remote?.get(agentDeviceId)?.providers ?? []; +} + +function locationAgents(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.agents; + return catalog.remote?.get(agentDeviceId)?.agents ?? catalog.agents; +} + +function flattenableAccounts(catalog, providerId) { + const all = catalog.localAccounts?.get(providerId); + const active = all?.filter((account) => account.paused !== true); + return all && all.length >= 2 && active && active.length > 0 ? active : null; +} + +export function sourceModelKey(view, agent, modelId) { + const declared = view.routing?.[agent]?.modelIdRewrite?.stripPrefix; + const id = (declared && modelId.startsWith(declared) ? modelId.slice(declared.length) : modelId).toLowerCase(); + return id.replace(/^[a-z0-9][a-z0-9._-]*\/([^/]+)$/, '$1'); +} + +function expandedId(routeId, modelKey) { + return `${MODEL_GROUP_EXPANDED_PREFIX}${createHash('sha256').update(`${routeId}\u0000${modelKey}`).digest('hex').slice(0, 40)}`; +} + +function runnableProviderModels(catalog, view, source, account) { + if (!usable(view)) return []; + const views = locationViews(catalog, source.agentDeviceId); + const agents = locationAgents(catalog, source.agentDeviceId); + const allowed = agents.filter((agent) => agent in GROUP_KIND); + const seen = new Set(); + const out = []; + for (const agent of allowed) { + for (const model of view.models?.[agent] ?? []) { + const key = sourceModelKey(view, agent, model.id); + if (model.disabled || seen.has(key)) continue; + if (account?.supportedModelIds && !account.supportedModelIds.has(model.id.replace(/^chatgpt\//, ''))) continue; + const agentKind = GROUP_KIND[agent]; + const candidate = { + agentKind, + providerId: view.id, + model: model.id, + ...(source.agentDeviceId ? { agentDeviceId: source.agentDeviceId } : {}), + ...(source.accountId ? { accountId: source.accountId } : {}), + ...(source.off ? { off: true } : {}), + ...(source.weight ? { weight: source.weight } : {}), + ...(source.tier ? { tier: source.tier } : {}), + }; + if (catalog.available && !catalog.available(candidate, views, agents)) continue; + seen.add(key); + out.push({ + key, + name: model.name ?? key, + candidate, + }); + } + } + return out; +} + +function memberSourceKey(member) { + return modelGroupSourceKey({ + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }); +} + +function accountKeysFor(view, accountId, account) { + if (accountId) return account?.accountKey ? [account.accountKey] : []; + return view?.subscriptionAccountKeys ?? []; +} + +function withoutRepeatedAccounts(members, catalog, offKeys) { + const localActiveKeys = new Set(); + const localModelKeys = new Set(); + for (const m of members) { + if (m.agentDeviceId || offKeys.has(memberSourceKey(m))) continue; + for (const k of accountKeysFor(m.view, m.accountId, m.account)) localActiveKeys.add(k); + if (m.view) { + for (const item of runnableProviderModels(catalog, m.view, { accountId: m.accountId }, m.account)) { + localModelKeys.add(item.key); + } + } + } + return members.filter((m) => { + if (!m.agentDeviceId || isProviderShareAgentDeviceId(m.agentDeviceId)) return true; + const keys = accountKeysFor(m.view, m.accountId, m.account); + if (keys.length === 0 || !keys.every((k) => localActiveKeys.has(k))) return true; + const models = m.view ? runnableProviderModels(catalog, m.view, { agentDeviceId: m.agentDeviceId }) : []; + return models.length > 0 && models.some((item) => !localModelKeys.has(item.key)); + }); +} + +// Incomplete: sorts by default tier and passes tier, but blindly inherits whole-provider `tier` onto PAYG pool keys. +export function buildAutoSourceRoutes(config, catalog) { + const families = new Map(); + const add = (view, agentDeviceId) => { + if (!usable(view)) return; + const family = providerFamily(view); + if (!family) return; + const accounts = !agentDeviceId ? flattenableAccounts(catalog, view.id) : null; + if (accounts) { + const expanded = accounts.map((account) => ({ + id: view.id, + name: view.name ?? family, + accountId: account.id, + account, + view, + })); + families.set(family, [...(families.get(family) ?? []), ...expanded]); + } else { + families.set(family, [ + ...(families.get(family) ?? []), + { id: view.id, name: view.name ?? family, ...(agentDeviceId ? { agentDeviceId } : {}), view }, + ]); + } + }; + for (const view of catalog.views ?? []) add(view); + for (const [deviceId, entry] of catalog.remote ?? []) { + for (const view of entry.providers ?? []) add(view, deviceId); + } + + const hidden = new Set(config.hiddenAuto ?? []); + const routes = []; + for (const [family, found] of families) { + const id = `${MODEL_GROUP_AUTO_PREFIX}${family}`.slice(0, MODEL_GROUP_LIMITS.id); + const saved = config.autoSources?.[id] ?? []; + const rank = new Map(saved.map((source, index) => [modelGroupSourceKey(source), { index, source }])); + const savedFor = (source) => + rank.get(modelGroupSourceKey(source)) + ?? (source.accountId ? rank.get(modelGroupSourceKey({ providerId: source.providerId })) : undefined); + const offKeys = new Set(); + for (const member of found) { + const source = { + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }; + if (savedFor(source)?.source.off) offKeys.add(memberSourceKey(member)); + } + const own = withoutRepeatedAccounts(found, catalog, offKeys) + .map((member, index) => ({ + member, + index, + rank: modelGroupTierRank(defaultModelGroupSourceTier({ + providerId: member.id, + agentDeviceId: member.agentDeviceId, + provider: member.view, + accountPayAsYouGo: Boolean(member.account?.apiConnectionId), + })), + })) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .map(({ member }) => member); + if (own.length < 2) continue; + const detected = own.map(({ id: providerId, agentDeviceId, accountId }) => ({ + providerId, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + })); + const ordered = detected + .map((source, index) => ({ source, index, saved: savedFor(source) })) + .sort((a, b) => (a.saved ? a.saved.index : saved.length + a.index) - (b.saved ? b.saved.index : saved.length + b.index) || a.index - b.index) + .map(({ source, saved: kept }) => ({ + ...source, + ...(kept?.source.off ? { off: true } : {}), + ...(kept?.source.weight ? { weight: kept.source.weight } : {}), + ...(kept?.source.tier ? { tier: kept.source.tier } : {}), + })); + routes.push({ + id, + name: own[0].name, + strategy: config.autoStrategy?.[id] ?? 'expiring', + sources: ordered.slice(0, MODEL_GROUP_LIMITS.candidates), + auto: true, + ...(hidden.has(id) ? { hidden: true } : {}), + }); + } + return routes; +} + +export function flattenManualSourceRoute(route, catalog) { + let changed = false; + const seen = new Set(); + const flattened = []; + for (const source of route.sources) { + if (!source.agentDeviceId && !source.accountId) { + const accounts = flattenableAccounts(catalog, source.providerId); + if (accounts) { + changed = true; + for (const account of accounts) { + const item = { ...source, accountId: account.id }; + const key = modelGroupSourceKey(item); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(item); + } + continue; + } + } + const key = modelGroupSourceKey(source); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(source); + } + return changed ? { ...route, sources: flattened.slice(0, MODEL_GROUP_LIMITS.candidates) } : route; +} + +export function expandSourceRouteDetail(route, catalog) { + const byModel = new Map(); + for (const source of route.sources) { + const views = locationViews(catalog, source.agentDeviceId); + const view = views.find((item) => item.id === source.providerId); + if (!view || !usable(view)) continue; + const account = !source.agentDeviceId && source.accountId + ? catalog.localAccounts?.get(source.providerId)?.find((item) => item.id === source.accountId) + : undefined; + for (const item of runnableProviderModels(catalog, view, source, account)) { + const entry = byModel.get(item.key) ?? { name: item.name, items: [] }; + entry.items.push(item.candidate); + byModel.set(item.key, entry); + } + } + const routes = []; + for (const [modelKey, { name, items }] of byModel) { + if (items.length === 0) continue; + routes.push({ + id: expandedId(route.id, modelKey), + name, + strategy: route.strategy, + parent: { id: route.id, name: route.name, model: modelKey }, + candidates: items, + }); + } + return { routes }; +} + +export function effectiveModelGroupsConfig(config, catalog) { + const autoRoutes = buildAutoSourceRoutes(config, catalog); + const manualRoutes = (config.sourceRoutes ?? []).map((route) => flattenManualSourceRoute(route, catalog)); + const sourceRoutes = [...autoRoutes, ...manualRoutes]; + const expanded = sourceRoutes.flatMap((route) => expandSourceRouteDetail(route, catalog).routes); + return { + ...config, + sourceRoutes, + routes: [...(config.routes ?? []), ...expanded], + }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/src/usage.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/usage.mjs new file mode 100644 index 0000000..c8d91ad --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/src/usage.mjs @@ -0,0 +1,64 @@ +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT = 85; +export const PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS = 60 * 60_000; + +function fiveHourTight(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || usedPercent < PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT) return false; + if (resetAtMs === null) return true; + return resetAtMs > now && resetAtMs - now > PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS; +} + +function fiveHourLeft(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || !Number.isFinite(usedPercent)) return null; + if (resetAtMs !== null && (resetAtMs <= now || resetAtMs - now <= PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS)) return null; + return Math.max(0, Math.min(100, 100 - usedPercent)); +} + +function tightestLeft(values) { + const known = values.filter((value) => value !== null); + return known.length > 0 ? Math.min(...known) : null; +} + +function timeLeftPercent(window, now) { + if (window.resetAtMs === null) return window.usedPercent > 0 ? null : 100; + const left = window.resetAtMs - now; + return left > 0 ? Math.min(100, (left / window.windowMs) * 100) : null; +} + +function quotaUrgency(window, now) { + const left = timeLeftPercent(window, now); + return left === null ? null : Math.max(0, 100 - window.usedPercent) / left; +} + +function paceOf(windows, now) { + let pace = null; + for (const window of windows) { + const urgency = quotaUrgency(window, now); + if (urgency === null) return null; + if (!pace || urgency < pace.urgency) pace = { urgency, window }; + } + return pace; +} + +function paceState(windows, now) { + const pace = windows ? paceOf(windows, now) : null; + return { + urgency: pace?.urgency ?? null, + quota: pace?.window ?? null, + headroom: windows && windows.length > 0 ? Math.max(0, 100 - Math.max(...windows.map((w) => w.usedPercent))) : null, + }; +} + +export function quotaWindowsScheduleState(windows, now) { + const live = windows.filter((w) => w.resetAtMs === null || w.resetAtMs > now); + const full = live.filter((w) => w.usedPercent >= 100); + const long = live.filter((w) => w.windowMs > FIVE_HOURS_MS); + const paced = long.length > 0 ? long : live; + return { + limited: full.length > 0, + resetAtMs: full.length > 0 && full.every((w) => w.resetAtMs !== null) ? Math.max(...full.map((w) => w.resetAtMs)) : null, + fiveHourTight: live.some((w) => w.windowMs <= FIVE_HOURS_MS && fiveHourTight(w.usedPercent, w.resetAtMs, now)), + fiveHourLeft: tightestLeft(live.filter((w) => w.windowMs <= FIVE_HOURS_MS).map((w) => fiveHourLeft(w.usedPercent, w.resetAtMs, now))), + ...paceState(paced.length > 0 ? paced : null, now), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/controls/incomplete/tests/smoke.test.mjs b/questions/smart-routing-three-tiers/v1/controls/incomplete/tests/smoke.test.mjs new file mode 100644 index 0000000..5fcb834 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/controls/incomplete/tests/smoke.test.mjs @@ -0,0 +1,116 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { pickModelGroupCandidate } from '../src/pick.mjs'; +import { applyRouteWeightStep } from '../src/scheduler.mjs'; +import { redactProviderCatalogForTunnel } from '../src/remote-catalog.mjs'; + +const NOW = Date.UTC(2026, 11, 3, 10, 0, 0); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +const week = (usedPercent, resetHours) => ({ + usedPercent, + resetAtMs: NOW + resetHours * HOUR, + windowMs: 7 * DAY, +}); + +const fact = (windows, extra = {}) => ({ + available: true, + modelName: 'Model', + sourceName: 'Source', + windows, + ...extra, +}); + +// True when any key or string value in `value` names `host`, either as the +// hostname of a parseable URL or as a bare host token such as "host:443". +const mentionsHost = (value, host) => { + const strings = []; + const walk = (v) => { + if (typeof v === 'string') strings.push(v); + else if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + strings.push(k); + walk(x); + } + } + }; + walk(value); + return strings.some((s) => { + try { + if (new URL(s).hostname === host) return true; + } catch {} + return (s.toLowerCase().match(/[a-z0-9-]+(?:\.[a-z0-9-]+)+/g) ?? []).some((t) => t === host); + }); +}; + +test('supports deterministic order, rotate, cheapest, and weighted strategies', () => { + const candidates = [ + { agentKind: 'codex', providerId: 'a', model: 'm1', weight: 3 }, + { agentKind: 'codex', providerId: 'b', model: 'm1', weight: 1 }, + ]; + const facts = [fact(null, { price: 15 }), fact(null, { price: 5 })]; + + const ordered = pickModelGroupCandidate({ id: 'r1', name: 'R1', strategy: 'order', candidates }, facts, { now: NOW }); + assert.equal(ordered.index, 0); + + const cheapest = pickModelGroupCandidate({ id: 'r2', name: 'R2', strategy: 'cheapest', candidates }, facts, { now: NOW }); + assert.equal(cheapest.index, 1); + assert.equal(cheapest.trace[1].why, 'cheapest'); + + let counters = new Map(); + const picks = []; + for (let i = 0; i < 4; i += 1) { + const res = pickModelGroupCandidate({ id: 'r3', name: 'R3', strategy: 'weighted', candidates }, facts, { now: NOW, weightCounters: counters }); + picks.push(res.index); + counters = applyRouteWeightStep(counters, res.weightStep); + } + assert.deepEqual(picks, [0, 0, 1, 0]); +}); + +test('auto strategy sprints expiring surplus subscriptions and skips exhausted sources', () => { + const route = { + id: 'r-auto', + name: 'Auto', + strategy: 'expiring', + candidates: [ + { agentKind: 'codex', providerId: 'sub-a', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-b', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-c', model: 'gpt-6' }, + ], + }; + const res = pickModelGroupCandidate( + route, + [ + fact([week(100, 12)]), + fact([week(20, 6 * 24)]), + fact([week(40, 18)]), // urgency = 60 / (18/168*100) = 5.6 >= 2.0 + ], + { now: NOW }, + ); + assert.equal(res.index, 2); + assert.equal(res.trace[0].state, 'skipped'); + assert.equal(res.trace[0].why, 'limited'); + assert.equal(res.trace[2].why, 'expiring'); +}); + +test('redactProviderCatalogForTunnel strips upstream URLs while preserving display wireProtocol', () => { + const redacted = redactProviderCatalogForTunnel({ + providers: [ + { + id: 'kimi', + name: 'Kimi', + connected: true, + auth: { method: 'apiKey' }, + routing: { + pi: { upstream: 'https://api.kimi.com/coding/v1', wireProtocol: 'openai-chat' }, + }, + }, + ], + }, { sameAccountController: true }); + assert.equal(mentionsHost(redacted, 'api.kimi.com'), false); + assert.deepEqual(redacted.providers[0].kimiCodingUsageAgents, ['pi']); + assert.equal(redacted.providers[0].routing.pi.wireProtocol, 'openai-chat'); +}); diff --git a/questions/smart-routing-three-tiers/v1/question.json b/questions/smart-routing-three-tiers/v1/question.json new file mode 100644 index 0000000..6036d24 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/question.json @@ -0,0 +1,82 @@ +{ + "id": "smart-routing-three-tiers", + "revision": "v1", + "scoringVersion": "capability-ratio-v1", + "title": "智能路由三档优先级、编码套餐按引擎分级与账号池隔离", + "status": "calibrated", + "changeNote": "Eval Bank v2 complex root-cause question extracted from makecindy/cindy PR #15050 (f79d9173de63).", + "environment": "any", + "sourceRepo": "https://github.com/makecindy/cindy", + "sourceLicense": "Apache-2.0", + "sourceCommit": "f79d9173de632655d20b3fcf99f9b5de67ffe91c", + "graderCommand": [ + "python3", + "-B", + "author/grade.py", + "{candidateRoot}", + "{outputJson}" + ], + "groups": [ + { + "id": "static_three_tier_defaults", + "weight": "3/20", + "mode": "ratio", + "items": [ + "default_tier_classification", + "byok_vs_healthy_subscription" + ] + }, + { + "id": "six_level_tight_placement", + "weight": "1/5", + "mode": "ratio", + "items": [ + "six_level_order", + "disconnected_primary_and_remote_compat" + ] + }, + { + "id": "merged_provider_tiers", + "weight": "3/20", + "mode": "ratio", + "items": [ + "merged_follow_source_tier", + "merged_fixed_outer_tier_and_bench_inherit" + ] + }, + { + "id": "per_engine_coding_plan_and_mixed_overrides", + "weight": "1/5", + "mode": "ratio", + "items": [ + "per_engine_coding_plan_routing", + "mixed_payg_override_preservation" + ] + }, + { + "id": "legacy_pool_tier_isolation", + "weight": "3/20", + "mode": "ratio", + "items": [ + "auto_route_default_tier_sort_and_override", + "legacy_whole_provider_tier_pool_isolation" + ] + }, + { + "id": "remote_catalog_redaction", + "weight": "1/10", + "mode": "all", + "items": [ + "redacts_routes_and_emits_per_engine_hints" + ] + }, + { + "id": "baseline_regression_guard", + "weight": "1/20", + "mode": "all", + "items": [ + "non_auto_strategies_and_same_tier_scoring" + ] + } + ] +} diff --git a/questions/smart-routing-three-tiers/v1/reference/CONTRACT.md b/questions/smart-routing-three-tiers/v1/reference/CONTRACT.md new file mode 100644 index 0000000..b06fe60 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/CONTRACT.md @@ -0,0 +1,58 @@ +# Product & Protocol Contract + +This contract defines the authoritative three-tier Smart Routing (`expiring` / Auto) semantics and public interfaces across `src/`. + +## 1. Static Three-Tier Default Classification (`src/provider-quota-source.mjs`) + +- Exports `MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']`, `modelGroupTierRank(tier)` (`0`/`1`/`2`), `defaultModelGroupSourceTier({ agentKind?, providerId, agentDeviceId?, provider?, accountPayAsYouGo? })`, and `isZhipuCodingPlanProviderView(view, agent?)`. +- Static default tier rules (never changing tier due to transient quota timeouts): + - Merged pay-as-you-go API key accounts (`accountPayAsYouGo`) → `'fallback'`. + - Shared providers (`agentDeviceId` starting with `share:`) → `'secondary'`. + - Organization-managed providers (`provider.source === 'organization'`) or BYOK IDs (`byok-*`) → `'secondary'`. + - ACP plugin engines (`agentKind === 'acp'` or `acp-plugin:*` provider IDs) → `'primary'`. + - Standard providers (evaluated per engine when `agentKind` is given, mapping `'cc'` → `'claude-code'`; when `agentKind` is omitted, a provider is treated as a coding plan if any configured engine uses an official coding plan): + - Official coding plans (Kimi Coding, OpenCode Go, Zhipu/Z.AI GLM Coding Plan) or local no-auth (`auth.method === 'none'`) → `'primary'`. + - Pay-as-you-go (`access.kind === 'api'` or `providerId === 'xd'`) → `'fallback'`. + - Subscriptions (`access.kind === 'subscription'` or `auth.method === 'oauth'`) → `'primary'`. + - Managed (`access.kind === 'managed'`) → `'secondary'`; otherwise `'primary'`. +- `isZhipuCodingPlanProviderView(view, agent?)`: requires `auth.method === 'apiKey'`; prefers per-engine `zhipuCodingPlanUsageAgents` when present, falls back to per-engine routing inspection, and honors legacy boolean `zhipuCodingPlanUsage` for a specific `agent` ONLY when that agent is the sole enabled route without an explicit `upstream` (never promoting multi-engine redacted views blindly). + +## 2. Six-Level Auto Selection & Wire Compatibility (`src/pick.mjs`, `src/model-groups.mjs`) + +- Neutral unknown-quota score within a tier is `AUTO_UNKNOWN_QUOTA_SCORE = 0.78`. +- For `strategy === 'expiring'`, pick among ready candidates in strict 6-level priority order: + 1. `primary` roomy → 2. `secondary` roomy → 3. `primary` 5h-tight → 4. `secondary` 5h-tight → 5. `fallback` roomy → 6. `fallback` 5h-tight. +- Within a tier, preserve expiring-surplus sprint (`>= 2.0×`), `quotaScore + usageBonus - running * 0.30`, and `0.06` soft rotation. +- **Trace reasons (`state` / `why`)**: + - When a `secondary` winner is chosen while any enabled (`!off`) `primary` peer exists (even disconnected or limited) → `why: 'secondaryFallback'`. + - When a `fallback` winner is chosen while any enabled non-`fallback` peer exists → `why: 'paygFallback'` (if PAYG) or `'tierFallback'` (otherwise). + - Non-picked ready candidates report `standby` (`paygReserve` / `tierReserve` for `fallback` below non-`fallback`; `secondaryReserve` for `secondary` below `primary`; otherwise `standby`) or `skipped` (`why: 'tight'` when 5h-tight and a roomy peer with higher priority in the 6-level order is ready — e.g. `secondary` roomy over `primary` 5h-tight, or `fallback` roomy over `fallback` 5h-tight). +- `normalizeModelGroupsConfig` validates and retains `tier` on route candidates, `sourceRoutes[].sources`, and `autoSources[id]`. +- `modelGroupResolveResultForRemote` downgrades new reasons for older peers while storing the true reason in `pickWhy`: `secondaryFallback` / `tierFallback` → `'order'`, `secondaryReserve` / `tierReserve` → `'standby'` (alongside existing `payg*` mappings); `modelGroupResolveResultFromRemote` restores `why` from recognized `pickWhy` and deletes `pickWhy`. + +## 3. Merged-Provider Routes (`src/model-groups.mjs`, `src/pick.mjs`) + +- `expandMergedSources` preserves an outer row's explicit `tier` on `via.tier`. +- Merged rows select an inner representative using each member's effective tier, then compete in the outer route at `via.tier` (fixed tier) if set or the representative's effective tier ("follow source") otherwise. +- When the row's representative is not picked in an `'expiring'` outer route and receives an outer `standby` reserve reason ranked higher (`paygReserve`/`tierReserve` = 2, `secondaryReserve` = 1) than a benched inner member's `standby` reason, the benched member inherits the outer reserve reason (mapping `paygReserve` → `tierReserve` for non-PAYG members). + +## 4. Per-Engine Tiering & Tier Controls (`src/resolver.mjs`, `src/provider-quota-source.mjs`) + +- `createModelGroupResolver` computes `defaultTier` per candidate using its `agentKind` (and sets `payAsYouGo = defaultTier === 'fallback'`), so mixed coding-plan/PAYG providers route each engine at its own tier. +- `resolveSourceDefaultTier(source, provider)`: returns the uniform default tier across `provider.agents`, or `undefined` ("follow source") when engines disagree. +- `resolveTierControlState({ value, defaultTier })`: returns `{ effective, showFollow, options }`; shows `'follow'` whenever `defaultTier === undefined` OR an explicit saved override `value` now equals `defaultTier` (preserving an explicit clear path). +- `applyTierControlSelection({ value, defaultTier }, next)`: no-op if `next === effective`; returns `undefined` when clearing to `'follow'` or matching default without `'follow'` shown; otherwise returns `next`. +- `retargetCandidateWithTier(previous, selected)`: preserves `previous.tier` only when `providerId`, `agentDeviceId`, and `accountId` are all unchanged; otherwise clears `tier`. + +## 5. Source Routes & Multi-Account Pool Isolation (`src/source-routes.mjs`) + +- `buildAutoSourceRoutes` stably orders default members by default tier rank before applying saved `autoSources` overrides. +- Exact `(providerId, accountId)` saved overrides apply to that exact account (including merged PAYG keys). Legacy whole-provider `{ providerId, tier }` overrides inherit ONLY onto subscription accounts (`!account.apiConnectionId`) in both `buildAutoSourceRoutes` and `flattenManualSourceRoute` — never onto merged PAYG API key pool members. +- `expandSourceRouteDetail` / `runnableProviderModels` propagates `source.tier` onto expanded candidates. + +## 6. Remote Catalog Redaction (`src/remote-catalog.mjs`) + +- `redactProviderCatalogForTunnel(result, { sameAccountController, readZhipuCodingPlanAccountUsage })`: + - Always strips untrusted incoming `zhipuCodingPlanUsage`, `zhipuCodingPlanUsageAgents`, `kimiCodingUsageAgents`, `opencodeGoUsageAgents` before recomputing. + - Emits `zhipuCodingPlanUsage: true` and per-engine `zhipuCodingPlanUsageAgents` ONLY when `sameAccountController && readZhipuCodingPlanAccountUsage` and the provider is active, remote-enabled, connected, API-key authenticated, and has at least one official GLM coding-plan engine route. + - Emits `kimiCodingUsageAgents` / `opencodeGoUsageAgents` per engine when non-empty, and projects `routing` for display without leaking `upstream` URLs or credentials. diff --git a/questions/smart-routing-three-tiers/v1/reference/ENVIRONMENT.md b/questions/smart-routing-three-tiers/v1/reference/ENVIRONMENT.md new file mode 100644 index 0000000..a837bde --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/ENVIRONMENT.md @@ -0,0 +1,6 @@ +# Environment + +- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline. +- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows). +- Public checks: + - `npm test` — baseline smoke tests covering core strategies, quota scheduling, and route display redaction diff --git a/questions/smart-routing-three-tiers/v1/reference/TASK.md b/questions/smart-routing-three-tiers/v1/reference/TASK.md new file mode 100644 index 0000000..c046f5f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/TASK.md @@ -0,0 +1,10 @@ +# Task + +Cindy's Smart Routing (`expiring` / Auto strategy) is being upgraded from a two-pool picker to a full three-tier priority model (`primary` / `secondary` / `fallback`), and production reports have surfaced several regressions across tier classification, merged routes, mixed coding-plan/PAYG providers, flattened multi-account pools, and remote catalog redaction. + +Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and implement the complete three-tier Smart Routing behavior so every product invariant holds while preserving all existing non-auto strategies, image-capability filtering, within-tier scoring, and redaction privacy guarantees. + +- Run `npm test` and add verification tests as needed. +- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`. + +允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。 diff --git a/questions/smart-routing-three-tiers/v1/reference/package.json b/questions/smart-routing-three-tiers/v1/reference/package.json new file mode 100644 index 0000000..2586868 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/package.json @@ -0,0 +1,9 @@ +{ + "name": "cindy-smart-routing-three-tiers", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/smoke.test.mjs" + } +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/auto-usage-profile.mjs b/questions/smart-routing-three-tiers/v1/reference/src/auto-usage-profile.mjs new file mode 100644 index 0000000..5750a1e --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/auto-usage-profile.mjs @@ -0,0 +1,150 @@ +export const AUTO_USAGE_WINDOW_DAYS = 14; +const AUTO_USAGE_WINDOW_MS = AUTO_USAGE_WINDOW_DAYS * 86_400_000; +const MAX_PRIORITY_MODELS = 128; + +function localDayKey(ms) { + const d = new Date(ms); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +export function canonicalUsageModelId(model) { + const trimmed = String(model ?? '').trim().toLowerCase(); + if (!trimmed) return ''; + const slash = trimmed.lastIndexOf('/'); + return slash >= 0 && slash < trimmed.length - 1 ? trimmed.slice(slash + 1) : trimmed; +} + +export function autoUsageSourceKey(agentDeviceId, providerId) { + return `${agentDeviceId ?? ''}\u0000${providerId}`; +} + +export function autoUsageCandidateKey(agentDeviceId, providerId, model) { + return `${agentDeviceId ?? ''}\u0000${providerId}\u0000${canonicalUsageModelId(model)}`; +} + +function recencyDecay(ageMs) { + const days = Math.max(0, ageMs / 86_400_000); + if (days <= 3) return 1.0; + if (days <= 7) return 0.7; + if (days <= AUTO_USAGE_WINDOW_DAYS) return 0.4; + return 0; +} + +function sampleWeight(ageMs, tokens) { + const decay = recencyDecay(ageMs); + if (decay <= 0) return 0; + const safeTokens = Number.isFinite(tokens) && tokens > 0 ? tokens : 0; + const volumeBoost = safeTokens > 0 ? Math.min(3, Math.log10(1 + safeTokens / 10_000)) : 0; + return decay * (1 + volumeBoost); +} + +function addStats(map, key, weight, tokens, atMs) { + const existing = map.get(key); + if (existing) { + existing.weight += weight; + existing.sessions += 1; + existing.tokens += tokens; + if (atMs > existing.lastActiveAt) existing.lastActiveAt = atMs; + } else { + map.set(key, { weight, sessions: 1, tokens, lastActiveAt: atMs }); + } +} + +function computeModelPriorities(byModel) { + const modelEntries = [...byModel.entries()] + .filter(([, stats]) => stats.weight > 0) + .sort((a, b) => b[1].weight - a[1].weight || b[1].lastActiveAt - a[1].lastActiveAt) + .slice(0, MAX_PRIORITY_MODELS); + const topModelWeight = modelEntries[0]?.[1].weight ?? 0; + const modelPriorities = {}; + if (topModelWeight > 0) { + for (const [modelId, stats] of modelEntries) { + modelPriorities[modelId] = Math.max(0.001, Math.round((stats.weight / topModelWeight) * 1000) / 1000); + } + } + return modelPriorities; +} + +export function buildAutoUsageProfile(samples, nowMs) { + const cutoffMs = nowMs - AUTO_USAGE_WINDOW_MS; + const bySource = new Map(); + const byCandidate = new Map(); + const byModel = new Map(); + const sessionRoutes = new Map(); + const activeDayKeys = new Set(); + const weekdayKeys = new Set(); + const weekendKeys = new Set(); + + for (const sample of samples) { + if (!sample.providerId || !Number.isFinite(sample.atMs)) continue; + const providerId = sample.providerId.trim(); + const agentDeviceId = sample.agentDeviceId?.trim() || null; + if (sample.sessionId) { + sessionRoutes.set(sample.sessionId, { providerId, agentDeviceId }); + } + if (sample.atMs < cutoffMs || sample.atMs > nowMs + 60_000) continue; + const tokens = typeof sample.tokens === 'number' && Number.isFinite(sample.tokens) && sample.tokens > 0 ? sample.tokens : 0; + const weight = sampleWeight(nowMs - sample.atMs, tokens); + if (weight <= 0) continue; + + const dayKey = localDayKey(sample.atMs); + activeDayKeys.add(dayKey); + const dow = new Date(sample.atMs).getDay(); + if (dow === 0 || dow === 6) weekendKeys.add(dayKey); + else weekdayKeys.add(dayKey); + + const srcKey = autoUsageSourceKey(agentDeviceId, providerId); + addStats(bySource, srcKey, weight, tokens, sample.atMs); + + const canonicalModel = canonicalUsageModelId(sample.model); + if (canonicalModel) { + addStats(byCandidate, `${srcKey}\u0000${canonicalModel}`, weight, tokens, sample.atMs); + addStats(byModel, canonicalModel, weight, tokens, sample.atMs); + } + } + + return { + computedAtMs: nowMs, + activeDays: activeDayKeys.size, + weekdayActiveDays: weekdayKeys.size, + weekendActiveDays: weekendKeys.size, + bySource, + byCandidate, + byModel, + modelPriorities: computeModelPriorities(byModel), + sessionRoutes, + }; +} + +export function autoUsageCandidateWeight(profile, candidate) { + if (!profile) return 0; + const exact = profile.byCandidate.get(autoUsageCandidateKey(candidate.agentDeviceId, candidate.providerId, candidate.model))?.weight ?? 0; + const source = profile.bySource.get(autoUsageSourceKey(candidate.agentDeviceId, candidate.providerId))?.weight ?? 0; + if (exact <= 0 && source <= 0) return 0; + return exact * 0.7 + source * 0.3; +} + +export function effectiveRemainingTimeFactor(profile, nowMs, resetAtMs) { + if (!profile || profile.activeDays < 4 || resetAtMs === null || resetAtMs <= nowMs) return 1; + const remainingDays = (resetAtMs - nowMs) / 86_400_000; + if (remainingDays < 0.25 || remainingDays > 7.5) return 1; + const weekdayRate = profile.weekdayActiveDays / 10; + const weekendRate = profile.weekendActiveDays / 4; + const avgRate = (weekdayRate * 5 + weekendRate * 2) / 7; + if (avgRate <= 0.05) return 1; + + const steps = Math.max(1, Math.min(28, Math.ceil(remainingDays * 4))); + const stepMs = (resetAtMs - nowMs) / steps; + let expectedRateSum = 0; + for (let i = 0; i < steps; i += 1) { + const mid = nowMs + stepMs * (i + 0.5); + const dow = new Date(mid).getDay(); + expectedRateSum += dow === 0 || dow === 6 ? weekendRate : weekdayRate; + } + const remainingAvgRate = expectedRateSum / steps; + const ratio = remainingAvgRate / avgRate; + return Math.max(0.75, Math.min(1.25, ratio)); +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/model-groups.mjs b/questions/smart-routing-three-tiers/v1/reference/src/model-groups.mjs new file mode 100644 index 0000000..a975d30 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/model-groups.mjs @@ -0,0 +1,240 @@ +export const MODEL_GROUP_AUTO_PREFIX = 'auto:'; +export const MODEL_GROUP_EXPANDED_PREFIX = 'src:'; +export const MODEL_GROUP_LIMITS = { + id: 80, + name: 80, + candidates: 32, + routes: 64, + effort: 32, + deviceId: 128, + accountId: 128, +}; + +export const MODEL_GROUP_TIERS = ['primary', 'secondary', 'fallback']; + +export function modelGroupTier(value) { + return value === 'primary' || value === 'secondary' || value === 'fallback' ? value : undefined; +} + +export function modelGroupTierRank(tier) { + if (tier === 'primary') return 0; + if (tier === 'secondary') return 1; + return 2; +} + +export function modelGroupWeight(value) { + const n = typeof value === 'number' ? Math.floor(value) : NaN; + return Number.isFinite(n) && n >= 1 ? Math.min(1000, n) : 1; +} + +export function modelGroupCandidateKey(candidate) { + const base = `${candidate.agentKind}\u0000${candidate.providerId}\u0000${candidate.model}`; + const loc = candidate.agentDeviceId ? `\u0000@${candidate.agentDeviceId}` : ''; + const acct = candidate.accountId ? `\u0000#${candidate.accountId}` : ''; + const merged = candidate.merged ? `\u0000M:${candidate.merged.id}\u0000${candidate.merged.model}` : ''; + return `${base}${loc}${acct}${merged}`; +} + +export function modelGroupCandidateBaseKey(key) { + return key.replace(/\u0000#[^\u0000]+/, ''); +} + +export function modelGroupCandidateRowKey(candidate) { + return candidate.via?.key ?? modelGroupCandidateKey(candidate); +} + +export function modelGroupSourceKey(source) { + const loc = source.agentDeviceId ? `\u0000@${source.agentDeviceId}` : ''; + const acct = source.accountId ? `\u0000#${source.accountId}` : ''; + return `${source.providerId}${loc}${acct}`; +} + +const LEGACY_WHY = { + drain: 'order', + drainNext: 'order', + headroom: 'expiring', + weighted: 'rotate', + usageHabit: 'expiring', + autoBalance: 'expiring', + lessBusy: 'expiring', + paygFallback: 'order', + paygReserve: 'standby', + secondaryFallback: 'order', + secondaryReserve: 'standby', + tierFallback: 'order', + tierReserve: 'standby', +}; + +function legacyWhy(entry) { + const legacy = LEGACY_WHY[entry.why]; + return legacy ? { ...entry, why: legacy, pickWhy: entry.why } : entry; +} + +function realWhy(entry) { + const { pickWhy, ...rest } = entry; + const known = typeof pickWhy === 'string' && Object.hasOwn(LEGACY_WHY, pickWhy); + return known ? { ...rest, why: pickWhy } : rest; +} + +export function modelGroupResolveResultForRemote(result) { + const trace = (result.trace ?? []).map(legacyWhy); + return result.outcome === 'routed' ? { ...legacyWhy(result), trace } : { ...result, trace }; +} + +export function modelGroupResolveResultFromRemote(result) { + const trace = (result.trace ?? []).map(realWhy); + return result.outcome === 'routed' ? { ...realWhy(result), trace } : { ...result, trace }; +} + +function text(value, max) { + if (typeof value !== 'string') return ''; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= max ? trimmed : ''; +} + +function normalizeCandidate(raw) { + if (!raw || typeof raw !== 'object') return null; + const agentKind = ['cc', 'codex', 'pi', 'acp'].includes(raw.agentKind) ? raw.agentKind : null; + const providerId = text(raw.providerId, MODEL_GROUP_LIMITS.id); + const model = text(raw.model, 160); + if (!agentKind || !providerId || !model) return null; + const agentDeviceId = raw.agentDeviceId ? text(raw.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const accountId = raw.accountId ? text(raw.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const weight = modelGroupWeight(raw.weight); + const tier = modelGroupTier(raw.tier); + const effort = text(raw.effort, MODEL_GROUP_LIMITS.effort); + const mergedRaw = raw.merged && typeof raw.merged === 'object' ? raw.merged : null; + const mergedId = mergedRaw ? text(mergedRaw.id, MODEL_GROUP_LIMITS.id) : ''; + const mergedModel = mergedRaw ? text(mergedRaw.model, 160) : ''; + return { + agentKind, + providerId, + model, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + ...(mergedId && mergedModel ? { merged: { id: mergedId, model: mergedModel } } : {}), + ...(raw.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(tier ? { tier } : {}), + ...(effort ? { effort } : {}), + }; +} + +function normalizeSources(raw) { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const out = []; + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const providerId = text(entry.providerId, MODEL_GROUP_LIMITS.id); + if (!providerId) continue; + const location = entry.agentDeviceId ? text(entry.agentDeviceId, MODEL_GROUP_LIMITS.deviceId) : ''; + const account = entry.accountId ? text(entry.accountId, MODEL_GROUP_LIMITS.accountId) : ''; + const key = modelGroupSourceKey({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + }); + if (seen.has(key)) continue; + seen.add(key); + const weight = modelGroupWeight(entry.weight); + const tier = modelGroupTier(entry.tier); + out.push({ + providerId, + ...(location ? { agentDeviceId: location } : {}), + ...(account ? { accountId: account } : {}), + ...(entry.off === true ? { off: true } : {}), + ...(weight !== 1 ? { weight } : {}), + ...(tier ? { tier } : {}), + ...(entry.sameModelsOnly === true ? { sameModelsOnly: true } : {}), + }); + } + return out.slice(0, MODEL_GROUP_LIMITS.candidates); +} + +export function normalizeModelGroupsConfig(raw) { + if (!raw || typeof raw !== 'object') return { routes: [] }; + const routes = Array.isArray(raw.routes) + ? raw.routes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + candidates: Array.isArray(r.candidates) ? r.candidates.map(normalizeCandidate).filter(Boolean) : [], + })) + : []; + const sourceRoutes = Array.isArray(raw.sourceRoutes) + ? raw.sourceRoutes.filter((r) => r && typeof r === 'object' && text(r.id, MODEL_GROUP_LIMITS.id)).map((r) => ({ + ...r, + id: text(r.id, MODEL_GROUP_LIMITS.id), + name: text(r.name, MODEL_GROUP_LIMITS.name) || text(r.id, MODEL_GROUP_LIMITS.id), + strategy: r.strategy ?? 'expiring', + sources: normalizeSources(r.sources), + })) + : []; + const autoSources = raw.autoSources && typeof raw.autoSources === 'object' + ? Object.fromEntries( + Object.entries(raw.autoSources) + .filter(([id]) => id.startsWith(MODEL_GROUP_AUTO_PREFIX)) + .map(([id, list]) => [id, normalizeSources(list)]) + .filter(([, list]) => list.length > 0), + ) + : {}; + return { + routes, + ...(sourceRoutes.length > 0 ? { sourceRoutes } : {}), + ...(Object.keys(autoSources).length > 0 ? { autoSources } : {}), + ...(raw.autoStrategy ? { autoStrategy: raw.autoStrategy } : {}), + ...(raw.hiddenAuto ? { hiddenAuto: raw.hiddenAuto } : {}), + }; +} + +export function expandMergedSources(route, config) { + if (route.parent || !route.candidates.some((candidate) => candidate.merged)) return route; + const seen = new Set(); + const localPools = new Set(); + const localAccounts = new Set(); + const out = []; + const push = (candidate) => { + const key = modelGroupCandidateKey(candidate); + if (seen.has(key)) return; + if (!candidate.agentDeviceId && !candidate.merged) { + const baseKey = modelGroupCandidateBaseKey(key); + if (candidate.accountId) { + if (localPools.has(baseKey)) return; + localAccounts.add(baseKey); + } else { + if (localAccounts.has(baseKey)) return; + localPools.add(baseKey); + } + } + seen.add(key); + out.push(candidate); + }; + for (const candidate of route.candidates) { + const { merged, ...row } = candidate; + if (!merged) { + push(candidate); + continue; + } + const owner = (config.sourceRoutes ?? []).find((item) => item.id === merged.id); + const child = config.routes.find((item) => item.parent?.id === merged.id && (item.parent.model ?? item.id) === merged.model); + if (!owner || !child || child.candidates.length === 0) { + push({ ...candidate, off: true }); + continue; + } + const via = { + key: modelGroupCandidateKey(candidate), + strategy: child.strategy, + name: owner.name, + ...(row.weight !== undefined ? { weight: row.weight } : {}), + ...(row.tier !== undefined ? { tier: row.tier } : {}), + }; + for (const member of child.candidates) { + const { merged: _nested, via: _via, ...plain } = member; + const effort = row.effort ?? member.effort; + push({ ...plain, ...(row.off || member.off ? { off: true } : {}), ...(effort ? { effort } : {}), via }); + } + } + return { ...route, candidates: out }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/pick.mjs b/questions/smart-routing-three-tiers/v1/reference/src/pick.mjs new file mode 100644 index 0000000..669c492 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/pick.mjs @@ -0,0 +1,451 @@ +import { + modelGroupCandidateKey, + modelGroupCandidateRowKey, + modelGroupWeight, +} from './model-groups.mjs'; +import { pickRouteMember, PROVIDER_GROUP_SIMILAR_URGENCY } from './scheduler.mjs'; +import { FIVE_HOURS_MS, quotaWindowsScheduleState } from './usage.mjs'; +import { + autoUsageCandidateWeight, + effectiveRemainingTimeFactor, +} from './auto-usage-profile.mjs'; + +export function modelGroupHeadroom(windows, now) { + const live = (windows ?? []).filter((window) => window.resetAtMs === null || window.resetAtMs > now); + const long = live.filter((window) => window.windowMs > FIVE_HOURS_MS); + let tightest = null; + for (const window of long.length > 0 ? long : live) { + const left = Math.max(0, 100 - window.usedPercent); + if (!tightest || left < tightest.left) tightest = { left, window }; + } + return tightest; +} + +function keepsCurrent(strategy, keep, picked, facts) { + switch (strategy) { + case 'rotate': + case 'weighted': + case 'drain': + return true; + case 'cheapest': + return costOf(facts[keep.index]) <= costOf(facts[picked.index]); + case 'headroom': + if (picked.headroom === null) return true; + return keep.headroom !== null && picked.headroom - keep.headroom < KEEP_HEADROOM_GAP; + default: + return false; + } +} + +function costOf(fact) { + if (fact?.windows) return 0; + return typeof fact?.price === 'number' && Number.isFinite(fact.price) && fact.price >= 0 + ? fact.price + : Number.POSITIVE_INFINITY; +} + +const AUTO_EXPIRING_SURPLUS_URGENCY = 2.0; +const AUTO_UNKNOWN_QUOTA_SCORE = 0.78; +const AUTO_USAGE_MAX_BONUS = 0.45; +const AUTO_USAGE_FULL_CONFIDENCE = 2.5; +const AUTO_RUNNING_PENALTY = 0.30; +const AUTO_SOFT_ROTATE_GAP = 0.06; +const AUTO_KEEP_QUOTA_GAP = 0.25; +const KEEP_HEADROOM_GAP = 20; + +function nextAutoCandidate(band, lastPickedKey) { + const previous = band.findIndex(({ row }) => row.key === lastPickedKey); + return band[(previous + 1) % band.length]; +} + +function pickWithinTier(pool, options) { + const { now, lastPickedKey, usageProfile, keep } = options; + const enriched = pool.map((row) => { + const timeFactor = row.urgency !== null + ? effectiveRemainingTimeFactor(usageProfile, now, row.quota?.resetAtMs ?? null) + : 1; + const effectiveUrgency = row.urgency !== null ? row.urgency / timeFactor : null; + const isExpiringSurplus = effectiveUrgency !== null && effectiveUrgency >= AUTO_EXPIRING_SURPLUS_URGENCY; + const usageWeight = autoUsageCandidateWeight(usageProfile, row.candidate); + return { row, effectiveUrgency, isExpiringSurplus, usageWeight }; + }); + + const expiring = enriched.filter((item) => item.isExpiringSurplus); + if (expiring.length > 0) { + const topUrgency = Math.max(...expiring.map((item) => item.effectiveUrgency)); + const band = expiring.filter((item) => item.effectiveUrgency >= topUrgency * PROVIDER_GROUP_SIMILAR_URGENCY); + const byUrgency = [...band].sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index)[0]; + if (options.keepKey) { + const kept = band.find((item) => item.row === keep); + return { picked: (kept ?? byUrgency).row, why: 'expiring' }; + } + const minRunning = Math.min(...band.map((item) => item.row.running)); + const idleBand = band.filter((item) => item.row.running === minRunning); + const topUsage = Math.max(...idleBand.map((item) => item.usageWeight)); + const rotationBand = idleBand + .filter((item) => topUsage - item.usageWeight <= 0.05) + .sort((a, b) => b.effectiveUrgency - a.effectiveUrgency || a.row.index - b.row.index); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + let why = 'expiring'; + if (byUrgency.row !== winner.row && byUrgency.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + idleBand.length > 1 + && winner.usageWeight >= 0.5 + && topUsage - byUrgency.usageWeight > 0.05 + ) { + why = 'usageHabit'; + } + return { picked: winner.row, why }; + } + + const totalUsageWeight = enriched.reduce((sum, item) => sum + item.usageWeight, 0); + const confidence = totalUsageWeight > 0 ? Math.min(1, totalUsageWeight / AUTO_USAGE_FULL_CONFIDENCE) : 0; + const scored = enriched.map((item) => { + const quotaScore = item.effectiveUrgency !== null + ? item.effectiveUrgency <= 1.0 + ? Math.max(0.05, item.effectiveUrgency) + : 1.0 + Math.min(1.0, item.effectiveUrgency - 1.0) * 0.12 + : AUTO_UNKNOWN_QUOTA_SCORE; + const usageShare = totalUsageWeight > 0 ? item.usageWeight / totalUsageWeight : 0; + const usageBonus = AUTO_USAGE_MAX_BONUS * confidence * usageShare; + const busyPenalty = item.row.running * AUTO_RUNNING_PENALTY; + const baseScore = quotaScore + usageBonus; + const totalScore = baseScore - busyPenalty; + return { ...item, quotaScore, usageBonus, busyPenalty, baseScore, totalScore }; + }); + + if (options.keepKey) { + const best = scored.reduce((top, item) => (item.quotaScore > top.quotaScore ? item : top)); + const kept = scored.find((item) => item.row === keep); + const winner = kept && best.quotaScore - kept.quotaScore <= AUTO_KEEP_QUOTA_GAP ? kept : best; + return { picked: winner.row, why: winner.effectiveUrgency === null ? 'autoBalance' : 'expiring' }; + } + + const sorted = [...scored].sort((a, b) => b.totalScore - a.totalScore || a.row.index - b.row.index); + const [leader] = sorted; + const rotationBand = sorted.filter((item) => leader.totalScore - item.totalScore <= AUTO_SOFT_ROTATE_GAP + && item.row.running <= leader.row.running); + const winner = nextAutoCandidate(rotationBand, lastPickedKey); + const rotated = winner !== leader; + const bestWithoutBusy = scored.reduce((top, cur) => (cur.baseScore > top.baseScore ? cur : top)); + const bestWithoutUsage = scored.reduce((top, cur) => + (cur.quotaScore - cur.busyPenalty) > (top.quotaScore - top.busyPenalty) ? cur : top); + const secondUsageBonus = Math.max(0, ...scored.filter((item) => item !== winner).map((item) => item.usageBonus)); + + let why; + if (bestWithoutBusy !== winner && bestWithoutBusy.row.running > winner.row.running) { + why = 'lessBusy'; + } else if ( + winner.usageBonus >= 0.08 + && (bestWithoutUsage !== winner || winner.usageBonus >= secondUsageBonus + 0.05) + ) { + why = 'usageHabit'; + } else if ( + rotated + || (winner.effectiveUrgency === null && scored.some((item) => item.effectiveUrgency !== null && item.effectiveUrgency < AUTO_UNKNOWN_QUOTA_SCORE)) + ) { + why = 'autoBalance'; + } else if (scored.every((item) => item.effectiveUrgency === null) && totalUsageWeight === 0) { + why = 'order'; + } else if (winner.effectiveUrgency === null) { + why = 'autoBalance'; + } else { + why = 'expiring'; + } + return { picked: winner.row, why }; +} + +function pickTightPool(pool, options) { + if (options.keep && pool.includes(options.keep)) return { picked: options.keep, why: 'autoBalance' }; + const scored = pool.map((row) => ({ + row, + urgency: row.urgency ?? AUTO_UNKNOWN_QUOTA_SCORE, + })); + const best = scored.reduce((top, cur) => { + if (!options.keepKey && cur.row.running !== top.row.running) { + return cur.row.running < top.row.running ? cur : top; + } + return cur.urgency > top.urgency ? cur : top; + }); + const why = best.row.urgency !== null ? 'expiring' : 'autoBalance'; + return { picked: best.row, why }; +} + +function pickAutoCandidate(ready, enabled, options) { + const { now, lastPickedKey, usageProfile } = options; + const keep = options.keepKey ? ready.find((row) => row.key === options.keepKey) : undefined; + const primary = ready.filter((row) => row.tier === 'primary'); + const secondary = ready.filter((row) => row.tier === 'secondary'); + const fallback = ready.filter((row) => row.tier === 'fallback'); + + const primaryRoomy = primary.filter((row) => !row.tight); + const secondaryRoomy = secondary.filter((row) => !row.tight); + const fallbackRoomy = fallback.filter((row) => !row.tight); + + // 1. Primary (not 5h-tight) + if (primaryRoomy.length > 0) { + return pickWithinTier(primaryRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + } + // 2. Secondary (not 5h-tight) + if (secondaryRoomy.length > 0) { + const result = pickWithinTier(secondaryRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + const hadPrimary = enabled.some((row) => row.tier === 'primary'); + return hadPrimary ? { picked: result.picked, why: 'secondaryFallback' } : result; + } + // 3. Primary (5h-tight) + if (primary.length > 0) { + return pickTightPool(primary, { keepKey: options.keepKey, keep }); + } + // 4. Secondary (5h-tight) + if (secondary.length > 0) { + const result = pickTightPool(secondary, { keepKey: options.keepKey, keep }); + const hadPrimary = enabled.some((row) => row.tier === 'primary'); + return hadPrimary ? { picked: result.picked, why: 'secondaryFallback' } : result; + } + // 5 & 6. Fallback (roomy then 5h-tight) + const hadHigherTier = enabled.some((row) => row.tier !== 'fallback'); + if (fallbackRoomy.length > 0) { + const result = pickWithinTier(fallbackRoomy, { now, lastPickedKey, usageProfile, keepKey: options.keepKey, keep }); + if (!hadHigherTier) return result; + return { picked: result.picked, why: result.picked.payAsYouGo ? 'paygFallback' : 'tierFallback' }; + } + const result = pickTightPool(fallback, { keepKey: options.keepKey, keep }); + if (!hadHigherTier) return result; + return { picked: result.picked, why: result.picked.payAsYouGo ? 'paygFallback' : 'tierFallback' }; +} + +export function pickModelGroupCandidate(route, facts, options) { + const { now } = options; + const anyVision = !!options.needsImage && route.candidates.some((candidate, index) => + !candidate.off && facts[index]?.available === true && facts[index]?.acceptsImage === true); + const rows = route.candidates.map((candidate, index) => { + const fact = facts[index]; + const state = fact?.windows ? quotaWindowsScheduleState(fact.windows, now) : null; + const outerUsesHeadroom = route.strategy === 'headroom'; + const innerUsesHeadroom = candidate.via?.strategy === 'headroom'; + const headroom = outerUsesHeadroom || innerUsesHeadroom ? modelGroupHeadroom(fact?.windows ?? null, now) : null; + const remaining = fact?.inner ? fact.inner.headroom : headroom?.left ?? null; + const quota = headroom?.window ?? state?.quota ?? null; + const running = typeof fact?.running === 'number' && Number.isFinite(fact.running) && fact.running > 0 + ? Math.floor(fact.running) + : 0; + const payAsYouGo = fact?.payAsYouGo === true && quota === null && !fact?.inner; + const defaultTier = fact?.defaultTier ?? (payAsYouGo ? 'fallback' : 'primary'); + const innerTier = candidate.tier ?? defaultTier; + const outerTier = candidate.via?.tier ?? innerTier; + return { + candidate, + index, + key: modelGroupCandidateKey(candidate), + noVision: anyVision && fact?.acceptsImage !== true, + usable: !candidate.off && fact?.available === true && !(anyVision && fact?.acceptsImage !== true), + limited: fact?.inner ? fact.inner.limited : state?.limited ?? false, + limitedUntilMs: fact?.inner ? null : state?.resetAtMs ?? null, + tight: fact?.inner ? fact.inner.fiveHourTight : state?.fiveHourTight ?? false, + urgency: fact?.inner ? fact.inner.urgency : state?.urgency ?? null, + quota, + headroom: outerUsesHeadroom ? remaining : null, + weight: modelGroupWeight(candidate.via ? candidate.via.weight : candidate.weight), + group: candidate.via?.key ?? null, + innerHeadroom: innerUsesHeadroom ? remaining : null, + payAsYouGo, + innerTier, + outerTier, + tier: outerTier, + running, + }; + }); + + const benched = new Set(); + const innerWhy = new Map(); + const groupRep = new Map(); + const groupSize = new Map(); + const groups = new Map(); + for (const row of rows) if (row.group) groups.set(row.group, [...(groups.get(row.group) ?? []), row]); + for (const [group, members] of groups) { + const inUsable = members.filter((row) => row.usable); + const inReady = inUsable.filter((row) => !row.limited); + groupSize.set(group, inUsable.length); + if (inReady.length === 0) continue; + const strategy = members[0].candidate.via.strategy; + let winner = inReady[0]; + let reason = strategy; + if (strategy === 'expiring') { + const innerReady = inReady.map((row) => ({ ...row, tier: row.innerTier })); + const innerEnabled = members.filter((row) => !row.candidate.off).map((row) => ({ ...row, tier: row.innerTier })); + const auto = pickAutoCandidate(innerReady, innerEnabled, { + now, + lastPickedKey: options.lastPickedKey, + usageProfile: options.usageProfile, + keepKey: options.keepKey, + }); + winner = inReady.find((row) => row.index === auto.picked.index) ?? inReady[0]; + reason = auto.why; + } else { + const result = pickRouteMember(members.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: row.key, + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: modelGroupWeight(row.candidate.weight), + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.innerHeadroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), strategy, { lastPicked: options.lastPickedKey ?? null }); + winner = inReady.find((row) => row.key === result.key) ?? inReady[0]; + const keep = options.keepKey ? inReady.find((row) => row.key === options.keepKey) : undefined; + if (keep && keep !== winner && keepsCurrent( + strategy, + { index: keep.index, headroom: keep.innerHeadroom }, + { index: winner.index, headroom: winner.innerHeadroom }, + facts, + )) winner = keep; + if (result.plain) reason = 'order'; + } + innerWhy.set(group, reason); + groupRep.set(group, winner); + for (const row of members) if (row !== winner) benched.add(row.index); + } + + const entryKey = (row) => modelGroupCandidateRowKey(row.candidate); + const lastRow = options.lastPickedKey ? rows.find((row) => row.key === options.lastPickedKey) : undefined; + const outerLast = options.lastPickedRowKey ?? (lastRow ? entryKey(lastRow) : options.lastPickedKey ?? null); + const enabledOuter = rows.filter((row) => !row.candidate.off && !benched.has(row.index)); + const usable = rows.filter((row) => row.usable && !benched.has(row.index)); + const ready = usable.filter((row) => !row.limited); + const current = options.keepKey ? rows.find((row) => row.key === options.keepKey) : undefined; + const keep = current ? ready.find((row) => entryKey(row) === entryKey(current)) : undefined; + + let picked = null; + let why = 'only'; + let weightStep; + let strategyWhy = route.strategy; + if (ready.length > 0) { + if (route.strategy === 'expiring') { + const auto = pickAutoCandidate(ready, enabledOuter, { + now, + lastPickedKey: ready.find((row) => entryKey(row) === outerLast)?.key, + usageProfile: options.usageProfile, + keepKey: keep?.key ?? options.keepKey, + }); + picked = auto.picked; + strategyWhy = auto.why; + why = usable.length === 1 ? 'only' : strategyWhy; + } else { + const entries = rows.filter((row) => !benched.has(row.index) + && (!row.group || innerWhy.has(row.group) || row === groups.get(row.group)[0])); + const result = pickRouteMember(entries.map((row) => { + const cost = costOf(facts[row.index]); + return { + key: entryKey(row), + usable: row.usable && !row.limited, + paused: false, + running: row.running, + limit: Number.POSITIVE_INFINITY, + weight: row.weight, + urgency: row.urgency, + fiveHourTight: row.tight, + headroom: row.headroom, + cost: Number.isFinite(cost) ? cost : null, + }; + }), route.strategy, { lastPicked: outerLast, weightCounters: options.weightCounters }); + picked = ready.find((row) => entryKey(row) === result.key) ?? ready[0]; + weightStep = result.weightStep; + if (keep && keep !== picked && keepsCurrent(route.strategy, keep, picked, facts)) { + picked = keep; + weightStep = undefined; + } + if (result.plain) strategyWhy = 'order'; + else if (route.strategy === 'drain' && entryKey(picked) !== outerLast && entries.some((row) => entryKey(row) === outerLast)) { + strategyWhy = 'drainNext'; + } + why = usable.length === 1 ? 'only' : strategyWhy; + if (why === 'cheapest') { + const cost = costOf(facts[picked.index]); + why = cost === 0 && facts[picked.index]?.windows ? 'cheapestFree' : Number.isFinite(cost) ? 'cheapest' : 'order'; + } + } + } else if (usable.length > 0) { + picked = usable.reduce((best, row) => + (row.limitedUntilMs ?? Number.POSITIVE_INFINITY) < (best.limitedUntilMs ?? Number.POSITIVE_INFINITY) ? row : best); + why = usable.length === 1 ? 'only' : 'soonest'; + } + + if (picked?.group && why === 'only' && (groupSize.get(picked.group) ?? 0) > 1) why = innerWhy.get(picked.group) ?? why; + + const trace = rows.map((row) => { + const fact = facts[row.index]; + const base = { + agentKind: row.candidate.agentKind, + providerId: row.candidate.providerId, + model: row.candidate.model, + ...(row.candidate.agentDeviceId ? { agentDeviceId: row.candidate.agentDeviceId } : {}), + ...(row.candidate.accountId ? { accountId: row.candidate.accountId } : {}), + modelName: fact?.modelName || row.candidate.model, + sourceName: fact?.sourceName || row.candidate.providerId, + quota: row.quota, + }; + if (row === picked) return { ...base, state: 'picked', why, ...(row.limited ? { limitedUntilMs: row.limitedUntilMs } : {}) }; + if (row.candidate.off) return { ...base, state: 'skipped', why: 'off' }; + if (fact?.available !== true) return { ...base, state: 'skipped', why: 'unavailable' }; + if (row.noVision) return { ...base, state: 'skipped', why: 'noVision' }; + if (row.limited) return { ...base, state: 'skipped', why: 'limited', limitedUntilMs: row.limitedUntilMs }; + + const isBenchedMember = !!row.group && benched.has(row.index); + const effectiveStrategy = isBenchedMember ? row.candidate.via.strategy : route.strategy; + const reserveRank = (reason) => ( + reason === 'paygReserve' || reason === 'tierReserve' ? 2 + : reason === 'secondaryReserve' ? 1 + : 0 + ); + const standbyReasonFor = (entry, peers, tierOf) => { + const rowTier = tierOf(entry); + if (rowTier === 'fallback' && peers.some((other) => tierOf(other) !== 'fallback')) { + return { state: 'standby', why: entry.payAsYouGo ? 'paygReserve' : 'tierReserve' }; + } + if (rowTier === 'secondary' && peers.some((other) => tierOf(other) === 'primary' && !other.tight)) { + return { state: 'standby', why: 'secondaryReserve' }; + } + if (entry.tight && peers.some((other) => !other.tight && (rowTier === 'fallback' || tierOf(other) !== 'fallback'))) { + return { state: 'skipped', why: 'tight' }; + } + if (rowTier === 'secondary' && peers.some((other) => tierOf(other) === 'primary')) { + return { state: 'standby', why: 'secondaryReserve' }; + } + return { state: 'standby', why: 'standby' }; + }; + const innerOutcome = effectiveStrategy === 'expiring' + ? standbyReasonFor( + row, + isBenchedMember ? groups.get(row.group).filter((other) => other.usable && !other.limited) : ready, + (entry) => (isBenchedMember ? entry.innerTier : entry.outerTier), + ) + : { state: 'standby', why: 'standby' }; + + if (isBenchedMember && innerOutcome.state === 'standby' && route.strategy === 'expiring') { + const rep = groupRep.get(row.group); + if (rep && rep !== picked) { + const repOuter = standbyReasonFor(rep, ready, (entry) => entry.outerTier); + if (repOuter.state === 'standby' && reserveRank(repOuter.why) > reserveRank(innerOutcome.why)) { + const inheritedWhy = repOuter.why === 'paygReserve' && !row.payAsYouGo ? 'tierReserve' : repOuter.why; + return { ...base, state: 'standby', why: inheritedWhy }; + } + } + } + if (effectiveStrategy === 'expiring') return { ...base, ...innerOutcome }; + return { ...base, state: 'standby', why: 'standby' }; + }); + + return { + index: picked?.index ?? null, + trace, + ...(options.needsImage ? { image: anyVision ? 'applied' : 'fallback' } : {}), + ...(weightStep ? { weightStep } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/provider-identity.mjs b/questions/smart-routing-three-tiers/v1/reference/src/provider-identity.mjs new file mode 100644 index 0000000..84156b4 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/provider-identity.mjs @@ -0,0 +1,107 @@ +export const PLUGIN_ENGINE_PROVIDER_PREFIX = 'acp-plugin:'; +export const PROVIDER_SHARE_AGENT_DEVICE_PREFIX = 'share:'; + +export function isByokProviderId(value) { + return typeof value === 'string' && /^byok-[a-z0-9][a-z0-9-]{0,185}$/.test(value); +} + +export function isOrganizationManagedProvider(provider) { + return provider?.source === 'organization'; +} + +export function isProviderShareAgentDeviceId(value) { + return typeof value === 'string' && value.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX); +} + +export function pluginEngineKeyFromProviderId(providerId) { + if (!providerId || !providerId.startsWith(PLUGIN_ENGINE_PROVIDER_PREFIX)) return null; + const key = providerId.slice(PLUGIN_ENGINE_PROVIDER_PREFIX.length); + const separator = key.lastIndexOf(':'); + return separator > 0 && separator < key.length - 1 ? key : null; +} + +/** Exact product scope, not brand/name matching. Never send a proxy's credential to Kimi. */ +export function kimiCodingUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (!['https://api.kimi.com', 'https://api.kimi.ai'].includes(url.origin)) return null; + if (!['/coding', '/coding/', '/coding/v1', '/coding/v1/'].includes(url.pathname)) return null; + return `${url.origin}/coding/v1/usages`; + } catch { + return null; + } +} + +export function isKimiCodingProvider(provider, agent) { + if (!provider || !['apiKey', 'oauth'].includes(provider.auth?.method)) return false; + if ( + provider.auth.method === 'oauth' + && !['https://auth.kimi.com/api/oauth/token', 'https://auth.kimi.ai/api/oauth/token'].includes( + provider.auth.oauth?.tokenUrl ?? '', + ) + ) { + return false; + } + return (agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {})).some( + (route) => route && !route.disabled && kimiCodingUsageEndpoint(route.upstream) !== null, + ); +} + +export function isKimiCodingProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.kimiCodingUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isKimiCodingProvider(provider, agent); +} + +/** Resolve only OpenCode Go's official inference route, never a user proxy. */ +export function opencodeGoUsageEndpoint(upstream) { + if (typeof upstream !== 'string' || !upstream) return null; + try { + const url = new URL(upstream); + if (url.username || url.password || url.search || url.hash) return null; + if (url.origin !== 'https://opencode.ai') return null; + if (!['/zen/go', '/zen/go/v1'].includes(url.pathname.replace(/\/+$/, ''))) return null; + return 'https://opencode.ai/zen/go/v1/usage'; + } catch { + return null; + } +} + +export function isOpenCodeGoProvider(provider, agent) { + if (!provider || provider.auth?.method !== 'apiKey') return false; + const routes = agent ? [provider.routing?.[agent]] : Object.values(provider.routing ?? {}); + return routes.some( + (route) => route && !route.disabled && opencodeGoUsageEndpoint(route.upstream) !== null, + ); +} + +export function isOpenCodeGoProviderView(provider, agent) { + if (!provider) return false; + const agents = provider.opencodeGoUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + return isOpenCodeGoProvider(provider, agent); +} + +export const ZHIPU_CODING_PLAN_ORIGINS = ['https://open.bigmodel.cn', 'https://api.z.ai']; + +export function isZhipuCodingPlanPath(pathname) { + return pathname === '/api/anthropic' || pathname.startsWith('/api/anthropic/') || pathname.startsWith('/api/coding/'); +} + +export function isZhipuCodingPlanRoute(route) { + if (!route?.upstream || route.disabled) return false; + let url; + try { + url = new URL(route.upstream); + } catch { + return false; + } + return ZHIPU_CODING_PLAN_ORIGINS.includes(url.origin) && isZhipuCodingPlanPath(url.pathname); +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/provider-quota-source.mjs b/questions/smart-routing-three-tiers/v1/reference/src/provider-quota-source.mjs new file mode 100644 index 0000000..2a658e1 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/provider-quota-source.mjs @@ -0,0 +1,118 @@ +import { MODEL_GROUP_TIERS } from './model-groups.mjs'; +import { + isByokProviderId, + isKimiCodingProviderView, + isOpenCodeGoProviderView, + isOrganizationManagedProvider, + isProviderShareAgentDeviceId, + isZhipuCodingPlanRoute, + pluginEngineKeyFromProviderId, +} from './provider-identity.mjs'; + +export function isPayAsYouGoProvider(provider) { + return provider?.access?.kind === 'api' || provider?.id === 'xd'; +} + +export function isZhipuCodingPlanProviderView(view, agent) { + if (!view || view.auth?.method !== 'apiKey') return false; + const routing = view.routing ?? {}; + const agents = view.zhipuCodingPlanUsageAgents; + if (Array.isArray(agents) && agents.length > 0 && agents.every((value) => ['claude-code', 'codex', 'pi'].includes(value))) { + return agent ? agents.includes(agent) : true; + } + if (!agent) return view.zhipuCodingPlanUsage === true || Object.values(routing).some(isZhipuCodingPlanRoute); + if (isZhipuCodingPlanRoute(routing[agent])) return true; + if (view.zhipuCodingPlanUsage !== true) return false; + const enabled = Object.entries(routing).filter(([, route]) => route && !route.disabled); + return enabled.length === 1 && enabled[0]?.[0] === agent && !routing[agent]?.upstream; +} + +/** + * Three-tier static default priority classifier shared across resolver, sourceRoutes, and UI controls: + * - primary: local/own subscriptions (OAuth, coding plans, local no-auth models) and ACP plugin engines; + * - secondary: organization BYOK, provider shares, and other managed connections; + * - fallback: personal pay-as-you-go API keys, merged pool PAYG keys, and Cindy AI (`xd`). + */ +export function defaultModelGroupSourceTier(input) { + if (input.accountPayAsYouGo) return 'fallback'; + if (input.agentDeviceId && isProviderShareAgentDeviceId(input.agentDeviceId)) return 'secondary'; + const view = input.provider ?? null; + if ((view && isOrganizationManagedProvider(view)) || isByokProviderId(input.providerId)) return 'secondary'; + if (input.agentKind === 'acp' || pluginEngineKeyFromProviderId(input.providerId) !== null) return 'primary'; + if (view) { + const agent = input.agentKind === 'cc' ? 'claude-code' : input.agentKind; + if (isKimiCodingProviderView(view, agent) || isOpenCodeGoProviderView(view, agent) || isZhipuCodingPlanProviderView(view, agent)) { + return 'primary'; + } + if (view.auth?.method === 'none') return 'primary'; + if (isPayAsYouGoProvider(view)) return 'fallback'; + if (view.access?.kind === 'subscription' || view.auth?.method === 'oauth') return 'primary'; + if (view.access?.kind === 'managed') return 'secondary'; + return 'primary'; + } + if (input.providerId === 'xd') return 'fallback'; + return 'primary'; +} + +/** + * Resolve the single default tier shown for a source row across its configured engines. + * When different engines on the same provider have different default tiers (mixed coding-plan / PAYG), + * returns `undefined` so the row defaults to "follow source". + */ +export function resolveSourceDefaultTier(source, provider) { + const tierSource = { + agentKind: source.agentKind, + providerId: source.providerId, + agentDeviceId: source.agentDeviceId, + provider, + accountPayAsYouGo: source.accountPayAsYouGo, + }; + const engineTiers = provider?.agents?.map((agent) => defaultModelGroupSourceTier({ + ...tierSource, + agentKind: agent === 'claude-code' ? 'cc' : agent, + })) ?? []; + const firstTier = engineTiers[0]; + return engineTiers.every((tier) => tier === firstTier) + ? firstTier ?? defaultModelGroupSourceTier(tierSource) + : undefined; +} + +/** + * Compute select control state for a source row's tier dropdown. + * Shows `'follow'` when `defaultTier === undefined` (mixed/merged) OR when catalog changes make + * `defaultTier` match an already-saved explicit override (`value === defaultTier`). + */ +export function resolveTierControlState({ value, defaultTier }) { + const effective = value ?? defaultTier ?? 'follow'; + const showFollow = defaultTier === undefined || value === defaultTier; + return { + effective, + showFollow, + options: showFollow ? ['follow', ...MODEL_GROUP_TIERS] : [...MODEL_GROUP_TIERS], + }; +} + +/** + * Apply a user's selection in the tier dropdown and return the persisted `tier` field (`undefined` clears override). + */ +export function applyTierControlSelection({ value, defaultTier }, next) { + const { effective, showFollow } = resolveTierControlState({ value, defaultTier }); + if (next === effective) return value; + return next === 'follow' || (!showFollow && next === defaultTier) ? undefined : next; +} + +/** + * Retarget a custom-route candidate row: preserve `tier` only when provider, device, and account stay identical. + */ +export function retargetCandidateWithTier(previous, selected) { + const sameSource = selected.providerId === previous.providerId + && (selected.agentDeviceId ?? undefined) === (previous.agentDeviceId ?? undefined) + && (selected.accountId ?? undefined) === (previous.accountId ?? undefined); + return { + ...selected, + ...(previous.off ? { off: previous.off } : {}), + ...(previous.weight !== undefined ? { weight: previous.weight } : {}), + ...(previous.tier && sameSource ? { tier: previous.tier } : {}), + ...(previous.effort ? { effort: previous.effort } : {}), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/remote-catalog.mjs b/questions/smart-routing-three-tiers/v1/reference/src/remote-catalog.mjs new file mode 100644 index 0000000..98162e0 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/remote-catalog.mjs @@ -0,0 +1,96 @@ +import { + isKimiCodingProvider, + isOpenCodeGoProvider, + isZhipuCodingPlanRoute, +} from './provider-identity.mjs'; + +const VALID_WIRE_PROTOCOLS = new Set([ + 'openai-chat', + 'openai-responses', + 'google-generative-ai', + 'anthropic-messages', +]); + +export function projectRoutingForDisplay(routing) { + if (!routing || typeof routing !== 'object' || Array.isArray(routing)) return undefined; + const out = {}; + for (const [agent, value] of Object.entries(routing)) { + const route = value && typeof value === 'object' && !Array.isArray(value) ? value : null; + const wireProtocol = VALID_WIRE_PROTOCOLS.has(route?.wireProtocol) + ? route.wireProtocol + : route?.authStrategy && route.wireProtocol === undefined + ? agent === 'codex' + ? 'openai-responses' + : agent === 'claude-code' + ? 'anthropic-messages' + : undefined + : undefined; + out[agent] = { + ...(wireProtocol ? { wireProtocol } : {}), + ...(route?.disabled === true ? { disabled: true } : {}), + }; + } + return out; +} + +/** + * Redact a provider list payload before returning it over the remote device-link tunnel. + * Strips execution endpoints and untrusted stored hints, then advertises per-engine coding-plan + * capabilities solely from official non-disabled routes. + */ +export function redactProviderCatalogForTunnel(result, options = {}) { + if (!result || typeof result !== 'object' || !Array.isArray(result.providers)) return result; + const { + sameAccountController = false, + readZhipuCodingPlanAccountUsage = true, + } = options; + const runtimeAgents = ['claude-code', 'codex', 'pi']; + + const providers = result.providers.map((p) => { + const rest = { ...p }; + delete rest.runLocation; + if (!sameAccountController) { + delete rest.subscriptionPoolTarget; + delete rest.subscriptionAccountKeys; + if (rest.openAiAccount && typeof rest.openAiAccount === 'object') { + const { accountKey: _key, ...account } = rest.openAiAccount; + rest.openAiAccount = account; + } + } + delete rest.remoteInvocationEnabled; + if (typeof p.remoteInvocationEnabled === 'boolean') rest.remoteInvocationEnabled = p.remoteInvocationEnabled; + + // A display-only capability survives route redaction. Never forward a stored hint. + delete rest.zhipuCodingPlanUsage; + delete rest.zhipuCodingPlanUsageAgents; + if ( + sameAccountController + && readZhipuCodingPlanAccountUsage + && p.remoteInvocationEnabled === true + && p.connected && !p.suspended && !p.removed + && p.auth?.method === 'apiKey' + ) { + const zhipuAgents = runtimeAgents.filter((agent) => isZhipuCodingPlanRoute(p.routing?.[agent])); + if (zhipuAgents.length > 0) { + rest.zhipuCodingPlanUsage = true; + rest.zhipuCodingPlanUsageAgents = zhipuAgents; + } + } + + delete rest.kimiCodingUsageAgents; + const kimiAgents = runtimeAgents.filter((agent) => isKimiCodingProvider(p, agent)); + if (kimiAgents.length > 0) rest.kimiCodingUsageAgents = kimiAgents; + + delete rest.opencodeGoUsageAgents; + const opencodeGoAgents = runtimeAgents.filter((agent) => isOpenCodeGoProvider(p, agent)); + if (opencodeGoAgents.length > 0) rest.opencodeGoUsageAgents = opencodeGoAgents; + + rest.routing = projectRoutingForDisplay(p.routing); + return rest; + }); + + return { + ...result, + providers, + }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/resolver.mjs b/questions/smart-routing-three-tiers/v1/reference/src/resolver.mjs new file mode 100644 index 0000000..05c9312 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/resolver.mjs @@ -0,0 +1,118 @@ +import { expandMergedSources } from './model-groups.mjs'; +import { pickModelGroupCandidate } from './pick.mjs'; +import { pluginEngineKeyFromProviderId } from './provider-identity.mjs'; +import { defaultModelGroupSourceTier } from './provider-quota-source.mjs'; +import { effectiveModelGroupsConfig } from './source-routes.mjs'; + +const AGENT_FOR_KIND = { cc: 'claude-code', codex: 'codex', pi: 'pi' }; + +export function createModelGroupResolver(deps) { + const now = deps.now ?? Date.now; + + async function resolve(request) { + const rawConfig = deps.config(); + const views = await deps.views(); + const agents = deps.agents ? deps.agents() : ['claude-code', 'codex', 'pi']; + const effectiveConfig = deps.catalog + ? effectiveModelGroupsConfig(rawConfig, deps.catalog(views, agents)) + : rawConfig; + + const rawRoute = (effectiveConfig.routes ?? []).find((r) => r.id === request.selection?.id); + if (!rawRoute) { + return { outcome: 'unavailable', reason: 'route_not_found', trace: [] }; + } + const route = expandMergedSources(rawRoute, effectiveConfig); + const windowsMap = deps.quotaWindows ? await deps.quotaWindows() : new Map(); + const usageProfile = deps.usageProfile ? deps.usageProfile() : null; + + const facts = await Promise.all(route.candidates.map(async (candidate) => { + const agentDeviceId = candidate.agentDeviceId ?? null; + const isAcp = candidate.agentKind === 'acp' || pluginEngineKeyFromProviderId(candidate.providerId) !== null; + if (isAcp) { + const engine = deps.pluginEngines ? (await deps.pluginEngines()).find((e) => e.providerId === candidate.providerId) : null; + const available = engine ? !engine.suspended && engine.availability?.state !== 'unavailable' : false; + const windows = windowsMap.get(candidate.providerId) ?? null; + const defaultTier = defaultModelGroupSourceTier({ + agentKind: 'acp', + providerId: candidate.providerId, + agentDeviceId, + }); + return { + available, + modelName: candidate.model, + sourceName: engine?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + defaultTier, + acceptsImage: true, + }; + } + + const locationViews = agentDeviceId && deps.remoteViews + ? (await deps.remoteViews(agentDeviceId)) + : views; + const view = locationViews.find((v) => v.id === candidate.providerId) ?? null; + const agent = AGENT_FOR_KIND[candidate.agentKind]; + const modelEntry = view?.models?.[agent]?.find((m) => m.id === candidate.model) ?? null; + const installed = deps.harnessInstalled ? await deps.harnessInstalled(agent, agentDeviceId) : true; + const accountFact = !agentDeviceId && candidate.accountId && deps.localAccount + ? deps.localAccount(candidate.providerId, candidate.accountId, candidate.model, candidate.agentKind) + : null; + const available = Boolean( + view && view.connected && !view.suspended && !view.removed + && installed + && modelEntry && !modelEntry.disabled + && (!accountFact || accountFact.usable !== false), + ); + const defaultTier = defaultModelGroupSourceTier({ + agentKind: candidate.agentKind, + providerId: candidate.providerId, + agentDeviceId, + provider: view, + accountPayAsYouGo: accountFact?.payAsYouGo, + }); + const payAsYouGo = defaultTier === 'fallback'; + const keyForQuota = candidate.accountId ? `${candidate.providerId}#${candidate.accountId}` : candidate.providerId; + const windows = accountFact?.windows ?? windowsMap.get(keyForQuota) ?? windowsMap.get(candidate.providerId) ?? null; + const running = candidate.accountId + ? (accountFact?.running ?? 0) + : (deps.runningCount ? deps.runningCount(candidate.providerId, agentDeviceId) : 0); + + return { + available, + modelName: modelEntry?.name ?? candidate.model, + sourceName: view?.name ?? candidate.providerId, + windows: windows && windows.length > 0 ? windows : null, + ...(payAsYouGo ? { payAsYouGo: true } : {}), + defaultTier, + ...(running > 0 ? { running } : {}), + acceptsImage: modelEntry?.imageInput !== false, + ...(typeof modelEntry?.price === 'number' ? { price: modelEntry.price } : {}), + }; + })); + + const picked = pickModelGroupCandidate(route, facts, { + now: now(), + lastPickedKey: request.lastPickedKey ?? null, + lastPickedRowKey: request.lastPickedRowKey ?? null, + needsImage: request.needsImage === true, + weightCounters: request.weightCounters, + usageProfile, + keepKey: request.keepKey ?? null, + }); + + if (picked.index === null) { + return { outcome: 'unavailable', reason: 'no_available_candidate', trace: picked.trace }; + } + const chosen = route.candidates[picked.index]; + const pickedEntry = picked.trace[picked.index]; + return { + outcome: 'routed', + route: chosen, + why: pickedEntry.why, + trace: picked.trace, + ...(picked.weightStep ? { weightStep: picked.weightStep } : {}), + }; + } + + return { resolve }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/scheduler.mjs b/questions/smart-routing-three-tiers/v1/reference/src/scheduler.mjs new file mode 100644 index 0000000..664190f --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/scheduler.mjs @@ -0,0 +1,119 @@ +export const PROVIDER_GROUP_SIMILAR_URGENCY = 0.9; +export const ROUTE_FIVE_HOUR_SHARE_PERCENT = 15; + +export function fiveHourTightFor(member) { + if (typeof member.fiveHourLeft === 'number' && Number.isFinite(member.fiveHourLeft)) { + return member.fiveHourLeft / (Math.max(0, member.running) + 1) <= ROUTE_FIVE_HOUR_SHARE_PERCENT; + } + return member.fiveHourTight === true; +} + +export function applyRouteWeightStep(counters, step) { + const next = new Map(counters); + let total = 0; + for (const { key, weight } of step.participants) { + next.set(key, (next.get(key) ?? 0) + weight); + total += weight; + } + next.set(step.pickedKey, (next.get(step.pickedKey) ?? 0) - total); + return next; +} + +function eligibleMembers(members, options) { + return members.filter((m) => m.usable && !m.paused && !options.exclude?.has(m.key)); +} + +function openMembers(members, options) { + return eligibleMembers(members, options).filter((m) => m.running < m.limit); +} + +function byQuota(open, keepUnknown) { + const roomy = open.filter((member) => !fiveHourTightFor(member)); + const pool = roomy.length > 0 ? roomy : open; + const known = (member) => typeof member.urgency === 'number' && Number.isFinite(member.urgency); + const urgencies = pool.filter(known).map((member) => member.urgency); + if (urgencies.length === 0) return pool; + const top = Math.max(...urgencies); + return pool.filter((member) => (known(member) ? member.urgency >= top * PROVIDER_GROUP_SIMILAR_URGENCY : keepUnknown)); +} + +export function routeSchedulingCandidates(members, strategy, options = {}) { + const reachable = openMembers(members, options); + const withPlan = reachable.filter((m) => !m.quotaSpent); + const open = withPlan.length > 0 ? withPlan : reachable; + return strategy === 'expiring' ? byQuota(open, options.keepUnknownQuota === true) : open; +} + +function activeLoadOf(member) { + const value = member.selectionRunning ?? member.running; + return Number.isFinite(value) ? value : Number.POSITIVE_INFINITY; +} + +function residentOf(member) { + return typeof member.residentLoad === 'number' && Number.isFinite(member.residentLoad) && member.residentLoad > 0 + ? member.residentLoad + : 0; +} + +function leastBusy(open, allMembers, lastIndex, rotateTies) { + let minRunning = Number.POSITIVE_INFINITY; + for (const m of open) { + const load = activeLoadOf(m); + if (load < minRunning) minRunning = load; + } + const leastRunning = open.filter((m) => activeLoadOf(m) === minRunning); + let minResident = Number.POSITIVE_INFINITY; + for (const m of leastRunning) { + const res = residentOf(m); + if (res < minResident) minResident = res; + } + const tied = leastRunning.filter((m) => residentOf(m) === minResident); + if (rotateTies && lastIndex >= 0 && tied.length > 1) { + return tied.find((m) => allMembers.indexOf(m) > lastIndex) ?? tied[0]; + } + return tied[0]; +} + +function costOf(member) { + return typeof member.cost === 'number' && Number.isFinite(member.cost) && member.cost >= 0 + ? member.cost + : Number.POSITIVE_INFINITY; +} + +export function pickRouteMember(members, strategy, options = {}) { + const open = routeSchedulingCandidates(members, strategy, options); + if (open.length === 0) return { key: null }; + const lastIndex = options.lastPicked ? members.findIndex((m) => m.key === options.lastPicked) : -1; + const after = () => open.find((m) => members.indexOf(m) > lastIndex) ?? open[0]; + switch (strategy) { + case 'order': + return { key: open[0].key }; + case 'rotate': { + const last = open.find((m) => m.key === options.lastPicked); + if (last && (options.roundPicks ?? 1) < (last.roundSlots ?? 1)) return { key: last.key }; + return { key: after().key }; + } + case 'drain': { + const last = open.find((m) => m.key === options.lastPicked); + return { key: (last ?? after()).key }; + } + case 'weighted': { + const rows = open.map((m) => ({ key: m.key, weight: Math.max(1, m.weight) })); + const score = (row) => (options.weightCounters?.get(row.key) ?? 0) + row.weight; + const best = rows.reduce((top, row) => (score(row) > score(top) ? row : top)); + return { key: best.key, weightStep: { participants: rows, pickedKey: best.key } }; + } + case 'headroom': { + const known = open.filter((m) => typeof m.headroom === 'number' && Number.isFinite(m.headroom)); + if (known.length === 0) return { key: open[0].key, plain: true }; + return { key: known.reduce((best, m) => (m.headroom > best.headroom ? m : best)).key }; + } + case 'cheapest': { + const priced = open.filter((m) => Number.isFinite(costOf(m))); + if (priced.length === 0) return { key: open[0].key, plain: true }; + return { key: priced.reduce((best, m) => (costOf(m) < costOf(best) ? m : best)).key }; + } + default: + return { key: leastBusy(open, members, lastIndex, options.rotateTies === true).key }; + } +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/source-routes.mjs b/questions/smart-routing-three-tiers/v1/reference/src/source-routes.mjs new file mode 100644 index 0000000..dd96c5e --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/source-routes.mjs @@ -0,0 +1,282 @@ +import { createHash } from 'node:crypto'; +import { + MODEL_GROUP_AUTO_PREFIX, + MODEL_GROUP_EXPANDED_PREFIX, + MODEL_GROUP_LIMITS, + modelGroupSourceKey, + modelGroupTierRank, +} from './model-groups.mjs'; +import { isProviderShareAgentDeviceId } from './provider-identity.mjs'; +import { defaultModelGroupSourceTier } from './provider-quota-source.mjs'; + +const GROUP_KIND = { 'claude-code': 'cc', codex: 'codex', pi: 'pi' }; +const NOT_A_FAMILY = new Set(['xd', 'cindy']); +const FAMILY_OF = { 'openai-spectrum': 'openai' }; + +export function providerFamily(view) { + const kind = view.logoKind ?? (['openai', 'anthropic', 'google', 'xai', 'deepseek', 'kimi', 'glm'].includes(view.id) ? view.id : null); + if (!kind || NOT_A_FAMILY.has(kind)) return null; + return FAMILY_OF[kind] ?? kind; +} + +const usable = (view) => view.connected && !view.suspended && !view.removed && !view.subscriptionPoolAlias; + +function locationViews(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.views; + return catalog.remote?.get(agentDeviceId)?.providers ?? []; +} + +function locationAgents(catalog, agentDeviceId) { + if (!agentDeviceId) return catalog.agents; + return catalog.remote?.get(agentDeviceId)?.agents ?? catalog.agents; +} + +function flattenableAccounts(catalog, providerId) { + const all = catalog.localAccounts?.get(providerId); + const active = all?.filter((account) => account.paused !== true); + return all && all.length >= 2 && active && active.length > 0 ? active : null; +} + +export function sourceModelKey(view, agent, modelId) { + const declared = view.routing?.[agent]?.modelIdRewrite?.stripPrefix; + const id = (declared && modelId.startsWith(declared) ? modelId.slice(declared.length) : modelId).toLowerCase(); + return id.replace(/^[a-z0-9][a-z0-9._-]*\/([^/]+)$/, '$1'); +} + +function expandedId(routeId, modelKey) { + return `${MODEL_GROUP_EXPANDED_PREFIX}${createHash('sha256').update(`${routeId}\u0000${modelKey}`).digest('hex').slice(0, 40)}`; +} + +function runnableProviderModels(catalog, view, source, account) { + if (!usable(view)) return []; + const views = locationViews(catalog, source.agentDeviceId); + const agents = locationAgents(catalog, source.agentDeviceId); + const allowed = agents.filter((agent) => agent in GROUP_KIND); + const seen = new Set(); + const out = []; + for (const agent of allowed) { + for (const model of view.models?.[agent] ?? []) { + const key = sourceModelKey(view, agent, model.id); + if (model.disabled || seen.has(key)) continue; + if (account?.supportedModelIds && !account.supportedModelIds.has(model.id.replace(/^chatgpt\//, ''))) continue; + const agentKind = GROUP_KIND[agent]; + const candidate = { + agentKind, + providerId: view.id, + model: model.id, + ...(source.agentDeviceId ? { agentDeviceId: source.agentDeviceId } : {}), + ...(source.accountId ? { accountId: source.accountId } : {}), + ...(source.off ? { off: true } : {}), + ...(source.weight ? { weight: source.weight } : {}), + ...(source.tier ? { tier: source.tier } : {}), + }; + if (catalog.available && !catalog.available(candidate, views, agents)) continue; + seen.add(key); + out.push({ + key, + name: model.name ?? key, + candidate, + }); + } + } + return out; +} + +function memberSourceKey(member) { + return modelGroupSourceKey({ + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }); +} + +function accountKeysFor(view, accountId, account) { + if (accountId) return account?.accountKey ? [account.accountKey] : []; + return view?.subscriptionAccountKeys ?? []; +} + +function withoutRepeatedAccounts(members, catalog, offKeys) { + const localActiveKeys = new Set(); + const localModelKeys = new Set(); + for (const m of members) { + if (m.agentDeviceId || offKeys.has(memberSourceKey(m))) continue; + for (const k of accountKeysFor(m.view, m.accountId, m.account)) localActiveKeys.add(k); + if (m.view) { + for (const item of runnableProviderModels(catalog, m.view, { accountId: m.accountId }, m.account)) { + localModelKeys.add(item.key); + } + } + } + return members.filter((m) => { + if (!m.agentDeviceId || isProviderShareAgentDeviceId(m.agentDeviceId)) return true; + const keys = accountKeysFor(m.view, m.accountId, m.account); + if (keys.length === 0 || !keys.every((k) => localActiveKeys.has(k))) return true; + const models = m.view ? runnableProviderModels(catalog, m.view, { agentDeviceId: m.agentDeviceId }) : []; + return models.length > 0 && models.some((item) => !localModelKeys.has(item.key)); + }); +} + +export function buildAutoSourceRoutes(config, catalog) { + const families = new Map(); + const add = (view, agentDeviceId) => { + if (!usable(view)) return; + const family = providerFamily(view); + if (!family) return; + const accounts = !agentDeviceId ? flattenableAccounts(catalog, view.id) : null; + if (accounts) { + const expanded = accounts.map((account) => ({ + id: view.id, + name: view.name ?? family, + accountId: account.id, + account, + view, + })); + families.set(family, [...(families.get(family) ?? []), ...expanded]); + } else { + families.set(family, [ + ...(families.get(family) ?? []), + { id: view.id, name: view.name ?? family, ...(agentDeviceId ? { agentDeviceId } : {}), view }, + ]); + } + }; + for (const view of catalog.views ?? []) add(view); + for (const [deviceId, entry] of catalog.remote ?? []) { + for (const view of entry.providers ?? []) add(view, deviceId); + } + + const hidden = new Set(config.hiddenAuto ?? []); + const routes = []; + for (const [family, found] of families) { + const id = `${MODEL_GROUP_AUTO_PREFIX}${family}`.slice(0, MODEL_GROUP_LIMITS.id); + const saved = config.autoSources?.[id] ?? []; + const rank = new Map(saved.map((source, index) => [modelGroupSourceKey(source), { index, source }])); + const savedFor = (source) => { + const exact = rank.get(modelGroupSourceKey(source)); + if (exact) return { ...exact, exact: true }; + const whole = source.accountId ? rank.get(modelGroupSourceKey({ providerId: source.providerId })) : undefined; + return whole ? { ...whole, exact: false } : undefined; + }; + const offKeys = new Set(); + for (const member of found) { + const source = { + providerId: member.id, + ...(member.agentDeviceId ? { agentDeviceId: member.agentDeviceId } : {}), + ...(member.accountId ? { accountId: member.accountId } : {}), + }; + if (savedFor(source)?.source.off) offKeys.add(memberSourceKey(member)); + } + const own = withoutRepeatedAccounts(found, catalog, offKeys) + .map((member, index) => ({ + member, + index, + rank: modelGroupTierRank(defaultModelGroupSourceTier({ + providerId: member.id, + agentDeviceId: member.agentDeviceId, + provider: member.view, + accountPayAsYouGo: Boolean(member.account?.apiConnectionId), + })), + })) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .map(({ member }) => member); + if (own.length < 2) continue; + const detected = own.map(({ id: providerId, agentDeviceId, accountId, account }) => ({ + source: { + providerId, + ...(agentDeviceId ? { agentDeviceId } : {}), + ...(accountId ? { accountId } : {}), + }, + accountPayAsYouGo: Boolean(account?.apiConnectionId), + })); + const ordered = detected + .map(({ source, accountPayAsYouGo }, index) => ({ source, accountPayAsYouGo, index, saved: savedFor(source) })) + .sort((a, b) => (a.saved ? a.saved.index : saved.length + a.index) - (b.saved ? b.saved.index : saved.length + b.index) || a.index - b.index) + .map(({ source, accountPayAsYouGo, saved: kept }) => ({ + ...source, + ...(kept?.source.off ? { off: true } : {}), + ...(kept?.source.weight ? { weight: kept.source.weight } : {}), + ...(kept?.source.tier && (kept.exact || !accountPayAsYouGo) ? { tier: kept.source.tier } : {}), + })); + routes.push({ + id, + name: own[0].name, + strategy: config.autoStrategy?.[id] ?? 'expiring', + sources: ordered.slice(0, MODEL_GROUP_LIMITS.candidates), + auto: true, + ...(hidden.has(id) ? { hidden: true } : {}), + }); + } + return routes; +} + +export function flattenManualSourceRoute(route, catalog) { + let changed = false; + const seen = new Set(); + const flattened = []; + for (const source of route.sources) { + if (!source.agentDeviceId && !source.accountId) { + const accounts = flattenableAccounts(catalog, source.providerId); + if (accounts) { + changed = true; + for (const account of accounts) { + const { tier: wholeTier, ...sourceRest } = source; + const item = { + ...sourceRest, + ...(wholeTier && !account.apiConnectionId ? { tier: wholeTier } : {}), + accountId: account.id, + }; + const key = modelGroupSourceKey(item); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(item); + } + continue; + } + } + const key = modelGroupSourceKey(source); + if (seen.has(key)) continue; + seen.add(key); + flattened.push(source); + } + return changed ? { ...route, sources: flattened.slice(0, MODEL_GROUP_LIMITS.candidates) } : route; +} + +export function expandSourceRouteDetail(route, catalog) { + const byModel = new Map(); + for (const source of route.sources) { + const views = locationViews(catalog, source.agentDeviceId); + const view = views.find((item) => item.id === source.providerId); + if (!view || !usable(view)) continue; + const account = !source.agentDeviceId && source.accountId + ? catalog.localAccounts?.get(source.providerId)?.find((item) => item.id === source.accountId) + : undefined; + for (const item of runnableProviderModels(catalog, view, source, account)) { + const entry = byModel.get(item.key) ?? { name: item.name, items: [] }; + entry.items.push(item.candidate); + byModel.set(item.key, entry); + } + } + const routes = []; + for (const [modelKey, { name, items }] of byModel) { + if (items.length === 0) continue; + routes.push({ + id: expandedId(route.id, modelKey), + name, + strategy: route.strategy, + parent: { id: route.id, name: route.name, model: modelKey }, + candidates: items, + }); + } + return { routes }; +} + +export function effectiveModelGroupsConfig(config, catalog) { + const autoRoutes = buildAutoSourceRoutes(config, catalog); + const manualRoutes = (config.sourceRoutes ?? []).map((route) => flattenManualSourceRoute(route, catalog)); + const sourceRoutes = [...autoRoutes, ...manualRoutes]; + const expanded = sourceRoutes.flatMap((route) => expandSourceRouteDetail(route, catalog).routes); + return { + ...config, + sourceRoutes, + routes: [...(config.routes ?? []), ...expanded], + }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/src/usage.mjs b/questions/smart-routing-three-tiers/v1/reference/src/usage.mjs new file mode 100644 index 0000000..c8d91ad --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/src/usage.mjs @@ -0,0 +1,64 @@ +export const FIVE_HOURS_MS = 5 * 3_600_000; +export const PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT = 85; +export const PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS = 60 * 60_000; + +function fiveHourTight(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || usedPercent < PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT) return false; + if (resetAtMs === null) return true; + return resetAtMs > now && resetAtMs - now > PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS; +} + +function fiveHourLeft(usedPercent, resetAtMs, now) { + if (usedPercent === undefined || !Number.isFinite(usedPercent)) return null; + if (resetAtMs !== null && (resetAtMs <= now || resetAtMs - now <= PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS)) return null; + return Math.max(0, Math.min(100, 100 - usedPercent)); +} + +function tightestLeft(values) { + const known = values.filter((value) => value !== null); + return known.length > 0 ? Math.min(...known) : null; +} + +function timeLeftPercent(window, now) { + if (window.resetAtMs === null) return window.usedPercent > 0 ? null : 100; + const left = window.resetAtMs - now; + return left > 0 ? Math.min(100, (left / window.windowMs) * 100) : null; +} + +function quotaUrgency(window, now) { + const left = timeLeftPercent(window, now); + return left === null ? null : Math.max(0, 100 - window.usedPercent) / left; +} + +function paceOf(windows, now) { + let pace = null; + for (const window of windows) { + const urgency = quotaUrgency(window, now); + if (urgency === null) return null; + if (!pace || urgency < pace.urgency) pace = { urgency, window }; + } + return pace; +} + +function paceState(windows, now) { + const pace = windows ? paceOf(windows, now) : null; + return { + urgency: pace?.urgency ?? null, + quota: pace?.window ?? null, + headroom: windows && windows.length > 0 ? Math.max(0, 100 - Math.max(...windows.map((w) => w.usedPercent))) : null, + }; +} + +export function quotaWindowsScheduleState(windows, now) { + const live = windows.filter((w) => w.resetAtMs === null || w.resetAtMs > now); + const full = live.filter((w) => w.usedPercent >= 100); + const long = live.filter((w) => w.windowMs > FIVE_HOURS_MS); + const paced = long.length > 0 ? long : live; + return { + limited: full.length > 0, + resetAtMs: full.length > 0 && full.every((w) => w.resetAtMs !== null) ? Math.max(...full.map((w) => w.resetAtMs)) : null, + fiveHourTight: live.some((w) => w.windowMs <= FIVE_HOURS_MS && fiveHourTight(w.usedPercent, w.resetAtMs, now)), + fiveHourLeft: tightestLeft(live.filter((w) => w.windowMs <= FIVE_HOURS_MS).map((w) => fiveHourLeft(w.usedPercent, w.resetAtMs, now))), + ...paceState(paced.length > 0 ? paced : null, now), + }; +} diff --git a/questions/smart-routing-three-tiers/v1/reference/tests/smoke.test.mjs b/questions/smart-routing-three-tiers/v1/reference/tests/smoke.test.mjs new file mode 100644 index 0000000..5fcb834 --- /dev/null +++ b/questions/smart-routing-three-tiers/v1/reference/tests/smoke.test.mjs @@ -0,0 +1,116 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { pickModelGroupCandidate } from '../src/pick.mjs'; +import { applyRouteWeightStep } from '../src/scheduler.mjs'; +import { redactProviderCatalogForTunnel } from '../src/remote-catalog.mjs'; + +const NOW = Date.UTC(2026, 11, 3, 10, 0, 0); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +const week = (usedPercent, resetHours) => ({ + usedPercent, + resetAtMs: NOW + resetHours * HOUR, + windowMs: 7 * DAY, +}); + +const fact = (windows, extra = {}) => ({ + available: true, + modelName: 'Model', + sourceName: 'Source', + windows, + ...extra, +}); + +// True when any key or string value in `value` names `host`, either as the +// hostname of a parseable URL or as a bare host token such as "host:443". +const mentionsHost = (value, host) => { + const strings = []; + const walk = (v) => { + if (typeof v === 'string') strings.push(v); + else if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + strings.push(k); + walk(x); + } + } + }; + walk(value); + return strings.some((s) => { + try { + if (new URL(s).hostname === host) return true; + } catch {} + return (s.toLowerCase().match(/[a-z0-9-]+(?:\.[a-z0-9-]+)+/g) ?? []).some((t) => t === host); + }); +}; + +test('supports deterministic order, rotate, cheapest, and weighted strategies', () => { + const candidates = [ + { agentKind: 'codex', providerId: 'a', model: 'm1', weight: 3 }, + { agentKind: 'codex', providerId: 'b', model: 'm1', weight: 1 }, + ]; + const facts = [fact(null, { price: 15 }), fact(null, { price: 5 })]; + + const ordered = pickModelGroupCandidate({ id: 'r1', name: 'R1', strategy: 'order', candidates }, facts, { now: NOW }); + assert.equal(ordered.index, 0); + + const cheapest = pickModelGroupCandidate({ id: 'r2', name: 'R2', strategy: 'cheapest', candidates }, facts, { now: NOW }); + assert.equal(cheapest.index, 1); + assert.equal(cheapest.trace[1].why, 'cheapest'); + + let counters = new Map(); + const picks = []; + for (let i = 0; i < 4; i += 1) { + const res = pickModelGroupCandidate({ id: 'r3', name: 'R3', strategy: 'weighted', candidates }, facts, { now: NOW, weightCounters: counters }); + picks.push(res.index); + counters = applyRouteWeightStep(counters, res.weightStep); + } + assert.deepEqual(picks, [0, 0, 1, 0]); +}); + +test('auto strategy sprints expiring surplus subscriptions and skips exhausted sources', () => { + const route = { + id: 'r-auto', + name: 'Auto', + strategy: 'expiring', + candidates: [ + { agentKind: 'codex', providerId: 'sub-a', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-b', model: 'gpt-6' }, + { agentKind: 'codex', providerId: 'sub-c', model: 'gpt-6' }, + ], + }; + const res = pickModelGroupCandidate( + route, + [ + fact([week(100, 12)]), + fact([week(20, 6 * 24)]), + fact([week(40, 18)]), // urgency = 60 / (18/168*100) = 5.6 >= 2.0 + ], + { now: NOW }, + ); + assert.equal(res.index, 2); + assert.equal(res.trace[0].state, 'skipped'); + assert.equal(res.trace[0].why, 'limited'); + assert.equal(res.trace[2].why, 'expiring'); +}); + +test('redactProviderCatalogForTunnel strips upstream URLs while preserving display wireProtocol', () => { + const redacted = redactProviderCatalogForTunnel({ + providers: [ + { + id: 'kimi', + name: 'Kimi', + connected: true, + auth: { method: 'apiKey' }, + routing: { + pi: { upstream: 'https://api.kimi.com/coding/v1', wireProtocol: 'openai-chat' }, + }, + }, + ], + }, { sameAccountController: true }); + assert.equal(mentionsHost(redacted, 'api.kimi.com'), false); + assert.deepEqual(redacted.providers[0].kimiCodingUsageAgents, ['pi']); + assert.equal(redacted.providers[0].routing.pi.wireProtocol, 'openai-chat'); +}); diff --git a/scripts/build-real-cshare-corpus.py b/scripts/build-real-cshare-corpus.py new file mode 100644 index 0000000..fc2e063 --- /dev/null +++ b/scripts/build-real-cshare-corpus.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python3 +"""Rebuild real .cshare entry sets for selected Cindy sessions, without the desktop app. + +Reproduces the file layout that the desktop exporter (``sessionShareExport.ts``) puts inside +a single-session ``.cshare`` zip: ``session.json`` (whitelisted snapshot), ``messages.jsonl``, +native transcripts (``transcripts/claude/.jsonl`` or ``transcripts/codex/``), +``codex-state/thread.json``, ``media-map.json`` and ``manifest.json``, in the exporter's order. +Plugin-engine (acp) sessions are db-only, exactly as the exporter does. + +The output is RAW and PRIVATE: it still contains local paths, injected system context and +whatever else the sessions saw. Write it outside the public eval-bank repository and run +``scrub-real-cshare-corpus.py`` before anything is published. + +Usage: + python3 -B scripts/build-real-cshare-corpus.py \ + --where "working_dir like '/private/var/folders/%/T/eval-%'" +""" + +import argparse +import datetime as dt +import glob +import hashlib +import json +import os +import sqlite3 +import sys + +HOME = os.path.expanduser("~") +CINDY_DATA = os.path.join(HOME, "Library", "Application Support", "CindyGlobal") + +FORMAT_VERSION = 3 +MIN_READER = {"plain": 1, "orca": 2, "acp": 3} + +MESSAGE_COLUMNS = ( + "id, client_id AS clientId, role, content, tool_use_id AS toolUseId, agent_meta AS agentMeta, " + "agent_kind AS agentKind, created_at AS createdAt, rewind_at AS rewindAt" +) + + +def js_compact(obj): + return json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + + +def js_pretty(obj): + return json.dumps(obj, ensure_ascii=False, indent=2) + + +def claude_transcript_index(): + """sid -> transcript path across the default and per-account Claude config dirs.""" + index = {} + for root in sorted(glob.glob(os.path.join(HOME, ".claude*"))): + projects = os.path.join(root, "projects") + if not os.path.isdir(projects): + continue + for proj in os.scandir(projects): + if not proj.is_dir(): + continue + for f in os.scandir(proj.path): + if f.name.endswith(".jsonl") and f.is_file(): + index.setdefault(f.name[:-6], f.path) + claude_home = os.path.join(CINDY_DATA, "claude-home", "projects") + if os.path.isdir(claude_home): + for proj in os.scandir(claude_home): + if proj.is_dir(): + for f in os.scandir(proj.path): + if f.name.endswith(".jsonl"): + index.setdefault(f.name[:-6], f.path) + return index + + +def codex_location(thread_id): + for loc in glob.glob(os.path.join(CINDY_DATA, "codex-accounts", "*", "thread-index", "locations", f"{thread_id}.json")): + with open(loc) as f: + return json.load(f) + return None + + +def latest_state_db(home): + best = None + for name in os.listdir(home) if os.path.isdir(home) else []: + if name.startswith("state_") and name.endswith(".sqlite"): + try: + n = int(name[len("state_"):-len(".sqlite")]) + except ValueError: + continue + if best is None or n > best[0]: + best = (n, os.path.join(home, name)) + return best[1] if best else None + + +def codex_state_rows(sqlite_home, thread_id): + db = latest_state_db(sqlite_home) + if not db: + return {"threads": [], "threadDynamicTools": [], "threadSpawnEdges": []} + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + con.row_factory = sqlite3.Row + tables = {r[0] for r in con.execute("select name from sqlite_master where type='table'")} + + def read(table, col): + if table not in tables: + return [] + out = [] + for row in con.execute(f'select * from "{table}" where "{col}" = ?', (thread_id,)): + rec = {} + for k in row.keys(): + v = row[k] + rec[k] = v.hex() if isinstance(v, bytes) else v + out.append(rec) + return out + + res = { + "threads": read("threads", "id"), + "threadDynamicTools": read("thread_dynamic_tools", "thread_id"), + "threadSpawnEdges": read("thread_spawn_edges", "parent_thread_id"), + } + con.close() + return res + + +def session_snapshot(s, active_sid): + kind = s["agent_kind"] + snap = { + "title": s["title"], + "workspaceKind": s["workspace_kind"], + "model": s["model"], + "effort": s["effort"], + "permissionMode": s["permission_mode"], + "sdkSessionId": active_sid if kind in ("pi", "acp") or s["agent_device_id"] else (active_sid or s["sdk_session_id"]), + "totalTokenUsage": s["total_token_usage"], + "totalCostUsd": s["total_cost_usd"], + "contextTokens": s["context_tokens"], + "contextWindow": s["context_window"], + "fastMode": bool(s["fast_mode"] or False), + "planModeEnabled": bool(s["plan_mode_enabled"]), + "agentKind": kind, + } + if kind == "acp": + snap["providerId"] = s["provider_id"] + chp = s["codex_history_has_product_prompt"] + snap["codexHistoryHasProductPrompt"] = None if chp is None else bool(chp) + snap["clearedAt"] = s["cleared_at"] + snap["userSendAt"] = s["user_send_at"] + snap["createdAt"] = s["created_at"] + snap["updatedAt"] = s["updated_at"] + return snap + + +def strip_meta_sid(agent_meta): + if not agent_meta: + return agent_meta + try: + meta = json.loads(agent_meta) + except ValueError: + return None + if not isinstance(meta, dict): + return None + if not isinstance(meta.get("sdkSessionId"), str): + return agent_meta + del meta["sdkSessionId"] + return js_compact(meta) + + +def build_bundle(con, s, claude_index): + kind = s["agent_kind"] + cond, params = ("and created_at > ?", [s["id"], s["cleared_at"]]) if s["cleared_at"] is not None else ("", [s["id"]]) + rows = [dict(r) for r in con.execute( + f"select {MESSAGE_COLUMNS} from messages where session_id = ? {cond} order by created_at asc, id asc", params)] + + entries = [] # (path, bytes) + refs = [] + sdk_ids = [] + active = None + codex_state = None + transcripts = [] + + if kind == "acp": + for r in rows: + r["agentMeta"] = strip_meta_sid(r["agentMeta"]) + if r["role"] == "agent_switch": + try: + c = json.loads(r["content"]) + if isinstance(c, dict): + c["fromSdkSessionId"] = None + r["content"] = js_compact(c) + except ValueError: + pass + elif kind == "cc": + ids = [] + if s["sdk_session_id"]: + ids.append(s["sdk_session_id"]) + for r in rows: + try: + sid = json.loads(r["agentMeta"] or "null") + sid = sid.get("sdkSessionId") if isinstance(sid, dict) else None + except ValueError: + sid = None + if isinstance(sid, str) and sid.strip() and sid.strip() not in ids: + ids.append(sid.strip()) + sdk_ids = ids + active = s["sdk_session_id"] + for sid in ids: + p = claude_index.get(sid) + if p and os.path.getsize(p) > 0: + zp = f"transcripts/claude/{sid}.jsonl" + with open(p, "rb") as f: + transcripts.append((zp, f.read())) + refs.append({"sdkSessionId": sid, "path": zp}) + else: + refs.append({"sdkSessionId": sid, "path": None}) + elif kind == "codex": + active = s["sdk_session_id"] + sdk_ids = [active] if active else [] + if active: + loc = codex_location(active) + if loc: + codex_state = codex_state_rows(loc["sqliteHome"], active) + rp = loc.get("path") + if rp and os.path.isfile(rp) and os.path.getsize(rp) > 0: + zp = f"transcripts/codex/{os.path.basename(rp)}" + with open(rp, "rb") as f: + transcripts.append((zp, f.read())) + refs.append({"sdkSessionId": active, "path": zp}) + else: + refs.append({"sdkSessionId": active, "path": None}) + else: + refs.append({"sdkSessionId": active, "path": None}) + else: + raise SystemExit(f"unsupported agent kind {kind}") + + entries.append(("session.json", js_pretty(session_snapshot(s, active)).encode())) + entries.append(("messages.jsonl", "\n".join(js_compact(r) for r in rows).encode())) + entries.extend(transcripts) + if codex_state is not None: + entries.append(("codex-state/thread.json", js_pretty(codex_state).encode())) + entries.append(("media-map.json", js_pretty({"entries": []}).encode())) + + found = sum(1 for r in refs if r["path"]) + fidelity = "db-only" if not refs or found == 0 else ("full" if found == len(refs) else "partial") + bundle_version = MIN_READER["acp"] if kind == "acp" else MIN_READER["plain"] + manifest = { + "formatVersion": FORMAT_VERSION if kind == "acp" else bundle_version, + "minReaderVersion": bundle_version, + "appVersion": "0.0.0", + "platform": "darwin", + "exportedAt": dt.datetime.fromtimestamp(s["updated_at"] / 1000, dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"), + "agentKind": kind, + **({"providerId": s["provider_id"]} if kind == "acp" else {}), + "title": s["title"], + "workspaceKind": "dialogue" if s["workspace_kind"] == "dialogue" else "project", + "originalWorkingDir": s["working_dir"], + "sdkSessionIds": sdk_ids, + "activeSdkSessionId": None if kind == "acp" else active, + "exportFidelity": fidelity, + "counts": {"messages": len(rows), "media": 0}, + "entries": [{"path": p, "bytes": len(b), "sha256": hashlib.sha256(b).hexdigest()} for p, b in entries], + "transcripts": refs, + } + entries.append(("manifest.json", js_pretty(manifest).encode())) + return entries, fidelity + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("db") + ap.add_argument("out") + ap.add_argument("--where", required=True, help="SQL condition on the sessions table") + args = ap.parse_args() + + con = sqlite3.connect(f"file:{args.db}?mode=ro", uri=True) + con.row_factory = sqlite3.Row + sessions = [dict(r) for r in con.execute(f"select * from sessions where {args.where} order by created_at, id")] + claude_index = claude_transcript_index() + os.makedirs(args.out, exist_ok=True) + index = [] + for n, s in enumerate(sessions): + entries, fidelity = build_bundle(con, s, claude_index) + label = f"b{n:03d}" + bdir = os.path.join(args.out, label) + os.makedirs(bdir, exist_ok=True) + for p, b in entries: + fp = os.path.join(bdir, "files", p) + os.makedirs(os.path.dirname(fp), exist_ok=True) + with open(fp, "wb") as f: + f.write(b) + with open(os.path.join(bdir, "order.json"), "w") as f: + json.dump([p for p, _ in entries], f, indent=1) + index.append({ + "label": label, "sessionId": s["id"], "title": s["title"], "agentKind": s["agent_kind"], + "model": s["model"], "fidelity": fidelity, "entries": len(entries), + "bytes": sum(len(b) for _, b in entries), + }) + with open(os.path.join(args.out, "index.json"), "w") as f: + json.dump(index, f, indent=1, ensure_ascii=False) + tot = sum(x["bytes"] for x in index) + print(json.dumps({"bundles": len(index), "bytes": tot, + "fidelity": {k: sum(1 for x in index if x["fidelity"] == k) for k in ("full", "partial", "db-only")}})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/build-v2-bank.py b/scripts/build-v2-bank.py new file mode 100644 index 0000000..8a727d2 --- /dev/null +++ b/scripts/build-v2-bank.py @@ -0,0 +1,72 @@ +"""Build a portable cross-platform (platform='any') Eval Bank v2 offline distribution.""" +import hashlib, json, pathlib, shutil, sys + +def sha256_file(p: pathlib.Path) -> str: + h = hashlib.sha256() + with p.open('rb') as f: + for chunk in iter(lambda: f.read(1024 * 1024), b''): + h.update(chunk) + return h.hexdigest() + +def main(): + if len(sys.argv) < 3: + raise SystemExit('Usage: python3 scripts/build-v2-bank.py ') + repo = pathlib.Path(__file__).resolve().parent.parent + suite_path = pathlib.Path(sys.argv[1]).resolve() + dst = pathlib.Path(sys.argv[2]).resolve() + if dst.exists(): + raise SystemExit(f'Output directory already exists: {dst}') + dst.mkdir(parents=True, exist_ok=False) + suite = json.loads(suite_path.read_text()) + rows = [] + for entry in suite['questions']: + qid, rev = entry['id'], entry['revision'] + rel = pathlib.Path('questions') / qid / rev + src_q = repo / rel + dst_q = dst / rel + dst_q.mkdir(parents=True) + shutil.copy2(src_q / 'question.json', dst_q / 'question.json') + shutil.copytree(src_q / 'candidate', dst_q / 'candidate', symlinks=False) + shutil.copytree(src_q / 'author', dst_q / 'author', symlinks=False) + spec = json.loads((dst_q / 'question.json').read_text()) + if spec['id'] != qid or spec['revision'] != rev: + raise ValueError(f'Question identity mismatch for {qid}@{rev}') + hashes = {} + for p in sorted(dst_q.rglob('*')): + if p.is_symlink(): + raise ValueError(f'Symlink forbidden: {p}') + if p.is_file(): + if '__pycache__' in p.parts or p.suffix == '.pyc': + p.unlink() + continue + hashes[p.relative_to(dst_q).as_posix()] = sha256_file(p) + source_manifest_sha = hashlib.sha256( + json.dumps(hashes, sort_keys=True, separators=(',', ':')).encode() + ).hexdigest() + rows.append({ + 'key': f'{qid}@{rev}', + 'title': spec['title'], + 'revision': rev, + 'environment': spec.get('environment', 'any'), + 'path': rel.as_posix(), + 'sourceManifestSha256': source_manifest_sha, + 'files': hashes, + }) + print(f"{qid}@{rev}: {len(hashes)} files, {sum((dst_q / k).stat().st_size for k in hashes) / 1024:.1f} KiB") + + dist = { + 'format': 'eval-lab-bank-v1', + 'suite': suite['id'], + 'platform': 'any', + 'questions': rows, + } + (dst / 'distribution.json').write_text(json.dumps(dist, ensure_ascii=False, indent=2) + '\n') + metric_count = sum(1 for q in suite['questions'] if q.get('kind') == 'metric') + (dst / 'README.txt').write_text( + f"Cindy Eval Bank 跨平台离线题包 {suite['id']}(platform: any,纯 Node.js >= 20 + Python 3,零外部依赖)。\n" + f"共 {len(rows)} 道题,其中 {metric_count} 道为连续数值优化题;不含参考答案、控制组或私人聊天。\n" + ) + print(json.dumps({'suite': suite['id'], 'platform': 'any', 'questions': len(rows), 'output': str(dst)}, ensure_ascii=False)) + +if __name__ == '__main__': + main() diff --git a/scripts/extract-real-link-profiles.py b/scripts/extract-real-link-profiles.py new file mode 100644 index 0000000..a2658a5 --- /dev/null +++ b/scripts/extract-real-link-profiles.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Turn Cindy Desktop device-link diagnostics into weak-network link profiles for +opt-relay-congestion-scheduler. + +Usage: + python3 -B scripts/extract-real-link-profiles.py [ ...] + +Reads only `device-link diagnostic` lines and only these fields: stage, relay round-trip time +(`transport.relayRttMs`), send size / attempts / time to ack, reply size and timing of slow +requests, concurrent peer counts, path (relay or direct) and the product channel name. +Timestamps become offsets inside a link; app instances and peer device ids become +`link-N` / `peer-N`. Nothing else from the log is kept, so the output carries no chat text, +paths, accounts or wall-clock times. + +Per relay link (app instance x controller) it measures: + - rtt p50 / p90 from relay round-trip samples + - loss as the retransmitted share of sends (attempts - 1 over attempts) + - stalls: sends whose current attempt waited >= max(1.5 s, 3 x rtt p50) for its ack; + each becomes an outage of (wait - rtt p50) in the 60 s real window with the most stall time + - capacity: p95 of the goodput seen on large (>= 32 KiB) replies, a lower bound of what the + path carried (the product's own pacing limited these transfers) + - message sizes: real send sizes on that link, small (<= 2 KiB) and large (>= 16 KiB); + the bulk backlog uses real large sizes (up to a quarter of a controller's share) adding up to + 20 s of the measured capacity, split evenly between two controllers + - concurrency: how many other controllers had bytes pending at the same time +Output: links.json (all measured links) and profiles.json (sim profiles for the busiest links). +""" + +import datetime +import json +import math +import os +import statistics +import sys +from collections import defaultdict + +MARK = 'device-link diagnostic ' +MIN_SENDS = 150 +WINDOW_MS = 60_000 +BULK_LINK_SECONDS = 20 # bulk backlog = this many seconds of the link's measured capacity +# Interactive deadline (a no-starvation gate, not the score): the longest outage, plus waiting +# behind the whole bulk backlog sent DEADLINE_BULK_FACTOR times over, plus 8 s. +DEADLINE_BULK_FACTOR = 2 + + +def parse(paths): + seen = set() + out = [] + for path in paths: + with open(path, errors='replace') as f: + for line in f: + i = line.find(MARK) + if i < 0 or not line.startswith('['): + continue + try: + t = datetime.datetime.fromisoformat(line[1:line.index(']')]).timestamp() * 1000 + d = json.loads(line[i + len(MARK):]) + except (ValueError, json.JSONDecodeError): + continue + key = (d.get('instance'), d.get('event'), d.get('part'), d.get('stage')) + if key in seen: + continue + seen.add(key) + d['_t'] = t + out.append(d) + out.sort(key=lambda d: d['_t']) + return out + + +def q(values, p): + if not values: + return None + s = sorted(values) + return s[min(len(s) - 1, int(len(s) * p))] + + +def measure(recs): + links = defaultdict(lambda: {'rtt': [], 'sends': [], 'replies': [], 'others': []}) + for d in recs: + dst = d.get('dst') + if not dst: + continue + link = links[(d.get('instance'), dst)] + tr = d.get('transport') if isinstance(d.get('transport'), dict) else {} + if tr.get('relayRttMs') is not None: + link['rtt'].append(tr['relayRttMs']) + if isinstance(tr.get('otherPeers'), list): + link['others'].append(sum(1 for p in tr['otherPeers'] if (p or {}).get('pending'))) + stage = d.get('stage') + if stage == 'send' and d.get('path') == 'relay' and d.get('outcome') == 'acked': + link['sends'].append({ + 't': d['_t'], 'bytes': d.get('bytes') or 0, 'attempts': d.get('attempts') or 1, + 'waitMs': d.get('currentAttemptToAckMs') or 0, + 'kind': (d.get('channel') or '').split(':', 1)[0], + }) + if stage == 'request' and (d.get('replyBytes') or 0) >= 32 * 1024: + rtt = tr.get('relayRttMs') or 300 + dur = (d.get('afterFirstWriteMs') or 0) - rtt + if dur > 50: + link['replies'].append(d['replyBytes'] * 8 / (dur / 1000)) + return links + + +def stalls_in_best_window(sends, rtt50): + threshold = max(1500, 3 * rtt50) + stalls = sorted((s['t'] - s['waitMs'], s['waitMs'] - rtt50) for s in sends if s['waitMs'] >= threshold) + best, best_ms = [], 0 + for i, (start, _) in enumerate(stalls): + window = [(s, d) for s, d in stalls[i:] if s < start + WINDOW_MS] + total = sum(d for _, d in window) + if total > best_ms: + best, best_ms = window, total + merged = [] + for s, d in best: + e = s + d + if merged and s <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], e) + else: + merged.append([s, e]) + base = merged[0][0] - 1500 if merged else 0 + return [[round(s - base), round(e - base)] for s, e in merged], len(stalls) + + +def summarize(links): + rows = [] + for (instance, dst), link in links.items(): + sends = link['sends'] + if len(sends) < MIN_SENDS or len(link['rtt']) < 30: + continue + rtt50, rtt90 = q(link['rtt'], 0.5), q(link['rtt'], 0.9) + attempts = sum(s['attempts'] for s in sends) + outages, stall_count = stalls_in_best_window(sends, rtt50) + span_h = max(1e-6, (sends[-1]['t'] - sends[0]['t']) / 3_600_000) + rows.append({ + '_key': (instance, dst), + 'sends': len(sends), 'spanHours': round(span_h, 2), + 'rttP50Ms': rtt50, 'rttP90Ms': rtt90, + 'lossPct': round(100 * (attempts - len(sends)) / attempts, 3), + 'stallsPerHour': round(stall_count / span_h, 2), + 'worstWindowOutagesMs': outages, + 'capacityBps': round(q(link['replies'], 0.95)) if len(link['replies']) >= 5 else None, + 'smallSizes': [s['bytes'] for s in sends if 0 < s['bytes'] <= 2048], + 'largeSizes': [s['bytes'] for s in sends if s['bytes'] >= 16 * 1024], + 'concurrentPeersP75': q(link['others'], 0.75) or 0, + }) + rows.sort(key=lambda r: -r['sends']) + for n, r in enumerate(rows): + r['link'] = f'link-{n}' + return rows + + +def pick(values, count, salt): + """Deterministic spread of `count` real values (by rank), no randomness needed.""" + s = sorted(values) + if not s: + return [] + return [s[(i * 7919 + salt) % len(s)] for i in range(count)] + + +def pick_until(values, total_bytes, salt): + """Real sizes, picked like `pick`, until they add up to at least `total_bytes`.""" + s = sorted(values) + out, i = [], 0 + while sum(out) < total_bytes: + out.append(s[(i * 7919 + salt) % len(s)]) + i += 1 + return out + + +def profile(row, fallback_capacity): + rtt50, rtt90 = row['rttP50Ms'], row['rttP90Ms'] + capacity = round(max(row['capacityBps'] or fallback_capacity, 256_000)) + queue = int(min(256_000, max(16_000, capacity / 8 * (rtt90 - rtt50) / 1000))) + outages = row['worstWindowOutagesMs'] + longest = max((e - s for s, e in outages), default=0) + horizon = max(5000, (outages[-1][1] + 1500) if outages else 0) + peers_n = int(min(4, max(3, 2 + row['concurrentPeersP75']))) + peers = [f'peer-{i}' for i in range(peers_n)] + large = row['largeSizes'] or [32 * 1024] + small = row['smallSizes'] or [512] + per_controller = capacity / 8 * BULK_LINK_SECONDS / 2 + # Sizes up to a quarter of a controller's backlog, so no single message decides fairness. + bulk_sizes = pick_until([b for b in large if b <= per_controller / 4] or [min(large)], per_controller, 1) + # Three request waves across the profile; inside a wave each controller's messages are 1 ms + # apart, so the two controllers' requests interleave instead of arriving as one block. + waves = [0, round(horizon * 0.3), round(horizon * 0.6)] + wave_of = [j * len(waves) // len(bulk_sizes) for j in range(len(bulk_sizes))] + bulk_times = [waves[w] + (j - wave_of.index(w)) for j, w in enumerate(wave_of)] + link = { + 'bitsPerSecond': capacity, 'propagationDelayMs': round(rtt50 / 2), + 'jitterMs': round(min(rtt50 / 2, max(1, (rtt90 - rtt50) / 2))), 'jitterFifo': True, + 'lossProb': round(row['lossPct'] / 100, 5), 'queueBytes': queue, + } + return { + 'name': row['link'], + 'seed': 7001 + int(row['link'].split('-')[1]), + 'source': {k: row[k] for k in ('sends', 'spanHours', 'rttP50Ms', 'rttP90Ms', 'lossPct', 'stallsPerHour', 'capacityBps')}, + 'peers': peers, + 'downlink': {**link, 'outages': outages}, + 'uplink': dict(link), + # Two controllers pull the same real sizes at the same time (equal bytes per controller). + 'bulkPeers': [ + {'peerId': peers[i], 'streamId': 'bulk-0', 'messageSizes': list(bulk_sizes), + 'waveTimesMs': bulk_times} + for i in range(2) + ], + 'interactive': { + 'count': 120, 'sizes': pick(small, 120, 5), + 'deadlineMs': max(18_000, longest + 8_000 + DEADLINE_BULK_FACTOR * BULK_LINK_SECONDS * 1000), + 'windows': [[120, horizon]], + 'peers': [peers[i % peers_n] for i in (2, 3, 0, 2, 3, 1)][:6] if peers_n > 3 else [peers[2], peers[0], peers[2], peers[1]], + }, + } + + +def main(): + if len(sys.argv) < 3: + raise SystemExit(__doc__) + out = sys.argv[1] + rows = summarize(measure(parse(sys.argv[2:]))) + caps = [r['capacityBps'] for r in rows if r['capacityBps']] + fallback = statistics.median(caps) if caps else 1_000_000 + os.makedirs(out, exist_ok=True) + public_rows = [{k: v for k, v in r.items() if not k.startswith('_') and k not in ('smallSizes', 'largeSizes')} for r in rows] + with open(os.path.join(out, 'links.json'), 'w') as f: + json.dump(public_rows, f, indent=1) + with open(os.path.join(out, 'profiles.json'), 'w') as f: + json.dump([profile(r, fallback) for r in rows], f, indent=1) + print(json.dumps({'links': len(rows), 'fallbackCapacityBps': round(fallback), + 'summary': [{k: r[k] for k in ('link', 'sends', 'rttP50Ms', 'rttP90Ms', 'lossPct', 'stallsPerHour', 'capacityBps')} + | {'outages': len(r['worstWindowOutagesMs'])} for r in rows]}, indent=1)) + + +if __name__ == '__main__': + main() diff --git a/scripts/extract-real-routing-trace.py b/scripts/extract-real-routing-trace.py new file mode 100644 index 0000000..928df7a --- /dev/null +++ b/scripts/extract-real-routing-trace.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Extract a de-identified real routing workload from a local Cindy database. + +Reads only usage fields from ``messages.agent_meta`` (never message content) and writes +per-window JSON traces for the opt-routing-cost-sim question. Output must stay outside the +public eval-bank repository until the owner approves publishing it. + +Usage: + python3 -B scripts/extract-real-routing-trace.py [--weeks 12] + +Each turn record (arrays keep files small): + [t, d, s, model, src, n, i, r, c, o, warmReal] + t arrival ms since the window's Monday 00:00 (local clock, so weekday/hour are real) + d service duration ms (turn wall time) + s session index within the window (first-appearance order; not reversible) + model canonical public model id + src real source label (generic ids such as codex-sub-2; account identifiers dropped) + n upstream requests in the turn + i/r/c/o uncached input, cache-read, cache-write and output tokens for the whole turn + warmReal 1 when the real turn started on the same source within 5 minutes of the + previous turn's end (used to split the turn-start prefix from in-turn volume) +""" + +import argparse +import datetime as dt +import json +import os +import sqlite3 +import sys +from collections import defaultdict + +FIVE_MIN_MS = 5 * 60_000 +# No model in the data accepts more than 1M context tokens; larger estimates come from +# turns whose request count is wrong, so the excess stays in-turn volume. +CONTEXT_CAP = 1_000_000 +DAY_MS = 86_400_000 + +PREFIXES = ("byok-openai-codex/", "openai-codex/", "openai/", "anthropic/", "google/", "xai/") + + +def canonical_model(model, per_model): + for cand in (model, per_model): + if not cand or cand == "auto": + continue + m = cand + for p in PREFIXES: + if m.startswith(p): + m = m[len(p):] + if m.startswith("deepseek/"): + m = m[len("deepseek/"):] + return m + return None + + +def family(model): + if model.startswith("claude-"): + return "anthropic" + if model.startswith("gpt-"): + return "openai" + if model.startswith("gemini-"): + return "google" + if model.startswith("grok-"): + return "xai" + if model.startswith("deepseek"): + return "deepseek" + return None + + +class SourceNamer: + """Maps real provider ids to generic labels in first-seen order.""" + + def __init__(self): + self.seen = {} + self.counts = defaultdict(int) + + def label(self, provider_id, billing, fam): + if provider_id in (None, ""): + if fam == "google": + provider_id, billing = "acp-google", "subscription" + else: + return None + if provider_id == "xd": + return "gateway" + if provider_id.startswith("byok-"): + return "byok-" + (fam or "unknown") + if provider_id in self.seen: + return self.seen[provider_id] + if provider_id.startswith("anthropic"): + base = "claude-sub" + elif provider_id.startswith("openai"): + base = "codex-sub" + elif provider_id.startswith("xai"): + base = "xai-sub" + elif provider_id == "acp-google": + base = "google-sub" + elif billing == "subscription": + base = (fam or "other") + "-sub" + else: + base = "payg-" + (fam or "other") + self.counts[base] += 1 + name = f"{base}-{self.counts[base]}" + self.seen[provider_id] = name + return name + + +def local_monday(ms): + d = dt.datetime.fromtimestamp(ms / 1000).astimezone() + monday = (d - dt.timedelta(days=d.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) + return int(monday.timestamp() * 1000) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("db") + ap.add_argument("out") + ap.add_argument("--weeks", type=int, default=12) + args = ap.parse_args() + + now_ms = int(dt.datetime.now().timestamp() * 1000) + since = now_ms - args.weeks * 7 * DAY_MS + con = sqlite3.connect(f"file:{args.db}?mode=ro", uri=True) + rows = con.execute( + """ + select session_id, created_at, + json_extract(agent_meta,'$.turnUsageDetails.model'), + json_extract(agent_meta,'$.turnUsageDetails.perModelTokens[0].model'), + json_extract(agent_meta,'$.turnUsageDetails.providerId'), + json_extract(agent_meta,'$.turnUsageDetails.billingSource'), + json_extract(agent_meta,'$.turnUsageDetails.inputTokens'), + json_extract(agent_meta,'$.turnUsageDetails.cacheReadTokens'), + json_extract(agent_meta,'$.turnUsageDetails.cacheCreateTokens'), + json_extract(agent_meta,'$.turnUsageDetails.outputTokens'), + json_extract(agent_meta,'$.turnUsageDetails.turnDurationMs'), + json_extract(agent_meta,'$.turnUsageDetails.durationMs'), + json_extract(agent_meta,'$.turnUsageDetails.trace.requests') + from messages indexed by idx_messages_created_at + where created_at >= ? and role = 'assistant' + and json_extract(agent_meta,'$.turnUsageDetails.totalTokens') is not null + order by created_at + """, + (since,), + ).fetchall() + + namer = SourceNamer() + skipped = defaultdict(int) + turns = [] + last_model = {} + for (sid, created, model, pm, prov, billing, i, r, c, o, tdur, dur, reqs) in rows: + m = canonical_model(model, pm) + if not m: + # Older rows sometimes omit the model; the session kept using its previous one. + m = last_model.get(sid) + fam = family(m) if m else None + if fam: + last_model[sid] = m + if not fam: + skipped["unknown_model"] += 1 + continue + i, r, c, o = (int(x or 0) for x in (i, r, c, o)) + if i + r + c + o <= 0: + skipped["zero_tokens"] += 1 + continue + d = int(tdur or dur or 0) + d = max(1000, min(d, 4 * 3_600_000)) + turns.append({ + "sid": sid, "end": int(created), "start": int(created) - d, "d": d, + "model": m, "fam": fam, "src": namer.label(prov, billing, fam), + "n": int(reqs) if reqs else None, "i": i, "r": r, "c": c, "o": o, + }) + + # Order by arrival; fill unknown sources from the session's previous turn and + # decide whether the real turn started warm (same source within 5 minutes). + turns.sort(key=lambda t: (t["start"], t["end"])) + last = {} + for t in turns: + prev = last.get(t["sid"]) + if t["src"] is None: + t["src"] = prev["src"] if prev and prev["fam"] == t["fam"] else f"{t['fam']}-unknown" + t["warm"] = int(bool(prev) and prev["src"] == t["src"] and 0 <= t["start"] - prev["end"] <= FIVE_MIN_MS) + last[t["sid"]] = t + + if not turns: + print("no turns", file=sys.stderr) + return 1 + + # Older rows lack the upstream request count. Impute it from the same model's + # median output-per-request and context-per-request (geometric mean of both + # estimates; on instrumented turns this lands within 2x of the truth ~90% of the time). + def median(xs): + xs = sorted(xs) + return xs[len(xs) // 2] if xs else None + + known = [t for t in turns if t["n"]] + per_model = defaultdict(lambda: ([], [])) + for t in known: + outs, ctxs = per_model[t["model"]] + outs.append(t["o"] / t["n"]) + ctxs.append((t["i"] + t["r"] + t["c"]) / t["n"]) + g_out = median([t["o"] / t["n"] for t in known]) or 300 + g_ctx = median([(t["i"] + t["r"] + t["c"]) / t["n"] for t in known]) or 50_000 + for t in turns: + t["imputed"] = 0 + if t["n"]: + continue + outs, ctxs = per_model.get(t["model"], ([], [])) + k_out = median(outs) or g_out + k_ctx = median(ctxs) or g_ctx + est = ((max(1.0, t["o"] / max(k_out, 1)) * max(1.0, (t["i"] + t["r"] + t["c"]) / max(k_ctx, 1))) ** 0.5) + t["n"] = int(min(500, max(1, round(est)))) + t["imputed"] = 1 + + # Split each turn into the turn-start context P (what a warm cache from the previous + # turn can cover) and the in-turn volume that is billed the same wherever the turn runs. + # Context is assumed to grow linearly over the turn's n requests by the new content + # (cache writes + uncached input + output). P comes out of the bucket it was billed in + # for real: cache reads when the real turn started warm, cache writes / input when cold. + for t in turns: + n, i, r, c, o = t["n"], t["i"], t["r"], t["c"], t["o"] + avg = (i + r + c) / n + growth = (c + i + o) * (n - 1) / (2 * n) + if t["warm"]: + p = min(max(0.0, avg - growth), r, CONTEXT_CAP) + t["P"], t["ri"], t["ci"], t["ii"] = int(p), r - int(p), c, i + else: + p = min(max(0.0, (avg - growth) / ((n + 1) / (2 * n))), c + i, CONTEXT_CAP) + p = int(p) + from_c = min(c, p) + t["P"], t["ri"], t["ci"], t["ii"] = p, r, c - from_c, i - (p - from_c) + + # Split into consecutive 14-day windows aligned to local Monday 00:00. + first_monday = local_monday(turns[0]["start"]) + windows = defaultdict(list) + for t in turns: + k = (t["start"] - first_monday) // (14 * DAY_MS) + windows[k].append(t) + + os.makedirs(args.out, exist_ok=True) + summary = {"generatedFrom": "local Cindy database (usage fields only)", "skipped": dict(skipped), "windows": []} + for k in sorted(windows): + ws = windows[k] + w_start = first_monday + k * 14 * DAY_MS + complete = w_start + 14 * DAY_MS <= now_ms + sidx = {} + recs = [] + for t in ws: + s = sidx.setdefault(t["sid"], len(sidx)) + recs.append([t["start"] - w_start, t["d"], s, t["model"], t["P"], t["ri"], t["ci"], t["ii"], t["o"], + t["src"], t["warm"], t["n"], t["imputed"]]) + label = dt.datetime.fromtimestamp(w_start / 1000).astimezone().strftime("%Y-%m-%d") + name = f"real-14d-{label}" + with open(os.path.join(args.out, name + ".json"), "w") as f: + json.dump({"name": name, "startWeekday": "Monday", "complete": complete, "turns": recs}, f, separators=(",", ":")) + by_src = defaultdict(int) + by_model = defaultdict(int) + for t in ws: + by_src[t["src"]] += 1 + by_model[t["model"]] += 1 + summary["windows"].append({ + "name": name, "complete": complete, "turns": len(recs), "sessions": len(sidx), + "bySource": dict(sorted(by_src.items(), key=lambda kv: -kv[1])), + "byModel": dict(sorted(by_model.items(), key=lambda kv: -kv[1])), + }) + with open(os.path.join(args.out, "summary.json"), "w") as f: + json.dump(summary, f, indent=1, ensure_ascii=False) + print(json.dumps({"windows": [(w["name"], w["turns"], w["sessions"], w["complete"]) for w in summary["windows"]], "skipped": dict(skipped)})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/o2-capture/build-real-fixture.mjs b/scripts/o2-capture/build-real-fixture.mjs new file mode 100644 index 0000000..427416a --- /dev/null +++ b/scripts/o2-capture/build-real-fixture.mjs @@ -0,0 +1,134 @@ +#!/usr/bin/env node +/** + * Turn a de-identified real .cshare corpus (opt-cshare-compression/*.json.br) into the host + * fixture that realFixture.ts feeds to Cindy's transfer baseline. + * + * Usage: + * node scripts/o2-capture/build-real-fixture.mjs + * + * - Session rows and message rows are the real Cindy database rows from the corpus. + * - Tool results in archived tasks are compacted in the database (`tool_result_compacted`). + * They are restored from the engine's native transcript in the same bundle, i.e. the text + * the database held while the task was live (the harness applies the product persist cap). + * Plugin-engine tasks have no native transcript and keep the compacted marker, as in reality. + * - Text pools (prose, tool calls with full results) feed the live turns the product scenario + * runs, so streamed turns carry real content in the product's scripted turn shape. + * + * Input is already de-identified; this script adds no new data. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; + +const [corpusPath, outPath] = process.argv.slice(2); +if (!outPath) throw new Error('usage: build-real-fixture.mjs '); + +const corpus = JSON.parse(zlib.brotliDecompressSync(fs.readFileSync(corpusPath)).toString('utf8')); +const parse = (text) => { try { return JSON.parse(text); } catch { return text; } }; +const isCompacted = (value) => value && typeof value === 'object' && value.type === 'tool_result_compacted'; + +function toolOutputText(content) { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content.map((part) => (typeof part === 'string' ? part : part?.text ?? part?.content ?? '')).join(''); + } + return content == null ? '' : JSON.stringify(content); +} + +/** tool_use id → full result text, from the native transcript. */ +function claudeResults(text) { + const map = new Map(); + for (const line of text.split('\n')) { + if (!line) continue; + const rec = parse(line); + const parts = rec?.type === 'user' && Array.isArray(rec.message?.content) ? rec.message.content : []; + for (const part of parts) { + if (part?.type === 'tool_result' && typeof part.tool_use_id === 'string') map.set(part.tool_use_id, toolOutputText(part.content)); + } + } + return map; +} + +/** Codex call ids differ from Cindy's tool ids, so results are matched in call order. */ +function codexResultsInOrder(text) { + const out = []; + for (const line of text.split('\n')) { + if (!line) continue; + const p = parse(line)?.payload; + if (p && (p.type === 'function_call_output' || p.type === 'custom_tool_call_output')) { + const o = p.output; + out.push(typeof o === 'string' ? o : Array.isArray(o) ? o.map((x) => x?.text ?? '').join('') : toolOutputText(o?.content ?? o)); + } + } + return out; +} + +const sessions = []; +const pools = { prose: [], tools: [], outputs: [] }; +const stats = { restored: 0, keptCompacted: 0 }; + +for (const bundle of corpus.bundles) { + const entry = (p) => bundle.entries.find((e) => e.path === p); + const snap = parse(entry('session.json').text); + const manifest = parse(entry('manifest.json').text); + const rows = entry('messages.jsonl').text.split('\n').filter(Boolean).map(parse); + const transcript = bundle.entries.find((e) => e.path.startsWith('transcripts/')); + + let byId = new Map(); + if (transcript && bundle.agentKind === 'cc') byId = claudeResults(transcript.text); + if (transcript && bundle.agentKind === 'codex') { + const ordered = codexResultsInOrder(transcript.text); + const resultRows = rows.filter((r) => r.role === 'tool_result'); + if (ordered.length === resultRows.length) resultRows.forEach((r, i) => byId.set(r.toolUseId, ordered[i])); + } + + const toolUse = new Map(); + const outRows = rows.map((r) => { + let content = parse(r.content); + if (r.role === 'tool_use' && content && typeof content === 'object') toolUse.set(r.toolUseId, content); + if (r.role === 'tool_result' && isCompacted(content)) { + const full = byId.get(r.toolUseId); + if (typeof full === 'string') { content = full; stats.restored++; } else stats.keptCompacted++; + } + if (r.role === 'user' && typeof content?.text === 'string') pools.prose.push(content.text); + if (r.role === 'assistant' && typeof content === 'string') pools.prose.push(content); + if (r.role === 'thinking' && typeof content?.text === 'string' && content.text) pools.prose.push(content.text); + if (r.role === 'tool_result' && typeof content === 'string') { + pools.outputs.push(content); + const call = toolUse.get(r.toolUseId); + if (call?.toolName) pools.tools.push({ toolName: call.toolName, input: call.input ?? {}, result: content }); + } + return { + id: r.id, clientId: r.clientId ?? r.id, role: r.role, content, toolUseId: r.toolUseId ?? null, + ...(r.agentMeta ? { agentMeta: parse(r.agentMeta) } : {}), createdAt: r.createdAt, + }; + }); + + const lastText = [...outRows].reverse().find((r) => (r.role === 'assistant' && typeof r.content === 'string') || (r.role === 'user' && typeof r.content?.text === 'string')); + const previewSource = lastText ? (typeof lastText.content === 'string' ? lastText.content : lastText.content.text) : ''; + sessions.push({ + source: bundle.name, + title: snap.title, + preview: previewSource.slice(0, 120), + previewRole: lastText?.role ?? 'assistant', + agentKind: snap.agentKind, + columns: { + model: snap.model, effort: snap.effort ?? 'medium', permissionMode: snap.permissionMode ?? 'default', + agentKind: snap.agentKind, workingDir: manifest.originalWorkingDir ?? '/workspace/demo', + workspaceKind: snap.workspaceKind ?? 'project', contextTokens: snap.contextTokens ?? null, + contextWindow: snap.contextWindow ?? null, totalTokenUsage: snap.totalTokenUsage ?? 0, + totalCostUsd: snap.totalCostUsd ?? 0, planModeEnabled: !!snap.planModeEnabled, + }, + rows: outRows, + }); +} + +pools.prose = pools.prose.filter((t) => t.trim().length > 0); +pools.outputs = pools.outputs.filter((t) => t.length > 0); +fs.mkdirSync(path.dirname(outPath), { recursive: true }); +fs.writeFileSync(outPath, JSON.stringify({ suite: corpus.suite, sessions, pools })); +console.log(JSON.stringify({ + sessions: sessions.length, rows: sessions.reduce((s, x) => s + x.rows.length, 0), ...stats, + prose: pools.prose.length, tools: pools.tools.length, outputs: pools.outputs.length, + outputBytes: pools.outputs.reduce((s, t) => s + Buffer.byteLength(t), 0), +})); diff --git a/scripts/o2-capture/capture-to-trace.mjs b/scripts/o2-capture/capture-to-trace.mjs new file mode 100644 index 0000000..bb72e48 --- /dev/null +++ b/scripts/o2-capture/capture-to-trace.mjs @@ -0,0 +1,92 @@ +#!/usr/bin/env node +/** + * Convert a realCapture.bench.ts capture into an opt-device-link-delta-sync trace. + * + * Usage: + * node scripts/o2-capture/capture-to-trace.mjs + * + * Steps keep the host's arrival order: capture.jsonl is written as handlers return, so each + * run's reads are put back in `seq` order (assigned when the request arrived). Product protocol + * options are removed from the request arguments (`historyDelta`, `messageBodies`): they belong + * to today's sync protocol, which is exactly what the question replaces. Lifecycle events follow + * what happened in the capture: + * - each scenario run starts on a new host and a new controller → `cold_reconnect` + * - a new controller process on the same host (connect_cold / v3_connect / v4_connect) + * → `client_restart` (the client restarts from its persisted state; the host keeps running) + * - two reads in flight at once (second arrived before the first returned) → `concurrent_rpc` + * Network drops and phone background/foreground keep both processes, so they add no event; + * the reads they trigger are in the trace. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import crypto from 'node:crypto'; + +const [dir, name, out] = process.argv.slice(2); +if (!out) throw new Error('usage: capture-to-trace.mjs '); + +const lines = fs.readFileSync(path.join(dir, 'capture.jsonl'), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)); +const wire = JSON.parse(fs.readFileSync(path.join(dir, 'product-wire.json'), 'utf8')); +const RESTART_STAGES = new Set(['connect_cold', 'v3_connect', 'v4_connect']); + +function logicalArgs(channel, args) { + if (channel !== 'local-db:messages:view' || !args[1] || typeof args[1] !== 'object') return args; + const { historyDelta: _h, messageBodies: _m, ...rest } = args[1]; + return [args[0], rest, ...args.slice(2)]; +} + +// Group reads per run, remembering which stages ran (from the product wire rows) so a +// controller restart between two reads is visible even when the restart stage read nothing. +const runs = []; +let current = []; +for (const line of lines) { + if (line.marker === 'run-end') { runs.push({ name: line.run, reads: current.sort((a, b) => a.seq - b.seq) }); current = []; continue; } + current.push(line); +} +const stageOrder = wire.runs.map((run) => [...new Set(run.rows.map((row) => row.stage))]); + +const steps = []; +const meta = { name, totalRpcs: 0, channelCounts: {}, rawJsonBytes: 0, coldReconnectCount: 0, clientRestartCount: 0, concurrentPairCount: 0 }; +let id = 0; +const read = (rec) => { + const groundTruthValue = rec.result; + meta.totalRpcs += 1; + meta.channelCounts[rec.channel] = (meta.channelCounts[rec.channel] ?? 0) + 1; + meta.rawJsonBytes += Buffer.byteLength(JSON.stringify(groundTruthValue)); + return { id: `r${String(++id).padStart(4, '0')}`, channel: rec.channel, argsKey: JSON.stringify(logicalArgs(rec.channel, rec.args)), groundTruthValue }; +}; + +runs.forEach((run, runIndex) => { + if (runIndex > 0) { steps.push({ type: 'cold_reconnect', label: `new-host-and-controller-${run.name}` }); meta.coldReconnectCount += 1; } + const order = stageOrder[runIndex] ?? []; + let lastStage = null; + for (let i = 0; i < run.reads.length; i++) { + const rec = run.reads[i]; + if (lastStage !== null && rec.stage !== lastStage) { + const between = order.slice(order.indexOf(lastStage) + 1, order.indexOf(rec.stage) + 1); + const restart = between.find((stage) => RESTART_STAGES.has(stage)); + if (restart) { steps.push({ type: 'client_restart', label: restart }); meta.clientRestartCount += 1; } + } + lastStage = rec.stage; + const next = run.reads[i + 1]; + if (next && next.stage === rec.stage && next.t0 < rec.t1) { + steps.push({ type: 'concurrent_rpc', reads: [read(rec), read(next)] }); + meta.concurrentPairCount += 1; + i += 1; + lastStage = next.stage; + } else steps.push({ type: 'rpc', ...read(rec) }); + } +}); + +// What today's Cindy sends for the same reads: invoke requests and their results on the +// controller socket (WebSocket frames, after the product's transfer codec and permessage-deflate). +let productRpcWireBytes = 0; +for (const run of wire.runs) for (const row of run.rows) if (row.kind === 'invoke' || row.kind === 'result') productRpcWireBytes += row.wireBytes; +meta.productRpcWireBytes = productRpcWireBytes; +meta.sourceCommit = wire.commit; + +const json = Buffer.from(JSON.stringify({ name, meta, steps }), 'utf8'); +const packed = zlib.brotliCompressSync(json, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_LGWIN]: 24 } }); +fs.mkdirSync(path.dirname(out), { recursive: true }); +fs.writeFileSync(out, packed); +console.log(JSON.stringify({ ...meta, steps: steps.length, fileBytes: packed.length, sha256: crypto.createHash('sha256').update(packed).digest('hex') })); diff --git a/scripts/o2-capture/realCapture.bench.ts b/scripts/o2-capture/realCapture.bench.ts new file mode 100644 index 0000000..5f9b851 --- /dev/null +++ b/scripts/o2-capture/realCapture.bench.ts @@ -0,0 +1,99 @@ +/** + * Records every remote RPC the phone controller sends during Cindy's transfer-baseline + * scenario, served by the real Desktop handlers over the real relay, with the host database + * filled from real de-identified tasks (realFixture.ts). Output (O2_CAPTURE_OUT): + * - capture.jsonl: one line per RPC as the host handler returned it + * { seq, stage, channel, args, t0, t1, result } + * - product-wire.json: the product protocol's own wire bytes per stage and channel for the + * same run (WireMeter rows), i.e. what today's Cindy spends on this workload. + * Copied into apps/desktop/src/test/transfer-baseline only for the run (see run-capture.sh). + */ +import { mkdir, writeFile, appendFile } from 'node:fs/promises'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { expect, it } from 'vitest'; +import { ipcMain } from 'electron'; +import { installInvokeCapture } from '../../main/device-link/invoke-registry'; +import { buildFixture } from './realFixture'; +import { startBaselineHost } from './hostHarness'; +import { PROFILES } from './profiles'; +import { startBaselineRelay } from './relay'; +import { runListRepeat, runProfile, runV4, type ScenarioEnv } from './realScenarios'; +import { applyCapabilitySwitches, readCapabilitySwitches } from './switches'; +import { WireMeter } from './wireMeter'; + +const HOST_ID = 'baseline-host'; +const outDir = process.env.O2_CAPTURE_OUT; +let currentMeter: WireMeter | null = null; +let seq = 0; +const pending: string[] = []; + +function installRecorder(): void { + installInvokeCapture(); + const registered = ipcMain.handle.bind(ipcMain); + ipcMain.handle = ((channel: string, listener: (...a: unknown[]) => unknown) => registered(channel, async (event: unknown, ...args: unknown[]) => { + const n = ++seq; + const stage = currentMeter?.currentStage ?? null; + const t0 = Date.now(); + // history-view-delta-v1 is encoded inside the handler. Read the same page once without the + // delta option first (no base is named or stored, so the product's own delta state is + // untouched) and record that complete page as the value the controller ends up holding. + let full: unknown; + const opts = args[1]; + if (channel === 'local-db:messages:view' && opts && typeof opts === 'object' && 'historyDelta' in opts) { + const { historyDelta: _omit, ...plain } = opts as Record; + full = await listener(event, args[0], plain, ...args.slice(2)); + } + const result = await listener(event, ...args); + const recorded = full !== undefined ? full : result; + pending.push(JSON.stringify({ seq: n, stage, channel, args, t0, t1: Date.now(), result: recorded === undefined ? null : recorded, + ...(full !== undefined ? { productDeltaBytes: Buffer.byteLength(JSON.stringify(result)) } : {}) })); + return result; + })) as typeof ipcMain.handle; +} + +async function flush(): Promise { + if (!pending.length) return; + const lines = pending.splice(0).join('\n') + '\n'; + await appendFile(path.join(outDir!, 'capture.jsonl'), lines); +} + +it('captures the phone RPC workload on real task content', async () => { + if (!outDir) throw new Error('O2_CAPTURE_OUT is required'); + await mkdir(outDir, { recursive: true }); + await writeFile(path.join(outDir, 'capture.jsonl'), ''); + installRecorder(); + const fixture = buildFixture(); + const base = PROFILES.find((p) => p.id === (process.env.TRANSFER_BASELINE_PROFILE ?? 'phone'))!; + const switches = readCapabilitySwitches(base.id); + const profile = applyCapabilitySwitches(base, switches); + const runs: Array<[string, (env: ScenarioEnv) => Promise]> = [ + ['profile', (env) => runProfile(env, profile, {})], + ['lists', (env) => runListRepeat(env, profile)], + ['v4', (env) => runV4(env, profile)], + ]; + const wire: unknown[] = []; + for (const [name, run] of runs) { + const meter = new WireMeter(new Set()); + currentMeter = meter; + const relay = await startBaselineRelay(HOST_ID, PROFILES.map((p) => ({ deviceId: p.deviceId, deviceName: p.deviceName, platform: p.platform }))); + try { + const host = await startBaselineHost({ wsUrl: relay.wsUrl, deviceId: HOST_ID, credential: relay.credentials.get(HOST_ID)!, meter, fixture }); + try { + await expect.poll(() => host.client.getStatus(), { timeout: 15_000, interval: 20 }).toBe('online'); + await run({ host, meter, wsUrl: relay.wsUrl, credentials: relay.credentials, dropTransfer: switches.dropTransfer }); + } finally { + await host.close(); + } + } finally { + await relay.close(); + } + pending.push(JSON.stringify({ marker: 'run-end', run: name })); + await flush(); + wire.push({ run: name, ...meter.finish() }); + currentMeter = null; + } + let commit: string | null = null; + try { commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(); } catch { /* not a checkout */ } + await writeFile(path.join(outDir, 'product-wire.json'), `${JSON.stringify({ commit, profile: profile.id, runs: wire })}\n`); +}); diff --git a/scripts/o2-capture/realFixture.ts b/scripts/o2-capture/realFixture.ts new file mode 100644 index 0000000..42f5f86 --- /dev/null +++ b/scripts/o2-capture/realFixture.ts @@ -0,0 +1,135 @@ +/** + * Drop-in replacement for transfer-baseline/fixture.ts that serves REAL, de-identified task + * content (built by build-real-fixture.mjs, path in O2_REAL_FIXTURE). + * + * Exports the names scenarios.ts imports, with the same signatures and length semantics, so + * the product scenario (request cadence, controller code, recovery core) runs unchanged: + * - buildFixture(): the real sessions and their real message rows. The busiest Claude Code + * task becomes the long task (fixtureId('tblong', 1)); the others become sidebar tasks + * (fixtureId('tbside', i)). Timestamps are shifted to the fixture epoch, keeping each + * task's real spacing. + * - zhProse / codeText: real prose / real tool output, cut to the requested length. + * - turnTools: real tool calls with their real full results. + * Copied next to scenarios.ts only for the capture run; never committed to the product repo. + */ +import { readFileSync } from 'node:fs'; +import { capToolResultTextForPersist } from '../../shared/toolResultPersistCap'; + +export const FIXTURE_EPOCH = Date.UTC(2026, 9, 1, 8, 0, 0); + +export function createRandom(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export function fixtureId(prefix: string, n: number): string { + return `${prefix}${String(n).padStart(25 - prefix.length, '0')}`; +} + +interface RealRow { id: string; clientId: string; role: string; content: unknown; toolUseId: string | null; agentMeta?: Record; createdAt: number } +interface RealSession { source: string; title: string; preview: string; previewRole: string; agentKind: string; columns: Record; rows: RealRow[] } +interface RealTool { toolName: string; input: Record; result: string } +interface RealFixtureFile { suite: string; sessions: RealSession[]; pools: { prose: string[]; tools: RealTool[]; outputs: string[] } } + +const fixturePath = process.env.O2_REAL_FIXTURE; +if (!fixturePath) throw new Error('O2_REAL_FIXTURE must point at a fixture built by build-real-fixture.mjs'); +const REAL: RealFixtureFile = JSON.parse(readFileSync(fixturePath, 'utf8')); + +const pick = (random: () => number, items: readonly T[]): T => items[Math.floor(random() * items.length)]; + +function cut(text: string, length: number): string { + let out = text.slice(0, length); + const last = out.charCodeAt(out.length - 1); + if (last >= 0xd800 && last <= 0xdbff) out = out.slice(0, -1); + return out; +} + +/** Real text from `pool`, starting at a random offset, concatenated until `length` UTF-16 units. */ +function realText(random: () => number, pool: readonly string[], length: number, joiner: string): string { + let text = ''; + while (text.length < length) { + const source = pick(random, pool); + const start = source.length > 1 ? Math.floor(random() * Math.max(1, source.length - Math.min(source.length, length))) : 0; + text += (text ? joiner : '') + source.slice(start); + } + return cut(text, length); +} + +export function zhProse(random: () => number, chars: number): string { + return realText(random, REAL.pools.prose, chars, '\n\n'); +} + +export function codeText(random: () => number, bytes: number): string { + return realText(random, REAL.pools.outputs, bytes, '\n'); +} + +export interface FixtureMessageRow { + id: string; clientId: string; sessionId: string; role: string; content: unknown; + toolUseId: string | null; agentMeta?: Record; createdAt: number; +} +export interface FixtureSessionRow { + id: string; title: string; preview: string; messageCount: number; createdAt: number; updatedAt: number; + columns?: Record; tagIds?: string[]; +} +export interface FixtureTool { toolName: string; input: Record; result: string } +export interface TurnShape { + userChars: number; thinkingChars: number; tools: number; toolResultBytes: number; largeResultBytes: number; answerChars: number; +} + +export const LONG_TURN: TurnShape = { userChars: 160, thinkingChars: 600, tools: 5, toolResultBytes: 3 * 1024, largeResultBytes: 879 * 1024, answerChars: 900 }; +export const SHORT_TURN: TurnShape = { userChars: 80, thinkingChars: 200, tools: 2, toolResultBytes: 1024, largeResultBytes: 0, answerChars: 300 }; + +/** Real tool calls with their real full results; the large slot keeps the scenario's size. */ +export function turnTools(random: () => number, shape: TurnShape): FixtureTool[] { + const tools: FixtureTool[] = []; + for (let i = 0; i < shape.tools; i++) { + const tool = pick(random, REAL.pools.tools); + tools.push({ toolName: tool.toolName, input: structuredClone(tool.input), result: tool.result }); + } + if (shape.largeResultBytes > 0) { + const tool = pick(random, REAL.pools.tools); + tools.push({ toolName: tool.toolName, input: structuredClone(tool.input), result: codeText(random, shape.largeResultBytes) }); + } + return tools; +} + +export const LONG_SESSION_ID = fixtureId('tblong', 1); +export const SIDEBAR_SESSIONS = REAL.sessions.length; +export const LARGE_SIDEBAR_SESSIONS = REAL.sessions.length; +export const LONG_SESSION_TURNS = 1; +export const SHORT_SESSION_TURNS = 1; + +export interface SidebarFixture { sessions: FixtureSessionRow[]; messages: FixtureMessageRow[] } + +export function buildFixture(): SidebarFixture { + const ordered = [...REAL.sessions]; + const longIndex = ordered.reduce((best, s, i) => (s.agentKind === 'cc' && (best < 0 || s.rows.length > ordered[best].rows.length) ? i : best), -1); + if (longIndex < 0) throw new Error('real fixture has no Claude Code task for the long task'); + ordered.unshift(...ordered.splice(longIndex, 1)); + const sessions: FixtureSessionRow[] = []; + const messages: FixtureMessageRow[] = []; + ordered.forEach((real, index) => { + const id = index === 0 ? LONG_SESSION_ID : fixtureId('tbside', index); + const updatedAt = FIXTURE_EPOCH - index * 3_600_000; + const lastAt = Math.max(...real.rows.map((r) => r.createdAt)); + const firstAt = Math.min(...real.rows.map((r) => r.createdAt)); + const shift = updatedAt - 1_000 - lastAt; + for (const row of real.rows) { + const content = row.role === 'tool_result' && typeof row.content === 'string' ? capToolResultTextForPersist(row.content) : row.content; + messages.push({ id: row.id, clientId: row.clientId, sessionId: id, role: row.role, content, toolUseId: row.toolUseId, + ...(row.agentMeta ? { agentMeta: row.agentMeta } : {}), createdAt: row.createdAt + shift }); + } + sessions.push({ + id, title: real.title, preview: real.preview, messageCount: real.rows.length, + createdAt: firstAt + shift - 1_000, updatedAt, + columns: { ...real.columns, listPreviewRole: real.previewRole, lastActivityAt: updatedAt, lastTurnEndedAt: updatedAt - 1_000 }, + }); + }); + return { sessions, messages }; +} diff --git a/scripts/o2-capture/run-capture.sh b/scripts/o2-capture/run-capture.sh new file mode 100755 index 0000000..24672ef --- /dev/null +++ b/scripts/o2-capture/run-capture.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Run Cindy's transfer-baseline scenario on real de-identified task content and record the +# phone's RPC workload. The four helper files are copied into the Cindy checkout for the run +# and removed afterwards; tracked product files are never modified. +# +# Usage: scripts/o2-capture/run-capture.sh +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +cindy="$(cd "$1" && pwd)" +fixture="$(cd "$(dirname "$2")" && pwd)/$(basename "$2")" +out="$3" +mkdir -p "$out" +out="$(cd "$out" && pwd)" +desktop="$cindy/apps/desktop" +tb="$desktop/src/test/transfer-baseline" +added=("$tb/realFixture.ts" "$tb/realScenarios.ts" "$tb/realCapture.bench.ts" "$desktop/vitest.real-capture.config.ts") +for f in "${added[@]}"; do + if [ -e "$f" ]; then echo "refusing to overwrite $f" >&2; exit 1; fi +done +cleanup() { rm -f "${added[@]}"; } +trap cleanup EXIT +cp "$here/realFixture.ts" "$tb/realFixture.ts" +cp "$here/realCapture.bench.ts" "$tb/realCapture.bench.ts" +sed "s#from './fixture'#from './realFixture'#" "$tb/scenarios.ts" > "$tb/realScenarios.ts" +grep -q "from './realFixture'" "$tb/realScenarios.ts" +cat > "$desktop/vitest.real-capture.config.ts" <<'EOF' +import base from './vitest.transfer-baseline.config'; +export default { ...base, test: { ...base.test, include: ['src/test/transfer-baseline/realCapture.bench.ts'] } }; +EOF +cd "$desktop" +O2_REAL_FIXTURE="$fixture" O2_CAPTURE_OUT="$out" TRANSFER_BASELINE_PROFILE="${TRANSFER_BASELINE_PROFILE:-phone}" \ + pnpm exec vitest run --config vitest.real-capture.config.ts +git -C "$cindy" rev-parse HEAD > "$out/cindy-commit.txt" diff --git a/scripts/pack-cshare-corpus.mjs b/scripts/pack-cshare-corpus.mjs new file mode 100644 index 0000000..7b5a82d --- /dev/null +++ b/scripts/pack-cshare-corpus.mjs @@ -0,0 +1,52 @@ +#!/usr/bin/env node +/** + * Pack scrubbed real .cshare bundles (output of scrub-real-cshare-corpus.py) into one + * brotli-compressed corpus file for the opt-cshare-compression question. + * + * Usage: + * node scripts/pack-cshare-corpus.mjs + * + * Corpus format (after brotli decompression): UTF-8 JSON + * { suite, bundles: [{ name, agentKind, model, entries: [{ path, text }] }] } + * Every entry is UTF-8 text; the loader turns `text` back into bytes. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import crypto from 'node:crypto'; + +const [dir, indexPath, suite, out] = process.argv.slice(2); +if (!out) throw new Error('usage: pack-cshare-corpus.mjs '); + +const index = new Map(JSON.parse(fs.readFileSync(indexPath, 'utf8')).map((x) => [x.label, x])); +const bundles = []; +for (const label of fs.readdirSync(dir).filter((d) => /^b\d+$/.test(d)).sort()) { + const meta = index.get(label); + const order = JSON.parse(fs.readFileSync(path.join(dir, label, 'order.json'), 'utf8')); + const entries = order.map((p) => { + const buf = fs.readFileSync(path.join(dir, label, 'files', p)); + const text = buf.toString('utf8'); + if (!Buffer.from(text, 'utf8').equals(buf)) throw new Error(`${label}/${p} is not valid UTF-8`); + return { path: p, text }; + }); + // The name comes from the scrubbed session title (never the raw index); the raw index only + // supplies the engine kind and model id, which must be plain identifiers. + const scrubbedTitle = JSON.parse(fs.readFileSync(path.join(dir, label, 'files', 'session.json'), 'utf8')).title ?? ''; + const tail = String(scrubbedTitle).split('·').pop().trim() || label; + for (const [field, value] of [['agentKind', meta.agentKind], ['model', meta.model], ['name', tail]]) { + if (!/^[A-Za-z0-9._-]{1,64}$/.test(value ?? '')) throw new Error(`${label}: ${field} is not a plain identifier`); + } + bundles.push({ name: `${tail}-${meta.agentKind}`, agentKind: meta.agentKind, model: meta.model, entries }); +} +const json = Buffer.from(JSON.stringify({ suite, bundles }), 'utf8'); +const packed = zlib.brotliCompressSync(json, { + params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_LGWIN]: 24 }, +}); +fs.mkdirSync(path.dirname(out), { recursive: true }); +fs.writeFileSync(out, packed); +const raw = bundles.reduce((s, b) => s + b.entries.reduce((t, e) => t + Buffer.byteLength(e.text), 0), 0); +console.log(JSON.stringify({ + suite, bundles: bundles.length, rawBytes: raw, fileBytes: packed.length, + sha256: crypto.createHash('sha256').update(packed).digest('hex'), + names: bundles.map((b) => b.name), +})); diff --git a/scripts/scrub-real-cshare-corpus.py b/scripts/scrub-real-cshare-corpus.py new file mode 100644 index 0000000..acb4a22 --- /dev/null +++ b/scripts/scrub-real-cshare-corpus.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +"""De-identify bundles produced by build-real-cshare-corpus.py before they can be published. + +Policy (see docs of the opt-cshare-compression question): + +1. Harness-injected instruction text is replaced line by line with surrogate text of the same + shape (every line of a confirmed prompt field, short ones included; elsewhere only lines of at + least 16 characters that also occur in a prompt field). This covers system / developer prompts, tool and skill listings, injected session + context and environment reminders, for every engine. These blocks carry the owner's private + context (memory index, installed plugins, e-mail) and third-party prompt text that is not ours + to publish. A surrogate line keeps the original's length, whitespace, punctuation and script + (ASCII words stay ASCII words of the same length, CJK stays CJK, digits stay digits) and is + seeded by a keyed hash of the whole line, so identical lines stay identical everywhere (the + redundancy a compressor can exploit is preserved) while nothing of the content is recoverable. +2. Model output, tool calls and results, and the task prompts are kept verbatim, except that + local paths, the OS user name, e-mail addresses and account identifiers are rewritten to + neutral values of the same shape. +3. A deny-list scan runs at the end; any remaining hit fails the run. + +The key file must stay private (outside the repository). The surrogate vocabulary comes from +public Cindy documentation so surrogate text has realistic word and character statistics. + +Usage: + python3 -B scripts/scrub-real-cshare-corpus.py --key-file \ + --vocab-repo [--vocab-ref origin/main] --deny-file +""" + +import argparse +import collections +import hashlib +import hmac +import io +import json +import os +import random +import re +import subprocess +import sys +import tarfile + +MIN_LINE = 16 + +CLAUDE_HARNESS_ATTACHMENTS = { + "prompt_snapshot", "skill_listing", "deferred_tools_delta", "agent_listing_delta", + "session_context", "environment", "model", "auto_mode", "silent_turn_reminder", + "total_tokens_reminder", "task_reminder", "credential_org", "date", "thinking_drop", +} + +ASCII_WORD = re.compile(r"[A-Za-z]+") +TOKEN = re.compile(r"[A-Za-z]+|[0-9]+|[㐀-鿿豈-﫿]|.", re.S) + + +# --------------------------------------------------------------------------- vocabulary + +def load_vocab(repo, ref, deny=()): + """Word-length buckets and CJK characters with frequencies from public Cindy docs. + + Words matching the deny list are dropped so the final deny scan only reports real leaks.""" + data = subprocess.run(["git", "-C", repo, "archive", ref, "docs"], check=True, capture_output=True).stdout + words = collections.Counter() + cjk = collections.Counter() + with tarfile.open(fileobj=io.BytesIO(data)) as tar: + for m in tar.getmembers(): + if not m.isfile() or not m.name.endswith(".md"): + continue + text = tar.extractfile(m).read().decode("utf-8", "replace") + for w in ASCII_WORD.findall(text): + w = w.lower() + if not any(rx.search(w) for rx in deny): + words[w] += 1 + for ch in text: + if "一" <= ch <= "鿿": + cjk[ch] += 1 + by_len = collections.defaultdict(list) + for w, c in words.items(): + if 1 <= len(w) <= 24: + by_len[len(w)].append((w, c)) + buckets = {} + for n, items in by_len.items(): + items.sort(key=lambda x: (-x[1], x[0])) + items = items[:400] + buckets[n] = ([w for w, _ in items], list(_cum([c for _, c in items]))) + chars = sorted(cjk.items(), key=lambda x: (-x[1], x[0]))[:1500] + return buckets, ([c for c, _ in chars], list(_cum([n for _, n in chars]))) + + +def _cum(xs): + s = 0 + for x in xs: + s += x + yield s + + +def _pick(rng, table): + items, cum = table + r = rng.random() * cum[-1] + lo, hi = 0, len(cum) - 1 + while lo < hi: + mid = (lo + hi) // 2 + if cum[mid] < r: + lo = mid + 1 + else: + hi = mid + return items[lo] + + +class Surrogate: + def __init__(self, key, vocab): + self.key = key + self.words, self.cjk = vocab + self.cache = {} + + def word(self, rng, n): + if n in self.words: + return _pick(rng, self.words[n]) + # Longer than any vocabulary word: concatenate shorter words (lengths 1..8 always exist). + out = "" + while len(out) < n: + out += _pick(rng, self.words[min(8, n - len(out))]) + return out + + def line(self, text): + got = self.cache.get(text) + if got is not None: + return got + rng = random.Random(hmac.new(self.key, text.encode("utf-8"), hashlib.sha256).digest()) + out = [] + for tok in TOKEN.findall(text): + c = tok[0] + if c.isascii() and c.isalpha(): + w = self.word(rng, len(tok)) + if tok.isupper() and len(tok) > 1: + w = w.upper() + elif c.isupper(): + w = w[0].upper() + w[1:] + out.append(w) + elif c.isdigit(): + out.append("".join(str(rng.randrange(10)) for _ in tok)) + elif "㐀" <= c <= "鿿" or "豈" <= c <= "﫿": + out.append(_pick(rng, self.cjk)) + elif c.isalpha(): + # Other scripts (kana, hangul, accented letters): neutral ASCII letter. + out.append(rng.choice("etaoinshr")) + else: + out.append(tok) + got = "".join(out) + self.cache[text] = got + return got + + +# --------------------------------------------------------------------------- harness lines + +def strings(x, keys=None): + if isinstance(x, dict): + for k, v in x.items(): + if keys is None or k in keys or isinstance(v, (dict, list)): + yield from strings(v, keys) + elif isinstance(x, list): + for v in x: + yield from strings(v, keys) + elif isinstance(x, str): + yield x + + +def harness_strings(engine, rec): + if engine == "claude": + t = rec.get("type") + if t == "attachment" and rec.get("attachment", {}).get("type") in CLAUDE_HARNESS_ATTACHMENTS: + yield from strings(rec.get("attachment")) + yield from strings(rec.get("rendered")) + elif t == "api-request-shape": + yield from strings(rec.get("shape", {}).get("system"), {"text"}) + yield from strings(rec.get("shape", {}).get("tools"), {"description"}) + elif engine == "codex": + t = rec.get("type") + p = rec.get("payload") or {} + if t == "session_meta": + yield from strings(p.get("base_instructions")) + yield from strings(p.get("dynamic_tools"), {"description"}) + elif t == "response_item" and p.get("type") == "message" and p.get("role") == "developer": + yield from strings(p.get("content"), {"text"}) + elif t == "response_item" and p.get("type") == "additional_tools": + yield from strings(p.get("tools"), {"description"}) + elif t == "world_state": + yield from strings(p.get("state"), {"body", "description", "text", "content"}) + elif t == "turn_context": + yield from strings(p, {"developer_instructions", "user_instructions", "base_instructions"}) + + +def collect_harness_lines(raw, only): + """Lines (>= MIN_LINE) to replace wherever they appear, and the whole harness strings. + + A whole harness string that is multi-line or at least MIN_LINE long is replaced line by line + including its short lines (headings, ids, versions); short lines elsewhere stay untouched so + ordinary text such as `}` or `high` is not rewritten across the corpus.""" + lines = set() + blocks = set() + for b in sorted(os.listdir(raw)): + if only and b not in only: + continue + tdir = os.path.join(raw, b, "files", "transcripts") + if not os.path.isdir(tdir): + continue + for engine in os.listdir(tdir): + for fn in os.listdir(os.path.join(tdir, engine)): + with open(os.path.join(tdir, engine, fn), encoding="utf-8") as f: + for l in f: + if not l.strip(): + continue + for s in harness_strings(engine, json.loads(l)): + if "\n" in s or len(s) >= MIN_LINE: + blocks.add(s) + for line in s.split("\n"): + if len(line) >= MIN_LINE: + lines.add(line) + return lines, blocks + + +def replace_lines(s, harness, sur, stats): + lines, blocks = harness + whole = s in blocks + parts = s.split("\n") + changed = False + for i, line in enumerate(parts): + if (whole and line.strip()) or (len(line) >= MIN_LINE and line in lines): + parts[i] = sur.line(line) + changed = True + stats["harness_lines"] += 1 + if not changed: + return s + return "\n".join(parts) + + +def scrub_value(x, harness, sur, stats): + if isinstance(x, dict): + return {k: scrub_value(v, harness, sur, stats) for k, v in x.items()} + if isinstance(x, list): + return [scrub_value(v, harness, sur, stats) for v in x] + if isinstance(x, str): + st = x.lstrip() + if st[:1] in ("{", "[") and len(x) > 2: + try: + inner = json.loads(x) + except ValueError: + inner = None + if isinstance(inner, (dict, list)) and json.dumps(inner, ensure_ascii=False, separators=(",", ":")) == x: + return json.dumps(scrub_value(inner, harness, sur, stats), ensure_ascii=False, separators=(",", ":")) + return replace_lines(x, harness, sur, stats) + return x + + +# --------------------------------------------------------------------------- identifiers + +class Pseudonyms: + def __init__(self, key): + self.key = key + self.map = {} + + def same_shape(self, value, alphabet): + got = self.map.get(value) + if got: + return got + rng = random.Random(hmac.new(self.key, b"id:" + value.encode(), hashlib.sha256).digest()) + out = [] + for ch in value: + if ch in "-_./:@": + out.append(ch) + elif ch.isdigit() and alphabet == "hex": + out.append(rng.choice("0123456789abcdef")) + elif alphabet == "hex": + out.append(rng.choice("0123456789abcdef") if ch in "abcdef" else ch) + else: + out.append(rng.choice("abcdefghijklmnopqrstuvwxyz0123456789") if ch.islower() or ch.isdigit() + else rng.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") if ch.isupper() else ch) + got = "".join(out) + self.map[value] = got + return got + + +ID_FIELDS = {"accountUuid", "organizationUuid", "creator_account_id", "creator_user_id"} +EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}") +SAFE_EMAIL_DOMAINS = re.compile(r"(?i)(^|\.)(example\.(com|org|net)|a\.com|b\.com|test|localhost|invalid)$") + + +def collect_ids(raw): + # Identifiers are collected from every bundle so a subset run still knows them all. + ids = set() + for dp, _, fns in os.walk(raw): + for fn in fns: + if not fn.endswith((".jsonl", ".json")): + continue + with open(os.path.join(dp, fn), encoding="utf-8") as f: + for l in f if fn.endswith(".jsonl") else [f.read()]: + if not l.strip(): + continue + try: + rec = json.loads(l) + except ValueError: + continue + stack = [rec] + while stack: + x = stack.pop() + if isinstance(x, dict): + for k, v in x.items(): + if k in ID_FIELDS and isinstance(v, str) and v: + ids.add(v) + stack.append(v) + elif isinstance(x, list): + stack.extend(x) + return ids + + +def byte_rules(ids, pseudo): + rules = [] + for v in sorted(ids, key=len, reverse=True): + rules.append((re.compile(re.escape(v)), lambda m: pseudo.same_shape(m.group(0), "alnum"))) + # macOS per-user temp root, in path form and in Claude's dash-encoded project dir form. + rules.append((re.compile(r"(var[-/]folders[-/])([a-z0-9_]{2})([-/])([a-z0-9_]{24,40})"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "alnum") + m.group(3) + pseudo.same_shape(m.group(4), "alnum"))) + # Same temp root when a preview cut the path before "var/folders". + rules.append((re.compile(r"([-/])([a-z0-9_]{2})([-/])([a-z0-9_]{28,32})(?=[-/]T[-/])"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "alnum") + m.group(3) + pseudo.same_shape(m.group(4), "alnum"))) + # Cindy per-owner data directory. + rules.append((re.compile(r"(owners[/\\-]+)([0-9a-f]{16,64})"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "hex"))) + # Per-account engine homes (owner hash, account uuid, provider hash). + rules.append((re.compile(r"((?:claude-)?cindy-)([0-9a-f]{12})(-)([0-9a-f-]{36})"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "hex") + m.group(3) + pseudo.same_shape(m.group(4), "hex"))) + rules.append((re.compile(r"(codex-accounts[/\\-]+)([0-9a-f]{64})"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "hex"))) + rules.append((re.compile(r"\b((?:openai|anthropic|claude|codex)-)([0-9a-f]{8})\b"), + lambda m: m.group(1) + pseudo.same_shape(m.group(2), "hex"))) + return rules + + +def apply_text_rules(text, rules, user, stats): + for rx, fn in rules: + text, n = rx.subn(fn, text) + stats["ids"] += n + # Home directory and the OS user name (same length replacement keeps shapes stable). + repl = "u" * len(user) if len(user) != 4 else "user" + text, n1 = re.subn(rf"(/Users/|-Users-|/home/){re.escape(user)}(?=[/\\\"'\s-]|$)", rf"\g<1>{repl}", text) + text, n2 = re.subn(rf"(?<=\s){re.escape(user)}(?=\s+(staff|wheel|admin)\b)", repl, text) + stats["paths"] += n1 + n2 + + # The owner's time zone is location data; neutralize it. + text, n3 = re.subn(r'("timezone":"|)[A-Za-z_]+/[A-Za-z_/+-]+', r"\g<1>Etc/UTC", text) + stats["timezones"] += n3 + + def email(m): + addr = m.group(0) + dom = addr.rsplit("@", 1)[1] + if SAFE_EMAIL_DOMAINS.search(dom): + return addr + stats["emails"] += 1 + return "user@example.com" + + return EMAIL.sub(email, text) + + +# --------------------------------------------------------------------------- main + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("raw") + ap.add_argument("out") + ap.add_argument("--key-file", required=True) + ap.add_argument("--vocab-repo", required=True) + ap.add_argument("--vocab-ref", default="origin/main") + ap.add_argument("--deny-file", required=True, help="one regex per line; private, not committed") + ap.add_argument("--os-user", default=os.environ.get("USER", "")) + ap.add_argument("--bundles", default="", help="comma-separated bundle labels (default: all)") + args = ap.parse_args() + only = set(filter(None, args.bundles.split(","))) + + with open(args.key_file, "rb") as f: + key = f.read().strip() + if len(key) < 32: + raise SystemExit("key file must hold at least 32 bytes") + with open(args.deny_file, encoding="utf-8") as f: + deny = [re.compile(l.rstrip("\n")) for l in f if l.strip() and not l.startswith("#")] + + sur = Surrogate(key, load_vocab(args.vocab_repo, args.vocab_ref, deny)) + harness = collect_harness_lines(args.raw, only) + pseudo = Pseudonyms(key) + rules = byte_rules(collect_ids(args.raw), pseudo) + stats = collections.Counter() + stats["harness_distinct_lines"] = len(harness[0]) + stats["harness_blocks"] = len(harness[1]) + + for b in sorted(os.listdir(args.raw)): + src = os.path.join(args.raw, b) + if not os.path.isdir(src) or (only and b not in only): + continue + with open(os.path.join(src, "order.json")) as f: + order = json.load(f) + files = {} + for rel in order: + with open(os.path.join(src, "files", rel), "rb") as f: + data = f.read() + if rel == "manifest.json": + files[rel] = data + continue + text = data.decode("utf-8") + if rel.endswith(".jsonl"): + out = [] + for l in text.split("\n"): + if l.strip(): + rec = json.loads(l) + new = scrub_value(rec, harness, sur, stats) + if new != rec: + l = json.dumps(new, ensure_ascii=False, separators=(",", ":")) + out.append(l) + text = "\n".join(out) + elif rel.endswith(".json"): + rec = json.loads(text) + new = scrub_value(rec, harness, sur, stats) + if new != rec: + text = json.dumps(new, ensure_ascii=False, indent=2) + files[rel] = apply_text_rules(text, rules, args.os_user, stats).encode("utf-8") + + manifest = json.loads(apply_text_rules(files["manifest.json"].decode("utf-8"), rules, args.os_user, stats)) + manifest["entries"] = [ + {"path": rel, "bytes": len(files[rel]), "sha256": hashlib.sha256(files[rel]).hexdigest()} + for rel in order if rel != "manifest.json" + ] + files["manifest.json"] = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8") + + dst = os.path.join(args.out, b) + for rel in order: + fp = os.path.join(dst, "files", rel) + os.makedirs(os.path.dirname(fp), exist_ok=True) + with open(fp, "wb") as f: + f.write(files[rel]) + with open(os.path.join(dst, "order.json"), "w") as f: + json.dump(order, f, indent=1) + + # Deny-list gate over everything written. + hits = collections.Counter() + for dp, _, fns in os.walk(args.out): + for fn in fns: + with open(os.path.join(dp, fn), encoding="utf-8", errors="replace") as f: + text = f.read() + for rx in deny: + n = len(rx.findall(text)) + if n: + hits[rx.pattern] += n + report = {"stats": dict(stats), "denyHits": dict(hits)} + print(json.dumps(report, ensure_ascii=False, indent=1)) + return 1 if hits else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify-v2-suite.mjs b/scripts/verify-v2-suite.mjs new file mode 100644 index 0000000..699df9f --- /dev/null +++ b/scripts/verify-v2-suite.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; + +const require = createRequire(import.meta.url); +const [suiteFile, enginePath] = process.argv.slice(2); +if (!suiteFile || !enginePath) { + console.error('Usage: node scripts/verify-v2-suite.mjs '); + process.exit(2); +} + +const { dispatch } = require(path.resolve(enginePath)); +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const suite = JSON.parse(await fs.readFile(suiteFile, 'utf8')); +const summary = []; + +for (const q of suite.questions) { + const qDir = path.join(repoRoot, 'questions', q.id, q.revision); + const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), `eval-v2-verify-${q.id}-`)); + try { + const draft = await dispatch('draft', { + root: tmpRoot, + id: q.id, + revision: q.revision, + records: [{ sessionId: `suite-${suite.id}`, text: `Verification run for ${q.id}@${q.revision}` }], + }); + for (const part of ['question.json', 'candidate', 'reference', 'controls', 'author']) { + await fs.cp(path.join(qDir, part), path.join(draft.directory, part), { recursive: true }); + } + const cal = await dispatch('calibrate', { root: tmpRoot, id: q.id, revision: q.revision }); + assert.equal(cal.ok, true, `Calibration failed for ${q.id}@${q.revision}: ${JSON.stringify(cal)}`); + + // Verify freeze + prepare + grade on reference and tamper rejection on protected TASK.md. + const frozen = await dispatch('freeze', { root: tmpRoot, checkId: cal.checkId }); + assert.equal(frozen.key, `custom:${q.id}@${q.revision}`); + + const prepTamper = await dispatch('prepare', { + root: tmpRoot, + question: frozen.key, + model: 'tamper-check', + harness: 'codex', + effort: 'high', + provider: 'verify', + }); + await fs.appendFile(path.join(prepTamper.workspace, 'TASK.md'), '\n\n'); + const gradedTamper = await dispatch('grade', { + root: tmpRoot, + runId: prepTamper.runId, + receipt: { channel: 'Orca Worker', sessionId: 's-tamper', workerId: 'w-tamper', completedAt: 2000, startedAt: 1000, acceptedAt: 500 }, + }); + assert.equal(gradedTamper.status, 'environment_invalid', `Submission gate failed to reject TASK.md tamper for ${q.id}@${q.revision}`); + + summary.push({ + key: `${q.id}@${q.revision}`, + ok: cal.ok, + candidate: cal.results[0].scoreExact, + reference: cal.results[1].scoreExact, + incomplete: cal.results[2].scoreExact, + referenceMetrics: cal.results[1].metrics || null, + tamperRejected: true, + }); + } finally { + await fs.rm(tmpRoot, { recursive: true, force: true }); + } +} + +console.log(JSON.stringify({ suite: suite.id, verified: summary.length, results: summary }, null, 2)); diff --git a/suites/cindy-eval-opt-v1-20261205.json b/suites/cindy-eval-opt-v1-20261205.json new file mode 100644 index 0000000..2880f57 --- /dev/null +++ b/suites/cindy-eval-opt-v1-20261205.json @@ -0,0 +1,40 @@ +{ + "id": "cindy-eval-opt-v1-20261205", + "rule": "equal-question-mean-v1", + "platform": "any", + "description": "Cindy Eval Bank Open-Ended High-Ceiling Optimization Suite v1: 4 ultra-deterministic, hardware-independent, Oracle-anchored continuous optimization tasks extracted from open-source makecindy/cindy (Apache-2.0): lossless .cshare archive compression, cross-device RPC delta sync, shared-relay weak-network congestion scheduling, and 14-day multi-account quota + prompt-cache cost routing. Pure Node.js ESM (official grading needs Node.js >= 20), zero external npm dependencies.", + "questions": [ + { + "id": "opt-cshare-compression", + "revision": "v1", + "kind": "metric", + "sourceModule": "apps/desktop/src/main/session-share/{sessionShareExport,xdtshareFormat.pure}.ts", + "sourceCommit": "b61c43049a9c2977e2bc64f2a4a12d6d344924bd", + "manifestSha256": "783f68f40c8abdacbea2d5d4f1bab98884b084bd38bd875a9de9a4e2c9e2a0cc" + }, + { + "id": "opt-device-link-delta-sync", + "revision": "v1", + "kind": "metric", + "sourceModule": "packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "f20c14db44b78d736097ee71785ffed52e2398072524ae12f81907e32895232a" + }, + { + "id": "opt-relay-congestion-scheduler", + "revision": "v1", + "kind": "metric", + "sourceModule": "packages/device-link/src/{congestionSendBudget,invokeScheduler,transport}.ts + packages/agent-net-core/sim/src/lib.rs", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "fcc7b19ab5554f203ad0e1d017bafd8f490ae8363cb1144ac90bc57fab0448b0" + }, + { + "id": "opt-routing-cost-sim", + "revision": "v1", + "kind": "metric", + "sourceModule": "apps/desktop/src/main/model-groups/{pick,turnRouting}.ts + provider-group/scheduler.ts + agentcompass/engine/quota-economy.mjs", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "b6e52bda733444a14edc85a826cb5d8f441864512b95aaf5040679c92c3739db" + } + ] +} diff --git a/suites/cindy-eval-opt-v2-20261206.json b/suites/cindy-eval-opt-v2-20261206.json new file mode 100644 index 0000000..0ddd3b1 --- /dev/null +++ b/suites/cindy-eval-opt-v2-20261206.json @@ -0,0 +1,32 @@ +{ + "id": "cindy-eval-opt-v2-20261206", + "rule": "equal-question-mean-v1", + "platform": "any", + "description": "Cindy Eval Bank open-ended optimization suite v2: 3 continuous-metric tasks from open-source makecindy/cindy (Apache-2.0) driven by real workloads instead of synthetic generators — lossless .cshare compression on real de-identified task exports, cross-device RPC delta sync on recorded real phone sessions, and shared-relay weak-network scheduling on relay links measured from Cindy Desktop diagnostics. Targets are measured physical/information floors, so stronger results keep scoring higher. opt-routing-cost-sim is shelved (see its v2/README.md). Pure Node.js ESM (official grading needs Node.js >= 20), zero external npm dependencies.", + "questions": [ + { + "id": "opt-cshare-compression", + "revision": "v2", + "kind": "metric", + "sourceModule": "apps/desktop/src/main/session-share/{sessionShareExport,xdtshareFormat.pure}.ts", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "14fc19321b3ddfa13924e24ad5ac89915d97d41374617047a80d11a8372811f7" + }, + { + "id": "opt-device-link-delta-sync", + "revision": "v2", + "kind": "metric", + "sourceModule": "packages/device-link/src/{invokeDelta,invokeTransfer,historyViewDelta,sessionMessageReuse}.ts", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "6cad8a1452dc8887c7de2f569a856a688f03f4a7f9ce8f5976a026eba65971ad" + }, + { + "id": "opt-relay-congestion-scheduler", + "revision": "v2", + "kind": "metric", + "sourceModule": "packages/device-link/src/{congestionSendBudget,invokeScheduler,transport}.ts + packages/agent-net-core/sim/src/lib.rs", + "sourceCommit": "28492cd2439300c7e461c742091cbd85f4d157e7", + "manifestSha256": "41c9d500e814b42717c6aa9eaf56e1d008fa352e85933d4f0ca962f9750c6d9a" + } + ] +} diff --git a/suites/cindy-eval-v2-20261205.json b/suites/cindy-eval-v2-20261205.json new file mode 100644 index 0000000..d185bce --- /dev/null +++ b/suites/cindy-eval-v2-20261205.json @@ -0,0 +1,64 @@ +{ + "id": "cindy-eval-v2-20261205", + "rule": "equal-question-mean-v1", + "platform": "any", + "description": "Cindy Eval Bank v2: 4 quantitative continuous-metric optimization tasks (memory, framing/parsing speedup, API quota budget) + 3 real protocol/routing root-cause tasks extracted from open-source makecindy/cindy (Apache-2.0). Pure Node.js >= 18 ESM, zero external npm dependencies.", + "questions": [ + { + "id": "perf-jsonl-hotpaths", + "revision": "v1", + "kind": "metric", + "sourcePr": "#15565", + "sourceCommit": "04b6fd217d88f8f613402555e1336a14036d30de", + "manifestSha256": "a7dc5431240be54299765f3c13442e33dd436e30b2e7fdd3be8de2d6cd585806" + }, + { + "id": "perf-mobile-home-heat", + "revision": "v1", + "kind": "metric", + "sourcePr": "#15544", + "sourceCommit": "3a8ae6d6cdf55432f6f99852075a99af19abcfd6", + "manifestSha256": "996df5e398158bed768b020fd53559a15fc5b7c79b582f954cf39816d1949a77" + }, + { + "id": "perf-mcp-hosttools-churn", + "revision": "v1", + "kind": "metric", + "sourcePr": "#15602", + "sourceCommit": "ca8c88794cdbdfaad6950b7f1160bb1b271f2ba4", + "manifestSha256": "567212bac414be4cbd8b49183426cee3e877b5416abaf94b62e99e93b4d9030d" + }, + { + "id": "perf-github-api-budget", + "revision": "v1", + "kind": "metric", + "sourcePr": "#14157", + "sourceCommit": "325a0d39ff60", + "manifestSha256": "c9ab6be3153ba01103c4a6c0cf087f3a3e97bc36f7241e35ac9b4895bda1fa34" + }, + { + "id": "mcp-apps-exact-origin", + "revision": "v1", + "kind": "root-cause", + "sourcePr": "#15220", + "sourceCommit": "5b6d74c1", + "manifestSha256": "2eccdf908066e0427482342548c426fbfa09a665c3d3f1b68b95b0d1522fda3f" + }, + { + "id": "codex-namespace-tool-collision", + "revision": "v1", + "kind": "root-cause", + "sourcePr": "#14563", + "sourceCommit": "793ac48b", + "manifestSha256": "52e9e19c635069c44beb99284bb0ebc81227f42aeede2e7cb794293a24ddb0e7" + }, + { + "id": "smart-routing-three-tiers", + "revision": "v1", + "kind": "root-cause", + "sourcePr": "#15050", + "sourceCommit": "f79d9173", + "manifestSha256": "d9ca501c15619cea79ad6546b3b814268fecc51485a808a1444dd45224f215e5" + } + ] +} diff --git a/tests/test_scrub_harness_lines.py b/tests/test_scrub_harness_lines.py new file mode 100644 index 0000000..42b42ce --- /dev/null +++ b/tests/test_scrub_harness_lines.py @@ -0,0 +1,69 @@ +import collections +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / 'scripts/scrub-real-cshare-corpus.py' +spec = importlib.util.spec_from_file_location('scrub_real_cshare_corpus', SCRIPT) +scrub = importlib.util.module_from_spec(spec) +spec.loader.exec_module(scrub) + + +class TaggingSurrogate: + def line(self, text): + return f'<{len(text)}>' + + +SKILL_LISTING = '\n'.join([ + 'The following skills are available:', + '', + '- run', + '- dataviz: charts', + '# Memory', + '- prefers concise answers for status reports', +]) + + +class HarnessLineTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.raw = Path(temp.name) + tdir = self.raw / 'b001/files/transcripts/claude' + tdir.mkdir(parents=True) + records = [ + {'type': 'attachment', 'attachment': {'type': 'skill_listing', 'content': SKILL_LISTING}}, + {'type': 'api-request-shape', 'shape': { + 'system': [{'type': 'text', 'text': 'You are a coding agent working in a terminal.'}], + 'tools': [{'name': 'Bash', 'description': 'Run a shell command.', + 'input_schema': {'type': 'object', 'properties': {'effort': {'enum': ['low', 'high']}}}}], + }}, + ] + (tdir / 's.jsonl').write_text(''.join(json.dumps(r) + '\n' for r in records), encoding='utf-8') + self.harness = scrub.collect_harness_lines(str(self.raw), set()) + self.stats = collections.Counter() + + def replace(self, value): + return scrub.scrub_value(value, self.harness, TaggingSurrogate(), self.stats) + + def test_every_non_empty_line_of_an_injected_block_is_replaced(self): + out = self.replace({'content': SKILL_LISTING})['content'].split('\n') + self.assertEqual(out, ['<35>', '', '<5>', '<17>', '<8>', '<44>']) + + def test_long_harness_lines_are_replaced_wherever_they_appear(self): + text = 'Quoted back:\n- prefers concise answers for status reports\n- run' + out = self.replace(text).split('\n') + self.assertEqual(out, ['Quoted back:', '<44>', '- run']) + self.assertEqual(self.replace('You are a coding agent working in a terminal.'), '<45>') + + def test_short_standalone_values_keep_the_record_structure(self): + # Schema keywords, enum values and tool names are harness strings too, but rewriting + # every `object` or `high` in the corpus would corrupt ordinary records. + record = {'type': 'object', 'effort': 'high', 'tool': 'Bash', 'kind': 'skill_listing'} + self.assertEqual(self.replace(record), record) + + +if __name__ == '__main__': + unittest.main() diff --git a/versions.json b/versions.json index a0f5a58..9f8e4d8 100644 --- a/versions.json +++ b/versions.json @@ -124,5 +124,103 @@ "importOnly": false, "sourceManifestSha256": "b1ef9e738204c45f31bdebeb1918e3c429e38530d39019acc04476fb85f319e0", "publishedRuntime": true + }, + { + "id": "perf-jsonl-hotpaths", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "a7dc5431240be54299765f3c13442e33dd436e30b2e7fdd3be8de2d6cd585806", + "publishedRuntime": false + }, + { + "id": "perf-mobile-home-heat", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "996df5e398158bed768b020fd53559a15fc5b7c79b582f954cf39816d1949a77", + "publishedRuntime": false + }, + { + "id": "perf-mcp-hosttools-churn", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "567212bac414be4cbd8b49183426cee3e877b5416abaf94b62e99e93b4d9030d", + "publishedRuntime": false + }, + { + "id": "perf-github-api-budget", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "c9ab6be3153ba01103c4a6c0cf087f3a3e97bc36f7241e35ac9b4895bda1fa34", + "publishedRuntime": false + }, + { + "id": "mcp-apps-exact-origin", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "2eccdf908066e0427482342548c426fbfa09a665c3d3f1b68b95b0d1522fda3f", + "publishedRuntime": false + }, + { + "id": "codex-namespace-tool-collision", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "52e9e19c635069c44beb99284bb0ebc81227f42aeede2e7cb794293a24ddb0e7", + "publishedRuntime": false + }, + { + "id": "smart-routing-three-tiers", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "d9ca501c15619cea79ad6546b3b814268fecc51485a808a1444dd45224f215e5", + "publishedRuntime": false + }, + { + "id": "opt-cshare-compression", + "revision": "v2", + "importOnly": false, + "sourceManifestSha256": "14fc19321b3ddfa13924e24ad5ac89915d97d41374617047a80d11a8372811f7", + "publishedRuntime": false + }, + { + "id": "opt-device-link-delta-sync", + "revision": "v2", + "importOnly": false, + "sourceManifestSha256": "6cad8a1452dc8887c7de2f569a856a688f03f4a7f9ce8f5976a026eba65971ad", + "publishedRuntime": false + }, + { + "id": "opt-relay-congestion-scheduler", + "revision": "v2", + "importOnly": false, + "sourceManifestSha256": "41c9d500e814b42717c6aa9eaf56e1d008fa352e85933d4f0ca962f9750c6d9a", + "publishedRuntime": false + }, + { + "id": "opt-cshare-compression", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "783f68f40c8abdacbea2d5d4f1bab98884b084bd38bd875a9de9a4e2c9e2a0cc", + "publishedRuntime": false + }, + { + "id": "opt-device-link-delta-sync", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "f20c14db44b78d736097ee71785ffed52e2398072524ae12f81907e32895232a", + "publishedRuntime": false + }, + { + "id": "opt-relay-congestion-scheduler", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "fcc7b19ab5554f203ad0e1d017bafd8f490ae8363cb1144ac90bc57fab0448b0", + "publishedRuntime": false + }, + { + "id": "opt-routing-cost-sim", + "revision": "v1", + "importOnly": false, + "sourceManifestSha256": "b6e52bda733444a14edc85a826cb5d8f441864512b95aaf5040679c92c3739db", + "publishedRuntime": false } ]