From 7d8a36d9790bef628aea8cd1471a8c0792249362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 11:32:38 +0800 Subject: [PATCH 01/38] Fence direct executor progress after Brain ownership changes --- .../java/io/agentscope/durable/DurableRuntime.java | 6 +++++- .../durable/NotifyingSessionBackend.java | 6 ++++++ .../java/io/agentscope/durable/SessionBackend.java | 3 +++ .../durable/TransactionalSessionBackend.java | 11 ++++++++++- .../durable/contract/SessionBackendContract.java | 13 ++++++++++++- agentscope-durable/protocol/schema.json | 3 +++ .../durable/http/HttpSessionBackend.java | 14 ++++++++++++++ .../durable/http/SessionBackendHandler.java | 13 +++++++++---- 8 files changed, 62 insertions(+), 7 deletions(-) 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 e64e871d7f..631aca80aa 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 @@ -753,7 +753,11 @@ private void resolve(Lease lease, ToolExecution tool, boolean cancel) { before.result(), before.dispatchAttempted(), cancel); - 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 ensureExecution() { 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 4aeb565a4d..ff32df41e5 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 @@ -361,6 +361,12 @@ public void acceptExecutionEvent(ExecutionMessages.Event event) { changed(event.request().session()); } + @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 68873461bc..7d63d62997 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 @@ -207,6 +207,9 @@ ModelCallPage modelCalls( 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); + void signal(ThreadKey session, String turnId, Signal signal); /** Withdrawal wins only before the input is atomically applied to native state. */ 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 89cfb0a90a..9e824a031c 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 @@ -1776,8 +1776,17 @@ public ToolExecution beginDispatch(Lease lease, String id) { }); } + @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"); @@ -1787,7 +1796,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; 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 390b866ea3..a672baeb33 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 @@ -1401,7 +1401,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")); diff --git a/agentscope-durable/protocol/schema.json b/agentscope-durable/protocol/schema.json index a3e2371b44..706d4ac376 100644 --- a/agentscope-durable/protocol/schema.json +++ b/agentscope-durable/protocol/schema.json @@ -4051,6 +4051,9 @@ "minLength": 1, "maxLength": 256 }, + "lease": { + "$ref": "#/$defs/lease" + }, "result": { "$ref": "#/$defs/executionResult" }, 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 30844ebeef..19fa2c71ce 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 @@ -399,6 +399,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 void acceptResult(ThreadKey session, String executionId, ExecutionResult result) { call("acceptResult", "thread", session, "executionId", executionId, "result", result); 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 ad8943411b..dce6163fe3 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 @@ -278,10 +278,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" -> { From 0d8cf9f79705ccf11e68b084feec0121ab29839c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 11:34:40 +0800 Subject: [PATCH 02/38] Bound consecutive losses of unfinished native runs --- .../durable/TransactionalSessionBackend.java | 36 ++++++++++++++++++- .../contract/SessionBackendContract.java | 12 +++++++ 2 files changed, 47 insertions(+), 1 deletion(-) 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 9e824a031c..9d358a2cd9 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 @@ -249,6 +249,7 @@ public static final class TurnData { public WaitCondition waiting; public RecoveryView recovery; public long failedEpoch; + public int consecutiveLostRuns; @JsonIgnore public Map tools = new LinkedHashMap<>(); @JsonIgnore public Map signals = new LinkedHashMap<>(); public List consumed = new ArrayList<>(); @@ -1047,7 +1048,36 @@ public Optional claim(ThreadKey key, String owner, Duration duration) { new Lease(key, turn.id, owner, turn.epoch, turn.expiresAt)); long ready = readyAt(s, now); if (ready < 0 || ready > now) return Optional.empty(); - invocations(s, turn).abandon(now, true); + 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 policy = + turn.recovery == null + ? DurableTypes.RecoveryPolicy.defaults() + : turn.recovery.policy(); + if (++turn.consecutiveLostRuns > policy.maxRetries()) { + turn.error = + "Repeated ownership loss without completed execution progress"; + turn.recovery = + new RecoveryView( + policy.maxRetries() + 1, + policy, + 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); @@ -1088,6 +1118,7 @@ public void release(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())); @@ -1246,6 +1277,9 @@ public CommitReceipt commit(Lease lease, Commit command) { if (r.revision != command.expectedRevision()) throw error(DurableException.Code.CONFLICT, "Revision changed"); 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()); 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 a672baeb33..fe03054773 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 @@ -1385,6 +1385,18 @@ private Lease claim() { .orElseThrow(); } + @Test + protected void repeatedExpiryOfUnfinishedRunsStopsInvocationRecovery() { + submit(); + var lease = claim(); + for (int i = 0; i <= RecoveryPolicy.defaults().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(); From ac346d62e3d98603405b974345d3dccc8549d9f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 11:37:24 +0800 Subject: [PATCH 03/38] Reconcile uncertain native tool outcomes under a fenced operator lease --- .../durable/agentscope/AgentScopeAdapter.java | 49 +++++++++++++++++++ .../agentscope/AgentScopeAdapterTest.java | 40 +++++++++++++++ 2 files changed, 89 insertions(+) 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 62193fd844..71de6518d2 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 @@ -260,6 +260,55 @@ public Capabilities capabilities() { List.of("text", "image", "audio", "video")); } + /** Operator-only repair under a claimed Turn lease. The host verifies the external evidence. */ + public void reconcileNativeTools( + HarnessContext context, + String requestId, + String evidenceRef, + Map verified) { + DurableJson.text(requestId, "requestId"); + DurableJson.text(evidenceRef, "evidenceRef"); + var outcomes = Map.copyOf(verified); + if (outcomes.isEmpty() + || outcomes.values().stream() + .anyMatch( + result -> + result.getState() == null + || result.getState() == ToolResultState.RUNNING + || result.isSuspended() + || result.getExecutionDetails() != null + && "UNKNOWN" + .equals( + result.getExecutionDetails() + .outcome() + .name()))) { + throw new DurableException( + DurableException.Code.INVALID, "Verified terminal outcomes required"); + } + var log = new BackendThreadJournal(context, executors, bindings); + String turn = context.lease().turnId(); + String key = "native-reconciliation:" + DurableJson.hash(List.of(turn, requestId)) + ":"; + String reason = key + DurableJson.hash(outcomes) + ":" + evidenceRef; + for (var event : log.scanMetadata(0, log.head().seq())) { + if (!turn.equals(event.turnId()) || !"recovery/applied".equals(event.type())) continue; + if (event.data().get("reason") instanceof String stored && stored.startsWith(key)) { + if (stored.equals(reason)) return; + throw new DurableException( + DurableException.Code.CONFLICT, "Reconciliation request changed"); + } + } + var projection = JournalProjection.read(log); + if (!turn.equals(projection.positionTurnId()) + || !projection.uncertainToolCalls().equals(outcomes.keySet()) + || context.frame().tools().stream() + .anyMatch(tool -> outcomes.containsKey(tool.request().call().callId()))) { + throw new DurableException( + DurableException.Code.CONFLICT, + "Outcomes must match this Turn's unresolved native calls"); + } + io.agentscope.core.journal.ThreadRecovery.reconcile(log, outcomes, reason); + } + @Override public void execute(HarnessContext context) { if (pauseIfRequested(context)) return; 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 d84a77c84b..16fa7dafa8 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 @@ -230,6 +230,46 @@ DurableRuntime runtime( return builder.build(); } + @Test + void verifiedNativeToolRepairSurvivesReopenAndRejectsChangedEvidence() { + var adapter = adapter(new ScriptedModel(false), PermissionMode.BYPASS, Map.of()); + try (var backend = LocalBackend.open(directory.resolve("repair")); + var runtime = runtime(backend, adapter, null)) { + var turn = runtime.createSession(key, "agent").submit("request", "hello"); + var lease = + backend.claim(new ThreadKey(key, "main"), "repair", Duration.ofMinutes(1)) + .orElseThrow(); + var context = new HarnessContext(backend, lease, new AtomicBoolean()); + var log = new BackendThreadJournal(context, Map.of()); + log.append( + turn.turnId(), + List.of( + Map.entry( + "state/checkpoint", + Map.of( + "stateJson", + io.agentscope.core.state.AgentState.builder() + .build() + .toJson(), + "projectorVersion", + 1)), + Map.entry("tool/dispatch", Map.of("toolCallId", "local-1")))); + var outcomes = + Map.of( + "local-1", + ToolResultBlock.text("verified") + .withIdAndName("local-1", "local") + .withState(ToolResultState.SUCCESS)); + adapter.reconcileNativeTools(context, "repair-1", "audit/123", outcomes); + long position = new BackendThreadJournal(context, Map.of()).head().seq(); + adapter.reconcileNativeTools(context, "repair-1", "audit/123", outcomes); + assertEquals(position, new BackendThreadJournal(context, Map.of()).head().seq()); + assertThrows( + DurableException.class, + () -> adapter.reconcileNativeTools(context, "repair-1", "other", outcomes)); + } + } + @Test void adapterOwnsTheInvocationJournalConfiguration() { var adapter = From f6f0f2cac8c8e16c09859901061ee966b815ecb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 11:38:50 +0800 Subject: [PATCH 04/38] Resume long threads from settled native state snapshots --- .../core/journal/InvocationRecorder.java | 7 +++- .../core/journal/JournalProjection.java | 2 +- .../core/journal/ThreadInteractions.java | 2 +- .../core/journal/ThreadJournal.java | 5 +++ .../durable/agentscope/AgentScopeAdapter.java | 8 ++-- .../agentscope/AgentScopeExecutionHost.java | 4 +- .../agentscope/BackendThreadJournal.java | 38 ++++++++++++++++--- .../agentscope/AgentScopeAdapterTest.java | 19 +++++++++- docs/dev/en/docs/harness/durable.md | 8 ++++ docs/dev/zh/docs/harness/durable.md | 8 ++++ 10 files changed, 86 insertions(+), 15 deletions(-) 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 5d5054d10f..29dc3e0324 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 @@ -143,7 +143,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.recoveryCursor() > 0) + restored.getContext().forEach(message -> recordedMessages.add(message.getId())); + } } catch (RuntimeException e) { log.release(writer); throw e; 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 25523ad3ba..65460525b2 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 @@ -53,7 +53,7 @@ public static JournalProjection read(ThreadJournal log, Consumer o var verifications = new ArrayList(); var extensions = new ArrayList(); long upper = log.head().seq(); - for (var event : log.scanMetadata(0, upper)) { + for (var event : log.scanMetadata(log.recoveryCursor(), upper)) { JournalEventTypes.validate(event); observer.accept(event); var data = event.data(); diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadInteractions.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadInteractions.java index f6b528bf01..4a15e90819 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadInteractions.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadInteractions.java @@ -51,7 +51,7 @@ public static Map continuationRequests( public static Map pending(ThreadJournal log) { long upper = log.head().seq(); var result = new LinkedHashMap(); - for (var event : log.scanMetadata(0, upper)) { + for (var event : log.scanMetadata(log.recoveryCursor(), upper)) { if (event.type().equals("interaction/requested")) result.put(String.valueOf(event.data().get("requestId")), event); if (event.type().equals("interaction/resolved")) diff --git a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadJournal.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadJournal.java index 0da1be2bd6..839be20d05 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadJournal.java +++ b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadJournal.java @@ -103,6 +103,11 @@ public JournalEvent next() { Head head(); + /** Cursor immediately before a settled state snapshot. Historical reads still start at zero. */ + default long recoveryCursor() { + return 0; + } + Writer acquire(String owner, Duration lease); /** 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 71de6518d2..86b4a03d83 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 @@ -289,7 +289,7 @@ public void reconcileNativeTools( String turn = context.lease().turnId(); String key = "native-reconciliation:" + DurableJson.hash(List.of(turn, requestId)) + ":"; String reason = key + DurableJson.hash(outcomes) + ":" + evidenceRef; - for (var event : log.scanMetadata(0, log.head().seq())) { + for (var event : log.scanMetadata(log.recoveryCursor(), log.head().seq())) { if (!turn.equals(event.turnId()) || !"recovery/applied".equals(event.type())) continue; if (event.data().get("reason") instanceof String stored && stored.startsWith(key)) { if (stored.equals(reason)) return; @@ -499,7 +499,7 @@ private static NativeInvocation latestInvocation(ThreadJournal log, String turnI String runId = null; RunOutcome outcome = null; Msg output = null; - for (var event : log.scanMetadata(0, log.head().seq())) { + for (var event : log.scanMetadata(log.recoveryCursor(), log.head().seq())) { if ("state/restored".equals(event.type())) { runId = null; outcome = null; @@ -525,7 +525,7 @@ private static NativeInvocation latestInvocation(ThreadJournal log, String turnI private static boolean hasInitialInput(ThreadJournal log, String turnId) { boolean received = false; - for (var event : log.scanMetadata(0, log.head().seq())) { + for (var event : log.scanMetadata(log.recoveryCursor(), log.head().seq())) { if ("state/restored".equals(event.type())) received = false; if ("input/received".equals(event.type()) && turnId.equals(event.turnId())) received = true; @@ -561,7 +561,7 @@ private static boolean completeInvocation(HarnessContext context, BackendThreadJ new Commit( "native-finished:" + invocation.runId(), frame.turn().revision(), - frame.checkpoint(), + log.settledCheckpoint(frame.checkpoint()), List.of(), List.of(), List.of(), 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 fb63eebe37..32dcd497f8 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 @@ -140,7 +140,7 @@ String resourceIdentity() { AgentScopeExecutionHost(HarnessContext durable, BackendThreadJournal log) { this.durable = durable; this.log = log; - for (var event : log.scan(0, log.head().seq())) { + for (var event : log.scan(log.recoveryCursor(), log.head().seq())) { if ("state/checkpoint".equals(event.type())) replayAfter = event.seq(); if (!durable.lease().turnId().equals(event.turnId())) continue; var data = event.data(); @@ -282,7 +282,7 @@ public Flux stream( String hash = requestHash(model, purpose, messages, tools, options); String id = null; long checkpoint = 0; - var history = log.scan(0, log.head().seq()); + var history = log.scan(log.recoveryCursor(), log.head().seq()); if (active) { int index = slot.getAndIncrement(); for (var event : history) { 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 8cb737cbde..85fbb3e4fc 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 @@ -68,6 +68,7 @@ final class BackendThreadJournal implements ThreadJournal { private String owner; private final Map captures = new LinkedHashMap<>(); private ObjectNode cached; + private final long recoveryCursor; private AgentScopeMessageEvents messages = new AgentScopeMessageEvents(); private AgentScopeToolEvents toolEvents = new AgentScopeToolEvents(); @@ -97,7 +98,8 @@ final class BackendThreadJournal implements ThreadJournal { cached.putArray("events"); cached.putObject("receipts"); cached.put("lastCommit", checkpoint.path("lastCommit").asText(null)); - long position = 0; + recoveryCursor = checkpoint.path("recoveryCursor").asLong(); + long position = recoveryCursor; while (true) { var page = context.journal(position, 1000); for (var entry : page) { @@ -155,6 +157,24 @@ private ObjectNode checkpoint() { return cached.deepCopy(); } + @Override + public long recoveryCursor() { + return recoveryCursor; + } + + /** Publish the last complete native state only in the commit settling the Turn. */ + JsonNode settledCheckpoint(JsonNode current) { + var checkpoint = (ObjectNode) current.deepCopy(); + var events = cached.path("events"); + for (int i = events.size() - 1; i >= 0; i--) { + if ("state/checkpoint".equals(events.get(i).path("type").asText())) { + checkpoint.put("recoveryCursor", recoveryCursor + i); + break; + } + } + return checkpoint; + } + @Override public synchronized Head head() { return head(checkpoint()); @@ -163,7 +183,7 @@ public synchronized Head head() { private Head head(ObjectNode state) { return new Head( FORMAT_VERSION, - state.path("events").size(), + recoveryCursor + state.path("events").size(), context.lease().epoch(), owner, context.lease().expiresAt(), @@ -240,7 +260,7 @@ private Head commit( return DurableJson.convert(previous.path("head"), Head.class); } check(writer); - if (state.path("events").size() != expected) + if (recoveryCursor + state.path("events").size() != expected) throw new DurableException(DurableException.Code.CONFLICT, "Native sequence changed"); var tools = new ArrayList(); var publicEvents = new ArrayList(); @@ -410,6 +430,8 @@ private Head commit( AgentScopeCheckpointCodec.STATE_VERSION, "position", seq, + "recoveryCursor", + recoveryCursor, "lastCommit", batchId)), tools, @@ -536,9 +558,15 @@ synchronized String messageId(String turnId, Msg message) { @Override public synchronized List readAfter(long after, int limit) { if (after < 0 || limit < 1) throw new IllegalArgumentException("Invalid native range"); - var events = checkpoint().path("events"); + if (after < recoveryCursor) + return context + .journal(after, (int) Math.min(Math.min(limit, 1000), recoveryCursor - after)) + .stream() + .map(entry -> DurableJson.convert(entry, JournalEvent.class)) + .toList(); + var events = cached.path("events"); var result = new ArrayList(); - for (long i = after; i < events.size() && result.size() < limit; i++) + for (long i = after - recoveryCursor; i < events.size() && result.size() < limit; i++) result.add(DurableJson.convert(events.get((int) i), JournalEvent.class)); return List.copyOf(result); } 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 16fa7dafa8..c4acc57765 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 @@ -2037,14 +2037,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 ("journal".equals(method.getName())) + reads.add((Long) args[1]); + 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"))); diff --git a/docs/dev/en/docs/harness/durable.md b/docs/dev/en/docs/harness/durable.md index 76c1ebee8d..a7c6d19ce3 100644 --- a/docs/dev/en/docs/harness/durable.md +++ b/docs/dev/en/docs/harness/durable.md @@ -765,6 +765,14 @@ a stopped Run is not necessarily a terminal Turn. ## Recovery limits +Direct executor progress is fenced by the observing Brain's lease. A stale observation cannot replace the new owner's operation handle. A confirmed terminal result for the same execution may still arrive late. + +When unfinished runs repeatedly lose ownership beyond the persisted recovery policy's retry limit (three retries before a policy is recorded), the replacement host settles the failure. Completing an execution step or releasing the lease normally resets consecutive losses. + +For an uncertain native tool, an authorized host independently verifies the outcomes, claims the original Turn, constructs a `HarnessContext` with that lease, and calls `AgentScopeAdapter.reconcileNativeTools(context, requestId, evidenceRef, outcomes)`. Supply terminal outcomes for all unresolved native call IDs and release the lease afterwards. Use a reference to an access-controlled audit record; omit sensitive payloads. Identical requests can be retried on the same Turn. Reconciliation repairs native state and preserves prior cancellation or exhausted recovery decisions. + +When a Turn completes normally, its terminal commit records the location of the most recent native state snapshot. The next invocation recovers from that snapshot and subsequent journal entries. Explicit historical reads retain the complete prefix. A single long unfinished Turn still replays entries since the previous snapshot. + Threads pin Harness and native-state versions. Restarts need matching factories, tool bindings and execution environments. A shared backend does not permit switching native kernels. The supplied implementation is Java; other language integrations require diff --git a/docs/dev/zh/docs/harness/durable.md b/docs/dev/zh/docs/harness/durable.md index c8f37fbf99..f0e4454a82 100644 --- a/docs/dev/zh/docs/harness/durable.md +++ b/docs/dev/zh/docs/harness/durable.md @@ -682,6 +682,14 @@ SSE 查询支持 threadId/turnId/runId,Last-Event-ID 优先于 cursor 参数 ## 恢复边界 +直接 Executor 的非终态进展由当前 Brain 的租约保护。换主后旧观察不能覆盖新宿主保存的操作句柄;同一执行迟到的已确认终态仍可交付。 + +同一 Turn 的未完成 Run 连续丢失所有权,超过持久恢复策略的重试次数(尚无策略记录时默认为三次)后,接管宿主停止推理并执行故障收尾。完成一个执行步骤或正常释放租约会清零连续丢失次数。 + +原生工具已派发、结果不确定时,由获授权的宿主独立确认结果,认领原 Turn,并调用 `AgentScopeAdapter.reconcileNativeTools(context, requestId, evidenceRef, outcomes)`。使用该租约构造 `HarnessContext`,提交全部未核实的原生调用 ID 及对应终态,完成后释放租约。证据引用应指向受控审计记录,勿传入敏感载荷。同一 Turn 的相同请求和结果可以重试;核实只修复原生状态,保留已有的取消或停止恢复决定。 + +正常完成 Turn 时,适配器在终态事务中保存最近原生状态快照的位置。下次恢复从该快照读取后续日志;按位置显式读取的历史仍完整保留。单个尚未完成的长 Turn 仍需回放自上一个快照起的记录。 + Thread 固定 Harness 和原生状态版本,重启需要匹配的工厂、工具绑定与执行环境。 共享后端不意味着可以切换原生内核。当前提供 Java 实现;其他语言接入需要自己的适配器和协议一致性检查。 From ab848697c5e72c095b5d20b68be03bb02c64c469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 13:36:32 +0800 Subject: [PATCH 05/38] Include the worker runtime in packaged distributed echo applications --- agentscope-examples/durable/brain-hands/echo-tool/pom.xml | 1 - 1 file changed, 1 deletion(-) 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 From d486ec17cdc9f48b2a745a1651c1d0a41e7c46c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 13:45:27 +0800 Subject: [PATCH 06/38] Scan PostgreSQL durable record keys independently of database collation --- .../durable/jdbc/JdbcRecordStore.java | 36 +++++++++++++++---- .../PostgresBackendConfigurationTest.java | 32 +++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) 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 b4b9f758f0..4f52fc71e3 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 @@ -204,7 +204,7 @@ private long time(Connection c) throws SQLException { } } - private static final class Parts implements Transaction { + private final class Parts implements Transaction { private final Connection connection; private final String scope; private final long now; @@ -269,11 +269,11 @@ public List keys(String prefix, String after, int limit) { checkLimit(limit); try (var s = connection.prepareStatement( - "SELECT part_key FROM durable_parts WHERE record_key=? AND part_key>=?" - + " AND part_key? ORDER BY part_key LIMIT ?")) { + "SELECT part_key FROM durable_parts WHERE record_key=? AND " + + prefixPage("part_key"))) { s.setString(1, scope); s.setString(2, prefix); - s.setString(3, prefix + "\uffff"); + s.setString(3, dialect == Dialect.POSTGRESQL ? prefix : prefix + "\uffff"); s.setString(4, after == null ? "" : after); s.setInt(5, limit); try (var rs = s.executeQuery()) { @@ -352,6 +352,28 @@ private static void checkKey(String value, int limit, String name) { throw new IllegalArgumentException("Invalid " + name); } + private String prefixPage(String column) { + if (dialect == Dialect.POSTGRESQL) { + String key = column + " COLLATE \"C\""; + return key + + ">=? AND starts_with(" + + column + + ",?) AND " + + key + + ">? ORDER BY " + + key + + " LIMIT ?"; + } + return column + + ">=? AND " + + column + + "? ORDER BY " + + column + + " LIMIT ?"; + } + @Override public List keys(String prefix, String after, int limit) { if (limit < 1 || limit > 1000) throw new IllegalArgumentException("Limit must be 1..1000"); @@ -360,10 +382,10 @@ public List keys(String prefix, String after, int limit) { var s = c.prepareStatement( "SELECT record_key FROM durable_records WHERE payload IS NOT NULL" - + " AND record_key>=? AND record_key? ORDER" - + " BY record_key LIMIT ?")) { + + " AND " + + prefixPage("record_key"))) { s.setString(1, prefix); - s.setString(2, prefix + "\uffff"); + s.setString(2, dialect == Dialect.POSTGRESQL ? prefix : prefix + "\uffff"); s.setString(3, after == null ? "" : after); s.setInt(4, limit); try (var rs = s.executeQuery()) { 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; From 8f7e89bda78c75cccd6855806a371123d3ee6933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 13:53:48 +0800 Subject: [PATCH 07/38] Bound PostgreSQL idle record transactions after owner disconnects --- agentscope-durable/README.md | 4 ++++ .../extensions/durable/jdbc/JdbcRecordStore.java | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 293d8cd27f..4581374fe8 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -307,6 +307,10 @@ the hosts at the same database. Each host needs matching definition/state versio and access to the required tools and workspace resources. Close each host and its Backend at application shutdown; the application owns the supplied pool. +PostgreSQL record transactions use a 30-second idle-in-transaction timeout when +the database setting is disabled. An existing positive timeout takes precedence. +This lets PostgreSQL release record locks after a disconnected host stops sending SQL. + Runtime scans durable ready work and renews ownership while executing it. Fencing rejects writes from an expired owner even if that process later reconnects. Optional wakeup notifications reduce latency; durable scans compensate for lost hints. 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 4f52fc71e3..4210668f19 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 @@ -160,6 +160,17 @@ public T transaction(String key, Function action) { try (Connection c = connect()) { c.setAutoCommit(false); try { + if (dialect == Dialect.POSTGRESQL) { + // Release the record lock if the owner disappears between statements. + // A positive timeout configured by the database takes precedence. + try (var statement = c.createStatement()) { + statement.execute( + "SELECT" + + " set_config('idle_in_transaction_session_timeout','30s',true)" + + " WHERE" + + " current_setting('idle_in_transaction_session_timeout')='0'"); + } + } try (var s = c.prepareStatement( "INSERT INTO durable_records(record_key,payload) VALUES (?,NULL) ON" From 1c8421c13d045847e3c7d0708e781e5b5996faa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 13:59:54 +0800 Subject: [PATCH 08/38] Exercise expired Hands ownership across independent consumers --- .../durable/worker/WorkerRuntimeTest.java | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) 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 6a253cb30f..701504fd2b 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 @@ -543,28 +543,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); - var old = store.claim(key, "old", Duration.ofSeconds(1)).orElseThrow(); - store.begin(old); - store.release(old, Duration.ZERO); - var current = store.claim(key, "new", Duration.ofSeconds(1)).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); + 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).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 From d859fc142e6dc93c98a8d4fee17208c437832384 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 14:21:02 +0800 Subject: [PATCH 09/38] Reuse model provider idempotency keys across Brain takeover --- .../core/journal/ModelInvocation.java | 5 ++ .../core/journal/RecordedModels.java | 14 ++++- agentscope-durable/README.md | 7 +++ .../agentscope/AgentScopeExecutionHost.java | 35 +++++++++++- .../agentscope/BackendThreadJournal.java | 12 ++++- .../durable/agentscope/ModelCapture.java | 7 ++- .../agentscope/AgentScopeAdapterTest.java | 54 +++++++++++++++++++ 7 files changed, 127 insertions(+), 7 deletions(-) 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 71de81241f..c40a5ee098 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 @@ -26,6 +26,11 @@ /** Optional call-scoped host replay boundary. Invoking next preserves recording and model policy. */ @FunctionalInterface public interface ModelInvocation { + /** Transport options for this recorded dispatch. The journal retains the original input. */ + default GenerateOptions providerOptions(String callId, GenerateOptions options) { + return options; + } + Flux stream( String model, String purpose, 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 45a9dc4556..24e73f51b0 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 @@ -101,7 +101,19 @@ private Flux invoke( context.getAgentState())) .thenReturn(callId), id -> - Flux.defer(() -> delegate.stream(messages, tools, options)) + Flux.defer( + () -> { + var host = + context.get( + ModelInvocation.class); + return delegate.stream( + messages, + tools, + host == null + ? options + : host.providerOptions( + id, options)); + }) .doOnNext( chunk -> { last.set(chunk); diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 4581374fe8..c3cf1622f0 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -311,6 +311,13 @@ PostgreSQL record transactions use a 30-second idle-in-transaction timeout when the database setting is disabled. An existing positive timeout takes precedence. 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. + Runtime scans durable ready work and renews ownership while executing it. Fencing rejects writes from an expired owner even if that process later reconnects. Optional wakeup notifications reduce latency; durable scans compensate for lost hints. 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 32dcd497f8..3b279313d0 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 @@ -67,6 +67,8 @@ private record Frame( private final BackendThreadJournal log; private Frame frame; private long replayAfter; + // Unfinished provider requests present at takeover, consumed once per matching replay. + private final Map pendingProviderKeys = new LinkedHashMap<>(); private final Set replayed = new HashSet<>(); private boolean completed; private volatile boolean active; @@ -141,9 +143,19 @@ String resourceIdentity() { this.durable = durable; this.log = log; for (var event : log.scan(log.recoveryCursor(), log.head().seq())) { - if ("state/checkpoint".equals(event.type())) replayAfter = event.seq(); + if ("state/checkpoint".equals(event.type())) { + replayAfter = event.seq(); + pendingProviderKeys.clear(); + } 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")); if (DurableEventSchemas.START.equals(event.type())) { frame = new Frame( @@ -334,16 +346,35 @@ public Flux stream( } } String call = id == null ? UUID.randomUUID().toString() : id; + String priorKey = pendingProviderKeys.remove(hash); log.modelStarted( call, new ModelCapture( - model, purpose, messages, tools, options, hash)); + model, + purpose, + messages, + tools, + options, + hash, + priorKey == null ? call : priorKey)); return Flux.defer(() -> next.apply(call)) .doOnNext(chunk -> log.modelChunk(call, chunk)); }) .subscribeOn(Schedulers.boundedElastic()); } + @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()); + } + static String requestHash( String model, String purpose, 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 85fbb3e4fc..2a2f774f84 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 @@ -123,6 +123,10 @@ 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); } @@ -132,11 +136,15 @@ private JournalEvent capture(JournalEvent event) { 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 c039ba247d..966eb8a1bd 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<>(); @@ -54,7 +55,9 @@ final class ModelCapture { List messages, List tools, GenerateOptions options, - String replayHash) { + String replayHash, + String providerKey) { + this.providerKey = providerKey; var data = new LinkedHashMap(); data.put("model", model); data.put("purpose", purpose); 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 c4acc57765..da76441151 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 @@ -497,6 +497,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 completedModelSurvivesCrashBeforeStateApplication() throws Exception { var model = new ScriptedModel(false); From 72947a5aacdf3fefa6e5d9a73a2d8c886dfd91ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 14:38:00 +0800 Subject: [PATCH 10/38] Fence late invocation commits after cancellation is accepted --- agentscope-durable/README.md | 3 ++- .../durable/TransactionalSessionBackend.java | 6 +++-- .../contract/SessionBackendContract.java | 27 +++++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index c3cf1622f0..daa75f6d75 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -213,7 +213,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 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 9d358a2cd9..c9d9ca8562 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 @@ -1259,6 +1259,10 @@ public CommitReceipt commit(Lease lease, Commit command) { return old; } owned(s, lease, now); + // Cancellation and native commits serialize on this record. A late inference + // must not publish an answer or checkpoint before cancellation settlement. + if (r.cancel && command.status() != TurnStatus.CANCELLED) + throw error(DurableException.Code.FENCED, "Invocation cancelled"); policy.check(s.tx, s.thread.definition, lease, command); if (command.journal() != null) { var append = command.journal(); @@ -1477,8 +1481,6 @@ public CommitReceipt commit(Lease lease, Commit command) { r.waiting = command.waiting(); r.output = DurableJson.copy(command.output()); r.error = command.error(); - if (r.cancel) - next = next.terminal() ? TurnStatus.CANCELLED : TurnStatus.CANCELLING; r.status = next; for (EventInput event : command.events()) { if (event.type().startsWith("session.") 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 fe03054773..e338a41aec 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 @@ -3287,6 +3287,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(); From 2dc1143e7e2b936c4ee33f68bad8fac0a7ec20a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 14:47:27 +0800 Subject: [PATCH 11/38] Advance native recovery cursor on terminal settlement --- agentscope-durable/README.md | 3 +++ .../durable/agentscope/BackendThreadJournal.java | 15 ++++++++++----- .../durable/agentscope/AgentScopeAdapterTest.java | 10 ++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index daa75f6d75..81aa224c74 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 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 2a2f774f84..ac3f0807cd 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 @@ -173,14 +173,17 @@ public long recoveryCursor() { /** Publish the last complete native state only in the commit settling the Turn. */ JsonNode settledCheckpoint(JsonNode current) { var checkpoint = (ObjectNode) current.deepCopy(); - var events = cached.path("events"); + checkpoint.put("recoveryCursor", settledCursor(cached.path("events"))); + return checkpoint; + } + + private long settledCursor(JsonNode events) { for (int i = events.size() - 1; i >= 0; i--) { if ("state/checkpoint".equals(events.get(i).path("type").asText())) { - checkpoint.put("recoveryCursor", recoveryCursor + i); - break; + return recoveryCursor + i; } } - return checkpoint; + return recoveryCursor; } @Override @@ -439,7 +442,9 @@ private Head commit( "position", seq, "recoveryCursor", - recoveryCursor, + turnStatus.terminal() + ? settledCursor(state.path("events")) + : recoveryCursor, "lastCommit", batchId)), tools, 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 da76441151..447de968eb 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 @@ -2670,6 +2670,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.checkpoint().required("recoveryCursor").asLong(); + 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 = From af091cda22776239f87721caef6cec341bcf2554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 14:53:56 +0800 Subject: [PATCH 12/38] Reconcile delayed live previews across subscription snapshot resets --- agentscope-durable/README.md | 2 + .../agentscope/durable/CompletedPreviews.java | 62 +++++++++++++++++++ .../durable/SessionEventClient.java | 10 +-- .../durable/SessionEventStream.java | 17 ++--- .../durable/SessionEventSubscription.java | 20 +++--- .../durable/SessionEventClientTest.java | 21 +++++++ .../durable/SessionStreamEventTest.java | 49 +++++++++++++++ 7 files changed, 151 insertions(+), 30 deletions(-) create mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 81aa224c74..a1216a92d4 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -75,6 +75,8 @@ 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. +On a subscription reset, replace the local projection and save its cursor together. +The SDK catches up on commits made during the reset before releasing live previews. 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. diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java new file mode 100644 index 0000000000..1ce6d823c2 --- /dev/null +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java @@ -0,0 +1,62 @@ +/* + * 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; + +import io.agentscope.durable.DurableTypes.LiveEvent; +import io.agentscope.durable.DurableTypes.PublicEvent; +import io.agentscope.durable.DurableTypes.Snapshot; +import java.util.HashSet; +import java.util.Set; + +/** Accessed by the serial delivery thread. Durable state supersedes delayed live previews. */ +final class CompletedPreviews { + private final Set messages = new HashSet<>(); + private final Set tools = new HashSet<>(); + + void reset(Snapshot snapshot) { + messages.clear(); + tools.clear(); + for (var message : snapshot.projection().path("messages")) + if (message.path("complete").asBoolean()) + messages.add(message.required("messageId").asText()); + snapshot.projection() + .path("tools") + .fields() + .forEachRemaining( + entry -> { + if (!"GENERATING_ARGUMENTS" + .equals(entry.getValue().path("data").path("status").asText())) + tools.add(entry.getKey()); + }); + } + + void accept(PublicEvent event) { + if ("message.completed".equals(event.type())) + messages.add(event.data().required("messageId").asText()); + if ("tool.call.updated".equals(event.type())) + tools.add(EventProjection.toolId(event.threadId(), event.turnId(), event.data())); + } + + boolean contains(LiveEvent event) { + String message = event.data().path("messageId").asText(null); + String call = event.data().path("toolCallId").asText(null); + return (message != null && messages.contains(message)) + || (call != null + && tools.contains( + EventProjection.toolId(event.threadId(), event.turnId(), call))); + } +} diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java index 5c863a1c60..ba40f7741b 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java @@ -167,7 +167,8 @@ public synchronized int poll() { if (Objects.equals(cursor, replayHighWatermark)) replayCaughtUp = true; } cursor = page.cursor(); - if (Objects.equals(cursor, replayHighWatermark)) replayCaughtUp = true; + if (Objects.equals(cursor, replayHighWatermark) + || Objects.equals(cursor, page.highWatermark())) replayCaughtUp = true; return page.events().size(); } @@ -177,9 +178,10 @@ synchronized void resynchronize() { if (closed.get()) return; snapshots.accept(snapshot); cursor = snapshot.cursor(); - replayHighWatermark = snapshot.cursor(); - replayBoundaryCaptured = true; - replayCaughtUp = true; + // Events may commit while the consumer is replacing its projection. + // Re-establish the replay boundary before releasing queued previews. + replayBoundaryCaptured = false; + replayCaughtUp = false; } boolean replayCaughtUp() { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java index 041cb9b7d4..5144ce373c 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java @@ -22,8 +22,6 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; @@ -59,8 +57,7 @@ default void reset(Snapshot snapshot) { private final EventFilter filter; private final EventPage firstPage; private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); - private final Set completedMessages = ConcurrentHashMap.newKeySet(); - private final Set completedToolCalls = ConcurrentHashMap.newKeySet(); + private final CompletedPreviews completed = new CompletedPreviews(); private final AutoCloseable liveSubscription; private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); @@ -183,9 +180,9 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { if (closed.get()) return; while (!closed.get()) { int delivered = current.poll(); + if (reset.get()) return; replayCaughtUp = replayCaughtUp || current.replayCaughtUp(); if (replayCaughtUp) delivered += drainLive(sink); - if (reset.get()) return; if (filter.threadId() != null) sink.cursor(current.cursor()); if (expired(until)) return; if (delivered == 0) { @@ -206,20 +203,14 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { } private void durable(Sink sink, PublicEvent event) { - if ("message.completed".equals(event.type())) - completedMessages.add(event.data().path("messageId").asText()); - if ("tool.call.updated".equals(event.type())) - completedToolCalls.add(event.data().path("callId").asText()); + completed.accept(event); sink.accept(event); } private int drainLive(Sink sink) { int delivered = 0; for (LiveEvent event; (event = live.poll()) != null; ) { - String messageId = event.data().path("messageId").asText(null); - if (messageId != null && completedMessages.contains(messageId)) continue; - String toolCallId = event.data().path("toolCallId").asText(null); - if (toolCallId != null && completedToolCalls.contains(toolCallId)) continue; + if (completed.contains(event)) continue; sink.live(event); delivered++; } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java index 4213720c94..c3facf7214 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java @@ -22,8 +22,6 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -60,8 +58,7 @@ public final class SessionEventSubscription implements AutoCloseable { private long retryAfter; private ScheduledFuture scheduled; private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); - private final Set completedMessages = ConcurrentHashMap.newKeySet(); - private final Set completedToolCalls = ConcurrentHashMap.newKeySet(); + private final CompletedPreviews completed = new CompletedPreviews(); private AutoCloseable liveSubscription; SessionEventSubscription( @@ -152,7 +149,10 @@ private void deliver(long token) { session, filter, initialCursor, - snapshots, + snapshot -> { + snapshots.accept(snapshot); + if (liveEvents != null) completed.reset(snapshot); + }, this::durable, this::changed); if (closed) { @@ -191,10 +191,7 @@ private void deliver(long token) { private int drainLive() { int delivered = 0; for (LiveEvent event; (event = live.poll()) != null; ) { - String messageId = event.data().path("messageId").asText(null); - if (messageId != null && completedMessages.contains(messageId)) continue; - String toolCallId = event.data().path("toolCallId").asText(null); - if (toolCallId != null && completedToolCalls.contains(toolCallId)) continue; + if (completed.contains(event)) continue; liveEvents.accept(event); delivered++; } @@ -202,10 +199,7 @@ private int drainLive() { } private void durable(PublicEvent event) { - if ("message.completed".equals(event.type())) - completedMessages.add(event.data().path("messageId").asText()); - if ("tool.call.updated".equals(event.type())) - completedToolCalls.add(event.data().path("callId").asText()); + completed.accept(event); events.accept(event); } diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java index 7e709ec91e..a4dd46b027 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java @@ -128,6 +128,27 @@ void replayBoundaryIsReachedEvenWhenTheNextPageAlsoContainsNewerEvents() { } } + @Test + void resetWaitsForFreshReplayBeforeDeliveringPreviews() { + var backend = mock(SessionBackend.class); + when(backend.wakeups()).thenReturn(Wakeups.none()); + var snapshot = mock(DurableTypes.Snapshot.class); + when(snapshot.cursor()).thenReturn("1"); + when(backend.snapshot(session)).thenReturn(snapshot); + when(backend.events(eq(session), any(), eq(100))) + .thenReturn( + new EventPage(List.of(event("2")), "2", "3"), + new EventPage(List.of(event("4")), "4", "4")); + try (var reader = new SessionEventClient(backend, session, null, s -> {}, e -> {})) { + reader.resynchronize(); + assertFalse(reader.replayCaughtUp()); + reader.poll(); + assertFalse(reader.replayCaughtUp()); + reader.poll(); + assertTrue(reader.replayCaughtUp()); + } + } + private PublicEvent event(String cursor) { return new PublicEvent( "1", diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java index 9399e0bd44..fcd5e31137 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java @@ -92,6 +92,55 @@ void defaultDurableStreamDoesNotDependOnTheLiveTransport() { } } + @Test + void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { + var completed = new CompletedPreviews(); + var snapshot = mock(DurableTypes.Snapshot.class); + when(snapshot.projection()) + .thenReturn( + DurableJson.value( + Map.of( + "messages", + Map.of( + "done", + Map.of( + "complete", + true, + "messageId", + "done"), + "partial", + Map.of( + "complete", + false, + "messageId", + "partial")), + "tools", + Map.of( + EventProjection.toolId( + "main", "turn-1", "call"), + Map.of( + "data", + Map.of("status", "RUNNING")))))); + completed.reset(snapshot); + assertTrue(completed.contains(live("message.delta", Map.of("messageId", "done")))); + assertFalse(completed.contains(live("message.delta", Map.of("messageId", "partial")))); + var preview = live("tool.arguments.delta", Map.of("toolCallId", "call")); + assertTrue(completed.contains(preview)); + assertFalse( + completed.contains( + new LiveEvent( + "1", + "next", + session, + "main", + "turn-2", + null, + null, + 2, + preview.type(), + preview.data()))); + } + private LiveEvent live(String type, Map data) { return new LiveEvent( "1", From be1a94e7826c0b46c19026abc87574925bb688db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 15:02:53 +0800 Subject: [PATCH 13/38] Scope durable live previews to the subscribed session --- .../src/main/java/io/agentscope/durable/DurableTypes.java | 4 ++++ .../java/io/agentscope/durable/SessionEventStream.java | 2 +- .../io/agentscope/durable/SessionEventSubscription.java | 2 +- .../io/agentscope/durable/SessionStreamEventTest.java | 8 ++++++++ .../protocol/public-interaction-contract.en.md | 2 ++ .../protocol/public-interaction-contract.md | 2 ++ 6 files changed, 18 insertions(+), 2 deletions(-) diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java index 3ceb82fed7..a398529481 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java @@ -696,6 +696,10 @@ public boolean matches(PublicEvent event) { return matches(event.threadId(), event.turnId(), event.runId()); } + boolean matches(SessionKey session, LiveEvent event) { + return session.equals(event.session()) && matches(event); + } + public boolean matches(LiveEvent event) { return matches(event.threadId(), event.turnId(), event.runId()); } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java index 5144ce373c..471861b915 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java @@ -79,7 +79,7 @@ default void reset(Snapshot snapshot) { .subscribe( event -> { if (!closed.get() - && filter.matches(event) + && filter.matches(session.key(), event) && options.accepts(event)) live.add(event); }); } catch (RuntimeException error) { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java index c3facf7214..59f0205d10 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java @@ -95,7 +95,7 @@ void start() { session.liveEvents() .subscribe( event -> { - if (filter.matches(event)) { + if (filter.matches(session.key(), event)) { live.add(event); changed(); } diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java index fcd5e31137..b6facff904 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java @@ -141,6 +141,14 @@ void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { preview.data()))); } + @Test + void matchingTurnCannotAdmitAnotherSessionsLivePreview() { + var filter = new EventFilter("main", "turn-1", null); + var preview = live("tool.arguments.delta", Map.of("toolCallId", "same", "text", "private")); + assertTrue(filter.matches(session, preview)); + assertFalse(filter.matches(new SessionKey("another-tenant", session.sessionId()), preview)); + } + private LiveEvent live(String type, Map data) { return new LiveEvent( "1", diff --git a/agentscope-durable/protocol/public-interaction-contract.en.md b/agentscope-durable/protocol/public-interaction-contract.en.md index cbd8b4eb91..4489955759 100644 --- a/agentscope-durable/protocol/public-interaction-contract.en.md +++ b/agentscope-durable/protocol/public-interaction-contract.en.md @@ -267,6 +267,8 @@ they do not reconstruct state from private native logs. A control receipt confir admission, while application events or the resulting Turn state confirm processing. User input does not acquire system privileges, and public events exclude private reasoning. +A client that displays an answer and crashes before saving its cursor can receive the same completion again. Upsert the answer by `messageId` within its Session for both snapshots and replay. Consumers that need an event-by-event audit must retain the events before pruning. + ## 6. Capabilities, errors and recovery Public capabilities reports operations, registered definition names and checkpoint bindings; diff --git a/agentscope-durable/protocol/public-interaction-contract.md b/agentscope-durable/protocol/public-interaction-contract.md index 825c3b57a5..b5bc000eb7 100644 --- a/agentscope-durable/protocol/public-interaction-contract.md +++ b/agentscope-durable/protocol/public-interaction-contract.md @@ -231,6 +231,8 @@ fork 在目标 Session 时间线记录目标 Thread 的恢复;继承的原生 恢复读取,必要时获取一致性快照,不需要从私有原生日志重建状态。控制回执确认已受理, 应用事件或最终 Turn 状态确认后续处理。用户输入不会获得系统权限,公共事件不包含私有推理。 +回答已显示而游标尚未持久化时,重连可能再次收到同一条完成事件。客户端应在当前 Session 内按 `messageId` 更新回答,快照与增量沿用同一身份。需要逐事件审计的消费者应在历史裁剪前自行保存事件。 + ## 6. 能力、错误与恢复 公共 capabilities 报告操作集合、已注册定义名称与 checkpoint 绑定,不枚举动态定义解析器内的所有配置。 From b40de32c2e1fd88857f518245b2c6f64eb4a17e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 15:27:10 +0800 Subject: [PATCH 14/38] Bound subscriber preview work and check committed projections by identity --- .../agentscope/durable/CompletedPreviews.java | 62 ----------------- .../io/agentscope/durable/DurableRuntime.java | 7 ++ .../io/agentscope/durable/DurableSession.java | 5 ++ .../durable/NotifyingSessionBackend.java | 6 ++ .../io/agentscope/durable/PreviewBuffer.java | 68 +++++++++++++++++++ .../io/agentscope/durable/SessionBackend.java | 8 +++ .../durable/SessionEventStream.java | 17 ++--- .../durable/SessionEventSubscription.java | 18 ++--- .../durable/TransactionalSessionBackend.java | 8 +++ .../durable/SessionStreamEventTest.java | 34 ++++++++-- .../public-interaction-contract.en.md | 2 + .../protocol/public-interaction-contract.md | 2 + 12 files changed, 142 insertions(+), 95 deletions(-) delete mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java create mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java deleted file mode 100644 index 1ce6d823c2..0000000000 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/CompletedPreviews.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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; - -import io.agentscope.durable.DurableTypes.LiveEvent; -import io.agentscope.durable.DurableTypes.PublicEvent; -import io.agentscope.durable.DurableTypes.Snapshot; -import java.util.HashSet; -import java.util.Set; - -/** Accessed by the serial delivery thread. Durable state supersedes delayed live previews. */ -final class CompletedPreviews { - private final Set messages = new HashSet<>(); - private final Set tools = new HashSet<>(); - - void reset(Snapshot snapshot) { - messages.clear(); - tools.clear(); - for (var message : snapshot.projection().path("messages")) - if (message.path("complete").asBoolean()) - messages.add(message.required("messageId").asText()); - snapshot.projection() - .path("tools") - .fields() - .forEachRemaining( - entry -> { - if (!"GENERATING_ARGUMENTS" - .equals(entry.getValue().path("data").path("status").asText())) - tools.add(entry.getKey()); - }); - } - - void accept(PublicEvent event) { - if ("message.completed".equals(event.type())) - messages.add(event.data().required("messageId").asText()); - if ("tool.call.updated".equals(event.type())) - tools.add(EventProjection.toolId(event.threadId(), event.turnId(), event.data())); - } - - boolean contains(LiveEvent event) { - String message = event.data().path("messageId").asText(null); - String call = event.data().path("toolCallId").asText(null); - return (message != null && messages.contains(message)) - || (call != null - && tools.contains( - EventProjection.toolId(event.threadId(), event.turnId(), call))); - } -} 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 631aca80aa..198dbcbbe8 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 @@ -352,6 +352,13 @@ Wakeups wakeups() { return backend == null ? Wakeups.none() : backend.wakeups(); } + List pendingPreviews(DurableSession session, List batch) { + if (backend != null) return backend.pendingPreviews(session.key(), batch); + var projection = session.snapshot().projection(); + return PreviewBuffer.pending( + batch, projection.path("messages")::get, projection.path("tools")::get); + } + LiveEvents liveEvents() { return liveEvents; } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java index 37d6e4ca39..4cfa78ab08 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java @@ -29,6 +29,7 @@ import io.agentscope.durable.DurableTypes.TurnPage; import io.agentscope.durable.DurableTypes.TurnView; import java.time.Duration; +import java.util.List; import java.util.Objects; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; @@ -51,6 +52,10 @@ Wakeups wakeups() { return runtime.wakeups(); } + List pendingPreviews(List batch) { + return runtime.pendingPreviews(this, batch); + } + LiveEvents liveEvents() { return runtime.liveEvents(); } 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 ff32df41e5..f65e3f162a 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 @@ -34,6 +34,7 @@ import io.agentscope.durable.DurableTypes.HistoryPage; import io.agentscope.durable.DurableTypes.Interaction; import io.agentscope.durable.DurableTypes.Lease; +import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.RecoveryView; @@ -391,6 +392,11 @@ public void cancel(ThreadKey session, String turnId, String requestId) { changed(session); } + @Override + public List pendingPreviews(SessionKey key, List batch) { + return delegate.pendingPreviews(key, batch); + } + @Override public Snapshot snapshot(SessionKey session) { return delegate.snapshot(session); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java new file mode 100644 index 0000000000..df543e289c --- /dev/null +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.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.durable; + +import com.fasterxml.jackson.databind.JsonNode; +import io.agentscope.durable.DurableTypes.LiveEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.function.Consumer; +import java.util.function.Function; + +/** Best-effort previews never block publishers or advance the durable cursor. */ +final class PreviewBuffer { + static final int CAPACITY = 128; + static final int BATCH = 32; + private final ArrayBlockingQueue queue = new ArrayBlockingQueue<>(CAPACITY); + + boolean offer(LiveEvent event) { + return queue.offer(event); + } + + int drain(DurableSession session, Consumer sink) { + var batch = new ArrayList(BATCH); + queue.drainTo(batch, BATCH); + if (!batch.isEmpty()) session.pendingPreviews(batch).forEach(sink); + return batch.size(); + } + + static List pending( + List events, + Function messages, + Function tools) { + return events.stream() + .filter( + event -> { + var message = event.data().path("messageId").asText(null); + if (message != null) { + var row = messages.apply(message); + if (row != null && row.path("complete").asBoolean()) return false; + } + var call = event.data().path("toolCallId").asText(null); + if (call == null) return true; + var row = + tools.apply( + EventProjection.toolId( + event.threadId(), event.turnId(), call)); + return row == null + || "GENERATING_ARGUMENTS" + .equals(row.path("data").path("status").asText()); + }) + .toList(); + } +} 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 7d63d62997..e2c431b938 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 @@ -29,6 +29,7 @@ import io.agentscope.durable.DurableTypes.Frame; import io.agentscope.durable.DurableTypes.HarnessSelector; import io.agentscope.durable.DurableTypes.Lease; +import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.RecoveryView; @@ -219,6 +220,13 @@ ModelCallPage modelCalls( Snapshot snapshot(SessionKey session); + /** Suppress previews superseded by committed facts, including facts before a saved cursor. */ + default List pendingPreviews(SessionKey session, List batch) { + var projection = snapshot(session).projection(); + return PreviewBuffer.pending( + batch, projection.path("messages")::get, projection.path("tools")::get); + } + EventPage events(SessionKey session, String cursor, int limit); List checkpoints(ThreadKey session, long after, int limit); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java index 471861b915..c3ab3941ca 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java @@ -22,7 +22,6 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; @@ -56,8 +55,7 @@ default void reset(Snapshot snapshot) { private final DurableSession session; private final EventFilter filter; private final EventPage firstPage; - private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); - private final CompletedPreviews completed = new CompletedPreviews(); + private final PreviewBuffer live = new PreviewBuffer(); private final AutoCloseable liveSubscription; private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); @@ -80,7 +78,7 @@ default void reset(Snapshot snapshot) { event -> { if (!closed.get() && filter.matches(session.key(), event) - && options.accepts(event)) live.add(event); + && options.accepts(event)) live.offer(event); }); } catch (RuntimeException error) { logLiveFailure(error); @@ -181,7 +179,7 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { while (!closed.get()) { int delivered = current.poll(); if (reset.get()) return; - replayCaughtUp = replayCaughtUp || current.replayCaughtUp(); + replayCaughtUp = current.replayCaughtUp(); if (replayCaughtUp) delivered += drainLive(sink); if (filter.threadId() != null) sink.cursor(current.cursor()); if (expired(until)) return; @@ -203,18 +201,11 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { } private void durable(Sink sink, PublicEvent event) { - completed.accept(event); sink.accept(event); } private int drainLive(Sink sink) { - int delivered = 0; - for (LiveEvent event; (event = live.poll()) != null; ) { - if (completed.contains(event)) continue; - sink.live(event); - delivered++; - } - return delivered; + return live.drain(session, sink::live); } private static boolean expired(long until) { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java index 59f0205d10..a39edd5d7b 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java @@ -22,7 +22,6 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -57,8 +56,7 @@ public final class SessionEventSubscription implements AutoCloseable { private long generation; private long retryAfter; private ScheduledFuture scheduled; - private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); - private final CompletedPreviews completed = new CompletedPreviews(); + private final PreviewBuffer live = new PreviewBuffer(); private AutoCloseable liveSubscription; SessionEventSubscription( @@ -95,8 +93,8 @@ void start() { session.liveEvents() .subscribe( event -> { - if (filter.matches(session.key(), event)) { - live.add(event); + if (filter.matches(session.key(), event) + && live.offer(event)) { changed(); } }); @@ -151,7 +149,6 @@ private void deliver(long token) { initialCursor, snapshot -> { snapshots.accept(snapshot); - if (liveEvents != null) completed.reset(snapshot); }, this::durable, this::changed); @@ -189,17 +186,10 @@ private void deliver(long token) { } private int drainLive() { - int delivered = 0; - for (LiveEvent event; (event = live.poll()) != null; ) { - if (completed.contains(event)) continue; - liveEvents.accept(event); - delivered++; - } - return delivered; + return live.drain(session, liveEvents); } private void durable(PublicEvent event) { - completed.accept(event); events.accept(event); } 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 c9d9ca8562..733852e2ff 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 @@ -41,6 +41,7 @@ import io.agentscope.durable.DurableTypes.Interaction; import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.Lifecycle; +import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.PublicEvent; @@ -2303,6 +2304,13 @@ private static void cancel(State s, String turnId, String requestId) { } } + @Override + public List pendingPreviews(SessionKey key, List batch) { + return change( + key, + (s, now) -> PreviewBuffer.pending(batch, s.messages::get, s.projectedTools::get)); + } + @Override public Snapshot snapshot(SessionKey key) { return change( diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java index b6facff904..1b1bb20d01 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java @@ -94,7 +94,7 @@ void defaultDurableStreamDoesNotDependOnTheLiveTransport() { @Test void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { - var completed = new CompletedPreviews(); + var snapshot = mock(DurableTypes.Snapshot.class); when(snapshot.projection()) .thenReturn( @@ -121,13 +121,19 @@ void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { Map.of( "data", Map.of("status", "RUNNING")))))); - completed.reset(snapshot); - assertTrue(completed.contains(live("message.delta", Map.of("messageId", "done")))); - assertFalse(completed.contains(live("message.delta", Map.of("messageId", "partial")))); + java.util.function.Predicate superseded = + e -> + PreviewBuffer.pending( + List.of(e), + snapshot.projection().path("messages")::get, + snapshot.projection().path("tools")::get) + .isEmpty(); + assertTrue(superseded.test(live("message.delta", Map.of("messageId", "done")))); + assertFalse(superseded.test(live("message.delta", Map.of("messageId", "partial")))); var preview = live("tool.arguments.delta", Map.of("toolCallId", "call")); - assertTrue(completed.contains(preview)); + assertTrue(superseded.test(preview)); assertFalse( - completed.contains( + superseded.test( new LiveEvent( "1", "next", @@ -141,6 +147,22 @@ void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { preview.data()))); } + @Test + void previewOverflowDropsOnlyBestEffortDataAndOneDrainYieldsAfterOneBatch() { + var buffer = new PreviewBuffer(); + var event = live("tool.arguments.delta", Map.of("toolCallId", "call", "text", "delta")); + for (int i = 0; i < PreviewBuffer.CAPACITY; i++) assertTrue(buffer.offer(event)); + assertFalse(buffer.offer(event)); + var session = mock(DurableSession.class); + when(session.pendingPreviews(any())).thenAnswer(invocation -> invocation.getArgument(0)); + var delivered = new java.util.concurrent.atomic.AtomicInteger(); + assertEquals( + PreviewBuffer.BATCH, buffer.drain(session, ignored -> delivered.incrementAndGet())); + assertEquals(PreviewBuffer.BATCH, delivered.get()); + for (int i = 0; i < PreviewBuffer.BATCH; i++) assertTrue(buffer.offer(event)); + assertFalse(buffer.offer(event)); + } + @Test void matchingTurnCannotAdmitAnotherSessionsLivePreview() { var filter = new EventFilter("main", "turn-1", null); diff --git a/agentscope-durable/protocol/public-interaction-contract.en.md b/agentscope-durable/protocol/public-interaction-contract.en.md index 4489955759..c87d51035c 100644 --- a/agentscope-durable/protocol/public-interaction-contract.en.md +++ b/agentscope-durable/protocol/public-interaction-contract.en.md @@ -269,6 +269,8 @@ User input does not acquire system privileges, and public events exclude private A client that displays an answer and crashes before saving its cursor can receive the same completion again. Upsert the answer by `messageId` within its Session for both snapshots and replay. Consumers that need an event-by-event audit must retain the events before pruning. +Each subscription buffers up to 128 live previews and processes up to 32 per poll. A full queue drops incoming previews. Committed events continue through backend paging. Delivery checks each preview against the current message or tool projection, including completions before the subscription cursor. Callbacks share `observerParallelism` execution slots (default 2). Each blocked callback occupies one slot. + ## 6. Capabilities, errors and recovery Public capabilities reports operations, registered definition names and checkpoint bindings; diff --git a/agentscope-durable/protocol/public-interaction-contract.md b/agentscope-durable/protocol/public-interaction-contract.md index b5bc000eb7..5b5a3c115b 100644 --- a/agentscope-durable/protocol/public-interaction-contract.md +++ b/agentscope-durable/protocol/public-interaction-contract.md @@ -233,6 +233,8 @@ fork 在目标 Session 时间线记录目标 Thread 的恢复;继承的原生 回答已显示而游标尚未持久化时,重连可能再次收到同一条完成事件。客户端应在当前 Session 内按 `messageId` 更新回答,快照与增量沿用同一身份。需要逐事件审计的消费者应在历史裁剪前自行保存事件。 +每个订阅最多缓存 128 条实时预览,每轮最多处理 32 条。队列满时丢弃新预览;已提交事件继续通过后端分页交付。投递预览前按消息或工具身份核对当前持久化投影,包括在订阅游标之前已经完成的对象。回调共享 `observerParallelism` 个执行槽(默认 2),每个阻塞回调占用一个槽。 + ## 6. 能力、错误与恢复 公共 capabilities 报告操作集合、已注册定义名称与 checkpoint 绑定,不枚举动态定义解析器内的所有配置。 From 071e70047f0ede2414d11a112d2a12727b0e07c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 15:37:39 +0800 Subject: [PATCH 15/38] Read preview projections without rewriting session state --- .../durable/SessionEventStream.java | 16 ++++------------ .../durable/SessionEventSubscription.java | 19 ++----------------- .../durable/TransactionalSessionBackend.java | 12 +++++++++--- 3 files changed, 15 insertions(+), 32 deletions(-) diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java index c3ab3941ca..3305f55aa9 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java @@ -157,10 +157,10 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { try { for (var event : firstPage.events()) { if (closed.get()) return; - durable(sink, event); + sink.accept(event); } boolean replayCaughtUp = Objects.equals(firstPage.cursor(), firstPage.highWatermark()); - if (replayCaughtUp) drainLive(sink); + if (replayCaughtUp) live.drain(session, sink::live); if (filter.threadId() != null) sink.cursor(firstPage.cursor()); if (closed.get() || expired(until)) return; var reset = new AtomicBoolean(); @@ -173,14 +173,14 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { reset.set(true); sink.reset(snapshot); }, - event -> durable(sink, event)); + sink); reader = current; if (closed.get()) return; while (!closed.get()) { int delivered = current.poll(); if (reset.get()) return; replayCaughtUp = current.replayCaughtUp(); - if (replayCaughtUp) delivered += drainLive(sink); + if (replayCaughtUp) delivered += live.drain(session, sink::live); if (filter.threadId() != null) sink.cursor(current.cursor()); if (expired(until)) return; if (delivered == 0) { @@ -200,14 +200,6 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { } } - private void durable(Sink sink, PublicEvent event) { - sink.accept(event); - } - - private int drainLive(Sink sink) { - return live.drain(session, sink::live); - } - private static boolean expired(long until) { return until != 0 && until - System.nanoTime() <= 0; } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java index a39edd5d7b..d974933017 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java @@ -144,14 +144,7 @@ private void deliver(long token) { if (reader == null) { reader = new SessionEventClient( - session, - filter, - initialCursor, - snapshot -> { - snapshots.accept(snapshot); - }, - this::durable, - this::changed); + session, filter, initialCursor, snapshots, events, this::changed); if (closed) { reader.close(); return; @@ -163,7 +156,7 @@ private void deliver(long token) { } if (closed) return; if (reader.poll() > 0) delay = 0; - if (reader.replayCaughtUp() && drainLive() > 0) delay = 0; + if (reader.replayCaughtUp() && live.drain(session, liveEvents) > 0) delay = 0; lastFailure = null; } catch (RuntimeException error) { failed = true; @@ -185,14 +178,6 @@ private void deliver(long token) { } } - private int drainLive() { - return live.drain(session, liveEvents); - } - - private void durable(PublicEvent event) { - events.accept(event); - } - /** Last successfully acknowledged cursor; persist event/snapshot cursors inside callbacks. */ public String cursor() { var current = reader; 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 733852e2ff..de7422102c 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 @@ -2306,9 +2306,15 @@ private static void cancel(State s, String turnId, String requestId) { @Override public List pendingPreviews(SessionKey key, List batch) { - return change( - key, - (s, now) -> PreviewBuffer.pending(batch, s.messages::get, s.projectedTools::get)); + return store.transaction( + key.storageKey(), + tx -> { + var state = load(tx); + if (!key.equals(state.session.key())) + throw error(DurableException.Code.CONFLICT, "Session key mismatch"); + return PreviewBuffer.pending( + batch, state.messages::get, state.projectedTools::get); + }); } @Override From cbff92dbb9977f492b9e93c99483b7c0d69f9f8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 15:46:27 +0800 Subject: [PATCH 16/38] Bound preview payloads and query versioned identities across HTTP --- .../io/agentscope/durable/DurableJson.java | 30 ++++ .../agentscope/durable/DurableOperations.java | 8 + .../io/agentscope/durable/DurableRuntime.java | 19 ++- .../io/agentscope/durable/DurableTypes.java | 32 ++++ .../durable/NotifyingSessionBackend.java | 6 +- .../io/agentscope/durable/PreviewBuffer.java | 33 +--- .../io/agentscope/durable/SessionBackend.java | 8 +- .../durable/TransactionalSessionBackend.java | 11 +- .../durable/SessionStreamEventTest.java | 45 +++++- .../contract/SessionBackendContract.java | 9 ++ .../durable/contract/UserApiContract.java | 31 ++++ .../public-interaction-contract.en.md | 4 +- .../protocol/public-interaction-contract.md | 4 +- agentscope-durable/protocol/schema.json | 148 ++++++++++++++++++ .../durable/http/HttpSessionBackend.java | 9 ++ .../durable/http/SessionBackendHandler.java | 12 ++ 16 files changed, 357 insertions(+), 52 deletions(-) diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java index d39c652055..8b442cb8a9 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java @@ -51,6 +51,36 @@ public static JsonNode value(Object value) { return MAPPER.valueToTree(value); } + /** Check a best-effort payload limit without allocating its full serialized representation. */ + static boolean fitsEncodedLimit(Object value, int maxBytes) { + var counter = + new java.io.OutputStream() { + private int remaining = maxBytes; + + @Override + public void write(int value) throws IOException { + consume(1); + } + + @Override + public void write(byte[] bytes, int offset, int length) throws IOException { + consume(length); + } + + private void consume(int bytes) throws IOException { + if (bytes > remaining) + throw new IOException("Preview exceeds its encoded size limit"); + remaining -= bytes; + } + }; + try { + MAPPER.writeValue(counter, value); + return true; + } catch (IOException invalidOrOversized) { + return false; + } + } + public static JsonNode copy(JsonNode value) { return value == null ? NullNode.instance : value.deepCopy(); } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java index 96949c521b..cfbefd0801 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java @@ -51,6 +51,7 @@ final class DurableOperations { "control", "interactions", "snapshot", + "previewEligibility", "events", "checkpoints", "restore", @@ -137,6 +138,13 @@ JsonNode invoke(DurableProtocol.Request request) { thread, DurableJson.convert(p.get("command"), ControlCommand.class)); case "interactions" -> backend.interactions(thread, p.path("turnId").asText()); + case "previewEligibility" -> + backend.previewEligibility( + key, + List.of( + DurableJson.convert( + p.required("identities"), + DurableTypes.PreviewIdentity[].class))); case "snapshot" -> filter(key, p).select(backend.snapshot(key)); case "events" -> filter(key, p) 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 198dbcbbe8..4aa933966e 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 @@ -353,10 +353,21 @@ Wakeups wakeups() { } List pendingPreviews(DurableSession session, List batch) { - if (backend != null) return backend.pendingPreviews(session.key(), batch); - var projection = session.snapshot().projection(); - return PreviewBuffer.pending( - batch, projection.path("messages")::get, projection.path("tools")::get); + var identities = batch.stream().map(DurableTypes.PreviewIdentity::of).toList(); + List eligible = + backend != null + ? backend.previewEligibility(session.key(), identities) + : List.of( + DurableJson.convert( + session.call( + "previewEligibility", "identities", identities), + Boolean[].class)); + if (eligible.size() != batch.size()) + throw new DurableException( + DurableException.Code.INCOMPATIBLE, "Preview response length differs"); + var pending = new java.util.ArrayList(); + for (int i = 0; i < eligible.size(); i++) if (eligible.get(i)) pending.add(batch.get(i)); + return pending; } LiveEvents liveEvents() { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java index a398529481..c46de28ff6 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java @@ -625,6 +625,38 @@ public record PublicEvent( String type, JsonNode data) {} + /** Durable projection keys for one best-effort preview. */ + public record PreviewIdentity(String messageId, String toolKey, long attempt, long revision) { + static PreviewIdentity of(LiveEvent event) { + var call = event.data().path("toolCallId").asText(null); + return new PreviewIdentity( + event.data().path("messageId").asText(null), + call == null + ? null + : EventProjection.toolId(event.threadId(), event.turnId(), call), + event.data().path("attempt").asLong(), + event.data().path("revision").asLong()); + } + + boolean pending( + java.util.function.Function messages, + java.util.function.Function tools) { + var message = messageId == null ? null : messages.apply(messageId); + if (message != null && (message.path("complete").asBoolean() || olderThan(message))) + return false; + var tool = toolKey == null ? null : tools.apply(toolKey); + return tool == null + || ("GENERATING_ARGUMENTS".equals(tool.path("data").path("status").asText()) + && !olderThan(tool.path("data"))); + } + + private boolean olderThan(JsonNode projection) { + var currentAttempt = projection.path("attempt").asLong(); + return attempt < currentAttempt + || attempt == currentAttempt && revision < projection.path("revision").asLong(); + } + } + /** * Best-effort live presentation signal. Live events have no durable sequence or cursor and are * never returned by event history or included in snapshots. 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 f65e3f162a..23d6db1a08 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 @@ -34,9 +34,9 @@ import io.agentscope.durable.DurableTypes.HistoryPage; import io.agentscope.durable.DurableTypes.Interaction; import io.agentscope.durable.DurableTypes.Lease; -import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; +import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -393,8 +393,8 @@ public void cancel(ThreadKey session, String turnId, String requestId) { } @Override - public List pendingPreviews(SessionKey key, List batch) { - return delegate.pendingPreviews(key, batch); + public List previewEligibility(SessionKey key, List identities) { + return delegate.previewEligibility(key, identities); } @Override diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java index df543e289c..f6c4ee7778 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java @@ -16,22 +16,22 @@ package io.agentscope.durable; -import com.fasterxml.jackson.databind.JsonNode; import io.agentscope.durable.DurableTypes.LiveEvent; import java.util.ArrayList; -import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.function.Consumer; -import java.util.function.Function; /** Best-effort previews never block publishers or advance the durable cursor. */ final class PreviewBuffer { static final int CAPACITY = 128; + static final int MAX_ENCODED_BYTES = 64 * 1024; static final int BATCH = 32; private final ArrayBlockingQueue queue = new ArrayBlockingQueue<>(CAPACITY); boolean offer(LiveEvent event) { - return queue.offer(event); + return queue.remainingCapacity() > 0 + && DurableJson.fitsEncodedLimit(event, MAX_ENCODED_BYTES) + && queue.offer(event); } int drain(DurableSession session, Consumer sink) { @@ -40,29 +40,4 @@ int drain(DurableSession session, Consumer sink) { if (!batch.isEmpty()) session.pendingPreviews(batch).forEach(sink); return batch.size(); } - - static List pending( - List events, - Function messages, - Function tools) { - return events.stream() - .filter( - event -> { - var message = event.data().path("messageId").asText(null); - if (message != null) { - var row = messages.apply(message); - if (row != null && row.path("complete").asBoolean()) return false; - } - var call = event.data().path("toolCallId").asText(null); - if (call == null) return true; - var row = - tools.apply( - EventProjection.toolId( - event.threadId(), event.turnId(), call)); - return row == null - || "GENERATING_ARGUMENTS" - .equals(row.path("data").path("status").asText()); - }) - .toList(); - } } 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 e2c431b938..9db421277b 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 @@ -29,9 +29,9 @@ import io.agentscope.durable.DurableTypes.Frame; import io.agentscope.durable.DurableTypes.HarnessSelector; import io.agentscope.durable.DurableTypes.Lease; -import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; +import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -221,11 +221,7 @@ ModelCallPage modelCalls( Snapshot snapshot(SessionKey session); /** Suppress previews superseded by committed facts, including facts before a saved cursor. */ - default List pendingPreviews(SessionKey session, List batch) { - var projection = snapshot(session).projection(); - return PreviewBuffer.pending( - batch, projection.path("messages")::get, projection.path("tools")::get); - } + List previewEligibility(SessionKey session, List identities); EventPage events(SessionKey session, String cursor, int limit); 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 de7422102c..34f4a1a8bf 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 @@ -41,9 +41,9 @@ import io.agentscope.durable.DurableTypes.Interaction; import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.Lifecycle; -import io.agentscope.durable.DurableTypes.LiveEvent; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; +import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.PublicEvent; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; @@ -2305,15 +2305,18 @@ private static void cancel(State s, String turnId, String requestId) { } @Override - public List pendingPreviews(SessionKey key, List batch) { + public List previewEligibility(SessionKey key, List identities) { + if (identities.size() > PreviewBuffer.BATCH) + throw error(DurableException.Code.INVALID, "Too many preview identities"); return store.transaction( key.storageKey(), tx -> { var state = load(tx); if (!key.equals(state.session.key())) throw error(DurableException.Code.CONFLICT, "Session key mismatch"); - return PreviewBuffer.pending( - batch, state.messages::get, state.projectedTools::get); + return identities.stream() + .map(id -> id.pending(state.messages::get, state.projectedTools::get)) + .toList(); }); } diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java index 1b1bb20d01..f6b58ce518 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java @@ -123,11 +123,10 @@ void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { Map.of("status", "RUNNING")))))); java.util.function.Predicate superseded = e -> - PreviewBuffer.pending( - List.of(e), + !DurableTypes.PreviewIdentity.of(e) + .pending( snapshot.projection().path("messages")::get, - snapshot.projection().path("tools")::get) - .isEmpty(); + snapshot.projection().path("tools")::get); assertTrue(superseded.test(live("message.delta", Map.of("messageId", "done")))); assertFalse(superseded.test(live("message.delta", Map.of("messageId", "partial")))); var preview = live("tool.arguments.delta", Map.of("toolCallId", "call")); @@ -147,10 +146,48 @@ void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { preview.data()))); } + @Test + void earlierAttemptAndRevisionCannotOverwriteAnActivePreview() { + var partial = DurableJson.value(Map.of("complete", false, "attempt", 2, "revision", 4)); + var tool = + DurableJson.value( + Map.of( + "data", + Map.of( + "status", + "GENERATING_ARGUMENTS", + "attempt", + 2, + "revision", + 4))); + for (var ref : List.of(Map.of("messageId", "msg"), Map.of("toolCallId", "call"))) { + var fields = new java.util.HashMap(ref); + fields.put("attempt", 1); + fields.put("revision", 20); + assertFalse( + DurableTypes.PreviewIdentity.of(live("message.delta", fields)) + .pending(k -> partial, k -> tool)); + fields.put("attempt", 2); + fields.put("revision", 3); + assertFalse( + DurableTypes.PreviewIdentity.of(live("message.delta", fields)) + .pending(k -> partial, k -> tool)); + fields.put("revision", 4); + assertTrue( + DurableTypes.PreviewIdentity.of(live("message.delta", fields)) + .pending(k -> partial, k -> tool)); + } + } + @Test void previewOverflowDropsOnlyBestEffortDataAndOneDrainYieldsAfterOneBatch() { var buffer = new PreviewBuffer(); var event = live("tool.arguments.delta", Map.of("toolCallId", "call", "text", "delta")); + assertFalse( + buffer.offer( + live( + "tool.arguments.delta", + Map.of("toolCallId", "large", "text", "界".repeat(24_000))))); for (int i = 0; i < PreviewBuffer.CAPACITY; i++) assertTrue(buffer.offer(event)); assertFalse(buffer.offer(event)); var session = mock(DurableSession.class); 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 e338a41aec..10109f2c09 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 @@ -3279,6 +3279,15 @@ protected void cursorsAreSessionBoundAndSnapshotSurvivesRetention() { backend.pruneEvents(key, snapshot.cursor()); code(DurableException.Code.CURSOR_EXPIRED, () -> backend.events(key, old, 10)); assertTrue(backend.events(key, snapshot.cursor(), 10).events().isEmpty()); + assertEquals( + List.of(false, true), + backend.previewEligibility( + key, + List.of( + new io.agentscope.durable.DurableTypes.PreviewIdentity( + "m", null, 0, 0), + new io.agentscope.durable.DurableTypes.PreviewIdentity( + "uncommitted", null, 0, 0)))); SessionKey other = new SessionKey("other", "session"); backend.create( new SessionSpec( diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java index 5204282397..09ecff5d4c 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java @@ -492,6 +492,37 @@ private void checkpoint( null)); } + @Test + void previewLookupReturnsOnlyOrderedFlagsForTheRequestedIdentities() { + session.submit("preview-input", "hello"); + var saved = session.snapshot().projection().required("messages").fieldNames().next(); + var requested = + List.of( + new io.agentscope.durable.DurableTypes.PreviewIdentity(saved, null, 0, 0), + new io.agentscope.durable.DurableTypes.PreviewIdentity( + null, "unknown", 0, 0)); + var lookup = + new DurableProtocol.Request( + DurableProtocol.VERSION, + "previewEligibility", + DurableJson.value(Map.of("session", key, "identities", requested))); + assertEquals(DurableJson.value(List.of(false, true)), api.invoke(lookup)); + code( + DurableException.Code.INVALID, + () -> + api.invoke( + new DurableProtocol.Request( + DurableProtocol.VERSION, + "previewEligibility", + DurableJson.value( + Map.of( + "session", + key, + "identities", + java.util.Collections.nCopies( + 33, requested.get(0))))))); + } + @Test void languageNeutralWorkflowMatchesLocalAndHttpBindings() throws Exception { try (var input = diff --git a/agentscope-durable/protocol/public-interaction-contract.en.md b/agentscope-durable/protocol/public-interaction-contract.en.md index c87d51035c..b917abee3b 100644 --- a/agentscope-durable/protocol/public-interaction-contract.en.md +++ b/agentscope-durable/protocol/public-interaction-contract.en.md @@ -269,7 +269,9 @@ User input does not acquire system privileges, and public events exclude private A client that displays an answer and crashes before saving its cursor can receive the same completion again. Upsert the answer by `messageId` within its Session for both snapshots and replay. Consumers that need an event-by-event audit must retain the events before pruning. -Each subscription buffers up to 128 live previews and processes up to 32 per poll. A full queue drops incoming previews. Committed events continue through backend paging. Delivery checks each preview against the current message or tool projection, including completions before the subscription cursor. Callbacks share `observerParallelism` execution slots (default 2). Each blocked callback occupies one slot. +Each subscription buffers up to 128 live previews and processes up to 32 per poll. A full queue drops incoming previews. A preview larger than 64 KiB of encoded JSON is also dropped. Committed events continue through backend paging. Delivery checks each preview against the current message or tool projection, including completions before the subscription cursor. Callbacks share `observerParallelism` execution slots (default 2). Each blocked callback occupies one slot. + +The Session-scoped `previewEligibility` operation checks up to 32 identities and returns booleans in input order. Clients send only `messageId`, the projection’s `toolKey`, `attempt` and `revision`. ## 6. Capabilities, errors and recovery diff --git a/agentscope-durable/protocol/public-interaction-contract.md b/agentscope-durable/protocol/public-interaction-contract.md index 5b5a3c115b..e48c7596d6 100644 --- a/agentscope-durable/protocol/public-interaction-contract.md +++ b/agentscope-durable/protocol/public-interaction-contract.md @@ -233,7 +233,9 @@ fork 在目标 Session 时间线记录目标 Thread 的恢复;继承的原生 回答已显示而游标尚未持久化时,重连可能再次收到同一条完成事件。客户端应在当前 Session 内按 `messageId` 更新回答,快照与增量沿用同一身份。需要逐事件审计的消费者应在历史裁剪前自行保存事件。 -每个订阅最多缓存 128 条实时预览,每轮最多处理 32 条。队列满时丢弃新预览;已提交事件继续通过后端分页交付。投递预览前按消息或工具身份核对当前持久化投影,包括在订阅游标之前已经完成的对象。回调共享 `observerParallelism` 个执行槽(默认 2),每个阻塞回调占用一个槽。 +每个订阅最多缓存 128 条实时预览,每轮最多处理 32 条。队列满或单条预览的 UTF-8 JSON 编码超过 64 KiB 时丢弃该预览;已提交事件继续通过后端分页交付。投递预览前按消息或工具身份核对当前持久化投影,包括在订阅游标之前已经完成的对象。回调共享 `observerParallelism` 个执行槽(默认 2),每个阻塞回调占用一个槽。 + +`previewEligibility` 在 Session 范围按输入顺序返回最多 32 个布尔值。客户端只发送 `messageId`、投影中的 `toolKey`、`attempt` 和 `revision`,无需下载历史快照。 ## 6. 能力、错误与恢复 diff --git a/agentscope-durable/protocol/schema.json b/agentscope-durable/protocol/schema.json index 706d4ac376..2f87bcb276 100644 --- a/agentscope-durable/protocol/schema.json +++ b/agentscope-durable/protocol/schema.json @@ -4515,6 +4515,9 @@ }, { "$ref": "#/$defs/backend_cancelDelegationRequest" + }, + { + "$ref": "#/$defs/backend_previewEligibilityRequest" } ] }, @@ -8105,6 +8108,9 @@ }, { "$ref": "#/$defs/user_listModelCallsRequest" + }, + { + "$ref": "#/$defs/user_previewEligibilityRequest" } ] }, @@ -11804,6 +11810,148 @@ "$ref": "#/$defs/delegationView" } } + }, + "user_previewEligibilityRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "operation", + "payload" + ], + "properties": { + "version": { + "const": "durable.v1" + }, + "operation": { + "const": "previewEligibility" + }, + "payload": { + "type": "object", + "additionalProperties": false, + "required": [ + "session", + "identities" + ], + "properties": { + "session": { + "$ref": "#/$defs/session" + }, + "identities": { + "$ref": "#/$defs/previewIdentities" + } + } + } + } + }, + "user_previewEligibilityResponse": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "result" + ], + "properties": { + "version": { + "const": "durable.v1" + }, + "result": { + "type": "array", + "maxItems": 32, + "items": { + "type": "boolean" + } + } + } + }, + "backend_previewEligibilityRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "operation", + "payload" + ], + "properties": { + "version": { + "const": "durable.v1" + }, + "operation": { + "const": "previewEligibility" + }, + "payload": { + "type": "object", + "additionalProperties": false, + "required": [ + "session", + "identities" + ], + "properties": { + "session": { + "$ref": "#/$defs/session" + }, + "identities": { + "$ref": "#/$defs/previewIdentities" + } + } + } + } + }, + "backend_previewEligibilityResponse": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "result" + ], + "properties": { + "version": { + "const": "durable.v1" + }, + "result": { + "type": "array", + "maxItems": 32, + "items": { + "type": "boolean" + } + } + } + }, + "previewIdentities": { + "type": "array", + "maxItems": 32, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "messageId", + "toolKey", + "attempt", + "revision" + ], + "properties": { + "messageId": { + "type": [ + "string", + "null" + ] + }, + "toolKey": { + "type": [ + "string", + "null" + ] + }, + "attempt": { + "type": "integer", + "minimum": 0 + }, + "revision": { + "type": "integer", + "minimum": 0 + } + } + } } } } 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 19fa2c71ce..1277bb53f6 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 @@ -38,6 +38,7 @@ import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; +import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -442,6 +443,14 @@ public void cancel(ThreadKey session, String turnId, String requestId) { call("cancel", "thread", session, "turnId", turnId, "requestId", requestId); } + @Override + public List previewEligibility(SessionKey key, List identities) { + return List.of( + as( + call("previewEligibility", "session", key, "identities", identities), + Boolean[].class)); + } + @Override public Snapshot snapshot(SessionKey session) { return as(call("snapshot", "session", session), Snapshot.class); 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 dce6163fe3..39b9cf3e5a 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 @@ -305,6 +305,18 @@ public void handle(HttpExchange exchange) throws IOException { backend.cancel(thread, text(p, "turnId"), text(p, "requestId")); result = null; } + case "previewEligibility" -> + result = + backend.previewEligibility( + key, + List.of( + get( + p, + "identities", + io.agentscope.durable.DurableTypes + .PreviewIdentity + [] + .class))); case "snapshot" -> result = backend.snapshot(key); case "events" -> result = From ca8fb3c8e5766a6d0a823d406c2b38d7d4a3430b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 15:54:00 +0800 Subject: [PATCH 17/38] Exercise bounded subscribers and crash recovery against Docker PostgreSQL and RocketMQ --- agentscope-durable/README.md | 15 + agentscope-durable/protocol/README.md | 2 + .../scripts/docker-regression/AckGate.java | 43 ++ .../docker-regression/CheckpointGate.java | 56 ++ .../docker-regression/LongHistory.java | 154 +++++ .../scripts/docker-regression/Probe.java | 240 +++++++ .../scripts/docker-regression/Subscriber.java | 254 ++++++++ .../scripts/docker-regression/run.py | 588 ++++++++++++++++++ 8 files changed, 1352 insertions(+) create mode 100644 agentscope-durable/scripts/docker-regression/AckGate.java create mode 100644 agentscope-durable/scripts/docker-regression/CheckpointGate.java create mode 100644 agentscope-durable/scripts/docker-regression/LongHistory.java create mode 100644 agentscope-durable/scripts/docker-regression/Probe.java create mode 100644 agentscope-durable/scripts/docker-regression/Subscriber.java create mode 100755 agentscope-durable/scripts/docker-regression/run.py diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index a1216a92d4..70226f9c17 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -448,6 +448,21 @@ make -C agentscope-durable check make -C agentscope-durable independent ``` +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 creates a private Docker network with PostgreSQL, +RocketMQ, independent Brain and Hands JVMs, a counting model endpoint and subscription clients. +It disconnects receivers before ACK, kills the model requester and checkpoint writer, and +reconnects a subscriber during pruning. A blocked subscriber competes with a healthy subscriber +for 4,096 previews. A separate long Thread commits 2,048 message completions, prunes the log and injects delayed previews. 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, displayed answers and subscriber cursors. The runner removes its containers, +volumes and network on exit. Set `ROCKETMQ_IMAGE` to use a locally available RocketMQ 5 image +with the broker proxy and `mqadmin` tools. + Normal checking covers build, formatting and tests. Isolation checking builds source dependencies in a separate Maven cache and audits dependency trees. Validate broker delivery, provider query/cancel diff --git a/agentscope-durable/protocol/README.md b/agentscope-durable/protocol/README.md index 5f319b544e..5be3bd6d23 100644 --- a/agentscope-durable/protocol/README.md +++ b/agentscope-durable/protocol/README.md @@ -218,6 +218,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 | @@ -260,6 +261,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 | diff --git a/agentscope-durable/scripts/docker-regression/AckGate.java b/agentscope-durable/scripts/docker-regression/AckGate.java new file mode 100644 index 0000000000..52e8593920 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/AckGate.java @@ -0,0 +1,43 @@ +/* + * 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; + +/** Compiled into the test copy of the receiver immediately around its real ACK. */ +final class AckGate { + static void observe(JsonNode envelope, MessageView message, boolean acknowledged) + throws InterruptedException { + String kind; + if ("EXECUTE".equals(envelope.path("kind").asText())) kind = "command"; + else if ("SUCCEEDED".equals(envelope.path("result").path("state").asText())) + kind = "result"; + else return; + System.out.printf( + "%s %s %s %d %s%n", + acknowledged ? "ACK" : "BEFORE", + kind, + message.getMessageId(), + message.getDeliveryAttempt(), + envelope.path("request").path("turnId").asText()); + while (!acknowledged && Files.exists(Path.of("/tmp/hold-" + kind))) Thread.sleep(50); + } +} diff --git a/agentscope-durable/scripts/docker-regression/CheckpointGate.java b/agentscope-durable/scripts/docker-regression/CheckpointGate.java new file mode 100644 index 0000000000..c4b0b21181 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/CheckpointGate.java @@ -0,0 +1,56 @@ +/* + * 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 switching = new ThreadLocal<>(); + + static void written(String part, JsonNode value) { + if (PHASE == null || !part.endsWith(":checkpoint") || value == null) return; + var pointer = value.path("inline"); + if (pointer.path("recoveryCursor").asLong() + > Long.parseLong(System.getenv("BASE_CURSOR"))) { + switching.set(true); + stopAt("cursor"); + } else if (pointer.path("position").asLong() + > Long.parseLong(System.getenv("BASE_POSITION"))) { + stopAt("snapshot"); + } + } + + static void committed() { + if (Boolean.TRUE.equals(switching.get())) { + switching.remove(); + stopAt("ack"); + } + } + + 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/LongHistory.java b/agentscope-durable/scripts/docker-regression/LongHistory.java new file mode 100644 index 0000000000..aa19933701 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/LongHistory.java @@ -0,0 +1,154 @@ +/* + * 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.durable.DurableJson; +import io.agentscope.durable.DurableRuntime; +import io.agentscope.durable.DurableTypes.*; +import io.agentscope.durable.EventStreamOptions; +import io.agentscope.durable.LiveEvents; +import io.agentscope.durable.SessionStreamEvent; +import io.agentscope.extensions.durable.jdbc.PostgresBackend; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +public class LongHistory { + public static void main(String[] args) throws Exception { + var key = new SessionKey("regression", "long-history"); + var bus = LiveEvents.local(); + try (var backend = PostgresBackend.builder().dataSource(Probe.database()).build(); + var runtime = DurableRuntime.builder().backend(backend).liveEvents(bus).build()) { + backend.create(new SessionSpec(key, new ThreadBinding("history", "1", "1"), null)); + var thread = new ThreadKey(key, "main"); + var turn = backend.submit(thread, "history", DurableJson.value("history")).turnId(); + var lease = + backend.claim(thread, "history-writer", Duration.ofMinutes(5)).orElseThrow(); + var session = runtime.getSession(key); + var options = + EventStreamOptions.builder() + .after(session.snapshot().cursor()) + .deltas(EventStreamOptions.EventDeltaType.MESSAGE) + .build(); + int total = 2048; + var delivered = new CountDownLatch(total); + var positive = new CountDownLatch(1); + var stale = new AtomicInteger(); + try (var observer = + session.subscribeEvents( + options, + event -> { + if (event instanceof SessionStreamEvent.Committed c + && "message.completed".equals(c.event().type())) + delivered.countDown(); + if (event instanceof SessionStreamEvent.EventDelta delta) { + if (delta.eventId().equals("active")) positive.countDown(); + else stale.incrementAndGet(); + } + })) { + long revision = backend.frame(lease).turn().revision(); + String cursor = null; + for (int first = 0; first < total; first += 64) { + var events = new ArrayList(); + for (int i = first; i < first + 64; i++) { + String id = "history-" + i; + events.add( + new EventInput( + id, + "message.completed", + DurableJson.value( + Map.of( + "messageId", + id, + "attempt", + 1, + "revision", + 0, + "text", + id)))); + } + if (first == 0) + events.add( + new EventInput( + "active-partial", + "message.delta", + DurableJson.value( + Map.of( + "messageId", + "partial", + "attempt", + 2, + "revision", + 4, + "text", + "partial")))); + var receipt = + backend.commit( + lease, + new Commit( + "page-" + first, + revision, + DurableJson.value("history"), + List.of(), + List.of(), + List.of(), + events, + TurnStatus.RUNNING, + null, + null, + null)); + revision = receipt.revision(); + cursor = receipt.cursor(); + } + if (!delivered.await(90, TimeUnit.SECONDS)) + throw new AssertionError("missed completions " + delivered.getCount()); + backend.pruneEvents(key, cursor); + for (var id : + List.of("history-0", "history-1024", "history-2047", "partial", "active")) { + bus.publish( + new LiveEvent( + "1", + id, + key, + "main", + turn, + null, + null, + 1, + "message.delta", + DurableJson.value( + Map.of( + "messageId", + id, + "text", + "preview", + "attempt", + 2, + "revision", + 3)))); + } + if (!positive.await(30, TimeUnit.SECONDS) || stale.get() != 0) + throw new AssertionError("stale preview count " + stale.get()); + System.out.println("LONG_HISTORY completions=2048 stale=0 active=1"); + } + } + } +} diff --git a/agentscope-durable/scripts/docker-regression/Probe.java b/agentscope-durable/scripts/docker-regression/Probe.java new file mode 100644 index 0000000000..c3dd4d0290 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/Probe.java @@ -0,0 +1,240 @@ +/* + * 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 generated = java.util.concurrent.ConcurrentHashMap.newKeySet(); + 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; + } + if (generated.add(key)) System.out.println("INFERENCE " + turn); + System.out.println("RECEIVED " + turn); + while (Files.exists(Path.of("/tmp/block"))) { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + return; + } + } + if (Files.exists(Path.of("/tmp/fail"))) { + exchange.sendResponseHeaders(500, -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("broker: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/Subscriber.java b/agentscope-durable/scripts/docker-regression/Subscriber.java new file mode 100644 index 0000000000..56da0bc944 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/Subscriber.java @@ -0,0 +1,254 @@ +/* + * 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.durable.*; +import io.agentscope.durable.DurableTypes.*; + +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class Subscriber { + private static final Path CURSOR = Path.of("/tmp/subscriber-cursor"); + + private static void await(CountDownLatch signal) { + try { + if (!signal.await(120, TimeUnit.SECONDS)) + throw new IllegalStateException("callback deadline"); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } + + private static void publish(LiveEvents bus, String turn, String field, String id, String text) { + publish(bus, Probe.KEY, turn, field, id, text); + } + + private static void publish( + LiveEvents bus, SessionKey source, String turn, String field, String id, String text) { + String type = field.equals("messageId") ? "message.delta" : "tool.arguments.delta"; + bus.publish( + new LiveEvent( + "1", + UUID.randomUUID().toString(), + source, + "main", + turn, + null, + null, + 1, + type, + DurableJson.value(Map.of(field, id, "text", text)))); + } + + public static void main(String[] args) throws Exception { + var bus = LiveEvents.local(); + try (var backend = + io.agentscope.extensions.durable.jdbc.PostgresBackend.builder() + .dataSource(Probe.database()) + .build(); + var runtime = DurableRuntime.builder().backend(backend).liveEvents(bus).build()) { + var session = runtime.getSession(Probe.KEY); + if (args[0].equals("save")) { + Files.writeString(CURSOR, session.snapshot().cursor()); + return; + } + if (args[0].equals("pressure")) { + pressure(session, bus, args[1]); + return; + } + var filter = new EventFilter("main", args[1], null); + var finished = new CountDownLatch(1); + try (var sub = + session.subscribeEvents( + filter, + EventStreamOptions.builder().after(Files.readString(CURSOR)).build(), + e -> { + try { + if (e instanceof SessionStreamEvent.Committed c) { + var data = c.event().data(); + if (EchoBrainExample.FINAL_ANSWER.equals( + data.path("text").asText())) { + var id = data.required("messageId").asText(); + Files.writeString( + Path.of("/tmp/display-" + id), + id, + StandardOpenOption.CREATE_NEW); + System.out.println("DISPLAY_BEFORE_CURSOR " + id); + Runtime.getRuntime().halt(73); + } + } + if (e instanceof SessionStreamEvent.SnapshotReset reset) { + int answers = 0; + for (var message : + reset.snapshot() + .projection() + .required("messages")) { + if (!args[1].equals( + message.required("turnId").asText())) + throw new AssertionError("turn leak"); + if (!EchoBrainExample.FINAL_ANSWER.equals( + message.path("text").asText())) continue; + String id = message.required("messageId").asText(); + if (!Files.readString(Path.of("/tmp/display-" + id)) + .equals(id)) throw new AssertionError(); + answers++; + } + if (answers != 1) + throw new AssertionError( + "snapshot answer count " + answers); + Files.createFile(Path.of("/tmp/reset-reached")); + while (Files.exists(Path.of("/tmp/hold-reset"))) { + try { + Thread.sleep(50); + } catch (InterruptedException ex) { + throw new IllegalStateException(ex); + } + } + Files.writeString(CURSOR, reset.snapshot().cursor()); + finished.countDown(); + } + } catch (java.io.IOException error) { + throw new IllegalStateException(error); + } + })) { + await(finished); + String boundary = session.snapshot().cursor(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (!boundary.equals(sub.cursor())) { + if (System.nanoTime() > deadline) + throw new AssertionError("filtered subscriber lag"); + Thread.sleep(50); + } + } + } + } + + private static void pressure(DurableSession session, LiveEvents bus, String oldTurn) + throws Exception { + var base = session.snapshot(new EventFilter("main", oldTurn, null)); + var options = + EventStreamOptions.builder() + .after(base.cursor()) + .deltas( + EventStreamOptions.EventDeltaType.MESSAGE, + EventStreamOptions.EventDeltaType.TOOL_ARGUMENTS) + .build(); + var blocked = new CountDownLatch(1); + var release = new CountDownLatch(1); + var fastAnswer = new CountDownLatch(1); + var slowAnswer = new CountDownLatch(1); + var sentinel = new CountDownLatch(2); + var stale = new AtomicInteger(); + var slowBurst = new AtomicInteger(); + try (var slow = + session.subscribeEvents( + options, + e -> { + if (e instanceof SessionStreamEvent.EventDelta d) { + String text = d.data().path("text").asText(); + if (text.equals("block")) { + blocked.countDown(); + await(release); + } + if (text.equals("late")) stale.incrementAndGet(); + if (text.equals("burst")) slowBurst.incrementAndGet(); + if (text.equals("sentinel")) sentinel.countDown(); + } + if (answer(e)) slowAnswer.countDown(); + }); + var fast = + session.subscribeEvents( + options, + e -> { + if (e instanceof SessionStreamEvent.EventDelta d) { + if ("late".equals(d.data().path("text").asText())) + stale.incrementAndGet(); + if ("sentinel".equals(d.data().path("text").asText())) + sentinel.countDown(); + } + if (answer(e)) fastAnswer.countDown(); + })) { + try { + publish(bus, oldTurn, "toolCallId", "new", "block"); + await(blocked); + for (int i = 0; i < 4096; i++) + publish(bus, oldTurn, "toolCallId", "burst", "burst"); + var turn = session.submit("slow-fast", "Call echo"); + await(fastAnswer); + System.out.println("FAST_WHILE_BLOCKED " + turn.turnId()); + } finally { + release.countDown(); + } + await(slowAnswer); + // Wait for the saturated queue to drain before using an ordered positive control. + var end = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (!Objects.equals(fast.cursor(), session.snapshot().cursor()) + || !Objects.equals(slow.cursor(), fast.cursor())) { + if (System.nanoTime() > end) throw new AssertionError("durable lag"); + Thread.sleep(50); + } + for (var message : base.projection().required("messages")) { + if (message.path("complete").asBoolean()) + publish( + bus, + oldTurn, + "messageId", + message.required("messageId").asText(), + "late"); + } + publish(bus, oldTurn, "toolCallId", "echo-" + oldTurn, "late"); + publish( + bus, + new SessionKey("other", Probe.KEY.sessionId()), + oldTurn, + "toolCallId", + "new", + "late"); + bus.publish( + new LiveEvent( + "1", + "oversized", + Probe.KEY, + "main", + oldTurn, + null, + null, + 1, + "tool.arguments.delta", + DurableJson.value( + Map.of( + "toolCallId", + "new", + "text", + "late", + "padding", + "x".repeat(70 * 1024))))); + publish(bus, oldTurn, "toolCallId", "new", "sentinel"); + await(sentinel); + if (stale.get() != 0) throw new AssertionError("stale previews " + stale); + if (slowBurst.get() > 128) throw new AssertionError("slow queue exceeded capacity"); + System.out.println("STALE_PREVIEWS 0 SLOW_BURST " + slowBurst.get() + "/4096"); + } + } + + private static boolean answer(SessionStreamEvent e) { + return e instanceof SessionStreamEvent.Committed c + && EchoBrainExample.FINAL_ANSWER.equals(c.event().data().path("text").asText()); + } +} diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py new file mode 100755 index 0000000000..1e59637bf4 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -0,0 +1,588 @@ +#!/usr/bin/env python3 +"""Run real ACK redelivery, model takeover and subscriber recovery on an isolated Docker network.""" + +from concurrent.futures import ThreadPoolExecutor +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 = os.getenv("ROCKETMQ_IMAGE", "apache/rocketmq:5.5.1") +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): + container = name(service) + docker( + "run", + "-d", + "--name", + container, + "--network", + PROJECT, + "--network-alias", + service, + *options, + image, + *command, + ) + containers.append(container) + + +def logs(service): + return docker("logs", name(service)) + + +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")) + before = "receiver.accept(payload);" + loop = instrument( + loop, + before, + before + + "\n AckGate.observe(envelope,message,false);", + folder, + ) + before = "consumer.ack(message);\n } catch" + instrument( + loop, + before, + "consumer.ack(message);\n AckGate.observe(envelope,message,true);\n } catch", + 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")) + site = "if (!absent) s.setString(3, value.toString());\n }\n s.executeUpdate();" + jdbc_store = instrument( + jdbc_store, + site, + site + "\n CheckpointGate.written(part,value);", + folder, + ) + site = "c.commit();\n return result;" + instrument( + jdbc_store, + site, + "c.commit();\n CheckpointGate.committed();\n return result;", + folder, + ) + (folder / "classes").mkdir() + subprocess.run( + [ + "javac", + "--release", + "17", + "-cp", + CP, + "-d", + "classes", + *HERE.glob("*.java"), + loop, + model, + jdbc_store, + ], + cwd=folder, + check=True, + ) + + +def exercise(folder): + mount = ["-v", f"{folder}:/lab:ro", "-w", "/lab"] + + def java(service, role, extra_options=()): + start( + service, + JRE, + [*mount, *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_records where record_key like 'queued:%' " + "and payload::jsonb#>>'{request,turnId}'='" + turn + "'" + ).split("|") + assert ( + len(received) == 3 + and received[0] == "SUCCEEDED" + and received[1] == received[2] + ), received + docker("network", "disconnect", PROJECT, name(old)) + java(new, role) + + def retried(): + return next( + ( + m + for m in re.finditer("ACK " + 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", PROJECT, 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") + start( + "broker", + MQ, + ["-e", "JAVA_OPT_EXT=-Xms256m -Xmx384m -XX:MaxDirectMemorySize=256m"], + "sh", + "-c", + "printf 'brokerName=regression\nbrokerIP1=broker\nautoCreateTopicEnable=true\n' >/tmp/b.conf && exec sh mqbroker -n ns:9876 -c /tmp/b.conf --enable-proxy", + ) + 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)" + ) + + 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, + "-r", + "1", + "-w", + "1", + ) + for suffix in ("brain", "worker", "worker-controls"): + docker( + "exec", + name("broker"), + "sh", + "mqadmin", + "updateSubGroup", + "-n", + "ns:9876", + "-c", + "DefaultCluster", + "-g", + "regression-hands-" + suffix, + ) + print(client("LongHistory").strip(), flush=True) + java("model", "model") + java("brain-a", "brain") + java("hands-a", "hands") + redeliver("command", "hands") + old_turn = 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) + client("Subscriber", "save") + turn = submit("subscriber-crash") + done(turn) + client("Subscriber", "watch", turn, code=73) + done(submit("offline")) + client("Probe", "prune") + gate("client", "touch", "hold-reset") + with ThreadPoolExecutor(max_workers=1) as pool: + reconnect = pool.submit(client, "Subscriber", "watch", turn) + try: + wait( + "snapshot callback", + lambda: run( + "docker", + "exec", + name("client"), + "test", + "-e", + "/tmp/reset-reached", + check=False, + ).returncode + == 0, + ) + done(submit("during-reset")) + finally: + gate("client", "rm", "hold-reset") + reconnect.result() + print("subscriber restored one displayed answer from pruned cursor", flush=True) + report = client("Subscriber", "pressure", old_turn) + assert "STALE_PREVIEWS 0" in report + print( + next(line for line in report.splitlines() if line.startswith("STALE_PREVIEWS")), + flush=True, + ) + done(re.search(r"FAST_WHILE_BLOCKED (turn_[\w-]+)", report)[1]) + print("slow/fast: committed answer before release; stale previews=0", 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) + + def pointer(): + row = sql( + "select payload::jsonb#>>'{inline,recoveryCursor}',payload::jsonb#>>'{inline,position}' from durable_parts where part_key like '%:checkpoint' and payload::jsonb#>>'{inline,recoveryCursor}' is not null" + ) + 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 = "ack" if phase == "failed-ack" else 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'" + ) + assert failed == "1" and counts(turn) == "1|0|0" + 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)) + gate(other, "rm", "hold-effect") + done(turn) + docker("network", "connect", PROJECT, 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: + exercise(folder) + 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) + docker("network", "rm", PROJECT) From f8f3e3062efbbef2dea333d86ddbef1c08325d02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:14:32 +0800 Subject: [PATCH 18/38] Reject truncated OpenAI streams without a terminal signal --- .../core/model/transport/HttpRequest.java | 13 ++ .../model/transport/JdkHttpTransport.java | 9 +- .../core/model/transport/OkHttpTransport.java | 9 +- .../extensions/model/openai/OpenAIClient.java | 154 +++++++++++------- .../openai/OpenAIStreamTerminationTest.java | 24 ++- 5 files changed, 143 insertions(+), 66 deletions(-) diff --git a/agentscope-core/src/main/java/io/agentscope/core/model/transport/HttpRequest.java b/agentscope-core/src/main/java/io/agentscope/core/model/transport/HttpRequest.java index 85f822b794..8196971183 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/model/transport/HttpRequest.java +++ b/agentscope-core/src/main/java/io/agentscope/core/model/transport/HttpRequest.java @@ -31,12 +31,18 @@ public class HttpRequest { private final String method; private final Map headers; private final String body; + private final boolean includeSseDone; private HttpRequest(Builder builder) { this.url = builder.url; this.method = builder.method; this.headers = Collections.unmodifiableMap(new HashMap<>(builder.headers)); this.body = builder.body; + this.includeSseDone = builder.includeSseDone; + } + + public boolean includeSseDone() { + return includeSseDone; } /** @@ -92,6 +98,13 @@ public static class Builder { private String method = "GET"; private final Map headers = new HashMap<>(); private String body; + private boolean includeSseDone; + + /** Deliver the terminal SSE marker to protocols that validate stream completion. */ + public Builder includeSseDone(boolean value) { + includeSseDone = value; + return this; + } /** * Set the request URL. diff --git a/agentscope-core/src/main/java/io/agentscope/core/model/transport/JdkHttpTransport.java b/agentscope-core/src/main/java/io/agentscope/core/model/transport/JdkHttpTransport.java index 7ab0233252..8827389439 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/model/transport/JdkHttpTransport.java +++ b/agentscope-core/src/main/java/io/agentscope/core/model/transport/JdkHttpTransport.java @@ -344,7 +344,9 @@ private Flux processStreamResponse(InputStream inputStream, HttpRequest new BufferedReader( new InputStreamReader( inputStream, StandardCharsets.UTF_8)); - return isNdjson ? readNdJsonLines(reader) : readSseLines(reader); + return isNdjson + ? readNdJsonLines(reader) + : readSseLines(reader, request.includeSseDone()); }) // reader.lines() uses blocking I/O internally .subscribeOn(streamScheduler); @@ -353,11 +355,12 @@ private Flux processStreamResponse(InputStream inputStream, HttpRequest /** * Extract non-empty SSE data payloads and stop before the terminal marker. */ - private Flux readSseLines(BufferedReader reader) { + private Flux readSseLines(BufferedReader reader, boolean includeDone) { return Flux.fromStream(reader.lines()) .filter(line -> line.startsWith(SSE_DATA_PREFIX)) .map(line -> line.substring(SSE_DATA_PREFIX.length()).trim()) - .takeWhile(data -> !SSE_DONE_MARKER.equals(data)) + .takeUntil(SSE_DONE_MARKER::equals) + .filter(data -> includeDone || !SSE_DONE_MARKER.equals(data)) .doOnNext(data -> log.debug("Received SSE data chunk")) .filter(data -> !data.isEmpty()); } diff --git a/agentscope-core/src/main/java/io/agentscope/core/model/transport/OkHttpTransport.java b/agentscope-core/src/main/java/io/agentscope/core/model/transport/OkHttpTransport.java index be3b236888..315f2b1316 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/model/transport/OkHttpTransport.java +++ b/agentscope-core/src/main/java/io/agentscope/core/model/transport/OkHttpTransport.java @@ -275,10 +275,13 @@ public Flux stream(HttpRequest request) { SSE_DATA_PREFIX .length()) .trim()) - .takeWhile( + .takeUntil(SSE_DONE_MARKER::equals) + .filter( data -> - !SSE_DONE_MARKER.equals( - data)) + request.includeSseDone() + || !SSE_DONE_MARKER + .equals( + data)) .filter(data -> !data.isEmpty()); }, this::closeQuietly) diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java index ddf548f739..3168953023 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java @@ -399,66 +399,106 @@ public Flux stream( .url(url) .method("POST") .headers(buildHeaders(effectiveApiKey, options)) + .includeSseDone(true) .body(requestBody) .build(); - AtomicBoolean seenChunk = new AtomicBoolean(false); - return transport.stream(httpRequest) - // The SSE `[DONE]` sentinel terminates the stream: complete the Flux here - // rather than merely filtering it out, otherwise completion is deferred until - // the underlying connection closes (keep-alive gateways may stall this for the - // full idle timeout even though the model has finished responding). - .takeWhile(data -> !SSE_DONE_MARKER.equals(data)) - .handle( - (data, sink) -> { - OpenAIResponse response = parseStreamData(data); - if (response != null) { - // Check for error in streaming response chunk - if (response.isError()) { - String errorMessage = response.getEffectiveErrorMessage(); - String errorCode = response.getEffectiveErrorCode(); - int statusCode = resolveErrorStatusCode(200, errorCode); - sink.error( - OpenAIException.create( - statusCode, - "OpenAI API error in streaming response: " - + errorMessage, - errorCode, - data)); - return; - } - // Some OpenAI-compatible providers (e.g. MiniMax) emit an - // extra non-chunk chat.completion summary event after regular - // chunks. Drop duplicated summary message content, but only - // after seeing at least one chunk so stream-only full - // chat.completion events are preserved. - if (response.isChunk()) { - seenChunk.set(true); - } else if (seenChunk.get()) { - OpenAIChoice summaryChoice = response.getFirstChoice(); - if (summaryChoice != null) { - summaryChoice.setMessage(null); - } - } - sink.next(response); - } - // If response is null (malformed chunk), skip it silently - }) - .onErrorMap( - ex -> { - if (ex instanceof HttpTransportException hte) { - Integer code = hte.getStatusCode(); - String msg = - "HTTP transport error during streaming: " - + ex.getMessage(); - if (code != null) { - return OpenAIException.create( - code, msg, null, hte.getResponseBody()); - } - return new OpenAIException(msg, ex); - } - return ex; - }); + return Flux.defer( + () -> { + AtomicBoolean terminated = new AtomicBoolean(); + AtomicBoolean seenChunk = new AtomicBoolean(false); + return transport.stream(httpRequest) + // The SSE `[DONE]` sentinel terminates the stream: complete the + // Flux here + // rather than merely filtering it out, otherwise completion is + // deferred until + // the underlying connection closes (keep-alive gateways may stall + // this for the + // full idle timeout even though the model has finished responding). + .takeWhile( + data -> { + if (!SSE_DONE_MARKER.equals(data)) return true; + terminated.set(true); + return false; + }) + .handle( + (data, sink) -> { + OpenAIResponse response = parseStreamData(data); + if (response != null) { + // Check for error in streaming response chunk + if (response.isError()) { + String errorMessage = + response.getEffectiveErrorMessage(); + String errorCode = + response.getEffectiveErrorCode(); + int statusCode = + resolveErrorStatusCode(200, errorCode); + sink.error( + OpenAIException.create( + statusCode, + "OpenAI API error in streaming" + + " response: " + + errorMessage, + errorCode, + data)); + return; + } + // Some OpenAI-compatible providers (e.g. MiniMax) + // emit an + // extra non-chunk chat.completion summary event + // after regular + // chunks. Drop duplicated summary message content, + // but only + // after seeing at least one chunk so stream-only + // full + // chat.completion events are preserved. + if (response.isChunk()) { + seenChunk.set(true); + } else if (seenChunk.get()) { + OpenAIChoice summaryChoice = + response.getFirstChoice(); + if (summaryChoice != null) { + summaryChoice.setMessage(null); + } + } + var choice = response.getFirstChoice(); + if (choice != null + && choice.getFinishReason() != null + && !choice.getFinishReason().isBlank()) + terminated.set(true); + sink.next(response); + } + // If response is null (malformed chunk), skip it + // silently + }) + .concatWith( + Flux.defer( + () -> + terminated.get() + ? Flux.empty() + : Flux.error( + new java.io.EOFException( + "OpenAI stream" + + " closed" + + " before" + + " finish_reason" + + " or [DONE]")))) + .onErrorMap( + ex -> { + if (ex instanceof HttpTransportException hte) { + Integer code = hte.getStatusCode(); + String msg = + "HTTP transport error during streaming: " + + ex.getMessage(); + if (code != null) { + return OpenAIException.create( + code, msg, null, hte.getResponseBody()); + } + return new OpenAIException(msg, ex); + } + return ex; + }); + }); } catch (JsonException | HttpTransportException e) { return Flux.error( new OpenAIException("Failed to initialize request: " + e.getMessage(), e)); diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java index bb437f76f0..5be91a6771 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java @@ -52,7 +52,7 @@ class OpenAIStreamTerminationTest { * completes ({@link Flux#never()}) — simulating a gateway that holds the connection open * after {@code [DONE]}. */ - private static HttpTransport keepAliveTransportAfterDone() { + private static HttpTransport transport(Flux frames) { return new HttpTransport() { @Override public HttpResponse execute(HttpRequest request) { @@ -61,7 +61,7 @@ public HttpResponse execute(HttpRequest request) { @Override public Flux stream(HttpRequest request) { - return Flux.just(CHUNK_CONTENT, CHUNK_FINISH, "[DONE]").concatWith(Flux.never()); + return frames; } @Override @@ -69,6 +69,20 @@ public void close() {} }; } + @Test + void truncatedStreamErrorsButFinishReasonPermitsCleanEof() { + for (boolean complete : List.of(false, true)) { + var frames = + complete ? Flux.just(CHUNK_CONTENT, CHUNK_FINISH) : Flux.just(CHUNK_CONTENT); + var stream = + new OpenAIClient(transport(frames)) + .stream("test", "http://localhost", sampleRequest(), null); + var expectation = StepVerifier.create(stream).expectNextCount(complete ? 2 : 1); + if (complete) expectation.verifyComplete(); + else expectation.verifyError(java.io.EOFException.class); + } + } + private static OpenAIRequest sampleRequest() { return OpenAIRequest.builder() .model("gpt-4o-mini") @@ -79,7 +93,11 @@ private static OpenAIRequest sampleRequest() { @Test @DisplayName("Stream should complete on [DONE] even if the connection stays open") void streamCompletesOnDoneSentinelWithoutWaitingForConnectionClose() { - OpenAIClient client = new OpenAIClient(keepAliveTransportAfterDone()); + OpenAIClient client = + new OpenAIClient( + transport( + Flux.just(CHUNK_CONTENT, CHUNK_FINISH, "[DONE]") + .concatWith(Flux.never()))); StepVerifier.create( client.stream( From 6b7e7174eb6be81e963a9864d7b62d1a44038cc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:18:23 +0800 Subject: [PATCH 19/38] Park uncertain native turns, honor recovery budgets and share journal history --- agentscope-durable/README.md | 12 +++ .../durable/agentscope/AgentScopeAdapter.java | 45 +++++++- .../durable/agentscope/ModelCapture.java | 5 +- .../agentscope/AgentScopeAdapterTest.java | 85 +++++++++++++-- .../io/agentscope/durable/DurableRuntime.java | 4 +- .../io/agentscope/durable/DurableTypes.java | 3 + .../java/io/agentscope/durable/Executor.java | 6 ++ .../io/agentscope/durable/JournalContent.java | 100 ++++++++++++++++++ .../durable/NotifyingSessionBackend.java | 13 ++- .../io/agentscope/durable/SessionBackend.java | 9 ++ .../durable/TransactionalSessionBackend.java | 51 ++++++--- .../agentscope/durable/store/RecordStore.java | 3 + .../durable/JournalContentTest.java | 63 +++++++++++ .../contract/SessionBackendContract.java | 11 +- agentscope-durable/protocol/schema.json | 10 ++ .../durable/http/HttpSessionBackend.java | 15 ++- .../durable/http/SessionBackendHandler.java | 10 +- .../durable/jdbc/JdbcRecordStore.java | 31 ++++-- .../durable/jdbc/DurableBackendTest.java | 43 ++++++++ .../durable/rocketmq/RocketMqWorker.java | 1 + 20 files changed, 473 insertions(+), 47 deletions(-) create mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java create mode 100644 agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 70226f9c17..c314a765b9 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -189,6 +189,18 @@ request whose result was never committed may need another model invocation. Workspace files and remote resources must also remain accessible; a saved checkpoint cannot reconstruct a deleted workspace or an expired external operation. +If an interrupted native tool has no verified result, the Turn waits for explicit +reconciliation. Scheduled Brains leave it parked. An operator can claim it and +call `reconcileNativeTools` with a verified outcome and evidence reference. +Cancelling the Turn closes the native call with an unverified outcome. A repeated +cancel request can use a new request ID. + +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. Large journal entries and checkpoints share +immutable content-defined chunks within a Session. Readers support the original +whole-object references. Upgrade every reader before writing the chunked format. + ### 2. Queue Turns, add instructions, and cancel work While an assistant investigates an incident, the user asks for a follow-up summary 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 86b4a03d83..72ed15e17b 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 @@ -317,6 +317,12 @@ public void execute(HarnessContext context) { if (host.pending()) host.restoreEntry(); else if (completeInvocation(context, log)) return; var frame = context.frame(); + var nativeCalls = new HashSet<>(JournalProjection.read(log).uncertainToolCalls()); + frame.tools().forEach(tool -> nativeCalls.remove(tool.request().call().callId())); + if (!nativeCalls.isEmpty()) { + waitFor(context, WaitCondition.NATIVE_RECONCILIATION); + return; + } var input = new ArrayList(); var results = new ArrayList(); var confirmations = new ArrayList(); @@ -641,9 +647,12 @@ public void settle(HarnessContext context, TurnStatus status, String error) { var projection = JournalProjection.read(log); var reconciled = frame.tools().stream().map(tool -> tool.request().call().callId()).toList(); - if (projection.uncertainToolCalls().stream().anyMatch(id -> !reconciled.contains(id))) - throw new DurableException( - DurableException.Code.CONFLICT, "Native tool outcome requires reconciliation"); + var uncertain = new HashSet<>(projection.uncertainToolCalls()); + uncertain.removeAll(reconciled); + if (!uncertain.isEmpty() && status != TurnStatus.CANCELLED) { + waitFor(context, WaitCondition.NATIVE_RECONCILIATION); + return; + } var state = projection.restore(); if (state == null) state = AgentState.builder().build(); var facts = new ArrayList>(); @@ -686,6 +695,30 @@ public void settle(HarnessContext context, TurnStatus status, String error) { "tool/result", Map.of("message", message, "synthetic", execution.isEmpty()))); } + for (String id : uncertain) { + var name = + state.contextMutable().stream() + .flatMap(msg -> msg.getContentBlocks(ToolUseBlock.class).stream()) + .filter(call -> id.equals(call.getId())) + .map(ToolUseBlock::getName) + .findFirst() + .orElse("unknown"); + var outcome = + ToolResultBlock.text("Turn cancelled; external outcome unverified.") + .withIdAndName(id, name) + .withState(ToolResultState.INTERRUPTED) + .withExecutionDetails( + new io.agentscope.core.message.ToolExecutionDetails( + "native", + io.agentscope.core.message.ToolExecutionDetails.Outcome + .UNKNOWN, + null, + false)); + var message = ToolResultMessage.builder().id("cancelled:" + id).result(outcome).build(); + state.contextMutable().add(message); + calls.add(id); + facts.add(Map.entry("tool/result", Map.of("message", message, "synthetic", true))); + } var messages = state.contextMutable(); for (int i = 0; i < messages.size(); i++) { var content = new ArrayList(); @@ -714,7 +747,11 @@ public void settle(HarnessContext context, TurnStatus status, String error) { "interruptedRuns", projection.activeRuns(), "resolvedToolCallIds", - reconciled, + java.util.stream.Stream.concat( + reconciled.stream(), uncertain.stream()) + .toList(), + "unverifiedToolCallIds", + uncertain, "reason", reason))); log.append(context.lease().turnId(), facts, status, error); 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 966eb8a1bd..94a802b417 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 @@ -38,7 +38,6 @@ final class ModelCapture { static final String OUTCOME = "durableModelOutcome"; private static final long MAX_BYTES = 16L * 1024 * 1024; - private final Map request; final String replayHash; final String providerKey; private final ReasoningContext content = new ReasoningContext("durable"); @@ -64,9 +63,8 @@ final class ModelCapture { data.put("messages", messages); data.put("tools", tools); data.put("options", options); - this.request = freeze(data); this.replayHash = replayHash; - if (JsonUtils.getJsonCodec().toJson(request).length() > MAX_BYTES) + if (JsonUtils.getJsonCodec().toJson(data).length() > MAX_BYTES) throw new DurableException( DurableException.Code.INVALID, "Model request exceeds capture limit"); } @@ -111,7 +109,6 @@ synchronized void accept(ChatResponse chunk) { synchronized Map freeze(String status) { var outcome = new LinkedHashMap(); - outcome.put("request", request); outcome.put("replayHash", replayHash); if (usage != null) outcome.put("usage", freeze(usage)); if (finishReason != null) outcome.put("finishReason", finishReason); 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 447de968eb..0e7244d0ca 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 @@ -230,8 +230,9 @@ DurableRuntime runtime( return builder.build(); } - @Test - void verifiedNativeToolRepairSurvivesReopenAndRejectsChangedEvidence() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void parkedNativeToolCanBeCancelledOrReconciled(boolean cancel) { var adapter = adapter(new ScriptedModel(false), PermissionMode.BYPASS, Map.of()); try (var backend = LocalBackend.open(directory.resolve("repair")); var runtime = runtime(backend, adapter, null)) { @@ -249,24 +250,94 @@ void verifiedNativeToolRepairSurvivesReopenAndRejectsChangedEvidence() { Map.of( "stateJson", io.agentscope.core.state.AgentState.builder() + .userId(key.namespace()) + .sessionId(key.sessionId()) + .threadId("main") .build() .toJson(), "projectorVersion", 1)), Map.entry("tool/dispatch", Map.of("toolCallId", "local-1")))); + adapter.execute(context); + assertEquals(TurnStatus.WAITING, turn.status().status()); + var thread = new ThreadKey(key, "main"); + assertTrue( + backend.claim( + thread, + "scheduler", + Duration.ofMinutes(1), + io.agentscope.durable.DurableTypes.RecoveryPolicy.defaults()) + .isEmpty()); + if (cancel) { + backend.cancel(thread, turn.turnId(), "cancel-1"); + backend.cancel(thread, turn.turnId(), "cancel-2"); + runtime.tick(thread); + assertEquals(TurnStatus.CANCELLED, turn.status().status()); + return; + } + var repairContext = + new HarnessContext( + backend, + backend.claim(thread, "operator", Duration.ofMinutes(1)).orElseThrow(), + new AtomicBoolean()); var outcomes = Map.of( "local-1", ToolResultBlock.text("verified") .withIdAndName("local-1", "local") .withState(ToolResultState.SUCCESS)); - adapter.reconcileNativeTools(context, "repair-1", "audit/123", outcomes); - long position = new BackendThreadJournal(context, Map.of()).head().seq(); - adapter.reconcileNativeTools(context, "repair-1", "audit/123", outcomes); - assertEquals(position, new BackendThreadJournal(context, Map.of()).head().seq()); + adapter.reconcileNativeTools(repairContext, "repair-1", "audit/123", outcomes); + long position = new BackendThreadJournal(repairContext, Map.of()).head().seq(); + adapter.reconcileNativeTools(repairContext, "repair-1", "audit/123", outcomes); + assertEquals(position, new BackendThreadJournal(repairContext, Map.of()).head().seq()); assertThrows( DurableException.class, - () -> adapter.reconcileNativeTools(context, "repair-1", "other", outcomes)); + () -> + adapter.reconcileNativeTools( + repairContext, "repair-1", "other", outcomes)); + backend.release(repairContext.lease(), Duration.ZERO); + runtime.tick(thread); + assertEquals(TurnStatus.SUCCEEDED, turn.status().status()); + } + } + + @Test + void growingConversationSharesHistoricalJournalPayloads() throws Exception { + var database = directory.resolve("history.db"); + var adapter = adapter(new ScriptedModel(false), PermissionMode.BYPASS, Map.of()); + try (var backend = + new io.agentscope.durable.TransactionalSessionBackend( + io.agentscope.extensions.durable.jdbc.JdbcRecordStore.sqlite( + database)); + var runtime = runtime(backend, adapter, null); + var connection = java.sql.DriverManager.getConnection("jdbc:sqlite:" + database); + var measure = + connection.prepareStatement( + "SELECT SUM(length(payload)) FROM durable_parts")) { + var session = runtime.createSession(key, "agent"); + var random = new java.util.Random(57); + long firstHalf = 0; + for (int i = 1; i <= 24; i++) { + byte[] bytes = new byte[1536]; + random.nextBytes(bytes); + var turn = + session.submit( + "input-" + i, java.util.Base64.getEncoder().encodeToString(bytes)); + runtime.tick(new ThreadKey(key, "main")); + assertEquals(TurnStatus.SUCCEEDED, turn.status().status()); + if (i == 12 || i == 24) { + try (var result = measure.executeQuery()) { + assertTrue(result.next()); + long size = result.getLong(1); + System.out.println("durable_parts payload at turn " + i + " = " + size); + if (i == 12) firstHalf = size; + else + assertTrue( + size < 3 * firstHalf, + "History amplification: " + size + " / " + firstHalf); + } + } + } } } 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 4aa933966e..babfef3f05 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 @@ -609,10 +609,10 @@ private void process(ThreadKey key, Active activeCall) { String claimId = owner + ":" + UUID.randomUUID(); Optional claimed; try { - claimed = backend.claim(key, claimId, leaseDuration); + claimed = backend.claim(key, claimId, leaseDuration, recoveryPolicy); } catch (DurableException error) { if (error.code() != DurableException.Code.UNAVAILABLE) throw error; - claimed = backend.claim(key, claimId, leaseDuration); + claimed = backend.claim(key, claimId, leaseDuration, recoveryPolicy); } if (claimed.isEmpty()) return; Lease lease = claimed.get(); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java index c46de28ff6..aa392cf24f 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java @@ -432,6 +432,9 @@ public SessionKey session() { } public record WaitCondition(String key, long deadline) { + public static final WaitCondition NATIVE_RECONCILIATION = + new WaitCondition("native:reconciliation", 0); + public WaitCondition { DurableJson.text(key, "wait key"); if (deadline < 0) throw new IllegalArgumentException("Negative deadline"); 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..589b3a5896 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. 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/JournalContent.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java new file mode 100644 index 0000000000..18cee868de --- /dev/null +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java @@ -0,0 +1,100 @@ +/* + * 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; + +import io.agentscope.durable.store.ObjectStore; +import io.agentscope.durable.store.ObjectStore.Reference; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.HexFormat; + +/** Content-defined chunks let successive full-history journal entries share their stable bytes. */ +final class JournalContent { + private static final int MIN = 1024; + private static final int MAX = 8192; + private static final int DESCRIPTOR = 36; + private static final HexFormat HEX = HexFormat.of(); + + record Root(Reference reference, int levels, int size, String digest) {} + + static Root put(ObjectStore store, String scope, byte[] bytes) { + if (bytes.length > ObjectStore.MAX_BYTES) + throw new IllegalArgumentException("Journal content too large"); + byte[] layer = bytes; + int levels = 0; + while (layer.length > MAX) { + var index = new ByteArrayOutputStream(); + int hash = 0; + int start = 0; + for (int i = 0; i < layer.length; i++) { + hash = (hash << 1) + GEAR[layer[i] & 255]; + int length = i - start + 1; + if (length >= MAX + || (length >= MIN && (hash & 2047) == 0) + || i == layer.length - 1) { + var chunk = store.put(scope, Arrays.copyOfRange(layer, start, i + 1)); + index.writeBytes( + ByteBuffer.allocate(DESCRIPTOR) + .putInt(length) + .put(HEX.parseHex(chunk.digest())) + .array()); + start = i + 1; + hash = 0; + } + } + layer = index.toByteArray(); + levels++; + } + return new Root(store.put(scope, layer), levels, bytes.length, ObjectStore.digest(bytes)); + } + + private static final int[] GEAR = gearTable(); + + private static int[] gearTable() { + var random = new java.util.Random(0x4167656e74L); + var table = new int[256]; + for (int i = 0; i < table.length; i++) table[i] = random.nextInt(); + return table; + } + + static byte[] read(ObjectStore store, String scope, Root root) { + if (!root.reference().scope().equals(scope) || root.levels() < 0 || root.levels() > 4) + throw new DurableException(DurableException.Code.INVALID, "Invalid journal index"); + var expected = new Reference(store.id(), scope, root.digest(), root.size()); + byte[] layer = store.read(root.reference()); + for (int level = root.levels(); level > 0; level--) { + if (layer.length % DESCRIPTOR != 0) + throw new DurableException( + DurableException.Code.INVALID, "Incomplete journal index"); + var index = ByteBuffer.wrap(layer); + var restored = new ByteArrayOutputStream(); + while (index.hasRemaining()) { + int length = index.getInt(); + if (length <= 0 || length > MAX || length > root.size() - restored.size()) + throw new DurableException( + DurableException.Code.INVALID, "Invalid journal chunk size"); + byte[] digest = new byte[32]; + index.get(digest); + restored.writeBytes( + store.read( + new Reference(store.id(), scope, HEX.formatHex(digest), length))); + } + layer = restored.toByteArray(); + } + return ObjectStore.verify(store.id(), expected, layer); + } +} 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 23d6db1a08..44dd5b3abe 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 @@ -264,8 +264,17 @@ public ModelCallPage modelCalls( } @Override - public Optional claim(ThreadKey session, String owner, Duration duration) { - var result = delegate.claim(session, owner, duration); + public Optional claim(ThreadKey key, String owner, Duration duration) { + return claim(key, owner, duration, null); + } + + @Override + public Optional claim( + ThreadKey session, + String owner, + Duration duration, + io.agentscope.durable.DurableTypes.RecoveryPolicy policy) { + var result = delegate.claim(session, owner, duration, policy); if (result.isPresent()) changed(session); return 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 9db421277b..744c067c05 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 @@ -171,6 +171,15 @@ ModelCallPage modelCalls( Optional claim(ThreadKey session, String owner, Duration duration); + /** Scheduled claims carry the host policy. Explicit claims can repair a parked native Turn. */ + default Optional claim( + ThreadKey session, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { + return claim(session, owner, duration); + } + void renew(Lease lease, Duration duration); void release(Lease lease, Duration delay); 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 34f4a1a8bf..3df6c833b3 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 @@ -136,14 +136,21 @@ public Optional localStorage() { private JsonNode storeContent(SessionKey session, JsonNode value) { byte[] bytes = DurableJson.value(value).toString().getBytes(StandardCharsets.UTF_8); - return bytes.length > 16384 - ? DurableJson.value( - new StoredContent(null, objects.put(objectScope(session), bytes))) - : DurableJson.value(new StoredContent(DurableJson.copy(value), null)); + if (bytes.length > 8192) + return DurableJson.value( + Map.of("chunked", JournalContent.put(objects, objectScope(session), bytes))); + return DurableJson.value(new StoredContent(DurableJson.copy(value), null)); } private JsonNode readContent(SessionKey session, JsonNode stored) { if (stored == null || stored.isNull()) return DurableJson.value(null); + if (stored.hasNonNull("chunked")) { + var root = DurableJson.convert(stored.get("chunked"), JournalContent.Root.class); + return DurableJson.parse( + new String( + JournalContent.read(objects, objectScope(session), root), + StandardCharsets.UTF_8)); + } var value = DurableJson.convert(stored, StoredContent.class); return value.reference() == null ? DurableJson.copy(value.inline()) @@ -248,6 +255,7 @@ 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; @@ -335,6 +343,7 @@ private static long readyAt(State s, long now) { if (turn.status == TurnStatus.PAUSED) return -1; if (turn.owner != null && turn.expiresAt > now) return turn.expiresAt; if (turn.cancel || turn.status == TurnStatus.PAUSING) return turn.nextAttemptAt; + if (WaitCondition.NATIVE_RECONCILIATION.equals(turn.waiting)) return -1; long ready = turn.nextAttemptAt; if (turn.recovery != null) { if (!turn.recovery.retryAllowed()) return ready; @@ -1037,8 +1046,18 @@ public ModelCallPage modelCalls( @Override public Optional claim(ThreadKey key, String owner, Duration duration) { + return claim(key, owner, duration, null); + } + + @Override + public Optional claim( + ThreadKey key, + String owner, + Duration duration, + io.agentscope.durable.DurableTypes.RecoveryPolicy policy) { DurableJson.text(owner, "owner"); long ttl = positive(duration); + store.boundIdleTransactionTime(duration); return change( key, (s, now) -> { @@ -1048,23 +1067,29 @@ public Optional claim(ThreadKey key, String owner, Duration duration) { return Optional.of( new Lease(key, turn.id, owner, turn.epoch, turn.expiresAt)); long ready = readyAt(s, now); - if (ready < 0 || ready > now) return Optional.empty(); + boolean repair = + policy == null + && turn.status == TurnStatus.WAITING + && WaitCondition.NATIVE_RECONCILIATION.equals(turn.waiting) + && (turn.owner == null || turn.expiresAt <= now); + if (!repair && (ready < 0 || ready > now)) return Optional.empty(); + 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 policy = - turn.recovery == null - ? DurableTypes.RecoveryPolicy.defaults() - : turn.recovery.policy(); - if (++turn.consecutiveLostRuns > policy.maxRetries()) { + 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( - policy.maxRetries() + 1, - policy, + lostPolicy.maxRetries() + 1, + lostPolicy, false, null, turn.error); @@ -2287,7 +2312,7 @@ private static void cancel(State s, String turnId, String requestId) { } TurnData r = requireTurn(s, turnId); s.commands.put(command, turnId); - if (!r.status.terminal()) { + if (!r.status.terminal() && !r.cancel) { r.cancel = true; boolean queued = r.epoch == 0; r.status = queued ? TurnStatus.CANCELLED : TurnStatus.CANCELLING; 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 64fde6b72a..3fb16f71a3 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/JournalContentTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java new file mode 100644 index 0000000000..f2af4049b7 --- /dev/null +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java @@ -0,0 +1,63 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.agentscope.durable.store.ObjectStore; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import org.junit.jupiter.api.Test; + +class JournalContentTest { + @Test + void growingHistorySharesBytesAndRecoversEveryVersion() { + Map chunks = new HashMap<>(); + ObjectStore objects = + new ObjectStore() { + public String id() { + return "test"; + } + + public Reference put(String scope, byte[] bytes) { + var ref = ObjectStore.reference(id(), scope, bytes); + chunks.putIfAbsent(ref.key(), bytes); + return ref; + } + + public byte[] read(Reference ref) { + return chunks.get(ref.key()); + } + }; + byte[] history = new byte[512 * 2048]; + new Random(42).nextBytes(history); + String scope = ObjectStore.digest(new byte[0]); + var roots = new java.util.ArrayList(); + for (int turn = 1; turn <= 512; turn++) { + roots.add(JournalContent.put(objects, scope, Arrays.copyOf(history, turn * 2048))); + } + assertTrue(roots.get(511).levels() >= 2); + long stored = chunks.values().stream().mapToLong(chunk -> chunk.length).sum(); + assertTrue(stored < history.length * 10L, "Unique chunk and index bytes: " + stored); + for (int i = 0; i < roots.size(); i++) + assertArrayEquals( + Arrays.copyOf(history, (i + 1) * 2048), + JournalContent.read(objects, scope, roots.get(i))); + } +} 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 10109f2c09..63aba56423 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 @@ -1388,8 +1388,10 @@ private Lease claim() { @Test protected void repeatedExpiryOfUnfinishedRunsStopsInvocationRecovery() { submit(); - var lease = claim(); - for (int i = 0; i <= RecoveryPolicy.defaults().maxRetries(); i++) { + var thread = new ThreadKey(key, "main"); + var policy = new RecoveryPolicy(2, 100, 500); + var lease = backend.claim(thread, "owner", Duration.ofSeconds(1), policy).orElseThrow(); + for (int i = 0; i <= policy.maxRetries(); i++) { backend.prepareRun(lease, "invoke-" + i); clock.set(lease.expiresAt() + 1); lease = claim(); @@ -1850,7 +1852,7 @@ protected void largeCheckpointAndJournalUseScopedImmutableContent() { tx -> { assertTrue( tx.get("thread-data:" + DurableJson.hash("main") + ":checkpoint") - .hasNonNull("reference")); + .hasNonNull("chunked")); assertTrue( tx.get("thread-data:" + DurableJson.hash("main") + ":checkpoint") .toString() @@ -1861,7 +1863,7 @@ protected void largeCheckpointAndJournalUseScopedImmutableContent() { "thread-data:" + DurableJson.hash("main") + ":journal:initial:00000000000000000001") - .hasNonNull("reference")); + .hasNonNull("chunked")); return null; }); byte[] bytes = "private artifact".getBytes(StandardCharsets.UTF_8); @@ -2932,6 +2934,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()); diff --git a/agentscope-durable/protocol/schema.json b/agentscope-durable/protocol/schema.json index 2f87bcb276..4eb1e3267f 100644 --- a/agentscope-durable/protocol/schema.json +++ b/agentscope-durable/protocol/schema.json @@ -3683,6 +3683,16 @@ }, "thread": { "$ref": "#/$defs/thread" + }, + "policy": { + "anyOf": [ + { + "type": "null" + }, + { + "$ref": "#/$defs/recoveryPolicy" + } + ] } } } 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 1277bb53f6..90add4b4d7 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 @@ -284,7 +284,16 @@ public ModelCallPage modelCalls( } @Override - public Optional claim(ThreadKey session, String owner, Duration duration) { + public Optional claim(ThreadKey key, String owner, Duration duration) { + return claim(key, owner, duration, null); + } + + @Override + public Optional claim( + ThreadKey session, + String owner, + Duration duration, + io.agentscope.durable.DurableTypes.RecoveryPolicy policy) { return Optional.ofNullable( as( call( @@ -294,7 +303,9 @@ public Optional claim(ThreadKey session, String owner, Duration duration) "owner", owner, "duration", - duration.toMillis()), + duration.toMillis(), + "policy", + policy), Lease.class)); } 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 39b9cf3e5a..b0cef6090d 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 @@ -215,7 +215,15 @@ public void handle(HttpExchange exchange) throws IOException { backend.claim( thread, text(p, "owner"), - Duration.ofMillis(p.path("duration").asLong())) + Duration.ofMillis(p.path("duration").asLong()), + p.hasNonNull("policy") + ? get( + p, + "policy", + io.agentscope.durable + .DurableTypes + .RecoveryPolicy.class) + : null) .orElse(null); case "renew" -> { backend.renew(lease, Duration.ofMillis(p.path("duration").asLong())); 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 4210668f19..6f113ed7cb 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 @@ -46,6 +46,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(); @Override @@ -161,14 +171,19 @@ public T transaction(String key, Function action) { c.setAutoCommit(false); try { if (dialect == Dialect.POSTGRESQL) { - // Release the record lock if the owner disappears between statements. - // A positive timeout configured by the database takes precedence. - try (var statement = c.createStatement()) { - statement.execute( - "SELECT" - + " set_config('idle_in_transaction_session_timeout','30s',true)" - + " WHERE" - + " current_setting('idle_in_transaction_session_timeout')='0'"); + // Use the shorter of the database limit and the leases served by this host. + try (var statement = + c.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(); } } try (var s = 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-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 f12dcd50b3..f68a146b5c 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 @@ -58,6 +58,7 @@ private RocketMqWorker(Builder builder) { updatesTopic = topology.updates(); authorizer = builder.authorizer; interval = builder.interval; + builder.records.boundIdleTransactionTime(builder.lease); store = new TransactionalExecutionStore(builder.records, name); ClientServiceProvider provider = builder.provider; Producer configuredProducer; From a1b6317dd6827b6bac8b171cbcf8f31504250eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:19:44 +0800 Subject: [PATCH 20/38] Cover missing and uncertain lookups after a running tool is reclaimed --- .../durable/ExecutionRecoveryTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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..2ff60d45f6 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,25 @@ 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, "recovered")).thenReturn(ExecutionResult.missing()); + when(executor.startExecution(request)).thenReturn(running); + assertEquals(running, ExecutionRecovery.resolve(executor, request, running, true, false)); + verify(executor).startExecution(request); + } + @Test void uncertainNonIdempotentEffectsAreNeverRepeated() { when(executor.capabilities()).thenReturn(new Executor.Capabilities(false, false, false)); From f3fe6ef18a5d4b8572265d6b2b8078fdb8a13d5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:36:27 +0800 Subject: [PATCH 21/38] Avoid repeat database transactions for recently verified immutable chunks --- .../durable/store/RecordObjectStore.java | 73 +++++++++++++------ .../durable/jdbc/ScopedWorkStoreTest.java | 31 ++++++++ 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java index 8b48f9e1d5..d9f496af56 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java @@ -20,11 +20,25 @@ import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Base64; +import java.util.LinkedHashMap; import java.util.Objects; /** Database fallback for small installations; production hosts may supply object storage. */ public final class RecordObjectStore implements ObjectStore { private final RecordStore records; + // Large journal entries revisit the same immutable chunks on both append and recovery. + // Retain at most 16 MiB of verified content per store, allowing cold readers to use the DB. + private final LinkedHashMap chunks = new LinkedHashMap<>(64, 0.75f, true); + + private synchronized byte[] cached(Reference ref) { + return chunks.get(ref); + } + + private synchronized void remember(Reference ref, byte[] bytes) { + if (bytes.length > 8192) return; + chunks.put(ref, bytes.clone()); + if (chunks.size() > 2048) chunks.remove(chunks.keySet().iterator().next()); + } public RecordObjectStore(RecordStore records) { this.records = Objects.requireNonNull(records); @@ -38,6 +52,7 @@ public String id() { public Reference put(String scope, byte[] bytes) { var reference = ObjectStore.reference(id(), scope, bytes); + if (cached(reference) != null) return reference; records.transaction( "object:" + reference.key(), tx -> { @@ -61,35 +76,45 @@ public Reference put(String scope, byte[] bytes) { tx.put("", DurableJson.value(reference)); return null; }); + remember(reference, bytes); return reference; } public byte[] read(Reference reference) { if (!id().equals(reference.store())) throw new DurableException(DurableException.Code.INVALID, "Object store differs"); - return records.transaction( - "object:" + reference.key(), - tx -> { - var existing = tx.get(""); - if (existing == null) - throw new DurableException( - DurableException.Code.NOT_FOUND, "Object not found"); - if (!reference.equals(DurableJson.convert(existing, Reference.class))) - throw new DurableException( - DurableException.Code.INVALID, "Object header differs"); - var bytes = new ByteArrayOutputStream(); - for (long offset = 0; offset < reference.size(); offset += CHUNK_BYTES) { - var chunk = tx.get("chunk:" + offset / CHUNK_BYTES); - if (chunk == null) - throw new DurableException( - DurableException.Code.INVALID, "Object chunk missing"); - byte[] decoded = Base64.getDecoder().decode(chunk.asText()); - if (decoded.length != Math.min(CHUNK_BYTES, reference.size() - offset)) - throw new DurableException( - DurableException.Code.INVALID, "Object chunk size differs"); - bytes.writeBytes(decoded); - } - return ObjectStore.verify(id(), reference, bytes.toByteArray()); - }); + byte[] hit = cached(reference); + if (hit != null) return hit.clone(); + byte[] loaded = + records.transaction( + "object:" + reference.key(), + tx -> { + var existing = tx.get(""); + if (existing == null) + throw new DurableException( + DurableException.Code.NOT_FOUND, "Object not found"); + if (!reference.equals(DurableJson.convert(existing, Reference.class))) + throw new DurableException( + DurableException.Code.INVALID, "Object header differs"); + var bytes = new ByteArrayOutputStream(); + for (long offset = 0; + offset < reference.size(); + offset += CHUNK_BYTES) { + var chunk = tx.get("chunk:" + offset / CHUNK_BYTES); + if (chunk == null) + throw new DurableException( + DurableException.Code.INVALID, "Object chunk missing"); + byte[] decoded = Base64.getDecoder().decode(chunk.asText()); + if (decoded.length + != Math.min(CHUNK_BYTES, reference.size() - offset)) + throw new DurableException( + DurableException.Code.INVALID, + "Object chunk size differs"); + bytes.writeBytes(decoded); + } + return ObjectStore.verify(id(), reference, bytes.toByteArray()); + }); + remember(reference, loaded); + return loaded; } } diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java index c8b8783599..c55d25ea96 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java @@ -28,6 +28,8 @@ import io.agentscope.durable.DurableTypes.SessionSpec; import io.agentscope.durable.DurableTypes.ThreadBinding; import io.agentscope.durable.TransactionalSessionBackend; +import io.agentscope.durable.store.ObjectStore; +import io.agentscope.durable.store.RecordObjectStore; import io.agentscope.durable.store.RecordStore; import java.nio.file.Path; import java.sql.DriverManager; @@ -83,6 +85,35 @@ void close() throws Exception { } } + @Test + void immutableChunkHitsAvoidDatabaseTransactionsAndNeverExposeCachedBytes() throws Exception { + var borrows = new java.util.concurrent.atomic.AtomicInteger(); + try (var counted = + new JdbcRecordStore( + () -> { + borrows.incrementAndGet(); + return connections.open(); + }, + dialect, + false)) { + var objects = new RecordObjectStore(counted); + byte[] value = {1, 2, 3}; + var scope = ObjectStore.digest(new byte[0]); + var ref = objects.put(scope, value); + int afterCommit = borrows.get(); + value[0] = 9; + objects.read(ref)[1] = 9; + assertEquals(ref, objects.put(scope, new byte[] {1, 2, 3})); + org.junit.jupiter.api.Assertions.assertArrayEquals( + new byte[] {1, 2, 3}, objects.read(ref)); + assertEquals(afterCommit, borrows.get()); + var cold = new RecordObjectStore(counted); + org.junit.jupiter.api.Assertions.assertArrayEquals( + new byte[] {1, 2, 3}, cold.read(ref)); + assertEquals(afterCommit + 1, borrows.get()); + } + } + @Test void siblingsRetainIndependentPayloadsOrderingAndDeadlinesAfterReopen() { store.transaction( From 7f24002994b3aebbb7f4ed0725742d0ce92574d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:44:33 +0800 Subject: [PATCH 22/38] Share growing journal indexes at immutable descriptor boundaries --- .../io/agentscope/durable/JournalContent.java | 45 +++++++++++++++---- .../durable/JournalContentTest.java | 5 +++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java index 18cee868de..338c823e1d 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java @@ -27,6 +27,9 @@ final class JournalContent { private static final int MIN = 1024; private static final int MAX = 8192; private static final int DESCRIPTOR = 36; + // The manifest changes on every append. Small, descriptor-aligned pages allow the + // stable interior of the index to be reused before it reaches data-chunk size. + private static final int MAX_INDEX = 32 * DESCRIPTOR; private static final HexFormat HEX = HexFormat.of(); record Root(Reference reference, int levels, int size, String digest) {} @@ -36,7 +39,7 @@ static Root put(ObjectStore store, String scope, byte[] bytes) { throw new IllegalArgumentException("Journal content too large"); byte[] layer = bytes; int levels = 0; - while (layer.length > MAX) { + if (layer.length > MAX) { var index = new ByteArrayOutputStream(); int hash = 0; int start = 0; @@ -46,12 +49,7 @@ static Root put(ObjectStore store, String scope, byte[] bytes) { if (length >= MAX || (length >= MIN && (hash & 2047) == 0) || i == layer.length - 1) { - var chunk = store.put(scope, Arrays.copyOfRange(layer, start, i + 1)); - index.writeBytes( - ByteBuffer.allocate(DESCRIPTOR) - .putInt(length) - .put(HEX.parseHex(chunk.digest())) - .array()); + appendChunk(store, scope, layer, start, i + 1, index); start = i + 1; hash = 0; } @@ -59,9 +57,40 @@ static Root put(ObjectStore store, String scope, byte[] bytes) { layer = index.toByteArray(); levels++; } + while (levels > 0 && layer.length > MAX_INDEX) { + var index = new ByteArrayOutputStream(); + int start = 0; + for (int end = DESCRIPTOR; end <= layer.length; end += DESCRIPTOR) { + int length = end - start; + // The last digest byte is stable even when preceding descriptors change. + if (length == MAX_INDEX + || (length >= 4 * DESCRIPTOR && (layer[end - 1] & 7) == 0) + || end == layer.length) { + appendChunk(store, scope, layer, start, end, index); + start = end; + } + } + layer = index.toByteArray(); + levels++; + } return new Root(store.put(scope, layer), levels, bytes.length, ObjectStore.digest(bytes)); } + private static void appendChunk( + ObjectStore store, + String scope, + byte[] layer, + int start, + int end, + ByteArrayOutputStream index) { + var chunk = store.put(scope, Arrays.copyOfRange(layer, start, end)); + index.writeBytes( + ByteBuffer.allocate(DESCRIPTOR) + .putInt(end - start) + .put(HEX.parseHex(chunk.digest())) + .array()); + } + private static final int[] GEAR = gearTable(); private static int[] gearTable() { @@ -72,7 +101,7 @@ private static int[] gearTable() { } static byte[] read(ObjectStore store, String scope, Root root) { - if (!root.reference().scope().equals(scope) || root.levels() < 0 || root.levels() > 4) + if (!root.reference().scope().equals(scope) || root.levels() < 0 || root.levels() > 8) throw new DurableException(DurableException.Code.INVALID, "Invalid journal index"); var expected = new Reference(store.id(), scope, root.digest(), root.size()); byte[] layer = store.read(root.reference()); diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java index f2af4049b7..ea15484471 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java @@ -53,6 +53,11 @@ public byte[] read(Reference ref) { roots.add(JournalContent.put(objects, scope, Arrays.copyOf(history, turn * 2048))); } assertTrue(roots.get(511).levels() >= 2); + assertTrue( + roots.stream() + .filter(root -> root.levels() > 0) + .allMatch(root -> root.reference().size() <= 32 * 36), + "Growing histories must share the index instead of copying all leaf descriptors"); long stored = chunks.values().stream().mapToLong(chunk -> chunk.length).sum(); assertTrue(stored < history.length * 10L, "Unique chunk and index bytes: " + stored); for (int i = 0; i < roots.size(); i++) From fa8845a8bac4f28b008f4eb7b340eb9c040312c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:46:10 +0800 Subject: [PATCH 23/38] Exercise paired RocketMQ consumers and attribute shared journal storage --- agentscope-durable/README.md | 20 ++ .../docker-regression/ConsumerPairProbe.java | 79 +++++++ .../docker-regression/compare_consumers.py | 222 ++++++++++++++++++ .../docker-regression/profile_journal.py | 140 +++++++++++ 4 files changed, 461 insertions(+) create mode 100644 agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java create mode 100644 agentscope-durable/scripts/docker-regression/compare_consumers.py create mode 100644 agentscope-durable/scripts/docker-regression/profile_journal.py diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index c314a765b9..08ef2fa14c 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -475,6 +475,26 @@ terminal events, displayed answers and subscriber cursors. The runner removes it volumes and network on exit. Set `ROCKETMQ_IMAGE` to use a locally available RocketMQ 5 image with the broker proxy and `mqadmin` tools. +The paired-consumer comparison starts separate NameServer, Broker, Proxy and consumer JVMs, +runs eight queues with the same consumer group, and varies only the broker direct-memory limit. +It 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 +``` + +For a single-Thread PostgreSQL test database, the read-only profiler attributes +`durable_parts.payload` bytes to native checkpoints, other journal entries and their +shared immutable chunks. Each shared chunk is counted once. The milestone is the +number of distinct Turns encountered in journal order. Take the measurement after +the last measured Turn finishes. Checkpoint-history rows, events, PostgreSQL indexes +and TOAST statistics can be measured separately. + +```sh +python3 agentscope-durable/scripts/docker-regression/profile_journal.py CONTAINER DATABASE USER 100 1000 +``` + Normal checking covers build, formatting and tests. Isolation checking builds source dependencies in a separate Maven cache and audits dependency trees. Validate broker delivery, provider query/cancel diff --git a/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java new file mode 100644 index 0000000000..58bd52509b --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java @@ -0,0 +1,79 @@ +/* + * 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 = 0; 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); + } + } + 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/compare_consumers.py b/agentscope-durable/scripts/docker-regression/compare_consumers.py new file mode 100644 index 0000000000..457ce09864 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/compare_consumers.py @@ -0,0 +1,222 @@ +#!/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=-Xms512m -Xmx1g -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) + 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=-Xms512m -Xmx1g -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): + def publish(): + result = lab.run( + "docker", + "run", + "--rm", + *options, + *java, + "send", + prefix, + str(count), + check=False, + ) + if result.returncode == 0: + return True + if ( + "ClientImpl.startUp" in result.stdout + and "response-code=40402" in result.stdout + ): + 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, 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") + print( + memory, + "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/profile_journal.py b/agentscope-durable/scripts/docker-regression/profile_journal.py new file mode 100644 index 0000000000..b14084dbbe --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/profile_journal.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Attribute persisted journal bytes on a single-thread Docker PostgreSQL test database.""" + +import argparse +import base64 +import collections +import json +import re +import struct +import subprocess + +DESCRIPTOR = struct.Struct(">I32s") + + +def profile(container, database, user, milestones): + # One statement gives the journal roots and the immutable chunks one MVCC view. + query = """ + SELECT record_key, part_key, payload + FROM durable_parts + WHERE part_key LIKE '%:journal:%' OR record_key LIKE 'object:%' + ORDER BY record_key, part_key + """ + command = [ + "docker", + "exec", + container, + "psql", + "-XqAt", + "-v", + "ON_ERROR_STOP=1", + "-U", + user, + "-d", + database, + "-F", + "\t", + "-c", + query, + ] + objects = {} + journal = [] + with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process: + for row in process.stdout: + record, part, payload = row.rstrip("\n").split("\t", 2) + if record.startswith("object:"): + if part == "chunk:0": + objects[record.split("/", 1)[1]] = ( + base64.b64decode(json.loads(payload)), + len(payload.encode()), + ) + else: + journal.append( + ( + record, + part.split(":journal:", 1)[0], + json.loads(payload), + len(payload.encode()), + ) + ) + if process.wait(): + raise RuntimeError("Could not read PostgreSQL journal") + if len({(record, prefix) for record, prefix, _, _ in journal}) != 1: + raise ValueError("Use a database containing exactly one measured Thread") + + usage = collections.defaultdict(int) + manifests = set() + turns = set() + inline_and_roots = [0, 0] + + def report(): + totals = collections.Counter() + for digest, mask in usage.items(): + totals[("journal", "snapshots", "shared")[mask - 1]] += objects[digest][1] + totals["journal"] += inline_and_roots[0] + totals["snapshots"] += inline_and_roots[1] + print( + json.dumps( + { + "turns": len(turns), + **totals, + "index_bytes_included": sum(objects[h][1] for h in manifests), + }, + sort_keys=True, + ) + ) + + for _, _, stored, length in journal: + references = set() + index_references = set() + if "chunked" in stored: + root = stored["chunked"] + key = root["reference"]["digest"] + references.add(key) + if root["levels"]: + index_references.add(key) + index = objects[key][0] + for level in range(root["levels"], 0, -1): + keys = [digest.hex() for _, digest in DESCRIPTOR.iter_unpack(index)] + references.update(keys) + if level > 1: + index_references.update(keys) + # The first leaf holds the journal envelope. Avoid reconstructing the history. + index = ( + objects[keys[0]][0] + if level == 1 + else b"".join(objects[k][0] for k in keys) + ) + + def header(field): + match = re.search(rb'"' + field + rb'":"([^"]+)"', index) + if not match: + raise ValueError("Missing journal header " + field.decode()) + return match[1].decode() + + kind, turn = header(b"type"), header(b"turnId") + else: + kind, turn = (stored["inline"][k] for k in ("type", "turnId")) + if turn not in turns: + if len(turns) in milestones: + report() + turns.add(turn) + manifests.update(index_references) + snapshot = kind == "state/checkpoint" + inline_and_roots[int(snapshot)] += length + for key in references: + usage[key] |= 2 if snapshot else 1 + if len(turns) in milestones: + report() + if not milestones or max(milestones) > len(turns): + raise ValueError(f"Only {len(turns)} Turns have journal entries") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("container") + parser.add_argument("database") + parser.add_argument("user") + parser.add_argument("milestones", nargs="+", type=int) + args = parser.parse_args() + profile(args.container, args.database, args.user, set(args.milestones)) From dcb774fe2907c1c17f103cdbe3908dc94957d57c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 17:58:39 +0800 Subject: [PATCH 24/38] Bound database prefix scans with matching binary-order indexes --- agentscope-durable/README.md | 5 ++ .../durable/jdbc/JdbcRecordStore.java | 77 ++++++++++++------- .../durable/jdbc/ScopedWorkStoreTest.java | 24 ++++++ 3 files changed, 78 insertions(+), 28 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 08ef2fa14c..9e2ce99b5d 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -325,6 +325,11 @@ the hosts at the same database. Each host needs matching definition/state versio and access to the required tools and workspace resources. Close each host and its Backend at application shutdown; the application owns the supplied pool. +Schema initialization also creates the binary-collation indexes used for prefix pagination. +For an existing database, run the initializer with the provisioning identity to install +`durable_parts_prefix` and `durable_records_prefix`. Ordinary runtime startup uses +the existing schema. + PostgreSQL record transactions use a 30-second idle-in-transaction timeout when the database setting is disabled. An existing positive timeout takes precedence. This lets PostgreSQL release record locks after a disconnected host stops sending SQL. 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 6f113ed7cb..8fd4849962 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 @@ -114,6 +114,14 @@ public JdbcRecordStore(Connections connections, Dialect dialect, boolean initial statement.executeUpdate( "CREATE INDEX IF NOT EXISTS durable_work_ready ON" + " durable_work(queue,ready_at,record_key,work_id)"); + if (dialect == Dialect.POSTGRESQL) { + statement.executeUpdate( + "CREATE INDEX IF NOT EXISTS durable_parts_prefix ON durable_parts" + + " (record_key, part_key COLLATE \"C\")"); + statement.executeUpdate( + "CREATE INDEX IF NOT EXISTS durable_records_prefix ON durable_records" + + " (record_key COLLATE \"C\") WHERE payload IS NOT NULL"); + } } } catch (SQLException e) { throw unavailable(e); @@ -293,15 +301,13 @@ public void put(String part, JsonNode value) { public List keys(String prefix, String after, int limit) { checkLimit(limit); + String upper = prefixEnd(prefix); try (var s = connection.prepareStatement( "SELECT part_key FROM durable_parts WHERE record_key=? AND " - + prefixPage("part_key"))) { + + prefixPage("part_key", upper))) { s.setString(1, scope); - s.setString(2, prefix); - s.setString(3, dialect == Dialect.POSTGRESQL ? prefix : prefix + "\uffff"); - s.setString(4, after == null ? "" : after); - s.setInt(5, limit); + bindPage(s, 2, prefix, upper, after, limit); try (var rs = s.executeQuery()) { var keys = new ArrayList(); while (rs.next()) keys.add(rs.getString(1)); @@ -378,42 +384,57 @@ private static void checkKey(String value, int limit, String name) { throw new IllegalArgumentException("Invalid " + name); } - private String prefixPage(String column) { - if (dialect == Dialect.POSTGRESQL) { - String key = column + " COLLATE \"C\""; - return key - + ">=? AND starts_with(" - + column - + ",?) AND " - + key - + ">? ORDER BY " - + key - + " LIMIT ?"; + private static String prefixEnd(String prefix) { + // UTF-8 byte order agrees with scalar-value order. Carry past maximal suffixes + // and skip surrogates to keep the exclusive upper bound a valid database string. + for (int end = prefix.length(); end > 0; ) { + int cp = prefix.codePointBefore(end); + end -= Character.charCount(cp); + if (cp < Character.MAX_CODE_POINT) { + int next = cp == Character.MIN_SURROGATE - 1 ? Character.MAX_SURROGATE + 1 : cp + 1; + return prefix.substring(0, end) + Character.toString(next); + } } - return column - + ">=? AND " - + column - + "=?" + + (upper == null ? "" : " AND " + key + "? ORDER BY " - + column + + key + " LIMIT ?"; } + private static void bindPage( + java.sql.PreparedStatement statement, + int index, + String prefix, + String upper, + String after, + int limit) + throws SQLException { + statement.setString(index++, prefix); + if (upper != null) statement.setString(index++, upper); + statement.setString(index++, after == null ? "" : after); + statement.setInt(index, limit); + } + @Override public List keys(String prefix, String after, int limit) { if (limit < 1 || limit > 1000) throw new IllegalArgumentException("Limit must be 1..1000"); - // Lexical bounds avoid LIKE wildcard interpretation in namespaces. + String upper = prefixEnd(prefix); try (Connection c = connect(); var s = c.prepareStatement( "SELECT record_key FROM durable_records WHERE payload IS NOT NULL" + " AND " - + prefixPage("record_key"))) { - s.setString(1, prefix); - s.setString(2, dialect == Dialect.POSTGRESQL ? prefix : prefix + "\uffff"); - s.setString(3, after == null ? "" : after); - s.setInt(4, limit); + + prefixPage("record_key", upper))) { + bindPage(s, 1, prefix, upper, after, limit); try (var rs = s.executeQuery()) { List result = new ArrayList<>(); while (rs.next()) result.add(rs.getString(1)); diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java index c55d25ea96..874c572e00 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java @@ -85,6 +85,30 @@ void close() throws Exception { } } + @Test + void prefixBoundsCoverSupplementarySuffixesAndCarryPastMaximalScalars() { + String max = Character.toString(Character.MAX_CODE_POINT); + String prefix = "literal_%:" + max; + store.transaction( + "unicode", + tx -> { + for (var key : + List.of( + prefix, + prefix + max, + "literal_%;", + "a\uD7FF", + "a\uE000", + max, + max + "x")) tx.put(key, DurableJson.value(1)); + assertEquals(List.of(prefix, prefix + max), tx.keys(prefix, null, 10)); + assertEquals(List.of(prefix + max), tx.keys(prefix, prefix, 1)); + assertEquals(List.of("a\uD7FF"), tx.keys("a\uD7FF", null, 10)); + assertEquals(List.of(max, max + "x"), tx.keys(max, null, 10)); + return null; + }); + } + @Test void immutableChunkHitsAvoidDatabaseTransactionsAndNeverExposeCachedBytes() throws Exception { var borrows = new java.util.concurrent.atomic.AtomicInteger(); From 7cf9c449a5327b1cc6619083b61f87c8f4e8945a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 18:33:32 +0800 Subject: [PATCH 25/38] Verify RocketMQ direct-memory limits and resume publication from receipts --- agentscope-durable/README.md | 12 +++++- .../docker-regression/ConsumerPairProbe.java | 3 +- .../docker-regression/compare_consumers.py | 40 +++++++++++++++---- .../scripts/docker-regression/run.py | 16 +++++++- 4 files changed, 60 insertions(+), 11 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 9e2ce99b5d..71815a5319 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -481,8 +481,16 @@ volumes and network on exit. Set `ROCKETMQ_IMAGE` to use a locally available Roc with the broker proxy and `mqadmin` tools. The paired-consumer comparison starts separate NameServer, Broker, Proxy and consumer JVMs, -runs eight queues with the same consumer group, and varies only the broker direct-memory limit. -It checks ordinary delivery, repeated receive deadlines during a Proxy pause, and redelivery +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 diff --git a/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java index 58bd52509b..daebc597a8 100644 --- a/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java +++ b/agentscope-durable/scripts/docker-regression/ConsumerPairProbe.java @@ -38,7 +38,7 @@ public static void main(String[] args) throws Exception { .setTopics(topic) .build()) { int count = Integer.parseInt(args[2]); - for (int i = 0; i < count; i++) { + for (int i = Integer.parseInt(args[3]); i < count; i++) { String key = args[1] + i; var message = provider.newMessageBuilder() .setTopic(topic) @@ -46,6 +46,7 @@ public static void main(String[] args) throws Exception { .setBody(key.getBytes(StandardCharsets.UTF_8)) .build(); producer.send(message); + System.out.println("SENT " + i); } } return; diff --git a/agentscope-durable/scripts/docker-regression/compare_consumers.py b/agentscope-durable/scripts/docker-regression/compare_consumers.py index 457ce09864..bebd55cee9 100644 --- a/agentscope-durable/scripts/docker-regression/compare_consumers.py +++ b/agentscope-durable/scripts/docker-regression/compare_consumers.py @@ -15,7 +15,7 @@ def exercise(folder, memory): lab.start( broker, lab.MQ, - ["-e", f"JAVA_OPT_EXT=-Xms512m -Xmx1g -XX:MaxDirectMemorySize={memory}"], + ["-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", @@ -35,6 +35,13 @@ def admin(*options): ) 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", @@ -58,7 +65,7 @@ def admin(*options): lab.start( proxy, lab.MQ, - ["-e", "JAVA_OPT_EXT=-Xms512m -Xmx1g -XX:MaxDirectMemorySize=1g"], + ["-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", @@ -90,7 +97,10 @@ def admin(*options): ) def send(prefix, count): + next_index = 0 + def publish(): + nonlocal next_index result = lab.run( "docker", "run", @@ -100,14 +110,18 @@ def publish(): "send", prefix, str(count), + str(next_index), check=False, ) if result.returncode == 0: return True - if ( - "ClientImpl.startUp" in result.stdout - and "response-code=40402" in result.stdout - ): + 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:]) @@ -135,7 +149,14 @@ def deadlines(): send("healthy", 16) lab.wait("healthy delivery", lambda: len(acks()) == 16) normal = deadlines() - print(memory, "normal deadlines", normal, flush=True) + print( + memory, + "normal deadlines", + normal, + "POP direct-memory error lines", + lab.pop_memory_errors(broker), + flush=True, + ) lab.docker("pause", lab.name(proxy)) try: @@ -164,8 +185,13 @@ def deadlines(): ["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", diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 1e59637bf4..5002a0746b 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -77,6 +77,17 @@ 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", @@ -322,7 +333,7 @@ def retried(): start( "broker", MQ, - ["-e", "JAVA_OPT_EXT=-Xms256m -Xmx384m -XX:MaxDirectMemorySize=256m"], + ["-e", "JAVA_OPT_EXT=-Xms256m -Xmx384m -XX:MaxDirectMemorySize=1g"], "sh", "-c", "printf 'brokerName=regression\nbrokerIP1=broker\nautoCreateTopicEnable=true\n' >/tmp/b.conf && exec sh mqbroker -n ns:9876 -c /tmp/b.conf --enable-proxy", @@ -572,6 +583,9 @@ def pointer(): docker("network", "create", PROJECT) try: 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( From 6e8f755170bd47b32bc77e1cdb4c04f5a9fd759c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 19:48:16 +0800 Subject: [PATCH 26/38] Bound uncertain Hands recovery and retain acknowledged provider handles --- .../agentscope/durable/ExecutionRecovery.java | 3 + .../java/io/agentscope/durable/Executor.java | 2 +- .../durable/ExecutionRecoveryTest.java | 17 ++++- .../worker/TransactionalExecutionStore.java | 70 +++++++++++++++---- .../durable/worker/WorkerRuntimeTest.java | 41 +++++++++++ agentscope-durable/protocol/README.md | 12 ++++ .../durable/rocketmq/RocketMqWorker.java | 10 ++- docs/dev/en/docs/harness/durable.md | 4 ++ docs/dev/zh/docs/harness/durable.md | 4 ++ 9 files changed, 146 insertions(+), 17 deletions(-) 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 589b3a5896..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 @@ -50,7 +50,7 @@ default void validateStart(ExecutionRequest request) {} /** * Return NOT_FOUND only for authoritative absence. A worker may then issue another start - * when idempotentStart is advertised. A timeout, partition, or eventually consistent lookup + * 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. */ 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 2ff60d45f6..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 @@ -122,12 +122,25 @@ void uncertainLookupOfRunningExecutionDoesNotRestartEvenAnIdempotentProvider() { @Test void authoritativeAbsenceAllowsIdempotentStartWithTheSameExecutionId() { when(executor.capabilities()).thenReturn(new Executor.Capabilities(true, true, false)); - when(executor.query(request, "recovered")).thenReturn(ExecutionResult.missing()); + when(executor.query(request, null)).thenReturn(ExecutionResult.missing()); when(executor.startExecution(request)).thenReturn(running); - assertEquals(running, ExecutionRecovery.resolve(executor, request, running, true, false)); + 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-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 0ce5f1a851..118e52a087 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 @@ -41,14 +41,28 @@ public final class TransactionalExecutionStore implements ExecutionStore { private final RecordStore records; private final String prefix; + public static final int DEFAULT_UNKNOWN_LIMIT = 8; + private final int unknownLimit; + public TransactionalExecutionStore(RecordStore records) { - this.records = records; - prefix = "execution:"; + this(records, null, DEFAULT_UNKNOWN_LIMIT); } public TransactionalExecutionStore(RecordStore records, String pool) { + this(records, DurableJson.text(pool, "pool"), DEFAULT_UNKNOWN_LIMIT); + } + + /** Freeze the maximum consecutive uncertain provider observations when admitting an execution. */ + public TransactionalExecutionStore(RecordStore records, String pool, int unknownLimit) { + 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")) + + ":"; } public static final class State { @@ -62,6 +76,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; @@ -106,25 +122,25 @@ private void save(State state) { state.request.executionId(), state.publishedSequence < state.sequence ? 0 : -1, DurableJson.value(null)); - boolean settled = state.result.state().terminal() && state.outputSealed; + boolean stopAutomaticWork = + state.result.state().terminal() && state.outputSealed + || state.unknownObservations >= state.unknownLimit; boolean recovery = state.attempted || state.cancelled; long readyAt = Math.max(state.expiresAt, state.nextAttemptAt); state.tx.schedule( "hands-start:" + prefix, state.request.executionId(), - settled || recovery ? -1 : readyAt, + stopAutomaticWork || recovery ? -1 : readyAt, DurableJson.value(null)); state.tx.schedule( "hands-recovery:" + prefix, state.request.executionId(), - settled || !recovery ? -1 : readyAt, + stopAutomaticWork || !recovery ? -1 : readyAt, DurableJson.value(null)); state.tx.schedule( "hands:" + prefix, state.request.executionId(), - state.result.state().terminal() && state.outputSealed - ? -1 - : Math.max(state.expiresAt, state.nextAttemptAt), + stopAutomaticWork ? -1 : Math.max(state.expiresAt, state.nextAttemptAt), DurableJson.value(state.request.call().executor())); } @@ -146,10 +162,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); @@ -196,8 +213,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; @@ -379,9 +398,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(); @@ -462,12 +483,35 @@ public void 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 701504fd2b..285e252077 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 @@ -277,6 +277,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); + 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); + 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"))) { diff --git a/agentscope-durable/protocol/README.md b/agentscope-durable/protocol/README.md index 5be3bd6d23..5694158541 100644 --- a/agentscope-durable/protocol/README.md +++ b/agentscope-durable/protocol/README.md @@ -446,6 +446,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, @@ -453,6 +458,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-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 f68a146b5c..83d5a0fd7c 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 @@ -59,7 +59,7 @@ private RocketMqWorker(Builder builder) { authorizer = builder.authorizer; interval = builder.interval; builder.records.boundIdleTransactionTime(builder.lease); - store = new TransactionalExecutionStore(builder.records, name); + store = new TransactionalExecutionStore(builder.records, name, builder.unknownLimit); ClientServiceProvider provider = builder.provider; Producer configuredProducer; SimpleConsumer configuredConsumer; @@ -257,6 +257,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 -> @@ -297,6 +298,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/docs/dev/en/docs/harness/durable.md b/docs/dev/en/docs/harness/durable.md index a7c6d19ce3..040188be74 100644 --- a/docs/dev/en/docs/harness/durable.md +++ b/docs/dev/en/docs/harness/durable.md @@ -1000,3 +1000,7 @@ tasks in a reused Thread. Cancellation before admission stores a tombstone; a la The transaction rejects cross-Session targets, the parent Thread itself and Thread dependency cycles formed by unfinished delegations. `turn.delegated`, `tool.delegated` and `tool.delegation.cancel_requested` are common public events; they do not replace the actual child result or its application by the parent. + +### Uncertain Hands executions + +Hands keeps querying an admitted provider handle across worker replacement. A missing lookup retains that handle. Before a handle exists, repeated start requires provider-side idempotency across all workers. After eight consecutive UNKNOWN observations by default, the transactional Hands ledger pauses automatic recovery. RocketMQ hosts can set `RocketMqWorker.Builder.unknownLimit` for new executions. The ledger freezes the limit at admission. An operator can claim the exact execution and reconcile with external evidence. The first cancellation wakes parked work to check cancellation; duplicate cancellations preserve its budget. diff --git a/docs/dev/zh/docs/harness/durable.md b/docs/dev/zh/docs/harness/durable.md index f0e4454a82..39656f5d67 100644 --- a/docs/dev/zh/docs/harness/durable.md +++ b/docs/dev/zh/docs/harness/durable.md @@ -875,3 +875,7 @@ var children = new DelegationExecutor(backend, request -> 取消先于受理时只保存取消记录,后续迟到的 start 不会创建子任务。事务内拒绝跨 Session、父 Thread 自身及未完成委派形成的 Thread 依赖环。`turn.delegated`、`tool.delegated` 和 `tool.delegation.cancel_requested` 是统一公开事件;它们不替代真实子任务结果及父任务的结果应用。 + +### Hands 执行结果不确定时的恢复 + +服务端已返回执行句柄时,接管的 Hands 会继续查询原句柄。查询返回缺失时仍保留该句柄。没有句柄时,只有提供方能对所有 Hands 按同一 executionId 去重才允许再次启动。事务型 Hands 账本默认在连续 8 次 UNKNOWN 后暂停自动恢复。RocketMQ 宿主可通过 `RocketMqWorker.Builder.unknownLimit` 设置新执行的上限,账本在接纳执行时固定该值。运维端可按原执行身份领取租约,依据外部证据核实结果。首次取消会唤醒已暂停的执行以核实取消结果,重复取消保留原有预算。 From f3c40d1a2d484d4c996501899caa4c6c52d74b19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 19:53:22 +0800 Subject: [PATCH 27/38] Cache error responses by provider key in the Docker model fixture --- .../scripts/docker-regression/Probe.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/agentscope-durable/scripts/docker-regression/Probe.java b/agentscope-durable/scripts/docker-regression/Probe.java index c3dd4d0290..78faa1dad8 100644 --- a/agentscope-durable/scripts/docker-regression/Probe.java +++ b/agentscope-durable/scripts/docker-regression/Probe.java @@ -110,7 +110,7 @@ public static String answer(String turn, GenerateOptions options) { static void model() throws Exception { var server = HttpServer.create(new InetSocketAddress(8080), 0); - var generated = java.util.concurrent.ConcurrentHashMap.newKeySet(); + var statusByKey = new java.util.concurrent.ConcurrentHashMap(); server.createContext( "/", exchange -> { @@ -121,7 +121,10 @@ static void model() throws Exception { exchange.sendResponseHeaders(400, -1); return; } - if (generated.add(key)) System.out.println("INFERENCE " + turn); + 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 { @@ -130,8 +133,8 @@ static void model() throws Exception { return; } } - if (Files.exists(Path.of("/tmp/fail"))) { - exchange.sendResponseHeaders(500, -1); + if (status != 200) { + exchange.sendResponseHeaders(status, -1); return; } var bytes = From c2e59a9325bb5139bda8566405dd8b6fe01492e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Mon, 16 Nov 2026 20:03:21 +0800 Subject: [PATCH 28/38] Compress immutable record chunks and attribute journal writes by event type --- agentscope-durable/README.md | 7 ++- .../durable/store/RecordObjectStore.java | 52 +++++++++++++++++-- .../docker-regression/profile_journal.py | 32 ++++++++++-- .../durable/jdbc/ScopedWorkStoreTest.java | 24 +++++++++ 4 files changed, 106 insertions(+), 9 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index 71815a5319..d310de27c5 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -499,13 +499,16 @@ python3 agentscope-durable/scripts/docker-regression/compare_consumers.py For a single-Thread PostgreSQL test database, the read-only profiler attributes `durable_parts.payload` bytes to native checkpoints, other journal entries and their -shared immutable chunks. Each shared chunk is counted once. The milestone is the +shared immutable chunks. Each shared chunk is counted once. The record-backed +object store compresses each compressible chunk after deduplication, preserving +its original content digest. The profiler reports the stored payload length. With `--detail-turn`, the per-type breakdown attributes a shared chunk to the first +event that wrote it. The milestone is the number of distinct Turns encountered in journal order. Take the measurement after the last measured Turn finishes. Checkpoint-history rows, events, PostgreSQL indexes and TOAST statistics can be measured separately. ```sh -python3 agentscope-durable/scripts/docker-regression/profile_journal.py CONTAINER DATABASE USER 100 1000 +python3 agentscope-durable/scripts/docker-regression/profile_journal.py CONTAINER DATABASE USER 100 1000 --detail-turn 100 ``` Normal checking covers build, formatting and tests. Isolation checking builds source diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java index d9f496af56..3d6cb8bc15 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java @@ -22,6 +22,9 @@ import java.util.Base64; import java.util.LinkedHashMap; import java.util.Objects; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; /** Database fallback for small installations; production hosts may supply object storage. */ public final class RecordObjectStore implements ObjectStore { @@ -69,9 +72,7 @@ public Reference put(String scope, byte[] bytes) { bytes, offset, Math.min(bytes.length, offset + CHUNK_BYTES)); - tx.put( - "chunk:" + offset / CHUNK_BYTES, - DurableJson.value(Base64.getEncoder().encodeToString(chunk))); + tx.put("chunk:" + offset / CHUNK_BYTES, DurableJson.value(encode(chunk))); } tx.put("", DurableJson.value(reference)); return null; @@ -80,6 +81,43 @@ public Reference put(String scope, byte[] bytes) { return reference; } + // Keep incompressible objects raw. The marker is outside the Base64 alphabet. + private static String encode(byte[] chunk) { + if (chunk.length >= 256) { + var encoder = new Deflater(Deflater.BEST_SPEED); + try { + encoder.setInput(chunk); + encoder.finish(); + byte[] compressed = new byte[chunk.length - 16]; + int length = encoder.deflate(compressed); + if (encoder.finished()) + return "~" + + Base64.getEncoder().encodeToString(Arrays.copyOf(compressed, length)); + } finally { + encoder.end(); + } + } + return Base64.getEncoder().encodeToString(chunk); + } + + private static byte[] decode(String stored, int size) { + if (!stored.startsWith("~")) return Base64.getDecoder().decode(stored); + var decoder = new Inflater(); + try { + decoder.setInput(Base64.getDecoder().decode(stored.substring(1))); + byte[] bytes = new byte[size]; + if (decoder.inflate(bytes) == size && decoder.finished() && decoder.getRemaining() == 0) + return bytes; + throw new DurableException( + DurableException.Code.INVALID, "Invalid compressed object size"); + } catch (DataFormatException invalid) { + throw new DurableException( + DurableException.Code.INVALID, "Invalid compressed object", invalid); + } finally { + decoder.end(); + } + } + public byte[] read(Reference reference) { if (!id().equals(reference.store())) throw new DurableException(DurableException.Code.INVALID, "Object store differs"); @@ -104,7 +142,13 @@ public byte[] read(Reference reference) { if (chunk == null) throw new DurableException( DurableException.Code.INVALID, "Object chunk missing"); - byte[] decoded = Base64.getDecoder().decode(chunk.asText()); + byte[] decoded = + decode( + chunk.asText(), + (int) + Math.min( + CHUNK_BYTES, + reference.size() - offset)); if (decoded.length != Math.min(CHUNK_BYTES, reference.size() - offset)) throw new DurableException( diff --git a/agentscope-durable/scripts/docker-regression/profile_journal.py b/agentscope-durable/scripts/docker-regression/profile_journal.py index b14084dbbe..b32421e3c8 100644 --- a/agentscope-durable/scripts/docker-regression/profile_journal.py +++ b/agentscope-durable/scripts/docker-regression/profile_journal.py @@ -8,11 +8,12 @@ import re import struct import subprocess +import zlib DESCRIPTOR = struct.Struct(">I32s") -def profile(container, database, user, milestones): +def profile(container, database, user, milestones, detail_turn=None): # One statement gives the journal roots and the immutable chunks one MVCC view. query = """ SELECT record_key, part_key, payload @@ -44,8 +45,14 @@ def profile(container, database, user, milestones): record, part, payload = row.rstrip("\n").split("\t", 2) if record.startswith("object:"): if part == "chunk:0": + encoded = json.loads(payload) + data = ( + zlib.decompress(base64.b64decode(encoded[1:])) + if encoded.startswith("~") + else base64.b64decode(encoded) + ) objects[record.split("/", 1)[1]] = ( - base64.b64decode(json.loads(payload)), + data, len(payload.encode()), ) else: @@ -65,6 +72,7 @@ def profile(container, database, user, milestones): usage = collections.defaultdict(int) manifests = set() turns = set() + detail = {} inline_and_roots = [0, 0] def report(): @@ -119,6 +127,19 @@ def header(field): if len(turns) in milestones: report() turns.add(turn) + if detail_turn == len(turns): + row = detail.setdefault( + kind, {"entries": 0, "serialized_bytes": 0, "new_stored_payload_bytes": 0} + ) + row["entries"] += 1 + if "chunked" in stored: + row["serialized_bytes"] += root["size"] + else: + inline = json.dumps(stored["inline"], separators=(",", ":"), ensure_ascii=False) + row["serialized_bytes"] += len(inline.encode()) + row["new_stored_payload_bytes"] += length + sum( + objects[key][1] for key in references if key not in usage + ) manifests.update(index_references) snapshot = kind == "state/checkpoint" inline_and_roots[int(snapshot)] += length @@ -126,6 +147,10 @@ def header(field): usage[key] |= 2 if snapshot else 1 if len(turns) in milestones: report() + if detail_turn is not None: + if not detail: + raise ValueError("Requested detail Turn was not found") + print(json.dumps({"detail_turn": detail_turn, "types": detail}, sort_keys=True)) if not milestones or max(milestones) > len(turns): raise ValueError(f"Only {len(turns)} Turns have journal entries") @@ -136,5 +161,6 @@ def header(field): parser.add_argument("database") parser.add_argument("user") parser.add_argument("milestones", nargs="+", type=int) + parser.add_argument("--detail-turn", type=int, help="attribute new bytes to first-writing journal event types in this Turn") args = parser.parse_args() - profile(args.container, args.database, args.user, set(args.milestones)) + profile(args.container, args.database, args.user, set(args.milestones), args.detail_turn) diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java index 874c572e00..51bd27637c 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java @@ -109,6 +109,30 @@ void prefixBoundsCoverSupplementarySuffixesAndCarryPastMaximalScalars() { }); } + @Test + void coldReadsVerifyMixedCompressedAndRawChunksAndRejectTruncatedData() { + var objects = new RecordObjectStore(store); + byte[] bytes = new byte[2 * 1024 * 1024]; + byte[] random = new byte[1024 * 1024]; + new java.util.Random(43).nextBytes(random); + System.arraycopy(random, 0, bytes, random.length, random.length); + var ref = objects.put(ObjectStore.digest(new byte[0]), bytes); + org.junit.jupiter.api.Assertions.assertArrayEquals( + bytes, new RecordObjectStore(store).read(ref)); + store.transaction( + "object:" + ref.key(), + tx -> { + String encoded = tx.get("chunk:0").asText(); + assertTrue(encoded.startsWith("~")); + assertFalse(tx.get("chunk:1").asText().startsWith("~")); + tx.put( + "chunk:0", + DurableJson.value(encoded.substring(0, encoded.length() - 4))); + return null; + }); + assertThrows(DurableException.class, () -> new RecordObjectStore(store).read(ref)); + } + @Test void immutableChunkHitsAvoidDatabaseTransactionsAndNeverExposeCachedBytes() throws Exception { var borrows = new java.util.concurrent.atomic.AtomicInteger(); From a22f5dac0dad2831999be800966cbf59f62fd427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 17 Nov 2026 10:32:21 +0800 Subject: [PATCH 29/38] Publish immutable objects with a write-through move on Windows --- .../pom.xml | 5 +++ .../durable/jdbc/FileObjectStore.java | 35 ++++++++++++++++--- .../durable/jdbc/BackendAssemblyTest.java | 20 +++++++++++ 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml b/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml index 5e316d9af4..f89960c481 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml @@ -21,6 +21,11 @@ agentscope-durable-runtime ${project.version} + + net.java.dev.jna + jna-platform + 5.17.0 + org.xerial sqlite-jdbc diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java index 8d85440117..03d4a3db82 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java @@ -15,6 +15,12 @@ */ package io.agentscope.extensions.durable.jdbc; +import com.sun.jna.Native; +import com.sun.jna.Platform; +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.WinBase; +import com.sun.jna.platform.win32.WinDef.DWORD; +import com.sun.jna.platform.win32.WinError; import io.agentscope.durable.DurableException; import io.agentscope.durable.store.ObjectStore; import java.io.IOException; @@ -52,13 +58,19 @@ public Reference put(String scope, byte[] bytes) { channel.force(true); } try { - Files.createLink(destination, temporary); + if (Platform.isWindows()) { + publishWindows(temporary, destination); + } else { + Files.createLink(destination, temporary); + } } catch (FileAlreadyExistsException existing) { - ObjectStore.verify(id(), ref, read(ref)); + read(ref); // Verify the winner's size and digest. } - try (var directory = - FileChannel.open(destination.getParent(), StandardOpenOption.READ)) { - directory.force(true); + if (!Platform.isWindows()) { + try (var directory = + FileChannel.open(destination.getParent(), StandardOpenOption.READ)) { + directory.force(true); + } } return ref; } catch (IOException failure) { @@ -75,6 +87,19 @@ public Reference put(String scope, byte[] bytes) { } } + // Windows cannot open the parent directory as a Java FileChannel. Publish in the + // same directory with write-through and without permission to replace an existing object. + private static void publishWindows(Path temporary, Path destination) throws IOException { + if (Kernel32.INSTANCE.MoveFileEx( + temporary.toString(), + destination.toString(), + new DWORD(WinBase.MOVEFILE_WRITE_THROUGH))) return; + int error = Native.getLastError(); + if (error == WinError.ERROR_ALREADY_EXISTS || error == WinError.ERROR_FILE_EXISTS) + throw new FileAlreadyExistsException(destination.toString()); + throw new IOException("MoveFileEx failed with Windows error " + error); + } + public byte[] read(Reference ref) { if (!id().equals(ref.store())) throw new DurableException(DurableException.Code.INVALID, "Object store differs"); diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java index 91fc7eb607..602c835d9f 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java @@ -16,6 +16,7 @@ package io.agentscope.extensions.durable.jdbc; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -32,6 +33,7 @@ import io.agentscope.durable.DurableTypes.ThreadKey; import io.agentscope.durable.SessionBackend; import io.agentscope.durable.Wakeups; +import io.agentscope.durable.store.ObjectStore; import java.nio.file.Files; import java.nio.file.Path; import java.sql.DriverManager; @@ -110,6 +112,24 @@ void cleanup() throws Exception { } } + @Test + void immutableFilePublicationReusesAndVerifiesTheExistingDestination() throws Exception { + var root = directory.resolve("objects"); + var writer = new FileObjectStore(root); + var reopened = new FileObjectStore(root); + byte[] content = {1, 2, 3}; + String scope = ObjectStore.digest(content); + var ref = writer.put(scope, content); + assertArrayEquals(content, reopened.read(ref)); + assertEquals(ref, reopened.put(scope, content)); + byte[] damaged = {3, 2, 1}; + Files.write(root.resolve(ref.key()), damaged); + assertEquals( + DurableException.Code.INVALID, + assertThrows(DurableException.class, () -> writer.put(scope, content)).code()); + assertArrayEquals(damaged, Files.readAllBytes(root.resolve(ref.key()))); + } + @Test void completeBackendReopensOriginalAdmissionAndClosesOnlyItsOwnStore() throws Exception { var notifications = new AtomicInteger(); From 72116f27374dd00887b12dd9ee135cc31300dc4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 17 Nov 2026 11:01:57 +0800 Subject: [PATCH 30/38] Freeze native replay policy at dispatch and settle uncertain calls with evidence --- .../java/io/agentscope/core/ReActAgent.java | 32 +-- .../core/journal/ThreadRecovery.java | 21 +- .../core/message/ToolResultBlock.java | 20 ++ agentscope-durable/README.md | 88 +++--- .../durable/agentscope/AgentScopeAdapter.java | 101 ++++++- .../agentscope/BackendThreadJournal.java | 32 ++- .../durable/agentscope/ModelCapture.java | 13 +- .../agentscope/NativeToolRecovery.java | 153 +++++++++++ .../agentscope/AgentScopeAdapterTest.java | 92 ++++--- .../io/agentscope/durable/DurableJson.java | 30 --- .../agentscope/durable/DurableOperations.java | 8 - .../io/agentscope/durable/DurableRuntime.java | 18 -- .../io/agentscope/durable/DurableSession.java | 5 - .../io/agentscope/durable/DurableTypes.java | 36 --- .../io/agentscope/durable/JournalContent.java | 129 --------- .../durable/NotifyingSessionBackend.java | 6 - .../io/agentscope/durable/PreviewBuffer.java | 43 --- .../io/agentscope/durable/SessionBackend.java | 4 - .../durable/SessionEventClient.java | 10 +- .../durable/SessionEventStream.java | 42 ++- .../durable/SessionEventSubscription.java | 41 ++- .../durable/TransactionalSessionBackend.java | 32 +-- .../durable/store/RecordObjectStore.java | 123 ++------- .../durable/JournalContentTest.java | 68 ----- .../durable/SessionEventClientTest.java | 21 -- .../durable/SessionStreamEventTest.java | 116 -------- .../contract/SessionBackendContract.java | 13 +- .../durable/contract/UserApiContract.java | 31 --- .../public-interaction-contract.en.md | 6 - .../protocol/public-interaction-contract.md | 6 - agentscope-durable/protocol/schema.json | 148 ---------- .../docker-regression/LongHistory.java | 154 ----------- .../docker-regression/NativeReplayProbe.java | 217 +++++++++++++++ .../scripts/docker-regression/Subscriber.java | 254 ------------------ .../docker-regression/profile_journal.py | 166 ------------ .../scripts/docker-regression/run.py | 91 ++++--- .../durable/http/HttpSessionBackend.java | 9 - .../durable/http/SessionBackendHandler.java | 12 - .../pom.xml | 5 - .../durable/jdbc/FileObjectStore.java | 35 +-- .../durable/jdbc/JdbcRecordStore.java | 71 +---- .../durable/jdbc/BackendAssemblyTest.java | 20 -- .../durable/jdbc/ScopedWorkStoreTest.java | 79 ------ docs/dev/en/docs/harness/durable.md | 12 + docs/dev/zh/docs/harness/durable.md | 12 + 45 files changed, 842 insertions(+), 1783 deletions(-) create mode 100644 agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/NativeToolRecovery.java delete mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java delete mode 100644 agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java delete mode 100644 agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java delete mode 100644 agentscope-durable/scripts/docker-regression/LongHistory.java create mode 100644 agentscope-durable/scripts/docker-regression/NativeReplayProbe.java delete mode 100644 agentscope-durable/scripts/docker-regression/Subscriber.java delete mode 100644 agentscope-durable/scripts/docker-regression/profile_journal.py 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 c9aa700d59..5aa0220ef7 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -3133,7 +3133,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)]}. @@ -3155,7 +3155,7 @@ private ContentBlock placeholderToolResultContent(ContentBlock block) { return block; } return placeholderResultBlock( - result.getId(), result.getName(), determineToolResultState(result)); + result.getId(), result.getName(), result.completedState()); } /** @@ -3768,8 +3768,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; @@ -4689,7 +4688,7 @@ public void onResult(ToolUseBlock call, ToolResultBlock result) { replyId, call.getId(), call.getName(), - determineToolResultState(result)) + result.completedState()) .withMetadata(metadata)); } @@ -4699,25 +4698,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. * @@ -4967,7 +4947,7 @@ private Mono notifyPostActingHook( // 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 = @@ -5032,7 +5012,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/ThreadRecovery.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java index f20829a68f..b12e0892bc 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 @@ -30,12 +30,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"); @@ -91,7 +106,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); 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 c541dd1054..1f161672a0 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 @@ -171,6 +171,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-durable/README.md b/agentscope-durable/README.md index d310de27c5..e8e1b65c7f 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -75,8 +75,6 @@ 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. -On a subscription reset, replace the local projection and save its cursor together. -The SDK catches up on commits made during the reset before releasing live previews. 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. @@ -184,22 +182,29 @@ 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. -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 -cannot reconstruct a deleted workspace or an expired external operation. - -If an interrupted native tool has no verified result, the Turn waits for explicit -reconciliation. Scheduled Brains leave it parked. An operator can claim it and -call `reconcileNativeTools` with a verified outcome and evidence reference. +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 operator can claim the Turn and call +`reconcileNativeTools` with verified outcomes and evidence. Cancelling the Turn closes the native call with an unverified outcome. A repeated cancel request can use a new request ID. 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. Large journal entries and checkpoints share -immutable content-defined chunks within a Session. Readers support the original -whole-object references. Upgrade every reader before writing the chunked format. +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 +cannot reconstruct a deleted workspace or an expired external operation. ### 2. Queue Turns, add instructions, and cancel work @@ -319,19 +324,8 @@ var host = DurableRuntime.builder() host.start(); ``` -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 -and access to the required tools and workspace resources. Close each host and its -Backend at application shutdown; the application owns the supplied pool. - -Schema initialization also creates the binary-collation indexes used for prefix pagination. -For an existing database, run the initializer with the provisioning identity to install -`durable_parts_prefix` and `durable_records_prefix`. Ordinary runtime startup uses -the existing schema. - -PostgreSQL record transactions use a 30-second idle-in-transaction timeout when -the database setting is disabled. An existing positive timeout takes precedence. +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. @@ -341,6 +335,12 @@ 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 +and access to the required tools and workspace resources. Close each host and its +Backend at application shutdown; the application owns the supplied pool. + Runtime scans durable ready work and renews ownership while executing it. Fencing rejects writes from an expired owner even if that process later reconnects. Optional wakeup notifications reduce latency; durable scans compensate for lost hints. @@ -465,6 +465,13 @@ make -C agentscope-durable check make -C agentscope-durable independent ``` +Normal checking covers build, formatting and tests. Isolation checking builds source +dependencies in a separate Maven cache and audits dependency trees. +Validate broker delivery, provider query/cancel +behavior and recovery under host replacement in your deployment environment. +Unqueryable or unverifiable external effects remain `UNKNOWN`; arbitrary external +operations are not promised exactly-once execution. + Run the Docker fault regression from the repository root with Docker, Python 3, Maven and a JDK on PATH: ```sh @@ -472,11 +479,9 @@ python3 agentscope-durable/scripts/docker-regression/run.py ``` The runner builds the current checkout and creates a private Docker network with PostgreSQL, -RocketMQ, independent Brain and Hands JVMs, a counting model endpoint and subscription clients. -It disconnects receivers before ACK, kills the model requester and checkpoint writer, and -reconnects a subscriber during pruning. A blocked subscriber competes with a healthy subscriber -for 4,096 previews. A separate long Thread commits 2,048 message completions, prunes the log and injects delayed previews. 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, displayed answers and subscriber cursors. The runner removes its containers, +RocketMQ, independent Brain and Hands JVMs, and a counting model endpoint. +It disconnects receivers before ACK and kills 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. Set `ROCKETMQ_IMAGE` to use a locally available RocketMQ 5 image with the broker proxy and `mqadmin` tools. @@ -497,27 +502,6 @@ to the surviving consumer after killing its peer before ACK. python3 agentscope-durable/scripts/docker-regression/compare_consumers.py ``` -For a single-Thread PostgreSQL test database, the read-only profiler attributes -`durable_parts.payload` bytes to native checkpoints, other journal entries and their -shared immutable chunks. Each shared chunk is counted once. The record-backed -object store compresses each compressible chunk after deduplication, preserving -its original content digest. The profiler reports the stored payload length. With `--detail-turn`, the per-type breakdown attributes a shared chunk to the first -event that wrote it. The milestone is the -number of distinct Turns encountered in journal order. Take the measurement after -the last measured Turn finishes. Checkpoint-history rows, events, PostgreSQL indexes -and TOAST statistics can be measured separately. - -```sh -python3 agentscope-durable/scripts/docker-regression/profile_journal.py CONTAINER DATABASE USER 100 1000 --detail-turn 100 -``` - -Normal checking covers build, formatting and tests. Isolation checking builds source -dependencies in a separate Maven cache and audits dependency trees. -Validate broker delivery, provider query/cancel -behavior and recovery under host replacement in your deployment environment. -Unqueryable or unverifiable external effects remain `UNKNOWN`; arbitrary external -operations are not promised exactly-once execution. - ## Usage and reference - [Java usage guide](../docs/dev/en/docs/harness/durable.md): reconnect, control tasks, 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 72ed15e17b..a9ee0de720 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 @@ -17,6 +17,7 @@ package io.agentscope.durable.agentscope; 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; @@ -82,25 +83,65 @@ 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(); + } + private final Function factory; private final Map executors; private final Map bindings; + private final Map replay; + private final NativeToolRecovery.ModelCheck modelCheck; private AgentScopeAdapter( Function factory, Map executors, Map bindings) { + this(factory, executors, bindings, Map.of(), null); + } + + private AgentScopeAdapter( + Function factory, + Map executors, + Map bindings, + Map replay, + NativeToolRecovery.ModelCheck modelCheck) { + this.replay = Map.copyOf(replay); + this.modelCheck = modelCheck; this.factory = factory; this.executors = Map.copyOf(executors); this.bindings = Map.copyOf(bindings); } + /** 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, policies, check); + } + /** Registers schemas from the same immutable definitions used by the remote worker. */ public static AgentScopeAdapter forReAct( Function factory, Collection tools) { @@ -147,6 +188,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); } @@ -196,6 +241,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); } @@ -285,7 +334,7 @@ public void reconcileNativeTools( throw new DurableException( DurableException.Code.INVALID, "Verified terminal outcomes required"); } - var log = new BackendThreadJournal(context, executors, bindings); + var log = new BackendThreadJournal(context, executors, bindings, replay); String turn = context.lease().turnId(); String key = "native-reconciliation:" + DurableJson.hash(List.of(turn, requestId)) + ":"; String reason = key + DurableJson.hash(outcomes) + ":" + evidenceRef; @@ -312,14 +361,27 @@ public void reconcileNativeTools( @Override public void execute(HarnessContext context) { if (pauseIfRequested(context)) return; - var log = new BackendThreadJournal(context, executors, bindings); + var log = new BackendThreadJournal(context, executors, bindings, replay); var host = new AgentScopeExecutionHost(context, log); if (host.pending()) host.restoreEntry(); else if (completeInvocation(context, log)) return; var frame = context.frame(); var nativeCalls = new HashSet<>(JournalProjection.read(log).uncertainToolCalls()); frame.tools().forEach(tool -> nativeCalls.remove(tool.request().call().callId())); + var dispatches = new ArrayList(); if (!nativeCalls.isEmpty()) { + for (var event : log.scan(log.recoveryCursor(), log.head().seq())) { + if ("tool/dispatch".equals(event.type()) + && frame.turn().turnId().equals(event.turnId()) + && nativeCalls.contains(event.data().get("toolCallId")) + && event.data().get("name") instanceof String) { + var dispatch = NativeToolRecovery.dispatch(frame.definition().key(), event); + if (dispatch.replay() == NativeToolRecovery.Replay.SAFE || modelCheck != null) + dispatches.add(dispatch); + } + } + } + if (!nativeCalls.isEmpty() && dispatches.isEmpty()) { waitFor(context, WaitCondition.NATIVE_RECONCILIATION); return; } @@ -435,6 +497,39 @@ public void execute(HarnessContext context) { 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)) return; + context.frame(); + 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"); + io.agentscope.core.journal.ThreadRecovery.reconcileOne(log, result, reason); + nativeCalls.remove(dispatch.call().getId()); + } + if (!nativeCalls.isEmpty()) waitFor(context, WaitCondition.NATIVE_RECONCILIATION); + return; + } agent.stream(List.copyOf(input), runtimeContext).blockLast(); } catch (DurableException failure) { throw failure; @@ -643,7 +738,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); + var log = new BackendThreadJournal(context, executors, bindings, replay); var projection = JournalProjection.read(log); var reconciled = frame.tools().stream().map(tool -> tool.request().call().callId()).toList(); 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 ac3f0807cd..845adf093a 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 @@ -63,6 +63,7 @@ final class BackendThreadJournal implements ThreadJournal { private final HarnessContext context; private final Map executors; private final Map bindings; + private final Map replay; private final Set sealed = new HashSet<>(); private final List signalsToApply = new ArrayList<>(); private String owner; @@ -80,6 +81,15 @@ final class BackendThreadJournal implements ThreadJournal { HarnessContext context, Map executors, Map bindings) { + this(context, executors, bindings, Map.of()); + } + + BackendThreadJournal( + HarnessContext context, + Map executors, + Map bindings, + Map replay) { + this.replay = replay; this.bindings = bindings; DurableEventSchemas.ensureRegistered(); this.context = context; @@ -132,6 +142,26 @@ synchronized void modelChunk(String id, ChatResponse 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(); @@ -142,7 +172,7 @@ private JournalEvent capture(JournalEvent event) { if (capture == null) return event; var data = new LinkedHashMap(event.data()); if (prepared) { - data.put("durableRequestHash", capture.replayHash); + 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( 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 94a802b417..a9be667833 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 @@ -38,11 +38,12 @@ final class ModelCapture { static final String OUTCOME = "durableModelOutcome"; private static final long MAX_BYTES = 16L * 1024 * 1024; - final String replayHash; - final String providerKey; + private final Map request; + private final String replayHash; private final ReasoningContext content = new ReasoningContext("durable"); private final List additional = new ArrayList<>(); private final Map metadata = new LinkedHashMap<>(); + final String providerKey; private ChatUsage usage; private String id; private String finishReason; @@ -63,12 +64,17 @@ final class ModelCapture { data.put("messages", messages); data.put("tools", tools); data.put("options", options); + this.request = freeze(data); this.replayHash = replayHash; - if (JsonUtils.getJsonCodec().toJson(data).length() > MAX_BYTES) + if (JsonUtils.getJsonCodec().toJson(request).length() > MAX_BYTES) throw new DurableException( DurableException.Code.INVALID, "Model request exceeds capture limit"); } + String replayHash() { + return replayHash; + } + synchronized void nextAttempt() { usage = null; finishReason = null; @@ -109,6 +115,7 @@ synchronized void accept(ChatResponse chunk) { synchronized Map freeze(String status) { var outcome = new LinkedHashMap(); + outcome.put("request", request); outcome.put("replayHash", replayHash); if (usage != null) outcome.put("usage", freeze(usage)); if (finishReason != null) outcome.put("finishReason", finishReason); 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 0e7244d0ca..688ff1f945 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 @@ -173,6 +173,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 -> { @@ -301,46 +353,6 @@ void parkedNativeToolCanBeCancelledOrReconciled(boolean cancel) { } } - @Test - void growingConversationSharesHistoricalJournalPayloads() throws Exception { - var database = directory.resolve("history.db"); - var adapter = adapter(new ScriptedModel(false), PermissionMode.BYPASS, Map.of()); - try (var backend = - new io.agentscope.durable.TransactionalSessionBackend( - io.agentscope.extensions.durable.jdbc.JdbcRecordStore.sqlite( - database)); - var runtime = runtime(backend, adapter, null); - var connection = java.sql.DriverManager.getConnection("jdbc:sqlite:" + database); - var measure = - connection.prepareStatement( - "SELECT SUM(length(payload)) FROM durable_parts")) { - var session = runtime.createSession(key, "agent"); - var random = new java.util.Random(57); - long firstHalf = 0; - for (int i = 1; i <= 24; i++) { - byte[] bytes = new byte[1536]; - random.nextBytes(bytes); - var turn = - session.submit( - "input-" + i, java.util.Base64.getEncoder().encodeToString(bytes)); - runtime.tick(new ThreadKey(key, "main")); - assertEquals(TurnStatus.SUCCEEDED, turn.status().status()); - if (i == 12 || i == 24) { - try (var result = measure.executeQuery()) { - assertTrue(result.next()); - long size = result.getLong(1); - System.out.println("durable_parts payload at turn " + i + " = " + size); - if (i == 12) firstHalf = size; - else - assertTrue( - size < 3 * firstHalf, - "History amplification: " + size + " / " + firstHalf); - } - } - } - } - } - @Test void adapterOwnsTheInvocationJournalConfiguration() { var adapter = diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java index 8b442cb8a9..d39c652055 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableJson.java @@ -51,36 +51,6 @@ public static JsonNode value(Object value) { return MAPPER.valueToTree(value); } - /** Check a best-effort payload limit without allocating its full serialized representation. */ - static boolean fitsEncodedLimit(Object value, int maxBytes) { - var counter = - new java.io.OutputStream() { - private int remaining = maxBytes; - - @Override - public void write(int value) throws IOException { - consume(1); - } - - @Override - public void write(byte[] bytes, int offset, int length) throws IOException { - consume(length); - } - - private void consume(int bytes) throws IOException { - if (bytes > remaining) - throw new IOException("Preview exceeds its encoded size limit"); - remaining -= bytes; - } - }; - try { - MAPPER.writeValue(counter, value); - return true; - } catch (IOException invalidOrOversized) { - return false; - } - } - public static JsonNode copy(JsonNode value) { return value == null ? NullNode.instance : value.deepCopy(); } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java index cfbefd0801..96949c521b 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java @@ -51,7 +51,6 @@ final class DurableOperations { "control", "interactions", "snapshot", - "previewEligibility", "events", "checkpoints", "restore", @@ -138,13 +137,6 @@ JsonNode invoke(DurableProtocol.Request request) { thread, DurableJson.convert(p.get("command"), ControlCommand.class)); case "interactions" -> backend.interactions(thread, p.path("turnId").asText()); - case "previewEligibility" -> - backend.previewEligibility( - key, - List.of( - DurableJson.convert( - p.required("identities"), - DurableTypes.PreviewIdentity[].class))); case "snapshot" -> filter(key, p).select(backend.snapshot(key)); case "events" -> filter(key, p) 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 babfef3f05..c47888e6f4 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 @@ -352,24 +352,6 @@ Wakeups wakeups() { return backend == null ? Wakeups.none() : backend.wakeups(); } - List pendingPreviews(DurableSession session, List batch) { - var identities = batch.stream().map(DurableTypes.PreviewIdentity::of).toList(); - List eligible = - backend != null - ? backend.previewEligibility(session.key(), identities) - : List.of( - DurableJson.convert( - session.call( - "previewEligibility", "identities", identities), - Boolean[].class)); - if (eligible.size() != batch.size()) - throw new DurableException( - DurableException.Code.INCOMPATIBLE, "Preview response length differs"); - var pending = new java.util.ArrayList(); - for (int i = 0; i < eligible.size(); i++) if (eligible.get(i)) pending.add(batch.get(i)); - return pending; - } - LiveEvents liveEvents() { return liveEvents; } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java index 4cfa78ab08..37d6e4ca39 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java @@ -29,7 +29,6 @@ import io.agentscope.durable.DurableTypes.TurnPage; import io.agentscope.durable.DurableTypes.TurnView; import java.time.Duration; -import java.util.List; import java.util.Objects; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; @@ -52,10 +51,6 @@ Wakeups wakeups() { return runtime.wakeups(); } - List pendingPreviews(List batch) { - return runtime.pendingPreviews(this, batch); - } - LiveEvents liveEvents() { return runtime.liveEvents(); } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java index aa392cf24f..52bf3d3ad6 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableTypes.java @@ -628,38 +628,6 @@ public record PublicEvent( String type, JsonNode data) {} - /** Durable projection keys for one best-effort preview. */ - public record PreviewIdentity(String messageId, String toolKey, long attempt, long revision) { - static PreviewIdentity of(LiveEvent event) { - var call = event.data().path("toolCallId").asText(null); - return new PreviewIdentity( - event.data().path("messageId").asText(null), - call == null - ? null - : EventProjection.toolId(event.threadId(), event.turnId(), call), - event.data().path("attempt").asLong(), - event.data().path("revision").asLong()); - } - - boolean pending( - java.util.function.Function messages, - java.util.function.Function tools) { - var message = messageId == null ? null : messages.apply(messageId); - if (message != null && (message.path("complete").asBoolean() || olderThan(message))) - return false; - var tool = toolKey == null ? null : tools.apply(toolKey); - return tool == null - || ("GENERATING_ARGUMENTS".equals(tool.path("data").path("status").asText()) - && !olderThan(tool.path("data"))); - } - - private boolean olderThan(JsonNode projection) { - var currentAttempt = projection.path("attempt").asLong(); - return attempt < currentAttempt - || attempt == currentAttempt && revision < projection.path("revision").asLong(); - } - } - /** * Best-effort live presentation signal. Live events have no durable sequence or cursor and are * never returned by event history or included in snapshots. @@ -731,10 +699,6 @@ public boolean matches(PublicEvent event) { return matches(event.threadId(), event.turnId(), event.runId()); } - boolean matches(SessionKey session, LiveEvent event) { - return session.equals(event.session()) && matches(event); - } - public boolean matches(LiveEvent event) { return matches(event.threadId(), event.turnId(), event.runId()); } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java deleted file mode 100644 index 338c823e1d..0000000000 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/JournalContent.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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; - -import io.agentscope.durable.store.ObjectStore; -import io.agentscope.durable.store.ObjectStore.Reference; -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HexFormat; - -/** Content-defined chunks let successive full-history journal entries share their stable bytes. */ -final class JournalContent { - private static final int MIN = 1024; - private static final int MAX = 8192; - private static final int DESCRIPTOR = 36; - // The manifest changes on every append. Small, descriptor-aligned pages allow the - // stable interior of the index to be reused before it reaches data-chunk size. - private static final int MAX_INDEX = 32 * DESCRIPTOR; - private static final HexFormat HEX = HexFormat.of(); - - record Root(Reference reference, int levels, int size, String digest) {} - - static Root put(ObjectStore store, String scope, byte[] bytes) { - if (bytes.length > ObjectStore.MAX_BYTES) - throw new IllegalArgumentException("Journal content too large"); - byte[] layer = bytes; - int levels = 0; - if (layer.length > MAX) { - var index = new ByteArrayOutputStream(); - int hash = 0; - int start = 0; - for (int i = 0; i < layer.length; i++) { - hash = (hash << 1) + GEAR[layer[i] & 255]; - int length = i - start + 1; - if (length >= MAX - || (length >= MIN && (hash & 2047) == 0) - || i == layer.length - 1) { - appendChunk(store, scope, layer, start, i + 1, index); - start = i + 1; - hash = 0; - } - } - layer = index.toByteArray(); - levels++; - } - while (levels > 0 && layer.length > MAX_INDEX) { - var index = new ByteArrayOutputStream(); - int start = 0; - for (int end = DESCRIPTOR; end <= layer.length; end += DESCRIPTOR) { - int length = end - start; - // The last digest byte is stable even when preceding descriptors change. - if (length == MAX_INDEX - || (length >= 4 * DESCRIPTOR && (layer[end - 1] & 7) == 0) - || end == layer.length) { - appendChunk(store, scope, layer, start, end, index); - start = end; - } - } - layer = index.toByteArray(); - levels++; - } - return new Root(store.put(scope, layer), levels, bytes.length, ObjectStore.digest(bytes)); - } - - private static void appendChunk( - ObjectStore store, - String scope, - byte[] layer, - int start, - int end, - ByteArrayOutputStream index) { - var chunk = store.put(scope, Arrays.copyOfRange(layer, start, end)); - index.writeBytes( - ByteBuffer.allocate(DESCRIPTOR) - .putInt(end - start) - .put(HEX.parseHex(chunk.digest())) - .array()); - } - - private static final int[] GEAR = gearTable(); - - private static int[] gearTable() { - var random = new java.util.Random(0x4167656e74L); - var table = new int[256]; - for (int i = 0; i < table.length; i++) table[i] = random.nextInt(); - return table; - } - - static byte[] read(ObjectStore store, String scope, Root root) { - if (!root.reference().scope().equals(scope) || root.levels() < 0 || root.levels() > 8) - throw new DurableException(DurableException.Code.INVALID, "Invalid journal index"); - var expected = new Reference(store.id(), scope, root.digest(), root.size()); - byte[] layer = store.read(root.reference()); - for (int level = root.levels(); level > 0; level--) { - if (layer.length % DESCRIPTOR != 0) - throw new DurableException( - DurableException.Code.INVALID, "Incomplete journal index"); - var index = ByteBuffer.wrap(layer); - var restored = new ByteArrayOutputStream(); - while (index.hasRemaining()) { - int length = index.getInt(); - if (length <= 0 || length > MAX || length > root.size() - restored.size()) - throw new DurableException( - DurableException.Code.INVALID, "Invalid journal chunk size"); - byte[] digest = new byte[32]; - index.get(digest); - restored.writeBytes( - store.read( - new Reference(store.id(), scope, HEX.formatHex(digest), length))); - } - layer = restored.toByteArray(); - } - return ObjectStore.verify(store.id(), expected, layer); - } -} 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 44dd5b3abe..1a7de9e52d 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 @@ -36,7 +36,6 @@ import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; -import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -401,11 +400,6 @@ public void cancel(ThreadKey session, String turnId, String requestId) { changed(session); } - @Override - public List previewEligibility(SessionKey key, List identities) { - return delegate.previewEligibility(key, identities); - } - @Override public Snapshot snapshot(SessionKey session) { return delegate.snapshot(session); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java deleted file mode 100644 index f6c4ee7778..0000000000 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/PreviewBuffer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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; - -import io.agentscope.durable.DurableTypes.LiveEvent; -import java.util.ArrayList; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.function.Consumer; - -/** Best-effort previews never block publishers or advance the durable cursor. */ -final class PreviewBuffer { - static final int CAPACITY = 128; - static final int MAX_ENCODED_BYTES = 64 * 1024; - static final int BATCH = 32; - private final ArrayBlockingQueue queue = new ArrayBlockingQueue<>(CAPACITY); - - boolean offer(LiveEvent event) { - return queue.remainingCapacity() > 0 - && DurableJson.fitsEncodedLimit(event, MAX_ENCODED_BYTES) - && queue.offer(event); - } - - int drain(DurableSession session, Consumer sink) { - var batch = new ArrayList(BATCH); - queue.drainTo(batch, BATCH); - if (!batch.isEmpty()) session.pendingPreviews(batch).forEach(sink); - return batch.size(); - } -} 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 744c067c05..b543fd8e4d 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 @@ -31,7 +31,6 @@ import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; -import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -229,9 +228,6 @@ default Optional claim( Snapshot snapshot(SessionKey session); - /** Suppress previews superseded by committed facts, including facts before a saved cursor. */ - List previewEligibility(SessionKey session, List identities); - EventPage events(SessionKey session, String cursor, int limit); List checkpoints(ThreadKey session, long after, int limit); diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java index ba40f7741b..5c863a1c60 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventClient.java @@ -167,8 +167,7 @@ public synchronized int poll() { if (Objects.equals(cursor, replayHighWatermark)) replayCaughtUp = true; } cursor = page.cursor(); - if (Objects.equals(cursor, replayHighWatermark) - || Objects.equals(cursor, page.highWatermark())) replayCaughtUp = true; + if (Objects.equals(cursor, replayHighWatermark)) replayCaughtUp = true; return page.events().size(); } @@ -178,10 +177,9 @@ synchronized void resynchronize() { if (closed.get()) return; snapshots.accept(snapshot); cursor = snapshot.cursor(); - // Events may commit while the consumer is replacing its projection. - // Re-establish the replay boundary before releasing queued previews. - replayBoundaryCaptured = false; - replayCaughtUp = false; + replayHighWatermark = snapshot.cursor(); + replayBoundaryCaptured = true; + replayCaughtUp = true; } boolean replayCaughtUp() { diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java index 3305f55aa9..041cb9b7d4 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventStream.java @@ -22,6 +22,9 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; @@ -55,7 +58,9 @@ default void reset(Snapshot snapshot) { private final DurableSession session; private final EventFilter filter; private final EventPage firstPage; - private final PreviewBuffer live = new PreviewBuffer(); + private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); + private final Set completedMessages = ConcurrentHashMap.newKeySet(); + private final Set completedToolCalls = ConcurrentHashMap.newKeySet(); private final AutoCloseable liveSubscription; private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); @@ -77,8 +82,8 @@ default void reset(Snapshot snapshot) { .subscribe( event -> { if (!closed.get() - && filter.matches(session.key(), event) - && options.accepts(event)) live.offer(event); + && filter.matches(event) + && options.accepts(event)) live.add(event); }); } catch (RuntimeException error) { logLiveFailure(error); @@ -157,10 +162,10 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { try { for (var event : firstPage.events()) { if (closed.get()) return; - sink.accept(event); + durable(sink, event); } boolean replayCaughtUp = Objects.equals(firstPage.cursor(), firstPage.highWatermark()); - if (replayCaughtUp) live.drain(session, sink::live); + if (replayCaughtUp) drainLive(sink); if (filter.threadId() != null) sink.cursor(firstPage.cursor()); if (closed.get() || expired(until)) return; var reset = new AtomicBoolean(); @@ -173,14 +178,14 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { reset.set(true); sink.reset(snapshot); }, - sink); + event -> durable(sink, event)); reader = current; if (closed.get()) return; while (!closed.get()) { int delivered = current.poll(); + replayCaughtUp = replayCaughtUp || current.replayCaughtUp(); + if (replayCaughtUp) delivered += drainLive(sink); if (reset.get()) return; - replayCaughtUp = current.replayCaughtUp(); - if (replayCaughtUp) delivered += live.drain(session, sink::live); if (filter.threadId() != null) sink.cursor(current.cursor()); if (expired(until)) return; if (delivered == 0) { @@ -200,6 +205,27 @@ public void transferTo(Sink sink, Duration duration, Duration pollInterval) { } } + private void durable(Sink sink, PublicEvent event) { + if ("message.completed".equals(event.type())) + completedMessages.add(event.data().path("messageId").asText()); + if ("tool.call.updated".equals(event.type())) + completedToolCalls.add(event.data().path("callId").asText()); + sink.accept(event); + } + + private int drainLive(Sink sink) { + int delivered = 0; + for (LiveEvent event; (event = live.poll()) != null; ) { + String messageId = event.data().path("messageId").asText(null); + if (messageId != null && completedMessages.contains(messageId)) continue; + String toolCallId = event.data().path("toolCallId").asText(null); + if (toolCallId != null && completedToolCalls.contains(toolCallId)) continue; + sink.live(event); + delivered++; + } + return delivered; + } + private static boolean expired(long until) { return until != 0 && until - System.nanoTime() <= 0; } diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java index d974933017..4213720c94 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionEventSubscription.java @@ -22,6 +22,9 @@ import io.agentscope.durable.DurableTypes.Snapshot; import java.time.Duration; import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -56,7 +59,9 @@ public final class SessionEventSubscription implements AutoCloseable { private long generation; private long retryAfter; private ScheduledFuture scheduled; - private final PreviewBuffer live = new PreviewBuffer(); + private final ConcurrentLinkedQueue live = new ConcurrentLinkedQueue<>(); + private final Set completedMessages = ConcurrentHashMap.newKeySet(); + private final Set completedToolCalls = ConcurrentHashMap.newKeySet(); private AutoCloseable liveSubscription; SessionEventSubscription( @@ -93,8 +98,8 @@ void start() { session.liveEvents() .subscribe( event -> { - if (filter.matches(session.key(), event) - && live.offer(event)) { + if (filter.matches(event)) { + live.add(event); changed(); } }); @@ -144,7 +149,12 @@ private void deliver(long token) { if (reader == null) { reader = new SessionEventClient( - session, filter, initialCursor, snapshots, events, this::changed); + session, + filter, + initialCursor, + snapshots, + this::durable, + this::changed); if (closed) { reader.close(); return; @@ -156,7 +166,7 @@ private void deliver(long token) { } if (closed) return; if (reader.poll() > 0) delay = 0; - if (reader.replayCaughtUp() && live.drain(session, liveEvents) > 0) delay = 0; + if (reader.replayCaughtUp() && drainLive() > 0) delay = 0; lastFailure = null; } catch (RuntimeException error) { failed = true; @@ -178,6 +188,27 @@ private void deliver(long token) { } } + private int drainLive() { + int delivered = 0; + for (LiveEvent event; (event = live.poll()) != null; ) { + String messageId = event.data().path("messageId").asText(null); + if (messageId != null && completedMessages.contains(messageId)) continue; + String toolCallId = event.data().path("toolCallId").asText(null); + if (toolCallId != null && completedToolCalls.contains(toolCallId)) continue; + liveEvents.accept(event); + delivered++; + } + return delivered; + } + + private void durable(PublicEvent event) { + if ("message.completed".equals(event.type())) + completedMessages.add(event.data().path("messageId").asText()); + if ("tool.call.updated".equals(event.type())) + completedToolCalls.add(event.data().path("callId").asText()); + events.accept(event); + } + /** Last successfully acknowledged cursor; persist event/snapshot cursors inside callbacks. */ public String cursor() { var current = reader; 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 3df6c833b3..041f0abee6 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 @@ -43,7 +43,6 @@ import io.agentscope.durable.DurableTypes.Lifecycle; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; -import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.PublicEvent; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; @@ -136,21 +135,14 @@ public Optional localStorage() { private JsonNode storeContent(SessionKey session, JsonNode value) { byte[] bytes = DurableJson.value(value).toString().getBytes(StandardCharsets.UTF_8); - if (bytes.length > 8192) - return DurableJson.value( - Map.of("chunked", JournalContent.put(objects, objectScope(session), bytes))); - return DurableJson.value(new StoredContent(DurableJson.copy(value), null)); + return bytes.length > 16384 + ? DurableJson.value( + new StoredContent(null, objects.put(objectScope(session), bytes))) + : DurableJson.value(new StoredContent(DurableJson.copy(value), null)); } private JsonNode readContent(SessionKey session, JsonNode stored) { if (stored == null || stored.isNull()) return DurableJson.value(null); - if (stored.hasNonNull("chunked")) { - var root = DurableJson.convert(stored.get("chunked"), JournalContent.Root.class); - return DurableJson.parse( - new String( - JournalContent.read(objects, objectScope(session), root), - StandardCharsets.UTF_8)); - } var value = DurableJson.convert(stored, StoredContent.class); return value.reference() == null ? DurableJson.copy(value.inline()) @@ -2329,22 +2321,6 @@ private static void cancel(State s, String turnId, String requestId) { } } - @Override - public List previewEligibility(SessionKey key, List identities) { - if (identities.size() > PreviewBuffer.BATCH) - throw error(DurableException.Code.INVALID, "Too many preview identities"); - return store.transaction( - key.storageKey(), - tx -> { - var state = load(tx); - if (!key.equals(state.session.key())) - throw error(DurableException.Code.CONFLICT, "Session key mismatch"); - return identities.stream() - .map(id -> id.pending(state.messages::get, state.projectedTools::get)) - .toList(); - }); - } - @Override public Snapshot snapshot(SessionKey key) { return change( diff --git a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java index 3d6cb8bc15..8b48f9e1d5 100644 --- a/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java +++ b/agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/store/RecordObjectStore.java @@ -20,28 +20,11 @@ import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Base64; -import java.util.LinkedHashMap; import java.util.Objects; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; /** Database fallback for small installations; production hosts may supply object storage. */ public final class RecordObjectStore implements ObjectStore { private final RecordStore records; - // Large journal entries revisit the same immutable chunks on both append and recovery. - // Retain at most 16 MiB of verified content per store, allowing cold readers to use the DB. - private final LinkedHashMap chunks = new LinkedHashMap<>(64, 0.75f, true); - - private synchronized byte[] cached(Reference ref) { - return chunks.get(ref); - } - - private synchronized void remember(Reference ref, byte[] bytes) { - if (bytes.length > 8192) return; - chunks.put(ref, bytes.clone()); - if (chunks.size() > 2048) chunks.remove(chunks.keySet().iterator().next()); - } public RecordObjectStore(RecordStore records) { this.records = Objects.requireNonNull(records); @@ -55,7 +38,6 @@ public String id() { public Reference put(String scope, byte[] bytes) { var reference = ObjectStore.reference(id(), scope, bytes); - if (cached(reference) != null) return reference; records.transaction( "object:" + reference.key(), tx -> { @@ -72,93 +54,42 @@ public Reference put(String scope, byte[] bytes) { bytes, offset, Math.min(bytes.length, offset + CHUNK_BYTES)); - tx.put("chunk:" + offset / CHUNK_BYTES, DurableJson.value(encode(chunk))); + tx.put( + "chunk:" + offset / CHUNK_BYTES, + DurableJson.value(Base64.getEncoder().encodeToString(chunk))); } tx.put("", DurableJson.value(reference)); return null; }); - remember(reference, bytes); return reference; } - // Keep incompressible objects raw. The marker is outside the Base64 alphabet. - private static String encode(byte[] chunk) { - if (chunk.length >= 256) { - var encoder = new Deflater(Deflater.BEST_SPEED); - try { - encoder.setInput(chunk); - encoder.finish(); - byte[] compressed = new byte[chunk.length - 16]; - int length = encoder.deflate(compressed); - if (encoder.finished()) - return "~" - + Base64.getEncoder().encodeToString(Arrays.copyOf(compressed, length)); - } finally { - encoder.end(); - } - } - return Base64.getEncoder().encodeToString(chunk); - } - - private static byte[] decode(String stored, int size) { - if (!stored.startsWith("~")) return Base64.getDecoder().decode(stored); - var decoder = new Inflater(); - try { - decoder.setInput(Base64.getDecoder().decode(stored.substring(1))); - byte[] bytes = new byte[size]; - if (decoder.inflate(bytes) == size && decoder.finished() && decoder.getRemaining() == 0) - return bytes; - throw new DurableException( - DurableException.Code.INVALID, "Invalid compressed object size"); - } catch (DataFormatException invalid) { - throw new DurableException( - DurableException.Code.INVALID, "Invalid compressed object", invalid); - } finally { - decoder.end(); - } - } - public byte[] read(Reference reference) { if (!id().equals(reference.store())) throw new DurableException(DurableException.Code.INVALID, "Object store differs"); - byte[] hit = cached(reference); - if (hit != null) return hit.clone(); - byte[] loaded = - records.transaction( - "object:" + reference.key(), - tx -> { - var existing = tx.get(""); - if (existing == null) - throw new DurableException( - DurableException.Code.NOT_FOUND, "Object not found"); - if (!reference.equals(DurableJson.convert(existing, Reference.class))) - throw new DurableException( - DurableException.Code.INVALID, "Object header differs"); - var bytes = new ByteArrayOutputStream(); - for (long offset = 0; - offset < reference.size(); - offset += CHUNK_BYTES) { - var chunk = tx.get("chunk:" + offset / CHUNK_BYTES); - if (chunk == null) - throw new DurableException( - DurableException.Code.INVALID, "Object chunk missing"); - byte[] decoded = - decode( - chunk.asText(), - (int) - Math.min( - CHUNK_BYTES, - reference.size() - offset)); - if (decoded.length - != Math.min(CHUNK_BYTES, reference.size() - offset)) - throw new DurableException( - DurableException.Code.INVALID, - "Object chunk size differs"); - bytes.writeBytes(decoded); - } - return ObjectStore.verify(id(), reference, bytes.toByteArray()); - }); - remember(reference, loaded); - return loaded; + return records.transaction( + "object:" + reference.key(), + tx -> { + var existing = tx.get(""); + if (existing == null) + throw new DurableException( + DurableException.Code.NOT_FOUND, "Object not found"); + if (!reference.equals(DurableJson.convert(existing, Reference.class))) + throw new DurableException( + DurableException.Code.INVALID, "Object header differs"); + var bytes = new ByteArrayOutputStream(); + for (long offset = 0; offset < reference.size(); offset += CHUNK_BYTES) { + var chunk = tx.get("chunk:" + offset / CHUNK_BYTES); + if (chunk == null) + throw new DurableException( + DurableException.Code.INVALID, "Object chunk missing"); + byte[] decoded = Base64.getDecoder().decode(chunk.asText()); + if (decoded.length != Math.min(CHUNK_BYTES, reference.size() - offset)) + throw new DurableException( + DurableException.Code.INVALID, "Object chunk size differs"); + bytes.writeBytes(decoded); + } + return ObjectStore.verify(id(), reference, bytes.toByteArray()); + }); } } diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java deleted file mode 100644 index ea15484471..0000000000 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/JournalContentTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import io.agentscope.durable.store.ObjectStore; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import org.junit.jupiter.api.Test; - -class JournalContentTest { - @Test - void growingHistorySharesBytesAndRecoversEveryVersion() { - Map chunks = new HashMap<>(); - ObjectStore objects = - new ObjectStore() { - public String id() { - return "test"; - } - - public Reference put(String scope, byte[] bytes) { - var ref = ObjectStore.reference(id(), scope, bytes); - chunks.putIfAbsent(ref.key(), bytes); - return ref; - } - - public byte[] read(Reference ref) { - return chunks.get(ref.key()); - } - }; - byte[] history = new byte[512 * 2048]; - new Random(42).nextBytes(history); - String scope = ObjectStore.digest(new byte[0]); - var roots = new java.util.ArrayList(); - for (int turn = 1; turn <= 512; turn++) { - roots.add(JournalContent.put(objects, scope, Arrays.copyOf(history, turn * 2048))); - } - assertTrue(roots.get(511).levels() >= 2); - assertTrue( - roots.stream() - .filter(root -> root.levels() > 0) - .allMatch(root -> root.reference().size() <= 32 * 36), - "Growing histories must share the index instead of copying all leaf descriptors"); - long stored = chunks.values().stream().mapToLong(chunk -> chunk.length).sum(); - assertTrue(stored < history.length * 10L, "Unique chunk and index bytes: " + stored); - for (int i = 0; i < roots.size(); i++) - assertArrayEquals( - Arrays.copyOf(history, (i + 1) * 2048), - JournalContent.read(objects, scope, roots.get(i))); - } -} diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java index a4dd46b027..7e709ec91e 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionEventClientTest.java @@ -128,27 +128,6 @@ void replayBoundaryIsReachedEvenWhenTheNextPageAlsoContainsNewerEvents() { } } - @Test - void resetWaitsForFreshReplayBeforeDeliveringPreviews() { - var backend = mock(SessionBackend.class); - when(backend.wakeups()).thenReturn(Wakeups.none()); - var snapshot = mock(DurableTypes.Snapshot.class); - when(snapshot.cursor()).thenReturn("1"); - when(backend.snapshot(session)).thenReturn(snapshot); - when(backend.events(eq(session), any(), eq(100))) - .thenReturn( - new EventPage(List.of(event("2")), "2", "3"), - new EventPage(List.of(event("4")), "4", "4")); - try (var reader = new SessionEventClient(backend, session, null, s -> {}, e -> {})) { - reader.resynchronize(); - assertFalse(reader.replayCaughtUp()); - reader.poll(); - assertFalse(reader.replayCaughtUp()); - reader.poll(); - assertTrue(reader.replayCaughtUp()); - } - } - private PublicEvent event(String cursor) { return new PublicEvent( "1", diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java index f6b58ce518..9399e0bd44 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/SessionStreamEventTest.java @@ -92,122 +92,6 @@ void defaultDurableStreamDoesNotDependOnTheLiveTransport() { } } - @Test - void resetSupersedesOnlyCompletedMessagesAndMatchingToolCalls() { - - var snapshot = mock(DurableTypes.Snapshot.class); - when(snapshot.projection()) - .thenReturn( - DurableJson.value( - Map.of( - "messages", - Map.of( - "done", - Map.of( - "complete", - true, - "messageId", - "done"), - "partial", - Map.of( - "complete", - false, - "messageId", - "partial")), - "tools", - Map.of( - EventProjection.toolId( - "main", "turn-1", "call"), - Map.of( - "data", - Map.of("status", "RUNNING")))))); - java.util.function.Predicate superseded = - e -> - !DurableTypes.PreviewIdentity.of(e) - .pending( - snapshot.projection().path("messages")::get, - snapshot.projection().path("tools")::get); - assertTrue(superseded.test(live("message.delta", Map.of("messageId", "done")))); - assertFalse(superseded.test(live("message.delta", Map.of("messageId", "partial")))); - var preview = live("tool.arguments.delta", Map.of("toolCallId", "call")); - assertTrue(superseded.test(preview)); - assertFalse( - superseded.test( - new LiveEvent( - "1", - "next", - session, - "main", - "turn-2", - null, - null, - 2, - preview.type(), - preview.data()))); - } - - @Test - void earlierAttemptAndRevisionCannotOverwriteAnActivePreview() { - var partial = DurableJson.value(Map.of("complete", false, "attempt", 2, "revision", 4)); - var tool = - DurableJson.value( - Map.of( - "data", - Map.of( - "status", - "GENERATING_ARGUMENTS", - "attempt", - 2, - "revision", - 4))); - for (var ref : List.of(Map.of("messageId", "msg"), Map.of("toolCallId", "call"))) { - var fields = new java.util.HashMap(ref); - fields.put("attempt", 1); - fields.put("revision", 20); - assertFalse( - DurableTypes.PreviewIdentity.of(live("message.delta", fields)) - .pending(k -> partial, k -> tool)); - fields.put("attempt", 2); - fields.put("revision", 3); - assertFalse( - DurableTypes.PreviewIdentity.of(live("message.delta", fields)) - .pending(k -> partial, k -> tool)); - fields.put("revision", 4); - assertTrue( - DurableTypes.PreviewIdentity.of(live("message.delta", fields)) - .pending(k -> partial, k -> tool)); - } - } - - @Test - void previewOverflowDropsOnlyBestEffortDataAndOneDrainYieldsAfterOneBatch() { - var buffer = new PreviewBuffer(); - var event = live("tool.arguments.delta", Map.of("toolCallId", "call", "text", "delta")); - assertFalse( - buffer.offer( - live( - "tool.arguments.delta", - Map.of("toolCallId", "large", "text", "界".repeat(24_000))))); - for (int i = 0; i < PreviewBuffer.CAPACITY; i++) assertTrue(buffer.offer(event)); - assertFalse(buffer.offer(event)); - var session = mock(DurableSession.class); - when(session.pendingPreviews(any())).thenAnswer(invocation -> invocation.getArgument(0)); - var delivered = new java.util.concurrent.atomic.AtomicInteger(); - assertEquals( - PreviewBuffer.BATCH, buffer.drain(session, ignored -> delivered.incrementAndGet())); - assertEquals(PreviewBuffer.BATCH, delivered.get()); - for (int i = 0; i < PreviewBuffer.BATCH; i++) assertTrue(buffer.offer(event)); - assertFalse(buffer.offer(event)); - } - - @Test - void matchingTurnCannotAdmitAnotherSessionsLivePreview() { - var filter = new EventFilter("main", "turn-1", null); - var preview = live("tool.arguments.delta", Map.of("toolCallId", "same", "text", "private")); - assertTrue(filter.matches(session, preview)); - assertFalse(filter.matches(new SessionKey("another-tenant", session.sessionId()), preview)); - } - private LiveEvent live(String type, Map data) { return new LiveEvent( "1", 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 63aba56423..4e6ec90eac 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 @@ -1852,7 +1852,7 @@ protected void largeCheckpointAndJournalUseScopedImmutableContent() { tx -> { assertTrue( tx.get("thread-data:" + DurableJson.hash("main") + ":checkpoint") - .hasNonNull("chunked")); + .hasNonNull("reference")); assertTrue( tx.get("thread-data:" + DurableJson.hash("main") + ":checkpoint") .toString() @@ -1863,7 +1863,7 @@ protected void largeCheckpointAndJournalUseScopedImmutableContent() { "thread-data:" + DurableJson.hash("main") + ":journal:initial:00000000000000000001") - .hasNonNull("chunked")); + .hasNonNull("reference")); return null; }); byte[] bytes = "private artifact".getBytes(StandardCharsets.UTF_8); @@ -3282,15 +3282,6 @@ protected void cursorsAreSessionBoundAndSnapshotSurvivesRetention() { backend.pruneEvents(key, snapshot.cursor()); code(DurableException.Code.CURSOR_EXPIRED, () -> backend.events(key, old, 10)); assertTrue(backend.events(key, snapshot.cursor(), 10).events().isEmpty()); - assertEquals( - List.of(false, true), - backend.previewEligibility( - key, - List.of( - new io.agentscope.durable.DurableTypes.PreviewIdentity( - "m", null, 0, 0), - new io.agentscope.durable.DurableTypes.PreviewIdentity( - "uncommitted", null, 0, 0)))); SessionKey other = new SessionKey("other", "session"); backend.create( new SessionSpec( diff --git a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java index 09ecff5d4c..5204282397 100644 --- a/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java +++ b/agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/contract/UserApiContract.java @@ -492,37 +492,6 @@ private void checkpoint( null)); } - @Test - void previewLookupReturnsOnlyOrderedFlagsForTheRequestedIdentities() { - session.submit("preview-input", "hello"); - var saved = session.snapshot().projection().required("messages").fieldNames().next(); - var requested = - List.of( - new io.agentscope.durable.DurableTypes.PreviewIdentity(saved, null, 0, 0), - new io.agentscope.durable.DurableTypes.PreviewIdentity( - null, "unknown", 0, 0)); - var lookup = - new DurableProtocol.Request( - DurableProtocol.VERSION, - "previewEligibility", - DurableJson.value(Map.of("session", key, "identities", requested))); - assertEquals(DurableJson.value(List.of(false, true)), api.invoke(lookup)); - code( - DurableException.Code.INVALID, - () -> - api.invoke( - new DurableProtocol.Request( - DurableProtocol.VERSION, - "previewEligibility", - DurableJson.value( - Map.of( - "session", - key, - "identities", - java.util.Collections.nCopies( - 33, requested.get(0))))))); - } - @Test void languageNeutralWorkflowMatchesLocalAndHttpBindings() throws Exception { try (var input = diff --git a/agentscope-durable/protocol/public-interaction-contract.en.md b/agentscope-durable/protocol/public-interaction-contract.en.md index b917abee3b..cbd8b4eb91 100644 --- a/agentscope-durable/protocol/public-interaction-contract.en.md +++ b/agentscope-durable/protocol/public-interaction-contract.en.md @@ -267,12 +267,6 @@ they do not reconstruct state from private native logs. A control receipt confir admission, while application events or the resulting Turn state confirm processing. User input does not acquire system privileges, and public events exclude private reasoning. -A client that displays an answer and crashes before saving its cursor can receive the same completion again. Upsert the answer by `messageId` within its Session for both snapshots and replay. Consumers that need an event-by-event audit must retain the events before pruning. - -Each subscription buffers up to 128 live previews and processes up to 32 per poll. A full queue drops incoming previews. A preview larger than 64 KiB of encoded JSON is also dropped. Committed events continue through backend paging. Delivery checks each preview against the current message or tool projection, including completions before the subscription cursor. Callbacks share `observerParallelism` execution slots (default 2). Each blocked callback occupies one slot. - -The Session-scoped `previewEligibility` operation checks up to 32 identities and returns booleans in input order. Clients send only `messageId`, the projection’s `toolKey`, `attempt` and `revision`. - ## 6. Capabilities, errors and recovery Public capabilities reports operations, registered definition names and checkpoint bindings; diff --git a/agentscope-durable/protocol/public-interaction-contract.md b/agentscope-durable/protocol/public-interaction-contract.md index e48c7596d6..825c3b57a5 100644 --- a/agentscope-durable/protocol/public-interaction-contract.md +++ b/agentscope-durable/protocol/public-interaction-contract.md @@ -231,12 +231,6 @@ fork 在目标 Session 时间线记录目标 Thread 的恢复;继承的原生 恢复读取,必要时获取一致性快照,不需要从私有原生日志重建状态。控制回执确认已受理, 应用事件或最终 Turn 状态确认后续处理。用户输入不会获得系统权限,公共事件不包含私有推理。 -回答已显示而游标尚未持久化时,重连可能再次收到同一条完成事件。客户端应在当前 Session 内按 `messageId` 更新回答,快照与增量沿用同一身份。需要逐事件审计的消费者应在历史裁剪前自行保存事件。 - -每个订阅最多缓存 128 条实时预览,每轮最多处理 32 条。队列满或单条预览的 UTF-8 JSON 编码超过 64 KiB 时丢弃该预览;已提交事件继续通过后端分页交付。投递预览前按消息或工具身份核对当前持久化投影,包括在订阅游标之前已经完成的对象。回调共享 `observerParallelism` 个执行槽(默认 2),每个阻塞回调占用一个槽。 - -`previewEligibility` 在 Session 范围按输入顺序返回最多 32 个布尔值。客户端只发送 `messageId`、投影中的 `toolKey`、`attempt` 和 `revision`,无需下载历史快照。 - ## 6. 能力、错误与恢复 公共 capabilities 报告操作集合、已注册定义名称与 checkpoint 绑定,不枚举动态定义解析器内的所有配置。 diff --git a/agentscope-durable/protocol/schema.json b/agentscope-durable/protocol/schema.json index 4eb1e3267f..48f2d7d3eb 100644 --- a/agentscope-durable/protocol/schema.json +++ b/agentscope-durable/protocol/schema.json @@ -4525,9 +4525,6 @@ }, { "$ref": "#/$defs/backend_cancelDelegationRequest" - }, - { - "$ref": "#/$defs/backend_previewEligibilityRequest" } ] }, @@ -8118,9 +8115,6 @@ }, { "$ref": "#/$defs/user_listModelCallsRequest" - }, - { - "$ref": "#/$defs/user_previewEligibilityRequest" } ] }, @@ -11820,148 +11814,6 @@ "$ref": "#/$defs/delegationView" } } - }, - "user_previewEligibilityRequest": { - "type": "object", - "additionalProperties": false, - "required": [ - "version", - "operation", - "payload" - ], - "properties": { - "version": { - "const": "durable.v1" - }, - "operation": { - "const": "previewEligibility" - }, - "payload": { - "type": "object", - "additionalProperties": false, - "required": [ - "session", - "identities" - ], - "properties": { - "session": { - "$ref": "#/$defs/session" - }, - "identities": { - "$ref": "#/$defs/previewIdentities" - } - } - } - } - }, - "user_previewEligibilityResponse": { - "type": "object", - "additionalProperties": false, - "required": [ - "version", - "result" - ], - "properties": { - "version": { - "const": "durable.v1" - }, - "result": { - "type": "array", - "maxItems": 32, - "items": { - "type": "boolean" - } - } - } - }, - "backend_previewEligibilityRequest": { - "type": "object", - "additionalProperties": false, - "required": [ - "version", - "operation", - "payload" - ], - "properties": { - "version": { - "const": "durable.v1" - }, - "operation": { - "const": "previewEligibility" - }, - "payload": { - "type": "object", - "additionalProperties": false, - "required": [ - "session", - "identities" - ], - "properties": { - "session": { - "$ref": "#/$defs/session" - }, - "identities": { - "$ref": "#/$defs/previewIdentities" - } - } - } - } - }, - "backend_previewEligibilityResponse": { - "type": "object", - "additionalProperties": false, - "required": [ - "version", - "result" - ], - "properties": { - "version": { - "const": "durable.v1" - }, - "result": { - "type": "array", - "maxItems": 32, - "items": { - "type": "boolean" - } - } - } - }, - "previewIdentities": { - "type": "array", - "maxItems": 32, - "items": { - "type": "object", - "additionalProperties": false, - "required": [ - "messageId", - "toolKey", - "attempt", - "revision" - ], - "properties": { - "messageId": { - "type": [ - "string", - "null" - ] - }, - "toolKey": { - "type": [ - "string", - "null" - ] - }, - "attempt": { - "type": "integer", - "minimum": 0 - }, - "revision": { - "type": "integer", - "minimum": 0 - } - } - } } } } diff --git a/agentscope-durable/scripts/docker-regression/LongHistory.java b/agentscope-durable/scripts/docker-regression/LongHistory.java deleted file mode 100644 index aa19933701..0000000000 --- a/agentscope-durable/scripts/docker-regression/LongHistory.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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.durable.DurableJson; -import io.agentscope.durable.DurableRuntime; -import io.agentscope.durable.DurableTypes.*; -import io.agentscope.durable.EventStreamOptions; -import io.agentscope.durable.LiveEvents; -import io.agentscope.durable.SessionStreamEvent; -import io.agentscope.extensions.durable.jdbc.PostgresBackend; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public class LongHistory { - public static void main(String[] args) throws Exception { - var key = new SessionKey("regression", "long-history"); - var bus = LiveEvents.local(); - try (var backend = PostgresBackend.builder().dataSource(Probe.database()).build(); - var runtime = DurableRuntime.builder().backend(backend).liveEvents(bus).build()) { - backend.create(new SessionSpec(key, new ThreadBinding("history", "1", "1"), null)); - var thread = new ThreadKey(key, "main"); - var turn = backend.submit(thread, "history", DurableJson.value("history")).turnId(); - var lease = - backend.claim(thread, "history-writer", Duration.ofMinutes(5)).orElseThrow(); - var session = runtime.getSession(key); - var options = - EventStreamOptions.builder() - .after(session.snapshot().cursor()) - .deltas(EventStreamOptions.EventDeltaType.MESSAGE) - .build(); - int total = 2048; - var delivered = new CountDownLatch(total); - var positive = new CountDownLatch(1); - var stale = new AtomicInteger(); - try (var observer = - session.subscribeEvents( - options, - event -> { - if (event instanceof SessionStreamEvent.Committed c - && "message.completed".equals(c.event().type())) - delivered.countDown(); - if (event instanceof SessionStreamEvent.EventDelta delta) { - if (delta.eventId().equals("active")) positive.countDown(); - else stale.incrementAndGet(); - } - })) { - long revision = backend.frame(lease).turn().revision(); - String cursor = null; - for (int first = 0; first < total; first += 64) { - var events = new ArrayList(); - for (int i = first; i < first + 64; i++) { - String id = "history-" + i; - events.add( - new EventInput( - id, - "message.completed", - DurableJson.value( - Map.of( - "messageId", - id, - "attempt", - 1, - "revision", - 0, - "text", - id)))); - } - if (first == 0) - events.add( - new EventInput( - "active-partial", - "message.delta", - DurableJson.value( - Map.of( - "messageId", - "partial", - "attempt", - 2, - "revision", - 4, - "text", - "partial")))); - var receipt = - backend.commit( - lease, - new Commit( - "page-" + first, - revision, - DurableJson.value("history"), - List.of(), - List.of(), - List.of(), - events, - TurnStatus.RUNNING, - null, - null, - null)); - revision = receipt.revision(); - cursor = receipt.cursor(); - } - if (!delivered.await(90, TimeUnit.SECONDS)) - throw new AssertionError("missed completions " + delivered.getCount()); - backend.pruneEvents(key, cursor); - for (var id : - List.of("history-0", "history-1024", "history-2047", "partial", "active")) { - bus.publish( - new LiveEvent( - "1", - id, - key, - "main", - turn, - null, - null, - 1, - "message.delta", - DurableJson.value( - Map.of( - "messageId", - id, - "text", - "preview", - "attempt", - 2, - "revision", - 3)))); - } - if (!positive.await(30, TimeUnit.SECONDS) || stale.get() != 0) - throw new AssertionError("stale preview count " + stale.get()); - System.out.println("LONG_HISTORY completions=2048 stale=0 active=1"); - } - } - } -} diff --git a/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java new file mode 100644 index 0000000000..11450e6752 --- /dev/null +++ b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java @@ -0,0 +1,217 @@ +/* + * 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")); + 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) { + 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()); + } + }; + } + + 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") + .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) 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.equals("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, check)) + .leaseDuration(Duration.ofSeconds(4)) + .pollInterval(Duration.ofMillis(100)) + .build()) { + var turn = runtime.createSession(key, "native").submit("one", "perform operation"); + runtime.start(); + long end = System.nanoTime() + Duration.ofSeconds(80).toNanos(); + while (System.nanoTime() < end) { + var v = turn.status(); + if (!old + && scenario.equals("unknown") + && v.status() == TurnStatus.WAITING + && WaitCondition.NATIVE_RECONCILIATION.equals(v.waiting())) { + System.out.println("PARKED " + turn.turnId()); + return; + } + if (v.status().terminal()) { + 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/Subscriber.java b/agentscope-durable/scripts/docker-regression/Subscriber.java deleted file mode 100644 index 56da0bc944..0000000000 --- a/agentscope-durable/scripts/docker-regression/Subscriber.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * 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.durable.*; -import io.agentscope.durable.DurableTypes.*; - -import java.nio.file.*; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicInteger; - -public class Subscriber { - private static final Path CURSOR = Path.of("/tmp/subscriber-cursor"); - - private static void await(CountDownLatch signal) { - try { - if (!signal.await(120, TimeUnit.SECONDS)) - throw new IllegalStateException("callback deadline"); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } - } - - private static void publish(LiveEvents bus, String turn, String field, String id, String text) { - publish(bus, Probe.KEY, turn, field, id, text); - } - - private static void publish( - LiveEvents bus, SessionKey source, String turn, String field, String id, String text) { - String type = field.equals("messageId") ? "message.delta" : "tool.arguments.delta"; - bus.publish( - new LiveEvent( - "1", - UUID.randomUUID().toString(), - source, - "main", - turn, - null, - null, - 1, - type, - DurableJson.value(Map.of(field, id, "text", text)))); - } - - public static void main(String[] args) throws Exception { - var bus = LiveEvents.local(); - try (var backend = - io.agentscope.extensions.durable.jdbc.PostgresBackend.builder() - .dataSource(Probe.database()) - .build(); - var runtime = DurableRuntime.builder().backend(backend).liveEvents(bus).build()) { - var session = runtime.getSession(Probe.KEY); - if (args[0].equals("save")) { - Files.writeString(CURSOR, session.snapshot().cursor()); - return; - } - if (args[0].equals("pressure")) { - pressure(session, bus, args[1]); - return; - } - var filter = new EventFilter("main", args[1], null); - var finished = new CountDownLatch(1); - try (var sub = - session.subscribeEvents( - filter, - EventStreamOptions.builder().after(Files.readString(CURSOR)).build(), - e -> { - try { - if (e instanceof SessionStreamEvent.Committed c) { - var data = c.event().data(); - if (EchoBrainExample.FINAL_ANSWER.equals( - data.path("text").asText())) { - var id = data.required("messageId").asText(); - Files.writeString( - Path.of("/tmp/display-" + id), - id, - StandardOpenOption.CREATE_NEW); - System.out.println("DISPLAY_BEFORE_CURSOR " + id); - Runtime.getRuntime().halt(73); - } - } - if (e instanceof SessionStreamEvent.SnapshotReset reset) { - int answers = 0; - for (var message : - reset.snapshot() - .projection() - .required("messages")) { - if (!args[1].equals( - message.required("turnId").asText())) - throw new AssertionError("turn leak"); - if (!EchoBrainExample.FINAL_ANSWER.equals( - message.path("text").asText())) continue; - String id = message.required("messageId").asText(); - if (!Files.readString(Path.of("/tmp/display-" + id)) - .equals(id)) throw new AssertionError(); - answers++; - } - if (answers != 1) - throw new AssertionError( - "snapshot answer count " + answers); - Files.createFile(Path.of("/tmp/reset-reached")); - while (Files.exists(Path.of("/tmp/hold-reset"))) { - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - throw new IllegalStateException(ex); - } - } - Files.writeString(CURSOR, reset.snapshot().cursor()); - finished.countDown(); - } - } catch (java.io.IOException error) { - throw new IllegalStateException(error); - } - })) { - await(finished); - String boundary = session.snapshot().cursor(); - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); - while (!boundary.equals(sub.cursor())) { - if (System.nanoTime() > deadline) - throw new AssertionError("filtered subscriber lag"); - Thread.sleep(50); - } - } - } - } - - private static void pressure(DurableSession session, LiveEvents bus, String oldTurn) - throws Exception { - var base = session.snapshot(new EventFilter("main", oldTurn, null)); - var options = - EventStreamOptions.builder() - .after(base.cursor()) - .deltas( - EventStreamOptions.EventDeltaType.MESSAGE, - EventStreamOptions.EventDeltaType.TOOL_ARGUMENTS) - .build(); - var blocked = new CountDownLatch(1); - var release = new CountDownLatch(1); - var fastAnswer = new CountDownLatch(1); - var slowAnswer = new CountDownLatch(1); - var sentinel = new CountDownLatch(2); - var stale = new AtomicInteger(); - var slowBurst = new AtomicInteger(); - try (var slow = - session.subscribeEvents( - options, - e -> { - if (e instanceof SessionStreamEvent.EventDelta d) { - String text = d.data().path("text").asText(); - if (text.equals("block")) { - blocked.countDown(); - await(release); - } - if (text.equals("late")) stale.incrementAndGet(); - if (text.equals("burst")) slowBurst.incrementAndGet(); - if (text.equals("sentinel")) sentinel.countDown(); - } - if (answer(e)) slowAnswer.countDown(); - }); - var fast = - session.subscribeEvents( - options, - e -> { - if (e instanceof SessionStreamEvent.EventDelta d) { - if ("late".equals(d.data().path("text").asText())) - stale.incrementAndGet(); - if ("sentinel".equals(d.data().path("text").asText())) - sentinel.countDown(); - } - if (answer(e)) fastAnswer.countDown(); - })) { - try { - publish(bus, oldTurn, "toolCallId", "new", "block"); - await(blocked); - for (int i = 0; i < 4096; i++) - publish(bus, oldTurn, "toolCallId", "burst", "burst"); - var turn = session.submit("slow-fast", "Call echo"); - await(fastAnswer); - System.out.println("FAST_WHILE_BLOCKED " + turn.turnId()); - } finally { - release.countDown(); - } - await(slowAnswer); - // Wait for the saturated queue to drain before using an ordered positive control. - var end = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); - while (!Objects.equals(fast.cursor(), session.snapshot().cursor()) - || !Objects.equals(slow.cursor(), fast.cursor())) { - if (System.nanoTime() > end) throw new AssertionError("durable lag"); - Thread.sleep(50); - } - for (var message : base.projection().required("messages")) { - if (message.path("complete").asBoolean()) - publish( - bus, - oldTurn, - "messageId", - message.required("messageId").asText(), - "late"); - } - publish(bus, oldTurn, "toolCallId", "echo-" + oldTurn, "late"); - publish( - bus, - new SessionKey("other", Probe.KEY.sessionId()), - oldTurn, - "toolCallId", - "new", - "late"); - bus.publish( - new LiveEvent( - "1", - "oversized", - Probe.KEY, - "main", - oldTurn, - null, - null, - 1, - "tool.arguments.delta", - DurableJson.value( - Map.of( - "toolCallId", - "new", - "text", - "late", - "padding", - "x".repeat(70 * 1024))))); - publish(bus, oldTurn, "toolCallId", "new", "sentinel"); - await(sentinel); - if (stale.get() != 0) throw new AssertionError("stale previews " + stale); - if (slowBurst.get() > 128) throw new AssertionError("slow queue exceeded capacity"); - System.out.println("STALE_PREVIEWS 0 SLOW_BURST " + slowBurst.get() + "/4096"); - } - } - - private static boolean answer(SessionStreamEvent e) { - return e instanceof SessionStreamEvent.Committed c - && EchoBrainExample.FINAL_ANSWER.equals(c.event().data().path("text").asText()); - } -} diff --git a/agentscope-durable/scripts/docker-regression/profile_journal.py b/agentscope-durable/scripts/docker-regression/profile_journal.py deleted file mode 100644 index b32421e3c8..0000000000 --- a/agentscope-durable/scripts/docker-regression/profile_journal.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 -"""Attribute persisted journal bytes on a single-thread Docker PostgreSQL test database.""" - -import argparse -import base64 -import collections -import json -import re -import struct -import subprocess -import zlib - -DESCRIPTOR = struct.Struct(">I32s") - - -def profile(container, database, user, milestones, detail_turn=None): - # One statement gives the journal roots and the immutable chunks one MVCC view. - query = """ - SELECT record_key, part_key, payload - FROM durable_parts - WHERE part_key LIKE '%:journal:%' OR record_key LIKE 'object:%' - ORDER BY record_key, part_key - """ - command = [ - "docker", - "exec", - container, - "psql", - "-XqAt", - "-v", - "ON_ERROR_STOP=1", - "-U", - user, - "-d", - database, - "-F", - "\t", - "-c", - query, - ] - objects = {} - journal = [] - with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process: - for row in process.stdout: - record, part, payload = row.rstrip("\n").split("\t", 2) - if record.startswith("object:"): - if part == "chunk:0": - encoded = json.loads(payload) - data = ( - zlib.decompress(base64.b64decode(encoded[1:])) - if encoded.startswith("~") - else base64.b64decode(encoded) - ) - objects[record.split("/", 1)[1]] = ( - data, - len(payload.encode()), - ) - else: - journal.append( - ( - record, - part.split(":journal:", 1)[0], - json.loads(payload), - len(payload.encode()), - ) - ) - if process.wait(): - raise RuntimeError("Could not read PostgreSQL journal") - if len({(record, prefix) for record, prefix, _, _ in journal}) != 1: - raise ValueError("Use a database containing exactly one measured Thread") - - usage = collections.defaultdict(int) - manifests = set() - turns = set() - detail = {} - inline_and_roots = [0, 0] - - def report(): - totals = collections.Counter() - for digest, mask in usage.items(): - totals[("journal", "snapshots", "shared")[mask - 1]] += objects[digest][1] - totals["journal"] += inline_and_roots[0] - totals["snapshots"] += inline_and_roots[1] - print( - json.dumps( - { - "turns": len(turns), - **totals, - "index_bytes_included": sum(objects[h][1] for h in manifests), - }, - sort_keys=True, - ) - ) - - for _, _, stored, length in journal: - references = set() - index_references = set() - if "chunked" in stored: - root = stored["chunked"] - key = root["reference"]["digest"] - references.add(key) - if root["levels"]: - index_references.add(key) - index = objects[key][0] - for level in range(root["levels"], 0, -1): - keys = [digest.hex() for _, digest in DESCRIPTOR.iter_unpack(index)] - references.update(keys) - if level > 1: - index_references.update(keys) - # The first leaf holds the journal envelope. Avoid reconstructing the history. - index = ( - objects[keys[0]][0] - if level == 1 - else b"".join(objects[k][0] for k in keys) - ) - - def header(field): - match = re.search(rb'"' + field + rb'":"([^"]+)"', index) - if not match: - raise ValueError("Missing journal header " + field.decode()) - return match[1].decode() - - kind, turn = header(b"type"), header(b"turnId") - else: - kind, turn = (stored["inline"][k] for k in ("type", "turnId")) - if turn not in turns: - if len(turns) in milestones: - report() - turns.add(turn) - if detail_turn == len(turns): - row = detail.setdefault( - kind, {"entries": 0, "serialized_bytes": 0, "new_stored_payload_bytes": 0} - ) - row["entries"] += 1 - if "chunked" in stored: - row["serialized_bytes"] += root["size"] - else: - inline = json.dumps(stored["inline"], separators=(",", ":"), ensure_ascii=False) - row["serialized_bytes"] += len(inline.encode()) - row["new_stored_payload_bytes"] += length + sum( - objects[key][1] for key in references if key not in usage - ) - manifests.update(index_references) - snapshot = kind == "state/checkpoint" - inline_and_roots[int(snapshot)] += length - for key in references: - usage[key] |= 2 if snapshot else 1 - if len(turns) in milestones: - report() - if detail_turn is not None: - if not detail: - raise ValueError("Requested detail Turn was not found") - print(json.dumps({"detail_turn": detail_turn, "types": detail}, sort_keys=True)) - if not milestones or max(milestones) > len(turns): - raise ValueError(f"Only {len(turns)} Turns have journal entries") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("container") - parser.add_argument("database") - parser.add_argument("user") - parser.add_argument("milestones", nargs="+", type=int) - parser.add_argument("--detail-turn", type=int, help="attribute new bytes to first-writing journal event types in this Turn") - args = parser.parse_args() - profile(args.container, args.database, args.user, set(args.milestones), args.detail_turn) diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 5002a0746b..0ed167984d 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 -"""Run real ACK redelivery, model takeover and subscriber recovery on an isolated Docker network.""" +"""Run real ACK redelivery, model takeover and native tool recovery on an isolated Docker network.""" -from concurrent.futures import ThreadPoolExecutor import os from pathlib import Path import re @@ -351,6 +350,50 @@ def retried(): "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"): + service = "native-" + scenario + start( + service, + JRE, + 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") + docker("kill", name(service)) + report = client("NativeReplayProbe", scenario, "recover") + terminal = "PARKED" if scenario == "unknown" else "SUCCEEDED" + match = re.search(r"^" + terminal + r" (turn_[\w-]+)$", report, re.MULTILINE) + if not match: + raise AssertionError(report) + assert sql(count) == ("2" if scenario == "safe" else "1"), report + assert report.count("MODEL_CHECK") == (0 if scenario == "safe" else 1), report + answers = sql( + "select count(*) from durable_parts where part_key like 'event:%' and " + "payload::jsonb->>'type'='message.completed' and payload::jsonb#>>'{data,text}'='verified answer' and " + "payload::jsonb->>'turnId'='" + match[1] + "'" + ) + assert answers == ("0" if scenario == "unknown" else "1") + print( + "native", + scenario, + terminal, + "starts", + sql(count), + "answers", + answers, + flush=True, + ) + def topics(): result = run( "docker", @@ -398,12 +441,11 @@ def topics(): "-g", "regression-hands-" + suffix, ) - print(client("LongHistory").strip(), flush=True) java("model", "model") java("brain-a", "brain") java("hands-a", "hands") redeliver("command", "hands") - old_turn = redeliver("result", "brain") + redeliver("result", "brain") gate("model", "touch", "block") turn = submit("model") wait("provider received", lambda: "RECEIVED " + turn in logs("model")) @@ -421,43 +463,6 @@ def topics(): assert logs("model").count("RECEIVED " + turn) == 2 assert logs("model").count("INFERENCE " + turn) == 1 print("model takeover: two requests, one inference", flush=True) - client("Subscriber", "save") - turn = submit("subscriber-crash") - done(turn) - client("Subscriber", "watch", turn, code=73) - done(submit("offline")) - client("Probe", "prune") - gate("client", "touch", "hold-reset") - with ThreadPoolExecutor(max_workers=1) as pool: - reconnect = pool.submit(client, "Subscriber", "watch", turn) - try: - wait( - "snapshot callback", - lambda: run( - "docker", - "exec", - name("client"), - "test", - "-e", - "/tmp/reset-reached", - check=False, - ).returncode - == 0, - ) - done(submit("during-reset")) - finally: - gate("client", "rm", "hold-reset") - reconnect.result() - print("subscriber restored one displayed answer from pruned cursor", flush=True) - report = client("Subscriber", "pressure", old_turn) - assert "STALE_PREVIEWS 0" in report - print( - next(line for line in report.splitlines() if line.startswith("STALE_PREVIEWS")), - flush=True, - ) - done(re.search(r"FAST_WHILE_BLOCKED (turn_[\w-]+)", report)[1]) - print("slow/fast: committed answer before release; stale previews=0", flush=True) - active = "brain-b" if owner == "brain-a" else "brain-a" gate("model", "touch", "block") turn = submit("cancel-in-flight") @@ -479,9 +484,13 @@ def 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#>>'{inline,recoveryCursor}',payload::jsonb#>>'{inline,position}' from durable_parts where part_key like '%:checkpoint' and payload::jsonb#>>'{inline,recoveryCursor}' is not null" + " and 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 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 90add4b4d7..d5ef186f6f 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 @@ -38,7 +38,6 @@ import io.agentscope.durable.DurableTypes.Lease; import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; -import io.agentscope.durable.DurableTypes.PreviewIdentity; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -454,14 +453,6 @@ public void cancel(ThreadKey session, String turnId, String requestId) { call("cancel", "thread", session, "turnId", turnId, "requestId", requestId); } - @Override - public List previewEligibility(SessionKey key, List identities) { - return List.of( - as( - call("previewEligibility", "session", key, "identities", identities), - Boolean[].class)); - } - @Override public Snapshot snapshot(SessionKey session) { return as(call("snapshot", "session", session), Snapshot.class); 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 b0cef6090d..7deaac9b65 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 @@ -313,18 +313,6 @@ public void handle(HttpExchange exchange) throws IOException { backend.cancel(thread, text(p, "turnId"), text(p, "requestId")); result = null; } - case "previewEligibility" -> - result = - backend.previewEligibility( - key, - List.of( - get( - p, - "identities", - io.agentscope.durable.DurableTypes - .PreviewIdentity - [] - .class))); case "snapshot" -> result = backend.snapshot(key); case "events" -> result = diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml b/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml index f89960c481..5e316d9af4 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/pom.xml @@ -21,11 +21,6 @@ agentscope-durable-runtime ${project.version} - - net.java.dev.jna - jna-platform - 5.17.0 - org.xerial sqlite-jdbc diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java index 03d4a3db82..8d85440117 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/main/java/io/agentscope/extensions/durable/jdbc/FileObjectStore.java @@ -15,12 +15,6 @@ */ package io.agentscope.extensions.durable.jdbc; -import com.sun.jna.Native; -import com.sun.jna.Platform; -import com.sun.jna.platform.win32.Kernel32; -import com.sun.jna.platform.win32.WinBase; -import com.sun.jna.platform.win32.WinDef.DWORD; -import com.sun.jna.platform.win32.WinError; import io.agentscope.durable.DurableException; import io.agentscope.durable.store.ObjectStore; import java.io.IOException; @@ -58,19 +52,13 @@ public Reference put(String scope, byte[] bytes) { channel.force(true); } try { - if (Platform.isWindows()) { - publishWindows(temporary, destination); - } else { - Files.createLink(destination, temporary); - } + Files.createLink(destination, temporary); } catch (FileAlreadyExistsException existing) { - read(ref); // Verify the winner's size and digest. + ObjectStore.verify(id(), ref, read(ref)); } - if (!Platform.isWindows()) { - try (var directory = - FileChannel.open(destination.getParent(), StandardOpenOption.READ)) { - directory.force(true); - } + try (var directory = + FileChannel.open(destination.getParent(), StandardOpenOption.READ)) { + directory.force(true); } return ref; } catch (IOException failure) { @@ -87,19 +75,6 @@ public Reference put(String scope, byte[] bytes) { } } - // Windows cannot open the parent directory as a Java FileChannel. Publish in the - // same directory with write-through and without permission to replace an existing object. - private static void publishWindows(Path temporary, Path destination) throws IOException { - if (Kernel32.INSTANCE.MoveFileEx( - temporary.toString(), - destination.toString(), - new DWORD(WinBase.MOVEFILE_WRITE_THROUGH))) return; - int error = Native.getLastError(); - if (error == WinError.ERROR_ALREADY_EXISTS || error == WinError.ERROR_FILE_EXISTS) - throw new FileAlreadyExistsException(destination.toString()); - throw new IOException("MoveFileEx failed with Windows error " + error); - } - public byte[] read(Reference ref) { if (!id().equals(ref.store())) throw new DurableException(DurableException.Code.INVALID, "Object store differs"); 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 8fd4849962..71aa0fd096 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 @@ -114,14 +114,6 @@ public JdbcRecordStore(Connections connections, Dialect dialect, boolean initial statement.executeUpdate( "CREATE INDEX IF NOT EXISTS durable_work_ready ON" + " durable_work(queue,ready_at,record_key,work_id)"); - if (dialect == Dialect.POSTGRESQL) { - statement.executeUpdate( - "CREATE INDEX IF NOT EXISTS durable_parts_prefix ON durable_parts" - + " (record_key, part_key COLLATE \"C\")"); - statement.executeUpdate( - "CREATE INDEX IF NOT EXISTS durable_records_prefix ON durable_records" - + " (record_key COLLATE \"C\") WHERE payload IS NOT NULL"); - } } } catch (SQLException e) { throw unavailable(e); @@ -238,7 +230,7 @@ private long time(Connection c) throws SQLException { } } - private final class Parts implements Transaction { + private static final class Parts implements Transaction { private final Connection connection; private final String scope; private final long now; @@ -301,13 +293,15 @@ public void put(String part, JsonNode value) { public List keys(String prefix, String after, int limit) { checkLimit(limit); - String upper = prefixEnd(prefix); try (var s = connection.prepareStatement( - "SELECT part_key FROM durable_parts WHERE record_key=? AND " - + prefixPage("part_key", upper))) { + "SELECT part_key FROM durable_parts WHERE record_key=? AND part_key>=?" + + " AND part_key? ORDER BY part_key LIMIT ?")) { s.setString(1, scope); - bindPage(s, 2, prefix, upper, after, limit); + s.setString(2, prefix); + s.setString(3, prefix + "\uffff"); + s.setString(4, after == null ? "" : after); + s.setInt(5, limit); try (var rs = s.executeQuery()) { var keys = new ArrayList(); while (rs.next()) keys.add(rs.getString(1)); @@ -384,57 +378,20 @@ private static void checkKey(String value, int limit, String name) { throw new IllegalArgumentException("Invalid " + name); } - private static String prefixEnd(String prefix) { - // UTF-8 byte order agrees with scalar-value order. Carry past maximal suffixes - // and skip surrogates to keep the exclusive upper bound a valid database string. - for (int end = prefix.length(); end > 0; ) { - int cp = prefix.codePointBefore(end); - end -= Character.charCount(cp); - if (cp < Character.MAX_CODE_POINT) { - int next = cp == Character.MIN_SURROGATE - 1 ? Character.MAX_SURROGATE + 1 : cp + 1; - return prefix.substring(0, end) + Character.toString(next); - } - } - return null; - } - - private String prefixPage(String column, String upper) { - String key = dialect == Dialect.POSTGRESQL ? column + " COLLATE \"C\"" : column; - return key - + ">=?" - + (upper == null ? "" : " AND " + key + "? ORDER BY " - + key - + " LIMIT ?"; - } - - private static void bindPage( - java.sql.PreparedStatement statement, - int index, - String prefix, - String upper, - String after, - int limit) - throws SQLException { - statement.setString(index++, prefix); - if (upper != null) statement.setString(index++, upper); - statement.setString(index++, after == null ? "" : after); - statement.setInt(index, limit); - } - @Override public List keys(String prefix, String after, int limit) { if (limit < 1 || limit > 1000) throw new IllegalArgumentException("Limit must be 1..1000"); - String upper = prefixEnd(prefix); + // Lexical bounds avoid LIKE wildcard interpretation in namespaces. try (Connection c = connect(); var s = c.prepareStatement( "SELECT record_key FROM durable_records WHERE payload IS NOT NULL" - + " AND " - + prefixPage("record_key", upper))) { - bindPage(s, 1, prefix, upper, after, limit); + + " AND record_key>=? AND record_key? ORDER" + + " BY record_key LIMIT ?")) { + s.setString(1, prefix); + s.setString(2, prefix + "\uffff"); + s.setString(3, after == null ? "" : after); + s.setInt(4, limit); try (var rs = s.executeQuery()) { List result = new ArrayList<>(); while (rs.next()) result.add(rs.getString(1)); diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java index 602c835d9f..91fc7eb607 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/BackendAssemblyTest.java @@ -16,7 +16,6 @@ package io.agentscope.extensions.durable.jdbc; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -33,7 +32,6 @@ import io.agentscope.durable.DurableTypes.ThreadKey; import io.agentscope.durable.SessionBackend; import io.agentscope.durable.Wakeups; -import io.agentscope.durable.store.ObjectStore; import java.nio.file.Files; import java.nio.file.Path; import java.sql.DriverManager; @@ -112,24 +110,6 @@ void cleanup() throws Exception { } } - @Test - void immutableFilePublicationReusesAndVerifiesTheExistingDestination() throws Exception { - var root = directory.resolve("objects"); - var writer = new FileObjectStore(root); - var reopened = new FileObjectStore(root); - byte[] content = {1, 2, 3}; - String scope = ObjectStore.digest(content); - var ref = writer.put(scope, content); - assertArrayEquals(content, reopened.read(ref)); - assertEquals(ref, reopened.put(scope, content)); - byte[] damaged = {3, 2, 1}; - Files.write(root.resolve(ref.key()), damaged); - assertEquals( - DurableException.Code.INVALID, - assertThrows(DurableException.class, () -> writer.put(scope, content)).code()); - assertArrayEquals(damaged, Files.readAllBytes(root.resolve(ref.key()))); - } - @Test void completeBackendReopensOriginalAdmissionAndClosesOnlyItsOwnStore() throws Exception { var notifications = new AtomicInteger(); diff --git a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java index 51bd27637c..c8b8783599 100644 --- a/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java +++ b/agentscope-extensions/agentscope-extensions-durable-jdbc/src/test/java/io/agentscope/extensions/durable/jdbc/ScopedWorkStoreTest.java @@ -28,8 +28,6 @@ import io.agentscope.durable.DurableTypes.SessionSpec; import io.agentscope.durable.DurableTypes.ThreadBinding; import io.agentscope.durable.TransactionalSessionBackend; -import io.agentscope.durable.store.ObjectStore; -import io.agentscope.durable.store.RecordObjectStore; import io.agentscope.durable.store.RecordStore; import java.nio.file.Path; import java.sql.DriverManager; @@ -85,83 +83,6 @@ void close() throws Exception { } } - @Test - void prefixBoundsCoverSupplementarySuffixesAndCarryPastMaximalScalars() { - String max = Character.toString(Character.MAX_CODE_POINT); - String prefix = "literal_%:" + max; - store.transaction( - "unicode", - tx -> { - for (var key : - List.of( - prefix, - prefix + max, - "literal_%;", - "a\uD7FF", - "a\uE000", - max, - max + "x")) tx.put(key, DurableJson.value(1)); - assertEquals(List.of(prefix, prefix + max), tx.keys(prefix, null, 10)); - assertEquals(List.of(prefix + max), tx.keys(prefix, prefix, 1)); - assertEquals(List.of("a\uD7FF"), tx.keys("a\uD7FF", null, 10)); - assertEquals(List.of(max, max + "x"), tx.keys(max, null, 10)); - return null; - }); - } - - @Test - void coldReadsVerifyMixedCompressedAndRawChunksAndRejectTruncatedData() { - var objects = new RecordObjectStore(store); - byte[] bytes = new byte[2 * 1024 * 1024]; - byte[] random = new byte[1024 * 1024]; - new java.util.Random(43).nextBytes(random); - System.arraycopy(random, 0, bytes, random.length, random.length); - var ref = objects.put(ObjectStore.digest(new byte[0]), bytes); - org.junit.jupiter.api.Assertions.assertArrayEquals( - bytes, new RecordObjectStore(store).read(ref)); - store.transaction( - "object:" + ref.key(), - tx -> { - String encoded = tx.get("chunk:0").asText(); - assertTrue(encoded.startsWith("~")); - assertFalse(tx.get("chunk:1").asText().startsWith("~")); - tx.put( - "chunk:0", - DurableJson.value(encoded.substring(0, encoded.length() - 4))); - return null; - }); - assertThrows(DurableException.class, () -> new RecordObjectStore(store).read(ref)); - } - - @Test - void immutableChunkHitsAvoidDatabaseTransactionsAndNeverExposeCachedBytes() throws Exception { - var borrows = new java.util.concurrent.atomic.AtomicInteger(); - try (var counted = - new JdbcRecordStore( - () -> { - borrows.incrementAndGet(); - return connections.open(); - }, - dialect, - false)) { - var objects = new RecordObjectStore(counted); - byte[] value = {1, 2, 3}; - var scope = ObjectStore.digest(new byte[0]); - var ref = objects.put(scope, value); - int afterCommit = borrows.get(); - value[0] = 9; - objects.read(ref)[1] = 9; - assertEquals(ref, objects.put(scope, new byte[] {1, 2, 3})); - org.junit.jupiter.api.Assertions.assertArrayEquals( - new byte[] {1, 2, 3}, objects.read(ref)); - assertEquals(afterCommit, borrows.get()); - var cold = new RecordObjectStore(counted); - org.junit.jupiter.api.Assertions.assertArrayEquals( - new byte[] {1, 2, 3}, cold.read(ref)); - assertEquals(afterCommit + 1, borrows.get()); - } - } - @Test void siblingsRetainIndependentPayloadsOrderingAndDeadlinesAfterReopen() { store.transaction( diff --git a/docs/dev/en/docs/harness/durable.md b/docs/dev/en/docs/harness/durable.md index 040188be74..a2a957d084 100644 --- a/docs/dev/en/docs/harness/durable.md +++ b/docs/dev/en/docs/harness/durable.md @@ -1004,3 +1004,15 @@ public events; they do not replace the actual child result or its application by ### Uncertain Hands executions Hands keeps querying an admitted provider handle across worker replacement. A missing lookup retains that handle. Before a handle exists, repeated start requires provider-side idempotency across all workers. After eight consecutive UNKNOWN observations by default, the transactional Hands ledger pauses automatic recovery. RocketMQ hosts can set `RocketMqWorker.Builder.unknownLimit` for new executions. The ledger freezes the limit at admission. An operator can claim the exact execution and reconcile with external evidence. The first cancellation wakes parked work to check cancellation; duplicate cancellations preserve its budget. + +### Interrupted native tools + +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 for explicit reconciliation or cancellation. Pass `null` for the model check to use operator reconciliation only. diff --git a/docs/dev/zh/docs/harness/durable.md b/docs/dev/zh/docs/harness/durable.md index 39656f5d67..8f133f3776 100644 --- a/docs/dev/zh/docs/harness/durable.md +++ b/docs/dev/zh/docs/harness/durable.md @@ -879,3 +879,15 @@ var children = new DelegationExecutor(backend, request -> ### Hands 执行结果不确定时的恢复 服务端已返回执行句柄时,接管的 Hands 会继续查询原句柄。查询返回缺失时仍保留该句柄。没有句柄时,只有提供方能对所有 Hands 按同一 executionId 去重才允许再次启动。事务型 Hands 账本默认在连续 8 次 UNKNOWN 后暂停自动恢复。RocketMQ 宿主可通过 `RocketMqWorker.Builder.unknownLimit` 设置新执行的上限,账本在接纳执行时固定该值。运维端可按原执行身份领取租约,依据外部证据核实结果。首次取消会唤醒已暂停的执行以核实取消结果,重复取消保留原有预算。 + +### 原生工具中断后的恢复 + +可按工具名配置恢复策略: + +```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` 即可关闭自查。 From 33bf983ee77d5a461015ee5174e50e3f7b728e7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 17 Nov 2026 11:06:24 +0800 Subject: [PATCH 31/38] Use a published RocketMQ image for the Docker regression --- agentscope-durable/README.md | 3 ++- agentscope-durable/scripts/docker-regression/run.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index e8e1b65c7f..253eed8f3b 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -482,7 +482,8 @@ The runner builds the current checkout and creates a private Docker network with RocketMQ, independent Brain and Hands JVMs, and a counting model endpoint. It disconnects receivers before ACK and kills 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. Set `ROCKETMQ_IMAGE` to use a locally available RocketMQ 5 image +volumes and network on exit. The default image is `apache/rocketmq:5.5.0`. Set +`ROCKETMQ_IMAGE` to use a different RocketMQ 5 image with the broker proxy and `mqadmin` tools. The paired-consumer comparison starts separate NameServer, Broker, Proxy and consumer JVMs, diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 0ed167984d..30f18e96e6 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -15,7 +15,7 @@ HERE = Path(__file__).resolve().parent ROOT = HERE.parents[2] PROJECT = "durable-" + uuid.uuid4().hex[:10] -MQ = os.getenv("ROCKETMQ_IMAGE", "apache/rocketmq:5.5.1") +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." From 8044606c02573a8497659e0ea04c1cc376488756 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 11:32:02 +0800 Subject: [PATCH 32/38] Resume committed native tool and model answers after Brain loss --- .../java/io/agentscope/core/ReActAgent.java | 5 +++- .../core/journal/InvocationRecorder.java | 2 +- .../core/journal/JournalProjection.java | 11 ++++++- .../core/journal/ThreadRecovery.java | 16 +++++----- .../agentscope/AgentScopeAdapterTest.java | 25 ++++++++++++---- .../docker-regression/NativeReplayProbe.java | 3 +- .../scripts/docker-regression/run.py | 27 +++++++++++++++-- .../openai/OpenAIStreamTerminationTest.java | 30 ++----------------- 8 files changed, 74 insertions(+), 45 deletions(-) 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 0cc519659f..d2bb102228 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -2734,7 +2734,10 @@ private Mono doCallInner(List msgs) { .toList(); for (var pair : pairs) messages.add( - buildReturnDirectPlaceholderMsg(pair.getKey(), pair.getValue())); + buildReturnDirectPlaceholderMsg( + pair.getKey(), + pair.getValue() + .withState(pair.getValue().completedState()))); return Mono.just(finalizeReturnDirect(pairs, state.getReplyId())); } } 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 976ffca827..bb6fe5b50d 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 @@ -793,7 +793,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 aea414d6a0..cc2d0d825f 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/ThreadRecovery.java b/agentscope-core/src/main/java/io/agentscope/core/journal/ThreadRecovery.java index 9ac51cc9db..617b76131d 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 @@ -85,7 +85,10 @@ private static void reconcile( else context.set(i, message.withContent(retained)); } context.addAll(verifiedMessages); - if (complete && !outcomes.isEmpty() && returnsDirectly(log, projection, state)) { + if (complete + && !outcomes.isEmpty() + && returnsDirectly( + log, projection.asOfSeq(), projection.positionTurnId(), state)) { state.setReturnDirectTurn(projection.positionTurnId()); } long seq = projection.asOfSeq(); @@ -152,14 +155,14 @@ private static void reconcile( } } - private static boolean returnsDirectly( - ThreadJournal log, JournalProjection projection, AgentState state) { + 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.getState() != ToolResultState.SUCCESS) return false; + if (result.completedState() != ToolResultState.SUCCESS) return false; successful.add(result.getId()); } index--; @@ -168,9 +171,8 @@ private static boolean returnsDirectly( 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.recoveryCursor(), projection.asOfSeq())) { - if ("tool/dispatch".equals(event.type()) - && Objects.equals(projection.positionTurnId(), event.turnId())) { + for (var event : log.scanMetadata(log.recoveryCursor(), 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); 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 f003b3ad35..01a38198f7 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 @@ -665,8 +665,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(); @@ -685,8 +686,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( @@ -738,7 +751,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( diff --git a/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java index a8bf1e2b82..826b5d6ae2 100644 --- a/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java +++ b/agentscope-durable/scripts/docker-regression/NativeReplayProbe.java @@ -139,7 +139,8 @@ public Mono callAsync( "receipt")); insert.executeUpdate(); } - if (old) Thread.sleep(Long.MAX_VALUE); + if (old && !scenario.equals("stored-direct")) + Thread.sleep(Long.MAX_VALUE); return ToolResultBlock.text("receipt-7"); }); } diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 860d3c9e41..9d90bb7215 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -184,6 +184,16 @@ def compile_probes(folder): "c.commit();\n CheckpointGate.committed();\n return result;", 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( [ @@ -198,6 +208,7 @@ def compile_probes(folder): loop, model, jdbc_store, + action_observations, ], cwd=folder, check=True, @@ -354,12 +365,13 @@ def retried(): "never-direct", "manual-direct", "cancel-direct", + "stored-direct", ): service = "native-" + scenario start( service, JRE, - mount, + [*mount, "-e", "HOLD_NATIVE_RESULT=1"] if scenario == "stored-direct" else mount, "java", "-Xmx256m", "-cp", @@ -370,6 +382,17 @@ def retried(): ) 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: @@ -383,7 +406,7 @@ def retried(): 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 else 1 + 0 if scenario.startswith("safe") or operator or stored else 1 ), report if scenario.endswith("-direct"): assert logs(service).count("REASONING_REQUEST") == 1 diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java index 510ac9ba42..bb437f76f0 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java @@ -21,8 +21,6 @@ import io.agentscope.core.model.transport.HttpTransport; import io.agentscope.extensions.model.openai.dto.OpenAIMessage; import io.agentscope.extensions.model.openai.dto.OpenAIRequest; -import io.agentscope.extensions.model.openai.exception.OpenAIException; -import java.io.EOFException; import java.time.Duration; import java.util.List; import org.junit.jupiter.api.DisplayName; @@ -54,7 +52,7 @@ class OpenAIStreamTerminationTest { * completes ({@link Flux#never()}) — simulating a gateway that holds the connection open * after {@code [DONE]}. */ - private static HttpTransport transport(Flux frames) { + private static HttpTransport keepAliveTransportAfterDone() { return new HttpTransport() { @Override public HttpResponse execute(HttpRequest request) { @@ -63,7 +61,7 @@ public HttpResponse execute(HttpRequest request) { @Override public Flux stream(HttpRequest request) { - return frames; + return Flux.just(CHUNK_CONTENT, CHUNK_FINISH, "[DONE]").concatWith(Flux.never()); } @Override @@ -71,24 +69,6 @@ public void close() {} }; } - @Test - void truncatedStreamErrorsButFinishReasonPermitsCleanEof() { - for (boolean complete : List.of(false, true)) { - var frames = - complete ? Flux.just(CHUNK_CONTENT, CHUNK_FINISH) : Flux.just(CHUNK_CONTENT); - var stream = - new OpenAIClient(transport(frames)) - .stream("test", "http://localhost", sampleRequest(), null); - var expectation = StepVerifier.create(stream).expectNextCount(complete ? 2 : 1); - if (complete) expectation.verifyComplete(); - else - expectation.verifyErrorMatches( - error -> - error instanceof OpenAIException - && error.getCause() instanceof EOFException); - } - } - private static OpenAIRequest sampleRequest() { return OpenAIRequest.builder() .model("gpt-4o-mini") @@ -99,11 +79,7 @@ private static OpenAIRequest sampleRequest() { @Test @DisplayName("Stream should complete on [DONE] even if the connection stays open") void streamCompletesOnDoneSentinelWithoutWaitingForConnectionClose() { - OpenAIClient client = - new OpenAIClient( - transport( - Flux.just(CHUNK_CONTENT, CHUNK_FINISH, "[DONE]") - .concatWith(Flux.never()))); + OpenAIClient client = new OpenAIClient(keepAliveTransportAfterDone()); StepVerifier.create( client.stream( From 3bf005dfae4998061b2f65bea0a0f820e1c57b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 11:38:04 +0800 Subject: [PATCH 33/38] Limit model continuation to recovery-aware hosts --- .../src/main/java/io/agentscope/core/ReActAgent.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 d2bb102228..ae2b2a4acb 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -3628,7 +3628,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(); } From 91ccf70c5c7c9a782b36dcdbfd59d0ea679db613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 11:42:55 +0800 Subject: [PATCH 34/38] Isolate RocketMQ redelivery from model connection loss --- agentscope-durable/README.md | 7 +++--- .../scripts/docker-regression/run.py | 24 ++++++++++++------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index dacd7f7b35..e982bc44f4 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -477,9 +477,10 @@ Run the Docker fault regression from the repository root with Docker, Python 3, python3 agentscope-durable/scripts/docker-regression/run.py ``` -The runner builds the current checkout and creates a private Docker network with PostgreSQL, -RocketMQ, independent Brain and Hands JVMs, and a counting model endpoint. -It disconnects receivers before ACK and kills 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, +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) diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 9d90bb7215..c9ea61f5fa 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -15,6 +15,7 @@ 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/*" @@ -54,7 +55,7 @@ def name(service): return PROJECT + "-" + service -def start(service, image, options, *command): +def start(service, image, options, *command, network=PROJECT): container = name(service) docker( "run", @@ -62,9 +63,7 @@ def start(service, image, options, *command): "--name", container, "--network", - PROJECT, - "--network-alias", - service, + f"name={network},alias={service}", *options, image, *command, @@ -219,10 +218,11 @@ 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, *extra_options], + [*mount, *broker_link, *extra_options], "java", "-Xmx256m", "-cp", @@ -310,7 +310,8 @@ def redeliver(kind, role): and received[0] == "SUCCEEDED" and received[1] == received[2] ), received - docker("network", "disconnect", PROJECT, name(old)) + # Drop the broker link without interrupting database writes or the model request. + docker("network", "disconnect", MQ_NETWORK, name(old)) java(new, role) def retried(): @@ -324,7 +325,7 @@ def retried(): ) second = wait("same broker message redelivered", retried, 420) - docker("network", "connect", PROJECT, name(old)) + docker("network", "connect", MQ_NETWORK, name(old)) gate(old, "rm", "hold-" + kind) done(turn) assert logs("model").count("RECEIVED " + turn) == 1 @@ -332,7 +333,7 @@ def retried(): return turn start("pg", "postgres:17-alpine", ["-e", "POSTGRES_HOST_AUTH_METHOD=trust"]) - start("ns", MQ, ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx128m"], "sh", "mqnamesrv") + start("ns", MQ, ["-e", "JAVA_OPT_EXT=-Xms128m -Xmx128m"], "sh", "mqnamesrv", network=MQ_NETWORK) start( "broker", MQ, @@ -340,6 +341,7 @@ def retried(): "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( @@ -500,6 +502,7 @@ def topics(): "ns:9876", "-pm", "cluster", + network=MQ_NETWORK, ) wait("cluster proxy startup", lambda: "startup successfully" in logs("proxy")) java("model", "model") @@ -612,9 +615,11 @@ def pointer(): ) 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)) @@ -652,6 +657,7 @@ def pointer(): 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") @@ -669,4 +675,4 @@ def pointer(): finally: if containers: run("docker", "rm", "-f", "-v", *containers) - docker("network", "rm", PROJECT) + run("docker", "network", "rm", PROJECT, MQ_NETWORK) From e33a158e4e858edfcb4e5e7d6f60fd1248ef0160 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 11:57:04 +0800 Subject: [PATCH 35/38] Keep JDBC lease timeout independent of snapshot setup --- .../io/agentscope/extensions/durable/jdbc/JdbcRecordStore.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f02a8a4ea5..dc775131c1 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 @@ -327,6 +327,7 @@ 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 = @@ -343,7 +344,6 @@ private T transact( statement.execute(); } } - var transaction = new Scopes(connection, writable, timing); T result = action.apply(transaction.open(key)); if (writable) for (var parts : transaction.opened.values()) parts.flush(); if (timing == null) connection.commit(); From 20ebf2d08b204acd855888e0867459c760f18e43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 11:57:57 +0800 Subject: [PATCH 36/38] Keep the recovery and subscriber pull requests independently mergeable --- agentscope-durable/README.md | 34 ++++++++++--------- .../durable/NotifyingSessionBackend.java | 11 ++++-- .../io/agentscope/durable/SessionBackend.java | 8 +++-- .../durable/http/HttpSessionBackend.java | 7 ++-- .../durable/http/SessionBackendHandler.java | 7 ++-- 5 files changed, 41 insertions(+), 26 deletions(-) diff --git a/agentscope-durable/README.md b/agentscope-durable/README.md index b0b8c20193..497ecaeb1d 100644 --- a/agentscope-durable/README.md +++ b/agentscope-durable/README.md @@ -455,22 +455,7 @@ 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. -## Build and check - -Java 17+ and Maven are required; isolated dependency checking also needs Python 3. -From the repository root: - -```sh -make -C agentscope-durable check -make -C agentscope-durable independent -``` - -Normal checking covers build, formatting and tests. Isolation checking builds source -dependencies in a separate Maven cache and audits dependency trees. -Validate broker delivery, provider query/cancel -behavior and recovery under host replacement in your deployment environment. -Unqueryable or unverifiable external effects remain `UNKNOWN`; arbitrary external -operations are not promised exactly-once execution. +## Docker recovery regressions Run the Docker fault regression from the repository root with Docker, Python 3, Maven and a JDK on PATH: @@ -505,6 +490,23 @@ to the surviving consumer after killing its peer before ACK. 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. +From the repository root: + +```sh +make -C agentscope-durable check +make -C agentscope-durable independent +``` + +Normal checking covers build, formatting and tests. Isolation checking builds source +dependencies in a separate Maven cache and audits dependency trees. +Validate broker delivery, provider query/cancel +behavior and recovery under host replacement in your deployment environment. +Unqueryable or unverifiable external effects remain `UNKNOWN`; arbitrary external +operations are not promised exactly-once execution. + ## Usage and reference - [Java usage guide](../docs/dev/en/docs/harness/durable.md): reconnect, control tasks, 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 9ff0402ce9..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 @@ -41,7 +41,6 @@ import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.OutputPage; -import io.agentscope.durable.DurableTypes.RecoveryPolicy; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -427,7 +426,10 @@ public ClaimOutcome claimOutcome(ThreadKey session, String owner, Duration durat @Override public ClaimOutcome claimOutcome( - ThreadKey session, String owner, Duration duration, RecoveryPolicy policy) { + 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; @@ -440,7 +442,10 @@ public ClaimOutcome claimOutcome(TurnDispatch dispatch, String owner, Duration d @Override public ClaimOutcome claimOutcome( - TurnDispatch dispatch, String owner, Duration duration, RecoveryPolicy policy) { + 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; 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 ceb2f7ea4d..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 @@ -38,7 +38,6 @@ import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.OutputPage; -import io.agentscope.durable.DurableTypes.RecoveryPolicy; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -268,12 +267,15 @@ default ClaimOutcome claimOutcome(TurnDispatch dispatch, String owner, Duration /** Claims using the recovery policy pinned when a Turn first starts. */ default ClaimOutcome claimOutcome( - ThreadKey thread, String owner, Duration duration, RecoveryPolicy policy) { + ThreadKey thread, String owner, Duration duration, DurableTypes.RecoveryPolicy policy) { return claimOutcome(thread, owner, duration); } default ClaimOutcome claimOutcome( - TurnDispatch dispatch, String owner, Duration duration, RecoveryPolicy policy) { + TurnDispatch dispatch, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { return claimOutcome(dispatch, owner, duration); } 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 c3317255d0..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; @@ -43,7 +44,6 @@ import io.agentscope.durable.DurableTypes.ModelCallPage; import io.agentscope.durable.DurableTypes.ModelCallView; import io.agentscope.durable.DurableTypes.OutputPage; -import io.agentscope.durable.DurableTypes.RecoveryPolicy; import io.agentscope.durable.DurableTypes.RecoveryView; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.RunPage; @@ -330,7 +330,10 @@ public ClaimOutcome claimOutcome(ThreadKey session, String owner, Duration durat @Override public ClaimOutcome claimOutcome( - ThreadKey session, String owner, Duration duration, RecoveryPolicy policy) { + ThreadKey session, + String owner, + Duration duration, + DurableTypes.RecoveryPolicy policy) { return as( call( "claim", 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 362292b74d..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; @@ -31,7 +32,6 @@ import io.agentscope.durable.DurableTypes.Failure; import io.agentscope.durable.DurableTypes.HarnessSelector; import io.agentscope.durable.DurableTypes.Lease; -import io.agentscope.durable.DurableTypes.RecoveryPolicy; import io.agentscope.durable.DurableTypes.Restoration; import io.agentscope.durable.DurableTypes.SessionKey; import io.agentscope.durable.DurableTypes.SessionSpec; @@ -227,7 +227,10 @@ public void handle(HttpExchange exchange) throws IOException { text(p, "owner"), Duration.ofMillis(p.path("duration").asLong()), p.hasNonNull("policy") - ? get(p, "policy", RecoveryPolicy.class) + ? get( + p, + "policy", + DurableTypes.RecoveryPolicy.class) : null); case "leaseControl" -> result = backend.leaseControl(lease); case "pendingInputs" -> result = backend.pendingInputs(lease); From 0b0a10adfbffd504a317fa785f0364e756585d9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 12:05:56 +0800 Subject: [PATCH 37/38] Gate failed Turn recovery only after the PostgreSQL commit --- .../scripts/docker-regression/CheckpointGate.java | 6 +++++- agentscope-durable/scripts/docker-regression/run.py | 10 +++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/agentscope-durable/scripts/docker-regression/CheckpointGate.java b/agentscope-durable/scripts/docker-regression/CheckpointGate.java index 8daea2ca77..490569c647 100644 --- a/agentscope-durable/scripts/docker-regression/CheckpointGate.java +++ b/agentscope-durable/scripts/docker-regression/CheckpointGate.java @@ -24,6 +24,10 @@ 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) @@ -42,7 +46,7 @@ static void written(String part, JsonNode value) { static void flushed() { String phase = pending.get(); - if (phase != null) stopAt(phase); + if ("snapshot".equals(phase) || "cursor".equals(phase)) stopAt(phase); } static void committed() { diff --git a/agentscope-durable/scripts/docker-regression/run.py b/agentscope-durable/scripts/docker-regression/run.py index 2490afc091..3b608dfda0 100755 --- a/agentscope-durable/scripts/docker-regression/run.py +++ b/agentscope-durable/scripts/docker-regression/run.py @@ -175,6 +175,13 @@ def compile_probes(folder): '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();", @@ -597,7 +604,8 @@ def pointer(): + turn + "' and payload::jsonb->>'type'='turn.failed'" ) - assert failed == "1" and counts(turn) == "1|0|0" + actual = counts(turn) + assert (failed, actual) == ("1", "1|0|0"), (turn, failed, actual) done(submit("after-failure")) else: done(turn) From ed6b69e7fccd87415fb39e203b1ca4352f0b115d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Dzhuzhiyu=2Ezzy=E2=80=9C?= Date: Tue, 1 Dec 2026 12:11:36 +0800 Subject: [PATCH 38/38] Make the DashScope async response check reliable in CI --- ...ScopeNonStreamingBlockingBehaviorTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) 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"); } }