diff --git a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java index dc669a9c29..03c8352b0b 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -99,6 +99,7 @@ import io.agentscope.core.message.ToolErrorKind; import io.agentscope.core.message.ToolErrorMetadata; import io.agentscope.core.message.ToolResultBlock; +import io.agentscope.core.message.ToolResultMessage; import io.agentscope.core.message.ToolResultState; import io.agentscope.core.message.ToolUseBlock; import io.agentscope.core.message.UserMessage; @@ -2723,6 +2724,34 @@ private Mono doCallInner(List msgs) { msgs = List.of(); } + if (state.getReturnDirectTurn() != null) { + boolean resume = state.getReturnDirectTurn().equals(rc.getTurnId()); + state.setReturnDirectTurn(null); + if (resume) { + var messages = state.contextMutable(); + var calls = MessageUtils.extractRecentToolCalls(messages, getName()); + var results = new java.util.HashMap(); + while (!messages.isEmpty() + && messages.get(messages.size() - 1) + instanceof ToolResultMessage message) { + for (var result : message.getContentBlocks(ToolResultBlock.class)) + results.put(result.getId(), result); + messages.remove(messages.size() - 1); + } + var pairs = + calls.stream() + .map(call -> Map.entry(call, results.get(call.getId()))) + .toList(); + for (var pair : pairs) + messages.add( + buildReturnDirectPlaceholderMsg( + pair.getKey(), + pair.getValue() + .withState(pair.getValue().completedState()))); + return Mono.just(finalizeReturnDirect(pairs, state.getReplyId())); + } + } + Set pendingIds = MessageUtils.pendingToolUseIds(state.contextMutable()); // No pending tools -> normal processing @@ -3276,7 +3305,7 @@ private List> pairProvidedToolResults( * Build placeholder-shaped copies of the caller-supplied messages for a returnDirect * short-circuit: every {@link ToolResultBlock}'s output is replaced with the * returnDirect placeholder sentence (id/name preserved, state normalized via {@link - * #determineToolResultState(ToolResultBlock)} like the in-framework path) while + * ToolResultBlock#completedState()} like the in-framework path) while * non-tool-result content passes through unchanged. New {@link Msg}s are built — the * caller's objects are never mutated — keeping the context invariant {@code [tool_use, * tool_result(placeholder), assistant(full result)]}. @@ -3298,7 +3327,7 @@ private ContentBlock placeholderToolResultContent(ContentBlock block) { return block; } return placeholderResultBlock( - result.getId(), result.getName(), determineToolResultState(result)); + result.getId(), result.getName(), result.completedState()); } /** @@ -3609,7 +3638,9 @@ private Mono reasoningApplied(int iteration, Msg answer) { InvocationRecorder recorder = InvocationRecorder.from(rc); if (recorder == null) return Mono.empty(); boolean deferred = recorder.pendingModelCallId() != null; - recorder.reasoningCompleted(iteration, answer); + // Only a host that implements model recovery can consume this continuation. + recorder.reasoningCompleted( + iteration, rc.get(ModelInvocation.class) == null ? null : answer); return deferred ? recorder.checkpoint(state, "model_result_applied") : Mono.empty(); } @@ -3924,8 +3955,7 @@ private List serverToolResultEvents(ToolResultBlock result, String r } events.add( - new ToolResultEndEvent( - replyId, toolId, toolName, determineToolResultState(result)) + new ToolResultEndEvent(replyId, toolId, toolName, result.completedState()) .withMetadata(eventMetadata)); return events; @@ -4918,7 +4948,7 @@ public void onResult(ToolUseBlock call, ToolResultBlock result) { replyId, call.getId(), call.getName(), - determineToolResultState(result)) + result.completedState()) .withMetadata(metadata)); } @@ -4928,25 +4958,6 @@ private ToolResultBlock resolvedResult(ToolUseBlock call) { } } - private ToolResultState determineToolResultState(ToolResultBlock result) { - if (result.isSuspended()) { - return ToolResultState.SUSPENDED; - } - if (result.getState() != null && result.getState() != ToolResultState.RUNNING) { - return result.getState(); - } - if (result.getOutput() != null - && result.getOutput().stream() - .anyMatch( - b -> - b instanceof TextBlock tb - && tb.getText() != null - && tb.getText().startsWith("[ERROR]"))) { - return ToolResultState.ERROR; - } - return ToolResultState.SUCCESS; - } - /** * Build a message containing suspended tool calls for user execution. * @@ -5222,7 +5233,7 @@ private Mono applyToolResult( // adding to contextMutable(), so that history queries via // agent.getAgentState(ctx).contextMutable() reflect the correct // final state instead of always showing RUNNING. - ToolResultState finalState = determineToolResultState(result); + ToolResultState finalState = result.completedState(); ToolResultBlock updatedResult = result.withState(finalState); Msg toolMsg = @@ -5287,7 +5298,7 @@ private boolean isReturnDirectToolCall(Map.Entry if (tool == null || !tool.isReturnDirect()) { return false; } - return determineToolResultState(entry.getValue()) == ToolResultState.SUCCESS; + return entry.getValue().completedState() == ToolResultState.SUCCESS; } /** Builds the placeholder tool_result, replacing only the output while keeping id/name/state. */ diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/InvocationRecorder.java b/agentscope-core/src/main/java/io/agentscope/core/journal/InvocationRecorder.java index b8df948937..51e6aa5288 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/InvocationRecorder.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/InvocationRecorder.java @@ -172,7 +172,12 @@ public InvocationRecorder( executionPosition = initial.executionPosition(); previousPosition = executionPosition; } - if (previousState != null) previousMessages = messageJson(initial.restore()); + if (previousState != null) { + var restored = initial.restore(); + previousMessages = messageJson(restored); + if (log.recoveryPosition() > 0) + restored.getContext().forEach(message -> recordedMessages.add(message.getId())); + } } catch (RuntimeException e) { log.release(writer); throw e; @@ -908,7 +913,7 @@ public synchronized void reasoningCompleted(int iteration) { /** Preserve a terminal model answer until this Run finishes. */ public synchronized void reasoningCompleted(int iteration, Msg answer) { executionPosition = new AgentExecutionPosition(Math.addExact(iteration, 1), iteration); - if (pendingModelCallId != null && answer != null) modelAnswerId = answer.getId(); + if (answer != null) modelAnswerId = answer.getId(); pendingModelCallId = null; } diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/JournalProjection.java b/agentscope-core/src/main/java/io/agentscope/core/journal/JournalProjection.java index be3c92f2ce..9b4894b7af 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/JournalProjection.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/JournalProjection.java @@ -126,16 +126,25 @@ public static JournalProjection read(ThreadJournal log, Consumer o for (var result : message.getContentBlocks(ToolResultBlock.class)) existing.add(result.getId()); var pending = MessageUtils.pendingToolUseIds(restored.getContext()); + boolean recoveredActionResult = false; for (var entry : results.entrySet()) if (pending.contains(entry.getKey()) && !existing.contains(entry.getKey()) - && !entry.getValue().isSuspended()) + && !entry.getValue().isSuspended()) { restored.contextMutable() .add( ToolResultMessage.builder() .id("recovered_" + entry.getKey()) .result(entry.getValue()) .build()); + recoveredActionResult = true; + } + // Completed actions may be durable before the closing assistant reply. + if (recoveredActionResult + && checkpoint != null + && checkpoint.turnId() != null + && ThreadRecovery.returnsDirectly(log, cursor, checkpoint.turnId(), restored)) + restored.setReturnDirectTurn(checkpoint.turnId()); for (var report : verifications) restored.getTasksContext() .recordVerification( diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/ModelInvocation.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ModelInvocation.java index 75c628d91b..5e7e472895 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/ModelInvocation.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/ModelInvocation.java @@ -39,6 +39,11 @@ default boolean beginFallback(String purpose, Throwable cause) { return true; } + /** Transport options for a recorded dispatch. The journal retains its original input. */ + default GenerateOptions providerOptions(String callId, GenerateOptions options) { + return options; + } + /** Prepared input and stable identity for this model invocation. */ record Call(String callId, String purpose, ModelCallInput input) {} diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/RecordedModels.java b/agentscope-core/src/main/java/io/agentscope/core/journal/RecordedModels.java index 29d6d767ba..9168d16eb1 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/RecordedModels.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/RecordedModels.java @@ -136,7 +136,16 @@ private Flux invoke( "Cannot call the model while waiting for " + pending)); admission = before(callId); - responses = Flux.defer(() -> delegate.stream(messages, tools, options)); + responses = + Flux.defer( + () -> + delegate.stream( + messages, + tools, + host == null + ? options + : host.providerOptions( + callId, options))); } var last = new AtomicReference(); var usage = new AtomicReference(); diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java index fee35b5e83..c3ab097237 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java @@ -18,11 +18,16 @@ import io.agentscope.core.message.MsgRole; import io.agentscope.core.message.ToolResultBlock; import io.agentscope.core.message.ToolResultMessage; +import io.agentscope.core.message.ToolResultState; +import io.agentscope.core.message.ToolUseBlock; +import io.agentscope.core.state.AgentState; import io.agentscope.core.util.JsonUtils; import java.time.Duration; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Objects; import java.util.UUID; /** Explicit operator reconciliation, never automatic re-execution of an uncertain side effect. */ @@ -31,12 +36,27 @@ private ThreadRecovery() {} public static void reconcile( ThreadJournal log, Map outcomes, String reason) { + reconcile(log, outcomes, reason, false); + } + + /** Persist one independently verified outcome while other dispatches may still need evidence. */ + public static void reconcileOne(ThreadJournal log, ToolResultBlock outcome, String reason) { + reconcile(log, Map.of(outcome.getId(), outcome), reason, true); + } + + private static void reconcile( + ThreadJournal log, + Map outcomes, + String reason, + boolean partial) { if (reason == null || reason.isBlank()) throw new IllegalArgumentException("A reconciliation reason is required"); var writer = log.acquire(UUID.randomUUID().toString(), Duration.ofMinutes(2)); try { var projection = JournalProjection.read(log); - if (!projection.uncertainToolCalls().equals(outcomes.keySet())) + boolean complete = projection.uncertainToolCalls().equals(outcomes.keySet()); + if (!complete + && !(partial && projection.uncertainToolCalls().containsAll(outcomes.keySet()))) throw new IllegalArgumentException("Supply exactly the unresolved tool outcomes"); var state = projection.restore(); if (state == null) throw new JournalException("No recoverable state baseline"); @@ -65,6 +85,12 @@ public static void reconcile( else context.set(i, message.withContent(retained)); } context.addAll(verifiedMessages); + if (complete + && !outcomes.isEmpty() + && returnsDirectly( + log, projection.asOfSeq(), projection.positionTurnId(), state)) { + state.setReturnDirectTurn(projection.positionTurnId()); + } long seq = projection.asOfSeq(); String run = projection.positionRunId(); String turn = projection.positionTurnId(); @@ -102,7 +128,9 @@ public static void reconcile( "outcomes", outcomes, "interruptedRuns", - projection.activeRuns()))); + complete + ? projection.activeRuns() + : java.util.List.of()))); var checkpointData = new LinkedHashMap(); checkpointData.put("stateJson", state.toJson()); checkpointData.put("projectorVersion", 1); @@ -126,4 +154,32 @@ public static void reconcile( log.release(writer); } } + + static boolean returnsDirectly( + ThreadJournal log, long asOfSeq, String turnId, AgentState state) { + var messages = state.contextMutable(); + int index = messages.size() - 1; + var successful = new HashSet(); + while (index >= 0 && messages.get(index) instanceof ToolResultMessage message) { + for (var result : message.getContentBlocks(ToolResultBlock.class)) { + if (result.completedState() != ToolResultState.SUCCESS) return false; + successful.add(result.getId()); + } + index--; + } + if (index < 0) return false; + var calls = messages.get(index).getContentBlocks(ToolUseBlock.class); + if (calls.isEmpty() || calls.size() != successful.size()) return false; + var direct = new HashSet(); + for (var event : log.scanMetadata(log.recoveryPosition(), asOfSeq)) { + if ("tool/dispatch".equals(event.type()) && Objects.equals(turnId, event.turnId())) { + String id = (String) event.data().get("toolCallId"); + if (Boolean.TRUE.equals(event.data().get("returnDirect"))) direct.add(id); + else direct.remove(id); + } + } + return calls.stream() + .allMatch( + call -> successful.contains(call.getId()) && direct.contains(call.getId())); + } } diff --git a/agentscope-core/src/main/java/io/agentscope/core/message/ToolResultBlock.java b/agentscope-core/src/main/java/io/agentscope/core/message/ToolResultBlock.java index e74b0850cc..c2fcb4f548 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/message/ToolResultBlock.java +++ b/agentscope-core/src/main/java/io/agentscope/core/message/ToolResultBlock.java @@ -195,6 +195,26 @@ public ToolResultState getState() { return state; } + /** Resolve the final state of a returned local tool invocation, including plain text results. */ + public ToolResultState completedState() { + if (isSuspended()) { + return ToolResultState.SUSPENDED; + } + if (getState() != null && getState() != ToolResultState.RUNNING) { + return getState(); + } + if (getOutput() != null + && getOutput().stream() + .anyMatch( + b -> + b instanceof TextBlock tb + && tb.getText() != null + && tb.getText().startsWith("[ERROR]"))) { + return ToolResultState.ERROR; + } + return ToolResultState.SUCCESS; + } + /** * Returns a copy of this block with the given state. * diff --git a/agentscope-core/src/main/java/io/agentscope/core/state/AgentState.java b/agentscope-core/src/main/java/io/agentscope/core/state/AgentState.java index 1fb61231b3..eaebe22da5 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/state/AgentState.java +++ b/agentscope-core/src/main/java/io/agentscope/core/state/AgentState.java @@ -63,6 +63,19 @@ public final class AgentState implements State { private String summary; private final List context; private String replyId; + private String returnDirectTurn; + + @JsonProperty("return_direct_turn") + @com.fasterxml.jackson.annotation.JsonInclude( + com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) + public String getReturnDirectTurn() { + return returnDirectTurn; + } + + public void setReturnDirectTurn(String turnId) { + returnDirectTurn = turnId; + } + private int curIter; private boolean shutdownInterrupted; private PermissionContextState permissionContext; diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java b/agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java index 83ff92b30a..97217d3f51 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java @@ -430,7 +430,12 @@ private Mono executeCore( // Without interceptors, retain the dispatch path with an optional final check. if (interceptors.isEmpty()) { return applyResultErrorMapping( - dispatchRecord(recorder, executionParam, toolCall, mergedInput) + dispatchRecord( + recorder, + executionParam, + toolCall, + mergedInput, + tool.isReturnDirect()) .then(Mono.defer(() -> invokeTool(tool, executionParam))), toolCall, param.isPropagateErrors()); @@ -445,7 +450,12 @@ private Mono executeCore( String agentName = callingAgent != null ? callingAgent.getName() : null; Function> terminal = iv -> - dispatchRecord(recorder, executionParam, toolCall, iv.input()) + dispatchRecord( + recorder, + executionParam, + toolCall, + iv.input(), + tool.isReturnDirect()) .then( Mono.defer( () -> @@ -496,7 +506,8 @@ private static Mono dispatchRecord( InvocationRecorder recorder, ToolCallParam executionParam, ToolUseBlock toolCall, - Map arguments) { + Map arguments, + boolean returnDirect) { if (recorder == null) { return Mono.empty(); } @@ -518,6 +529,8 @@ private static Mono dispatchRecord( recorder.actionId(toolCall.getId()), "name", toolCall.getName(), + "returnDirect", + returnDirect, "arguments", arguments)); }); diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 5dcdb4afd1..497ecaeb1d 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -75,6 +75,9 @@ Durable keeps three kinds of information connected: the Harness's private native state, durable execution facts, and public messages/events. A display snapshot can rebuild a UI; the native checkpoint and execution facts determine how work continues. Applications use the public API without interpreting private checkpoint formats. +The AgentScope adapter advances the native recovery cursor when it commits a +settled Turn, including cancellation and failure settlement. A replacement Brain +loads the last complete state checkpoint and replays the journal entries after it. ### Session, Thread, Turn, and Run @@ -180,6 +183,24 @@ work, restores native state at supported boundaries, and continues the original Turn. Completed results remain available without another Agent invocation. Reading history alone does not start execution. +Register per-tool policies with `AgentScopeAdapter.withNativeToolRecovery(policies, modelCheck)`. +The first native dispatch records the policy and the admitted arguments. A replacement Brain +uses that record even if its configuration changes. Use `NativeToolRecovery.Replay.SAFE` for +reads or operations that tolerate duplicate execution. After a lost result the Brain runs the +same call again. The default, `NEVER`, parks the Turn unless an optional model check can +verify the outcome. Pass `null` to disable that check. + +A `NativeToolRecovery.ModelCheck` gives the model one read-only lookup tool. The application +looks up the original operation in an independent system, validates its identity and arguments, +and returns a terminal tool result and evidence reference. A missing record, inconsistent result +or model-only assertion leaves the Turn waiting. An authorized host submits verified +outcomes through `NativeToolReconciliation.submit(backend, threadKey, turnId)`. +The Turn waits for evidence even after a cancellation request. + +The first scheduled owner persists its recovery policy for consecutive lease +losses. PostgreSQL hosts bound idle transactions by the shortest lease they serve +and respect shorter database limits. + Recovery reuses committed native results and tool outcomes. An interrupted model request whose result was never committed may need another model invocation. Workspace files and remote resources must also remain accessible; a saved checkpoint @@ -214,7 +235,8 @@ with task completion can be rejected because its state precondition no longer ho clients should re-read the Turn. Steer does not interrupt a model mid-token or undo an already dispatched tool. Active cancellation records intent and coordinates outstanding execution; a remote operation is only cancelled when its outcome is -confirmed. +confirmed. Once the backend accepts cancellation, it rejects subsequent invocation +commits except cancellation settlement. Previously committed messages remain in history. Other controls cover context injection, withdrawal of unapplied input, interaction responses, and explicit pause/resume. Pause takes effect at a safe boundary; observe @@ -302,6 +324,17 @@ var host = DurableRuntime.builder() host.start(); ``` +PostgreSQL bounds idle record transactions by the configured lease and any shorter +database timeout. Without a configured bound the store defaults to 30 seconds. +This lets PostgreSQL release record locks after a disconnected host stops sending SQL. + +The AgentScope adapter supplies an `Idempotency-Key` for each model generation. +After a crash with a request in flight, recovery can send a second HTTP request +with the same key. A provider that implements idempotency can return the original +generation. Providers that ignore the key can generate and bill twice. Completed +journaled responses replay locally. Explicit per-request idempotency headers +take precedence. + Initialize the Backend schema during provisioning with `PostgresBackend.initializeSchema(dataSource)`, add the PostgreSQL driver, and point the hosts at the same database. Each host needs matching definition/state versions @@ -422,6 +455,41 @@ and runs with host permissions, not production isolation. Real queued runs also RocketMQ 5, topics/groups and authorization. `--compile-only` checks packaging, not broker or end-to-end delivery; see each scenario README for infrastructure and configuration. +## Docker recovery regressions + +Run the Docker fault regression from the repository root with Docker, Python 3, Maven and a JDK on PATH: + +```sh +python3 agentscope-durable/scripts/docker-regression/run.py +``` + +The runner builds the current checkout and starts PostgreSQL, RocketMQ, independent Brain and +Hands JVMs, and a counting model endpoint on isolated Docker networks. It disconnects receivers +from the broker before ACK while retaining database and model connectivity. Separate scenarios kill +the model requester and checkpoint writer. The tool recovery cases query a committed effect or reconcile an opaque effect against external evidence. The checks compare broker message IDs, provider executions, committed effects, +terminal events and committed answers. The runner removes its containers, +volumes and network on exit. The default image is `apache/rocketmq:5.5.0`. Set +`ROCKETMQ_IMAGE` to use another LiteTopic-compatible RocketMQ image (5.5.0 or later) +with `mqbroker`, `mqproxy` and `mqadmin`. The runner starts the proxy in cluster mode +to support LiteTopic delivery. + +The paired-consumer comparison starts separate NameServer, Broker, Proxy and consumer JVMs, +runs eight queues with the same consumer group, and verifies each Broker direct-memory limit +from the running JVM before delivery. +The normal fault suite sets the Broker JVM direct-memory limit to 1 GiB and checks the POP log +for Netty allocation failures. In the two-Hands PostgreSQL fixture on RocketMQ 5.5.1, a +128 MiB Broker direct-memory limit caused POP allocations to fail. The Proxy then +timed out waiting for the Broker, and the clients reported receive deadlines. A Proxy pause +can also produce this client error. Use the Broker POP log and Proxy response together to +identify which path occurred. + +The comparison checks ordinary delivery, repeated receive deadlines during a Proxy pause, and redelivery +to the surviving consumer after killing its peer before ACK. + +```sh +python3 agentscope-durable/scripts/docker-regression/compare_consumers.py +``` + ## Build and check Java 17+ and Maven are required; isolated dependency checking also needs Python 3. diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeAdapter.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeAdapter.java index 94b1c76fba..a19c19ddd7 100644 --- a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeAdapter.java +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeAdapter.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.databind.JsonNode; import io.agentscope.core.ReActAgent; +import io.agentscope.core.agent.Agent; import io.agentscope.core.agent.AgentExecutionHost; import io.agentscope.core.agent.RunOutcome; import io.agentscope.core.agent.RuntimeContext; @@ -94,12 +95,31 @@ private record InvocationBinding(Binding binding, ThreadJournalStore journalStor private interface NativeAgent extends AutoCloseable { ThreadJournal log(RuntimeContext context); + ToolResultBlock replay(ToolUseBlock call, RuntimeContext context); + Flux stream(List input, RuntimeContext context); @Override void close(); } + private static ToolResultBlock replayNative( + Toolkit toolkit, Agent agent, ToolUseBlock call, RuntimeContext context) { + if (toolkit.getTool(call.getName()) == null || toolkit.isExternalTool(call.getName())) { + return null; + } + return toolkit.callTool( + ToolCallParam.builder() + .toolUseBlock(call) + .input(call.getInput()) + .agent(agent) + .runtimeContext(context) + .propagateErrors(true) + .build()) + .map(result -> result.withState(result.completedState())) + .block(); + } + /** Visibility of middleware-produced thinking previews and completed public messages. */ public record ThinkingPolicy(boolean preview, boolean save) { static final ThinkingPolicy DISABLED = new ThinkingPolicy(false, false); @@ -109,6 +129,8 @@ public record ThinkingPolicy(boolean preview, boolean save) { private final Function factory; private final Map executors; private final Map bindings; + private final Map replay; + private final NativeToolRecovery.ModelCheck modelCheck; private final ModelExecutions modelExecutions; private final String modelRoute; private final Duration replyTimeout; @@ -126,7 +148,9 @@ private AgentScopeAdapter( null, ExecutionConfig.MODEL_DEFAULTS.getTimeout(), AgentScopeToolHooks.NONE, - ThinkingPolicy.DISABLED); + ThinkingPolicy.DISABLED, + Map.of(), + null); } private AgentScopeAdapter( @@ -137,7 +161,11 @@ private AgentScopeAdapter( String modelRoute, Duration replyTimeout, AgentScopeToolHooks toolHooks, - ThinkingPolicy thinking) { + ThinkingPolicy thinking, + Map replay, + NativeToolRecovery.ModelCheck modelCheck) { + this.replay = Map.copyOf(replay); + this.modelCheck = modelCheck; this.thinking = Objects.requireNonNull(thinking); this.replyTimeout = replyTimeout; this.modelExecutions = modelExecutions; @@ -158,7 +186,9 @@ public AgentScopeAdapter withToolHooks(AgentScopeToolHooks hooks) { modelRoute, replyTimeout, hooks, - thinking); + thinking, + replay, + modelCheck); } public AgentScopeAdapter withThinking(ThinkingPolicy policy) { @@ -170,7 +200,27 @@ public AgentScopeAdapter withThinking(ThinkingPolicy policy) { modelRoute, replyTimeout, toolHooks, - policy); + policy, + replay, + modelCheck); + } + + /** Configure native dispatches by tool name. Unlisted tools default to NEVER. */ + public AgentScopeAdapter withNativeToolRecovery( + Map policies, NativeToolRecovery.ModelCheck check) { + if (policies.keySet().stream().anyMatch(executors::containsKey)) + throw new IllegalArgumentException("Replay policies apply only to native tools"); + return new AgentScopeAdapter( + factory, + executors, + bindings, + modelExecutions, + modelRoute, + replyTimeout, + toolHooks, + thinking, + policies, + check); } /** Hand off reasoning to a lease-based Model Worker. */ @@ -190,7 +240,9 @@ public AgentScopeAdapter withModelExecutions( DurableJson.text(route, "model route"), replyTimeout, toolHooks, - thinking); + thinking, + replay, + modelCheck); } /** Registers schemas from the same immutable definitions used by the remote worker. */ @@ -239,6 +291,10 @@ public ThreadJournal log(RuntimeContext context) { return agent.threadJournal(context); } + public ToolResultBlock replay(ToolUseBlock call, RuntimeContext context) { + return replayNative(agent.getToolkit(), agent, call, context); + } + public Flux stream(List input, RuntimeContext context) { return agent.streamEvents(input, context); } @@ -290,6 +346,10 @@ public ThreadJournal log(RuntimeContext context) { return agent.threadJournal(context); } + public ToolResultBlock replay(ToolUseBlock call, RuntimeContext context) { + return replayNative(agent.getToolkit(), agent, call, context); + } + public Flux stream(List input, RuntimeContext context) { return agent.streamEvents(input, context); } @@ -362,11 +422,36 @@ public void execute(HarnessContext context) { var turnId = context.lease().turnId(); BackendThreadJournal log; try (var timing = PreparationTiming.start("journal.restore", turnId)) { - log = new BackendThreadJournal(context, executors, bindings, thinking); + log = new BackendThreadJournal(context, executors, bindings, thinking, replay); + } + var nativeCalls = new HashSet(); + var dispatches = new ArrayList(); + if (log.hasUnsettledNativeTools(turnId)) { + var projection = JournalProjection.read(log); + if (frame.signals().stream() + .anyMatch( + signal -> + WaitCondition.NATIVE_TOOL_RECONCILIATION.equals( + signal.key()))) { + if (resolveNativeToolOutcomes(context, log, projection) == null) return; + } else { + nativeCalls.addAll(projection.uncertainToolCalls()); + frame.tools().forEach(tool -> nativeCalls.remove(tool.request().call().callId())); + for (var event : log.scan(log.recoveryPosition(), log.head().seq())) { + if ("tool/dispatch".equals(event.type()) + && turnId.equals(event.turnId()) + && nativeCalls.contains(event.data().get("toolCallId"))) { + var dispatch = NativeToolRecovery.dispatch(frame.definition().key(), event); + if (dispatch.replay() == NativeToolRecovery.Replay.SAFE + || modelCheck != null) dispatches.add(dispatch); + } + } + if (!nativeCalls.isEmpty() && dispatches.isEmpty()) { + parkNativeToolOutcomes(context, nativeCalls); + return; + } + } } - if (log.hasUnsettledNativeTools(turnId) - && resolveNativeToolOutcomes(context, log, JournalProjection.read(log)) == null) - return; var hooks = new ToolHookJournal(toolHooks, frame.definition(), context.lease().turnId(), log); var host = @@ -512,6 +597,53 @@ && resolveNativeToolOutcomes(context, log, JournalProjection.read(log)) == null) throw new DurableException( DurableException.Code.INCOMPATIBLE, "Adapter did not install the invocation journal"); + if (!nativeCalls.isEmpty()) { + for (var dispatch : dispatches) { + if (!nativeCalls.contains(dispatch.call().getId())) continue; + if (pauseIfRequested(context) + || context.draining() + || context.frame().turn().cancellationRequested()) return; + runtimeContext.setAgentState(JournalProjection.read(log).restore()); + ToolResultBlock result; + String reason; + if (dispatch.replay() == NativeToolRecovery.Replay.SAFE) { + result = agent.replay(dispatch.call(), runtimeContext); + reason = "safe replay " + dispatch.actionId(); + } else { + var verified = modelCheck.check(dispatch); + if (verified.isEmpty()) continue; + result = verified.get().result(); + reason = + "verified " + + dispatch.actionId() + + " " + + verified.get().evidenceRef(); + } + if (!NativeToolRecovery.terminal(result)) continue; + if (!dispatch.call().getId().equals(result.getId()) + || !dispatch.call().getName().equals(result.getName())) + throw new DurableException( + DurableException.Code.CONFLICT, + "Native recovery result identity differs"); + var call = dispatch.call(); + var normalized = + normalizeExternalResult( + log, + hooks, + frame.turn().turnId(), + TransactionalSessionBackend.executionId( + frame.definition().key(), + frame.turn().turnId(), + call.getId()), + call, + result, + DurableJson.hash(result)); + ThreadRecovery.reconcileOne(log, normalized, reason); + nativeCalls.remove(dispatch.call().getId()); + } + if (!nativeCalls.isEmpty()) parkNativeToolOutcomes(context, nativeCalls); + return; + } // A view fixed by the claim can recover without a separate native start commit. host.deferInvocationStart(workspace.pinInvocationWorkspace()); agent.stream(List.copyOf(input), runtimeContext).blockLast(); @@ -903,7 +1035,7 @@ public void settle(HarnessContext context, TurnStatus status, String error) { throw new DurableException( DurableException.Code.CONFLICT, "External tool outcome requires reconciliation"); - var log = new BackendThreadJournal(context, executors, bindings, thinking); + var log = new BackendThreadJournal(context, executors, bindings, thinking, replay); var projection = JournalProjection.read(log); String turnId = context.lease().turnId(); var thread = context.lease().thread(); diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeExecutionHost.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeExecutionHost.java index 53a4c137ec..9cad39b333 100644 --- a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeExecutionHost.java +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeExecutionHost.java @@ -106,6 +106,7 @@ WaitCondition waitingForModel() { private Frame frame; private long replayAfter; + private final Map pendingProviderKeys = new LinkedHashMap<>(); private boolean replayingModelReply; private final Set replayed = new HashSet<>(); private boolean completed; @@ -382,10 +383,18 @@ public Mono normalizeToolResult( for (var event : log.scan(log.recoveryPosition(), log.head().seq())) { if ("state/checkpoint".equals(event.type())) { replayAfter = event.seq(); + pendingProviderKeys.clear(); replayingModelReply = false; } if (!durable.lease().turnId().equals(event.turnId())) continue; var data = event.data(); + if ("request/prepared".equals(event.type()) + && data.get("durableRequestHash") instanceof String hash + && data.get("durableProviderKey") instanceof String key) + pendingProviderKeys.put(hash, key); + if ("model/end".equals(event.type()) + && data.get(ModelCapture.OUTCOME) instanceof Map outcome) + pendingProviderKeys.remove(outcome.get("replayHash")); // A recorded local reply replays against its original request. if ("model/end".equals(event.type()) && "completed".equals(data.get("status")) @@ -629,11 +638,17 @@ && isQueued(data.get("modelCallId")) Flux invoke = Flux.defer( () -> { + String key = pendingProviderKeys.remove(hash); log.modelStarted( call, new ModelCapture( - model, purpose, messages, tools, - options, hash)); + model, + purpose, + messages, + tools, + options, + hash, + key == null ? call : key)); return next.apply(call); }) .doOnNext(chunk -> log.modelChunk(call, chunk)); @@ -643,6 +658,18 @@ && isQueued(data.get("modelCallId")) }); } + @Override + public GenerateOptions providerOptions(String callId, GenerateOptions options) { + if (options != null + && options.getAdditionalHeaders().keySet().stream() + .anyMatch("Idempotency-Key"::equalsIgnoreCase)) return options; + return GenerateOptions.mergeOptions( + options, + GenerateOptions.builder() + .additionalHeader("Idempotency-Key", log.providerKey(callId)) + .build()); + } + private Mono checkQueuedReplyAsync() { return Mono.defer( () -> { diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/BackendThreadJournal.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/BackendThreadJournal.java index 2cff66a50f..19516094d9 100644 --- a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/BackendThreadJournal.java +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/BackendThreadJournal.java @@ -95,6 +95,7 @@ void suppressCompletedModelPreviews(String step) { completedRemoteStep = step; } + private final Map replay; private final Map captures = new LinkedHashMap<>(); private ObjectNode cached; private final long recoveryPosition; @@ -111,6 +112,16 @@ void suppressCompletedModelPreviews(String step) { Map executors, Map bindings, AgentScopeAdapter.ThinkingPolicy thinking) { + this(context, executors, bindings, thinking, Map.of()); + } + + BackendThreadJournal( + HarnessContext context, + Map executors, + Map bindings, + AgentScopeAdapter.ThinkingPolicy thinking, + Map replay) { + this.replay = replay; thinkingPreviews = thinking.preview(); saveThinking = thinking.save(); previews = new AgentScopeMessageEvents(thinking.save()); @@ -196,20 +207,48 @@ synchronized void modelStarted(String id, ModelCapture capture) { captures.put(id, capture); } + synchronized String providerKey(String id) { + return captures.get(id).providerKey; + } + synchronized void modelChunk(String id, ChatResponse chunk) { captures.get(id).accept(chunk); } private JournalEvent capture(JournalEvent event) { + if ("tool/dispatch".equals(event.type()) + && event.data().get("name") instanceof String name + && !executors.containsKey(name)) { + var data = new LinkedHashMap<>(event.data()); + data.put( + "replay", + replay.getOrDefault(name, NativeToolRecovery.Replay.NEVER) + .name() + .toLowerCase(Locale.ROOT)); + return new JournalEvent( + event.schemaVersion(), + event.eventId(), + event.seq(), + event.occurredAt(), + event.type(), + event.executionRunId(), + event.turnId(), + event.required(), + JsonUtils.getJsonCodec().toJson(data)); + } if ("model/request_started".equals(event.type())) { var capture = captures.get(String.valueOf(event.data().get("modelCallId"))); if (capture != null) capture.nextAttempt(); } - if (!"model/end".equals(event.type())) return event; + boolean prepared = "request/prepared".equals(event.type()); + if (!prepared && !"model/end".equals(event.type())) return event; var capture = captures.get(String.valueOf(event.data().get("modelCallId"))); if (capture == null) return event; var data = new LinkedHashMap(event.data()); - data.put(ModelCapture.OUTCOME, capture.freeze(String.valueOf(data.get("status")))); + if (prepared) { + data.put("durableRequestHash", capture.replayHash); + data.put("durableProviderKey", capture.providerKey); + } else data.put(ModelCapture.OUTCOME, capture.freeze(String.valueOf(data.get("status")))); return new JournalEvent( event.schemaVersion(), event.eventId(), diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/ModelCapture.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/ModelCapture.java index e6c0b36092..020a9ff5d0 100644 --- a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/ModelCapture.java +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/ModelCapture.java @@ -39,7 +39,8 @@ final class ModelCapture { static final String OUTCOME = "durableModelOutcome"; private static final long MAX_BYTES = 16L * 1024 * 1024; private final Map request; - private final String replayHash; + final String replayHash; + final String providerKey; private final ReasoningContext content = new ReasoningContext("durable"); private final List additional = new ArrayList<>(); private final Map metadata = new LinkedHashMap<>(); @@ -51,6 +52,7 @@ final class ModelCapture { ModelCapture() { this.request = Map.of(); this.replayHash = null; + this.providerKey = null; } ModelCapture( @@ -59,7 +61,8 @@ final class ModelCapture { List messages, List tools, GenerateOptions options, - String replayHash) { + String replayHash, + String providerKey) { var data = new LinkedHashMap(); data.put("model", model); data.put("purpose", purpose); @@ -68,6 +71,7 @@ final class ModelCapture { data.put("options", options); this.request = freeze(data); this.replayHash = replayHash; + this.providerKey = providerKey; if (JsonUtils.getJsonCodec().toJson(request).length() > MAX_BYTES) throw new DurableException( DurableException.Code.INVALID, "Model request exceeds capture limit"); diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/NativeToolRecovery.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/NativeToolRecovery.java new file mode 100644 index 0000000000..12e9f108b1 --- /dev/null +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/NativeToolRecovery.java @@ -0,0 +1,153 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.agentscope.durable.agentscope; + +import io.agentscope.core.agent.accumulator.ReasoningContext; +import io.agentscope.core.journal.JournalEvent; +import io.agentscope.core.message.Msg; +import io.agentscope.core.message.SystemMessage; +import io.agentscope.core.message.ToolResultBlock; +import io.agentscope.core.message.ToolResultState; +import io.agentscope.core.message.ToolUseBlock; +import io.agentscope.core.message.UserMessage; +import io.agentscope.core.model.Model; +import io.agentscope.core.model.ToolSchema; +import io.agentscope.durable.DurableJson; +import io.agentscope.durable.DurableTypes.ThreadKey; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** Policy frozen on the first native dispatch, and optional evidence lookup for an uncertain call. */ +public final class NativeToolRecovery { + private NativeToolRecovery() {} + + public enum Replay { + SAFE, + NEVER + } + + /** The identity and post-interception arguments actually admitted by the original Brain. */ + public record Dispatch( + ThreadKey thread, String turnId, String actionId, ToolUseBlock call, Replay replay) {} + + @SuppressWarnings("unchecked") + static Dispatch dispatch(ThreadKey thread, JournalEvent event) { + var data = event.data(); + var call = + ToolUseBlock.builder() + .id((String) data.get("toolCallId")) + .name((String) data.get("name")) + .input((Map) data.get("arguments")) + .build(); + return new Dispatch( + thread, + event.turnId(), + (String) data.get("actionId"), + call, + "safe".equals(data.get("replay")) ? Replay.SAFE : Replay.NEVER); + } + + static boolean terminal(ToolResultBlock result) { + return result != null + && result.getState() != null + && !result.isSuspended() + && result.getState() != ToolResultState.RUNNING + && !(result.getExecutionDetails() != null + && "UNKNOWN".equals(result.getExecutionDetails().outcome().name())); + } + + public record Evidence(String evidenceRef, ToolResultBlock result) { + public Evidence { + DurableJson.text(evidenceRef, "evidenceRef"); + if (!terminal(result)) + throw new IllegalArgumentException("Verified terminal outcome required"); + } + } + + /** Read-only lookup. Verify the external record against this thread, turn and original call. + * Return empty when absent, inconsistent or inconclusive. The model's lookup hint is untrusted. */ + @FunctionalInterface + public interface EvidenceLookup { + Optional verify(Dispatch dispatch, String hint); + } + + /** A separate model invocation with one read-only verification tool and no side-effect tools. */ + public record ModelCheck(Model model, EvidenceLookup lookup) { + public ModelCheck { + Objects.requireNonNull(model); + Objects.requireNonNull(lookup); + } + + Optional check(Dispatch dispatch) { + var schema = + ToolSchema.builder() + .name("verify_outcome") + .description("Look up independent evidence for the original operation") + .parameters( + Map.of( + "type", + "object", + "properties", + Map.of("hint", Map.of("type", "string")), + "required", + List.of("hint"))) + .build(); + var prompt = + List.of( + SystemMessage.builder() + .textContent( + "An interrupted operation may already have run. To" + + " check it, call verify_outcome with a lookup" + + " hint from the original request. If no lookup is" + + " possible, abstain.") + .build(), + UserMessage.builder() + .textContent(DurableJson.value(dispatch).toString()) + .build()); + try { + var capture = new ReasoningContext("native-recovery"); + model.stream(prompt, List.of(schema), null) + .doOnNext(capture::processChunk) + .blockLast(); + var message = capture.buildFinalMessage(); + if (message == null) return Optional.empty(); + var calls = message.getContentBlocks(ToolUseBlock.class); + if (calls.size() != 1 + || !"verify_outcome".equals(calls.get(0).getName()) + || !(calls.get(0).getInput().get("hint") instanceof String hint) + || hint.isBlank()) return Optional.empty(); + return lookup.verify(dispatch, hint) + .filter( + evidence -> + dispatch.call().getId().equals(evidence.result().getId()) + && dispatch.call() + .getName() + .equals(evidence.result().getName())); + } catch (RuntimeException unavailable) { + System.getLogger(ModelCheck.class.getName()) + .log( + System.Logger.Level.WARNING, + "Native evidence check unavailable for action {0} ({1})", + dispatch.actionId(), + unavailable.getClass().getSimpleName()); + return Optional.empty(); + } + } + } +} diff --git a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeAdapterTest.java b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeAdapterTest.java index 13944560eb..3f55adf005 100644 --- a/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeAdapterTest.java +++ b/agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeAdapterTest.java @@ -209,6 +209,58 @@ public Flux stream( } } + @Test + void nativeEvidenceCheckRequiresMatchingIndependentEvidence() { + var original = ToolUseBlock.builder().id("call").name("charge").input(Map.of()).build(); + var dispatch = + new NativeToolRecovery.Dispatch( + new ThreadKey(new SessionKey("app", "session"), "thread"), + "turn", + "action", + original, + NativeToolRecovery.Replay.NEVER); + var check = + new NativeToolRecovery.ModelCheck( + new ScriptedModel(false), + (operation, hint) -> { + throw new AssertionError( + "A prose response must not trigger evidence lookup"); + }); + assertTrue(check.check(dispatch).isEmpty()); + + var model = org.mockito.Mockito.mock(Model.class); + var query = + ToolUseBlock.builder() + .id("lookup") + .name("verify_outcome") + .input(Map.of("hint", "receipt")) + .build(); + doReturn(Flux.just(ChatResponse.builder().content(List.of(query)).build())) + .when(model) + .stream(any(), any(), any()); + var wrongReceipt = + new NativeToolRecovery.Evidence( + "receipt-1", + ToolResultBlock.success("ok").withIdAndName("another-call", "charge")); + var lookups = new AtomicInteger(); + check = + new NativeToolRecovery.ModelCheck( + model, + (operation, hint) -> { + assertEquals(dispatch, operation); + assertEquals("receipt", hint); + lookups.incrementAndGet(); + return java.util.Optional.of(wrongReceipt); + }); + assertTrue(check.check(dispatch).isEmpty()); + assertEquals(1, lookups.get()); + assertThrows( + IllegalArgumentException.class, + () -> + new NativeToolRecovery.Evidence( + "receipt-1", ToolResultBlock.text("still running"))); + } + AgentScopeAdapter adapter(Model model, PermissionMode mode, Map bindings) { return AgentScopeAdapter.forReAct( binding -> { @@ -524,6 +576,60 @@ public Flux stream( } } + @Test + void inFlightModelReusesProviderKeyAcrossTakeover() throws Exception { + var calls = new CopyOnWriteArrayList(); + Model model = + new Model() { + public String getModelName() { + return "counting"; + } + + public Flux stream( + List messages, List tools, GenerateOptions options) { + calls.add(options.getAdditionalHeaders().get("Idempotency-Key")); + return Flux.just( + ChatResponse.builder() + .content(List.of(TextBlock.builder().text("done").build())) + .build()); + } + }; + var thread = new ThreadKey(key, "main"); + try (var storage = LocalBackend.open(directory.resolve("in-flight-model"))) { + var interrupted = spy(storage); + doAnswer( + invocation -> { + if (!calls.isEmpty()) + throw new DurableException( + DurableException.Code.UNAVAILABLE, + "Interrupted after provider admission"); + return invocation.callRealMethod(); + }) + .when(interrupted) + .commit(any(), any()); + String turn; + try (var runtime = + runtime(interrupted, adapter(model, PermissionMode.BYPASS, Map.of()), null)) { + turn = runtime.createSession(key, "agent").submit("one", "hello").turnId(); + runtime.tick(thread); + assertEquals(1, calls.size()); + } + Thread.sleep(5); + try (var runtime = + runtime(storage, adapter(model, PermissionMode.BYPASS, Map.of()), null)) { + runtime.tick(thread); + assertEquals(TurnStatus.SUCCEEDED, storage.turn(thread, turn).status()); + assertEquals(2, calls.size()); + assertNotNull(calls.get(0)); + assertEquals(calls.get(0), calls.get(1)); + runtime.getSession(key).submit("two", "hello"); + runtime.tick(thread); + assertEquals(3, calls.size()); + assertFalse(calls.get(0).equals(calls.get(2))); + } + } + } + @Test void receivedInputIsRetriedIfTheFirstHostStopsBeforeApplyingIt() { var model = new ScriptedModel(false); @@ -593,8 +699,9 @@ void receivedInputIsRetriedIfTheFirstHostStopsBeforeApplyingIt() { } } - @Test - void completedModelSurvivesCrashBeforeStateApplication() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void completedModelSurvivesCrashBeforeFinalization(boolean checkpointAnswer) throws Exception { var model = new ScriptedModel(false); var crash = new AtomicBoolean(); var armed = new AtomicBoolean(); @@ -613,8 +720,20 @@ void completedModelSurvivesCrashBeforeStateApplication() throws Exception { JournalEvent.class)) .anyMatch( event -> - event.type() - .equals("model/end")); + checkpointAnswer + ? "state/checkpoint" + .equals( + event + .type()) + && "state_save" + .equals( + event.data() + .get( + "reason")) + : "model/end" + .equals( + event + .type())); if (armed.get()) { crash.set(true); throw new DurableException( @@ -666,7 +785,9 @@ void completedModelSurvivesCrashBeforeStateApplication() throws Exception { assertEquals("done", answer.path("text").asText()); assertEquals(1, answer.path("attempt").asLong()); assertEquals( - 1, answer.path("revision").asLong(), "Replay replaces the partial stream"); + checkpointAnswer ? 0 : 1, + answer.path("revision").asLong(), + "A completed answer keeps its revision while replay replaces a preview"); var projection = new EventProjection(key); for (var event : storage.events(key, null, 1000).events()) projection.accept(event); assertEquals( @@ -2324,14 +2445,31 @@ void nativeHistoryAndReliableFinalSurviveRebuiltAgentAndBackend() throws Excepti } var reopened = new TransactionalSessionBackend(JdbcRecordStore.sqlite(file)); var model = new ScriptedModel(false); + var reads = new CopyOnWriteArrayList(); + var observed = + (SessionBackend) + java.lang.reflect.Proxy.newProxyInstance( + SessionBackend.class.getClassLoader(), + new Class[] {SessionBackend.class}, + (proxy, method, args) -> { + if ("replayJournal".equals(method.getName())) + reads.add((Long) args[2]); + try { + return method.invoke(reopened, args); + } catch (java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + }); try (var runtime = - runtime(reopened, adapter(model, PermissionMode.BYPASS, Map.of()), null)) { + runtime(observed, adapter(model, PermissionMode.BYPASS, Map.of()), null)) { var turn = runtime.getSession(key).submit("two", "continue"); runtime.tick(new ThreadKey(key, "main")); assertNull(runtime.lastFailure(new ThreadKey(key, "main"))); assertEquals( TurnStatus.SUCCEEDED, reopened.turn(new ThreadKey(key, "main"), turn.turnId()).status()); + assertFalse(reads.isEmpty()); + assertTrue(reads.stream().allMatch(after -> after > 0), reads.toString()); assertTrue( model.inputs.get(0).stream() .anyMatch(m -> m.getTextContent().contains("remember this"))); @@ -4140,6 +4278,16 @@ void cancelPendingInteractionClearsNativeStateForNextTurn() throws Exception { assertEquals( TurnStatus.CANCELLED, backend.turn(new ThreadKey(key, "main"), turn.turnId()).status()); + var thread = new ThreadKey(key, "main"); + var checkpoints = backend.checkpoints(thread, 0, 1000); + long position = Long.parseLong(checkpoints.get(checkpoints.size() - 1).position()); + var checkpoint = backend.checkpoint(thread, position); + assertTrue(checkpoint.settled()); + long cursor = checkpoint.journalAnchor() - 1; + assertTrue(cursor > 0); + var first = backend.checkpointJournal(thread, position, cursor, 1).get(0); + assertEquals("state/checkpoint", first.required("type").asText()); + assertEquals(turn.turnId(), first.required("turnId").asText()); } var nextModel = new ScriptedModel(false); try (var runtime = diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java index 3999626aea..0537eb823e 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java @@ -893,8 +893,8 @@ public void tick(ThreadKey key) { private ClaimOutcome claim(ThreadKey key, TurnDispatch dispatch, String claimId) { return dispatch == null - ? backend.claimOutcome(key, claimId, leaseDuration) - : backend.claimOutcome(dispatch, claimId, leaseDuration); + ? backend.claimOutcome(key, claimId, leaseDuration, recoveryPolicy) + : backend.claimOutcome(dispatch, claimId, leaseDuration, recoveryPolicy); } private void process(ThreadKey key, Active activeCall, TurnDispatch dispatch, Source source) { @@ -1231,7 +1231,11 @@ private void resolve( } finally { endProviderCall(activeCall); } - backend.acceptResult(lease.thread(), tool.request().executionId(), result); + if (result.state().terminal()) { + backend.acceptResult(lease.thread(), tool.request().executionId(), result); + } else { + backend.acceptResult(lease, tool.request().executionId(), result); + } } private void endProviderCall(Active activeCall) { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/ExecutionRecovery.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/ExecutionRecovery.java index 3d09214e12..1cf63f2dad 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/ExecutionRecovery.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/ExecutionRecovery.java @@ -65,7 +65,10 @@ public static ExecutionResult resolve( : unknown(observed, "Provider cannot confirm cancellation"); } else if (queryable) { observed = retainHandle(executor.query(request, observed.handle()), observed); + // A previously issued provider handle is evidence of admission. A + // different Hands may have a weaker view; never replace that operation. if (observed.state() == ExecutionState.NOT_FOUND + && previous.handle() == null && capabilities.idempotentStart()) observed = retainHandle(executor.startExecution(request), observed); } else if (capabilities.idempotentStart()) { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/Executor.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/Executor.java index 5b20513902..c15a1a5357 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/Executor.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/Executor.java @@ -48,6 +48,12 @@ default void validateStart(ExecutionRequest request) {} /** Starts or recovers the execution identified by the request. */ ExecutionResult startExecution(ExecutionRequest request); + /** + * Return NOT_FOUND only for authoritative absence. A worker may then issue another start + * when idempotentStart is advertised and the provider has not already issued a handle. A timeout, partition, or eventually consistent lookup + * cannot establish absence and must report UNKNOWN or a transient failure. Idempotent start + * must suppress duplicate effects across concurrent workers using the same execution ID. + */ ExecutionResult query(ExecutionRequest request, String handle); ExecutionResult cancel(ExecutionRequest request, String handle); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/NotifyingSessionBackend.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/NotifyingSessionBackend.java index d33a3a5e10..cb2db01a09 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/NotifyingSessionBackend.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/NotifyingSessionBackend.java @@ -421,14 +421,32 @@ public Optional claim(TurnDispatch dispatch, String owner, Duration durat @Override public ClaimOutcome claimOutcome(ThreadKey session, String owner, Duration duration) { - var result = delegate.claimOutcome(session, owner, duration); + return claimOutcome(session, owner, duration, null); + } + + @Override + public ClaimOutcome claimOutcome( + ThreadKey session, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { + var result = delegate.claimOutcome(session, owner, duration, policy); if (result.lease() != null) changed(session.session()); return result; } @Override public ClaimOutcome claimOutcome(TurnDispatch dispatch, String owner, Duration duration) { - var result = delegate.claimOutcome(dispatch, owner, duration); + return claimOutcome(dispatch, owner, duration, null); + } + + @Override + public ClaimOutcome claimOutcome( + TurnDispatch dispatch, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { + var result = delegate.claimOutcome(dispatch, owner, duration, policy); if (result.lease() != null) changed(dispatch.thread().session()); return result; } @@ -650,6 +668,12 @@ public OutputPage toolOutput(ThreadKey thread, String turnId, String executionId return delegate.toolOutput(thread, turnId, executionId, offset); } + @Override + public void acceptResult(Lease lease, String executionId, ExecutionResult result) { + delegate.acceptResult(lease, executionId, result); + changed(lease.thread()); + } + @Override public void acceptResult(ThreadKey session, String executionId, ExecutionResult result) { delegate.acceptResult(session, executionId, result); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionBackend.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionBackend.java index c9a1c63608..52837bcd9c 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionBackend.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionBackend.java @@ -265,6 +265,20 @@ default ClaimOutcome claimOutcome(TurnDispatch dispatch, String owner, Duration throw new UnsupportedOperationException("This backend does not host execution"); } + /** Claims using the recovery policy pinned when a Turn first starts. */ + default ClaimOutcome claimOutcome( + ThreadKey thread, String owner, Duration duration, DurableTypes.RecoveryPolicy policy) { + return claimOutcome(thread, owner, duration); + } + + default ClaimOutcome claimOutcome( + TurnDispatch dispatch, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { + return claimOutcome(dispatch, owner, duration); + } + /** Indexed publication backlog. A send receipt does not consume a dispatch. */ default List pendingDispatches(int limit) { throw new UnsupportedOperationException("Turn dispatch is not supported"); @@ -442,6 +456,9 @@ default ExecutionUpdate acceptExecutionEvents( void acceptResult(ThreadKey session, String executionId, ExecutionResult result); + /** Persist a nonterminal direct executor observation under the active Brain lease. */ + void acceptResult(Lease lease, String executionId, ExecutionResult result); + /** Read an accepted output page by its byte offset within the named Turn and execution. */ default OutputPage toolOutput( ThreadKey thread, String turnId, String executionId, long offset) { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/TransactionalSessionBackend.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/TransactionalSessionBackend.java index 8a804b92a8..d35d33b13c 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/TransactionalSessionBackend.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/TransactionalSessionBackend.java @@ -55,6 +55,7 @@ import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.OutputPage; import io.agentscope.durable.DurableTypes.PublicEvent; +import io.agentscope.durable.DurableTypes.RecoveryPolicy; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -333,8 +334,10 @@ public static final class TurnData { public JsonNode output; public String error; public WaitCondition waiting; + public DurableTypes.RecoveryPolicy claimPolicy; public RecoveryView recovery; public long failedEpoch; + public int consecutiveLostRuns; public boolean jobWaitRegistered; public boolean eventDrivenTools; public boolean hasTools; @@ -1785,18 +1788,35 @@ public Optional claim(TurnDispatch dispatch, String owner, Duration durat @Override public ClaimOutcome claimOutcome(ThreadKey thread, String owner, Duration duration) { - return claimOutcome(thread, null, owner, duration); + return claimOutcome(thread, owner, duration, null); + } + + @Override + public ClaimOutcome claimOutcome( + ThreadKey thread, String owner, Duration duration, RecoveryPolicy policy) { + return claimOutcome(thread, null, owner, duration, policy); } @Override public ClaimOutcome claimOutcome(TurnDispatch dispatch, String owner, Duration duration) { - return claimOutcome(dispatch.thread(), dispatch, owner, duration); + return claimOutcome(dispatch, owner, duration, null); + } + + @Override + public ClaimOutcome claimOutcome( + TurnDispatch dispatch, String owner, Duration duration, RecoveryPolicy policy) { + return claimOutcome(dispatch.thread(), dispatch, owner, duration, policy); } private ClaimOutcome claimOutcome( - ThreadKey key, TurnDispatch dispatch, String owner, Duration duration) { + ThreadKey key, + TurnDispatch dispatch, + String owner, + Duration duration, + RecoveryPolicy policy) { DurableJson.text(owner, "owner"); long ttl = positive(duration); + store.boundIdleTransactionTime(duration); return changeAndRead( key, "claim", @@ -1817,7 +1837,37 @@ private ClaimOutcome claimOutcome( if (ready > now) return ClaimOutcome.unavailable(ClaimStatus.NOT_DUE); if (!turn.cancel) attachBackgroundInputs(s, turn); Long eligibleAt = s.thread.dispatchEligibleAt; - invocations(s, turn).abandon(now, true); + if (turn.claimPolicy == null) + turn.claimPolicy = + policy == null ? DurableTypes.RecoveryPolicy.defaults() : policy; + var records = invocations(s, turn); + if (turn.owner != null + && turn.lastRunId != null + && !records.run(turn.lastRunId).status().terminal() + && (turn.recovery == null || turn.recovery.retryAllowed())) { + var lostPolicy = + turn.recovery == null ? turn.claimPolicy : turn.recovery.policy(); + if (++turn.consecutiveLostRuns > lostPolicy.maxRetries()) { + turn.error = + "Repeated ownership loss without completed execution progress"; + turn.recovery = + new RecoveryView( + lostPolicy.maxRetries() + 1, + lostPolicy, + false, + null, + turn.error); + turn.revision++; + append( + s, + turn, + new EventInput( + "lost-limit:" + turn.id + ":" + turn.epoch, + "turn.recovery", + DurableJson.value(turn.recovery))); + } + } + records.abandon(now, true); turn.owner = owner; turn.epoch = ++s.thread.epoch; turn.expiresAt = Math.addExact(now, ttl); @@ -1942,6 +1992,7 @@ public DispatchSchedule releaseUpdate(Lease lease, Duration delay) { return null; } invocations(s, r).abandon(n, false); + r.consecutiveLostRuns = 0; r.owner = null; r.expiresAt = 0; r.nextAttemptAt = Math.max(r.nextAttemptAt, Math.addExact(n, delay.toMillis())); @@ -2167,6 +2218,9 @@ public CommitUpdate commitUpdate(Lease lease, Commit command, Duration publicati if (startsModel && (r.cancel || r.status == TurnStatus.PAUSING)) throw error( DurableException.Code.FENCED, "Turn stopped before model start"); + boolean cancellationRepair = r.cancel && nativeCancellationRepair(r, command); + if (r.cancel && command.status() != TurnStatus.CANCELLED && !cancellationRepair) + throw error(DurableException.Code.FENCED, "Invocation cancelled"); boolean appendOnly = append != null && !append.entries().isEmpty() @@ -2199,6 +2253,9 @@ public CommitUpdate commitUpdate(Lease lease, Commit command, Duration publicati if (!journal.isEmpty()) s.thread.journalCommitId = command.commitId(); } var effectPositions = new ArrayList(); + if (command.steps().stream() + .anyMatch(step -> step.status() == DurableTypes.StepStatus.COMPLETED)) + r.consecutiveLostRuns = 0; for (var call : command.tools()) if (!r.tools.containsKey(executionId(lease.thread(), r.id, call.callId()))) effectPositions.add(call.origin()); @@ -2399,7 +2456,9 @@ public CommitUpdate commitUpdate(Lease lease, Commit command, Duration publicati } TurnStatus previousStatus = r.status; r.revision++; - r.waiting = command.waiting(); + if (!cancellationRepair + || command.journal() == null + || !command.consumedSignals().isEmpty()) r.waiting = command.waiting(); if (r.cancel) next = next.terminal() ? TurnStatus.CANCELLED : TurnStatus.CANCELLING; r.output = DurableJson.copy(r.cancel ? null : command.output()); @@ -3171,8 +3230,17 @@ public T stageExecutionBatch( }); } + @Override + public void acceptResult(Lease lease, String id, ExecutionResult result) { + acceptResult(lease.thread(), lease, id, result); + } + @Override public void acceptResult(ThreadKey key, String id, ExecutionResult result) { + acceptResult(key, null, id, result); + } + + private void acceptResult(ThreadKey key, Lease lease, String id, ExecutionResult result) { Objects.requireNonNull(result); if (result.state() == ExecutionState.NOT_FOUND) throw error(DurableException.Code.INVALID, "NOT_FOUND is not an accepted outcome"); @@ -3182,7 +3250,7 @@ public void acceptResult(ThreadKey key, String id, ExecutionResult result) { String turnId = s.executions.get(id); if (turnId == null) throw error(DurableException.Code.NOT_FOUND, "Execution not found"); - TurnData r = requireTurn(s, turnId); + TurnData r = lease == null ? requireTurn(s, turnId) : owned(s, lease, n); ToolData t = requireTool(r, id); acceptResult(s, r, t, id, result); return null; @@ -3833,6 +3901,50 @@ private static boolean waitSatisfied(TurnData turn, WaitCondition wait, long now && !turn.withdrawn.contains(signal.id())); } + /** A cancelling Turn can park for, and then commit, verified native tool evidence. */ + private static boolean nativeCancellationRepair(TurnData turn, Commit command) { + if (!command.tools().isEmpty() + || !command.output().isNull() + || command.error() != null + || command.run() != null + || !command.steps().isEmpty() + || !command.appliedResults().isEmpty() + || command.events().stream() + .anyMatch(event -> !"tool.call.updated".equals(event.type()))) return false; + if (command.journal() == null) { + return command.status() == TurnStatus.WAITING + && command.waiting() != null + && WaitCondition.NATIVE_TOOL_RECONCILIATION.equals(command.waiting().key()); + } + if (command.status() != TurnStatus.RUNNING) return false; + var entries = command.journal().entries(); + if (command.consumedSignals().isEmpty()) { + return entries.size() == 1 + && "durable/tool_normalized".equals(entries.get(0).path("type").asText()); + } + return awaitingNativeToolReconciliation(turn) + && command.consumedSignals().stream() + .allMatch( + id -> { + Signal signal = turn.signals.get(id); + return signal != null + && WaitCondition.NATIVE_TOOL_RECONCILIATION.equals( + signal.key()) + && !turn.consumed.contains(id) + && !turn.withdrawn.contains(id); + }) + && entries.stream() + .anyMatch(entry -> "recovery/applied".equals(entry.path("type").asText())) + && entries.stream() + .allMatch( + entry -> + Set.of( + "tool/result", + "recovery/applied", + "state/checkpoint") + .contains(entry.path("type").asText())); + } + private static boolean awaitingNativeToolReconciliation(TurnData turn) { return turn.waiting != null && WaitCondition.NATIVE_TOOL_RECONCILIATION.equals(turn.waiting.key()); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordStore.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordStore.java index 2c8ba790f9..3ecdfb31d2 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordStore.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordStore.java @@ -31,6 +31,9 @@ default Capabilities capabilities() { return new Capabilities("custom", false, false); } + /** Bound abandoned idle transactions by the shortest lease served by this store. */ + default void boundIdleTransactionTime(java.time.Duration leaseDuration) {} + record Record(JsonNode value, long now) {} record Update(JsonNode value, T result) {} diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/ExecutionRecoveryTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/ExecutionRecoveryTest.java index b6fcf2ab52..02cd002af9 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/ExecutionRecoveryTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/ExecutionRecoveryTest.java @@ -109,6 +109,38 @@ void anIdempotentProviderWithoutLookupCanReuseTheOriginalStartIdentity() { verify(executor, never()).query(any(), any()); } + @Test + void uncertainLookupOfRunningExecutionDoesNotRestartEvenAnIdempotentProvider() { + when(executor.capabilities()).thenReturn(new Executor.Capabilities(true, true, false)); + when(executor.query(request, "recovered")).thenReturn(unknown); + assertEquals( + ExecutionState.UNKNOWN, + ExecutionRecovery.resolve(executor, request, running, true, false).state()); + verify(executor, never()).startExecution(any()); + } + + @Test + void authoritativeAbsenceAllowsIdempotentStartWithTheSameExecutionId() { + when(executor.capabilities()).thenReturn(new Executor.Capabilities(true, true, false)); + when(executor.query(request, null)).thenReturn(ExecutionResult.missing()); + when(executor.startExecution(request)).thenReturn(running); + assertEquals(running, ExecutionRecovery.resolve(executor, request, unknown, true, false)); + verify(executor).startExecution(request); + } + + @Test + void missingAdmittedHandleRemainsQueryableAcrossMultipleReclaims() { + when(executor.capabilities()).thenReturn(new Executor.Capabilities(true, true, false)); + when(executor.query(request, "recovered")).thenReturn(ExecutionResult.missing()); + var observation = running; + for (int attempt = 0; attempt < 2; attempt++) { + observation = ExecutionRecovery.resolve(executor, request, observation, true, false); + assertEquals(ExecutionState.UNKNOWN, observation.state()); + assertEquals("recovered", observation.handle()); + } + verify(executor, never()).startExecution(any()); + } + @Test void uncertainNonIdempotentEffectsAreNeverRepeated() { when(executor.capabilities()).thenReturn(new Executor.Capabilities(false, false, false)); diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/SessionBackendContract.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/SessionBackendContract.java index ab2d99b10f..810d69e2e7 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/SessionBackendContract.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/SessionBackendContract.java @@ -1723,6 +1723,23 @@ private Lease claim() { .orElseThrow(); } + @Test + protected void repeatedExpiryOfUnfinishedRunsStopsInvocationRecovery() { + submit(); + var thread = new ThreadKey(key, "main"); + var policy = new RecoveryPolicy(2, 100, 500); + var lease = + backend.claimOutcome(thread, "owner", Duration.ofSeconds(1), policy) + .ownership() + .orElseThrow(); + for (int i = 0; i <= policy.maxRetries(); i++) { + backend.prepareRun(lease, "invoke-" + i); + clock.set(lease.expiresAt() + 1); + lease = claim(); + } + assertFalse(backend.frame(lease).turn().recovery().retryAllowed()); + } + @Test protected void changedProgressIsReplayableEvenWhenAnEarlierStateReturns() { submit(); @@ -1739,7 +1756,18 @@ protected void changedProgressIsReplayableEvenWhenAnEarlierStateReturns() { var id = backend.frame(lease).tools().get(0).request().executionId(); backend.beginDispatch(lease, id); var running = new ExecutionResult(ExecutionState.RUNNING, "original", null, null); - backend.acceptResult(new ThreadKey(key, "main"), id, running); + backend.release(lease, Duration.ZERO); + var replacement = claim(); + backend.acceptResult(replacement, id, running); + assertEquals( + DurableException.Code.FENCED, + assertThrows( + DurableException.class, + () -> + backend.acceptResult( + lease, id, ExecutionResult.unknown("late"))) + .code()); + assertEquals("original", backend.frame(replacement).tools().get(0).result().handle()); backend.acceptResult(new ThreadKey(key, "main"), id, running); backend.acceptResult( new ThreadKey(key, "main"), id, ExecutionResult.unknown("temporarily unreachable")); @@ -3408,8 +3436,17 @@ protected void cancellationAndCompletionPreserveTheOutcomeOfTheWinningDecision() List.of(), List.of(), List.of()); - var receipt = backend.commit(owner, late); - assertEquals(receipt, backend.commit(owner, late)); + code(DurableException.Code.FENCED, () -> backend.commit(owner, late)); + var settlement = + commit( + backend.frame(owner), + "settle-cancellation", + TurnStatus.CANCELLED, + List.of(), + List.of(), + List.of()); + var receipt = backend.commit(owner, settlement); + assertEquals(receipt, backend.commit(owner, settlement)); var cancelled = backend.turn(thread, first.turnId()); assertEquals(TurnStatus.CANCELLED, cancelled.status()); assertTrue(cancelled.output().isNull()); @@ -3830,6 +3867,7 @@ protected void pauseAndResumePreserveRecoveryBackoffAndCancellationBypassesIt() assertTrue(backend.claim(thread, "early", Duration.ofSeconds(1)).isEmpty()); assertEquals(1, backend.turn(thread, turn.turnId()).recovery().failures()); backend.cancel(thread, turn.turnId(), "cancel"); + backend.cancel(thread, turn.turnId(), "cancel-again"); var cancellation = claim(); assertTrue(backend.frame(cancellation).turn().cancellationRequested()); assertEquals(1, backend.frame(cancellation).turn().recovery().failures()); @@ -4263,6 +4301,33 @@ protected void cursorsAreSessionBoundAndSnapshotSurvivesRetention() { assertEquals(snapshot.projection(), backend.snapshot(key).projection()); } + @Test + protected void acceptedCancellationFencesLateModelAndCompletionCommits() { + var turn = submit(); + var owner = claim(); + var stale = backend.frame(owner); + backend.cancel(owner.thread(), turn.turnId(), "cancel"); + for (var frame : List.of(stale, backend.frame(owner))) { + for (var status : List.of(TurnStatus.RUNNING, TurnStatus.SUCCEEDED)) { + var late = commit(frame, "late-" + status, status, List.of(), List.of(), List.of()); + code(DurableException.Code.FENCED, () -> backend.commit(owner, late)); + assertTrue( + backend.receipt(owner.thread(), turn.turnId(), late.commitId()).isEmpty()); + } + } + assertEquals(TurnStatus.CANCELLING, backend.frame(owner).turn().status()); + backend.commit( + owner, + commit( + backend.frame(owner), + "settle", + TurnStatus.CANCELLED, + List.of(), + List.of(), + List.of())); + assertEquals(TurnStatus.CANCELLED, backend.turn(owner.thread(), turn.turnId()).status()); + } + @Test protected void cancellingUnknownExternalEffectDoesNotClaimItStopped() { submit(); diff --git a/agentscope-durable/durable-worker/src/main/java/io/agentscope/durable/worker/TransactionalExecutionStore.java b/agentscope-durable/durable-worker/src/main/java/io/agentscope/durable/worker/TransactionalExecutionStore.java index e69044656a..1da9b24616 100644 --- a/agentscope-durable/durable-worker/src/main/java/io/agentscope/durable/worker/TransactionalExecutionStore.java +++ b/agentscope-durable/durable-worker/src/main/java/io/agentscope/durable/worker/TransactionalExecutionStore.java @@ -48,20 +48,38 @@ public record Received(String key, boolean runnable, boolean recovery) {} private record Mutation(T result, boolean pendingEvents) {} + public static final int DEFAULT_UNKNOWN_LIMIT = 8; + private final int unknownLimit; + public TransactionalExecutionStore(RecordStore records) { - this.records = records; - prefix = "execution:"; - publications = key -> {}; + this(records, null, DEFAULT_UNKNOWN_LIMIT, key -> {}); } public TransactionalExecutionStore(RecordStore records, String pool) { - this(records, pool, key -> {}); + this(records, DurableJson.text(pool, "pool"), DEFAULT_UNKNOWN_LIMIT, key -> {}); + } + + public TransactionalExecutionStore(RecordStore records, String pool, int unknownLimit) { + this(records, pool, unknownLimit, key -> {}); } public TransactionalExecutionStore( RecordStore records, String pool, Consumer publications) { + this(records, DurableJson.text(pool, "pool"), DEFAULT_UNKNOWN_LIMIT, publications); + } + + /** Freeze the maximum consecutive uncertain provider observations when admitting an execution. */ + public TransactionalExecutionStore( + RecordStore records, String pool, int unknownLimit, Consumer publications) { + if (unknownLimit < 1) throw new IllegalArgumentException("unknownLimit must be positive"); + this.unknownLimit = unknownLimit; this.records = records; - prefix = "execution-pool:" + DurableJson.hash(DurableJson.text(pool, "pool")) + ":"; + prefix = + pool == null + ? "execution:" + : "execution-pool:" + + DurableJson.hash(DurableJson.text(pool, "pool")) + + ":"; this.publications = Objects.requireNonNull(publications); } @@ -78,6 +96,8 @@ public static final class State { public long createdAt; public long publicationPendingAt; public int consecutiveFailures; + public int unknownLimit = DEFAULT_UNKNOWN_LIMIT; + public int unknownObservations; public boolean outputEnabled; public boolean attempted; public boolean cancelled; @@ -121,7 +141,9 @@ private record WorkTimes(long publication, long start, long recovery, long avail private static WorkTimes workTimes(State state) { if (state == null) return new WorkTimes(-1, -1, -1, -1); - boolean settled = state.result.state().terminal() && state.outputSealed; + boolean settled = + state.result.state().terminal() && state.outputSealed + || state.unknownObservations >= state.unknownLimit; boolean recovery = state.attempted || state.cancelled; long readyAt = settled ? -1 : Math.max(state.expiresAt, state.nextAttemptAt); return new WorkTimes( @@ -187,10 +209,11 @@ private static void same(State state, ExecutionRequest request) { throw failure(DurableException.Code.CONFLICT, "Execution identity content changed"); } - private static State create(RecordStore.Transaction tx, ExecutionRequest request) { + private State create(RecordStore.Transaction tx, ExecutionRequest request) { var state = new State(); state.tx = tx; state.createdAt = tx.now(); + state.unknownLimit = unknownLimit; state.request = request; state.digest = DurableJson.hash(request); emit(state, publicResult(state), null); @@ -238,8 +261,10 @@ public ExecutionResult cancel(ExecutionRequest request) { } private static void cancel(State state) { + if (state.cancelled) return; state.cancelled = true; state.nextAttemptAt = 0; + state.unknownObservations = 0; if (!state.attempted && !state.result.state().terminal()) { state.result = new ExecutionResult(ExecutionState.CANCELLED, null, null, null); state.outputSealed = true; @@ -483,9 +508,11 @@ private Optional claim( key, (state, now) -> { if (request != null) same(state, request); + boolean parked = state.unknownObservations >= state.unknownLimit; if (state.result.state().terminal() && state.outputSealed || state.expiresAt > now - || state.nextAttemptAt > now) return Optional.empty(); + || (parked ? request == null : state.nextAttemptAt > now)) + return Optional.empty(); state.owner = owner; state.epoch++; state.expiresAt = now + lease.toMillis(); @@ -582,12 +609,35 @@ public boolean update(Work work, ExecutionResult result) { work.key(), (state, now) -> { fence(state, work, now); + var observation = result; + if (result.state() == ExecutionState.UNKNOWN + && work.cancellationRequested() == state.cancelled) { + if (state.unknownObservations < state.unknownLimit + && ++state.unknownObservations == state.unknownLimit) { + observation = + new ExecutionResult( + ExecutionState.UNKNOWN, + result.handle(), + null, + "Automatic recovery paused after " + + state.unknownLimit + + " UNKNOWN observations; external" + + " reconciliation required"); + System.getLogger(TransactionalExecutionStore.class.getName()) + .log( + System.Logger.Level.WARNING, + "Hands execution {0} parked after {1} UNKNOWN" + + " observations", + state.request.executionId(), + state.unknownLimit); + } + } else state.unknownObservations = 0; if (state.result.state().terminal()) { if (!state.result.equals(result)) throw failure( DurableException.Code.CONFLICT, "Terminal result changed"); - } else if (!state.result.equals(result)) { - state.result = result; + } else if (!state.result.equals(observation)) { + state.result = observation; if (!result.state().terminal() || state.outputSealed) emit(state, publicResult(state), null); } diff --git a/agentscope-durable/durable-worker/src/test/java/io/agentscope/durable/worker/WorkerRuntimeTest.java b/agentscope-durable/durable-worker/src/test/java/io/agentscope/durable/worker/WorkerRuntimeTest.java index 46b511c8a4..9cb4ce3fc0 100644 --- a/agentscope-durable/durable-worker/src/test/java/io/agentscope/durable/worker/WorkerRuntimeTest.java +++ b/agentscope-durable/durable-worker/src/test/java/io/agentscope/durable/worker/WorkerRuntimeTest.java @@ -320,6 +320,47 @@ void capturedOutputRemainsReadableWithoutProviderAndReportsBoundedBacklog() { } } + @Test + void parkedUnknownBudgetIsFrozenAndOnlyExplicitControlReopensIt() throws Exception { + try (var records = JdbcRecordStore.sqlite(directory.resolve("parked.db"))) { + var original = new TransactionalExecutionStore(records, "hands", 1); + original.admit(request); + var replacement = new TransactionalExecutionStore(records, "hands", 10); + var lease = Duration.ofSeconds(5); + var key = replacement.ready(1).get(0); + var work = replacement.claim(key, "worker", lease).orElseThrow(); + replacement.begin(work, false); + replacement.update(work, ExecutionResult.unknown("provider unreachable")); + replacement.defer(work, lease, lease); + assertTrue(original.ready(1).isEmpty()); + assertTrue( + original.query(request).error().contains("external reconciliation required")); + assertTrue(original.claim(key, "background", lease).isEmpty()); + var inspector = original.claim(request, "operator", lease).orElseThrow(); + original.release(inspector, Duration.ZERO); + replacement.cancel(request); + var cancelling = original.claim(key, "worker", lease).orElseThrow(); + original.update(cancelling, ExecutionResult.unknown("cancel unconfirmed")); + original.release(cancelling, Duration.ZERO); + replacement.cancel(request); + assertTrue(original.ready(true, 1).isEmpty()); + } + } + + @Test + void aLateUnknownFromStartCannotExhaustConcurrentCancellationBudget() throws Exception { + try (var records = JdbcRecordStore.sqlite(directory.resolve("cancel-race.db"))) { + var store = new TransactionalExecutionStore(records, "hands", 1); + store.admit(request); + var work = store.claim(request, "original", Duration.ofSeconds(5)).orElseThrow(); + store.begin(work, false); + store.cancel(request); + store.update(work, ExecutionResult.unknown("start lost")); + store.release(work, Duration.ZERO); + assertEquals(List.of(work.key()), store.ready(true, 1)); + } + } + @Test void deferredRecoverySurvivesReplacementAndCancellationBypassesBackoff() throws Exception { try (var records = JdbcRecordStore.sqlite(directory.resolve("backoff.db"))) { @@ -586,31 +627,35 @@ void cancellationBeforeDispatchNeverCallsProvider() { @Test void staleWorkerCannotPublishResult() throws Exception { - var store = - new TransactionalExecutionStore( - JdbcRecordStore.sqlite(directory.resolve("fence.db"))); - store.admit(request); - var key = store.keys(null, 1).get(0); - // A 1s claim lease expired between claim and release on loaded runners (#4219: "Worker - // lease lost" after 2.4s); the staleness under test comes from release(ZERO) plus the - // re-claim below, so the initial lease only needs to outlive setup. - var old = store.claim(key, "old", Duration.ofSeconds(30)).orElseThrow(); - store.begin(old, false); - store.release(old, Duration.ZERO); - var current = store.claim(key, "new", Duration.ofSeconds(30)).orElseThrow(); - assertThrows( - DurableException.class, - () -> - store.update( - old, - new ExecutionResult( - ExecutionState.SUCCEEDED, - null, - DurableJson.value("late"), - null))); - store.update( - current, new ExecutionResult(ExecutionState.UNKNOWN, null, null, "Needs query")); - assertEquals(ExecutionState.UNKNOWN, store.query(request).state()); + var file = directory.resolve("fence.db"); + try (var first = JdbcRecordStore.sqlite(file); + var second = JdbcRecordStore.sqlite(file)) { + var store = new TransactionalExecutionStore(first); + var replacement = new TransactionalExecutionStore(second); + var command = ExecutionMessages.command(ExecutionMessages.Kind.EXECUTE, request); + store.receive(command); + var old = store.claim(request, "old", Duration.ofSeconds(1)).orElseThrow(); + store.begin(old, false); + replacement.receive(command); + assertTrue(replacement.claim(request, "new", Duration.ofSeconds(1)).isEmpty()); + Thread.sleep(1100); + var current = replacement.claim(request, "new", Duration.ofSeconds(5)).orElseThrow(); + assertTrue(replacement.begin(current, false).attempted()); + var confirmed = + new ExecutionResult( + ExecutionState.SUCCEEDED, + request.executionId(), + DurableJson.value("verified"), + null); + replacement.update(current, confirmed); + assertEquals( + DurableException.Code.FENCED, + assertThrows( + DurableException.class, + () -> store.update(old, ExecutionResult.unknown("late return"))) + .code()); + assertEquals(confirmed, store.query(request)); + } } @Test diff --git a/agentscope-durable/protocol/README.md b/agentscope-durable/protocol/README.md index 674abf3982..c3b24d544b 100644 --- a/agentscope-durable/protocol/README.md +++ b/agentscope-durable/protocol/README.md @@ -219,6 +219,7 @@ common envelope; consult `userRequest` and the operation-specific definitions in | `getModelCall / listModelCalls` | Thread/Turn/Run scope plus `modelCallId` or nullable `stepId, cursor, limit`; returns model-call diagnostics | | `control` | `session, threadId, command`; returns a CommandReceipt | | `interactions` | `session, threadId, turnId`; returns pending interactions | +| `previewEligibility` | `session, identities` (up to 32 message/tool keys with attempt and revision). Returns one eligibility flag per identity in request order. | | `snapshot / events` | `session` and optional `filter`; events also takes `cursor, limit` | | `checkpoints` | `session, threadId, after, limit`; lists checkpoint metadata | | `restore` | `session, threadId, position, expectedPosition, requestId`; returns CommitReceipt | @@ -265,6 +266,7 @@ private state and execution authority and must not be exposed as public user RPC | `commit / receipt / recordFailure` | Atomically commit progress, resolve commit receipts, and record recovery failures | | `execution / beginDispatch / acceptResult / acceptExecutionEvent` | Read persisted intent, fence dispatch, and accept execution results/events | | `delegate / delegation / cancelDelegation` | Atomically admit child work, retain its mapping, and persist cancellation | +| `previewEligibility` | Look up the projected version and completion status of a bounded batch of preview identities. | | `snapshot / events / pruneEvents` | Read public projections and replay, or prune retained events | | `checkpoints / checkpoint / checkpointJournal / checkpointResources / restore` | Inspect and restore retained recovery boundaries | | `resource` | Resolve recovery resources under fenced access | @@ -460,6 +462,11 @@ leave the outcome unconfirmed. `NOT_FOUND` permits another start only under the frozen idempotent-start guarantee. Pending cancellation remains `PENDING` or `RUNNING` until the provider confirms a terminal outcome. +Once a provider has issued a handle, recovery preserves it through missing or +uncertain lookups and only queries or cancels that admitted operation. Without a +handle, repeated admission still requires an idempotent provider using the +original execution ID. Provider-side idempotency must span Hands processes. + ### Verified UNKNOWN reconciliation `executionReconciliation` carries a stable request ID, a terminal ExecutionResult, @@ -467,6 +474,13 @@ and an evidence reference. This is a host operations contract. The host verifies the external fact and authorizes the operator, claims the original execution with `ExecutionStore.claim(request, owner, lease)`, then calls `reconcile(work, command)`. +The transactional Hands ledger stops automatic starts and queries after its +admission-time limit of consecutive UNKNOWN observations (default eight). +It retains the uncertain result and pending result publications. An exact +operator claim still observes the active lease fence. The first cancellation +opens a separate observation budget; redelivering that cancellation cannot +reset it again. + Only `UNKNOWN` can be settled through this path. Audit evidence, outcome, and outbox commit together; missing output receives an explicit terminal gap before the result. Identical request ID/content is idempotent; changed content conflicts. diff --git a/agentscope-durable/protocol/schema.json b/agentscope-durable/protocol/schema.json index 2b4b1dbe0c..5b00f43dd0 100644 --- a/agentscope-durable/protocol/schema.json +++ b/agentscope-durable/protocol/schema.json @@ -3952,6 +3952,16 @@ }, "thread": { "$ref": "#/$defs/thread" + }, + "policy": { + "anyOf": [ + { + "type": "null" + }, + { + "$ref": "#/$defs/recoveryPolicy" + } + ] } } } @@ -4404,6 +4414,9 @@ "minLength": 1, "maxLength": 256 }, + "lease": { + "$ref": "#/$defs/lease" + }, "result": { "$ref": "#/$defs/executionResult" }, diff --git a/agentscope-durable/scripts/docker-regression/AckGate.java b/agentscope-durable/scripts/docker-regression/AckGate.java new file mode 100644 index 0000000000..bf978d503e --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/AckGate.java @@ -0,0 +1,48 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.extensions.durable.rocketmq; + +import com.fasterxml.jackson.databind.JsonNode; + +import org.apache.rocketmq.client.apis.message.MessageView; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** Pause after durable admission and before the Lite consumer reports success to the SDK. */ +final class AckGate { + static void beforeSuccess(JsonNode envelope, MessageView message) { + String kind; + JsonNode request; + if (envelope.has("batchId")) { + kind = "command"; + request = envelope.path("requests").path(0); + } else if ("SUCCEEDED".equals(envelope.path("result").path("state").asText())) { + kind = "result"; + request = envelope.path("request"); + } else return; + String delivery = String.format("%s %s %d %s", kind, message.getMessageId(), + message.getDeliveryAttempt(), request.path("turnId").asText()); + System.out.println("BEFORE " + delivery); + try { + while (Files.exists(Path.of("/tmp/hold-" + kind))) Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted before delivery completed", e); + } + System.out.println("SUCCESS " + delivery); + } +} diff --git a/agentscope-durable/scripts/docker-regression/CheckpointGate.java b/agentscope-durable/scripts/docker-regression/CheckpointGate.java new file mode 100644 index 0000000000..490569c647 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/CheckpointGate.java @@ -0,0 +1,68 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.extensions.durable.jdbc; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.concurrent.CountDownLatch; + +/** Injected only in the test JVM. Pause at an uncommitted checkpoint or after its commit. */ +final class CheckpointGate { + private static final String PHASE = System.getenv("CHECKPOINT_GATE"); + private static final ThreadLocal pending = new ThreadLocal<>(); + + static void begin() { + pending.remove(); + } + + static void written(String part, JsonNode value) { + if (PHASE == null || value == null) return; + if ("failed-ack".equals(PHASE) + && part.startsWith("event:") + && "turn.failed".equals(value.path("type").asText())) pending.set("failed-ack"); + if (!part.isEmpty() || "failed-ack".equals(pending.get())) return; + var state = value.path("execution"); + if (state.isMissingNode()) return; + if (state.path("replayAfter").asLong() > Long.parseLong(System.getenv("BASE_CURSOR"))) { + pending.set("cursor"); + return; + } + if (state.path("checkpointPosition").asLong() + > Long.parseLong(System.getenv("BASE_POSITION"))) pending.set("snapshot"); + } + + static void flushed() { + String phase = pending.get(); + if ("snapshot".equals(phase) || "cursor".equals(phase)) stopAt(phase); + } + + static void committed() { + String phase = pending.get(); + pending.remove(); + if ("cursor".equals(phase)) stopAt("ack"); + if ("failed-ack".equals(phase)) stopAt(phase); + } + + private static void stopAt(String phase) { + if (!phase.equals(PHASE)) return; + System.out.println("CHECKPOINT_GATE " + phase); + try { + new CountDownLatch(1).await(); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java new file mode 100644 index 0000000000..daebc597a8 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java @@ -0,0 +1,80 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.durable.examples.brainhands.echo; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import org.apache.rocketmq.client.apis.ClientConfiguration; +import org.apache.rocketmq.client.apis.ClientServiceProvider; +import org.apache.rocketmq.client.apis.consumer.FilterExpression; + +/** Separate JVMs for the producer and each member of a SimpleConsumer group. */ +public final class ConsumerPairProbe { + public static void main(String[] args) throws Exception { + var provider = ClientServiceProvider.loadService(); + var config = ClientConfiguration.newBuilder() + .setEndpoints("127.0.0.1:8081") + .enableSsl(false) + .build(); + String topic = "paired-commands"; + if ("send".equals(args[0])) { + try (var producer = provider.newProducerBuilder() + .setClientConfiguration(config) + .setTopics(topic) + .build()) { + int count = Integer.parseInt(args[2]); + for (int i = Integer.parseInt(args[3]); i < count; i++) { + String key = args[1] + i; + var message = provider.newMessageBuilder() + .setTopic(topic) + .setKeys(key) + .setBody(key.getBytes(StandardCharsets.UTF_8)) + .build(); + producer.send(message); + System.out.println("SENT " + i); + } + } + return; + } + try (var consumer = provider.newSimpleConsumerBuilder() + .setClientConfiguration(config) + .setConsumerGroup("paired-hands") + .setAwaitDuration(Duration.ofSeconds(10)) + .setSubscriptionExpressions(Map.of(topic, FilterExpression.SUB_ALL)) + .build()) { + System.out.println("READY"); + while (true) { + try { + for (var message : consumer.receive(16, Duration.ofSeconds(30))) { + String key = message.getKeys().iterator().next(); + System.out.println("RECEIVE " + key + " " + message.getDeliveryAttempt()); + if ("fault0".equals(key) && message.getDeliveryAttempt() == 1) { + System.out.println("BEFORE_ACK"); + new CountDownLatch(1).await(); + } + consumer.ack(message); + System.out.println("ACK " + key); + } + } catch (Exception failure) { + System.out.println("ERROR " + failure); + Thread.sleep(100); + } + } + } + } +} diff --git a/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java new file mode 100644 index 0000000000..826b5d6ae2 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java @@ -0,0 +1,264 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.durable.examples.brainhands.echo; + +import io.agentscope.core.ReActAgent; +import io.agentscope.core.message.*; +import io.agentscope.core.model.*; +import io.agentscope.core.permission.*; +import io.agentscope.core.tool.*; +import io.agentscope.durable.*; +import io.agentscope.durable.DurableTypes.*; +import io.agentscope.durable.agentscope.*; +import io.agentscope.extensions.durable.jdbc.PostgresBackend; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.*; + +/** Two real Brain processes. PostgreSQL counts starts independently of the native journal. */ +public class NativeReplayProbe { + static Model model(String scenario) { + return new Model() { + public String getModelName() { + return "native-recovery-fixture"; + } + + public Flux stream( + List messages, List tools, GenerateOptions options) { + boolean check = + tools != null + && tools.stream() + .anyMatch(t -> t.getName().equals("verify_outcome")); + if (!check) System.out.println("REASONING_REQUEST"); + boolean applied = + messages.stream().anyMatch(m -> m.hasContentBlocks(ToolResultBlock.class)); + ContentBlock output; + if (check) { + System.out.println("MODEL_CHECK"); + output = + ToolUseBlock.builder() + .id("lookup") + .name("verify_outcome") + .input( + Map.of( + "hint", + scenario.equals("unknown") + ? "missing" + : "receipt-7")) + .build(); + } else if (applied) { + if (scenario.endsWith("-direct")) + throw new AssertionError("Unexpected model request after direct tool"); + output = TextBlock.builder().text("verified answer").build(); + } else { + output = + ToolUseBlock.builder() + .id("original-call") + .name("operation") + .input(Map.of("receipt", "receipt-7")) + .build(); + } + return Flux.just(ChatResponse.builder().content(List.of(output)).build()); + } + }; + } + + private static boolean waitingForEvidence(TurnView turn) { + return turn.status() == TurnStatus.WAITING && turn.waiting() != null + && WaitCondition.NATIVE_TOOL_RECONCILIATION.equals(turn.waiting().key()); + } + + public static void main(String[] args) throws Exception { + String scenario = args[0]; + boolean old = args[1].equals("first"); + var key = new SessionKey("native-regression", scenario); + var model = model(scenario); + var adapter = + AgentScopeAdapter.forReAct( + binding -> { + var toolkit = new Toolkit(); + toolkit.registerAgentTool( + new ToolBase( + ToolBase.builder() + .name("operation") + .returnDirect( + old && scenario.endsWith("-direct")) + .description("Instrumented local operation") + .inputSchema( + Map.of( + "type", + "object", + "properties", + Map.of( + "receipt", + Map.of( + "type", + "string"))))) { + public Mono callAsync( + ToolCallParam param) { + return Mono.fromCallable( + () -> { + try (var c = + Probe.database() + .getConnection(); + var insert = + c.prepareStatement( + "insert into" + + " native_starts" + + " values" + + " (?,?,?,?)")) { + insert.setString(1, scenario); + insert.setString( + 2, + binding.context().getTurnId()); + insert.setString( + 3, + param.getToolUseBlock() + .getId()); + insert.setString( + 4, + (String) + param.getInput() + .get( + "receipt")); + insert.executeUpdate(); + } + if (old && !scenario.equals("stored-direct")) + Thread.sleep(Long.MAX_VALUE); + return ToolResultBlock.text("receipt-7"); + }); + } + }); + return ReActAgent.builder() + .name("native") + .model(model) + .toolkit(toolkit) + .permissionContext( + PermissionContextState.builder() + .mode(PermissionMode.BYPASS) + .build()); + }, + Map.of()); + boolean safe = scenario.startsWith("safe"); + // Intentionally reverse the registration on takeover. The dispatch fact must win. + var policies = + Map.of( + "operation", + old == safe + ? NativeToolRecovery.Replay.SAFE + : NativeToolRecovery.Replay.NEVER); + var check = + new NativeToolRecovery.ModelCheck( + model, + (dispatch, hint) -> { + try (var c = Probe.database().getConnection(); + var q = + c.prepareStatement( + "select receipt from native_starts where" + + " scenario=? and turn_id=? and call_id=?" + + " and receipt=?")) { + q.setString(1, dispatch.thread().session().sessionId()); + q.setString(2, dispatch.turnId()); + q.setString(3, dispatch.call().getId()); + q.setString(4, hint); + try (var row = q.executeQuery()) { + if (!row.next()) return Optional.empty(); + return Optional.of( + new NativeToolRecovery.Evidence( + "postgres:receipt/" + row.getString(1), + ToolResultBlock.success(row.getString(1)) + .withIdAndName( + dispatch.call().getId(), + "operation"))); + } + } catch (java.sql.SQLException e) { + throw new IllegalStateException(e); + } + }); + try (var backend = PostgresBackend.builder().dataSource(Probe.database()).build(); + var runtime = + DurableRuntime.builder() + .backend(backend) + .harness( + "native", + "1", + adapter.withNativeToolRecovery( + policies, args[1].equals("operator") ? null : check)) + .leaseDuration(Duration.ofSeconds(4)) + .pollInterval(Duration.ofMillis(100)) + .build()) { + var turn = runtime.createSession(key, "native").submit("one", "perform operation"); + if (args[1].equals("operator")) { + var thread = new ThreadKey(key, "main"); + runtime.start(); + long deadline = System.nanoTime() + Duration.ofSeconds(60).toNanos(); + while (!waitingForEvidence(turn.status()) && System.nanoTime() < deadline) + Thread.sleep(100); + if (!waitingForEvidence(turn.status()) || !runtime.drain(Duration.ofSeconds(10))) + throw new AssertionError("Expected a parked native call: " + turn.status()); + try (var c = Probe.database().getConnection(); + var q = + c.prepareStatement( + "select call_id, receipt from native_starts where" + + " scenario=? and turn_id=?")) { + q.setString(1, scenario); + q.setString(2, turn.turnId()); + try (var row = q.executeQuery()) { + if (!row.next()) throw new AssertionError("Missing independent receipt"); + var id = row.getString(1); + new NativeToolReconciliation( + "repair", + "postgres:" + id, + List.of(ToolResultBlock.success(row.getString(2)) + .withIdAndName(id, "operation"))) + .submit(backend, thread, turn.turnId()); + } + } + if (scenario.startsWith("cancel")) + backend.cancel(thread, turn.turnId(), "cancel-after-repair"); + System.out.println("REPAIRED"); + System.out.flush(); + Runtime.getRuntime().halt(0); + } + runtime.start(); + long end = System.nanoTime() + Duration.ofSeconds(80).toNanos(); + while (System.nanoTime() < end) { + var v = turn.status(); + if (!old + && scenario.equals("unknown") + && waitingForEvidence(v)) { + System.out.println("PARKED " + turn.turnId()); + return; + } + if (v.status().terminal()) { + if (scenario.startsWith("cancel") && v.status() == TurnStatus.CANCELLED) { + System.out.println("CANCELLED " + turn.turnId()); + return; + } + if (v.status() != TurnStatus.SUCCEEDED || scenario.equals("unknown")) + throw new AssertionError(v); + System.out.println("SUCCEEDED " + turn.turnId()); + return; + } + Thread.sleep(100); + } + throw new AssertionError(turn.status()); + } + } +} diff --git a/agentscope-durable/scripts/docker-regression/Probe.java b/agentscope-durable/scripts/docker-regression/Probe.java new file mode 100644 index 0000000000..896f43efbe --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/Probe.java @@ -0,0 +1,243 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.durable.examples.brainhands.echo; + +import com.sun.net.httpserver.HttpServer; + +import io.agentscope.core.model.GenerateOptions; +import io.agentscope.durable.*; +import io.agentscope.durable.DurableTypes.*; +import io.agentscope.extensions.durable.jdbc.*; +import io.agentscope.extensions.durable.rocketmq.*; + +import org.apache.rocketmq.client.apis.ClientConfiguration; +import org.postgresql.ds.PGSimpleDataSource; + +import java.net.*; +import java.net.http.*; +import java.nio.file.*; +import java.time.Duration; +import java.util.*; +import java.util.concurrent.Executors; + +/** Independent processes sharing only PostgreSQL, RocketMQ and the counting model endpoint. */ +public class Probe { + static final SessionKey KEY = new SessionKey("regression", "session"); + + static PGSimpleDataSource database() { + var source = new PGSimpleDataSource(); + source.setURL( + "jdbc:postgresql://pg/postgres?user=postgres&connectTimeout=4&socketTimeout=10"); + return source; + } + + static class Tool implements Executor { + public Capabilities capabilities() { + boolean recoverable = System.getenv("OPAQUE") == null; + return new Capabilities(recoverable, recoverable, false); + } + + public ExecutionResult startExecution(ExecutionRequest request) { + try (var conn = database().getConnection()) { + conn.setAutoCommit(false); + for (String sql : + List.of( + "insert into starts values (?)", + "insert into effects values (?) on conflict do nothing")) { + try (var insert = conn.prepareStatement(sql)) { + insert.setString(1, request.executionId()); + insert.executeUpdate(); + } + } + conn.commit(); + System.out.println("EFFECT " + request.turnId()); + while (Files.exists(Path.of("/tmp/hold-effect"))) Thread.sleep(50); + return query(request, null); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public ExecutionResult query(ExecutionRequest request, String handle) { + try (var conn = database().getConnection(); + var select = conn.prepareStatement("select 1 from effects where id=?")) { + select.setString(1, request.executionId()); + boolean committed = select.executeQuery().next(); + return new ExecutionResult( + committed ? ExecutionState.SUCCEEDED : ExecutionState.NOT_FOUND, + committed ? request.executionId() : null, + committed ? DurableJson.value("echo: " + request.call().arguments()) : null, + null); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public ExecutionResult cancel(ExecutionRequest request, String handle) { + return query(request, handle); + } + } + + public static String answer(String turn, GenerateOptions options) { + System.out.println("MODEL_REQUEST " + turn); + try { + var req = + HttpRequest.newBuilder(URI.create("http://model:8080/" + turn)) + .POST(HttpRequest.BodyPublishers.noBody()); + options.getAdditionalHeaders().forEach(req::header); + var response = + HttpClient.newHttpClient() + .send(req.build(), HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) throw new IllegalStateException("model failed"); + return response.body(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + static void model() throws Exception { + var server = HttpServer.create(new InetSocketAddress(8080), 0); + var statusByKey = new java.util.concurrent.ConcurrentHashMap(); + server.createContext( + "/", + exchange -> { + try (exchange) { + var turn = exchange.getRequestURI().getPath().substring(1); + var key = exchange.getRequestHeaders().getFirst("Idempotency-Key"); + if (key == null) { + exchange.sendResponseHeaders(400, -1); + return; + } + int status = statusByKey.computeIfAbsent(key, ignored -> { + System.out.println("INFERENCE " + turn); + return Files.exists(Path.of("/tmp/fail")) ? 500 : 200; + }); + System.out.println("RECEIVED " + turn); + while (Files.exists(Path.of("/tmp/block"))) { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + return; + } + } + if (status != 200) { + exchange.sendResponseHeaders(status, -1); + return; + } + var bytes = + EchoBrainExample.FINAL_ANSWER.getBytes( + java.nio.charset.StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + } + }); + server.setExecutor(Executors.newCachedThreadPool()); + server.start(); + } + + public static void main(String[] args) throws Exception { + if (args[0].equals("model")) { + model(); + return; + } + if (args[0].equals("init")) { + PostgresBackend.initializeSchema(database()); + return; + } + if (args[0].equals("verify-effect")) { + var request = DurableJson.convert(DurableJson.parse(args[1]), ExecutionRequest.class); + var verified = new Tool().query(request, null); + if (verified.state() != ExecutionState.SUCCEEDED) + throw new AssertionError("missing external evidence"); + var command = + new ExecutionReconciliation( + "verify-" + request.executionId(), + verified, + "postgres:effects/" + request.executionId()); + try (var records = + new JdbcRecordStore( + () -> database().getConnection(), + JdbcRecordStore.Dialect.POSTGRESQL, + false)) { + var ledger = + new io.agentscope.durable.worker.TransactionalExecutionStore( + records, "hands"); + long deadline = + System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(60); + while (System.nanoTime() < deadline) { + var lease = ledger.claim(request, "verifier", Duration.ofSeconds(5)); + if (lease.isPresent()) { + ledger.reconcile(lease.get(), command); + ledger.reconcile(lease.get(), command); + if (!ledger.reconciliation(request, command.requestId()) + .orElseThrow() + .equals(command)) + throw new AssertionError("missing reconciliation receipt"); + return; + } + Thread.sleep(100); + } + throw new AssertionError("verification lease deadline"); + } + } + var mq = ClientConfiguration.newBuilder().setEndpoints("proxy:8081").build(); + if (args[0].equals("hands")) { + try (var records = + new JdbcRecordStore( + () -> database().getConnection(), + JdbcRecordStore.Dialect.POSTGRESQL, + false); + var worker = + RocketMqWorker.builder() + .namespace("regression") + .executor("hands", new Tool()) + .recordStore(records) + .clientConfiguration(mq) + .authorize(command -> {}) + .leaseDuration(Duration.ofSeconds(5)) + .build()) { + worker.start(); + System.out.println("READY"); + Thread.sleep(Long.MAX_VALUE); + } + return; + } + try (var backend = PostgresBackend.builder().dataSource(database()).build()) { + if (args[0].equals("brain")) { + var executor = + RocketMqRemoteExecutor.builder() + .namespace("regression") + .clientConfiguration(mq) + .build(); + try (var runtime = EchoBrainExample.runtime(backend, executor)) { + runtime.createSession(KEY, EchoBrainExample.HARNESS); + runtime.start(); + System.out.println("READY"); + Thread.sleep(Long.MAX_VALUE); + } + } else + try (var runtime = DurableRuntime.builder().backend(backend).build()) { + var session = runtime.getSession(KEY); + if (args[0].equals("prune")) + backend.pruneEvents(KEY, session.snapshot().cursor()); + else if (args[0].equals("cancel")) + session.getTurn(args[1]).cancel("cancel-" + args[1]); + else + System.out.println("TURN " + session.submit(args[1], "Call echo").turnId()); + } + } + } +} diff --git a/agentscope-durable/scripts/docker-regression/compare_consumers.py b/agentscope-durable/scripts/docker-regression/compare_consumers.py new file mode 100644 index 0000000000..bebd55cee9 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/compare_consumers.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Compare paired SimpleConsumers on separate RocketMQ NameServer, Broker and Proxy JVMs.""" + +from collections import Counter +from pathlib import Path +import tempfile +import time + +import run as lab + + +def exercise(folder, memory): + ns, broker, proxy = [memory + "-" + role for role in ("ns", "broker", "proxy")] + lab.start(ns, lab.MQ, ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx128m"], "sh", "mqnamesrv") + lab.start( + broker, + lab.MQ, + ["-e", f"JAVA_OPT_EXT=-Xms128m -Xmx256m -XX:MaxDirectMemorySize={memory}"], + "sh", + "-c", + f"printf 'brokerName=paired\nbrokerIP1={broker}\nautoCreateTopicEnable=true\nautoCreateSubscriptionGroup=true\n' >/tmp/b.conf && exec sh mqbroker -n {ns}:9876 -c /tmp/b.conf", + ) + + def admin(*options): + return lab.run( + "docker", + "exec", + lab.name(broker), + "sh", + "mqadmin", + *options, + "-n", + ns + ":9876", + check=False, + ) + + lab.wait("broker registration", lambda: "paired" in admin("clusterList").stdout) + flags = lab.docker( + "exec", lab.name(broker), "sh", "-c", + """pid=$(jps -l | awk '/BrokerStartup$/ {print $1}'); jcmd "$pid" VM.flags""", + ).split() + expected = {"256m": 256 << 20, "1g": 1 << 30}[memory] + if f"-XX:MaxDirectMemorySize={expected}" not in flags: + raise RuntimeError(f"Broker JVM did not apply the {memory} direct-memory limit") + for args in ( + ( + "updateTopic", + "-c", + "DefaultCluster", + "-t", + "paired-commands", + "-r", + "8", + "-w", + "8", + ), + ("updateSubGroup", "-c", "DefaultCluster", "-g", "paired-hands"), + ): + lab.wait(args[0], lambda: admin(*args).returncode == 0) + config = ( + '{"namesrvAddr":"' + + ns + + ':9876","localServeAddr":"127.0.0.1","grpcServerPort":8081}' + ) + lab.start( + proxy, + lab.MQ, + ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx256m -XX:MaxDirectMemorySize=1g"], + "sh", + "-c", + f"echo '{config}' >/tmp/proxy.json && exec sh mqproxy -n {ns}:9876 -pc /tmp/proxy.json -pm cluster", + ) + lab.wait("proxy startup", lambda: "startup successfully" in lab.logs(proxy)) + + clients = [memory + "-a", memory + "-b"] + options = [ + "--network", + "container:" + lab.name(proxy), + "-v", + f"{folder}:/lab:ro", + "-w", + "/lab", + ] + java = [ + lab.JRE, + "java", + "-Xmx256m", + "-cp", + lab.CP, + lab.PACKAGE + "ConsumerPairProbe", + ] + for client in clients: + lab.docker("run", "-d", "--name", lab.name(client), *options, *java, "receive") + lab.containers.append(lab.name(client)) + lab.wait( + "two active consumers", lambda: all("READY" in lab.logs(c) for c in clients) + ) + + def send(prefix, count): + next_index = 0 + + def publish(): + nonlocal next_index + result = lab.run( + "docker", + "run", + "--rm", + *options, + *java, + "send", + prefix, + str(count), + str(next_index), + check=False, + ) + if result.returncode == 0: + return True + if "response-code=40402" in result.stdout: + # NO_TOPIC_ROUTE rejects the current send. Resume after confirmed receipts. + for line in result.stdout.splitlines(): + if line.startswith("SENT "): + if int(line[5:]) != next_index: + raise RuntimeError("Unexpected producer receipt sequence") + next_index += 1 + print(memory, "producer waiting for topic route", flush=True) + return False + raise RuntimeError(result.stdout[-3500:]) + + lab.wait("producer route and publication", publish, 150) + + def acks(): + return Counter( + line[4:] + for c in clients + for line in lab.logs(c).splitlines() + if line.startswith("ACK ") + ) + + def deadlines(): + return [ + sum( + line.startswith("ERROR ") and "DEADLINE_EXCEEDED" in line + for line in lab.logs(c).splitlines() + ) + for c in clients + ] + + time.sleep(45) + send("healthy", 16) + lab.wait("healthy delivery", lambda: len(acks()) == 16) + normal = deadlines() + print( + memory, + "normal deadlines", + normal, + "POP direct-memory error lines", + lab.pop_memory_errors(broker), + flush=True, + ) + + lab.docker("pause", lab.name(proxy)) + try: + lab.wait( + "three consecutive receive deadlines on both clients", + lambda: all(a - b >= 3 for a, b in zip(deadlines(), normal)), + 120, + ) + interrupted = deadlines() + print(memory, "observed paused proxy", interrupted, flush=True) + finally: + lab.docker("unpause", lab.name(proxy)) + send("recovered", 16) + lab.wait("delivery after proxy recovery", lambda: len(acks()) == 32) + send("fault", 1) + old = lab.wait( + "before ACK", + lambda: next((c for c in clients if "BEFORE_ACK" in lab.logs(c)), None), + ) + lab.docker("kill", lab.name(old)) + new = next(c for c in clients if c != old) + lab.wait( + "redelivery to surviving process", lambda: "ACK fault0" in lab.logs(new), 180 + ) + if "RECEIVE fault0 2" not in lab.logs(new) or acks() != Counter( + ["fault0"] + [f"{p}{i}" for p in ("healthy", "recovered") for i in range(16)] + ): + raise RuntimeError("Unexpected delivery counts") + errors = lab.pop_memory_errors(broker) + if memory == "1g" and errors: + raise RuntimeError("Broker POP exhausted direct memory in the 1g control") + print( + memory, + "POP direct-memory error lines", + errors, + "paused proxy deadlines", + [a - b for a, b in zip(interrupted, normal)], + "acknowledged=33 redelivery=1,2", + flush=True, + ) + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory(prefix="durable-consumers-") as scratch: + folder = Path(scratch).resolve() + lab.compile_probes(folder) + lab.docker("network", "create", lab.PROJECT) + try: + for memory in ("256m", "1g"): + try: + exercise(folder, memory) + except Exception: + for role in ("broker", "proxy", "a", "b"): + container = lab.name(memory + "-" + role) + print( + container, + lab.run( + "docker", + "inspect", + "-f", + "{{json .State}}", + container, + check=False, + ).stdout, + lab.run( + "docker", "logs", "--tail", "12", container, check=False + ).stdout, + flush=True, + ) + if role == "broker": + print( + lab.run( + "docker", + "exec", + container, + "sh", + "-c", + "tail -30 ~/logs/rocketmqlogs/store.log ~/logs/rocketmqlogs/broker.log", + check=False, + ).stdout, + flush=True, + ) + raise + finally: + if lab.containers: + lab.run("docker", "rm", "-f", "-v", *reversed(lab.containers)) + lab.containers.clear() + finally: + lab.docker("network", "rm", lab.PROJECT) diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py new file mode 100755 index 0000000000..3b608dfda0 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -0,0 +1,691 @@ +#!/usr/bin/env python3 +"""Run real ACK redelivery, model takeover and native tool recovery on an isolated Docker network.""" + +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time +import uuid +import zipfile +import xml.etree.ElementTree as ET + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +PROJECT = "durable-" + uuid.uuid4().hex[:10] +MQ_NETWORK = PROJECT + "-mq" +MQ = os.getenv("ROCKETMQ_IMAGE", "apache/rocketmq:5.5.0") +JRE = "eclipse-temurin:21-jre" +CP = "classes:pg.jar:BOOT-INF/classes:BOOT-INF/lib/*" +PACKAGE = "io.agentscope.durable.examples.brainhands.echo." +containers = [] + + +def run(*args, check=True): + result = subprocess.run( + args, + cwd=ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + ) + if check and result.returncode: + raise RuntimeError(f"{args}: {result.stdout[-4000:]}") + return result + + +def docker(*args): + return run("docker", *args).stdout.strip() + + +def wait(description, condition, seconds=150): + end = time.monotonic() + seconds + while time.monotonic() < end: + value = condition() + if value: + return value + time.sleep(0.5) + raise TimeoutError(description) + + +def name(service): + return PROJECT + "-" + service + + +def start(service, image, options, *command, network=PROJECT): + container = name(service) + docker( + "run", + "-d", + "--name", + container, + "--network", + f"name={network},alias={service}", + *options, + image, + *command, + ) + containers.append(container) + + +def logs(service): + return docker("logs", name(service)) + + +def pop_memory_errors(service): + count = docker( + "exec", + name(service), + "sh", + "-c", + """awk '/OutOfDirectMemoryError/{n++} END{print n+0}' "$HOME/logs/rocketmqlogs/pop.log" """, + ) + return int(count) + + +def sql(query): + return docker( + "exec", + name("pg"), + "psql", + "-v", + "ON_ERROR_STOP=1", + "-U", + "postgres", + "-Atc", + query, + ) + + +def instrument(source, before, after, folder): + text = source.read_text() + if text.count(before) != 1: + raise RuntimeError("Fault injection site changed: " + str(source)) + dest = folder / source.name + dest.write_text(text.replace(before, after)) + return dest + + +def copy_driver(folder): + # The example marks the driver optional. Resolve only this external artifact so the + # test also works with an empty local Maven repo and no installed AgentScope jars. + bom = ROOT / "agentscope-dependencies-bom/pom.xml" + version = ET.parse(bom).findtext("{*}properties/{*}postgresql.version") + if not version: + raise RuntimeError("Missing managed PostgreSQL driver version") + subprocess.run( + [ + "mvn", + "-B", + "-ntp", + "-f", + str(bom), + "dependency:copy", + "-Dartifact=org.postgresql:postgresql:" + version, + "-DoutputDirectory=" + str(folder), + ], + cwd=ROOT, + check=True, + ) + (folder / ("postgresql-" + version + ".jar")).rename(folder / "pg.jar") + + +def compile_probes(folder): + args = [ + "mvn", + "-B", + "-ntp", + "-DskipTests", + "-Djacoco.skip=true", + "-Dmaven.javadoc.skip=true", + ] + subprocess.run( + [*args, "-pl", ":agentscope-durable-example-echo-tool", "-am", "package"], + check=True, + cwd=ROOT, + ) + copy_driver(folder) + example = ROOT / "agentscope-examples/durable/brain-hands/echo-tool" + with zipfile.ZipFile(next((example / "target").glob("*-brain.jar"))) as jar: + for path in jar.namelist(): + if path.startswith("BOOT-INF/"): + jar.extract(path, folder) + loop = next((ROOT / "agentscope-extensions").rglob("RocketMqLoop.java")) + loop = instrument( + loop, + "receiver.accept(payload(message), message);", + "var envelope = payload(message);\n" + " receiver.accept(envelope, message);\n" + " AckGate.beforeSuccess(envelope, message);", + folder, + ) + model = instrument( + next(example.rglob("EchoBrainExample.java")), + ".text(FINAL_ANSWER)", + ".text(Probe.answer(turnId, options))", + folder, + ) + jdbc_store = next((ROOT / "agentscope-extensions").rglob("JdbcRecordStore.java")) + jdbc_store = instrument( + jdbc_store, + 'public void put(String part, JsonNode value) {', + 'public void put(String part, JsonNode value) {\n CheckpointGate.written(part, value);', + folder, + ) + jdbc_store = instrument( + jdbc_store, + " var transaction = new Scopes(connection, writable, timing);", + " CheckpointGate.begin();\n" + " var transaction = new Scopes(connection, writable, timing);", + folder, + ) + jdbc_store = instrument( + jdbc_store, + " if (timing == null) connection.commit();", + " CheckpointGate.flushed();\n if (timing == null) connection.commit();", + folder, + ) + instrument( + jdbc_store, + " return result;\n } catch (SQLException | RuntimeException | Error error)", + " CheckpointGate.committed();\n return result;\n } catch (SQLException | RuntimeException | Error error)", + folder, + ) + action_observations = instrument( + next((ROOT / "agentscope-core").rglob("ActionObservations.java")), + "return recorded;", + "return result == null || !\"1\".equals(System.getenv(\"HOLD_NATIVE_RESULT\"))" + "\n ? recorded : recorded.doOnSuccess(ignored -> {" + "\n System.out.println(\"NATIVE_RESULT_COMMITTED\");" + "\n new java.util.concurrent.Semaphore(0).acquireUninterruptibly();" + "\n });", + folder, + ) + (folder / "classes").mkdir() + subprocess.run( + [ + "javac", + "--release", + "17", + "-cp", + CP, + "-d", + "classes", + *HERE.glob("*.java"), + loop, + model, + jdbc_store, + action_observations, + ], + cwd=folder, + check=True, + ) + + +def exercise(folder): + mount = ["-v", f"{folder}:/lab:ro", "-w", "/lab"] + + def java(service, role, extra_options=()): + broker_link = ["--network", MQ_NETWORK] if role != "model" else [] + start( + service, + JRE, + [*mount, *broker_link, *extra_options], + "java", + "-Xmx256m", + "-cp", + CP, + PACKAGE + "Probe", + role, + ) + if role != "model": + + def ready(): + if "READY" in logs(service): + return True + if ( + docker("inspect", "-f", "{{.State.Running}}", name(service)) + != "true" + ): + raise RuntimeError(service + " exited before readiness") + return False + + wait(service + " ready", ready) + + def client(cls, *args, code=0): + result = run( + "docker", + "exec", + name("client"), + "java", + "-Xmx256m", + "-cp", + CP, + PACKAGE + cls, + *args, + check=False, + ) + if result.returncode != code: + raise RuntimeError(result.stdout[-4000:]) + return result.stdout + + def submit(label): + return re.search(r"TURN (turn_[\w-]+)", client("Probe", "submit", label))[1] + + def counts(turn): + condition = f"payload::jsonb->>'turnId'='{turn}'" + events = f"from durable_parts where part_key like 'event:%' and {condition}" + return sql( + "select count(*) filter(where payload::jsonb->>'type'='tool.result.applied')," + "count(*) filter(where payload::jsonb#>>'{data,text}'='Hands result applied' and payload::jsonb->>'type'='message.completed')," + "count(*) filter(where payload::jsonb->>'type'='turn.succeeded') " + events + ) + + def done(turn): + wait("applied/final/terminal once " + turn, lambda: counts(turn) == "1|1|1") + key = sql( + "select payload::jsonb#>>'{value,request,executionId}' from durable_parts " + "where part_key like 'turn-data:%:tool:%' and payload::jsonb#>>'{value,request,turnId}'='" + + turn + + "'" + ) + actual = sql( + f"select count(*),(select count(*) from effects where id='{key}') from starts where id='{key}'" + ) + if actual != "1|1": + raise AssertionError((turn, actual)) + print(turn, "starts/effects/applied/answers/success=1/1/1/1/1", flush=True) + + def gate(service, action, file): + docker("exec", name(service), action, "/tmp/" + file) + + def redeliver(kind, role): + old, new = role + "-a", role + "-b" + gate(old, "touch", "hold-" + kind) + turn = submit(kind) + pattern = rf"{kind} (\S+) (\d+) {turn}" + first = wait( + "pre-ACK " + kind, lambda: re.search("BEFORE " + pattern, logs(old)) + ) + if kind == "result": + received = sql( + "select payload::jsonb#>>'{result,state}',payload::jsonb->>'receivedSequence'," + "payload::jsonb->>'deliveredSequence' from durable_parts where part_key like 'queued:v5:%:state:%' " + "and payload::jsonb#>>'{request,turnId}'='" + turn + "'" + ).split("|") + assert ( + len(received) == 3 + and received[0] == "SUCCEEDED" + and received[1] == received[2] + ), received + # Drop the broker link without interrupting database writes or the model request. + docker("network", "disconnect", MQ_NETWORK, name(old)) + java(new, role) + + def retried(): + return next( + ( + m + for m in re.finditer("SUCCESS " + pattern, logs(new)) + if m[1] == first[1] and int(m[2]) > int(first[2]) + ), + None, + ) + + second = wait("same broker message redelivered", retried, 420) + docker("network", "connect", MQ_NETWORK, name(old)) + gate(old, "rm", "hold-" + kind) + done(turn) + assert logs("model").count("RECEIVED " + turn) == 1 + print(kind, "broker attempts", first[2], second[2], flush=True) + return turn + + start("pg", "postgres:17-alpine", ["-e", "POSTGRES_HOST_AUTH_METHOD=trust"]) + start("ns", MQ, ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx128m"], "sh", "mqnamesrv", network=MQ_NETWORK) + start( + "broker", + MQ, + ["-e", "JAVA_OPT_EXT=-Xms256m -Xmx384m -XX:MaxDirectMemorySize=1g"], + "sh", + "-c", + "printf 'brokerName=regression\nbrokerIP1=broker\nenableLmq=true\nenableMultiDispatch=true\nstoreType=defaultRocksDB\nautoCreateTopicEnable=true\n' >/tmp/b.conf && exec sh mqbroker -n ns:9876 -c /tmp/b.conf", + network=MQ_NETWORK, + ) + start("client", JRE, mount, "sleep", "infinity") + wait( + "PostgreSQL", + lambda: run( + "docker", "exec", name("pg"), "pg_isready", "-U", "postgres", check=False + ).returncode + == 0, + ) + client("Probe", "init") + sql( + "create table starts(id text not null); create table effects(id text primary key)" + ) + + sql( + "create table native_starts(scenario text, turn_id text, call_id text, receipt text)" + ) + for scenario in ( + "safe", + "never", + "unknown", + "safe-direct", + "never-direct", + "manual-direct", + "cancel-direct", + "stored-direct", + ): + service = "native-" + scenario + start( + service, + JRE, + [*mount, "-e", "HOLD_NATIVE_RESULT=1"] if scenario == "stored-direct" else mount, + "java", + "-Xmx256m", + "-cp", + CP, + PACKAGE + "NativeReplayProbe", + scenario, + "first", + ) + count = "select count(*) from native_starts where scenario='" + scenario + "'" + wait("native dispatch " + scenario, lambda: sql(count) == "1") + stored = scenario == "stored-direct" + if stored: + wait("native result committed before final answer", + lambda: "NATIVE_RESULT_COMMITTED" in logs(service)) + assert sql( + "select count(*) from durable_parts where part_key like 'event:%' " + "and payload::jsonb->>'type'='message.completed' " + "and payload::jsonb#>>'{data,text}'='receipt-7' " + "and payload::jsonb->>'turnId'=(select turn_id from native_starts " + "where scenario='stored-direct')" + ) == "0" + docker("kill", name(service)) + operator = scenario in ("manual-direct", "cancel-direct") + if operator: + assert "REPAIRED" in client("NativeReplayProbe", scenario, "operator") + report = client("NativeReplayProbe", scenario, "recover") + terminal = "PARKED" if scenario == "unknown" else "SUCCEEDED" + if scenario == "cancel-direct": + terminal = "CANCELLED" + match = re.search(r"^" + terminal + r" (turn_[\w-]+)$", report, re.MULTILINE) + if not match: + raise AssertionError(report) + assert sql(count) == ("2" if scenario.startswith("safe") else "1"), report + assert report.count("MODEL_CHECK") == ( + 0 if scenario.startswith("safe") or operator or stored else 1 + ), report + if scenario.endswith("-direct"): + assert logs(service).count("REASONING_REQUEST") == 1 + assert report.count("REASONING_REQUEST") == 0, report + expected = "receipt-7" if scenario.endswith("-direct") else "verified answer" + answers = sql( + "select count(*) from durable_parts where part_key like 'event:%' and " + "payload::jsonb->>'type'='message.completed' and payload::jsonb#>>'{data,text}'='" + + expected + + "' and " + "payload::jsonb->>'turnId'='" + match[1] + "'" + ) + assert answers == ("0" if scenario in ("unknown", "cancel-direct") else "1") + print( + "native", + scenario, + terminal, + "starts", + sql(count), + "answers", + answers, + flush=True, + ) + + def topics(): + result = run( + "docker", + "exec", + name("broker"), + "sh", + "mqadmin", + "clusterList", + "-n", + "ns:9876", + check=False, + ) + return result.returncode == 0 and "regression" in result.stdout + + wait("broker registration", topics) + for suffix in ["commands", "updates", "controls"]: + docker( + "exec", + name("broker"), + "sh", + "mqadmin", + "updateTopic", + "-n", + "ns:9876", + "-c", + "DefaultCluster", + "-t", + "regression-hands-" + suffix, + "-a", + "+message.type=LITE", + "-r", + "1", + "-w", + "1", + ) + for suffix, topic in ( + ("brain", "updates"), + ("worker", "commands"), + ("worker-controls", "controls"), + ): + docker( + "exec", + name("broker"), + "sh", + "mqadmin", + "updateSubGroup", + "-n", + "ns:9876", + "-c", + "DefaultCluster", + "-g", + "regression-hands-" + suffix, + "-o", + "true", + "-m", + "true", + "--attributes", + f"+lite.bind.topic=regression-hands-{topic},+lite.sub.model=Shared,+lite.sub.wildcard=true", + ) + start( + "proxy", + MQ, + ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx256m"], + "sh", + "mqproxy", + "-n", + "ns:9876", + "-pm", + "cluster", + network=MQ_NETWORK, + ) + wait("cluster proxy startup", lambda: "startup successfully" in logs("proxy")) + java("model", "model") + java("brain-a", "brain") + java("hands-a", "hands") + redeliver("command", "hands") + redeliver("result", "brain") + gate("model", "touch", "block") + turn = submit("model") + wait("provider received", lambda: "RECEIVED " + turn in logs("model")) + assert counts(turn) == "1|0|0" + owner = next( + s for s in ("brain-a", "brain-b") if "MODEL_REQUEST " + turn in logs(s) + ) + docker("kill", name(owner)) + wait( + "model replacement request", + lambda: logs("model").count("RECEIVED " + turn) >= 2, + ) + gate("model", "rm", "block") + done(turn) + assert logs("model").count("RECEIVED " + turn) == 2 + assert logs("model").count("INFERENCE " + turn) == 1 + print("model takeover: two requests, one inference", flush=True) + active = "brain-b" if owner == "brain-a" else "brain-a" + gate("model", "touch", "block") + turn = submit("cancel-in-flight") + wait("cancel model barrier", lambda: "RECEIVED " + turn in logs("model")) + client("Probe", "cancel", turn) + gate("model", "rm", "block") + + def cancelled(): + return ( + sql( + "select payload::jsonb#>>'{value,status}' from durable_parts where part_key like 'turn:%' and payload::jsonb#>>'{value,id}'='" + + turn + + "'" + ) + == "CANCELLED" + ) + + wait("cancelled terminal", cancelled) + assert counts(turn) == "1|0|0" + print("cancelled in-flight model: applied=1 answers=0 success=0", flush=True) + + checkpoint_session_turn = turn + + def pointer(): + row = sql( + "select payload::jsonb#>>'{execution,replayAfter}'," + "payload::jsonb#>>'{execution,checkpointPosition}' from durable_records" + " where record_key in (select record_key from durable_parts where part_key like 'turn:%'" + " and payload::jsonb#>>'{value,id}'='" + checkpoint_session_turn + "')" + ) + cursor, position = map(int, row.split("|")) + return cursor, position + + for phase in ("snapshot", "cursor", "ack", "failed-ack"): + docker("kill", name(active)) + base, position = pointer() + if phase == "failed-ack": + gate("model", "touch", "fail") + turn = submit("checkpoint-" + phase) + barrier = phase + faulted = "checkpoint-" + phase + java( + faulted, + "brain", + [ + "-e", + "CHECKPOINT_GATE=" + barrier, + "-e", + "BASE_CURSOR=" + str(base), + "-e", + "BASE_POSITION=" + str(position), + ], + ) + wait(phase, lambda: "CHECKPOINT_GATE " + barrier in logs(faulted)) + visible = pointer()[0] + assert (visible > base) == (barrier == "ack"), (phase, base, visible) + docker("kill", name(faulted)) + active = "replacement-" + phase + java(active, "brain") + if phase == "failed-ack": + gate("model", "rm", "fail") + failed = sql( + "select count(*) from durable_parts where part_key like 'event:%' and payload::jsonb->>'turnId'='" + + turn + + "' and payload::jsonb->>'type'='turn.failed'" + ) + actual = counts(turn) + assert (failed, actual) == ("1", "1|0|0"), (turn, failed, actual) + done(submit("after-failure")) + else: + done(turn) + wait("settled checkpoint", lambda: pointer()[0] > base) + print("checkpoint", phase, "recovered", flush=True) + + for worker in ("hands-a", "hands-b"): + gate(worker, "touch", "hold-effect") + turn = submit("effect-before-result") + old = wait( + "committed effect", + lambda: next( + ( + worker + for worker in ("hands-a", "hands-b") + if "EFFECT " + turn in logs(worker) + ), + None, + ), + ) + other = "hands-b" if old == "hands-a" else "hands-a" + docker("network", "disconnect", PROJECT, name(old)) + docker("network", "disconnect", MQ_NETWORK, name(old)) + gate(other, "rm", "hold-effect") + done(turn) + docker("network", "connect", PROJECT, name(old)) + docker("network", "connect", MQ_NETWORK, name(old)) + gate(old, "rm", "hold-effect") + for worker in (old, other): + docker("stop", "-t", "2", name(worker)) + done(turn) + + java("opaque", "hands", ["-e", "OPAQUE=true"]) + gate("opaque", "touch", "hold-effect") + turn = submit("opaque-effect") + wait("opaque provider commit", lambda: "EFFECT " + turn in logs("opaque")) + docker("kill", name("opaque")) + java("opaque-replacement", "hands", ["-e", "OPAQUE=true"]) + row = ( + " from durable_records where record_key like 'execution-pool:%' and payload::jsonb#>>'{request,turnId}'='" + + turn + + "'" + ) + wait( + "UNKNOWN", + lambda: sql("select payload::jsonb#>>'{result,state}'" + row) == "UNKNOWN", + ) + assert counts(turn) == "0|0|0" + client("Probe", "verify-effect", sql("select payload::jsonb->'request'" + row)) + done(turn) + print( + "opaque tool: UNKNOWN verified against committed effect; repeated repair kept one answer", + flush=True, + ) + + +if __name__ == "__main__": + if not __debug__: + sys.exit("Run without -O so regression assertions are enabled") + with tempfile.TemporaryDirectory(prefix="durable-regression-") as scratch: + folder = Path(scratch).resolve() + compile_probes(folder) + docker("network", "create", PROJECT) + try: + docker("network", "create", MQ_NETWORK) + exercise(folder) + if pop_memory_errors("broker"): + raise RuntimeError("Broker POP encountered direct-memory exhaustion") + print("broker POP direct-memory errors=0", flush=True) + except BaseException: + for container in containers: + print( + container, + run( + "docker", "logs", "--tail", "15", container, check=False + ).stdout, + file=sys.stderr, + ) + raise + finally: + if containers: + run("docker", "rm", "-f", "-v", *containers) + run("docker", "network", "rm", PROJECT, MQ_NETWORK) diff --git a/agentscope-examples/durable/brain-hands/echo-tool/pom.xml b/agentscope-examples/durable/brain-hands/echo-tool/pom.xml index fba0fc440f..b4c54027a1 100644 --- a/agentscope-examples/durable/brain-hands/echo-tool/pom.xml +++ b/agentscope-examples/durable/brain-hands/echo-tool/pom.xml @@ -61,7 +61,6 @@ io.agentscope agentscope-durable-worker ${revision} - test diff --git a/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/HttpSessionBackend.java b/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/HttpSessionBackend.java index 49b961a25d..1bba463348 100644 --- a/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/HttpSessionBackend.java +++ b/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/HttpSessionBackend.java @@ -20,6 +20,7 @@ import io.agentscope.durable.DurableException; import io.agentscope.durable.DurableJson; import io.agentscope.durable.DurableProtocol.Endpoint; +import io.agentscope.durable.DurableTypes; import io.agentscope.durable.DurableTypes.ActiveTurnCancellation; import io.agentscope.durable.DurableTypes.CheckpointMetadata; import io.agentscope.durable.DurableTypes.CheckpointView; @@ -324,8 +325,26 @@ public Optional claim(ThreadKey session, String owner, Duration duration) @Override public ClaimOutcome claimOutcome(ThreadKey session, String owner, Duration duration) { + return claimOutcome(session, owner, duration, null); + } + + @Override + public ClaimOutcome claimOutcome( + ThreadKey session, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { return as( - call("claim", "thread", session, "owner", owner, "duration", duration.toMillis()), + call( + "claim", + "thread", + session, + "owner", + owner, + "duration", + duration.toMillis(), + "policy", + policy), ClaimOutcome.class); } @@ -484,6 +503,20 @@ public void acceptExecutionEvent(ExecutionMessages.Event event) { call("acceptExecutionEvent", "thread", event.request().thread(), "event", event); } + @Override + public void acceptResult(Lease lease, String executionId, ExecutionResult result) { + call( + "acceptResult", + "thread", + lease.thread(), + "lease", + lease, + "executionId", + executionId, + "result", + result); + } + @Override public ToolExecutionView toolExecution( ThreadKey thread, String turnId, String callId, String executionId) { diff --git a/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/SessionBackendHandler.java b/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/SessionBackendHandler.java index 80c001f51f..b0ea36684d 100644 --- a/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/SessionBackendHandler.java +++ b/agentscope-extensions/agentscope-extensions-durable-http/src/main/java/io/agentscope/extensions/durable/http/SessionBackendHandler.java @@ -23,6 +23,7 @@ import io.agentscope.durable.DurableJson; import io.agentscope.durable.DurableProtocol; import io.agentscope.durable.DurableProtocol.Endpoint; +import io.agentscope.durable.DurableTypes; import io.agentscope.durable.DurableTypes.Commit; import io.agentscope.durable.DurableTypes.ControlCommand; import io.agentscope.durable.DurableTypes.DelegationTarget; @@ -224,7 +225,13 @@ public void handle(HttpExchange exchange) throws IOException { backend.claimOutcome( thread, text(p, "owner"), - Duration.ofMillis(p.path("duration").asLong())); + Duration.ofMillis(p.path("duration").asLong()), + p.hasNonNull("policy") + ? get( + p, + "policy", + DurableTypes.RecoveryPolicy.class) + : null); case "leaseControl" -> result = backend.leaseControl(lease); case "pendingInputs" -> result = backend.pendingInputs(lease); case "renew" -> @@ -328,10 +335,15 @@ public void handle(HttpExchange exchange) throws IOException { result = null; } case "acceptResult" -> { - backend.acceptResult( - thread, - text(p, "executionId"), - get(p, "result", ExecutionResult.class)); + var id = text(p, "executionId"); + var observation = get(p, "result", ExecutionResult.class); + if (lease == null) backend.acceptResult(thread, id, observation); + else { + if (!thread.equals(lease.thread())) + throw new DurableException( + DurableException.Code.INVALID, "Lease scope differs"); + backend.acceptResult(lease, id, observation); + } result = null; } case "signal" -> { diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/JdbcRecordStore.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/JdbcRecordStore.java index 133748544f..35d5fc2eb7 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/JdbcRecordStore.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/JdbcRecordStore.java @@ -107,6 +107,16 @@ public interface Connections { private final Connections connections; private final Dialect dialect; + private final java.util.concurrent.atomic.AtomicLong idleMillis = + new java.util.concurrent.atomic.AtomicLong(30_000); + + @Override + public void boundIdleTransactionTime(java.time.Duration leaseDuration) { + long millis = leaseDuration.toMillis(); + if (millis < 1) throw new IllegalArgumentException("Positive lease duration required"); + idleMillis.accumulateAndGet(millis, Math::min); + } + private final AtomicBoolean closed = new AtomicBoolean(); private final Object drainLock = new Object(); private int inFlight; @@ -414,6 +424,22 @@ private T transact( connection.setAutoCommit(false); try { var transaction = new Scopes(connection, writable, timing); + if (writable && dialect == Dialect.POSTGRESQL) { + // Use the shorter of the database limit and the leases served by this host. + try (var statement = + connection.prepareStatement( + "SELECT set_config('idle_in_transaction_session_timeout', ?" + + " ,true) WHERE" + + " current_setting('idle_in_transaction_session_timeout')::interval" + + " = interval '0' OR" + + " current_setting('idle_in_transaction_session_timeout')::interval" + + " > ?::interval")) { + String timeout = idleMillis.get() + "ms"; + statement.setString(1, timeout); + statement.setString(2, timeout); + statement.execute(); + } + } T result = action.apply(transaction.open(key)); if (writable) for (var parts : transaction.opened.values()) parts.flush(); if (timing == null) connection.commit(); diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/DurableBackendTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/DurableBackendTest.java index 871ed6838e..4971371c04 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/DurableBackendTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/DurableBackendTest.java @@ -45,6 +45,49 @@ protected RecordStore openStore() { return JdbcRecordStore.postgres(postgresUrl, properties); } + @org.junit.jupiter.api.Test + @org.junit.jupiter.api.condition.EnabledIfSystemProperty( + named = "durable.test.jdbcUrl", + matches = ".+") + void idleOwnerCannotHoldRecordLockBeyondShortLease() throws Exception { + try (var owner = openStore(); + var successor = openStore()) { + owner.boundIdleTransactionTime(java.time.Duration.ofSeconds(1)); + var locked = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var first = + java.util.concurrent.CompletableFuture.runAsync( + () -> + owner.transaction( + "idle", + tx -> { + locked.countDown(); + try { + release.await( + 12, + java.util.concurrent.TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return null; + })); + try { + org.junit.jupiter.api.Assertions.assertTrue( + locked.await(5, java.util.concurrent.TimeUnit.SECONDS)); + var second = + java.util.concurrent.CompletableFuture.runAsync( + () -> successor.transaction("idle", tx -> null)); + second.get(6, java.util.concurrent.TimeUnit.SECONDS); + } finally { + release.countDown(); + } + org.junit.jupiter.api.Assertions.assertThrows( + java.util.concurrent.ExecutionException.class, + () -> first.get(5, java.util.concurrent.TimeUnit.SECONDS)); + } + } + @AfterEach protected void cleanup() throws Exception { if (schema != null) diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/PostgresBackendConfigurationTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/PostgresBackendConfigurationTest.java index b53bd7bc80..9cfd2b98a7 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/PostgresBackendConfigurationTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/PostgresBackendConfigurationTest.java @@ -37,6 +37,38 @@ import org.junit.jupiter.api.Test; class PostgresBackendConfigurationTest { + /** Run against a disposable PostgreSQL database with a non-C default collation. */ + @Test + @org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable( + named = "DURABLE_TEST_POSTGRES_URL", + matches = ".+") + void prefixDiscoveryAndPaginationUseBinaryOrdering() { + String prefix = "test:" + java.util.UUID.randomUUID() + ":"; + var keys = java.util.List.of(prefix + "A", prefix + "a", prefix + "😀"); + try (var store = + JdbcRecordStore.postgres( + System.getenv("DURABLE_TEST_POSTGRES_URL"), new java.util.Properties())) { + for (var key : keys) + store.transaction( + key, + tx -> { + tx.put("", io.agentscope.durable.DurableJson.value(1)); + return null; + }); + assertEquals(keys, store.keys(prefix, null, 10)); + assertEquals(keys.subList(1, 3), store.keys(prefix, keys.get(0), 10)); + store.transaction( + prefix, + tx -> { + for (var key : keys) + tx.put(key, io.agentscope.durable.DurableJson.value(1)); + assertEquals(keys, tx.keys(prefix, null, 10)); + assertEquals(keys.subList(1, 3), tx.keys(prefix, keys.get(0), 10)); + return null; + }); + } + } + DataSource source; Connection connection; Statement statement; diff --git a/agentscope-extensions/agentscope-extensions-durable-rocketmq/src/main/java/io/agentscope/extensions/durable/rocketmq/RocketMqWorker.java b/agentscope-extensions/agentscope-extensions-durable-rocketmq/src/main/java/io/agentscope/extensions/durable/rocketmq/RocketMqWorker.java index 0a4073473f..992c5e8348 100644 --- a/agentscope-extensions/agentscope-extensions-durable-rocketmq/src/main/java/io/agentscope/extensions/durable/rocketmq/RocketMqWorker.java +++ b/agentscope-extensions/agentscope-extensions-durable-rocketmq/src/main/java/io/agentscope/extensions/durable/rocketmq/RocketMqWorker.java @@ -62,6 +62,7 @@ private RocketMqWorker(Builder builder) { updatesTopic = topology.updates(); authorizer = builder.authorizer; interval = builder.publicationRepairInterval; + builder.records.boundIdleTransactionTime(builder.lease); ClientServiceProvider provider = builder.provider; Producer configuredProducer; Subscription configuredConsumer; @@ -128,7 +129,10 @@ private RocketMqWorker(Builder builder) { builder.records); store = new TransactionalExecutionStore( - builder.records, name, key -> loop.wake(key, () -> publishPending(key))); + builder.records, + name, + builder.unknownLimit, + key -> loop.wake(key, () -> publishPending(key))); worker = WorkerRuntime.builder() .executionStore(store) @@ -302,6 +306,7 @@ public static final class Builder { private Duration lease = Duration.ofSeconds(30); private int parallelism = 4; private int recoveryParallelism = 2; + private int unknownLimit = TransactionalExecutionStore.DEFAULT_UNKNOWN_LIMIT; private Duration retryMaximum = Duration.ofSeconds(30); private Consumer errors = error -> @@ -342,6 +347,13 @@ public Builder recordStore(RecordStore value) { return this; } + /** Maximum consecutive UNKNOWN observations for newly admitted executions. */ + public Builder unknownLimit(int value) { + if (value < 1) throw new IllegalArgumentException("unknownLimit must be positive"); + unknownLimit = value; + return this; + } + /** RocketMQ connection only; topics and consumer groups follow the shared route convention. */ public Builder clientConfiguration(ClientConfiguration value) { clientConfiguration = Objects.requireNonNull(value); diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-dashscope/src/test/java/io/agentscope/extensions/model/dashscope/DashScopeNonStreamingBlockingBehaviorTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-dashscope/src/test/java/io/agentscope/extensions/model/dashscope/DashScopeNonStreamingBlockingBehaviorTest.java index 5630749225..d22eff91f5 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-dashscope/src/test/java/io/agentscope/extensions/model/dashscope/DashScopeNonStreamingBlockingBehaviorTest.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-dashscope/src/test/java/io/agentscope/extensions/model/dashscope/DashScopeNonStreamingBlockingBehaviorTest.java @@ -15,17 +15,15 @@ */ package io.agentscope.extensions.model.dashscope; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; import io.agentscope.core.message.Msg; import io.agentscope.core.message.MsgRole; import io.agentscope.core.message.TextBlock; import java.io.IOException; import java.util.List; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; @@ -57,7 +55,12 @@ void testDashScopeChatModelNonBlocking() throws Exception { mockServer.enqueue( new MockResponse() .setResponseCode(200) - .setBody("{\"request_id\":\"test\",\"output\":{\"choices\":[]}}") + .setBody( + """ + {"request_id":"test","output":{"choices":[ + {"finish_reason":"stop","message":{"role":"assistant","content":"Hello"}} + ]}} + """) .setHeader("Content-Type", "application/json")); DashScopeChatModel model = @@ -72,21 +75,18 @@ void testDashScopeChatModelNonBlocking() throws Exception { .content(List.of(TextBlock.builder().text("Hello").build())) .build()); - CountDownLatch latch = new CountDownLatch(1); - String currentThreadName = Thread.currentThread().getName(); - AtomicReference streamThreadName = new AtomicReference<>(); + Thread caller = Thread.currentThread(); + var callback = new CompletableFuture(); model.stream(messages, null, null) .subscribe( - response -> { - streamThreadName.set(Thread.currentThread().getName()); - latch.countDown(); - }, - error -> latch.countDown()); - latch.await(3, TimeUnit.SECONDS); - assertNotNull(streamThreadName.get()); - assertNotEquals( - currentThreadName, - streamThreadName.get(), - "DashScopeChatModel should be NON-BLOCKING"); + response -> callback.complete(Thread.currentThread()), + callback::completeExceptionally, + () -> + callback.completeExceptionally( + new AssertionError("No model response"))); + assertNotSame( + caller, + callback.get(30, TimeUnit.SECONDS), + "DashScopeChatModel should deliver the response asynchronously"); } } diff --git a/docs/dev/en/docs/harness/durable.md b/docs/dev/en/docs/harness/durable.md index 78afcbcb55..8e90e19f1a 100644 --- a/docs/dev/en/docs/harness/durable.md +++ b/docs/dev/en/docs/harness/durable.md @@ -899,6 +899,16 @@ After observing PAUSED, use `turn.resume(requestId, expectedRevision)` with that It removes explicit pause only: outstanding approval, tool and signal conditions still apply, and terminal tasks cannot restart. Generic extension signals require an `x.*` key. +Configure per-tool recovery on the AgentScope adapter: + +```java +var recovery = adapter.withNativeToolRecovery( + Map.of("lookup", NativeToolRecovery.Replay.SAFE, "charge", NativeToolRecovery.Replay.NEVER), + new NativeToolRecovery.ModelCheck(checkModel, evidenceLookup)); +``` + +The first dispatch freezes the policy and admitted arguments. Choose `SAFE` for tools that tolerate repeated execution. A replacement Brain can call them again under the original call identity. Unlisted tools default to `NEVER`. For these, a model can suggest a lookup hint. The application's read-only `EvidenceLookup` must match the original operation against an independent record and return a terminal result with the original tool name, call ID and an evidence reference. An inconclusive check parks the Turn until an authorized host submits verified evidence. Pass `null` for the model check to use operator reconciliation only. + ### Tool policies and result hooks Use `AgentScopeAdapter.withToolHooks(new AgentScopeToolHooks(version, timeout, policies, diff --git a/docs/dev/zh/docs/harness/durable.md b/docs/dev/zh/docs/harness/durable.md index fdc30a662f..c652117f4b 100644 --- a/docs/dev/zh/docs/harness/durable.md +++ b/docs/dev/zh/docs/harness/durable.md @@ -779,6 +779,16 @@ Backend 关闭自己拥有的记录存储访问;PostgreSQL 不关闭传入的 它只解除显式暂停;未完成的审批、工具和信号条件仍需满足,也不会重启终态任务。 通用扩展信号仅允许 `x.*` key,不能冒充框架内部控制。 +可按工具名配置恢复策略: + +```java +var recovery = adapter.withNativeToolRecovery( + Map.of("lookup", NativeToolRecovery.Replay.SAFE, "charge", NativeToolRecovery.Replay.NEVER), + new NativeToolRecovery.ModelCheck(checkModel, evidenceLookup)); +``` + +首次派发时,journal 记录策略和已获准执行的参数。对允许重复执行的工具使用 `SAFE`,接管的 Brain 可按原调用身份重新执行。未配置的工具默认使用 `NEVER`。模型可提供查询线索,应用的只读 `EvidenceLookup` 负责在独立系统中核对原操作,并返回带原工具名、调用 ID 和证据引用的终态结果。无法核实时,Turn 保持等待,直至授权宿主提交已核实的证据。将模型自查参数设为 `null` 即可关闭自查。 + ### 工具策略与结果 Hooks 使用 `AgentScopeAdapter.withToolHooks(new AgentScopeToolHooks(version, timeout, policies,