forked from alibaba/open-code-review
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(scan): report token budget stop in JSON summary.budget_exceeded #25
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
Open
chethanuk
wants to merge
1
commit into
main
Choose a base branch
from
feat/issue-771-scan-budget-exceeded
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+215
−9
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // Copyright 2026 alibaba/open-code-review Contributors | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/alibaba/open-code-review/internal/config/template" | ||
| "github.com/alibaba/open-code-review/internal/llm" | ||
| "github.com/alibaba/open-code-review/internal/scan" | ||
| "github.com/alibaba/open-code-review/internal/session" | ||
| "github.com/alibaba/open-code-review/internal/tool" | ||
| ) | ||
|
|
||
| // fakeScanBudgetClient finishes every file in one round and reports a fixed | ||
| // 50K token usage, so the aggregate budget gate trips deterministically. | ||
| type fakeScanBudgetClient struct{} | ||
|
|
||
| func (fakeScanBudgetClient) CompletionsWithCtx(_ context.Context, _ llm.ChatRequest) (*llm.ChatResponse, error) { | ||
| return &llm.ChatResponse{ | ||
| Choices: []llm.Choice{{ | ||
| Message: llm.ResponseMessage{ | ||
| Role: "assistant", | ||
| ToolCalls: []llm.ToolCall{{ | ||
| ID: "1", | ||
| Type: "function", | ||
| Function: llm.FunctionCall{Name: "task_done", Arguments: "{}"}, | ||
| }}, | ||
| }, | ||
| FinishReason: "tool_calls", | ||
| }}, | ||
| Usage: &llm.UsageInfo{PromptTokens: 50_000, TotalTokens: 50_000}, | ||
| }, nil | ||
| } | ||
|
|
||
| // TestScanBudgetJSON is the end-to-end contract for #771: a real *scan.Agent, | ||
| // real enumeration, real budget gate, through the shared emitRunResult | ||
| // pipeline. BudgetExceeded() was hard-coded false, so summary.budget_exceeded | ||
| // never appeared however early the gate cut the run short. | ||
| // | ||
| // The unlimited case asserts on the RAW capture, not the decoded struct: | ||
| // budget_exceeded is omitempty, so false and absent are indistinguishable | ||
| // after Unmarshal. | ||
| func TestScanBudgetJSON(t *testing.T) { | ||
| cases := []struct { | ||
| name string | ||
| budget int64 | ||
| want bool | ||
| wantStatus string | ||
| }{ | ||
| // The budget stop must NOT invent a typed status: it stays the | ||
| // ordinary warning-derived one (output.go leaves out.Status alone). | ||
| {name: "budget stop sets budget_exceeded", budget: 120_000, want: true, wantStatus: "completed_with_warnings"}, | ||
| {name: "unlimited budget omits the key", budget: 0, want: false, wantStatus: "success"}, | ||
| } | ||
|
|
||
| for _, tc := range cases { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| t.Setenv("HOME", t.TempDir()) | ||
|
|
||
| repoDir := t.TempDir() | ||
| // Zero-padded so lexical walk order is stable (f10 vs f2). | ||
| for _, name := range []string{"f01.go", "f02.go", "f03.go", "f04.go", "f05.go", "f06.go", "f07.go", "f08.go"} { | ||
| if err := os.WriteFile(filepath.Join(repoDir, name), []byte("package x\n"), 0o600); err != nil { | ||
| t.Fatalf("write %s: %v", name, err) | ||
| } | ||
| } | ||
|
|
||
| ag := scan.NewAgent(scan.Args{ | ||
| RepoDir: repoDir, | ||
| Template: template.ScanTemplate{ | ||
| MaxTokens: 100000, | ||
| MaxToolRequestTimes: 5, | ||
| MainTask: template.LlmConversation{ | ||
| Messages: []template.ChatMessage{ | ||
| {Role: "system", Content: "scan"}, | ||
| {Role: "user", Content: "review {{file_content}}"}, | ||
| }, | ||
| }, | ||
| }, | ||
| LLMClient: fakeScanBudgetClient{}, | ||
| Tools: tool.NewRegistry(), | ||
| CommentCollector: tool.NewCommentCollector(), | ||
| MaxConcurrency: 1, // serialize so the gate is deterministic | ||
| MaxTokensBudget: tc.budget, | ||
| Session: session.New(t.TempDir(), "main", "test", session.SessionOptions{ReviewMode: session.ReviewModeFullScan}), | ||
| SkipPlan: true, | ||
| SkipDedup: true, | ||
| SkipSummary: true, | ||
| }) | ||
|
|
||
| comments, err := ag.Run(context.Background()) | ||
| if err != nil { | ||
| t.Fatalf("scan Run: %v", err) | ||
| } | ||
|
|
||
| raw := captureStdout(t, func() { | ||
| if err := emitRunResult(context.Background(), ag, comments, time.Now(), "json", "developer", nil, nil, nil); err != nil { | ||
| t.Fatalf("emitRunResult: %v", err) | ||
| } | ||
| }) | ||
|
|
||
| var out jsonOutput | ||
| if err := json.Unmarshal([]byte(raw), &out); err != nil { | ||
| t.Fatalf("unmarshal %q: %v", raw, err) | ||
| } | ||
| if out.Status != tc.wantStatus { | ||
| t.Errorf("status = %q, want %q", out.Status, tc.wantStatus) | ||
| } | ||
| if out.Summary == nil { | ||
| t.Fatal("summary must be present") | ||
| } | ||
| if got := out.Summary.BudgetExceeded; got != tc.want { | ||
| t.Errorf("summary.budget_exceeded = %v, want %v", got, tc.want) | ||
| } | ||
| if !tc.want && strings.Contains(raw, "budget_exceeded") { | ||
| t.Errorf("unlimited budget must omit budget_exceeded entirely, got %s", raw) | ||
| } | ||
|
|
||
| var warned bool | ||
| for _, w := range out.Warnings { | ||
| if w.Type == "token_budget_reached" { | ||
| warned = true | ||
| break | ||
| } | ||
| } | ||
| if warned != tc.want { | ||
| t.Errorf("token_budget_reached warning present = %v, want %v", warned, tc.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // Copyright 2026 alibaba/open-code-review Contributors | ||
|
|
||
| package scan | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/alibaba/open-code-review/internal/session" | ||
| "github.com/alibaba/open-code-review/internal/tool" | ||
| ) | ||
|
|
||
| // TestBudgetExceededFlag pins BudgetExceeded() to the actual state of the | ||
| // token budget gate. Before this it was hard-coded false, so a budget stop | ||
| // never reached summary.budget_exceeded in `ocr scan --format json` (#771). | ||
| // | ||
| // Both cases run the same 50K-tokens-per-file fake through dispatchSubtasks; | ||
| // only MaxTokensBudget differs. MaxConcurrency=1 serializes dispatch so the | ||
| // gate trips deterministically. | ||
| // | ||
| // The zero-value case is not repeated here: TestScanGettersOnEmptyAgent in | ||
| // getters_test.go already asserts BudgetExceeded()==false on &Agent{}, and | ||
| // that assertion stops being vacuous now that the getter reads a field. | ||
| func TestBudgetExceededFlag(t *testing.T) { | ||
| cases := []struct { | ||
| name string | ||
| budget int64 | ||
| items int | ||
| want bool | ||
| }{ | ||
| {name: "gate trips", budget: 120_000, items: 10, want: true}, | ||
| {name: "unlimited budget", budget: 0, items: 5, want: false}, | ||
| } | ||
|
|
||
| for _, tc := range cases { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| a := NewAgent(Args{ | ||
| Template: budgetTestTemplate(), | ||
| LLMClient: &fakeBudgetClient{perCallTokens: 50_000}, | ||
| CommentCollector: tool.NewCommentCollector(), | ||
| Tools: tool.NewRegistry(), | ||
| MaxConcurrency: 1, | ||
| MaxTokensBudget: tc.budget, | ||
| Session: session.New(t.TempDir(), "main", "test", session.SessionOptions{ReviewMode: session.ReviewModeFullScan}), | ||
| SkipPlan: true, | ||
| SkipDedup: true, | ||
| SkipSummary: true, | ||
| }) | ||
| a.items = makeScanItems(tc.items) | ||
| a.args.Tools.Freeze() | ||
|
|
||
| if _, err := a.dispatchSubtasks(context.Background()); err != nil { | ||
| t.Fatalf("dispatchSubtasks: %v", err) | ||
| } | ||
| if got := a.BudgetExceeded(); got != tc.want { | ||
| t.Errorf("BudgetExceeded() = %v, want %v", got, tc.want) | ||
| } | ||
| }) | ||
| } | ||
| } |
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.
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.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep the budget-stop status as
success.Line 60 expects
completed_with_warnings, but the PR contract requires scan status to remainsuccessafter an aggregate token-budget stop. A conforming implementation will fail this test. Do not change production output to satisfy this expectation.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents