Repository navigation
Expand file tree
/
Copy pathmemory_store.go
More file actions
292 lines (281 loc) · 8.65 KB
/
Copy pathmemory_store.go
File metadata and controls
292 lines (281 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package inofy
import (
"context"
"encoding/json"
"fmt"
"sort"
"sync"
)
// MemoryRunStore is the in-memory RunStore adapter for tests and
// explicit ephemeral embedding (§6). It implements identical Commit
// semantics — atomic transitions, CommitID idempotency, epoch fencing —
// and advertises no restart recovery: Load only sees this process.
type MemoryRunStore struct {
mu sync.Mutex
runs map[string]*memRun
seq uint64
}
type memRun struct {
ref ExecutionRef
status RunStatus
commits map[string]memCommit
unresolved map[string]OperationRef
events []Event
results int
usage Usage
limits Limits
input json.RawMessage
checkpoint *CheckpointEnvelope
waits []WaitRequest
interrupts map[string]string
gates []string
resumeKey string
resumeAnswers map[string]json.RawMessage
}
type memCommit struct {
body string
receipt Receipt
}
// NewMemoryRunStore returns a process-local ephemeral store.
func NewMemoryRunStore() *MemoryRunStore {
return &MemoryRunStore{runs: map[string]*memRun{}}
}
// Commit applies one atomic change. Replaying the same CommitID with
// the same canonical body returns the original receipt; a changed body
// is idempotency_conflict. Stale epochs and wrong transition
// expectations fail before any write.
func (m *MemoryRunStore) Commit(ctx context.Context, ref ExecutionRef, change RunCommit) (Receipt, error) {
if err := ctx.Err(); err != nil {
return Receipt{}, err
}
body, err := commitBody(change)
if err != nil {
return Receipt{}, err
}
var admittedInput json.RawMessage
if len(change.AdmittedInput) > 0 {
admittedInput, err = NormalizeJSONValue(change.AdmittedInput)
if err != nil {
return Receipt{}, &Error{Code: ErrInvalidDefinition, Path: ref.RunID,
Err: err, Message: "admitted input is not a valid JSON value"}
}
}
var resumeAnswers map[string]json.RawMessage
if change.ResumeKey != "" {
resumeAnswers, err = normalizeAnswers(change.ResumeAnswers)
if err != nil {
return Receipt{}, &Error{Code: ErrInvalidDefinition, Path: ref.RunID,
Err: err, Message: "resume claim contains invalid values"}
}
}
m.mu.Lock()
defer m.mu.Unlock()
run, ok := m.runs[ref.RunID]
if !ok {
if change.Transition.Expected != "" {
return Receipt{}, &Error{Code: ErrRevisionConflict, Path: ref.RunID,
Message: "run is not admitted"}
}
run = &memRun{
ref: ref,
commits: map[string]memCommit{},
unresolved: map[string]OperationRef{},
}
}
if ok && (run.ref.ProgramID != ref.ProgramID || run.ref.HostBindingID != ref.HostBindingID) {
return Receipt{}, &Error{Code: ErrCheckpointIncompatible, Path: ref.RunID,
Message: "program or host binding identity mismatch"}
}
if prev, ok := run.commits[change.CommitID]; ok {
if prev.body == body {
return prev.receipt, nil
}
return Receipt{}, &Error{Code: ErrIdempotencyConflict, Path: ref.RunID,
Message: "commit id reused with a different body"}
}
if run != nil {
// Writer epoch CAS: a newer epoch claims the run; an older
// one is a stale writer. Equal epochs continue the same claim.
if ref.Epoch < run.ref.Epoch {
return Receipt{}, &Error{Code: ErrStaleWriter, Path: ref.RunID,
Message: "writer epoch mismatch"}
}
if run.status != change.Transition.Expected {
return Receipt{}, &Error{Code: ErrRevisionConflict, Path: ref.RunID,
Message: fmt.Sprintf("run is %q, commit expects %q",
run.status, change.Transition.Expected)}
}
}
if len(admittedInput) > 0 && len(run.input) > 0 && !sameJSON(run.input, admittedInput) {
return Receipt{}, &Error{Code: ErrIdempotencyConflict, Path: ref.RunID,
Message: "run was admitted with different input values"}
}
if !ok {
m.runs[ref.RunID] = run
}
if ref.Epoch > run.ref.Epoch {
run.ref.Epoch = ref.Epoch
}
run.status = change.Transition.Target
if change.Checkpoint != nil {
cp := *change.Checkpoint
cp.Payload = append([]byte(nil), change.Checkpoint.Payload...)
run.checkpoint = &cp
}
for _, ev := range change.Events {
evCopy := ev
if len(evCopy.Data) > 0 {
evCopy.Data = append([]byte(nil), evCopy.Data...)
}
run.events = append(run.events, evCopy)
if ev.Kind == EventRunAdmitted && len(ev.Data) > 0 {
var meta struct {
Limits Limits `json:"limits"`
}
if json.Unmarshal(ev.Data, &meta) == nil {
run.limits = meta.Limits
}
}
if ev.Kind == EventRunWaiting && len(ev.Data) > 0 {
var meta struct {
Waits []WaitRequest `json:"waits"`
Interrupts map[string]string `json:"interrupts"`
Gates []string `json:"gates"`
}
if json.Unmarshal(ev.Data, &meta) == nil {
run.waits = meta.Waits
run.interrupts = meta.Interrupts
run.gates = meta.Gates
}
}
if ev.Kind == EventRunResumed && len(ev.Data) > 0 {
run.waits = nil
run.interrupts = nil
run.gates = nil
}
key := opKeyFor(ev)
switch ev.Kind {
case EventNodeAttempt:
run.unresolved[key] = OperationRef{
OperationKey: ref.RunID + "/" + ev.Path,
Path: ev.Path,
Attempt: ev.Attempt,
}
case EventNodeCompleted, EventNodeFailed, EventNodeDegraded,
EventNodeWait, EventNodeStarted:
if ev.Kind != EventNodeStarted {
delete(run.unresolved, key)
}
}
run.usage.Attempts++
}
if len(admittedInput) > 0 {
run.input = append(json.RawMessage(nil), admittedInput...)
}
if change.ResumeKey != "" {
run.resumeKey = change.ResumeKey
run.resumeAnswers = cloneRawMap(resumeAnswers)
}
for _, r := range change.Results {
run.unresolved[fmt.Sprintf("%s/%d", r.Path, r.Attempt)] = OperationRef{
OperationKey: ref.RunID + "/" + r.Path, Path: r.Path, Attempt: r.Attempt,
}
delete(run.unresolved, fmt.Sprintf("%s/%d", r.Path, r.Attempt))
run.results++
run.usage.CompletedOutputBytes += int64(len(r.Output))
}
m.seq += uint64(len(change.Events))
if m.seq == 0 {
m.seq = 1
}
rcpt := Receipt{FirstSequence: m.seq, LastSequence: m.seq}
run.commits[change.CommitID] = memCommit{body: body, receipt: rcpt}
return rcpt, nil
}
// Load returns the recorded recovery state for one admitted run.
func (m *MemoryRunStore) Load(ctx context.Context, runID string) (RecoveryState, error) {
m.mu.Lock()
defer m.mu.Unlock()
run, ok := m.runs[runID]
if !ok {
return RecoveryState{}, &Error{Code: ErrRevisionConflict, Path: runID,
Message: "unknown run"}
}
ops := make([]OperationRef, 0, len(run.unresolved))
for _, op := range run.unresolved {
ops = append(ops, op)
}
sort.Slice(ops, func(i, j int) bool { return ops[i].OperationKey < ops[j].OperationKey })
var cp *CheckpointEnvelope
if run.checkpoint != nil {
v := *run.checkpoint
v.Payload = append([]byte(nil), run.checkpoint.Payload...)
cp = &v
}
waits := make([]WaitRequest, len(run.waits))
copy(waits, run.waits)
ints := map[string]string{}
for k, v := range run.interrupts {
ints[k] = v
}
return RecoveryState{
Ref: run.ref,
Status: run.status,
AdmittedInput: append(json.RawMessage(nil), run.input...),
Limits: run.limits,
Usage: run.usage,
LatestCheckpoint: cp,
Waits: waits,
Interrupts: ints,
Gates: append([]string(nil), run.gates...),
ResumeKey: run.resumeKey,
ResumeAnswers: cloneRawMap(run.resumeAnswers),
UnresolvedOperations: ops,
}, nil
}
// Events exposes the committed event projection for tests and SSE.
func (m *MemoryRunStore) Events(runID string) []Event {
m.mu.Lock()
defer m.mu.Unlock()
run, ok := m.runs[runID]
if !ok {
return nil
}
out := make([]Event, len(run.events))
copy(out, run.events)
return out
}
func opKeyFor(ev Event) string { return fmt.Sprintf("%s/%d", ev.Path, ev.Attempt) }
// commitBody canonicalizes the semantic body (CommitID excluded) for
// idempotency comparison via the JSON wire form.
func commitBody(c RunCommit) (string, error) {
raw, err := json.Marshal(map[string]any{
"events": c.Events,
"results": c.Results,
"checkpoint": c.Checkpoint,
"transition": c.Transition,
"admitted_input": c.AdmittedInput,
"resume_key": c.ResumeKey,
"resume_answers": c.ResumeAnswers,
})
if err != nil {
return "", &Error{Code: ErrInvalidDefinition, Err: err,
Message: "commit body cannot marshal"}
}
b, err := NormalizeJSONValue(raw)
if err != nil {
return "", &Error{Code: ErrInvalidDefinition, Err: err,
Message: "commit body is not canonicalizable"}
}
return string(b), nil
}
func cloneRawMap(src map[string]json.RawMessage) map[string]json.RawMessage {
if src == nil {
return nil
}
out := make(map[string]json.RawMessage, len(src))
for key, value := range src {
out[key] = append(json.RawMessage(nil), value...)
}
return out
}