package pipeline import ( "context" ) func (s *Store) RunSession(ctx context.Context, id int64, sequence int, session string, active bool, metadata ...string) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() if err = affected(tx.ExecContext(ctx, "UPDATE run_steps SET session_id=?,agent_active=? WHERE run_id=? AND sequence=? AND status='running'", session, active, id, sequence)); err != nil { return err } if len(metadata) > 0 { backend := metadata[0] if backend == "" { backend = "v2" } reference := "" if len(metadata) > 1 { reference = metadata[1] } if _, err = tx.ExecContext(ctx, "INSERT INTO run_session_owners(run_id,sequence,backend,reference) VALUES(?,?,?,?) ON CONFLICT(run_id,sequence) DO UPDATE SET backend=excluded.backend,reference=excluded.reference", id, sequence, backend, reference); err != nil { return err } } return tx.Commit() } // ConfirmRecoveredSession clears the agent-active marker after startup has // interrupted a previously active session, so it no longer blocks new work. func (s *Store) ConfirmRecoveredSession(ctx context.Context, owner SessionOwner) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET agent_active=0 WHERE run_id=? AND session_id=?", owner.RunID, owner.ID); err != nil { return err } if _, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET cleanup_unconfirmed=0 WHERE id=? AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=? AND agent_active=1)`, owner.RunID, owner.RunID); err != nil { return err } return tx.Commit() } type SessionOwner struct { ID string Backend string Directory string Reference string // RunID is the owning run, used to tell an orphaned session (no active run) // from one owned by a run that is active right now. RunID int64 // Active is true while the owning step records the session as agent-active. Active bool } func (s *Store) RunSessionOwner(ctx context.Context, id int64, sequence int) (SessionOwner, error) { var owner SessionOwner err := s.db.QueryRowContext(ctx, `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,'') FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id LEFT JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.run_id=? AND s.sequence=?`, id, sequence).Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference) return owner, err } // sessionOwnerScanLimit bounds the ownership scan so a long-lived database with // thousands of historical sessions cannot make one chat_sessions request scan // them all. Rows are read newest-run first, so the bound only ever drops the // oldest owners, never the sessions a client can still be writing. const sessionOwnerScanLimit = 1024 // ActiveSessionOwners reports every currently active agent session, deduped by // session id (newest owning run wins). func (s *Store) ActiveSessionOwners(ctx context.Context) ([]SessionOwner, error) { return s.sessionOwners(ctx, true) } // OwnedSessions reports every session the server ever recorded in run_steps, // deduped by session id (newest owning run wins) and including inactive ones, so // chat_sessions can be restricted to sessions this server created. func (s *Store) OwnedSessions(ctx context.Context) ([]SessionOwner, error) { return s.sessionOwners(ctx, false) } // sessionOwners is the single ownership query both ActiveSessionOwners and // OwnedSessions run, so the SQL is not duplicated. It reads one bounded, // newest-run-first window and drops repeated session ids in favour of the most // recent owning run's directory and active flag. func (s *Store) sessionOwners(ctx context.Context, activeOnly bool) ([]SessionOwner, error) { query := `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,''),s.run_id,s.agent_active FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id LEFT JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.session_id<>''` if activeOnly { query += " AND s.agent_active=1" } query += " ORDER BY s.run_id DESC" var args []any if !activeOnly { query += " LIMIT ?" args = append(args, sessionOwnerScanLimit) } // Recovery cannot silently drop old but still-active owners at the history cap. rows, err := s.db.QueryContext(ctx, query, args...) if err != nil { return nil, err } defer rows.Close() seen := map[string]struct{}{} var owners []SessionOwner for rows.Next() { var owner SessionOwner var active int if err = rows.Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference, &owner.RunID, &active); err != nil { return nil, err } owner.Active = active != 0 if _, ok := seen[owner.ID]; ok { continue } seen[owner.ID] = struct{}{} owners = append(owners, owner) } return owners, rows.Err() } // ActiveAgentSessionsForRun returns the distinct active agent session ids that // belong to one run. It is scoped to run_steps.run_id so concurrent runs never // observe each other's sessions: run_steps is keyed by (run_id, sequence), so // this is one indexed lookup, not a scan. func (s *Store) ActiveAgentSessionsForRun(ctx context.Context, runID int64) ([]string, error) { rows, err := s.db.QueryContext(ctx, "SELECT DISTINCT session_id FROM run_steps WHERE run_id=? AND agent_active=1 AND session_id<>''", runID) if err != nil { return nil, err } defer rows.Close() ids := []string{} for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return nil, err } ids = append(ids, id) } return ids, rows.Err() }