-
Notifications
You must be signed in to change notification settings - Fork 390
Replace N+1 execution fetches in batch-status handler with one batch fetch #811
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b10b86b
issue/batch-status-n-plus-1: replace N+1 execution fetches in batch-s…
AbirAbbas ae4e11d
Merge remote-tracking branch 'origin/main' into issue/417f3831-batch-…
AbirAbbas ee8b9fb
fix: preserve batch status partial results
AbirAbbas f43370c
chore(skills): sync embedded skill mirrors on branch
AbirAbbas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
206 changes: 206 additions & 0 deletions
206
control-plane/internal/handlers/execute_batch_status_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| package handlers | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/Agent-Field/agentfield/control-plane/pkg/types" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| var errBatchStorageBoom = errors.New("storage unavailable") | ||
|
|
||
| // batchCountingStorage wraps testExecutionStorage and counts how many times | ||
| // the batch fetch method is invoked, so tests can assert the N+1 fix. | ||
| type batchCountingStorage struct { | ||
| *testExecutionStorage | ||
| batchCalls int | ||
| singleGetCalls int | ||
| getExecutionRecordsBatchErr error | ||
| getExecutionRecordErrs map[string]error | ||
| } | ||
|
|
||
| func newBatchCountingStorage() *batchCountingStorage { | ||
| return &batchCountingStorage{ | ||
| testExecutionStorage: newTestExecutionStorage(nil), | ||
| } | ||
| } | ||
|
|
||
| // Override the single-record fetch to count it; the handler should no longer | ||
| // touch this path for batch status. | ||
| func (s *batchCountingStorage) GetExecutionRecord(ctx context.Context, executionID string) (*types.Execution, error) { | ||
| s.singleGetCalls++ | ||
| if err := s.getExecutionRecordErrs[executionID]; err != nil { | ||
| return nil, err | ||
| } | ||
| return s.testExecutionStorage.GetExecutionRecord(ctx, executionID) | ||
| } | ||
|
|
||
| func (s *batchCountingStorage) GetExecutionRecordsBatch(ctx context.Context, executionIDs []string) (map[string]*types.Execution, error) { | ||
| s.batchCalls++ | ||
| if s.getExecutionRecordsBatchErr != nil { | ||
| return nil, s.getExecutionRecordsBatchErr | ||
| } | ||
| return s.testExecutionStorage.GetExecutionRecordsBatch(ctx, executionIDs) | ||
| } | ||
|
|
||
| func seedBatchExecution(t *testing.T, store *batchCountingStorage, id, status string) { | ||
| t.Helper() | ||
| now := time.Now().UTC() | ||
| exec := &types.Execution{ | ||
| ExecutionID: id, | ||
| RunID: "run-batch", | ||
| AgentNodeID: "agent-1", | ||
| ReasonerID: "reasoner-" + id, | ||
| NodeID: "node-1", | ||
| Status: status, | ||
| StartedAt: now, | ||
| CreatedAt: now, | ||
| UpdatedAt: now, | ||
| } | ||
| require.NoError(t, store.CreateExecutionRecord(context.Background(), exec)) | ||
| } | ||
|
|
||
| func TestHandleBatchStatus_SingleFetchForTenIDs(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
|
|
||
| store := newBatchCountingStorage() | ||
|
|
||
| // Seed 10 existing executions. | ||
| for i := 0; i < 10; i++ { | ||
| seedBatchExecution(t, store, "exec-"+string(rune('a'+i)), string(types.ExecutionStatusSucceeded)) | ||
| } | ||
|
|
||
| // Request 10 existing + 2 missing. | ||
| ids := []string{ | ||
| "exec-a", "exec-b", "exec-c", "exec-d", "exec-e", | ||
| "exec-f", "exec-g", "exec-h", "exec-i", "exec-j", | ||
| "missing-1", "missing-2", | ||
| } | ||
| body, _ := json.Marshal(BatchStatusRequest{ExecutionIDs: ids}) | ||
|
|
||
| router := gin.New() | ||
| router.POST("/batch", BatchExecutionStatusHandler(store)) | ||
|
|
||
| req := httptest.NewRequest(http.MethodPost, "/batch", bytes.NewReader(body)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| w := httptest.NewRecorder() | ||
| router.ServeHTTP(w, req) | ||
|
|
||
| require.Equal(t, http.StatusOK, w.Code) | ||
| require.Equal(t, 1, store.batchCalls, "handleBatchStatus must make exactly one storage fetch") | ||
| require.Equal(t, 0, store.singleGetCalls, "handleBatchStatus must not call GetExecutionRecord per ID") | ||
|
|
||
| var response BatchStatusResponse | ||
| require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) | ||
| require.Len(t, response, len(ids)) | ||
|
|
||
| // Existing IDs get the rendered status response contract. | ||
| for _, id := range ids[:10] { | ||
| entry, ok := response[id] | ||
| require.True(t, ok, "missing entry for %s", id) | ||
| require.Equal(t, id, entry.ExecutionID) | ||
| require.Equal(t, "run-batch", entry.RunID) | ||
| require.Equal(t, string(types.ExecutionStatusSucceeded), entry.Status) | ||
| require.NotEmpty(t, entry.StartedAt) | ||
| } | ||
|
|
||
| // Missing IDs preserve the prior per-ID response behavior: not_found. | ||
| for _, id := range ids[10:] { | ||
| entry, ok := response[id] | ||
| require.True(t, ok, "missing entry for %s", id) | ||
| require.Equal(t, id, entry.ExecutionID) | ||
| require.Equal(t, "not_found", entry.Status) | ||
| } | ||
| } | ||
|
|
||
| func TestHandleBatchStatus_RejectsOversizedBatch(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
|
|
||
| store := newBatchCountingStorage() | ||
|
|
||
| ids := make([]string, 501) | ||
| for i := range ids { | ||
| ids[i] = "exec-" + string(rune('a'+i%26)) | ||
| } | ||
| body, _ := json.Marshal(BatchStatusRequest{ExecutionIDs: ids}) | ||
|
|
||
| router := gin.New() | ||
| router.POST("/batch", BatchExecutionStatusHandler(store)) | ||
|
|
||
| req := httptest.NewRequest(http.MethodPost, "/batch", bytes.NewReader(body)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| w := httptest.NewRecorder() | ||
| router.ServeHTTP(w, req) | ||
|
|
||
| require.Equal(t, http.StatusBadRequest, w.Code) | ||
| require.Equal(t, 0, store.batchCalls, "oversized batch must not hit storage") | ||
| } | ||
|
|
||
| func TestHandleBatchStatus_BatchStorageErrorPreservesPerIDResults(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
|
|
||
| store := newBatchCountingStorage() | ||
| store.getExecutionRecordsBatchErr = errBatchStorageBoom | ||
| store.getExecutionRecordErrs = map[string]error{"bad": errBatchStorageBoom} | ||
| seedBatchExecution(t, store, "good", string(types.ExecutionStatusSucceeded)) | ||
|
|
||
| body, _ := json.Marshal(BatchStatusRequest{ExecutionIDs: []string{"bad", "good"}}) | ||
| router := gin.New() | ||
| router.POST("/batch", BatchExecutionStatusHandler(store)) | ||
|
|
||
| req := httptest.NewRequest(http.MethodPost, "/batch", bytes.NewReader(body)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| w := httptest.NewRecorder() | ||
| router.ServeHTTP(w, req) | ||
|
|
||
| require.Equal(t, http.StatusOK, w.Code) | ||
| require.Equal(t, 1, store.batchCalls) | ||
| require.Equal(t, 2, store.singleGetCalls) | ||
|
|
||
| var response BatchStatusResponse | ||
| require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) | ||
| require.Equal(t, "error", response["bad"].Status) | ||
| require.Contains(t, *response["bad"].Error, "load execution: storage unavailable") | ||
| require.Equal(t, string(types.ExecutionStatusSucceeded), response["good"].Status) | ||
| } | ||
|
|
||
| func TestHandleBatchStatus_BatchStorageErrorWithCanceledContextReturnsPerIDErrors(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
|
|
||
| store := newBatchCountingStorage() | ||
| store.getExecutionRecordsBatchErr = context.Canceled | ||
| store.getExecutionRecordErrs = map[string]error{ | ||
| "exec-a": context.Canceled, | ||
| "exec-b": context.Canceled, | ||
| } | ||
| body, _ := json.Marshal(BatchStatusRequest{ExecutionIDs: []string{"exec-a", "exec-b"}}) | ||
| router := gin.New() | ||
| router.POST("/batch", BatchExecutionStatusHandler(store)) | ||
|
|
||
| reqCtx, cancel := context.WithCancel(context.Background()) | ||
| cancel() | ||
| req := httptest.NewRequest(http.MethodPost, "/batch", bytes.NewReader(body)).WithContext(reqCtx) | ||
| req.Header.Set("Content-Type", "application/json") | ||
| w := httptest.NewRecorder() | ||
| router.ServeHTTP(w, req) | ||
|
|
||
| require.Equal(t, http.StatusOK, w.Code) | ||
| require.Equal(t, 1, store.batchCalls) | ||
| require.Equal(t, 2, store.singleGetCalls) | ||
|
|
||
| var response BatchStatusResponse | ||
| require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) | ||
| for _, id := range []string{"exec-a", "exec-b"} { | ||
| require.Equal(t, "error", response[id].Status) | ||
| require.Contains(t, *response[id].Error, "load execution: context canceled") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Caution
Must-fix before merge. This changes the public batch-polling API from partial results (HTTP 200) to all-or-nothing (HTTP 500), breaking existing clients with no migration path.
Make the batch-status endpoint return partial per-ID results on mixed failures, or explicitly declare the all‑or‑nothing contract and add mixed-error regression tests.
🟠
IMPORTANT· confidence 95%The handler at lines 820–823 returns HTTP 500 for any batch read error, discarding results for IDs that succeeded. Previously, each ID error was recorded in the response map and an HTTP 200 was returned, so clients could process the successful ID. This breaks the documented partial‑results contract, and the new tests only cover a single‑ID 500 case.
Evidence
💡 Suggested Fix
Preserve partial responses by representing per-ID batch errors or falling back to individual reads after a batch error. If the API intentionally becomes all-or-nothing, document that HTTP 500 behavior for batch polling and add mixed success/failure plus canceled-context/query-error regression tests.
Batch-status failure contract· confidence 95%🤖 Reviewed by AgentField PR-AF