refactor(experiments): share transactional run and dispatch insertion (CL29)
This commit is contained in:
parent
33e224048f
commit
731acc41db
8 changed files with 136 additions and 40 deletions
|
|
@ -29,6 +29,7 @@ import {
|
|||
experimentTrialRequest,
|
||||
} from './experiment-input';
|
||||
import type { ExperimentsService } from './experiments.service';
|
||||
import { insertExperimentTrial } from './insert-experiment-trial';
|
||||
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import {
|
||||
|
|
@ -595,21 +596,15 @@ export class ChronologicalValidationService {
|
|||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID(),
|
||||
request = experimentTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
runId,
|
||||
preview.input.backtestId,
|
||||
++number,
|
||||
request,
|
||||
request.datasetHash,
|
||||
id,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
await insertExperimentTrial(client, {
|
||||
runId,
|
||||
backtestId: preview.input.backtestId,
|
||||
runNumber: ++number,
|
||||
request,
|
||||
experimentId: id,
|
||||
trialKey: candidate.trialKey,
|
||||
trialIndex: candidate.index,
|
||||
});
|
||||
}
|
||||
}
|
||||
private async evidence(
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ import {
|
|||
PREVIEW_RUN_ID,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { insertExperimentTrial } from './insert-experiment-trial';
|
||||
import {
|
||||
lockExperimentResearchAgent,
|
||||
lockResearchAgent,
|
||||
|
|
@ -319,21 +320,15 @@ export class ExperimentsService {
|
|||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID();
|
||||
const request = workbenchTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
runId,
|
||||
input.backtestId,
|
||||
++runNumber,
|
||||
request,
|
||||
request.datasetHash,
|
||||
experimentId,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
await insertExperimentTrial(client, {
|
||||
runId,
|
||||
backtestId: input.backtestId,
|
||||
runNumber: ++runNumber,
|
||||
request,
|
||||
experimentId,
|
||||
trialKey: candidate.trialKey,
|
||||
trialIndex: candidate.index,
|
||||
});
|
||||
}
|
||||
return this.readDetail(client, experimentId);
|
||||
});
|
||||
|
|
|
|||
32
apps/stock/web-api/src/services/insert-experiment-trial.ts
Normal file
32
apps/stock/web-api/src/services/insert-experiment-trial.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
|
||||
/** Internal persistence step; the caller owns admission, identities, numbering and transaction. */
|
||||
export async function insertExperimentTrial(
|
||||
client: PoolClient,
|
||||
trial: {
|
||||
runId: string;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
request: CanonicalRunRequest;
|
||||
experimentId: string;
|
||||
trialKey: string;
|
||||
trialIndex: number;
|
||||
}
|
||||
): Promise<void> {
|
||||
await client.query(
|
||||
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
trial.runId,
|
||||
trial.backtestId,
|
||||
trial.runNumber,
|
||||
trial.request,
|
||||
trial.request.datasetHash,
|
||||
trial.experimentId,
|
||||
trial.trialKey,
|
||||
trial.trialIndex,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [trial.runId]);
|
||||
}
|
||||
|
|
@ -35,3 +35,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
|
|||
- **CL33:** Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved.
|
||||
|
||||
- **CL22:** Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative.
|
||||
|
||||
- **CL29:** Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**Active: E13 architecture cleanup, CL22–CL35 (13/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
|
||||
**Active: E13 architecture cleanup, CL22–CL35 (14/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
|
||||
|
||||
**Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-28.143",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "architecture_cleanup_in_progress",
|
||||
"plan_status": "architecture_cleanup_complete",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "Owner: commit and continue with the rest of the tasks till 100%",
|
||||
|
|
@ -3757,7 +3757,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL22"],
|
||||
"completed_commit": "3fc0a272d8356fa1de98f703d4df763f4938547c",
|
||||
"completed_commit": "1aa35d2db330179c4b19a6dadaacdb0b23761d3b",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -3817,7 +3817,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL25"],
|
||||
"completed_commit": "366a6054bf831df7bff02207bccccb9b82912dc7",
|
||||
"completed_commit": "2a9382a201477590c93b76ed7c82caec405cd8af",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -3837,7 +3837,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL26"],
|
||||
"completed_commit": "b4589d5af1c4b78026ef4fad484a8f493bc98786",
|
||||
"completed_commit": "33e224048ff326e482ad452f48ad5590a753373b",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -3857,7 +3857,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL27"],
|
||||
"completed_commit": "5c9e32d0ef1811acd2b79a59c896d55233c2179e",
|
||||
"completed_commit": "dac49ac1b89414afd980dfb6b57f0fb153ca981e",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -3890,7 +3890,7 @@
|
|||
"epic": "E13",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "done",
|
||||
"dependencies": ["CL28"],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL29.md",
|
||||
|
|
@ -3900,7 +3900,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md"
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
"integration_state": "accepted",
|
||||
"validation": "Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission."
|
||||
},
|
||||
{
|
||||
"id": "CL30",
|
||||
|
|
@ -10407,7 +10409,7 @@
|
|||
],
|
||||
"work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.",
|
||||
"first_wave": ["CL22", "CL23", "CL24"],
|
||||
"completed": 13,
|
||||
"last_verification": "Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative."
|
||||
"completed": 14,
|
||||
"last_verification": "Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,3 +18,7 @@ PostgreSQL duplicate keys, numbering, rollback, holdout isolation. Focused revie
|
|||
|
||||
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
|
||||
|
||||
|
||||
## Accepted verification
|
||||
|
||||
Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission.
|
||||
|
|
|
|||
66
test/integration/experiment-trial-insertion.test.ts
Normal file
66
test/integration/experiment-trial-insertion.test.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, mock, test } from 'bun:test';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { insertExperimentTrial } from '../../apps/stock/web-api/src/services/insert-experiment-trial';
|
||||
import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
|
||||
|
||||
function trial() {
|
||||
const { request } = canonicalRunnerFixture();
|
||||
return {
|
||||
runId: request.runId,
|
||||
backtestId: request.backtestId,
|
||||
runNumber: 17,
|
||||
request,
|
||||
experimentId: randomUUID(),
|
||||
trialKey: 'a'.repeat(64),
|
||||
trialIndex: 3,
|
||||
};
|
||||
}
|
||||
|
||||
test('the admitted trial and dispatch use the existing connection and exact caller identities', async () => {
|
||||
const input = trial();
|
||||
const snapshot = structuredClone(input);
|
||||
const query = mock(async (_text: string, _values: unknown[]) => ({ rows: [] }));
|
||||
await insertExperimentTrial({ query } as unknown as PoolClient, input);
|
||||
expect(query).toHaveBeenCalledTimes(2);
|
||||
const [run, dispatch] = query.mock.calls;
|
||||
expect(run?.[0]).toContain("VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)");
|
||||
expect(run?.[1]).toEqual([
|
||||
input.runId,
|
||||
input.backtestId,
|
||||
17,
|
||||
input.request,
|
||||
input.request.datasetHash,
|
||||
input.experimentId,
|
||||
input.trialKey,
|
||||
3,
|
||||
]);
|
||||
expect(run?.[1][3]).toBe(input.request);
|
||||
expect(dispatch).toEqual(['INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [input.runId]]);
|
||||
expect(input).toEqual(snapshot);
|
||||
});
|
||||
|
||||
test('a failed run insert never attempts dispatch and propagates the original transaction failure', async () => {
|
||||
const failure = new Error('duplicate trial');
|
||||
const query = mock(async () => {
|
||||
throw failure;
|
||||
});
|
||||
await expect(insertExperimentTrial({ query } as unknown as PoolClient, trial())).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('a failed dispatch insert propagates so the caller rolls back the run and whole experiment', async () => {
|
||||
const failure = new Error('dispatch insertion failed');
|
||||
const query = mock(async (text: string) => {
|
||||
if (text.startsWith('INSERT INTO backtest_dispatch')) {
|
||||
throw failure;
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
await expect(insertExperimentTrial({ query } as unknown as PoolClient, trial())).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(query).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue