Skip to content

Commit 9dc3efb

Browse files
authored
feat(durable): support brokerless Hands execution and session event push (#4573)
1 parent 26f8b94 commit 9dc3efb

43 files changed

Lines changed: 3890 additions & 168 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,10 @@ Wakeups wakeups() {
492492
return backend == null ? Wakeups.none() : backend.wakeups();
493493
}
494494

495+
SessionEventPush sessionEventPush(SessionKey session) {
496+
return backend == null ? null : backend.sessionEventPush(session);
497+
}
498+
495499
LiveEvents liveEvents() {
496500
return liveEvents;
497501
}
@@ -1176,7 +1180,7 @@ private void dispatchBatch(
11761180
if (!accepting.get() || activeCall.stopped.get()) return;
11771181
var requests = new ArrayList<ExecutionRequest>();
11781182
for (var tool : tools) {
1179-
if (!tool.dispatchAttempted()) executor.validateStart(tool.request());
1183+
if (!tool.dispatchAttempted()) executor.prepareStart(tool.request());
11801184
requests.add(tool.request());
11811185
}
11821186
try {
@@ -1191,7 +1195,7 @@ private void dispatchBatch(
11911195
}
11921196

11931197
private ToolExecution prepareDispatch(Lease lease, ToolExecution tool, Executor executor) {
1194-
if (!tool.dispatchAttempted()) executor.validateStart(tool.request());
1198+
if (!tool.dispatchAttempted()) executor.prepareStart(tool.request());
11951199
try {
11961200
return backend.beginDispatch(
11971201
lease,

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableSession.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ Wakeups wakeups() {
4949
return runtime.wakeups();
5050
}
5151

52+
SessionEventPush sessionEventPush() {
53+
return runtime.sessionEventPush(key());
54+
}
55+
5256
LiveEvents liveEvents() {
5357
return runtime.liveEvents();
5458
}

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/Executor.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,14 @@ public Capabilities(
4545
*/
4646
default void validateStart(ExecutionRequest request) {}
4747

48+
/**
49+
* Prepare infrastructure before recording the first tool dispatch. May be retried after a
50+
* crash and must never start the tool itself.
51+
*/
52+
default void prepareStart(ExecutionRequest request) {
53+
validateStart(request);
54+
}
55+
4856
/** Starts or recovers the execution identified by the request. */
4957
ExecutionResult startExecution(ExecutionRequest request);
5058

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/NotifyingSessionBackend.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ private void report(SessionKey session, RuntimeException error) {
168168
}
169169
}
170170

171+
@Override
172+
public SessionEventPush sessionEventPush(SessionKey session) {
173+
return delegate.sessionEventPush(session);
174+
}
175+
171176
@Override
172177
public Wakeups wakeups() {
173178
return wakeups;

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/SessionBackend.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,11 @@ default Optional<LocalStorage> localStorage() {
8888
return Optional.empty();
8989
}
9090

91+
/** Optional committed push transport for this Session. */
92+
default SessionEventPush sessionEventPush(SessionKey session) {
93+
return null;
94+
}
95+
9196
/**
9297
* Optional local access to change hints. This is wiring, not a remote protocol operation.
9398
* Readers and runtimes always retain polling as their source of truth.
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
/*
2+
* Copyright 2024-2026 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.agentscope.durable;
17+
18+
import io.agentscope.durable.DurableTypes.EventPage;
19+
import io.agentscope.durable.DurableTypes.PublicEvent;
20+
import io.agentscope.durable.DurableTypes.SessionActivity;
21+
import io.agentscope.durable.DurableTypes.SessionKey;
22+
import io.agentscope.durable.DurableTypes.SessionPhase;
23+
import io.agentscope.durable.store.RecordStore;
24+
import java.util.ArrayList;
25+
import java.util.Collection;
26+
import java.util.List;
27+
import java.util.Locale;
28+
import java.util.Map;
29+
import java.util.TreeMap;
30+
import java.util.TreeSet;
31+
32+
/** Storage-side ordered index used by a payload-bearing Session event transport. */
33+
public final class SessionCommittedLog {
34+
public record Entry(String stream, PublicEvent event) {}
35+
36+
public record Prune(String stream, long through) {}
37+
38+
public record Published(PublicEvent event, PublicEvent threadEvent) {}
39+
40+
private record Stored(String stream, long offset, PublicEvent event) {}
41+
42+
public static final class Head {
43+
public long sequence;
44+
public long retained;
45+
public String retainedCursor;
46+
public Map<String, Long> offsets = new TreeMap<>();
47+
public Map<String, SessionActivity> activity = new TreeMap<>();
48+
}
49+
50+
private SessionCommittedLog() {}
51+
52+
public static String key(SessionKey session) {
53+
return "committed-session-events:" + DurableJson.hash(session);
54+
}
55+
56+
private static Head head(RecordStore.Transaction tx) {
57+
var value = tx.get("");
58+
return value == null ? null : DurableJson.convert(value, Head.class);
59+
}
60+
61+
static boolean exists(RecordStore.Transaction tx) {
62+
return head(tx) != null;
63+
}
64+
65+
public static List<Published> append(RecordStore.Transaction tx, List<Entry> entries) {
66+
if (entries.isEmpty()) return List.of();
67+
var first = entries.get(0);
68+
var head = head(tx);
69+
if (head == null) {
70+
// A Session that predates application of this storage mode keeps its existing history.
71+
if (!first.stream().isEmpty() || !"1".equals(first.event().sequence()))
72+
return List.of();
73+
head = new Head();
74+
}
75+
var events = new ArrayList<Published>();
76+
for (var entry : entries) {
77+
var raw = entry.event();
78+
long offset = Long.parseLong(raw.sequence());
79+
if (offset != head.offsets.getOrDefault(entry.stream(), 0L) + 1)
80+
throw new DurableException(
81+
DurableException.Code.CONFLICT, "Session committed event index has a gap");
82+
head.offsets.put(entry.stream(), offset);
83+
String type = raw.type();
84+
String thread = raw.threadId();
85+
var data = raw.data();
86+
if ("thread.activity_changed".equals(type)) {
87+
var previous = activity(head.activity.values());
88+
head.activity.put(entry.stream(), DurableJson.convert(data, SessionActivity.class));
89+
var next = activity(head.activity.values());
90+
if (!next.equals(previous)) {
91+
type = "session.activity_changed";
92+
thread = null;
93+
data = DurableJson.value(next);
94+
}
95+
}
96+
long sequence = ++head.sequence;
97+
var event =
98+
new PublicEvent(
99+
raw.schemaVersion(),
100+
raw.eventId(),
101+
raw.session(),
102+
thread,
103+
raw.turnId(),
104+
raw.runId(),
105+
raw.stepId(),
106+
Long.toString(sequence),
107+
SessionEventCursor.encode(raw.session(), head.offsets),
108+
raw.occurredAt(),
109+
type,
110+
data);
111+
tx.put(part(sequence), DurableJson.value(new Stored(entry.stream(), offset, event)));
112+
tx.put(source(entry.stream(), offset), DurableJson.value(sequence));
113+
events.add(new Published(event, entry.stream().isEmpty() ? null : raw));
114+
}
115+
tx.put("", DurableJson.value(head));
116+
return events;
117+
}
118+
119+
public static void prune(RecordStore.Transaction tx, List<Prune> prunes) {
120+
if (prunes.isEmpty()) return;
121+
var head = head(tx);
122+
if (head == null) return;
123+
long through = head.retained;
124+
for (var prune : prunes) {
125+
var sequence = tx.get(source(prune.stream(), prune.through()));
126+
if (sequence != null) through = Math.max(through, sequence.longValue());
127+
}
128+
if (through == head.retained) return;
129+
for (long sequence = head.retained + 1; sequence <= through; sequence++) {
130+
var value = read(tx, sequence);
131+
tx.put(source(value.stream(), value.offset()), null);
132+
tx.put(part(sequence), null);
133+
head.retainedCursor = value.event().cursor();
134+
}
135+
head.retained = through;
136+
tx.put("", DurableJson.value(head));
137+
}
138+
139+
static EventPage page(
140+
RecordStore.Transaction tx,
141+
SessionKey session,
142+
String cursor,
143+
int limit,
144+
boolean reverse) {
145+
var head = head(tx);
146+
if (head == null) return null;
147+
String high = SessionEventCursor.encode(session, head.offsets);
148+
long position =
149+
cursor == null
150+
? (reverse ? head.sequence + 1 : 0)
151+
: position(tx, session, head, cursor);
152+
if (!reverse && position < head.retained
153+
|| reverse && cursor != null && head.retained > 0 && position - 1 <= head.retained)
154+
throw expired();
155+
var events = new ArrayList<PublicEvent>();
156+
if (reverse) {
157+
for (long i = position - 1; i > head.retained && events.size() < limit; i--)
158+
events.add(read(tx, i).event());
159+
} else {
160+
var parts = tx.parts("ordered:", part(position), limit);
161+
parts.forEach(
162+
value -> events.add(DurableJson.convert(value.value(), Stored.class).event()));
163+
}
164+
String scanned =
165+
events.isEmpty()
166+
? cursor == null ? SessionEventCursor.encode(session, Map.of()) : cursor
167+
: events.get(events.size() - 1).cursor();
168+
String sequence =
169+
events.isEmpty()
170+
? Long.toString(reverse && cursor == null ? 0 : position)
171+
: events.get(events.size() - 1).sequence();
172+
return new EventPage(events, scanned, high, sequence, Long.toString(head.sequence));
173+
}
174+
175+
private static long position(
176+
RecordStore.Transaction tx, SessionKey session, Head head, String cursor) {
177+
try {
178+
var fields = SessionEventCursor.decode(session, cursor).fields();
179+
long position = 0;
180+
while (fields.hasNext()) {
181+
var value = fields.next();
182+
long offset = value.getValue().longValue();
183+
if (!value.getValue().isIntegralNumber()
184+
|| !value.getValue().canConvertToLong()
185+
|| offset <= 0
186+
|| offset > head.offsets.getOrDefault(value.getKey(), 0L))
187+
throw new IllegalArgumentException();
188+
position = Math.addExact(position, offset);
189+
}
190+
if (position < head.retained) throw expired();
191+
String expected =
192+
position == 0
193+
? SessionEventCursor.encode(session, Map.of())
194+
: position == head.retained
195+
? head.retainedCursor
196+
: read(tx, position).event().cursor();
197+
if (!cursor.equals(expected)) throw new IllegalArgumentException();
198+
return position;
199+
} catch (IllegalArgumentException | ArithmeticException invalid) {
200+
throw new DurableException(
201+
DurableException.Code.INVALID, "Invalid Session event cursor");
202+
}
203+
}
204+
205+
private static DurableException expired() {
206+
return new DurableException(
207+
DurableException.Code.CURSOR_EXPIRED, "Cursor expired; load a snapshot");
208+
}
209+
210+
private static Stored read(RecordStore.Transaction tx, long sequence) {
211+
return DurableJson.convert(tx.get(part(sequence)), Stored.class);
212+
}
213+
214+
private static String part(long sequence) {
215+
return "ordered:" + String.format(Locale.ROOT, "%020d", sequence);
216+
}
217+
218+
private static String source(String stream, long offset) {
219+
return "source:" + DurableJson.hash(stream) + ":" + offset;
220+
}
221+
222+
static SessionActivity activity(Collection<SessionActivity> states) {
223+
var pending = new TreeSet<String>();
224+
boolean exhausted = false;
225+
for (var state : states) {
226+
if (state.phase() == SessionPhase.RUNNING)
227+
return new SessionActivity(SessionPhase.RUNNING, List.of());
228+
pending.addAll(state.interactionIds());
229+
exhausted |= state.phase() == SessionPhase.RETRIES_EXHAUSTED;
230+
}
231+
if (!pending.isEmpty())
232+
return new SessionActivity(SessionPhase.REQUIRES_ACTION, List.copyOf(pending));
233+
return new SessionActivity(
234+
exhausted ? SessionPhase.RETRIES_EXHAUSTED : SessionPhase.IDLE, List.of());
235+
}
236+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Copyright 2024-2026 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.agentscope.durable;
17+
18+
import io.agentscope.durable.DurableTypes.PublicEvent;
19+
import io.agentscope.durable.DurableTypes.SessionKey;
20+
import java.util.function.Consumer;
21+
22+
/** Payload-bearing, per-Session notifications for the committed event log. */
23+
public interface SessionEventPush {
24+
/** An event, a committed watermark, or a signal to repair after subscription loss. */
25+
record Update(
26+
PublicEvent event,
27+
PublicEvent threadEvent,
28+
String cursor,
29+
long through,
30+
boolean repair) {}
31+
32+
AutoCloseable subscribe(SessionKey session, Consumer<Update> receiver);
33+
}

0 commit comments

Comments
 (0)