Repository navigation
Conversation
7a61956 to
a6a2b55
Compare
a6a2b55 to
378a90a
Compare
53e7ac3 to
1242bf0
Compare
wenjin272
left a comment
There was a problem hiding this comment.
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:
- Remove the single-argument
BaseChatModelSetup.chat(List<ChatMessage> messages)overload, which currently only has test callers. - Remove the public static
ChatModelAction.chat(UUID, String, ...)wrapper, which also currently only has test callers, and exercise the production event entry point in those tests instead.
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 = |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
Could we move Builder to the end of ReActLoopBudget, keeping the main class implementation together?
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Could we rename closing in ChatModelAction to budgetExhausted to reflect why finalization is triggered, while keeping finalTurn in ChatModelInvoker to describe the invocation behavior?
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
1242bf0 to
7ab851f
Compare
pltbkd
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
813f5ff to
4f3868e
Compare
|
Thanks for adding the job-level E2E coverage. Could we further simplify the tests in these areas?
|
wenjin272
left a comment
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Two small, non-blocking nits.
| public final class JacksonMapperFactory { | ||
| private JacksonMapperFactory() {} | ||
|
|
||
| public static JsonMapper.Builder builderWithJavaTime() { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. | |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Shortened the table entry and moved the detailed truncation rules below the table in 088b891.
|
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! |
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
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
088b891 to
86cc6aa
Compare
wenjin272
left a comment
There was a problem hiding this comment.
Thanks for addressing all the feedback. No further comments from my side. LGTM.
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
ChatResponseEventwithout starting another turnBehavioral contracts
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
ReActLoopBudgetTest,test_react_loop_budget.pyChatModelActionRetryTest,test_chat_model_action_retry.pyChatModelActionRoutingTest,test_model_routing.pytest_soft_fallback_tool_calls_fail_before_routing_eventReActLoopBudgetRecoveryTestChatMemoryIsolationTest,ChatCallTest,ReActAgentSubagentTestReActLoopBudgetE2ETestandreact_loop_budget_test.pyexercise the public APIs in Java and Python Flink jobs.ReActLoopBudgetCrossLanguageTestverifies budget JSON round-trips and budget enforcement across the Java/Python bridge.ReActLoopBudgetCrossLanguageTestverifies that restarted jobs reuse persisted model results and retain the original budget start time.API
Adds Java/Python
ReActLoopBudget, budget configuration throughChatRequestEvent,ReActAgent, and Pythonctx.chat, plusreact-loop.budget.*job-level defaults. Javactx.chataccepts 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-neededdoc-not-neededdoc-includedWas this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)