返回 DeepSeek-Reasonix
export_snapshot.go
根目录 / internal / session / export_snapshot.go
1 package session
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strings"
9 "time"
10 )
11
12 // ExportSnapshot names an immutable display-history cut, not a provider workset.
13 // It is safe to retain while the source runtime continues accepting events.
14 type ExportSnapshot struct {
15 ReadIncomplete bool `json:"readIncomplete,omitempty"`
16 Ref SessionRef `json:"session"`
17 StorageGeneration string `json:"storageGeneration"`
18 SnapshotSequence uint64 `json:"snapshotSequence"`
19 AcceptedThrough uint64 `json:"acceptedThrough"`
20 DurableThrough uint64 `json:"durableThrough"`
21 CapturedAt time.Time `json:"capturedAt"`
22 Title string `json:"title"`
23 }
24
25 func (q *Query) CaptureExportSnapshot(ctx context.Context, ref SessionRef) (ExportSnapshot, error) {
26 out := ExportSnapshot{Ref: ref, CapturedAt: time.Now().UTC()}
27 if err := ref.validate(q.hostID); err != nil {
28 return out, err
29 }
30 generation := q.storageGeneration(ref.SessionID)
31 if generation == "" {
32 return out, ErrSessionNotFound
33 }
34 live := false
35 if q.service != nil {
36 if runtime, ok := q.service.Runtime(ref); ok {
37 live = true
38 out.AcceptedThrough = runtime.Session().EventSequence()
39 receipt, err := runtime.Session().FlushThrough(ctx, out.AcceptedThrough)
40 if err != nil {
41 return out, err
42 }
43 out.DurableThrough = receipt.DurableSequence
44 }
45 }
46 _, path, err := q.prepareHistoryIndex(ctx, ref)
47 if err != nil {
48 return out, err
49 }
50 handle, err := openHistoryProjection(ctx, path)
51 if err != nil {
52 return out, err
53 }
54 defer handle.DB.Close()
55 metadata, err := readHistoryIndexMetadata(ctx, handle.DB)
56 if err != nil {
57 return out, err
58 }
59 if q.storageGeneration(ref.SessionID) != generation {
60 return out, ErrStaleGeneration
61 }
62 if !live {
63 out.AcceptedThrough = metadata.durableSequence
64 out.DurableThrough = metadata.durableSequence
65 }
66 out.SnapshotSequence = out.AcceptedThrough
67 out.StorageGeneration = generation
68 if out.SnapshotSequence > metadata.durableSequence {
69 return out, fmt.Errorf("session: history does not cover export watermark")
70 }
71 if metadata.generation != fmt.Sprintf("%s:%d", generation, metadata.viewSequence) {
72 return out, ErrStaleGeneration
73 }
74 info, err := q.Stat(ctx, ref)
75 if err != nil {
76 return out, err
77 }
78 out.Title = info.Title
79 return out, nil
80 }
81
82 // VisitExportMessages traverses the existing versioned display projection in
83 // ascending order, without accumulating the transcript or growing a UI window.
84 func (q *Query) VisitExportMessages(ctx context.Context, snapshot ExportSnapshot, visit func(PersistentMessage) error) error {
85 return q.VisitExportMessagesForRef(ctx, snapshot.Ref, snapshot, visit)
86 }
87
88 // VisitExportMessagesForRef keeps the trusted storage identity separate from
89 // snapshot metadata received over a transport boundary.
90 func (q *Query) VisitExportMessagesForRef(ctx context.Context, ref SessionRef, snapshot ExportSnapshot, visit func(PersistentMessage) error) error {
91 if err := q.ValidateExportSourceForRef(ref, snapshot); err != nil {
92 return err
93 }
94 generation := q.storageGeneration(ref.SessionID)
95 filesystem, path, err := q.prepareHistoryIndex(ctx, ref)
96 if err != nil {
97 return err
98 }
99 handle, err := openHistoryProjection(ctx, path)
100 if err != nil {
101 return err
102 }
103 defer handle.DB.Close()
104 metadata, err := readHistoryIndexMetadata(ctx, handle.DB)
105 if err != nil {
106 return err
107 }
108 if q.storageGeneration(ref.SessionID) != generation || metadata.durableSequence < snapshot.SnapshotSequence {
109 return ErrStaleGeneration
110 }
111 if metadata.generation != fmt.Sprintf("%s:%d", generation, metadata.viewSequence) {
112 return ErrStaleGeneration
113 }
114 boundary := int64(1)
115 for {
116 if err := ctx.Err(); err != nil {
117 return err
118 }
119 if q.storageGeneration(ref.SessionID) != generation {
120 return ErrStaleGeneration
121 }
122 page, err := q.readHistoryWindowPage(ctx, handle.DB, filesystem, ref, metadata, snapshot.SnapshotSequence, boundary, historyWindowDirNewer, 100)
123 if err != nil {
124 return err
125 }
126 if err = q.attachHistoryWindowTurnStats(ctx, handle.DB, &page); err != nil {
127 return err
128 }
129 if err = q.attachToolObservations(ctx, handle.DB, ref, &page); err != nil {
130 return err
131 }
132 for _, message := range page.Messages {
133 if message.ContentRef != nil {
134 contentRef := *message.ContentRef
135 body := make([]byte, 0)
136 for offset := int64(0); offset < contentRef.Bytes; {
137 chunk, err := q.ReadContent(ctx, ref, contentRef, offset, min(int64(1<<20), contentRef.Bytes-offset))
138 if err != nil {
139 return err
140 }
141 if len(chunk) == 0 {
142 return fmt.Errorf("session: empty export content chunk")
143 }
144 body = append(body, chunk...)
145 offset += int64(len(chunk))
146 }
147 if !json.Valid(body) {
148 return fmt.Errorf("session: invalid export message")
149 }
150 message.Inline = body
151 message.ContentRef = nil
152 }
153 if err := visit(message); err != nil {
154 return err
155 }
156 }
157 if !page.HasNewer {
158 if q.storageGeneration(ref.SessionID) != generation {
159 return ErrStaleGeneration
160 }
161 return nil
162 }
163 if len(page.Messages) == 0 {
164 return fmt.Errorf("session: export cursor did not advance")
165 }
166 boundary = page.Messages[len(page.Messages)-1].Position + 1
167 }
168 }
169
170 // CaptureDiagnosticSnapshot records an accepted boundary without requiring a
171 // successful persistence checkpoint or a readable display projection.
172 func (q *Query) CaptureDiagnosticSnapshot(ctx context.Context, ref SessionRef) (ExportSnapshot, error) {
173 out := ExportSnapshot{Ref: ref, CapturedAt: time.Now().UTC()}
174 if err := ref.validate(q.hostID); err != nil {
175 return out, err
176 }
177 out.StorageGeneration = q.storageGeneration(ref.SessionID)
178 if out.StorageGeneration == "" {
179 return out, ErrSessionNotFound
180 }
181 if q.service != nil {
182 if runtime, ok := q.service.Runtime(ref); ok {
183 state := runtime.Session().StateSnapshot()
184 out.AcceptedThrough, out.DurableThrough = state.EventSequence, state.DurableSequence
185 out.SnapshotSequence = out.AcceptedThrough
186 return out, nil
187 }
188 }
189 err := q.StreamSession(ctx, ref, func(commit Commit) error {
190 out.DurableThrough = commit.LastSequence()
191 return nil
192 })
193 out.AcceptedThrough, out.SnapshotSequence = out.DurableThrough, out.DurableThrough
194 out.ReadIncomplete = err != nil
195 // A damaged tail must not prevent exporting its readable prefix and errors.
196 if err != nil && ctx.Err() != nil {
197 return out, ctx.Err()
198 }
199 return out, nil
200 }
201
202 // ValidateExportSource never rebinds a handle to replacement storage.
203 func (q *Query) ValidateExportSource(snapshot ExportSnapshot) error {
204 return q.ValidateExportSourceForRef(snapshot.Ref, snapshot)
205 }
206
207 // ValidateExportSourceForRef validates transport metadata against a trusted
208 // canonical identity without using request-owned fields as path components.
209 func (q *Query) ValidateExportSourceForRef(ref SessionRef, snapshot ExportSnapshot) error {
210 if err := ref.validate(q.hostID); err != nil {
211 return err
212 }
213 if snapshot.Ref != ref {
214 return ErrStaleGeneration
215 }
216 generation := q.storageGeneration(ref.SessionID)
217 if generation == "" {
218 return ErrSessionNotFound
219 }
220 if snapshot.StorageGeneration != generation && !strings.HasPrefix(snapshot.StorageGeneration, generation+":") {
221 return ErrStaleGeneration
222 }
223 return nil
224 }
225
226 // StreamExportCommits visits a fixed raw prefix for cold diagnostics. Reopening
227 // that session in another tab cannot make traversal chase new commits forever.
228 func (q *Query) StreamExportCommits(ctx context.Context, snapshot ExportSnapshot, visit func(Commit) error) error {
229 if err := q.ValidateExportSource(snapshot); err != nil {
230 return err
231 }
232 reached := errors.New("export boundary reached")
233 err := q.StreamSession(ctx, snapshot.Ref, func(commit Commit) error {
234 if commit.LastSequence() > snapshot.SnapshotSequence {
235 return reached
236 }
237 if err := visit(commit); err != nil {
238 return err
239 }
240 if commit.LastSequence() == snapshot.SnapshotSequence {
241 return reached
242 }
243 return nil
244 })
245 if errors.Is(err, reached) {
246 err = nil
247 }
248 if err != nil {
249 return err
250 }
251 return q.ValidateExportSource(snapshot)
252 }
253
253 lines GO