behavior-contracts 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ package coderuntime
2
+
3
+ import (
4
+ "fmt"
5
+ "sort"
6
+ "sync"
7
+ )
8
+
9
+ // ExecutionPlanSpec is the stage grouping for run_plan.
10
+ type ExecutionPlanSpec struct {
11
+ Groups [][]int
12
+ Concurrency int64
13
+ }
14
+
15
+ // OpSpec describes one operation. Policy is the raw string (validated at run time
16
+ // so unknown policies fail closed rather than at parse time). Parent < 0 = root.
17
+ type OpSpec struct {
18
+ ID string
19
+ Parent int // -1 for root
20
+ BindField string
21
+ HasBindField bool
22
+ RelationKind string // "connection" | "" (既定 = 注記の不在 → 未生成は nil)
23
+ Policy string // "fail" | "retry" | "continue" | "" (unknown)
24
+ HasPolicy bool // whether the policy field was present (absent => default "fail")
25
+ }
26
+
27
+ // ErrorDetail is the structured, recoverable payload a failure carries (scp-error.md "The Error
28
+ // Value"). The leaf produces it at the wire boundary / the runtime at the outType boundary; it is
29
+ // transported verbatim. Concrete fields — no boxed Value, no serialized blob in a string:
30
+ // ExpectedType is Portable Type Notation, a rendering of a statically declared type. Kind is the
31
+ // closed set (typeMismatch / missingField / overflow), empty when the failure is not about a datum.
32
+ type ErrorDetail struct {
33
+ Kind string
34
+ Model string
35
+ Field string
36
+ ExpectedType string
37
+ ActualWireType string
38
+ RawValue string
39
+ Context map[string]string
40
+ }
41
+
42
+ // ExecOutcome is a consumer-supplied node execution result (mock). A failure carries a message plus
43
+ // the structured, recoverable Detail the leaf produced (nil when the failure is not about a datum).
44
+ type ExecOutcome struct {
45
+ IsError bool
46
+ Ok Value
47
+ Err string
48
+ Detail *ErrorDetail
49
+ }
50
+
51
+ // OkOutcome / ErrOutcome are convenience constructors.
52
+ func OkOutcome(v Value) ExecOutcome { return ExecOutcome{Ok: v} }
53
+ func ErrOutcome(e string) ExecOutcome { return ExecOutcome{IsError: true, Err: e} }
54
+
55
+ // ErrOutcomeDetail — a failure outcome carrying a structured Error Value.
56
+ func ErrOutcomeDetail(e string, d *ErrorDetail) ExecOutcome {
57
+ return ExecOutcome{IsError: true, Err: e, Detail: d}
58
+ }
59
+
60
+ // Exec is the consumer callback: exec(op, boundValue) -> outcome.
61
+ type Exec func(op OpSpec, boundValue Value) ExecOutcome
62
+
63
+ // OnSkip is called once, AT THE MOMENT an op is skipped (its Port is settled as
64
+ // unproduced). The caller binds the op's unproduced value there: a later op that
65
+ // reads the skipped op as a non-parent dependency is not skipped and reads that
66
+ // value (scp-error.md "Dependency rules for continue"). It is called only from the
67
+ // single point that records a skip (RunPlan's skip).
68
+ type OnSkip func(op OpSpec)
69
+
70
+ // PlanFailure is a plan execution Failure with a stable code.
71
+ //
72
+ // OpIndex is the operations[] index whose interpretation raised this failure, or
73
+ // -1 when the failure is not attributable to a single op (INVALID_PLAN). Additive
74
+ // (bc#23): RunBehavior uses it to restore the sequential precedence of failures
75
+ // raised inside its exec closure over the synthetic plan-level unwind.
76
+ type PlanFailure struct {
77
+ Code string
78
+ Msg string
79
+ OpIndex int
80
+ Detail *ErrorDetail
81
+ }
82
+
83
+ func (e *PlanFailure) Error() string { return e.Code + ": " + e.Msg }
84
+
85
+ func planFail(code, msg string) *PlanFailure { return &PlanFailure{Code: code, Msg: msg, OpIndex: -1} }
86
+
87
+ func planFailAt(op int, code, msg string) *PlanFailure {
88
+ return &PlanFailure{Code: code, Msg: msg, OpIndex: op}
89
+ }
90
+
91
+ type opStatus int
92
+
93
+ const (
94
+ statusNone opStatus = iota
95
+ statusOK
96
+ statusSkipped
97
+ )
98
+
99
+ type opState struct {
100
+ status opStatus
101
+ value Value
102
+ }
103
+
104
+ // RunResult holds the outcome of run_plan.
105
+ type RunResult struct {
106
+ states []opState
107
+ ops []OpSpec
108
+ Executed []string
109
+ Skipped []string
110
+ }
111
+
112
+ // FinalTree builds the observed result tree (opId -> value; Skip -> unproduced form).
113
+ func (r *RunResult) FinalTree() *Obj {
114
+ tree := NewObj()
115
+ for i, st := range r.states {
116
+ switch st.status {
117
+ case statusOK:
118
+ tree.Set(r.ops[i].ID, st.value)
119
+ case statusSkipped:
120
+ tree.Set(r.ops[i].ID, unproducedValue(r.ops[i].RelationKind))
121
+ }
122
+ }
123
+ return tree
124
+ }
125
+
126
+ func unproducedValue(kind string) Value {
127
+ if kind == "connection" {
128
+ o := NewObj()
129
+ o.Set("items", []Value{})
130
+ o.Set("cursor", nil)
131
+ return o
132
+ }
133
+ return nil
134
+ }
135
+
136
+ // parsePolicy resolves the effective policy. An ABSENT policy field defaults to
137
+ // "fail"; a PRESENT but unknown value (including "") is fail-closed as
138
+ // UNKNOWN_POLICY — matching TS `?? 'fail'` (defaults only undefined/null), not a
139
+ // truthy default that would silently coerce "" to "fail".
140
+ func parsePolicy(hasPolicy bool, raw string) (string, error) {
141
+ if !hasPolicy {
142
+ return "fail", nil
143
+ }
144
+ switch raw {
145
+ case "fail":
146
+ return "fail", nil
147
+ case "retry":
148
+ return "retry", nil
149
+ case "continue":
150
+ return "continue", nil
151
+ default:
152
+ return "", planFail("UNKNOWN_POLICY", "unknown policy kind: "+raw)
153
+ }
154
+ }
155
+
156
+ // RunPlan executes the plan. plan may be nil (1 op = 1 stage fallback).
157
+ //
158
+ // Bounded parallel stage execution (bc#23, execution-plan.md §4.1): when
159
+ // plan.Concurrency > 1 and a stage has 2+ members, the member execs are
160
+ // dispatched speculatively on a bounded worker pool (up to Concurrency), while
161
+ // interpretation (Skip / Policy Kind / Failure) is COMMITTED in ascending index
162
+ // order — the observed result (tree / executed / skipped / failure code+message)
163
+ // is byte-identical to sequential execution. A consumer shipping a plan with
164
+ // Concurrency > 1 declares that its exec callback is safe to call from that many
165
+ // goroutines concurrently (ship Concurrency: 1 otherwise). Safe fallbacks that
166
+ // keep sequential dispatch (results unchanged): Concurrency <= 1, single-member
167
+ // stages, or intra-stage parent/child dependencies (defense against §1-violating
168
+ // plans — preserves sequential visibility semantics).
169
+ //
170
+ // onSkip is optional (at most one): see OnSkip.
171
+ func RunPlan(plan *ExecutionPlanSpec, ops []OpSpec, exec Exec, onSkip ...OnSkip) (*RunResult, error) {
172
+ n := len(ops)
173
+ states := make([]opState, n)
174
+ var executedIdx, skippedIdx []int
175
+ skip := makeSkip(ops, &skippedIdx, onSkip)
176
+
177
+ var stages [][]int
178
+ concurrency := int64(1)
179
+ if plan != nil {
180
+ stages = plan.Groups
181
+ concurrency = plan.Concurrency
182
+ } else {
183
+ stages = make([][]int, n)
184
+ for i := range ops {
185
+ stages[i] = []int{i}
186
+ }
187
+ }
188
+
189
+ if err := validateCoverage(stages, n); err != nil {
190
+ return nil, err
191
+ }
192
+
193
+ for _, stage := range stages {
194
+ ordered := append([]int(nil), stage...)
195
+ sort.Ints(ordered) // determinism: interpretation is committed in ascending index order
196
+
197
+ inStage := map[int]bool{}
198
+ for _, i := range ordered {
199
+ inStage[i] = true
200
+ }
201
+ hasIntraDeps := false
202
+ for _, i := range ordered {
203
+ if ops[i].Parent >= 0 && inStage[ops[i].Parent] {
204
+ hasIntraDeps = true
205
+ break
206
+ }
207
+ }
208
+
209
+ if concurrency <= 1 || len(ordered) <= 1 || hasIntraDeps {
210
+ // Sequential fallback (§4.1): per-op preflight → exec → commit, serially.
211
+ for _, i := range ordered {
212
+ st, err := runOp(i, ops[i], states, exec, &executedIdx, skip)
213
+ if err != nil {
214
+ return nil, err
215
+ }
216
+ states[i] = st
217
+ }
218
+ continue
219
+ }
220
+
221
+ // ── Parallel path (bc#23) ─────────────────────────────────────────────
222
+ // Preflight (ascending index): prior-stage states are settled and stage
223
+ // members are mutually independent (§1), so skip decisions and bindField
224
+ // bindings are derivable before dispatch — identical to sequential.
225
+ pres := make([]opPreflight, len(ordered))
226
+ numExec := 0
227
+ for k, i := range ordered {
228
+ pres[k] = preflightOp(ops[i], states)
229
+ if pres[k].kind == preExec {
230
+ numExec++
231
+ }
232
+ }
233
+
234
+ // Dispatch (ascending index, bounded): jobs are sent in declaration order;
235
+ // panics are captured per worker and re-raised at commit in declaration
236
+ // order (matching sequential panic propagation).
237
+ type settled struct {
238
+ outcome ExecOutcome
239
+ panicked bool
240
+ panicVal any
241
+ }
242
+ outcomes := make([]settled, len(ordered))
243
+ workers := int(concurrency)
244
+ if workers > numExec {
245
+ workers = numExec
246
+ }
247
+ jobs := make(chan int)
248
+ var wg sync.WaitGroup
249
+ for w := 0; w < workers; w++ {
250
+ wg.Add(1)
251
+ go func() {
252
+ defer wg.Done()
253
+ for k := range jobs {
254
+ i := ordered[k]
255
+ func() {
256
+ defer func() {
257
+ if r := recover(); r != nil {
258
+ outcomes[k] = settled{panicked: true, panicVal: r}
259
+ }
260
+ }()
261
+ outcomes[k] = settled{outcome: exec(ops[i], pres[k].bound)}
262
+ }()
263
+ }
264
+ }()
265
+ }
266
+ for k := range ordered {
267
+ if pres[k].kind == preExec {
268
+ jobs <- k
269
+ }
270
+ }
271
+ close(jobs)
272
+ wg.Wait()
273
+
274
+ // Commit (ascending index): interpret outcomes in declaration order — the
275
+ // failure identity matches sequential execution exactly.
276
+ for k, i := range ordered {
277
+ switch pres[k].kind {
278
+ case preInvalidPolicy:
279
+ return nil, planFailAt(i, "UNKNOWN_POLICY", pres[k].msg)
280
+ case preSkip:
281
+ states[i] = skip(i)
282
+ default:
283
+ if outcomes[k].panicked {
284
+ panic(outcomes[k].panicVal) // propagate like sequential exec panics
285
+ }
286
+ st, err := interpretOutcome(i, ops[i], pres[k].policy, outcomes[k].outcome, &executedIdx, skip)
287
+ if err != nil {
288
+ return nil, err
289
+ }
290
+ states[i] = st
291
+ }
292
+ }
293
+ }
294
+
295
+ sort.Ints(executedIdx)
296
+ sort.Ints(skippedIdx)
297
+ res := &RunResult{states: states, ops: ops}
298
+ for _, i := range executedIdx {
299
+ res.Executed = append(res.Executed, ops[i].ID)
300
+ }
301
+ for _, i := range skippedIdx {
302
+ res.Skipped = append(res.Skipped, ops[i].ID)
303
+ }
304
+ return res, nil
305
+ }
306
+
307
+ type preKind int
308
+
309
+ const (
310
+ preExec preKind = iota
311
+ preSkip
312
+ preInvalidPolicy
313
+ )
314
+
315
+ // preflight is the pure pre-exec decision for one op (policy validation → skip
316
+ // decision → bindField binding), shared by the sequential and parallel paths.
317
+ type opPreflight struct {
318
+ kind preKind
319
+ policy string // effective policy (kind == preExec)
320
+ bound Value // bindField binding (kind == preExec)
321
+ msg string // failure message (kind == preInvalidPolicy)
322
+ }
323
+
324
+ // preflightOp mirrors the first half of the sequential runOp exactly: the policy
325
+ // check precedes the skip decision (UNKNOWN_POLICY fires even for ops that would
326
+ // be skipped).
327
+ func preflightOp(op OpSpec, states []opState) opPreflight {
328
+ policy, err := parsePolicy(op.HasPolicy, op.Policy)
329
+ if err != nil {
330
+ return opPreflight{kind: preInvalidPolicy, msg: err.(*PlanFailure).Msg} // fail-closed on unknown
331
+ }
332
+
333
+ var boundValue Value
334
+ if op.Parent >= 0 {
335
+ parent := states[op.Parent]
336
+ if parent.status != statusOK {
337
+ return opPreflight{kind: preSkip}
338
+ }
339
+ if op.HasBindField {
340
+ var bound Value
341
+ var present bool
342
+ if o, ok := parent.value.(*Obj); ok {
343
+ bound, present = o.Get(op.BindField)
344
+ }
345
+ if !present || bound == nil {
346
+ return opPreflight{kind: preSkip}
347
+ }
348
+ boundValue = bound
349
+ }
350
+ }
351
+ return opPreflight{kind: preExec, policy: policy, bound: boundValue}
352
+ }
353
+
354
+ // interpretOutcome is the second half of the sequential runOp (executed
355
+ // bookkeeping → Policy Kind interpretation), shared by both paths so failure
356
+ // messages stay identical.
357
+ func interpretOutcome(i int, op OpSpec, policy string, outcome ExecOutcome, executedIdx *[]int, skip func(int) opState) (opState, error) {
358
+ *executedIdx = append(*executedIdx, i)
359
+
360
+ if !outcome.IsError {
361
+ return opState{status: statusOK, value: outcome.Ok}, nil
362
+ }
363
+
364
+ switch policy {
365
+ case "fail":
366
+ f := planFailAt(i, "OP_FAILED", fmt.Sprintf("operation '%s' failed under 'fail' policy: %s", op.ID, outcome.Err))
367
+ f.Detail = outcome.Detail // transport the leaf's Error Value verbatim
368
+ return opState{}, f
369
+ case "retry":
370
+ f := planFailAt(i, "OP_FAILED", fmt.Sprintf("operation '%s' failed under 'retry' policy (exhausted): %s", op.ID, outcome.Err))
371
+ f.Detail = outcome.Detail
372
+ return opState{}, f
373
+ default: // continue: failed op produces no Port -> skip downstream
374
+ *executedIdx = (*executedIdx)[:len(*executedIdx)-1] // ran but produced no Port
375
+ return skip(i), nil
376
+ }
377
+ }
378
+
379
+ // makeSkip builds the SINGLE point that records an op as skipped: the skipped
380
+ // bookkeeping and the OnSkip notification happen at the same moment (a preflight
381
+ // skip and a continue-failure skip, sequential or parallel commit, all go here).
382
+ func makeSkip(ops []OpSpec, skippedIdx *[]int, onSkip []OnSkip) func(int) opState {
383
+ return func(i int) opState {
384
+ *skippedIdx = append(*skippedIdx, i)
385
+ for _, f := range onSkip {
386
+ f(ops[i])
387
+ }
388
+ return opState{status: statusSkipped}
389
+ }
390
+ }
391
+
392
+ func runOp(i int, op OpSpec, states []opState, exec Exec, executedIdx *[]int, skip func(int) opState) (opState, error) {
393
+ pre := preflightOp(op, states)
394
+ switch pre.kind {
395
+ case preInvalidPolicy:
396
+ return opState{}, planFailAt(i, "UNKNOWN_POLICY", pre.msg)
397
+ case preSkip:
398
+ return skip(i), nil
399
+ }
400
+
401
+ outcome := exec(op, pre.bound)
402
+ return interpretOutcome(i, op, pre.policy, outcome, executedIdx, skip)
403
+ }
404
+
405
+ func validateCoverage(stages [][]int, n int) error {
406
+ seen := map[int]bool{}
407
+ for _, stage := range stages {
408
+ for _, i := range stage {
409
+ if i < 0 || i >= n {
410
+ return planFail("INVALID_PLAN", fmt.Sprintf("stage index %d out of range [0,%d)", i, n))
411
+ }
412
+ if seen[i] {
413
+ return planFail("INVALID_PLAN", fmt.Sprintf("operation %d appears in more than one stage", i))
414
+ }
415
+ seen[i] = true
416
+ }
417
+ }
418
+ if len(seen) != n {
419
+ return planFail("INVALID_PLAN", fmt.Sprintf("plan does not cover all %d operations (covered %d)", n, len(seen)))
420
+ }
421
+ return nil
422
+ }