Skip to content

[api][plan][runtime] Add per-chat budgets for turns, time, and tokens - #1397

Open
eemario wants to merge 8 commits into
apache:mainfrom
eemario:codex/chat-loop-budget
Open

eemario wants to merge 8 commits into
apache:mainfrom
eemario:codex/chat-loop-budget

Conversation

@eemario

@eemario eemario commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue: #1398
Design discussion: #1409

Purpose of change

Allow users to limit turns, elapsed time, and token usage for each chat loop, preventing unbounded execution and resource consumption.

Runtime flow

Resolve the request budget or job-level defaults, then check limits before each turn, including before routing. Model responses update token usage. Exhaustion starts a tool-free closing turn or returns a failed response.

Key decisions

Check at turn boundaries rather than interrupting in-flight calls. Routing, retries, fallback, and structured-output conversion belong to the same turn. Subagents track independent budgets.

Behavioral Semantics

Interaction decisions

Condition Behavior
No request budget Use job-level defaults; unlimited if unset
Explicit request budget Replace all job-level budget defaults
Multiple limits Any exhausted limit triggers the configured mode
SOFT (default) Allow one additional tool-free turn, including retries and structured-output conversion
HARD Return a failed ChatResponseEvent without starting another turn
Subagent invocation Exclude child turns/tokens from the parent budget; parent elapsed time includes waiting

Behavioral contracts

  • A turn calls the model and executes its requested tools. Routing, retries, fallback, and structured-output conversion do not consume additional turns.
  • Time includes recovery downtime. Limits do not interrupt an admitted turn or guarantee a strict spending ceiling.
  • Tokens accumulate from reported input/output usage, including LLM-judge calls. Missing usage logs a warning and may undercount consumption.
  • Recovery preserves the persisted start time and reconstructs budget usage from replayed results. Re-execution may incur additional external consumption.

Failure behavior

Invalid budgets are rejected. Model and parsing failures retain existing retry/fallback behavior. HARD exhaustion, unsuccessful SOFT finalization, or tool calls returned by SOFT finalization produce a failed ChatResponseEvent. Persistence failures continue through the existing runtime failure path.

Tests

Contract Coverage
Validation and serialization ReActLoopBudgetTest, test_react_loop_budget.py
Request overrides and turn-boundary checks ChatModelActionRetryTest, test_chat_model_action_retry.py
Routing/retries/fallback share budget accounting ChatModelActionRoutingTest, test_model_routing.py
Invalid SOFT output fails before fallback events test_soft_fallback_tool_calls_fail_before_routing_event
Recovery preserves timing and reconstructs usage ReActLoopBudgetRecoveryTest
Chat memory and subagent budget isolation ChatMemoryIsolationTest, ChatCallTest, ReActAgentSubagentTest
Turn, time, and token limits in SOFT and HARD modes ReActLoopBudgetE2ETest and react_loop_budget_test.py exercise the public APIs in Java and Python Flink jobs.
Cross-language serialization and execution ReActLoopBudgetCrossLanguageTest verifies budget JSON round-trips and budget enforcement across the Java/Python bridge.
Cross-language recovery after a job restart ReActLoopBudgetCrossLanguageTest verifies that restarted jobs reuse persisted model results and retain the original budget start time.

API

Adds Java/Python ReActLoopBudget, budget configuration through ChatRequestEvent, ReActAgent, and Python ctx.chat, plus react-loop.budget.* job-level defaults. Java ctx.chat accepts the budget through its request event.

Existing constructors remain available. Existing callers remain unlimited unless budget defaults are configured. Agent YAML gains no new budget field.

Documentation

  • doc-needed
  • doc-not-needed
  • doc-included

Was this patch authored or co-authored using generative AI tooling?

  • Yes
  • No

Generated-by: Codex (GPT-6)

@github-actions github-actions Bot added doc-included Your PR already contains the necessary documentation updates. fixVersion/1.0.0 The feature or bug should be implemented/fixed in the 1.0.0 version. priority/major Default priority of the PR or issue. labels Nov 17, 2026
@eemario
eemario force-pushed the codex/chat-loop-budget branch from 7a61956 to a6a2b55 Compare November 17, 2026 02:36
@github-actions github-actions Bot added doc-included Your PR already contains the necessary documentation updates. and removed doc-included Your PR already contains the necessary documentation updates. labels Nov 17, 2026
@eemario
eemario force-pushed the codex/chat-loop-budget branch from a6a2b55 to 378a90a Compare November 17, 2026 03:17
@github-actions github-actions Bot added doc-included Your PR already contains the necessary documentation updates. and removed doc-included Your PR already contains the necessary documentation updates. labels Nov 17, 2026
@eemario
eemario marked this pull request as ready for review November 17, 2026 05:50
@eemario
eemario force-pushed the codex/chat-loop-budget branch 4 times, most recently from 53e7ac3 to 1242bf0 Compare November 19, 2026 08:32
@github-actions github-actions Bot added doc-included Your PR already contains the necessary documentation updates. and removed doc-included Your PR already contains the necessary documentation updates. labels Nov 20, 2026

@wenjin272 wenjin272 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @eemario for implementing per-chat budgets and covering both Java and Python, including recovery scenarios. I've left 11 inline suggestions focused on API reuse, simpler configuration and finalization logic, and E2E coverage.

Two additional API cleanups could be handled in a separate follow-up hotfix PR:

These two cleanups can stay outside the scope of this budget PR.

ShortTermMemoryTtlVisibility.class,
ShortTermMemoryTtlVisibility.NEVER_RETURN_EXPIRED);

public static final ConfigOption<Integer> LOOP_MAX_TURNS =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we move the budget options out of AgentExecutionOptions into a dedicated ReActLoopBudgetOptions class? Python could define the corresponding class in the existing module without introducing a separate file.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2. Budget options now live in ReActLoopBudgetOptions; the Python class stays in the existing core_options module.

}

/** Applies the setup prompt and calls the model without tools or tool-only parameters. */
public ChatResult chatWithoutTools(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we reuse the existing chat API with explicit tools instead of adding chatWithoutTools? The caller could first call prepareRequestMessages, then invoke chat with an empty tool list. Please apply the same approach in Python.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2. Java and Python now prepare the messages and reuse chat with an explicit empty tool list. Removed chatWithoutTools and retained the plain-chat parameter behavior; bridge and tool-parameter tests cover both paths.

}

@JsonValue
public Map<String, Object> toMap() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use Jackson and Pydantic's built-in serialization instead of maintaining manual map conversions? In Java, we could annotate the existing constructor and properties and register JavaTimeModule for Duration. In Python, we could use the native timedelta field handling. This would remove the custom millisecond conversion while retaining business validation in the constructor and validators. Please verify Java/Python round-tripping.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2. Java uses Jackson annotations and JavaTimeModule, and Python uses Pydantic fields. A small duration serializer keeps ISO durations in days/seconds because Java Duration does not accept Pydantic's year representation. Cross-language round-trip tests cover long durations too.

}

/** Builder for an immutable request-scoped budget. */
public static final class Builder {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we move Builder to the end of ReActLoopBudget, keeping the main class implementation together?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2; Builder is now at the end of ReActLoopBudget.

private static final Logger LOG = LoggerFactory.getLogger(ReActLoopBudgetUtils.class);
static final String LOOP_BUDGET_CONTEXT = "_LOOP_BUDGET_CONTEXT";

static void initialize(RunnerContext ctx, ChatRequestEvent event) throws Exception {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we simplify initialize by separating budget resolution from start-time initialization and reducing nested branches? Could we also avoid redundant existence checks before reads and extract the repeated state keys into constants? In Java, please use BudgetMode.SOFT.name() instead of the literal "SOFT". Please apply the relevant simplifications in Python as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2. Separated budget resolution and time initialization, removed redundant checks, extracted state-key constants, and used BudgetMode.SOFT.name(). Applied the corresponding Python cleanup.

false);
}

static ChatAttemptResult chatWithRetries(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we keep a single chatWithRetries method with the finalTurn parameter and update existing callers to pass false, rather than retaining an overload that only supplies the default?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the budget-specific forwarding overload in 60b8af2. After rebasing, retained the two upstream overloads introduced for deferOutputSchema; only the full overload takes finalTurn. The existing convenience overload supplies false for both flags.

chatModel.chat(messages, promptArgs, Map.of()), null);
ChatResult response =
closing
? chatModel.chatWithoutTools(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we unify SOFT budget finalization and native structured-output conversion through a shared finalizeResponse() helper accepting prepared messages and an optional schema, with tools disabled?

SOFT finalization could pass the conversation history plus the closing instruction and apply the native schema directly, avoiding a second conversion call. Normal completion could retain the existing answer-conversion message.

Could we also rename the invoker's closing parameter to finalTurn and let the shared helper append :final for both paths, removing BUDGET_FINALIZATION_SUFFIX? Please align Java/Python and update the recovery tests accordingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2. Both paths share finalization with prepared messages, optional native schema, and no tools. Soft finalization avoids a separate conversion call. Renamed the invocation flag to finalTurn and unified the durable suffix as :final, with Java/Python and recovery tests updated.

RunnerContext ctx,
@Nullable String reason)
throws Exception {
boolean closing = reason != null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we rename closing in ChatModelAction to budgetExhausted to reflect why finalization is triggered, while keeping finalTurn in ChatModelInvoker to describe the invocation behavior?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 60b8af2: the action uses budgetExhausted, while the invoker uses finalTurn.

return;
}
confData.put(option.getKey(), value);
confData.put(option.getKey(), value instanceof Enum<?> ? ((Enum<?>) value).name() : value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you clarify why this enum-to-string conversion is needed? get() already handles enum values, and Jackson serializes them as strings when passing the plan to Python. If this only supports JSON round-tripping, could we omit it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed; the conversion was redundant and has been removed in 60b8af2. Existing enum handling and Jackson serialization cover this path.

import static org.assertj.core.api.Assertions.assertThatThrownBy;

/** Runs real Python actions/resources through Pemja and the checkpointable operator. */
@EnabledForJreRange(min = JRE.JAVA_21)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add job-level E2E tests for Java-only, Python-only, and cross-language scenarios, using deterministic mock chat models to verify SOFT/HARD budget behavior through the public APIs, rather than relying solely on the operator test harness?

Also, why does the entire test class require Java 21+, given that both chat and tool async execution are disabled?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added mock-model job-level coverage for Java, Python, and cross-language SOFT/HARD turn, token, and time budgets in 60b8af2. Removed the cross-language test class's Java 21 restriction and verified it on Java 17 and 21.

@eemario
eemario force-pushed the codex/chat-loop-budget branch from 1242bf0 to 7ab851f Compare November 23, 2026 09:15

@pltbkd pltbkd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this together and for covering both Java and Python, including recovery scenarios. Overall LGTM. In addition to Wenjin’s feedback, I have three small inline suggestions for your consideration.

static void initialize(RunnerContext ctx, ChatRequestEvent event) throws Exception {
if (getBudgetState(ctx.getSensoryMemory(), event.getId()) != null) return;
ReActLoopBudget limits = event.getBudget();
if (limits == null && ctx.getConfig() != null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we validate the job-level budget defaults at job submission? The existing validation runs when a chat first uses those defaults. Moving it to the shared submission path would surface configuration errors before the job starts processing requests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 813f5ff. The shared CompileUtils submission path now validates job-level budget defaults before creating the operator. Tests cover valid and invalid configurations through both Java plans and Python plan JSON.

this(descriptor, prompt, outputSchema, skills, null);
}

public ReActAgent(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we introduce a ReActAgent builder and expose the budget option there? The growing set of constructor overloads makes the API easy to misuse, especially when callers pass null for optional arguments. For example, the documented call is ambiguous because the fourth argument matches both List<String> and Skills. Named builder methods would make those choices explicit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 813f5ff. Added ReActAgent.builder(), moved budget construction behind private constructors, and updated the documented example. Existing public constructors remain unchanged; tests cover optional arguments and skill configuration.

private static void processChatRequest(ChatRequestEvent event, RunnerContext ctx)
throws Exception {
ReActLoopBudgetUtils.initialize(ctx, event);
String reason = ReActLoopBudgetUtils.tryStartTurn(ctx.getSensoryMemory(), event.getId());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit — Both the sync and async model calls can replay a persisted result. If recovery happens after the deadline, the wall-clock admission check can take the timeout branch before replay reaches that result. Could we use durableExecute to record the admission, for example by recording the timestamp, when a time budget is configured? The same turn would replay the recorded admission, and each new turn would still check the current time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 813f5ff for Java and Python. Time-budget admission now records a durable timestamp, so recovery replays the same turn's admission and a new turn checks a fresh time. Added controlled-clock recovery tests, including real Java continuation-based async execution on JDK 21.

@eemario
eemario force-pushed the codex/chat-loop-budget branch from 813f5ff to 4f3868e Compare November 24, 2026 07:23
@wenjin272

Copy link
Copy Markdown
Contributor

Thanks for adding the job-level E2E coverage. Could we further simplify the tests in these areas?

  • Remove the cross-language operator-harness tests from the E2E module and cover recovery through actual Flink job failure/restart tests. Keep operator-harness tests in runtime, without requiring the real Python bridge.
  • Remove or rewrite test_recovered_budget_branch_uses_distinct_durable_identity: it changes budget state between two independent contexts rather than replaying a journal, and its branch-switching premise no longer matches durable admission.
  • Consolidate the overlapping budget-state update tests in Java/Python, retaining the assertions for correct deductions, zero clamping, snapshot preservation, and request isolation.
  • Use native_conversion in test_final_turn_tool_calls_fail_without_another_conversion; the mock currently always returns True, so both parameterized cases exercise the same path.
  • Replace the full parameter matrix in test_first_action_restores_durable_start_time with explicit scenarios covering distinct recovery behavior, while retaining coverage of persistence boundaries, sync/async execution, and SOFT/HARD timeout handling.

@wenjin272 wenjin272 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the test cleanup suggestions. I have five follow-up comments, including a routing context-truncation regression introduced by the new cross-language message preparation.

promptArgs == null ? Map.of() : promptArgs)));
List<ChatMessage> result = new ArrayList<>();
for (Object message : (List<?>) prepared) {
result.add(adapter.fromPythonChatMessage(message));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PythonChatModelSetup.prepareRequestMessages() reconstructs messages when converting them back from Python, so unchanged conversation messages become new Java objects. Since pinnedRenderedIndices identifies generated prompts by object identity, it incorrectly pins the entire conversation, preventing max_context_chars from trimming history.

Could we instead apply the limit to the original conversation before calling prepareRequestMessages, retaining system messages and the latest message, then add the prompt/skills messages? This would remove the identity-based inference while preserving the List<ChatMessage> return type. Please update the documentation and tests to clarify that added prompt/skills messages are outside the budget and the final context may exceed the limit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b0300c8. Both routing strategies now trim the original conversation before adding prompt and skill messages. Updated the docs and added a regression test with copied messages.

return callConnection(messages, tools, modelParams, outputSchema, tools.isEmpty());
}

private ChatResult callConnection(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we simplify both Java and Python to strip tool-only parameters whenever the effective tool list is empty? Java could retain the original delegation to the explicit-tools chat method and remove callConnection, while Python could remove disable_tools and check the resolved tool list directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b0300c8. Java and Python now strip tool-only parameters whenever the resolved tool list is empty. Added coverage for plain chat in both languages.

Object budget = attributes.get("budget");
if (budget instanceof Map) {
attributes.put("budget", MAPPER.convertValue(budget, ReActLoopBudget.class));
} else if (budget != null && !(budget instanceof ReActLoopBudget)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we remove this else if check and keep only the map-to-budget conversion? The normal construction and serialization paths already produce a ReActLoopBudget or a map, so a dedicated check for manually supplied invalid types seems unnecessary here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b0300c8. Removed the type check and kept the map-to-budget conversion. The restoration tests still cover invalid budget fields.

private Map<String, Object> deserializeJavaConfig(JsonNode node) throws Exception {

ObjectMapper mapper = new ObjectMapper();
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we centralize the JavaTimeModule registration in a shared mapper factory and cache the resulting mapper in a private static final field at each call site? This would avoid repeated setup and allocation while allowing each component to retain its own serializers and mixins, without sharing a mutable global mapper.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b0300c8. Centralized JavaTimeModule registration in JacksonMapperFactory. Each component caches its own mapper and retains its serializers and mixins.

"true,HARD,token", "true,SOFT,token", "false,HARD,token", "false,SOFT,token",
"true,HARD,time", "true,SOFT,time", "false,HARD,time", "false,SOFT,time"
})
void budgetsRunThroughPublicApiInFlinkJob(boolean javaModel, String mode, String limit)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also add a Java-only budget E2E test to the integration module, similar to the Python-only test? The Java-only cases currently live in the cross-language module, whose CI matrix differs from the Java integration matrix. This would verify budget behavior across the supported Flink/JDK combinations.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b0300c8. Moved the six Java-only budget cases into the integration module. All six passed locally on each of the five Flink/JDK matrix combinations.

@wenjin272 wenjin272 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two small, non-blocking nits.

public final class JacksonMapperFactory {
private JacksonMapperFactory() {}

public static JsonMapper.Builder builderWithJavaTime() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Could we rename this to builder() and document JavaTimeModule as part of the default configuration? This also keeps the name appropriate if we add other common modules later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed the method to builder() and documented JavaTimeModule as part of its default configuration in 088b891.

|---------|-------------|
| `Strategies.llm(judgeModel, promptTemplate)` | Supply the judge's system instructions. Include `{candidates}` to insert one `- name: description` line per candidate, and instruct the judge to return the verdict format above. |
| `withMaxContextChars(int)` | Limit conversation text, including tool calls and results. System messages, rendered prompt messages, and the newest message are always kept; older messages are included newest-first as space allows. Media stays with its message and does not count toward the character limit. Required messages can exceed the limit. |
| `withMaxContextChars(int)` | Limit conversation text, including tool calls and results. System messages and the newest message are always kept. Older messages are included newest-first as space allows. The anchor model’s bound prompt and skill-discovery messages are added after this limit is applied. Media stays with its message and does not count toward the character limit. Required messages can exceed the limit. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Could we shorten this description to the limit’s scope and key exceptions, and move the detailed truncation behavior to the text below the table?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shortened the table entry and moved the detailed truncation rules below the table in 088b891.

@eemario

eemario commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Hi @xintongsong , this PR adds configurable limits on turns, elapsed time, and token usage for each chat loop. If you have a chance, could you take a look as well? Thanks!

eemario and others added 6 commits November 25, 2026 16:15
Add Java and Python turn, elapsed-time and token budgets with job-level defaults and per-request overrides. Admit each turn before routing, account for routing and model usage, and allow a tool-free closing turn in soft mode or a failed response in hard mode.

Persist loop start times for unfinished-action recovery and keep subagent budgets independent. Include unit and runtime recovery tests, cross-language support, and configuration and usage documentation.

Validation after rebasing onto main: 416 Java tests passed (1 skipped), 468 Python tests passed; Spotless, Ruff, Hugo and diff checks passed. Tests cover routed fallback/retries sharing a turn and token budget, admission before routing, and chat memory isolation during checkpoint recovery. After aligning Python soft-finalization validation before fallback events, all 296 Python action tests and Ruff checks passed.

Additional validation: 14 budget-specific cross-language and Python checkpoint recovery cases passed; the cross-language selection passed 28 tests (2 Ollama-dependent tests skipped). Python targeted regression tests passed 150 cases, and DashScope unit tests passed 25 cases after configuring the test context with real defaults.

Latest validation: Python plan and configuration loader tests passed (708 passed, 1 skipped); Java configuration tests passed (20). Ruff, Spotless and diff checks passed. TokenMetricsE2ETest passed locally with Java 21 / Flink 2.3.

Cleanup validation: 634 Python plan tests passed (1 skipped), 139 Java retry/routing tests passed, and all 14 budget cross-language/recovery tests passed after rebuilding Java/Python artifacts. Ruff, Spotless and diff checks passed.

Generated-by: Codex (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: GPT-6
AI-Contributed/Feature: 6/6
AI-Contributed/UT: 10/10
Separate budget options, reuse explicit-tool chat calls and unify finalization.
Use Jackson/Pydantic budget serialization with cross-language duration support.
Simplify budget state handling and add public-API job-level E2E coverage.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: gpt-6
AI-Contributed/Feature: 52/52
AI-Contributed/UT: 0/0
Validate job-level defaults at submission, expose ReActAgent budgets through a
builder, and persist per-turn time admission in Java and Python. Cover sync and
real async recovery, routing, and the public builder and configuration paths.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: gpt-6
AI-Contributed/Feature: 141/141
AI-Contributed/UT: 392/392
Pass an Event serializer to the updated runner context constructors.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: gpt-6
AI-Contributed/Feature: 0/0
AI-Contributed/UT: 24/24
Replace the cross-language harness with job restart coverage. Consolidate budget state tests and verify replay identities, finalization arguments, and time admission.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6.2 Astra)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: gpt-6.2-astra
AI-Contributed/Feature: 7/7
AI-Contributed/UT: 472/472
Trim history before preparing routing prompts and align tool-free calls
across Java and Python. Centralize Java time mapper setup, simplify budget
restoration, and exercise Java budgets in the integration matrix.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: GPT-6
AI-Contributed/Feature: 345/345
AI-Contributed/UT: 535/535
eemario and others added 2 commits November 25, 2026 16:15
Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: GPT-6
AI-Contributed/Feature: 42/42
AI-Contributed/UT: 12/12
…lures

Wait until the durable result has been persisted before simulating a crash
so the async recovery test exercises result replay.

Generated-by: Codex CLI 0.171.0-alpha.13 (GPT-6)
Co-Authored-By: Codex <noreply@openai.com>
AI-Model: GPT-6
AI-Contributed/Feature: 0/0
AI-Contributed/UT: 14/14
@eemario
eemario force-pushed the codex/chat-loop-budget branch from 088b891 to 86cc6aa Compare November 25, 2026 08:19

@wenjin272 wenjin272 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing all the feedback. No further comments from my side. LGTM.

@github-actions github-actions Bot added doc-included Your PR already contains the necessary documentation updates. and removed doc-included Your PR already contains the necessary documentation updates. labels Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc-included Your PR already contains the necessary documentation updates. fixVersion/1.0.0 The feature or bug should be implemented/fixed in the 1.0.0 version. priority/major Default priority of the PR or issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants