Restrict chat_sessions to server-owned sessions
chat_sessions now brokers GET /api/session but filters the global list to the sessions this server recorded in run_steps, deduped by session id, and fails closed to an empty list when no ownership source is configured. A session another client holds (in-server claim, released on stream end or disconnect) or an active run is marked busy; a second client's chat_prompt for a held session is rejected before any OpenCode call. chat_create stays unbrokered.
This commit is contained in:
@@ -26,6 +26,7 @@ input_json TEXT NOT NULL, output_json TEXT NOT NULL DEFAULT '{}', diagnostic TEX
|
||||
session_id TEXT NOT NULL DEFAULT '', agent_active INTEGER NOT NULL DEFAULT 0, transcript TEXT NOT NULL DEFAULT '',
|
||||
started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT, PRIMARY KEY(run_id,sequence));
|
||||
CREATE INDEX IF NOT EXISTS run_latest ON pipeline_runs(id DESC);
|
||||
CREATE INDEX IF NOT EXISTS run_steps_session ON run_steps(session_id);
|
||||
CREATE TABLE IF NOT EXISTS step_notifications (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, receipts_json TEXT NOT NULL,
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
@@ -335,6 +336,8 @@ type SessionOwner struct {
|
||||
// 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) {
|
||||
@@ -343,19 +346,54 @@ func (s *Store) RunSessionOwner(ctx context.Context, id int64, sequence int) (Se
|
||||
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) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,''),s.run_id
|
||||
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.agent_active=1 AND s.session_id<>''`)
|
||||
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 LIMIT ?"
|
||||
rows, err := s.db.QueryContext(ctx, query, sessionOwnerScanLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
seen := map[string]struct{}{}
|
||||
var owners []SessionOwner
|
||||
for rows.Next() {
|
||||
var owner SessionOwner
|
||||
if err = rows.Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference, &owner.RunID); err != nil {
|
||||
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()
|
||||
|
||||
@@ -149,3 +149,66 @@ func TestActiveAgentSessionsAreScopedToRun(t *testing.T) {
|
||||
t.Fatalf("second run's own session was affected: %v %v", sessions, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOwnedSessionsListsRecordedWithActiveFlag proves OwnedSessions returns every
|
||||
// session the server ever recorded (active or not) in run_steps, deduped by
|
||||
// session id in favour of the newest owning run, with that run's workspace
|
||||
// directory and the active flag.
|
||||
func TestOwnedSessionsListsRecordedWithActiveFlag(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "owned.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "owned", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
definition, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record := func(key, workspace, session string, active bool) {
|
||||
t.Helper()
|
||||
run, _, err := store.CreateRun(ctx, definition, key, workspace, false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, run, 1, "one", map[string]any{"prompt": "task"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.RunSession(ctx, run, 1, session, active, "v2", "/repo"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
record("owned-a", "/work/a", "ses_active", true)
|
||||
record("owned-b", "/work/b", "ses_idle", false)
|
||||
// The same session recorded by a newer run must dedupe to one entry, taking
|
||||
// the newest run's workspace and active flag.
|
||||
record("owned-c", "/work/c", "ses_idle", true)
|
||||
|
||||
owners, err := store.OwnedSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(owners) != 2 {
|
||||
t.Fatalf("owned sessions = %+v, want 2 deduped", owners)
|
||||
}
|
||||
byID := map[string]SessionOwner{}
|
||||
for _, owner := range owners {
|
||||
byID[owner.ID] = owner
|
||||
}
|
||||
if owner, ok := byID["ses_active"]; !ok || !owner.Active || owner.Directory != "/work/a" {
|
||||
t.Fatalf("active owner = %+v", owner)
|
||||
}
|
||||
if owner, ok := byID["ses_idle"]; !ok || !owner.Active || owner.Directory != "/work/c" {
|
||||
t.Fatalf("deduped owner should come from the newest run: %+v", owner)
|
||||
}
|
||||
if active, err := store.ActiveSessionOwners(ctx); err != nil || len(active) != 2 {
|
||||
t.Fatalf("ActiveSessionOwners = %+v %v, want both now-active sessions", active, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user