返回 DeepSeek-Reasonix
history_window.go
根目录 / internal / session / history_window.go
1 package session
2
3 import (
4 "context"
5 "database/sql"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "path/filepath"
11 "slices"
12
13 "reasonix/internal/sessioncontent"
14 )
15
16 // History window reading (capability history-window-v1) pages a bounded
17 // window around an anchor: the newest page, a target message, a target turn,
18 // or an opaque continuation cursor — in either direction. It never walks
19 // pages from the newest position to reach a target: anchors resolve through
20 // the locator index. Protocol 7 HistoryPage stays unchanged for old clients.
21 const (
22 HistoryWindowDefaultLimit = 32
23 HistoryWindowMaxLimit = 100
24
25 historyWindowDirOlder = "older"
26 historyWindowDirNewer = "newer"
27
28 // HistoryWindowUnsupported answers a peer that never negotiated
29 // history-window-v1. It is a status, not an error: the older service still
30 // serves bounded protocol-7 pages, so only the newer-direction and
31 // anchor-jump affordances are withheld until it is upgraded.
32 HistoryWindowUnsupported = "unsupported"
33 )
34
35 // HistoryWindowRequest locates and pages one bounded window in a single
36 // round trip. Anchor selects the entry point; Direction picks which side of
37 // the anchor the page covers ("older" ends at the anchor, "newer" starts at
38 // it). Cursor anchors ignore MessageID/Turn.
39 type HistoryWindowRequest struct {
40 Generation string `json:"generation,omitempty"`
41 SnapshotSequence *uint64 `json:"snapshotSequence,omitempty"`
42 Anchor string `json:"anchor"` // newest | message | turn | cursor
43 MessageID string `json:"messageId,omitempty"` // anchor=message
44 Turn int `json:"turn,omitempty"` // anchor=turn
45 Cursor string `json:"cursor,omitempty"` // anchor=cursor
46 Direction string `json:"direction,omitempty"` // older (default) | newer
47 Limit int `json:"limit,omitempty"`
48 }
49
50 // HistoryWindowPage is one bounded window of a fixed durable snapshot plus
51 // the cursors to keep reading in both directions.
52 type HistoryWindowPage struct {
53 Messages []PersistentMessage `json:"messages"`
54 Status string `json:"status"` // preparing|ready|failed|stale_cursor|not_found|unsupported
55 SnapshotSequence uint64 `json:"snapshotSequence"`
56 CoverageSequence uint64 `json:"coverageSequence"`
57 Generation string `json:"generation,omitempty"`
58 TotalTurns int `json:"totalTurns"`
59 HasOlder bool `json:"hasOlder"`
60 HasNewer bool `json:"hasNewer"`
61 OlderCursor string `json:"olderCursor,omitempty"`
62 NewerCursor string `json:"newerCursor,omitempty"`
63 AnchorMessageID string `json:"anchorMessageId,omitempty"`
64 AnchorTurn int `json:"anchorTurn,omitempty"`
65 }
66
67 // historyWindowCursor is the opaque cursor for window paging. Boundary is
68 // exclusive for older paging (positions < boundary) and inclusive for newer
69 // paging (positions >= boundary).
70 type historyWindowCursor struct {
71 SessionID string `json:"sessionId"`
72 StorageRevision int `json:"storageRevision"`
73 SnapshotSequence uint64 `json:"snapshotSequence"`
74 Boundary int64 `json:"boundary"`
75 Direction string `json:"direction"`
76 Projection int `json:"projection"`
77 Generation string `json:"generation"`
78 }
79
80 func encodeHistoryWindowCursor(c historyWindowCursor) (string, error) {
81 data, err := json.Marshal(c)
82 if err != nil {
83 return "", err
84 }
85 return base64.RawURLEncoding.EncodeToString(data), nil
86 }
87
88 func decodeHistoryWindowCursor(cursor string) (historyWindowCursor, error) {
89 var c historyWindowCursor
90 data, err := base64.RawURLEncoding.DecodeString(cursor)
91 if err != nil {
92 return historyWindowCursor{}, err
93 }
94 if err := json.Unmarshal(data, &c); err != nil {
95 return historyWindowCursor{}, err
96 }
97 return c, nil
98 }
99
100 // ReadHistoryWindow resolves the anchor against the locator index and returns one
101 // page. The snapshot stays fixed across a paging session: appends do not
102 // invalidate cursors (version intervals retain the old view), while a storage
103 // replacement or projection rebuild answers stale_cursor. The client
104 // re-anchors at most once on stale_cursor and keeps the current page after a
105 // second failure.
106 func (q *Query) ReadHistoryWindow(ctx context.Context, ref SessionRef, req HistoryWindowRequest) (HistoryWindowPage, error) {
107 if q == nil {
108 return HistoryWindowPage{}, errors.New("session: nil query")
109 }
110 if err := ref.validate(q.hostID); err != nil {
111 return HistoryWindowPage{}, err
112 }
113 filesystem, ok := q.persistence.(*FilesystemPersistence)
114 if !ok {
115 return HistoryWindowPage{}, errors.New("session: history window requires filesystem persistence")
116 }
117 if req.Limit <= 0 {
118 req.Limit = HistoryWindowDefaultLimit
119 }
120 req.Limit = min(req.Limit, HistoryWindowMaxLimit)
121 if req.Direction != historyWindowDirNewer {
122 req.Direction = historyWindowDirOlder
123 }
124 anchor := req.Anchor
125 if anchor == "" {
126 if req.Cursor != "" {
127 anchor = "cursor"
128 } else {
129 anchor = "newest"
130 }
131 }
132 switch anchor {
133 case "newest", "message", "turn", "cursor":
134 default:
135 return HistoryWindowPage{}, fmt.Errorf("session: unknown history window anchor %q", req.Anchor)
136 }
137
138 path := historyIndexPath(filesystem.Root, ref.SessionID)
139 ready, err := q.historyLocatorReady(ctx, filesystem, ref.SessionID, path)
140 if err != nil {
141 return HistoryWindowPage{}, err
142 }
143 if !ready {
144 return HistoryWindowPage{Messages: []PersistentMessage{}, Status: "preparing"}, nil
145 }
146 handle, err := openHistoryProjection(ctx, path)
147 if err != nil {
148 return HistoryWindowPage{}, err
149 }
150 defer handle.DB.Close()
151 metadata, err := readHistoryIndexMetadata(ctx, handle.DB)
152 if err != nil {
153 return HistoryWindowPage{}, err
154 }
155
156 page := HistoryWindowPage{
157 Messages: []PersistentMessage{},
158 CoverageSequence: metadata.durableSequence,
159 Generation: metadata.generation,
160 AnchorMessageID: req.MessageID,
161 AnchorTurn: req.Turn,
162 }
163 if req.Generation != "" && req.Generation != metadata.generation {
164 page.Status = "stale_cursor"
165 return page, nil
166 }
167 page, boundary, direction, err := resolveWindowAnchor(ctx, handle.DB, ref, req, anchor, metadata, page)
168 if err != nil || page.Status != "" {
169 // A typed status is the whole answer: stale_cursor and not_found are
170 // results the client reasons about, not failures.
171 return page, err
172 }
173 result, err := q.readHistoryWindowPage(ctx, handle.DB, filesystem, ref, metadata, page.SnapshotSequence, boundary, direction, req.Limit)
174 if err != nil {
175 return HistoryWindowPage{}, err
176 }
177 if err := q.attachHistoryWindowTurnStats(ctx, handle.DB, &result); err != nil {
178 return HistoryWindowPage{}, err
179 }
180
181 if err := q.attachToolObservations(ctx, handle.DB, ref, &result); err != nil {
182 return HistoryWindowPage{}, err
183 }
184 return attachWindowAnchor(result, page), nil
185 }
186
187 func (q *Query) attachHistoryWindowTurnStats(ctx context.Context, db *sql.DB, page *HistoryWindowPage) error {
188 for i := range page.Messages {
189 message := &page.Messages[i]
190 var duration int64
191 var turnID string
192 err := db.QueryRowContext(ctx, `SELECT MAX(0,ended_at-started_at),turn_id FROM turn_summaries WHERE final_message_id=? AND end_sequence>0 AND end_sequence<=? AND start_sequence<=? LIMIT 1`, message.MessageID, page.SnapshotSequence, message.EventSequence).Scan(&duration, &turnID)
193 if err == nil {
194 message.TurnFinal, message.TurnDurationMs = true, duration
195 var samples, tools int
196 if err := db.QueryRowContext(ctx, `SELECT COUNT(CASE WHEN kind='assistant/attempt' THEN 1 END),COUNT(CASE WHEN kind='tool/call' THEN 1 END) FROM turn_counts WHERE turn_id=? AND sequence<=?`, turnID, page.SnapshotSequence).Scan(&samples, &tools); err != nil {
197 return err
198 }
199 if samples > 0 || tools > 0 {
200 message.SamplingCount, message.ToolCount = &samples, &tools
201 }
202 } else if !errors.Is(err, sql.ErrNoRows) {
203 return err
204 }
205 }
206 return nil
207 }
208
209 // resolveWindowAnchor turns a request's anchor into the boundary and direction
210 // the page read needs. A newest anchor reads the latest durable cut; the others
211 // pin a snapshot and answer through page.Status (with a nil error) when the
212 // anchor is stale or missing rather than failing the call.
213 func resolveWindowAnchor(
214 ctx context.Context,
215 db *sql.DB,
216 ref SessionRef,
217 req HistoryWindowRequest,
218 anchor string,
219 metadata historyIndexMetadata,
220 page HistoryWindowPage,
221 ) (HistoryWindowPage, int64, string, error) {
222 // Newest pages have no boundary above them; the read walks down from the end.
223 boundary := int64(^uint64(0) >> 1)
224 direction := req.Direction
225 cut := metadata.durableSequence
226 if req.SnapshotSequence != nil {
227 if *req.SnapshotSequence > cut {
228 page.Status = "stale_cursor"
229 return page, boundary, direction, nil
230 }
231 cut = *req.SnapshotSequence
232 }
233 if anchor == "newest" {
234 page.SnapshotSequence = cut
235 return page, boundary, direction, nil
236 }
237 if anchor == "cursor" {
238 parsed, err := decodeHistoryWindowCursor(req.Cursor)
239 if err != nil {
240 // An unreadable cursor means the same thing to a client as one bound
241 // to a replaced snapshot: start over. A typed status keeps that with
242 // the caller instead of surfacing an error that reads as transport.
243 page.Status = "stale_cursor"
244 return page, boundary, direction, nil
245 }
246 if parsed.SessionID != ref.SessionID || parsed.StorageRevision != StorageRevision ||
247 parsed.Projection != historyIndexVersion || parsed.Generation != metadata.generation ||
248 (parsed.Direction != historyWindowDirOlder && parsed.Direction != historyWindowDirNewer) ||
249 parsed.Boundary <= 0 {
250 page.Status = "stale_cursor"
251 return page, boundary, direction, nil
252 }
253 if parsed.SnapshotSequence > metadata.durableSequence {
254 page.Status = "stale_cursor"
255 page.SnapshotSequence = metadata.durableSequence
256 return page, boundary, direction, nil
257 }
258 // The cursor pins the snapshot it was issued under; that pin is what
259 // keeps appends from invalidating a paging session.
260 page.SnapshotSequence = parsed.SnapshotSequence
261 return page, parsed.Boundary, parsed.Direction, nil
262 }
263 page.SnapshotSequence = cut
264 var anchorPos int64
265 var err error
266 if anchor == "message" {
267 anchorPos, err = resolveMessagePosition(ctx, db, req.MessageID, page.SnapshotSequence)
268 } else {
269 anchorPos, err = resolveTurnPosition(ctx, db, req.Turn, page.SnapshotSequence)
270 }
271 if errors.Is(err, sql.ErrNoRows) {
272 page.Status = "not_found"
273 return page, boundary, direction, nil
274 }
275 if err != nil {
276 return HistoryWindowPage{}, boundary, direction, err
277 }
278 // Paging older from an anchor puts the anchor itself at the page's newest,
279 // so the reader sees the message or turn they asked for.
280 if direction == historyWindowDirOlder {
281 anchorPos++
282 }
283 return page, anchorPos, direction, nil
284 }
285
286 // attachWindowAnchor carries the resolved anchor identity onto the page the
287 // builder produced.
288 func attachWindowAnchor(result, resolved HistoryWindowPage) HistoryWindowPage {
289 // The page builder starts from a fresh value, so the anchor identity has to
290 // travel with the result: clients place the reading anchor and the visible
291 // turn range from it, and losing it makes an anchored page unanchored.
292 result.AnchorMessageID = resolved.AnchorMessageID
293 result.AnchorTurn = resolved.AnchorTurn
294 return result
295 }
296
297 func resolveMessagePosition(ctx context.Context, db *sql.DB, messageID string, snapshot uint64) (int64, error) {
298 var position int64
299 err := db.QueryRowContext(ctx,
300 `SELECT position FROM messages WHERE message_id=? AND event_sequence<=? AND (valid_to=0 OR valid_to>?) ORDER BY version DESC LIMIT 1`,
301 messageID, snapshot, snapshot).Scan(&position)
302 return position, err
303 }
304
305 func resolveTurnPosition(ctx context.Context, db *sql.DB, turn int, snapshot uint64) (int64, error) {
306 var position int64
307 err := db.QueryRowContext(ctx,
308 `SELECT MIN(position) FROM messages WHERE visible_turn=? AND event_sequence<=? AND (valid_to=0 OR valid_to>?)`,
309 turn, snapshot, snapshot).Scan(&position)
310 if err != nil {
311 return 0, err
312 }
313 if position == 0 {
314 // Zero positions never occur in the locator: MIN yielded NULL over no
315 // rows only when the turn has no current messages — confirm to
316 // distinguish not_found from a scan error.
317 var exists bool
318 if err := db.QueryRowContext(ctx,
319 `SELECT EXISTS(SELECT 1 FROM messages WHERE visible_turn=? AND event_sequence<=? AND (valid_to=0 OR valid_to>?))`,
320 turn, snapshot, snapshot).Scan(&exists); err != nil {
321 return 0, err
322 }
323 if !exists {
324 return 0, sql.ErrNoRows
325 }
326 }
327 return position, nil
328 }
329
330 // readHistoryWindowPage pages [boundary,∞) or (−∞,boundary) of a fixed
331 // snapshot in limit-sized steps, inlining small bodies and authorizing
332 // content-range credentials for referenced ones — the same body budget as
333 // protocol 7 pages.
334 func (q *Query) readHistoryWindowPage(ctx context.Context, db *sql.DB, filesystem *FilesystemPersistence, ref SessionRef, metadata historyIndexMetadata, snapshot uint64, boundary int64, direction string, limit int) (HistoryWindowPage, error) {
335 page := HistoryWindowPage{
336 Messages: []PersistentMessage{},
337 Status: "ready",
338 SnapshotSequence: snapshot,
339 CoverageSequence: metadata.durableSequence,
340 Generation: metadata.generation,
341 }
342 if err := db.QueryRowContext(ctx, `SELECT COALESCE(MAX(visible_turn),0) FROM messages WHERE event_sequence<=? AND (valid_to=0 OR valid_to>?)`, snapshot, snapshot).Scan(&page.TotalTurns); err != nil {
343 return HistoryWindowPage{}, err
344 }
345 var rows *sql.Rows
346 var err error
347 if direction == historyWindowDirNewer {
348 rows, err = db.QueryContext(ctx, `SELECT message_id,position,version,role,preview,event_sequence,visible_turn,inline,content_digest,content_bytes,content_index_digest,COALESCE((SELECT submission_id FROM submissions WHERE submissions.message_id=messages.message_id AND submissions.sequence<=messages.event_sequence AND submissions.session_id=(SELECT value FROM metadata WHERE key='session_id') LIMIT 1),'') FROM messages WHERE position>=? AND event_sequence<=? AND (valid_to=0 OR valid_to>?) ORDER BY position ASC LIMIT ?`, boundary, snapshot, snapshot, limit+1)
349 } else {
350 rows, err = db.QueryContext(ctx, `SELECT message_id,position,version,role,preview,event_sequence,visible_turn,inline,content_digest,content_bytes,content_index_digest,COALESCE((SELECT submission_id FROM submissions WHERE submissions.message_id=messages.message_id AND submissions.sequence<=messages.event_sequence AND submissions.session_id=(SELECT value FROM metadata WHERE key='session_id') LIMIT 1),'') FROM messages WHERE position<? AND event_sequence<=? AND (valid_to=0 OR valid_to>?) ORDER BY position DESC LIMIT ?`, boundary, snapshot, snapshot, limit+1)
351 }
352 if err != nil {
353 return HistoryWindowPage{}, err
354 }
355 defer rows.Close()
356 encodedBytes := 0
357 storageGeneration := q.storageGeneration(ref.SessionID)
358 scanned := 0
359 for rows.Next() {
360 var message PersistentMessage
361 var inline []byte
362 var digest, indexDigest string
363 var contentBytes int64
364 if err := rows.Scan(&message.MessageID, &message.Position, &message.Version, &message.Role, &message.Preview, &message.EventSequence, &message.VisibleTurn, &inline, &digest, &contentBytes, &indexDigest, &message.SubmissionID); err != nil {
365 return HistoryWindowPage{}, err
366 }
367 scanned++
368 if len(page.Messages) == limit {
369 break
370 }
371 message.Inline = append(json.RawMessage(nil), inline...)
372 if digest != "" {
373 contentRef := sessioncontent.Ref{Digest: digest, Bytes: contentBytes, IndexDigest: indexDigest, IntegrityBlock: sessioncontent.IntegrityBlockBytes, MediaType: "application/json"}
374 if contentBytes <= recentInlineBytes && encodedBytes+int(contentBytes) <= HistoryPageMaxBytes {
375 body, readErr := contentStoreForSessionDir(filepath.Join(filesystem.Root, ref.SessionID)).ReadRange(ctx, contentRef, 0, contentBytes)
376 if readErr != nil {
377 return HistoryWindowPage{}, readErr
378 }
379 message.Inline = json.RawMessage(body)
380 } else {
381 message.ContentRef = &contentRef
382 q.authorizeContentForGeneration(ref.SessionID, storageGeneration, digest, contentBytes, indexDigest)
383 }
384 }
385 encoded, _ := json.Marshal(message)
386 if len(page.Messages) > 0 && encodedBytes+len(encoded) > HistoryPageMaxBytes {
387 break
388 }
389 encodedBytes += len(encoded)
390 page.Messages = append(page.Messages, message)
391 }
392 if err := rows.Err(); err != nil {
393 return HistoryWindowPage{}, err
394 }
395 hasMoreBeyond := scanned > len(page.Messages)
396 if direction == historyWindowDirNewer {
397 page.HasNewer = hasMoreBeyond
398 page.HasOlder = boundary > 1
399 if page.HasNewer && len(page.Messages) > 0 {
400 last := page.Messages[len(page.Messages)-1]
401 page.NewerCursor, err = encodeHistoryWindowCursor(historyWindowCursor{SessionID: ref.SessionID, StorageRevision: StorageRevision, SnapshotSequence: snapshot, Boundary: last.Position + 1, Direction: historyWindowDirNewer, Projection: historyIndexVersion, Generation: metadata.generation})
402 if err != nil {
403 return HistoryWindowPage{}, err
404 }
405 }
406 if page.HasOlder {
407 page.OlderCursor, err = encodeHistoryWindowCursor(historyWindowCursor{SessionID: ref.SessionID, StorageRevision: StorageRevision, SnapshotSequence: snapshot, Boundary: boundary, Direction: historyWindowDirOlder, Projection: historyIndexVersion, Generation: metadata.generation})
408 if err != nil {
409 return HistoryWindowPage{}, err
410 }
411 }
412 // Newer pages were collected oldest-first: already display order.
413 return page, nil
414 }
415 // Older paging: the collected messages are newest-first and reversed for
416 // display; continuation cursors cover both directions.
417 page.HasOlder = hasMoreBeyond
418 if page.HasOlder && len(page.Messages) > 0 {
419 oldest := page.Messages[len(page.Messages)-1]
420 page.OlderCursor, err = encodeHistoryWindowCursor(historyWindowCursor{SessionID: ref.SessionID, StorageRevision: StorageRevision, SnapshotSequence: snapshot, Boundary: oldest.Position, Direction: historyWindowDirOlder, Projection: historyIndexVersion, Generation: metadata.generation})
421 if err != nil {
422 return HistoryWindowPage{}, err
423 }
424 }
425 // The locator opens at most one connection: release this result set
426 // before issuing the existence probe.
427 rows.Close()
428 var newer bool
429 if err := db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE position>=? AND event_sequence<=? AND (valid_to=0 OR valid_to>?))`, boundary, snapshot, snapshot).Scan(&newer); err != nil {
430 return HistoryWindowPage{}, err
431 }
432 page.HasNewer = newer
433 if page.HasNewer {
434 page.NewerCursor, err = encodeHistoryWindowCursor(historyWindowCursor{SessionID: ref.SessionID, StorageRevision: StorageRevision, SnapshotSequence: snapshot, Boundary: boundary, Direction: historyWindowDirNewer, Projection: historyIndexVersion, Generation: metadata.generation})
435 if err != nil {
436 return HistoryWindowPage{}, err
437 }
438 }
439 slices.Reverse(page.Messages)
440 return page, nil
441 }
442
442 lines GO