Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Make session listing O(changed files), not O(all transcript bytes)

rcourtmanab01e56db03d
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index ce987a9f24..003258fd58 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -1441,6 +1441,16 @@ deriving an older display status from `workflowStatusHistory`.
atomically readable through temp-file plus rename so a large recent-session
list cannot block `EnsureSession`, `AddMessage`, or stored handoff reads on
a new prompt.
+ Session listing cost must not scale with stored transcript bytes.
+ `SessionStore.List` serves summaries from a per-file cache validated by
+ each file's (modTime, size), re-reading only files that changed since the
+ last list, and a cache-miss parse must not deep-decode message or redo
+ payloads (only their counts feed the summary). The cache persists as
+ `.sessions_index.json` beside the session files so the first list after a
+ restart stays index-speed; the index is best-effort and self-healing
+ (missing, corrupt, or stale entries only cost a re-parse, never a wrong
+ summary, and dotfiles are never listed as sessions). `writeSession` and
+ `Delete` keep the cache and index coherent on every mutation.
Assistant session navigation must provide a searchable history path in the
drawer-owned picker, using the canonical `/api/ai/sessions` contract rather
than a separate recent-chat store. Search is applied before result limiting
@@ -2297,7 +2307,13 @@ deriving an older display status from `workflowStatusHistory`.
from the canonical approval store and action-audit store. Session listing is
an operator decision surface, so it must not leave stale pending/approval
labels in the drawer after the governed action moved on, and it must still
- omit raw commands, preflight bodies, and execution output.
+ omit raw commands, preflight bodies, and execution output. That refresh is
+ bounded, not exhaustive: the list is newest-first and only the
+ `maxSessionHandoffRefreshPerList` (20) most recent action-carrying
+ sessions are re-checked per list call, which covers every summary the
+ recent-sessions surface and picker top present; deeper history self-heals
+ because the send path refreshes the active session's handoff actions on
+ load before the turn executes.
The Assistant drawer must also fetch that current session list before
opening the session picker instead of presenting mount-time cached
summaries as the operator's decision surface. For restored Patrol
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index cfd7591a8e..e6c5ba5745 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -2956,6 +2956,12 @@ func (s *Service) ListAvailableTools(ctx context.Context, prompt string) []strin
}
// ListSessions returns all sessions
+// maxSessionHandoffRefreshPerList bounds how many sessions get their handoff
+// action status re-checked per list call. The list is newest-first, so this
+// covers every session the recent-sessions UI surfaces; older sessions
+// self-heal when loaded (the turn path refreshes the active session).
+const maxSessionHandoffRefreshPerList = 20
+
func (s *Service) ListSessions(ctx context.Context) ([]Session, error) {
s.mu.RLock()
sessions := s.sessions
@@ -2967,25 +2973,36 @@ func (s *Service) ListSessions(ctx context.Context) ([]Session, error) {
return nil, fmt.Errorf("service not started")
}
- refreshSessionHandoffActionSummaries(sessions, orgID, actionAuditStore)
- return sessions.List()
+ list, err := sessions.List()
+ if err != nil {
+ return nil, err
+ }
+ if refreshSessionHandoffActionSummaries(sessions, orgID, actionAuditStore, list) {
+ // Some summaries were rewritten on disk; re-list (cheap, cached) so
+ // the response carries the refreshed action status.
+ return sessions.List()
+ }
+ return list, nil
}
-func refreshSessionHandoffActionSummaries(sessions *SessionStore, orgID string, actionStore unifiedresources.ResourceStore) {
+// refreshSessionHandoffActionSummaries re-checks handoff action status against
+// the action audit store for the most recent sessions that carry actions.
+// It returns true when at least one session summary was rewritten.
+func refreshSessionHandoffActionSummaries(sessions *SessionStore, orgID string, actionStore unifiedresources.ResourceStore, list []Session) bool {
if sessions == nil {
- return
- }
-
- list, err := sessions.List()
- if err != nil {
- log.Debug().Err(err).Msg("[ChatService] Failed to list sessions for handoff action refresh")
- return
+ return false
}
+ updated := false
+ checked := 0
for _, session := range list {
+ if checked >= maxSessionHandoffRefreshPerList {
+ break
+ }
if session.HandoffSummary == nil || session.HandoffSummary.ActionCount == 0 {
continue
}
+ checked++
actions, err := sessions.GetModelHandoffActions(session.ID)
if err != nil {
log.Debug().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to load session handoff actions for summary refresh")
@@ -2997,8 +3014,11 @@ func refreshSessionHandoffActionSummaries(sessions *SessionStore, orgID string,
}
if err := sessions.SetModelHandoffActions(session.ID, refreshed); err != nil {
log.Debug().Err(err).Str("session_id", session.ID).Msg("[ChatService] Failed to persist refreshed session handoff action summary")
+ continue
}
+ updated = true
}
+ return updated
}
func handoffActionsEqual(a, b []HandoffAction) bool {
diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.go
index 47093d431b..1fb106832a 100644
--- a/internal/ai/chat/session.go
+++ b/internal/ai/chat/session.go
@@ -39,6 +39,43 @@ type SessionStore struct {
// These extract and preserve key facts from tool results to prevent amnesia
// when old tool results are compacted from the conversation context.
knowledgeAccumulators map[string]*KnowledgeAccumulator
+
+ // summaryMu guards summaryCache. It is a leaf lock: never acquire s.mu
+ // while holding it. List() must stay off s.mu (see
+ // TestSessionStoreListDoesNotHoldStoreMutex), so the cache has its own.
+ summaryMu sync.Mutex
+ // summaryCache holds per-file session summaries keyed by file name,
+ // validated by (modTime, size). Listing sessions must not scale with
+ // transcript bytes: a session file is only re-read when it changed.
+ summaryCache map[string]sessionSummaryCacheEntry
+
+ // indexMu serializes summary index file writes.
+ indexMu sync.Mutex
+}
+
+type sessionSummaryCacheEntry struct {
+ modTime time.Time
+ size int64
+ summary Session
+}
+
+// sessionSummaryIndexFile persists the summary cache across restarts so the
+// first List() after boot does not re-read every transcript. Entries are
+// validated against each file's (modTime, size) before use, so a stale or
+// hand-edited index only costs a re-parse, never a wrong summary.
+const sessionSummaryIndexFile = ".sessions_index.json"
+
+const sessionSummaryIndexVersion = 1
+
+type sessionSummaryIndexEntry struct {
+ ModTime time.Time `json:"mod_time"`
+ Size int64 `json:"size"`
+ Summary Session `json:"summary"`
+}
+
+type sessionSummaryIndexData struct {
+ Version int `json:"version"`
+ Entries map[string]sessionSummaryIndexEntry `json:"entries"`
}
const maxSessionTurnRedoStack = 10
@@ -391,6 +428,31 @@ func sessionSummaryFromData(data sessionData) Session {
}
}
+// sessionListData decodes only what a session summary needs. Message and redo
+// payloads stay as raw JSON so listing cost does not scale with transcript
+// size — only their counts matter here.
+type sessionListData struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Messages []json.RawMessage `json:"messages"`
+ ModelContext *sessionModelContext `json:"model_context,omitempty"`
+ TurnRedoStack []json.RawMessage `json:"turn_redo_stack,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+func sessionSummaryFromListData(data sessionListData) Session {
+ return Session{
+ ID: data.ID,
+ Title: data.Title,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ MessageCount: len(data.Messages),
+ CanRedo: len(data.TurnRedoStack) > 0,
+ HandoffSummary: modelContextHandoffSummary(data.ModelContext),
+ }
+}
+
const (
maxSessionIDLength = 128
maxSessionTitleRunes = 120
@@ -405,13 +467,16 @@ func NewSessionStore(dataDir string) (*SessionStore, error) {
return nil, fmt.Errorf("failed to create sessions directory: %w", err)
}
- return &SessionStore{
+ store := &SessionStore{
dataDir: sessionsDir,
resolvedContexts: make(map[string]*ResolvedContext),
sessionFSMs: make(map[string]*SessionFSM),
sessionToolSets: make(map[string]map[string]bool),
knowledgeAccumulators: make(map[string]*KnowledgeAccumulator),
- }, nil
+ summaryCache: make(map[string]sessionSummaryCacheEntry),
+ }
+ store.loadSummaryIndex()
+ return store, nil
}
// sessionPath returns the file path for a session
@@ -485,40 +550,75 @@ func (s *SessionStore) findLegacySessionPath(id string) (string, error) {
return "", nil
}
-// List returns all sessions, sorted by updated_at descending
+// List returns all sessions, sorted by updated_at descending.
+// Summaries are served from a per-file cache validated by (modTime, size);
+// only files that changed since the last call are re-read and re-parsed.
func (s *SessionStore) List() ([]Session, error) {
entries, err := os.ReadDir(s.dataDir)
if err != nil {
return nil, fmt.Errorf("failed to read sessions directory: %w", err)
}
+ seen := make(map[string]struct{}, len(entries))
+ cacheChanged := false
var sessions []Session
for _, entry := range entries {
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
+ name := entry.Name()
+ if entry.IsDir() || strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".json") {
continue
}
+ info, err := entry.Info()
+ if err != nil {
+ log.Warn().Err(err).Str("file", name).Msg("failed to stat session file")
+ continue
+ }
+ seen[name] = struct{}{}
- path, err := securityutil.JoinStorageLeaf(s.dataDir, entry.Name())
+ s.summaryMu.Lock()
+ cached, ok := s.summaryCache[name]
+ s.summaryMu.Unlock()
+ if ok && cached.modTime.Equal(info.ModTime()) && cached.size == info.Size() {
+ sessions = append(sessions, cached.summary)
+ continue
+ }
+
+ path, err := securityutil.JoinStorageLeaf(s.dataDir, name)
if err != nil {
- log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to resolve session file path")
+ log.Warn().Err(err).Str("file", name).Msg("failed to resolve session file path")
continue
}
file, err := os.ReadFile(path)
if err != nil {
- log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to read session file")
+ log.Warn().Err(err).Str("file", name).Msg("failed to read session file")
continue
}
- var data sessionData
+ var data sessionListData
if err := json.Unmarshal(file, &data); err != nil {
- log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to parse session file")
+ log.Warn().Err(err).Str("file", name).Msg("failed to parse session file")
continue
}
- for i := range data.Messages {
- data.Messages[i] = data.Messages[i].NormalizeCollections()
+
+ summary := sessionSummaryFromListData(data)
+ s.summaryMu.Lock()
+ s.summaryCache[name] = sessionSummaryCacheEntry{modTime: info.ModTime(), size: info.Size(), summary: summary}
+ s.summaryMu.Unlock()
+ cacheChanged = true
+ sessions = append(sessions, summary)
+ }
+
+ // Drop cache entries for files that no longer exist
+ s.summaryMu.Lock()
+ for name := range s.summaryCache {
+ if _, ok := seen[name]; !ok {
+ delete(s.summaryCache, name)
+ cacheChanged = true
}
+ }
+ s.summaryMu.Unlock()
- sessions = append(sessions, sessionSummaryFromData(data))
+ if cacheChanged {
+ s.saveSummaryIndex()
}
// Sort by updated_at descending (newest first)
@@ -529,6 +629,79 @@ func (s *SessionStore) List() ([]Session, error) {
return sessions, nil
}
+// loadSummaryIndex hydrates the summary cache from the persisted index.
+// Best-effort: a missing or corrupt index just means the next List()
+// re-parses changed files and rewrites it.
+func (s *SessionStore) loadSummaryIndex() {
+ path := filepath.Join(s.dataDir, sessionSummaryIndexFile)
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ log.Warn().Err(err).Msg("failed to read session summary index")
+ }
+ return
+ }
+ var data sessionSummaryIndexData
+ if err := json.Unmarshal(raw, &data); err != nil {
+ log.Warn().Err(err).Msg("failed to parse session summary index; rebuilding on next list")
+ return
+ }
+ if data.Version != sessionSummaryIndexVersion {
+ return
+ }
+ s.summaryMu.Lock()
+ defer s.summaryMu.Unlock()
+ for name, entry := range data.Entries {
+ if strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ s.summaryCache[name] = sessionSummaryCacheEntry{modTime: entry.ModTime, size: entry.Size, summary: entry.Summary}
+ }
+}
+
+// saveSummaryIndex persists the summary cache next to the session files.
+// Best-effort: failures are logged and never block session operations.
+func (s *SessionStore) saveSummaryIndex() {
+ s.summaryMu.Lock()
+ data := sessionSummaryIndexData{
+ Version: sessionSummaryIndexVersion,
+ Entries: make(map[string]sessionSummaryIndexEntry, len(s.summaryCache)),
+ }
+ for name, entry := range s.summaryCache {
+ data.Entries[name] = sessionSummaryIndexEntry{ModTime: entry.modTime, Size: entry.size, Summary: entry.summary}
+ }
+ s.summaryMu.Unlock()
+
+ raw, err := json.Marshal(data)
+ if err != nil {
+ log.Warn().Err(err).Msg("failed to marshal session summary index")
+ return
+ }
+
+ s.indexMu.Lock()
+ defer s.indexMu.Unlock()
+ path := filepath.Join(s.dataDir, sessionSummaryIndexFile)
+ tmpFile, err := os.CreateTemp(s.dataDir, sessionSummaryIndexFile+".tmp-")
+ if err != nil {
+ log.Warn().Err(err).Msg("failed to create session summary index temp file")
+ return
+ }
+ tmpPath := tmpFile.Name()
+ if err := tmpFile.Chmod(0600); err == nil {
+ _, err = tmpFile.Write(raw)
+ }
+ if closeErr := tmpFile.Close(); err == nil {
+ err = closeErr
+ }
+ if err == nil {
+ err = os.Rename(tmpPath, path)
+ }
+ if err != nil {
+ _ = os.Remove(tmpPath)
+ log.Warn().Err(err).Msg("failed to write session summary index")
+ }
+}
+
// Create creates a new session
func (s *SessionStore) Create() (*Session, error) {
s.mu.Lock()
@@ -773,10 +946,14 @@ func (s *SessionStore) Delete(id string) error {
return fmt.Errorf("failed to delete session: %w", err)
}
removed = true
+ s.summaryMu.Lock()
+ delete(s.summaryCache, filepath.Base(candidate))
+ s.summaryMu.Unlock()
}
if !removed {
return fmt.Errorf("session not found: %s", id)
}
+ s.saveSummaryIndex()
// Also clean up resolved context, FSM, and knowledge accumulator
delete(s.resolvedContexts, id)
@@ -1295,7 +1472,24 @@ func (s *SessionStore) writeSession(data sessionData) error {
cleanupTemp = false
if legacyPath, err := s.directLegacySessionPath(data.ID); err == nil && legacyPath != "" && legacyPath != path {
_ = os.Remove(legacyPath)
+ s.summaryMu.Lock()
+ delete(s.summaryCache, filepath.Base(legacyPath))
+ s.summaryMu.Unlock()
+ }
+
+ // Keep the list summary cache warm so List() never re-reads this file.
+ s.summaryMu.Lock()
+ if info, err := os.Stat(path); err == nil {
+ s.summaryCache[filepath.Base(path)] = sessionSummaryCacheEntry{
+ modTime: info.ModTime(),
+ size: info.Size(),
+ summary: sessionSummaryFromData(data),
+ }
+ } else {
+ delete(s.summaryCache, filepath.Base(path))
}
+ s.summaryMu.Unlock()
+ s.saveSummaryIndex()
return nil
}
diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.go
index 386cec427e..e0ae44470c 100644
--- a/internal/ai/chat/session_test.go
+++ b/internal/ai/chat/session_test.go
@@ -442,6 +442,109 @@ func TestSessionStoreListDoesNotHoldStoreMutex(t *testing.T) {
}
}
+func TestSessionStoreListServesSummariesFromCacheUntilFileChanges(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ require.NoError(t, err)
+
+ session, err := store.Create()
+ require.NoError(t, err)
+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "user", Content: "aaaa"}))
+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "assistant", Content: "reply"}))
+
+ sessions, err := store.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 1)
+ assert.Equal(t, "aaaa", sessions[0].Title)
+ assert.Equal(t, 2, sessions[0].MessageCount)
+
+ // Rewrite the file out of band with same-length content and restore the
+ // original mtime: List must serve the cached summary without re-reading.
+ path, err := store.sessionPath(session.ID)
+ require.NoError(t, err)
+ info, err := os.Stat(path)
+ require.NoError(t, err)
+ raw, err := os.ReadFile(path)
+ require.NoError(t, err)
+ patched := strings.Replace(string(raw), `"title": "aaaa"`, `"title": "bbbb"`, 1)
+ require.NotEqual(t, string(raw), patched, "test fixture must contain the title to patch")
+ require.NoError(t, os.WriteFile(path, []byte(patched), 0600))
+ require.NoError(t, os.Chtimes(path, info.ModTime(), info.ModTime()))
+
+ sessions, err = store.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 1)
+ assert.Equal(t, "aaaa", sessions[0].Title, "unchanged (mtime, size) must serve the cached summary")
+
+ // Bump the mtime: List must notice the change and re-parse the file.
+ require.NoError(t, os.Chtimes(path, info.ModTime().Add(2*time.Second), info.ModTime().Add(2*time.Second)))
+ sessions, err = store.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 1)
+ assert.Equal(t, "bbbb", sessions[0].Title, "changed mtime must invalidate the cached summary")
+ assert.Equal(t, 2, sessions[0].MessageCount)
+}
+
+func TestSessionStoreSummaryIndexSurvivesRestart(t *testing.T) {
+ dir := t.TempDir()
+ store, err := NewSessionStore(dir)
+ require.NoError(t, err)
+
+ session, err := store.Create()
+ require.NoError(t, err)
+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "user", Content: "indexed title"}))
+
+ // A fresh store (simulated restart) must serve the summary from the
+ // persisted index without re-reading the transcript: corrupt the message
+ // payload on disk at unchanged (mtime, size) and expect the indexed
+ // summary, not a parse of the corrupted file.
+ path, err := store.sessionPath(session.ID)
+ require.NoError(t, err)
+ info, err := os.Stat(path)
+ require.NoError(t, err)
+ raw, err := os.ReadFile(path)
+ require.NoError(t, err)
+ patched := strings.Replace(string(raw), `"content": "indexed title"`, `"content": "altered titlexx"`, 1)
+ require.NotEqual(t, string(raw), patched)
+ require.NoError(t, os.WriteFile(path, []byte(patched), 0600))
+ require.NoError(t, os.Chtimes(path, info.ModTime(), info.ModTime()))
+
+ reopened, err := NewSessionStore(dir)
+ require.NoError(t, err)
+ sessions, err := reopened.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 1)
+ assert.Equal(t, "indexed title", sessions[0].Title)
+ assert.Equal(t, 1, sessions[0].MessageCount)
+
+ // The index file itself must never show up as a session.
+ for _, s := range sessions {
+ assert.NotEmpty(t, s.ID)
+ }
+}
+
+func TestSessionStoreListDropsExternallyDeletedSessions(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ require.NoError(t, err)
+
+ keep, err := store.Create()
+ require.NoError(t, err)
+ drop, err := store.Create()
+ require.NoError(t, err)
+
+ sessions, err := store.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 2)
+
+ path, err := store.sessionPath(drop.ID)
+ require.NoError(t, err)
+ require.NoError(t, os.Remove(path))
+
+ sessions, err = store.List()
+ require.NoError(t, err)
+ require.Len(t, sessions, 1)
+ assert.Equal(t, keep.ID, sessions[0].ID)
+}
+
func TestSessionStoreEnsureSessionDoesNotScanIndirectLegacyFilesForNewSession(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
require.NoError(t, err)