feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
327
apps/stock/web-api/src/services/research-agents.service.ts
Normal file
327
apps/stock/web-api/src/services/research-agents.service.ts
Normal file
|
|
@ -0,0 +1,327 @@
|
|||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
createResearchAgentSchema,
|
||||
researchAgentIdSchema,
|
||||
updateResearchAgentSchema,
|
||||
type ResearchAgentBudget,
|
||||
type ResearchAgentRecord,
|
||||
} from '@stock-bot/stock-config/research-agents';
|
||||
import { HistoricalDataRequestError, isResearchAgent } from '@stock-bot/types';
|
||||
import { admitCanonicalRequest } from './canonical-research.service';
|
||||
import { PREVIEW_RUN_ID } from './experiment-input';
|
||||
import {
|
||||
ResearchAgentError,
|
||||
researchGrantHash,
|
||||
researchGrantPolicy,
|
||||
} from './research-agent-budget';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
|
||||
const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex');
|
||||
function record(row: QueryResultRow): ResearchAgentRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
enabled: row.enabled,
|
||||
revision: row.revision,
|
||||
allowedProjectIds: row.policy.allowedProjectIds,
|
||||
grants: row.policy.grants.map((grant: { backtestId: string; policyHash: string }) => ({
|
||||
backtestId: grant.backtestId,
|
||||
policyHash: grant.policyHash,
|
||||
})),
|
||||
limits: row.policy.limits,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
updatedAt: new Date(row.updated_at).toISOString(),
|
||||
};
|
||||
}
|
||||
const uuid = '[0-9a-fA-F-]{36}';
|
||||
function permitted(request: Request): boolean {
|
||||
const path = new URL(request.url).pathname,
|
||||
method = request.method;
|
||||
if (method === 'GET' || method === 'HEAD') {
|
||||
return (
|
||||
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
|
||||
path
|
||||
) || path === '/api/v2/research-agent/budget'
|
||||
);
|
||||
}
|
||||
if (method === 'PUT') {
|
||||
return new RegExp(`^/api/v2/research-projects/${uuid}/strategies/${uuid}$`).test(path);
|
||||
}
|
||||
if (method !== 'POST') {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
path === '/api/v2/strategies' ||
|
||||
new RegExp(`^/api/v2/strategies/${uuid}/versions$`).test(path) ||
|
||||
new RegExp(`^/api/v2/strategy-versions/${uuid}/(clone|validate)$`).test(path) ||
|
||||
new RegExp(`^/api/v2/research-projects/${uuid}/(hypotheses|analysis-artifacts)$`).test(path) ||
|
||||
new RegExp(`^/api/v2/(hypotheses|analysis-artifacts)/${uuid}/revisions$`).test(path) ||
|
||||
/^\/api\/v2\/experiments(?:\/(?:preview|cost-sensitivity(?:\/preview)?|validation(?:\/preview)?|walk-forward(?:\/preview)?))?$/.test(
|
||||
path
|
||||
) ||
|
||||
new RegExp(
|
||||
`^/api/v2/experiments/(?:validation/|walk-forward/)?${uuid}/(?:cancel|select|finalize)$`
|
||||
).test(path) ||
|
||||
new RegExp(`^/api/v2/experiments/${uuid}/trials/${uuid}/retry$`).test(path)
|
||||
);
|
||||
}
|
||||
export class ResearchAgentsService {
|
||||
private readonly database;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
}
|
||||
private async policy(
|
||||
client: PoolClient,
|
||||
input: {
|
||||
allowedProjectIds: string[];
|
||||
allowedBacktestIds: string[];
|
||||
limits: ResearchAgentRecord['limits'];
|
||||
}
|
||||
) {
|
||||
for (const id of input.allowedProjectIds) {
|
||||
if (
|
||||
!(
|
||||
await client.query(
|
||||
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
|
||||
[id]
|
||||
)
|
||||
).rows.length
|
||||
) {
|
||||
throw new ResearchAgentError(400, 'Choose existing active research projects');
|
||||
}
|
||||
}
|
||||
// Lock every parent before acquiring any family lock; interleaving these can deadlock
|
||||
// a concurrent admission on another granted template sharing the same family.
|
||||
const parents = (
|
||||
await client.query(
|
||||
'SELECT * FROM backtests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE',
|
||||
[input.allowedBacktestIds]
|
||||
)
|
||||
).rows;
|
||||
if (
|
||||
parents.length !== input.allowedBacktestIds.length ||
|
||||
parents.some(row => row.archived_at)
|
||||
) {
|
||||
throw new ResearchAgentError(400, 'Choose existing active canonical templates');
|
||||
}
|
||||
await client.query(
|
||||
'SELECT id FROM strategies WHERE id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY id FOR UPDATE',
|
||||
[parents.map(row => row.strategy_version_id).filter(Boolean)]
|
||||
);
|
||||
const grants = [];
|
||||
for (const row of parents) {
|
||||
const id = row.id as string;
|
||||
let request;
|
||||
try {
|
||||
request = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
{
|
||||
name: row.name,
|
||||
strategyVersionId: row.strategy_version_id,
|
||||
strategyParameters: row.strategy_parameters,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: Number(row.initial_capital),
|
||||
config: row.config,
|
||||
},
|
||||
id,
|
||||
PREVIEW_RUN_ID
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
!(
|
||||
error instanceof HistoricalDataRequestError ||
|
||||
error instanceof StrategyCatalogError ||
|
||||
error instanceof z.ZodError
|
||||
)
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
throw new ResearchAgentError(
|
||||
400,
|
||||
'Agent grants require currently approved canonical templates'
|
||||
);
|
||||
}
|
||||
const policy = researchGrantPolicy(request);
|
||||
grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy });
|
||||
}
|
||||
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
|
||||
}
|
||||
async create(raw: unknown) {
|
||||
const input = createResearchAgentSchema.parse(raw),
|
||||
token = `sb-research.${randomBytes(32).toString('base64url')}`;
|
||||
const agent = await this.database.transaction(async client => {
|
||||
const policy = await this.policy(client, input);
|
||||
const row = (
|
||||
await client.query(
|
||||
'INSERT INTO research_agents(id,name,token_hash,policy) VALUES($1,$2,$3,$4::jsonb) RETURNING *',
|
||||
[`agent:${randomUUID()}`, input.name, tokenHash(token), JSON.stringify(policy)]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new Error('Research agent was not created');
|
||||
}
|
||||
return record(row);
|
||||
});
|
||||
return { agent, token };
|
||||
}
|
||||
async list(): Promise<ResearchAgentRecord[]> {
|
||||
return (
|
||||
await this.database.query('SELECT * FROM research_agents ORDER BY created_at,id')
|
||||
).rows.map(record);
|
||||
}
|
||||
async update(id: string, raw: unknown): Promise<ResearchAgentRecord> {
|
||||
researchAgentIdSchema.parse(id);
|
||||
const input = updateResearchAgentSchema.parse(raw);
|
||||
return this.database.transaction(async client => {
|
||||
const old = (await client.query('SELECT * FROM research_agents WHERE id=$1 FOR UPDATE', [id]))
|
||||
.rows[0];
|
||||
if (!old) {
|
||||
throw new ResearchAgentError(404, 'Research principal not found');
|
||||
}
|
||||
if (old.revision !== input.expectedRevision) {
|
||||
throw new ResearchAgentError(
|
||||
409,
|
||||
'Research principal policy changed; reload before editing'
|
||||
);
|
||||
}
|
||||
const policy =
|
||||
input.allowedBacktestIds === undefined
|
||||
? {
|
||||
...old.policy,
|
||||
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
|
||||
limits: input.limits ?? old.policy.limits,
|
||||
}
|
||||
: await this.policy(client, {
|
||||
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
|
||||
allowedBacktestIds: input.allowedBacktestIds,
|
||||
limits: input.limits ?? old.policy.limits,
|
||||
});
|
||||
if (input.allowedProjectIds) {
|
||||
for (const projectId of input.allowedProjectIds) {
|
||||
if (
|
||||
!(
|
||||
await client.query(
|
||||
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
|
||||
[projectId]
|
||||
)
|
||||
).rows.length
|
||||
) {
|
||||
throw new ResearchAgentError(400, 'Choose existing active research projects');
|
||||
}
|
||||
}
|
||||
}
|
||||
const row = (
|
||||
await client.query(
|
||||
'UPDATE research_agents SET name=$2,enabled=$3,policy=$4::jsonb,revision=revision+1,updated_at=NOW() WHERE id=$1 RETURNING *',
|
||||
[id, input.name ?? old.name, input.enabled ?? old.enabled, JSON.stringify(policy)]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new Error('Research principal update disappeared');
|
||||
}
|
||||
return record(row);
|
||||
});
|
||||
}
|
||||
async budget(id: string, allowDisabled = false): Promise<ResearchAgentBudget> {
|
||||
const row = (
|
||||
await this.database.query(
|
||||
`SELECT a.*,(SELECT count(*)::integer FROM runs r WHERE r.research_agent_id=a.id AND r.status IN ('pending','running','paused')) AS active_trials FROM research_agents a WHERE a.id=$1`,
|
||||
[researchAgentIdSchema.parse(id)]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row || (!allowDisabled && !row.enabled)) {
|
||||
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
|
||||
}
|
||||
const agent = record(row),
|
||||
activeTrials = Number(row.active_trials);
|
||||
return {
|
||||
agent,
|
||||
activeTrials,
|
||||
remainingActiveTrials: Math.max(0, agent.limits.maxActiveTrials - activeTrials),
|
||||
};
|
||||
}
|
||||
async authenticate(
|
||||
request: Request
|
||||
): Promise<{ principal: `agent:${string}` } | Response | undefined> {
|
||||
const match = /^Bearer (sb-research\.[A-Za-z0-9_-]+)$/i.exec(
|
||||
request.headers.get('authorization') ?? ''
|
||||
);
|
||||
if (!match?.[1]) {
|
||||
return undefined;
|
||||
}
|
||||
const row = (
|
||||
await this.database.query(
|
||||
'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1',
|
||||
[tokenHash(match[1])]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row?.enabled || !isResearchAgent(row.id)) {
|
||||
return undefined;
|
||||
}
|
||||
const deny = () =>
|
||||
Response.json(
|
||||
{ error: 'Research credential does not permit this operation' },
|
||||
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
|
||||
);
|
||||
if (!permitted(request)) {
|
||||
return deny();
|
||||
}
|
||||
if (!['GET', 'HEAD'].includes(request.method)) {
|
||||
const path = new URL(request.url).pathname;
|
||||
const project = new RegExp(`^/api/v2/research-projects/(${uuid})/`).exec(path);
|
||||
if (project && !row.policy.allowedProjectIds.includes(project[1]?.toLowerCase())) {
|
||||
return deny();
|
||||
}
|
||||
const experiment = new RegExp(
|
||||
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
|
||||
).exec(path);
|
||||
if (experiment) {
|
||||
const table =
|
||||
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
|
||||
const owned = (
|
||||
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
|
||||
experiment[2],
|
||||
])
|
||||
).rows[0];
|
||||
if (owned?.submission_principal !== row.id) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
const family = new RegExp(`^/api/v2/strategies/(${uuid})/versions$`).exec(path);
|
||||
if (
|
||||
family &&
|
||||
(
|
||||
await this.database.query('SELECT owner_principal FROM strategies WHERE id=$1', [
|
||||
family[1],
|
||||
])
|
||||
).rows[0]?.owner_principal !== row.id
|
||||
) {
|
||||
return deny();
|
||||
}
|
||||
const narrative = new RegExp(
|
||||
`^/api/v2/(hypotheses|analysis-artifacts)/(${uuid})/revisions$`
|
||||
).exec(path);
|
||||
if (narrative) {
|
||||
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
|
||||
const owned = (
|
||||
await this.database.query(`SELECT owner_principal,project_id FROM ${table} WHERE id=$1`, [
|
||||
narrative[2],
|
||||
])
|
||||
).rows[0];
|
||||
if (
|
||||
owned?.owner_principal !== row.id ||
|
||||
!row.policy.allowedProjectIds.includes(owned.project_id)
|
||||
) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { principal: row.id };
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue