Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/schedule-agent-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@truefoundry/trueforge": patch
---

Add NOT NULL `agent_id` on `schedule` (backfilled from `agent`), FK to `agent(id)` ON DELETE CASCADE (replacing the `(tenant_id, agent_name)` FK), and `(tenant_id, agent_id)` index for per-agent listing.
1 change: 1 addition & 0 deletions packages/trueforge/src/apis/schedules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const { schedule } = await deps.scheduleStore.createScheduleAndRun(
{
tenant_id: requestContext.tenant_id,
agent_id: agent.id,
agent_name: agent.name,
name: body.name,
manifest: body.manifest,
Expand Down
3 changes: 3 additions & 0 deletions packages/trueforge/src/db/indexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@ export const SESSION_CREATED_BY_SUBJECT_ID_IDX = 'session_created_by_subject_id_
/** `(tenant_id, created_by_subject.subject_id)` on schedule. */
export const SCHEDULE_CREATED_BY_SUBJECT_ID_IDX = 'schedule_created_by_subject_id_idx';

/** `(tenant_id, agent_id)` on schedule — list schedules for one agent by id. */
export const SCHEDULE_AGENT_ID_IDX = 'schedule_agent_id_idx';

/** `(tenant_id, created_by_subject.subject_id)` on schedule_run. */
export const SCHEDULE_RUN_CREATED_BY_SUBJECT_ID_IDX = 'schedule_run_created_by_subject_id_idx';
Comment thread
thesujai marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { sql, type Kysely } from 'kysely';
import { SCHEDULE_AGENT_ID_IDX } from '../../indexes';

/**
* Add `agent_id` on schedule (stable ULID binding). Backfills from `agent` via
* `(tenant_id, agent_name)`, then drops the name FK in favor of `agent(id)`.
* Index mirrors `session_agent_id_idx` for per-agent schedule lists.
* Runs inside the Migrator's transaction — do not nest `db.transaction()`.
*/
export async function up(db: Kysely<unknown>): Promise<void> {
await sql`
SET LOCAL lock_timeout = '5s';

ALTER TABLE schedule
ADD COLUMN agent_id text;
UPDATE schedule AS s
SET agent_id = a.id
FROM agent AS a
WHERE s.tenant_id = a.tenant_id
AND s.agent_name = a.name;
ALTER TABLE schedule
ALTER COLUMN agent_id SET NOT NULL;
ALTER TABLE schedule
DROP CONSTRAINT schedule_agent_name_fk;
ALTER TABLE schedule
ADD CONSTRAINT schedule_agent_id_fk
FOREIGN KEY (agent_id) REFERENCES agent (id) ON DELETE CASCADE;
CREATE INDEX ${sql.raw(SCHEDULE_AGENT_ID_IDX)}
ON schedule (tenant_id, agent_id);
`.execute(db);
}

export async function down(db: Kysely<unknown>): Promise<void> {
await sql`
SET LOCAL lock_timeout = '5s';

DROP INDEX IF EXISTS ${sql.raw(SCHEDULE_AGENT_ID_IDX)};
ALTER TABLE schedule
DROP CONSTRAINT IF EXISTS schedule_agent_id_fk;
ALTER TABLE schedule
ADD CONSTRAINT schedule_agent_name_fk
FOREIGN KEY (tenant_id, agent_name) REFERENCES agent (tenant_id, name) ON DELETE CASCADE;
ALTER TABLE schedule
DROP COLUMN agent_id;
`.execute(db);
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function toScheduleRecord(row: Selectable<ScheduleTable>): ScheduleRecord {
return {
id: row.id,
tenant_id: row.tenant_id,
agent_id: row.agent_id,
agent_name: row.agent_name,
name: row.name,
manifest: parseStoredScheduleManifest(row.manifest),
Expand Down Expand Up @@ -140,6 +141,7 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
.values({
id: newId(),
tenant_id: input.tenant_id,
agent_id: input.agent_id,
agent_name: input.agent_name,
name: input.name,
manifest: json(input.manifest),
Expand Down
7 changes: 5 additions & 2 deletions packages/trueforge/src/db/postgres/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,13 +386,16 @@ export interface AgentTable {
* Configured schedules — immutable ULID `id` PK.
* PRIMARY KEY (id)
* CREATE INDEX schedule_agent_idx ON schedule (tenant_id, agent_name)
* FK (tenant_id, agent_name) → agent(tenant_id, name) ON DELETE CASCADE
* CREATE INDEX schedule_agent_id_idx ON schedule (tenant_id, agent_id)
* FK (agent_id) → agent(id) ON DELETE CASCADE
*/
export interface ScheduleTable {
/** application-generated (ulid); FK target for schedule_run */
id: string;
tenant_id: string;
/** FK with tenant_id → agent(tenant_id, name). Immutable; agent version resolves at run time. */
/** FK → agent(id). Immutable. */
agent_id: string;
/** Create-time snapshot of registry agent name. */
agent_name: string;
/** Display label; not unique. */
name: string;
Expand Down
5 changes: 4 additions & 1 deletion packages/trueforge/src/db/scheduleStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export function manualRunName(): string {
export interface ScheduleRecord {
id: string;
tenant_id: string;
/** Immutable FK to `agent.name` (with tenant); agent version resolves at run time. */
/** Immutable FK to `agent.id`. */
agent_id: string;
/** Create-time snapshot of registry agent name. */
agent_name: string;
/** Slug-shaped label, unique per agent (`schedule_name_uq`). */
name: string;
Expand Down Expand Up @@ -108,6 +110,7 @@ export interface GetScheduleInput {

export interface CreateScheduleInput {
tenant_id: string;
agent_id: string;
agent_name: string;
name: string;
manifest: ScheduleManifest;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { sql, type Kysely } from 'kysely';
import { SCHEDULE_AGENT_ID_IDX, SCHEDULE_CREATED_BY_SUBJECT_ID_IDX } from '../../indexes';

/**
* Add NOT NULL `agent_id` on schedule — mirrors
* db/postgres/migrations/20260904_000001_schedule_agent_id.ts.
* Drops the `(tenant_id, agent_name)` FK; binding is `agent(id)` only.
*
* SQLite STRICT cannot ADD a NOT NULL column without a DEFAULT, so rebuild
* `schedule` (FKs off so `schedule_run` rows survive the drop/rename).
* better-sqlite3 prepares one statement per call — keep statements separate.
*/
export async function up(db: Kysely<unknown>): Promise<void> {
await sql`PRAGMA foreign_keys = OFF`.execute(db);
try {
await db.transaction().execute(async trx => {
await sql`
Comment thread
thesujai marked this conversation as resolved.
Resolved
CREATE TABLE schedule_new (
id TEXT NOT NULL,
tenant_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
agent_name TEXT NOT NULL,
name TEXT NOT NULL,
manifest BLOB NOT NULL,
status TEXT NOT NULL CHECK (length(status) <= 16),
created_by_subject BLOB NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (agent_id) REFERENCES agent (id) ON DELETE CASCADE
) STRICT
`.execute(trx);

await sql`
INSERT INTO schedule_new (
id,
tenant_id,
agent_id,
agent_name,
name,
manifest,
status,
created_by_subject,
created_at,
updated_at
)
SELECT
s.id,
s.tenant_id,
a.id,
s.agent_name,
s.name,
s.manifest,
s.status,
s.created_by_subject,
s.created_at,
s.updated_at
FROM schedule AS s
INNER JOIN agent AS a
ON a.tenant_id = s.tenant_id
AND a.name = s.agent_name
`.execute(trx);

await sql`DROP TABLE schedule`.execute(trx);
await sql`ALTER TABLE schedule_new RENAME TO schedule`.execute(trx);

await sql`
CREATE INDEX schedule_agent_idx
ON schedule (tenant_id, agent_name)
`.execute(trx);
await sql`
CREATE UNIQUE INDEX schedule_name_uq
ON schedule (tenant_id, agent_name, name)
`.execute(trx);
await sql`
CREATE INDEX ${sql.raw(SCHEDULE_CREATED_BY_SUBJECT_ID_IDX)}
ON schedule (tenant_id, json_extract(created_by_subject, '$.subject_id'))
`.execute(trx);
await sql`
CREATE INDEX ${sql.raw(SCHEDULE_AGENT_ID_IDX)}
ON schedule (tenant_id, agent_id)
`.execute(trx);
});
} finally {
await sql`PRAGMA foreign_keys = ON`.execute(db);
}
}

export async function down(db: Kysely<unknown>): Promise<void> {
await sql`PRAGMA foreign_keys = OFF`.execute(db);
try {
await db.transaction().execute(async trx => {
await sql`
CREATE TABLE schedule_old (
id TEXT NOT NULL,
tenant_id TEXT NOT NULL,
agent_name TEXT NOT NULL,
name TEXT NOT NULL,
manifest BLOB NOT NULL,
status TEXT NOT NULL CHECK (length(status) <= 16),
created_by_subject BLOB NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (tenant_id, agent_name) REFERENCES agent (tenant_id, name) ON DELETE CASCADE
) STRICT
`.execute(trx);

await sql`
INSERT INTO schedule_old (
id, tenant_id, agent_name, name, manifest, status, created_by_subject, created_at, updated_at
)
SELECT
id, tenant_id, agent_name, name, manifest, status, created_by_subject, created_at, updated_at
FROM schedule
`.execute(trx);

await sql`DROP TABLE schedule`.execute(trx);
await sql`ALTER TABLE schedule_old RENAME TO schedule`.execute(trx);

await sql`
CREATE INDEX schedule_agent_idx
ON schedule (tenant_id, agent_name)
`.execute(trx);
await sql`
CREATE UNIQUE INDEX schedule_name_uq
ON schedule (tenant_id, agent_name, name)
`.execute(trx);
await sql`
CREATE INDEX ${sql.raw(SCHEDULE_CREATED_BY_SUBJECT_ID_IDX)}
ON schedule (tenant_id, json_extract(created_by_subject, '$.subject_id'))
`.execute(trx);
});
} finally {
await sql`PRAGMA foreign_keys = ON`.execute(db);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ function scheduleColumns(eb: ExpressionBuilder<Database, 'schedule'>) {
return [
'id' as const,
'tenant_id' as const,
'agent_id' as const,
'agent_name' as const,
'name' as const,
jsonText<ScheduleManifest>(eb.ref('manifest')).as('manifest'),
Expand Down Expand Up @@ -67,6 +68,7 @@ function runColumns(eb: ExpressionBuilder<Database, 'schedule_run'>) {
interface ScheduleRow {
id: string;
tenant_id: string;
agent_id: string;
agent_name: string;
name: string;
manifest: ScheduleManifest;
Expand Down Expand Up @@ -146,6 +148,7 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
.values({
id: newId(),
tenant_id: input.tenant_id,
agent_id: input.agent_id,
agent_name: input.agent_name,
name: input.name,
manifest: jsonbBind(input.manifest),
Expand Down
6 changes: 4 additions & 2 deletions packages/trueforge/src/db/sqlite/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,15 @@ export interface AgentTable {
/**
* Configured schedules.
* PRIMARY KEY (id).
* FK (tenant_id, agent_name) → agent(tenant_id, name) ON DELETE CASCADE.
* FK (agent_id) → agent(id) ON DELETE CASCADE.
*/
export interface ScheduleTable {
/** application-generated (ulid); FK target for schedule_run */
id: string;
tenant_id: string;
/** FK with tenant_id → agent(tenant_id, name). Immutable; agent version resolves at run time. */
/** FK → agent(id). Immutable. */
agent_id: string;
/** Create-time snapshot of registry agent name. */
agent_name: string;
/** Display label; not unique. */
name: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function runScheduleDispatchContractSuite<TTransaction>(deps: {
const logger = createLogger({ silent: true });
let seq = 0;

async function seedAgent(): Promise<string> {
async function seedAgent(): Promise<{ id: string; name: string }> {
seq += 1;
const agent = await deps.getAgentStore().createAgent({
tenant_id: TENANT,
Expand All @@ -77,7 +77,7 @@ export function runScheduleDispatchContractSuite<TTransaction>(deps: {
}),
external_id: null,
});
return agent.name;
return { id: agent.id, name: agent.name };
}

async function scheduledRunsFor(scheduleId: string): Promise<ScheduleRunRecord[]> {
Expand All @@ -104,12 +104,13 @@ export function runScheduleDispatchContractSuite<TTransaction>(deps: {
createdBySubject?: CreatedBySubject;
}): Promise<{ schedule: ScheduleRecord; run: ScheduleRunRecord }> {
const store = deps.getScheduleStore();
const agentName = await seedAgent();
const agent = await seedAgent();
const status = params.status ?? 'active';
const cron = params.cron ?? CRON;
const { schedule, pendingRun } = await store.createScheduleAndRun({
tenant_id: TENANT,
agent_name: agentName,
agent_id: agent.id,
agent_name: agent.name,
name: `sched-${String(Date.now())}-${String(seq)}`,
manifest: manifest({ status, cron }),
created_by_subject: USER_SUBJECT,
Expand Down
Loading