fix(executors): truthful executor rows, startup reconciliation, resume-safe cleanup (#1597) (#1608)

Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
point-source
2026-07-08 15:37:02 -07:00
committed by GitHub
parent bd22a1318c
commit e1cf99f821
37 changed files with 1855 additions and 99 deletions
@@ -46,6 +46,11 @@ func (r *Repository) migrateSessionsAddCostColumns() {
func (r *Repository) runMigrations() error {
r.migrate.Apply("executors_running.last_message_uuid", `ALTER TABLE executors_running ADD COLUMN last_message_uuid TEXT DEFAULT ''`)
r.migrate.Apply("executors_running.metadata", `ALTER TABLE executors_running ADD COLUMN metadata TEXT DEFAULT '{}'`)
// local_pid holds a host-local liveness handle (the standalone agentctl
// control-server PID Kandev spawns) for local/standalone rows. It is kept
// deliberately separate from the SSH-only `pid` column, which holds an
// agentctl PID on the *remote* host. See ADR 0025 / issue #1597.
r.migrate.Apply("executors_running.local_pid", `ALTER TABLE executors_running ADD COLUMN local_pid INTEGER DEFAULT 0`)
r.migrate.Apply("tasks.is_ephemeral", `ALTER TABLE tasks ADD COLUMN is_ephemeral INTEGER NOT NULL DEFAULT 0`)
r.migrate.Apply("task_repositories.checkout_branch", `ALTER TABLE task_repositories ADD COLUMN checkout_branch TEXT DEFAULT ''`)
// Multi-branch support: drop the old UNIQUE(task_id, repository_id) and
@@ -176,6 +176,7 @@ const infraSchemaDDL = `
agentctl_url TEXT DEFAULT '',
agentctl_port INTEGER DEFAULT 0,
pid INTEGER DEFAULT 0,
local_pid INTEGER DEFAULT 0,
worktree_id TEXT DEFAULT '',
worktree_path TEXT DEFAULT '',
worktree_branch TEXT DEFAULT '',
@@ -164,10 +164,10 @@ func (r *Repository) UpsertExecutorRunning(ctx context.Context, running *models.
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
INSERT INTO executors_running (
id, session_id, task_id, executor_id, runtime, status, resumable, resume_token,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid, local_pid,
worktree_id, worktree_path, worktree_branch, last_seen_at, error_message, metadata,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id) DO UPDATE SET
id = excluded.id,
task_id = excluded.task_id,
@@ -182,6 +182,7 @@ func (r *Repository) UpsertExecutorRunning(ctx context.Context, running *models.
agentctl_url = excluded.agentctl_url,
agentctl_port = excluded.agentctl_port,
pid = excluded.pid,
local_pid = excluded.local_pid,
worktree_id = excluded.worktree_id,
worktree_path = excluded.worktree_path,
worktree_branch = excluded.worktree_branch,
@@ -204,6 +205,7 @@ func (r *Repository) UpsertExecutorRunning(ctx context.Context, running *models.
running.AgentctlURL,
running.AgentctlPort,
running.PID,
running.LocalPID,
running.WorktreeID,
running.WorktreePath,
running.WorktreeBranch,
@@ -219,7 +221,7 @@ func (r *Repository) UpsertExecutorRunning(ctx context.Context, running *models.
func (r *Repository) ListExecutorsRunning(ctx context.Context) ([]*models.ExecutorRunning, error) {
rows, err := r.ro.QueryContext(ctx, `
SELECT id, session_id, task_id, executor_id, runtime, status, resumable, resume_token,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid, local_pid,
worktree_id, worktree_path, worktree_branch, last_seen_at, error_message, metadata,
created_at, updated_at
FROM executors_running
@@ -239,7 +241,7 @@ func (r *Repository) ListExecutorsRunningByTaskID(ctx context.Context, taskID st
}
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
SELECT id, session_id, task_id, executor_id, runtime, status, resumable, resume_token,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid, local_pid,
worktree_id, worktree_path, worktree_branch, last_seen_at, error_message, metadata,
created_at, updated_at
FROM executors_running
@@ -265,7 +267,7 @@ func (r *Repository) GetExecutorRunningBySessionID(ctx context.Context, sessionI
err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
SELECT id, session_id, task_id, executor_id, runtime, status, resumable, resume_token,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid,
last_message_uuid, agent_execution_id, container_id, agentctl_url, agentctl_port, pid, local_pid,
worktree_id, worktree_path, worktree_branch, last_seen_at, error_message, metadata,
created_at, updated_at
FROM executors_running
@@ -285,6 +287,7 @@ func (r *Repository) GetExecutorRunningBySessionID(ctx context.Context, sessionI
&running.AgentctlURL,
&running.AgentctlPort,
&running.PID,
&running.LocalPID,
&running.WorktreeID,
&running.WorktreePath,
&running.WorktreeBranch,
@@ -336,6 +339,7 @@ func scanExecutorRunningRows(rows *sql.Rows) ([]*models.ExecutorRunning, error)
&running.AgentctlURL,
&running.AgentctlPort,
&running.PID,
&running.LocalPID,
&running.WorktreeID,
&running.WorktreePath,
&running.WorktreeBranch,
@@ -448,6 +452,36 @@ func (r *Repository) UpdateResumeToken(ctx context.Context, sessionID, expectedE
return nil
}
// RepairExecutorRunningDead repairs a row in place to reflect that its backing
// process is gone, WITHOUT deleting it. The resume-safety invariant requires a
// resumable / non-terminal row be repaired rather than pruned
// (#1597 resume-safety invariant): flip status to "stopped", clear the local
// liveness handle (local_pid = 0) so the row no longer claims a live process,
// and re-stamp last_seen_at as a fresh liveness observation. resume_token,
// worktree, and endpoint columns are intentionally preserved so the session
// stays resumable.
//
// Returns ErrExecutorRunningNotFound when no row exists for the session.
func (r *Repository) RepairExecutorRunningDead(ctx context.Context, sessionID string) error {
if sessionID == "" {
return fmt.Errorf("session_id is required")
}
now := time.Now().UTC()
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
UPDATE executors_running
SET status = ?, local_pid = 0, last_seen_at = ?, updated_at = ?
WHERE session_id = ?
`), models.ExecutorRunningStatusStopped, now, now, sessionID)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return fmt.Errorf("%w for session: %s", models.ErrExecutorRunningNotFound, sessionID)
}
return nil
}
// UpdateExecutorRunningStatus narrowly updates the status column.
// Returns ErrExecutorRunningNotFound when no row exists for the session.
func (r *Repository) UpdateExecutorRunningStatus(ctx context.Context, sessionID, status string) error {
@@ -0,0 +1,275 @@
package sqlite
import (
"context"
"errors"
"testing"
"time"
"github.com/kandev/kandev/internal/agentruntime"
"github.com/kandev/kandev/internal/task/models"
)
// TestExecutorRunningLocalPIDRoundTrips proves the local_pid column is an
// independent, fully-plumbed column: it is written by UpsertExecutorRunning and
// read back by GetExecutorRunningBySessionID / ListExecutorsRunning without
// aliasing the SSH-only pid column. This is the schema half of the #1597
// executor-row-desync fix (#1597 truthful executor rows): a local/standalone row
// must be able to carry a real host-local liveness handle distinct from the
// remote-host SSH pid.
func TestExecutorRunningLocalPIDRoundTrips(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
lastSeen := time.Now().UTC().Truncate(time.Second)
seedExecutorRunningCleanupTask(t, repo, "task-1")
if err := repo.CreateTaskSession(ctx, &models.TaskSession{
ID: "session-local",
TaskID: "task-1",
State: models.TaskSessionStateRunning,
}); err != nil {
t.Fatalf("CreateTaskSession(session-local): %v", err)
}
// A local/standalone row: local_pid is the host-local agentctl PID, pid is
// 0 (SSH-only, no remote host). last_seen_at reflects a real observation.
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-local",
SessionID: "session-local",
TaskID: "task-1",
ExecutorID: "exec-local",
Runtime: agentruntime.RuntimeStandalone,
Status: models.ExecutorRunningStatusReady,
Resumable: true,
AgentctlURL: "http://127.0.0.1:8765",
AgentctlPort: 8765,
PID: 0,
LocalPID: 424242,
LastSeenAt: &lastSeen,
}); err != nil {
t.Fatalf("UpsertExecutorRunning(session-local): %v", err)
}
got, err := repo.GetExecutorRunningBySessionID(ctx, "session-local")
if err != nil {
t.Fatalf("GetExecutorRunningBySessionID: %v", err)
}
if got.LocalPID != 424242 {
t.Fatalf("local_pid not persisted/read: got %d want 424242", got.LocalPID)
}
if got.PID != 0 {
t.Fatalf("pid must stay independent of local_pid: got %d want 0", got.PID)
}
if got.Status != models.ExecutorRunningStatusReady {
t.Fatalf("status not persisted: got %q want %q", got.Status, models.ExecutorRunningStatusReady)
}
if got.LastSeenAt == nil || !got.LastSeenAt.Equal(lastSeen) {
t.Fatalf("last_seen_at not persisted: got %v want %v", got.LastSeenAt, lastSeen)
}
// The upsert path (ON CONFLICT) must update local_pid too, not just insert it.
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-local",
SessionID: "session-local",
TaskID: "task-1",
ExecutorID: "exec-local",
Runtime: agentruntime.RuntimeStandalone,
Status: models.ExecutorRunningStatusReady,
LocalPID: 515151,
}); err != nil {
t.Fatalf("UpsertExecutorRunning(update local_pid): %v", err)
}
got, err = repo.GetExecutorRunningBySessionID(ctx, "session-local")
if err != nil {
t.Fatalf("GetExecutorRunningBySessionID(after update): %v", err)
}
if got.LocalPID != 515151 {
t.Fatalf("local_pid not updated on conflict: got %d want 515151", got.LocalPID)
}
// list path must scan the column too.
rows, err := repo.ListExecutorsRunning(ctx)
if err != nil {
t.Fatalf("ListExecutorsRunning: %v", err)
}
var found bool
for _, row := range rows {
if row.SessionID == "session-local" {
found = true
if row.LocalPID != 515151 {
t.Fatalf("list did not scan local_pid: got %d want 515151", row.LocalPID)
}
}
}
if !found {
t.Fatalf("session-local row missing from ListExecutorsRunning")
}
}
// TestExecutorRunningLocalPIDSeparateFromSSHPID guards the #1597 pid-semantics rule
// that a local liveness handle must never overload the SSH pid column: an SSH row
// carries pid (remote host) with local_pid==0, and a local row carries local_pid
// with pid==0, and neither leaks into the other.
func TestExecutorRunningLocalPIDSeparateFromSSHPID(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
seedExecutorRunningCleanupTask(t, repo, "task-1")
if err := repo.CreateTaskSession(ctx, &models.TaskSession{ID: "session-ssh", TaskID: "task-1", State: models.TaskSessionStateRunning}); err != nil {
t.Fatalf("CreateTaskSession(session-ssh): %v", err)
}
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-ssh",
SessionID: "session-ssh",
TaskID: "task-1",
ExecutorID: "exec-ssh",
Runtime: agentruntime.RuntimeSSH,
Status: models.ExecutorRunningStatusRunning,
PID: 9999, // remote-host agentctl pid
LocalPID: 0,
}); err != nil {
t.Fatalf("UpsertExecutorRunning(session-ssh): %v", err)
}
got, err := repo.GetExecutorRunningBySessionID(ctx, "session-ssh")
if err != nil {
t.Fatalf("GetExecutorRunningBySessionID(session-ssh): %v", err)
}
if got.PID != 9999 {
t.Fatalf("ssh pid clobbered: got %d want 9999", got.PID)
}
if got.LocalPID != 0 {
t.Fatalf("ssh row must not carry a local_pid: got %d want 0", got.LocalPID)
}
}
// TestRepairExecutorRunningDead proves the repair-in-place primitive of the
// resume-safety invariant (#1597 resume-safety invariant): a row whose process is
// gone is marked stopped with its local liveness handle cleared, WITHOUT losing
// the resume_token / worktree that keep the session resumable.
func TestRepairExecutorRunningDead(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
seedExecutorRunningCleanupTask(t, repo, "task-1")
if err := repo.CreateTaskSession(ctx, &models.TaskSession{ID: "session-r", TaskID: "task-1", State: models.TaskSessionStateWaitingForInput}); err != nil {
t.Fatalf("CreateTaskSession(session-r): %v", err)
}
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-r",
SessionID: "session-r",
TaskID: "task-1",
ExecutorID: "exec-local",
Runtime: agentruntime.RuntimeStandalone,
Status: models.ExecutorRunningStatusRunning,
Resumable: true,
ResumeToken: "acp-resume-xyz",
WorktreePath: "/tmp/wt/session-r",
WorktreeBranch: "feature/x",
LocalPID: 777777,
}); err != nil {
t.Fatalf("UpsertExecutorRunning(session-r): %v", err)
}
if err := repo.RepairExecutorRunningDead(ctx, "session-r"); err != nil {
t.Fatalf("RepairExecutorRunningDead: %v", err)
}
got, err := repo.GetExecutorRunningBySessionID(ctx, "session-r")
if err != nil {
t.Fatalf("GetExecutorRunningBySessionID(session-r): %v", err)
}
if got.Status != models.ExecutorRunningStatusStopped {
t.Fatalf("repair status: got %q want stopped", got.Status)
}
if got.LocalPID != 0 {
t.Fatalf("repair must clear the local liveness handle: got local_pid=%d", got.LocalPID)
}
if got.ResumeToken != "acp-resume-xyz" {
t.Fatalf("repair must preserve resume_token: got %q", got.ResumeToken)
}
if got.WorktreePath != "/tmp/wt/session-r" || got.WorktreeBranch != "feature/x" {
t.Fatalf("repair must preserve worktree columns: got path=%q branch=%q", got.WorktreePath, got.WorktreeBranch)
}
if got.LastSeenAt == nil {
t.Fatal("repair must stamp a fresh last_seen_at observation")
}
// Missing row → ErrExecutorRunningNotFound (idempotent-friendly for callers).
if err := repo.RepairExecutorRunningDead(ctx, "no-such-session"); !errors.Is(err, models.ErrExecutorRunningNotFound) {
t.Fatalf("repair on missing row: got %v want ErrExecutorRunningNotFound", err)
}
}
// TestExecutorRunningLocalPIDMigrationOnLegacyDB is the same-database replay test
// mandated by ADR 0027 for a schema change: it proves the `local_pid` ADD COLUMN
// migration upgrades a DB that PREDATES the column, adding it with the default
// while leaving existing rows intact and readable. This is the real production
// upgrade path — the operator's existing executors_running rows (all pid=0) gain
// local_pid=0 on first boot of the new binary, not a fresh install.
func TestExecutorRunningLocalPIDMigrationOnLegacyDB(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
// Seed a row on the current (migrated) schema.
seedExecutorRunningCleanupTask(t, repo, "task-legacy")
if err := repo.CreateTaskSession(ctx, &models.TaskSession{
ID: "session-legacy", TaskID: "task-legacy", State: models.TaskSessionStateWaitingForInput,
}); err != nil {
t.Fatalf("CreateTaskSession: %v", err)
}
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-legacy",
SessionID: "session-legacy",
TaskID: "task-legacy",
ExecutorID: "exec-legacy",
Runtime: agentruntime.RuntimeStandalone,
Status: models.ExecutorRunningStatusStarting,
Resumable: true,
ResumeToken: "legacy-resume-token",
LocalPID: 321,
}); err != nil {
t.Fatalf("UpsertExecutorRunning: %v", err)
}
// Rewind to a pre-local_pid schema: drop the column so the row now looks like
// one written by an older binary that never had it.
if _, err := repo.db.Exec(`ALTER TABLE executors_running DROP COLUMN local_pid`); err != nil {
t.Fatalf("simulate legacy schema (drop local_pid): %v", err)
}
// Re-run migrations, exactly as a boot of the new binary would. The
// idempotent ADD COLUMN must re-add local_pid without erroring.
if err := repo.runMigrations(); err != nil {
t.Fatalf("runMigrations on legacy DB: %v", err)
}
// The pre-existing row survives, is readable, and its resume_token is intact —
// the migration must not drop rows. local_pid comes back as the column default
// (0) for a row that predated the column.
got, err := repo.GetExecutorRunningBySessionID(ctx, "session-legacy")
if err != nil {
t.Fatalf("legacy row must survive the migration: %v", err)
}
if got.LocalPID != 0 {
t.Errorf("legacy row local_pid = %d, want 0 (column default after ADD COLUMN)", got.LocalPID)
}
if got.ResumeToken != "legacy-resume-token" {
t.Errorf("resume_token lost across migration: got %q", got.ResumeToken)
}
if got.Status != models.ExecutorRunningStatusStarting {
t.Errorf("status lost across migration: got %q", got.Status)
}
// And the re-added column is fully usable: a repair writes/reads local_pid=0.
if err := repo.RepairExecutorRunningDead(ctx, "session-legacy"); err != nil {
t.Fatalf("repair after migration: %v", err)
}
repaired, err := repo.GetExecutorRunningBySessionID(ctx, "session-legacy")
if err != nil {
t.Fatalf("read after repair: %v", err)
}
if repaired.Status != models.ExecutorRunningStatusStopped || repaired.LocalPID != 0 {
t.Errorf("re-added local_pid column must be writable; got status=%q local_pid=%d", repaired.Status, repaired.LocalPID)
}
}
@@ -5,10 +5,68 @@ import (
"testing"
"time"
"github.com/kandev/kandev/internal/agentruntime"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/testutil"
)
// TestPostgresExecutorRunningLocalPIDMigration is the Postgres counterpart to
// TestExecutorRunningLocalPIDMigrationOnLegacyDB (SQLite): local_pid is on the
// shared migration path, so ADR 0027 asks for env-gated Postgres replay coverage
// too. It rewinds to a pre-local_pid schema, re-runs migrations, and asserts the
// ADD COLUMN re-adds the column with its default while an existing row survives.
// Skips unless KANDEV_TEST_POSTGRES_DSN is set.
func TestPostgresExecutorRunningLocalPIDMigration(t *testing.T) {
db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t))
repo, err := NewWithDB(db, db, nil)
if err != nil {
t.Fatalf("init postgres schema: %v", err)
}
ctx := context.Background()
now := time.Now().UTC()
if _, err := db.Exec(db.Rebind(`
INSERT INTO tasks (id, workspace_id, title, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`), "task-pg", "ws-task-pg", "Task pg", now, now); err != nil {
t.Fatalf("seed task: %v", err)
}
if err := repo.CreateTaskSession(ctx, &models.TaskSession{
ID: "session-pg", TaskID: "task-pg", State: models.TaskSessionStateWaitingForInput,
}); err != nil {
t.Fatalf("CreateTaskSession: %v", err)
}
if err := repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "session-pg", SessionID: "session-pg", TaskID: "task-pg", ExecutorID: "exec-pg",
Runtime: agentruntime.RuntimeStandalone, Status: models.ExecutorRunningStatusStarting,
Resumable: true, ResumeToken: "pg-resume-token", LocalPID: 321,
}); err != nil {
t.Fatalf("UpsertExecutorRunning: %v", err)
}
// Rewind to a pre-local_pid schema, then re-migrate as a new-binary boot would.
if _, err := db.Exec(`ALTER TABLE executors_running DROP COLUMN local_pid`); err != nil {
t.Fatalf("simulate legacy schema (drop local_pid): %v", err)
}
if err := repo.runMigrations(); err != nil {
t.Fatalf("runMigrations on legacy postgres DB: %v", err)
}
got, err := repo.GetExecutorRunningBySessionID(ctx, "session-pg")
if err != nil {
t.Fatalf("legacy row must survive the migration: %v", err)
}
if got.LocalPID != 0 {
t.Errorf("legacy row local_pid = %d, want 0 (column default after ADD COLUMN)", got.LocalPID)
}
if got.ResumeToken != "pg-resume-token" {
t.Errorf("resume_token lost across migration: got %q", got.ResumeToken)
}
if got.Status != models.ExecutorRunningStatusStarting {
t.Errorf("status lost across migration: got %q", got.Status)
}
}
func TestPostgresSchemaReinitializes(t *testing.T) {
db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t))