|
| 1 | +package runtime |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sync/atomic" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + |
| 11 | + "github.com/docker/docker-agent/pkg/agent" |
| 12 | + "github.com/docker/docker-agent/pkg/config/latest" |
| 13 | + "github.com/docker/docker-agent/pkg/hooks" |
| 14 | + "github.com/docker/docker-agent/pkg/session" |
| 15 | + "github.com/docker/docker-agent/pkg/team" |
| 16 | +) |
| 17 | + |
| 18 | +// TestBeforeLLMCallHookFiresOncePerLoopIteration is a regression test |
| 19 | +// for a duplicate dispatch in [LocalRuntime.RunStream] that fired |
| 20 | +// [LocalRuntime.executeBeforeLLMCallHooks] twice per iteration. The |
| 21 | +// bug would silently break stateful before_llm_call hooks (the |
| 22 | +// max_iterations builtin would have tripped at half its configured |
| 23 | +// limit). A single-turn session must observe exactly one fire. |
| 24 | +func TestBeforeLLMCallHookFiresOncePerLoopIteration(t *testing.T) { |
| 25 | + t.Parallel() |
| 26 | + |
| 27 | + const counterName = "test-before-llm-counter" |
| 28 | + var calls atomic.Int32 |
| 29 | + |
| 30 | + stream := newStreamBuilder(). |
| 31 | + AddContent("Hello"). |
| 32 | + AddStopWithUsage(3, 2). |
| 33 | + Build() |
| 34 | + prov := &mockProvider{id: "test/mock-model", stream: stream} |
| 35 | + |
| 36 | + root := agent.New("root", "test agent", |
| 37 | + agent.WithModel(prov), |
| 38 | + agent.WithHooks(&latest.HooksConfig{ |
| 39 | + BeforeLLMCall: []latest.HookDefinition{ |
| 40 | + {Type: "builtin", Command: counterName}, |
| 41 | + }, |
| 42 | + }), |
| 43 | + ) |
| 44 | + tm := team.New(team.WithAgents(root)) |
| 45 | + |
| 46 | + rt, err := NewLocalRuntime(tm, |
| 47 | + WithSessionCompaction(false), |
| 48 | + WithModelStore(mockModelStore{}), |
| 49 | + ) |
| 50 | + require.NoError(t, err) |
| 51 | + |
| 52 | + // Builtin lookup happens at dispatch time, not at executor build, |
| 53 | + // so registering after NewLocalRuntime is sufficient. |
| 54 | + require.NoError(t, rt.hooksRegistry.RegisterBuiltin( |
| 55 | + counterName, |
| 56 | + func(_ context.Context, _ *hooks.Input, _ []string) (*hooks.Output, error) { |
| 57 | + calls.Add(1) |
| 58 | + return nil, nil |
| 59 | + }, |
| 60 | + )) |
| 61 | + |
| 62 | + sess := session.New(session.WithUserMessage("hi")) |
| 63 | + sess.Title = "Unit Test" |
| 64 | + |
| 65 | + for range rt.RunStream(t.Context(), sess) { |
| 66 | + } |
| 67 | + |
| 68 | + assert.Equal(t, int32(1), calls.Load(), |
| 69 | + "before_llm_call must fire exactly once per loop iteration; "+ |
| 70 | + "a duplicate dispatch would silently break stateful hooks like max_iterations") |
| 71 | +} |
0 commit comments