refactor(orchestrator): return validated worker results (CL20)
This commit is contained in:
parent
6055aeeee9
commit
8a5d0c3ef2
8 changed files with 145 additions and 23 deletions
|
|
@ -22,6 +22,8 @@ import {
|
|||
parseRetainedStrategyResult,
|
||||
retainedStrategyRequestSchema,
|
||||
type NativeWorkerRequest,
|
||||
type RetainedStrategyRequest,
|
||||
type RetainedStrategyResult,
|
||||
} from './native-worker-protocol';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
||||
|
|
@ -36,6 +38,30 @@ export class NativeBacktestWorker {
|
|||
signal: AbortSignal,
|
||||
onProgress: (progress: { progress: number; message: string }) => void
|
||||
): Promise<string> {
|
||||
return (await this.executeWorker(request, signal, onProgress)).raw;
|
||||
}
|
||||
|
||||
/** Return the admitted envelope only after the child and its candidate have closed. */
|
||||
async executeRetained(
|
||||
request: RetainedStrategyRequest,
|
||||
signal: AbortSignal,
|
||||
onProgress: (progress: { progress: number; message: string }) => void
|
||||
): Promise<RetainedStrategyResult> {
|
||||
if (request.type !== 'runRetainedStrategy') {
|
||||
throw new Error('Typed retained execution requires a retained strategy request');
|
||||
}
|
||||
const result = await this.executeWorker(request, signal, onProgress);
|
||||
if (!result.retained) {
|
||||
throw new Error('Retained strategy worker completed without a validated envelope');
|
||||
}
|
||||
return result.retained;
|
||||
}
|
||||
|
||||
private async executeWorker(
|
||||
request: NativeWorkerRequest,
|
||||
signal: AbortSignal,
|
||||
onProgress: (progress: { progress: number; message: string }) => void
|
||||
): Promise<{ raw: string; retained?: RetainedStrategyResult }> {
|
||||
signal.throwIfAborted();
|
||||
request = nativeWorkerRequestSchema.parse(request);
|
||||
if (this.active) {
|
||||
|
|
@ -98,8 +124,9 @@ export class NativeBacktestWorker {
|
|||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
});
|
||||
this.active = child;
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
let result: string | undefined;
|
||||
let retained: RetainedStrategyResult | undefined;
|
||||
let failure: Error | undefined;
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
|
|
@ -131,7 +158,7 @@ export class NativeBacktestWorker {
|
|||
} else if (message.type === 'result') {
|
||||
if (retainedRequest) {
|
||||
try {
|
||||
parseRetainedStrategyResult(message.result, retainedRequest.request);
|
||||
retained = parseRetainedStrategyResult(message.result, retainedRequest.request);
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
|
|
@ -192,7 +219,7 @@ export class NativeBacktestWorker {
|
|||
)
|
||||
);
|
||||
} else {
|
||||
resolve(result);
|
||||
resolve({ raw: result, retained });
|
||||
}
|
||||
};
|
||||
child.on('message', onMessage);
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ import {
|
|||
type BacktestExecutionEngine,
|
||||
} from './execution-engine';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import { parseRetainedStrategyResult } from './native-worker-protocol';
|
||||
import { NativeBacktestWorker } from './NativeBacktestWorker';
|
||||
|
||||
export type BacktestResult = NativeBacktestResult;
|
||||
|
|
@ -65,7 +64,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
async (signal, aborted) => {
|
||||
const dataset = await Promise.race([resolveDataset(signal), aborted]);
|
||||
signal.throwIfAborted();
|
||||
const raw = await this.worker.execute(
|
||||
const result = await this.worker.executeRetained(
|
||||
{
|
||||
type: 'runRetainedStrategy',
|
||||
request,
|
||||
|
|
@ -80,7 +79,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
this.publish('progress', progress);
|
||||
}
|
||||
);
|
||||
const result = parseRetainedStrategyResult(raw, request);
|
||||
this.currentTime = dataset.manifest.bounds.tradeEnd;
|
||||
return { financial: result.financial, analytics: result.analytics };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,4 +94,5 @@ export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
|||
]);
|
||||
|
||||
export type NativeWorkerRequest = z.input<typeof nativeWorkerRequestSchema>;
|
||||
export type RetainedStrategyRequest = z.input<typeof retainedStrategyRequestSchema>;
|
||||
export type NativeWorkerMessage = z.infer<typeof nativeWorkerMessageSchema>;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Current follow-up: [orchestrator/engine cleanup](orchestrator-engine-cleanup.md), CL14–CL21. Planning and per-task implementation commits are authorized; CL21 is conditional. Historical milestones below remain evidence, not a new activation request.
|
||||
Current follow-up: [orchestrator/engine cleanup](orchestrator-engine-cleanup.md). All seven scheduled stories CL14–CL20 are complete and validated with per-task commits; CL21 remains conditional. Historical milestones below remain evidence, not a new activation request.
|
||||
|
||||
## Cleanup implementation — October 26, 2026
|
||||
|
||||
|
|
|
|||
|
|
@ -144,7 +144,7 @@ R06/R08/R09 and the R07 comparison/measurement are complete. The default support
|
|||
|
||||
## E11 — Orchestrator and engine cleanup
|
||||
|
||||
Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). First wave CL14/CL15/CL16 is completed and committed. CL17–CL19 are completed; CL20 is in progress; CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged.
|
||||
Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). All seven scheduled stories CL14–CL20 are complete. CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged.
|
||||
|
||||
| Task | Priority | Dependencies |
|
||||
| --- | --- | --- |
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-26.84",
|
||||
"plan_revision": "2026-10-26.85",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "orchestrator_engine_cleanup_remaining_wave",
|
||||
"plan_status": "orchestrator_engine_cleanup_scheduled_complete",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "Owner: commit and continue with the rest of the tasks till 100%",
|
||||
|
|
@ -2965,10 +2965,10 @@
|
|||
],
|
||||
"assignment": "/root/implement_cl19",
|
||||
"branch": "cleanup/cl19-strategy-bookkeeping",
|
||||
"completed_commit": null,
|
||||
"completed_commit": "6055aeee",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated_pending_commit",
|
||||
"integration_state": "validated_committed",
|
||||
"integration_base": "580a6de7",
|
||||
"completion_evidence": "orchestrator-engine-cleanup.md",
|
||||
"reviewer": "/root/review_cl19",
|
||||
|
|
@ -2976,7 +2976,8 @@
|
|||
"integration": "Root 60 passed, 6959 assertions; application types passed",
|
||||
"postgres": "Root 35 passed, 275 assertions: canonical paper, crash and strategy recovery",
|
||||
"review": "Independent reviewer accepted; canonicalJson bytes verified against baseline"
|
||||
}
|
||||
},
|
||||
"implementation_commit": "6055aeee"
|
||||
},
|
||||
{
|
||||
"id": "CL20",
|
||||
|
|
@ -2984,7 +2985,7 @@
|
|||
"epic": "E11",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "in_progress",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"CL14"
|
||||
],
|
||||
|
|
@ -3011,9 +3012,15 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "implementing",
|
||||
"integration_state": "validated_pending_commit",
|
||||
"integration_base": "580a6de7",
|
||||
"completion_evidence": "orchestrator-engine-cleanup.md"
|
||||
"completion_evidence": "orchestrator-engine-cleanup.md",
|
||||
"reviewer": "/root",
|
||||
"validation": {
|
||||
"integration": "Root 59 passed, 232 assertions; application and authored-test types/lint passed",
|
||||
"review": "Root independently accepted; result-after-close and unchanged candidate cleanup failure branch inspected",
|
||||
"combined": "All repository checks passed: tooling134,utils43,calculations44,integration1236,Rust150; 14 existing integration skips and 4 Rust ignored"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "CL21",
|
||||
|
|
|
|||
|
|
@ -75,3 +75,18 @@ CL17 implementation commit: `984dc1a9`.
|
|||
Research and paper share pure diagnostic initialization and owner-feedback projection, keeping their separate confirmation/SQL commit boundaries. Feed planning and paper admission share the existing timestamp/phase/UTF-8/source comparator. `canonicalJson` moved unchanged to a neutral module with its legacy re-export; canonical consumers no longer depend on legacy recovery.
|
||||
|
||||
Implemented by `/root/implement_cl19`, independently accepted by `/root/review_cl19`, integrated by `/root`. Root runtime/feed/recovery/architecture suite: 60 passed, 6,959 assertions; application types passed. Root disposable canonical-paper, crash and strategy-recovery suite: 35 passed, 275 assertions. Root also compared the entire canonicalJson function/comment against baseline bytes. Tests cover research/paper state/RNG/feedback parity and detached initial state, malformed-owner atomicity, native-accepted Unicode ordering and historical serialization. Explicit authored-test types/lint/format passed. Worktree Bun browser-bundle errors cleared on separate architecture rerun; root combined focused invocation passed. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl19-root-{tests,types,postgres}.log`.
|
||||
|
||||
|
||||
CL19 implementation commit: `6055aeee`.
|
||||
|
||||
### CL20 — accepted
|
||||
|
||||
The worker supervisor exposes a narrow typed retained-result entry while preserving raw trace/strategy callers. It retains the existing validated envelope and returns it only after successful child close and candidate cleanup; the canonical adapter no longer reparses it. Input snapshots, child error/cancellation handling, trust-boundary/persistence validation and financial semantics are unchanged.
|
||||
|
||||
Implemented by `/root/implement_cl20`, independently reviewed/integrated by `/root`. Root rebuilt the orchestrator and ran retained-strategy-worker, canonical-worker-lifecycle, canonical-strategy-worker and native-replay-report: 59 passed, 232 assertions. New cases prove raw/typed parity, specific malformed identity/policy/artifact/analytics failures, caller mutation isolation, cancellation/reuse and valid result followed by exit code 23. The existing supervisor cleanup-failure branch was inspected unchanged; it was not newly fault-injected. Application and explicit authored-test typechecks, lint, formatting and diff checks passed. A worktree Zod bundling failure cleared after copying that dependency locally into ignored node_modules; root checkout tests passed unchanged. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl20-root-{build,tests,types}.log`.
|
||||
|
||||
### Remaining-wave integration — accepted
|
||||
|
||||
`CARGO_BUILD_JOBS=2 bun run check` passed on the integrated CL17–CL20 changes: 134 tooling, 43 utility, 44 calculation, 1,236 integration and 150 Rust tests; 14 existing conditional integration skips and 4 ignored Rust tests remain. Builds, application/contract typechecks, lint and secret audit passed. Root separately ran the disposable database suites recorded above (12 stored-source/recovery and 35 canonical-paper/crash/recovery cases, with overlapping recovery coverage). No browser E2E or full database suite was rerun; UI and financial schema/policy are unchanged. No performance claims or activation. Full log: `/tmp/stock-bot-engine-cleanup-20261026/remaining-wave-check.log`.
|
||||
|
||||
CL14–CL20, all seven scheduled cleanup stories, are complete. CL21 remains conditional on an actual replay scheduling/calendar need and explicit activation. The 72 task records outside this wave remain unchanged, including earlier CL01–CL13 review status and the six original conditional tasks. Disposable test containers were stopped/removed; isolated worktrees and logs remain for inspection.
|
||||
|
|
|
|||
|
|
@ -102,6 +102,9 @@ describe('retained canonical strategy worker', () => {
|
|||
'%s exact packaged bytes match the native report and repeat identically',
|
||||
async strategyId => {
|
||||
const value = await input(strategyId);
|
||||
if (value.request.strategy.origin !== 'builtin') {
|
||||
throw new Error('Expected a built-in fixture');
|
||||
}
|
||||
const load = prepareReplayLoad(value.dataset, value.request.policy);
|
||||
const direct = runStrategyReplay(
|
||||
load,
|
||||
|
|
@ -117,11 +120,21 @@ describe('retained canonical strategy worker', () => {
|
|||
expect(first.result.build).toEqual(value.request.build);
|
||||
expect(first.result.artifactHash).toBe(value.request.strategy.package.artifact.sha256);
|
||||
expect((await execute(value)).raw).toBe(first.raw);
|
||||
expect(
|
||||
await new NativeBacktestWorker().executeRetained(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
)
|
||||
).toEqual(first.result);
|
||||
}
|
||||
);
|
||||
|
||||
test('a retained version executes its own bytes when the current constructor differs', async () => {
|
||||
const value = await input();
|
||||
if (value.request.strategy.origin !== 'builtin') {
|
||||
throw new Error('Expected a built-in fixture');
|
||||
}
|
||||
const current = runStrategyReplay(
|
||||
prepareReplayLoad(value.dataset, value.request.policy),
|
||||
[createBuiltinStrategy(value.request.strategy.selection)],
|
||||
|
|
@ -236,7 +249,7 @@ describe('retained canonical strategy worker', () => {
|
|||
test('capture detaches all admitted inputs before the caller can mutate them', async () => {
|
||||
const value = structuredClone(await input());
|
||||
const captured = structuredClone(value.request);
|
||||
const running = new NativeBacktestWorker().execute(
|
||||
const running = new NativeBacktestWorker().executeRetained(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
|
|
@ -245,7 +258,7 @@ describe('retained canonical strategy worker', () => {
|
|||
value.request.strategy.selection.seed = 222;
|
||||
value.request.build.engineBinarySha256 = 'f'.repeat(64);
|
||||
(value.dataset.bars as unknown[]).length = 0;
|
||||
const result = parseRetainedStrategyResult(await running, captured);
|
||||
const result = await running;
|
||||
expect(result.artifactHash).toBe(captured.strategy.package.artifact.sha256);
|
||||
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
|
@ -291,6 +304,61 @@ describe('retained canonical strategy worker', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
[
|
||||
'result.artifactHash = "f".repeat(64)',
|
||||
'Retained strategy result build/artifact identity mismatch',
|
||||
],
|
||||
[
|
||||
'result.build.workerSha256 = "f".repeat(64)',
|
||||
'Retained strategy result build/artifact identity mismatch',
|
||||
],
|
||||
[
|
||||
'result.financial.policy.matching.risk.feeRate = "0"',
|
||||
'Native replay result identity mismatch',
|
||||
],
|
||||
[
|
||||
'result.analytics.metrics.exposureTime = null',
|
||||
'Retained strategy result analytics do not match the frozen policy',
|
||||
],
|
||||
])('typed worker rejects a malformed completed envelope: %s', async (mutation, reason) => {
|
||||
const value = await input();
|
||||
// A trusted fixture artifact intercepts its own child's IPC result. The
|
||||
// supervisor must still validate the envelope before returning typed data.
|
||||
retainedSource(
|
||||
value.request,
|
||||
`${value.request.strategy.package.artifact.content}
|
||||
const originalSend = process.send.bind(process);
|
||||
process.send = (message, callback) => {
|
||||
if (message.type === 'result') {
|
||||
const result = JSON.parse(message.result);
|
||||
${mutation};
|
||||
message.result = JSON.stringify(result);
|
||||
}
|
||||
return originalSend(message, callback);
|
||||
};`
|
||||
);
|
||||
await expect(
|
||||
new NativeBacktestWorker().executeRetained(value, new AbortController().signal, () => {})
|
||||
).rejects.toThrow(reason);
|
||||
});
|
||||
|
||||
test('typed retained results wait for successful child exit', async () => {
|
||||
const value = await input();
|
||||
retainedSource(
|
||||
value.request,
|
||||
`${value.request.strategy.package.artifact.content}
|
||||
const originalSend = process.send.bind(process);
|
||||
process.send = (message, callback) => {
|
||||
if (message.type === 'result') process.exitCode = 23;
|
||||
return originalSend(message, callback);
|
||||
};`
|
||||
);
|
||||
await expect(
|
||||
new NativeBacktestWorker().executeRetained(value, new AbortController().signal, () => {})
|
||||
).rejects.toThrow('code 23');
|
||||
});
|
||||
|
||||
test('alternate and source workers cannot claim the bundled worker identity', async () => {
|
||||
const value = await input();
|
||||
const sourceUrl = new URL(
|
||||
|
|
@ -298,7 +366,11 @@ describe('retained canonical strategy worker', () => {
|
|||
import.meta.url
|
||||
);
|
||||
await expect(
|
||||
new NativeBacktestWorker(sourceUrl).execute(value, new AbortController().signal, () => {})
|
||||
new NativeBacktestWorker(sourceUrl).executeRetained(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
)
|
||||
).rejects.toThrow('canonical bundled worker');
|
||||
expect(
|
||||
await new NativeBacktestWorker(canonicalWorkerUrl).execute(
|
||||
|
|
@ -342,10 +414,12 @@ describe('retained canonical strategy worker', () => {
|
|||
const worker = new NativeBacktestWorker();
|
||||
const abort = new AbortController();
|
||||
await expect(
|
||||
worker.execute(value, abort.signal, () => abort.abort(new Error('cancel retained replay')))
|
||||
worker.executeRetained(value, abort.signal, () =>
|
||||
abort.abort(new Error('cancel retained replay'))
|
||||
)
|
||||
).rejects.toThrow('cancel retained replay');
|
||||
expect(
|
||||
JSON.parse(await worker.execute(value, new AbortController().signal, () => {})).type
|
||||
).toBe('retainedStrategyResult');
|
||||
expect((await worker.executeRetained(value, new AbortController().signal, () => {})).type).toBe(
|
||||
'retainedStrategyResult'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue