ContextWithRun stores rc in ctx. Step counter cleanup is reference-counted per RunID: each live RunContext increments a counter and runtime.AddCleanup decrements it when the struct is garbage collected. Shared state (step counters) is only deleted when the last RunContext for a given RunID becomes
(ctx context.Context, rc *RunContext)
| 27 | // RunID becomes unreachable, preventing premature cleanup when |
| 28 | // multiple RunContext instances share the same RunID. |
| 29 | func ContextWithRun(ctx context.Context, rc *RunContext) context.Context { |
| 30 | if rc == nil { |
| 31 | panic("chatdebug: nil RunContext") |
| 32 | } |
| 33 | |
| 34 | enriched := context.WithValue(ctx, runContextKey{}, rc) |
| 35 | if rc.RunID != uuid.Nil { |
| 36 | trackRunRef(rc.RunID) |
| 37 | runtime.AddCleanup(rc, func(id uuid.UUID) { |
| 38 | releaseRunRef(id) |
| 39 | }, rc.RunID) |
| 40 | } |
| 41 | return enriched |
| 42 | } |
| 43 | |
| 44 | // RunFromContext returns the debug run context stored in ctx. |
| 45 | func RunFromContext(ctx context.Context) (*RunContext, bool) { |