refactor(schema): make runs.task_id nullable, delete heartbeat workaround
The NOT NULL constraint forced heartbeat runs to synthesize a fake task row (`[Heartbeat] X — Check for work`) so the FK could resolve. Three layers of code — acquireHeartbeatTask, findReusableHeartbeatTask, cleanupDuplicateHeartbeatTasks, plus the is_heartbeat flag column + UI filter — existed to paper over one bad constraint. Remove the constraint and the whole workaround vanishes. SQLite table rebuild with data preservation. Live production DB, no backup — migration is atomic, idempotent, and verified before DROP. ## Migration v35 (rebuild runs with nullable task_id) Uses `fn:` form so it can: - Snapshot `COUNT(*) FROM runs` before copy - Walk `PRAGMA table_info(runs)` to detect drift columns (v34 declared a column set; any additive ALTER since v14 shows up here) - Assert `COUNT(*) FROM runs_new == beforeCount` before `DROP TABLE runs` - `PRAGMA defer_foreign_keys = ON` so run_events(run_id) FK defers to commit time, by which runs has the same id set under the new name - Recreate all 6 indexes on the new table If the assertion fails, the migration throws inside the existing `transaction()` wrapper. SQLite rolls back the whole migration, old `runs` table is untouched, `schema_migrations` never records v35. Next app start retries cleanly. ## Migration v36 (drop tasks.is_heartbeat + synthetic rows) Runs now carry `task_id = NULL` for heartbeat dispatches. The `is_heartbeat` flag is dead data going forward. 1. `UPDATE runs SET task_id = NULL WHERE task_id IN (SELECT id FROM tasks WHERE is_heartbeat = 1)` 2. `DELETE FROM tasks WHERE is_heartbeat = 1` (synthetic rows, not real work) 3. Rebuild `tasks` without the `is_heartbeat` column (same defer-FK + row-count-assert pattern as v35) ## Code cleanup - `RunRecord.taskId: string | null`; `createRun` / `cancelRunForDeletion` / `finishRun` guard every `UPDATE tasks` path with a null-check. - `TaskRecord.isHeartbeat` removed; every SELECT / filter / UI reference dropped. - Delete `acquireHeartbeatTask` / `findReusableHeartbeatTask` / `cleanupDuplicateHeartbeatTasks` — dead after the constraint lifts. - Delete `src/main/orchestration/heartbeat-task.ts` (pure workaround constant file). - `heartbeat.ts` creates runs with `taskId: null` when the agent has no assigned work. Turn context already supports nullable task (heartbeatFallbackSection); prompt surface unchanged. - `validateTaskCreation` drops the `isHeartbeat` parameter — user- authored + automation-authored tasks are never heartbeat. - Renderer: `run.taskId ? taskMap.get(...) : undefined` in Dashboard / RunCenter / RunDetail / RunQueue. - Delete `tests/unit/heartbeat-coalescing.test.ts` (12 tests that exercised the deleted DB methods). - Drop 1 isHeartbeat-bypass test from `task-quality-gates.test.ts`. ## Grep verification - `isHeartbeatTaskTitle src/` → 0 - `acquireHeartbeatTask src/` → migration comment only - `is_heartbeat src/` → schema.ts migration history only - `isHeartbeat src/` → 0 Tests: 578/578 (was 591 — delta is 13 tests that tested deleted code).
This commit is contained in:
1 parent
92795f7bfb
commit
7e1d4199ee
44 files changed
+385
-674
No files matched your search
@@ -1,4 +1,3 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { TaskRecord } from "@shared/types";
|
||||
import {
|
||||
@@ -12,7 +11,7 @@ import { chooseBestTaskAssignee } from "./task-assignment";
|
||||
export function buildTaskStatusMethods(
|
||||
getDb: () => DatabaseSync,
|
||||
readAll: ReadAll,
|
||||
transaction: Transaction,
|
||||
_transaction: Transaction,
|
||||
deps: {
|
||||
addComment: (input: { companyId: string; taskId: string; authorAgentId: string | null; authorName: string; body: string }) => void;
|
||||
addActivity: (input: { companyId: string; actor: string; action: string; entityType: string; entityId: string; detail: string }) => void;
|
||||
@@ -102,152 +101,6 @@ export function buildTaskStatusMethods(
|
||||
return { previousStatus };
|
||||
},
|
||||
|
||||
findReusableHeartbeatTask(agentId: string, companyId: string): TaskRecord | null {
|
||||
const row = getDb()
|
||||
.prepare(
|
||||
`SELECT id, company_id as companyId, project_id as projectId, goal_id as goalId,
|
||||
parent_id as parentId, title, description,
|
||||
assignee_agent_id as assigneeAgentId, workspace_id as workspaceId,
|
||||
status, priority, active_run_id as activeRunId,
|
||||
session_json as sessionJson, session_display_id as sessionDisplayId,
|
||||
cost_usd as costUsd, requires_user_review as requiresUserReview,
|
||||
is_heartbeat as isHeartbeat,
|
||||
created_at as createdAt, updated_at as updatedAt
|
||||
FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('done', 'in_review')
|
||||
ORDER BY updated_at DESC, rowid DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(companyId, agentId) as TaskRecord | undefined;
|
||||
if (row) {
|
||||
row.requiresUserReview = Boolean(row.requiresUserReview);
|
||||
row.isHeartbeat = Boolean(row.isHeartbeat);
|
||||
}
|
||||
return row ?? null;
|
||||
},
|
||||
|
||||
acquireHeartbeatTask(input: {
|
||||
agentId: string;
|
||||
companyId: string;
|
||||
runId: string;
|
||||
workspaceId: string | null;
|
||||
title: string;
|
||||
description: string;
|
||||
priority: string;
|
||||
}): TaskRecord | null {
|
||||
return transaction<TaskRecord | null>(() => {
|
||||
const ts = nowIso();
|
||||
const db = getDb();
|
||||
|
||||
const claimable = db
|
||||
.prepare(
|
||||
`SELECT id, status FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('todo', 'backlog', 'done', 'in_review')
|
||||
AND checkout_run_id IS NULL
|
||||
ORDER BY
|
||||
CASE status WHEN 'todo' THEN 0 WHEN 'backlog' THEN 1 WHEN 'in_review' THEN 2 WHEN 'done' THEN 3 ELSE 4 END ASC,
|
||||
updated_at DESC, rowid DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(input.companyId, input.agentId) as { id: string; status: string } | undefined;
|
||||
|
||||
let taskId: string | null = null;
|
||||
if (claimable) {
|
||||
const claimResult = db
|
||||
.prepare(
|
||||
`UPDATE tasks
|
||||
SET checkout_run_id = ?, execution_locked_at = ?, status = 'in_progress',
|
||||
started_at = COALESCE(started_at, ?), completed_at = NULL, cancelled_at = NULL,
|
||||
updated_at = ?
|
||||
WHERE id = ? AND checkout_run_id IS NULL
|
||||
AND status IN ('todo', 'backlog', 'done', 'in_review')`,
|
||||
)
|
||||
.run(input.runId, ts, ts, ts, claimable.id);
|
||||
if (claimResult.changes > 0) {
|
||||
taskId = claimable.id;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const inflight = db
|
||||
.prepare(
|
||||
`SELECT 1 FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status NOT IN ('done', 'cancelled')
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(input.companyId, input.agentId);
|
||||
if (inflight) return null;
|
||||
|
||||
taskId = randomUUID();
|
||||
db.prepare(
|
||||
`INSERT INTO tasks
|
||||
(id, company_id, project_id, goal_id, parent_id, title, description,
|
||||
assignee_agent_id, workspace_id, status, priority,
|
||||
checkout_run_id, execution_locked_at, started_at, is_heartbeat,
|
||||
created_at, updated_at)
|
||||
VALUES (?, ?, NULL, NULL, NULL, ?, ?, ?, ?, 'in_progress', ?, ?, ?, ?, 1, ?, ?)`,
|
||||
).run(
|
||||
taskId,
|
||||
input.companyId,
|
||||
input.title,
|
||||
input.description,
|
||||
input.agentId,
|
||||
input.workspaceId,
|
||||
input.priority,
|
||||
input.runId,
|
||||
ts,
|
||||
ts,
|
||||
ts,
|
||||
ts,
|
||||
);
|
||||
}
|
||||
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id, company_id as companyId, project_id as projectId, goal_id as goalId,
|
||||
parent_id as parentId, title, description,
|
||||
assignee_agent_id as assigneeAgentId, workspace_id as workspaceId,
|
||||
status, priority, active_run_id as activeRunId,
|
||||
session_json as sessionJson, session_display_id as sessionDisplayId,
|
||||
cost_usd as costUsd, requires_user_review as requiresUserReview,
|
||||
is_heartbeat as isHeartbeat, task_type as taskType,
|
||||
started_at as startedAt, completed_at as completedAt, cancelled_at as cancelledAt,
|
||||
created_at as createdAt, updated_at as updatedAt
|
||||
FROM tasks WHERE id = ?`,
|
||||
)
|
||||
.get(taskId) as TaskRecord | undefined;
|
||||
if (!row) return null;
|
||||
row.requiresUserReview = Boolean(row.requiresUserReview);
|
||||
row.isHeartbeat = Boolean(row.isHeartbeat);
|
||||
row.startedAt = row.startedAt ?? null;
|
||||
row.completedAt = row.completedAt ?? null;
|
||||
row.cancelledAt = row.cancelledAt ?? null;
|
||||
return row;
|
||||
});
|
||||
},
|
||||
|
||||
cleanupDuplicateHeartbeatTasks(companyId: string): number {
|
||||
const ts = nowIso();
|
||||
const result = getDb()
|
||||
.prepare(
|
||||
`UPDATE tasks SET status = 'cancelled', updated_at = ?
|
||||
WHERE company_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('done', 'in_review', 'todo', 'blocked', 'backlog')
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (PARTITION BY assignee_agent_id ORDER BY updated_at DESC, rowid DESC) as rn
|
||||
FROM tasks
|
||||
WHERE company_id = ? AND is_heartbeat = 1 AND status != 'cancelled'
|
||||
) WHERE rn = 1
|
||||
)`,
|
||||
)
|
||||
.run(ts, companyId, companyId);
|
||||
return Number(result.changes);
|
||||
},
|
||||
|
||||
listReviewTasksForManager(managerId: string, companyId: string): TaskRecord[] {
|
||||
return readAll<TaskRecord>(
|
||||
`select t.id, t.company_id as companyId, t.project_id as projectId, t.goal_id as goalId,
|
||||
@@ -255,11 +108,11 @@ export function buildTaskStatusMethods(
|
||||
t.assignee_agent_id as assigneeAgentId, t.workspace_id as workspaceId,
|
||||
t.status, t.priority, t.active_run_id as activeRunId,
|
||||
t.session_json as sessionJson, t.session_display_id as sessionDisplayId,
|
||||
t.cost_usd as costUsd, t.is_heartbeat as isHeartbeat,
|
||||
t.cost_usd as costUsd,
|
||||
t.created_at as createdAt, t.updated_at as updatedAt
|
||||
from tasks t
|
||||
inner join agents a on t.assignee_agent_id = a.id
|
||||
where t.company_id = ? and t.status = 'in_review' and a.reports_to = ? and t.is_heartbeat = 0
|
||||
where t.company_id = ? and t.status = 'in_review' and a.reports_to = ?
|
||||
order by ${taskPriorityOrderSql("t.priority")} desc, t.created_at asc`,
|
||||
companyId,
|
||||
managerId,
|
||||
|
||||
Reference in new issue
Block a user