feat(research): isolate candidates and add reviewed paper promotion

This commit is contained in:
Boki 2026-10-24 18:46:55 -04:00
parent 26b97265c6
commit 25b5cbf481
128 changed files with 13038 additions and 1388 deletions

View file

@ -0,0 +1,200 @@
import { randomUUID } from 'node:crypto';
import { PassThrough } from 'node:stream';
import { describe, expect, test } from 'bun:test';
import {
candidateExecutionSchema,
candidateSandboxLimits,
} from '../../apps/stock/config/src/contracts/candidate-execution';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
} from '../../apps/stock/config/src/contracts/canonical-research';
import {
chronologicalPolicyForOrigin,
chronologicalValidationPolicy,
} from '../../apps/stock/config/src/contracts/chronological-validation';
import { experimentInputSchema } from '../../apps/stock/config/src/contracts/experiments';
import {
readCandidateFrames,
writeCandidateFrame,
} from '../../apps/stock/orchestrator/src/backtest/candidate-protocol';
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
export const fakeCandidateExecution = () =>
candidateExecutionSchema.parse({
kind: 'typescript-isolated-candidate/v1',
imageId: `sha256:${'a'.repeat(64)}`,
profile: {
version: 1,
policy: 'linux-docker-guardian/v1',
protocol: 'candidate-controller/v1',
platform: 'linux',
arch: 'x64',
hostSha256: 'b'.repeat(64),
guardianSha256: 'c'.repeat(64),
bunSha256: 'd'.repeat(64),
limits: candidateSandboxLimits,
},
});
function candidateFixture() {
const { request } = canonicalRunnerFixture();
const candidateId = randomUUID(),
ownerId = `strategy:${candidateId}`;
const policy = structuredClone(request.policy);
policy.matching.risk.ledger.ownerIds = [ownerId];
policy.matching.owners = [{ ownerId, mode: 'Target' }];
policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
const candidate = {
...request,
policy,
strategy: {
...request.strategy,
origin: 'candidate',
versionId: candidateId,
baselineVersionId: request.strategy.versionId,
reviewId: null,
execution: fakeCandidateExecution(),
package: {
...request.strategy.package,
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
},
selection: { ...request.strategy.selection, ownerId },
},
};
return { builtin: request, candidate: canonicalRunRequestSchema.parse(candidate) };
}
describe('isolated candidate contracts', () => {
test('builtin snapshots and grant projection retain exact existing bytes', () => {
const { builtin } = candidateFixture();
expect(JSON.stringify(canonicalRunRequestSchema.parse(builtin))).toBe(JSON.stringify(builtin));
expect(canonicalStrategyExecution(builtin)).toBe('typescript-retained-builtin/v1');
expect(builtin.strategy).not.toHaveProperty('execution');
expect(builtin.strategy).not.toHaveProperty('baselineVersionId');
const policy = researchGrantPolicy(builtin);
expect(policy.versionId).toBe(builtin.strategy.versionId);
expect(policy.policy.matching.owners).toEqual(builtin.policy.matching.owners);
});
test('candidate alone accepts no review, generic identity and fixed declared warmup', () => {
const { builtin, candidate } = candidateFixture();
expect(candidate.strategy.reviewId).toBeNull();
expect(canonicalStrategyExecution(candidate)).toBe('typescript-isolated-candidate/v1');
expect(
canonicalRunRequestSchema.safeParse({
...builtin,
strategy: { ...builtin.strategy, reviewId: null },
}).success
).toBeFalse();
for (const field of ['execution', 'baselineVersionId']) {
const malformed = {
...candidate,
strategy: Object.fromEntries(
Object.entries(candidate.strategy).filter(([name]) => name !== field)
),
};
expect(canonicalRunRequestSchema.safeParse(malformed).success).toBeFalse();
}
expect(
canonicalRunRequestSchema.safeParse({
...builtin,
strategy: { ...builtin.strategy, execution: fakeCandidateExecution() },
}).success
).toBeFalse();
});
test('candidate maps only its derived identities back to the frozen baseline grant', () => {
const { builtin, candidate } = candidateFixture();
expect(researchGrantPolicy(candidate)).toEqual(researchGrantPolicy(builtin));
const changed = structuredClone(candidate);
changed.policy.matching.risk.maxGrossExposure =
'1.00000000' as typeof changed.policy.matching.risk.maxGrossExposure;
expect(researchGrantPolicy(changed)).not.toEqual(researchGrantPolicy(builtin));
if (changed.strategy.origin !== 'candidate') {
throw new Error('fixture origin');
}
changed.strategy.baselineVersionId = randomUUID();
expect(researchGrantPolicy(changed).versionId).not.toBe(researchGrantPolicy(builtin).versionId);
});
test('profile cannot raise limits, choose trusted execution, add host flags or choose an unsupported platform', () => {
const execution = fakeCandidateExecution();
for (const changed of [
{ ...execution, kind: 'typescript-retained-builtin/v1' },
{ ...execution, flags: ['--privileged'] },
{ ...execution, profile: { ...execution.profile, arch: 'arm64' } },
{
...execution,
profile: {
...execution.profile,
limits: { ...execution.profile.limits, memoryBytes: 1073741824 },
},
},
]) {
expect(candidateExecutionSchema.safeParse(changed).success).toBeFalse();
}
});
test('candidate input is explicit and strategy policy never claims inferred determinism', () => {
const input = {
backtestId: randomUUID(),
name: 'Candidate',
grid: {},
candidate: { versionId: randomUUID(), parameters: {} },
};
expect(experimentInputSchema.parse(input)).toEqual(input);
expect(
experimentInputSchema.safeParse({ ...input, candidate: { ...input.candidate, feeRate: '0' } })
.success
).toBeFalse();
expect(chronologicalPolicyForOrigin('builtin')).toBe(chronologicalValidationPolicy);
expect(chronologicalPolicyForOrigin('candidate')).toEqual({
...chronologicalValidationPolicy,
model: 'unverified-candidate',
});
});
test('framing preserves exact JSON across chunks and rejects truncation/oversize before parsing', async () => {
const encoded = new PassThrough();
const output: unknown[] = [];
const read = (async () => {
for await (const frame of readCandidateFrames(encoded)) {
output.push(frame);
}
})();
await writeCandidateFrame(encoded, { version: 1, string: 'Unicode α', sequence: 1 });
encoded.end();
await read;
expect(output).toEqual([{ version: 1, string: 'Unicode α', sequence: 1 }]);
for (const length of [0, candidateSandboxLimits.frameBytes + 1]) {
const input = new PassThrough(),
bytes = Buffer.alloc(4);
bytes.writeUInt32BE(length);
input.end(bytes);
await expect(readCandidateFrames(input).next()).rejects.toThrow('Invalid or oversized');
}
const input = new PassThrough();
input.end(Buffer.from([0, 0, 0, 5, 123]));
await expect(readCandidateFrames(input).next()).rejects.toThrow('Truncated');
});
test('split UTF-8 frames are decoded only when complete; malformed UTF-8 and flooding are rejected', async () => {
const content = Buffer.from(JSON.stringify({ value: 'αβ😀' }));
const header = Buffer.alloc(4);
header.writeUInt32BE(content.length);
const input = new PassThrough();
const collected = (async () => {
const out: unknown[] = [];
for await (const value of readCandidateFrames(input)) {
out.push(value);
}
return out;
})();
for (const byte of Buffer.concat([header, content])) {
input.write(Buffer.from([byte]));
await Promise.resolve();
}
input.end();
expect(await collected).toEqual([{ value: 'αβ😀' }]);
const invalid = new PassThrough();
invalid.end(Buffer.from([0, 0, 0, 1, 255]));
await expect(readCandidateFrames(invalid).next()).rejects.toThrow();
const flood = new PassThrough();
flood.end(Buffer.alloc(candidateSandboxLimits.frameBytes + 5));
await expect(readCandidateFrames(flood).next()).rejects.toThrow('buffer exceeds');
});
});