GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fork: one first-come line in the slot gate; idle compaction retried w… · scuttletoby/t3code@5320eb6

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • fork
      • agentSlotRoutes.test.ts
      • agentSlotRoutes.ts
      • continuationSlot.test.ts
      • continuationSlot.ts
      • delegatedResults
        • DelegatedOrphanScan.test.ts
        • DelegatedOrphanScan.ts
        • delegatedResults.testkit.ts
      • handoff
        • HandoffService.test.ts
        • HandoffService.ts
        • handoffDispatch.ts
      • limitResumeSlot.test.ts
      • limitResumeSlot.ts
      • pullRequestWatchSlot.test.ts
      • pullRequestWatchSlot.ts
      • workerWakeSlots.test.ts
      • workerWakeSlots.ts
    • slots
      • SlotGate.test.ts
      • SlotGate.ts
    • waits
      • WaitDelivery.ts
      • WaitService.slots.test.ts
      • WaitService.ts
  • docs/fork
    • README.md
  • packages/shared/src
    • agentSlots.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/fork/agentSlotRoutes.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/fork/agentSlotRoutes.test.ts
+300-3Lines changed: 300 additions & 3 deletions
Large diffs are not rendered by default.
Collapse file

‎apps/server/src/fork/agentSlotRoutes.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/fork/agentSlotRoutes.ts
+188-38Lines changed: 188 additions & 38 deletions
Large diffs are not rendered by default.
Collapse file

‎apps/server/src/fork/continuationSlot.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/fork/continuationSlot.test.ts
+104-14Lines changed: 104 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from "@t3tools/contracts";
1616
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
1717
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
18+
import * as Deferred from "effect/Deferred";
1819
import * as Effect from "effect/Effect";
1920
import * as FileSystem from "effect/FileSystem";
2021
import * as Layer from "effect/Layer";
@@ -54,8 +55,14 @@ interface World {
5455
/** Threads the gate refuses whatever is free. */
5556
full: Set<ThreadId>;
5657
asks: Array<SlotGate.SlotAcquireInput>;
58+
/** The gate's calls after an ask: `started <thread>`, `release <token>`, `leave <key>`. */
59+
calls: Array<string>;
60+
/** Threads whose ask takes this long (a slow count read), then is refused. */
61+
slow: Set<ThreadId>;
5762
/** Threads gone (`null` shell), and whether a shell read fails. */
5863
gone: Set<ThreadId>;
64+
/** Threads the gate sees live but upstream's worker then reads archived. */
65+
archivedForUpstream: Set<ThreadId>;
5966
unreadable: boolean;
6067
logs: Array<string>;
6168
}
@@ -64,27 +71,36 @@ const newWorld = (free: number): World => ({
6471
free,
6572
full: new Set(),
6673
asks: [],
74+
calls: [],
75+
slow: new Set(),
6776
gone: new Set(),
77+
archivedForUpstream: new Set(),
6878
unreadable: false,
6979
logs: [],
7080
});
7181

7282
const gateOf = (world: World) =>
7383
Layer.mock(SlotGate.SlotGate)({
7484
acquire: (input) =>
75-
Effect.sync((): SlotGate.SlotAcquire => {
85+
Effect.gen(function* () {
7686
world.asks.push(input);
77-
if (world.free === 0 || world.full.has(input.callerThreadId!))
78-
return {
79-
type: "refuse",
80-
message: "full",
81-
refusal: { type: "unread", problem: "timeout" },
82-
};
87+
const refused: SlotGate.SlotAcquire = {
88+
type: "refuse",
89+
message: "full",
90+
refusal: { type: "unread", problem: "timeout" },
91+
};
92+
if (world.slow.has(input.callerThreadId!)) {
93+
yield* Effect.sleep("5 seconds");
94+
return refused;
95+
}
96+
if (world.free === 0 || world.full.has(input.callerThreadId!)) return refused;
8397
world.free -= 1;
84-
return { type: "allow", token: world.asks.length };
98+
return { type: "allow", token: world.asks.length } satisfies SlotGate.SlotAcquire;
8599
}),
86-
started: () => Effect.void,
87-
release: () => Effect.void,
100+
started: (token, childThreadId) =>
101+
Effect.sync(() => world.calls.push(`started ${childThreadId} ${token}`)),
102+
release: (token) => Effect.sync(() => world.calls.push(`release ${token}`)),
103+
leave: (keys) => Effect.sync(() => world.calls.push(...keys.map((key) => `leave ${key}`))),
88104
});
89105

90106
const projection = {
@@ -115,7 +131,7 @@ const server = (
115131
),
116132
getThreadRecords: (threadId) =>
117133
Effect.succeed(
118-
world.gone.has(threadId)
134+
world.gone.has(threadId) || world.archivedForUpstream.has(threadId)
119135
? { ...projection, thread: { archivedAt: "2026-11-21T00:00:00.000Z", deletedAt: null } }
120136
: projection,
121137
) as never,
@@ -152,6 +168,12 @@ const offer = (value: ProviderContinuationRequests.ProviderContinuationRequest)
152168
Effect.flatMap((requests) => requests.offer(value)),
153169
);
154170

171+
/** Lets forked fibers run (scheduler turns, no clock moved). */
172+
const settle = Effect.forEach(Array.from({ length: 50 }), () => Effect.yieldNow, { discard: true });
173+
174+
/** The gate's slot calls, without the line's. */
175+
const slotCalls = (world: World) => world.calls.filter((call) => !call.startsWith("leave "));
176+
155177
const waitLogs = (world: World) =>
156178
world.logs.filter((log) => log.includes("provider continuation waits for an agent slot"));
157179

@@ -182,7 +204,10 @@ describe("provider continuations take an agent slot", () => {
182204
targetInstanceId: INSTANCE,
183205
intoThreadId: A,
184206
keepsHeld: true,
207+
place: { key: "continuation:0" },
185208
});
209+
// Every ask in its one place in the gate's line.
210+
assert.isTrue(world.asks.every((asked) => asked.place?.key === "continuation:0"));
186211
world.free = 1;
187212
yield* TestClock.adjust("5 seconds");
188213
const sent = yield* Queue.take(dispatched);
@@ -214,6 +239,69 @@ describe("provider continuations take an agent slot", () => {
214239
}),
215240
);
216241

242+
it.effect("a slow count read for one thread holds up no other thread's continuation", () =>
243+
Effect.gen(function* () {
244+
const world = newWorld(5);
245+
world.slow.add(A);
246+
const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>();
247+
yield* Effect.gen(function* () {
248+
yield* offer(request(A));
249+
yield* offer(request(B));
250+
// No time passes: B is not queued behind A's 5-second ask.
251+
yield* settle;
252+
assert.strictEqual(yield* Queue.size(dispatched), 1);
253+
const sent = yield* Queue.take(dispatched);
254+
assert.strictEqual(sent.type === "message.dispatch" && sent.threadId, B);
255+
// A's ask ends (it cannot be cut off half-way), so the server can stop.
256+
yield* TestClock.adjust("5 seconds");
257+
}).pipe(Effect.provide(server(world, dispatched)), Effect.scoped);
258+
}),
259+
);
260+
261+
it.effect(
262+
"a granted slot is held until upstream's dispatch of it ends, however long it waits",
263+
() =>
264+
Effect.gen(function* () {
265+
const world = newWorld(1);
266+
const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>();
267+
const lockFree = yield* Deferred.make<void>();
268+
yield* Effect.gen(function* () {
269+
yield* offer(
270+
request(A, {
271+
// Behind its own thread's earlier dispatch (its parent's lock) for 2 minutes.
272+
dispatchIfCurrent: (effect) =>
273+
Deferred.await(lockFree).pipe(Effect.andThen(Effect.asSome(effect))),
274+
}),
275+
);
276+
yield* TestClock.adjust("2 minutes");
277+
assert.lengthOf(world.asks, 1);
278+
// Asked and granted, not ended: the start counts whatever the start grace.
279+
assert.deepStrictEqual(slotCalls(world), []);
280+
yield* Deferred.succeed(lockFree, undefined);
281+
yield* Queue.take(dispatched);
282+
yield* settle;
283+
assert.deepStrictEqual(slotCalls(world), [`started ${A} 1`, "release 1"]);
284+
}).pipe(Effect.provide(server(world, dispatched)), Effect.scoped);
285+
}),
286+
);
287+
288+
it.effect("a granted request upstream drops (its thread archived meanwhile) frees its slot", () =>
289+
Effect.gen(function* () {
290+
const world = newWorld(1);
291+
const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>();
292+
const cleared: Array<ThreadId> = [];
293+
yield* Effect.gen(function* () {
294+
// Granted on a live shell; upstream then reads the thread archived and clears the latch.
295+
world.archivedForUpstream.add(A);
296+
yield* offer(request(A, { clearIfCurrent: () => Effect.sync(() => cleared.push(A)) }));
297+
yield* settle;
298+
assert.deepStrictEqual(cleared, [A]);
299+
assert.strictEqual(yield* Queue.size(dispatched), 0);
300+
assert.deepStrictEqual(slotCalls(world), [`started ${A} 1`, "release 1"]);
301+
}).pipe(Effect.provide(server(world, dispatched)), Effect.scoped);
302+
}),
303+
);
304+
217305
it.effect("a thread that cannot be read waits, then is sent once", () =>
218306
Effect.gen(function* () {
219307
const world = newWorld(5);
@@ -241,7 +329,7 @@ describe("provider continuations take an agent slot", () => {
241329
const cleared: Array<ThreadId> = [];
242330
yield* Effect.gen(function* () {
243331
yield* offer(request(A, { clearIfCurrent: () => Effect.sync(() => cleared.push(A)) }));
244-
yield* TestClock.adjust("0 seconds");
332+
yield* settle;
245333
assert.deepStrictEqual(cleared, [A]);
246334
assert.deepStrictEqual(world.asks, []);
247335
assert.strictEqual(yield* Queue.size(dispatched), 0);
@@ -254,7 +342,7 @@ describe("provider continuations take an agent slot", () => {
254342
const world = newWorld(0);
255343
const inner =
256344
yield* Queue.unbounded<ProviderContinuationRequests.ProviderContinuationRequest>();
257-
const gated = ContinuationSlot.gateContinuations(
345+
const gated = yield* ContinuationSlot.gateContinuations(
258346
{
259347
offer: (value) => Queue.offer(inner, value).pipe(Effect.asVoid),
260348
take: Queue.take(inner),
@@ -291,6 +379,8 @@ describe("provider continuations take an agent slot", () => {
291379
yield* TestClock.adjust("12 seconds");
292380
}).pipe(Effect.provide(server(world, dispatched)), Effect.scoped);
293381
const asked = world.asks.length;
382+
// Its place in the line goes with it.
383+
assert.include(world.calls, "leave continuation:0");
294384
world.free = 5;
295385
yield* TestClock.adjust("1 minute");
296386
assert.strictEqual(yield* Queue.size(dispatched), 0);
@@ -308,7 +398,7 @@ describe("provider continuations take an agent slot", () => {
308398
}).pipe(Effect.provide(server(world, dispatched, null)), Effect.scoped);
309399
const inner = { offer: () => Effect.void, take: Effect.never };
310400
assert.strictEqual(
311-
ContinuationSlot.gateContinuations(
401+
yield* ContinuationSlot.gateContinuations(
312402
inner,
313403
Option.none(),
314404
() => Effect.succeed(null),
Collapse file

‎apps/server/src/fork/continuationSlot.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/fork/continuationSlot.ts
+80-44Lines changed: 80 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
/**
2-
* Fork: a provider continuation into an idle thread takes an agent slot. Asked at the queue, not
3-
* around the dispatch: an adapter's `dispatchIfCurrent` holds its own lock while it dispatches.
4-
* A refused request goes back on the queue; the adapter's latch stays set, so it offers no second.
2+
* Fork: a provider continuation into an idle thread takes an agent slot, asked off upstream's queue
3+
* (never inside `dispatchIfCurrent`, which holds the adapter's lock), each request in its own fiber
4+
* and place in the gate's line. The slot is held until upstream's dispatch of it ends.
55
*/
66
import type { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
77
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
88
import * as Duration from "effect/Duration";
99
import * as Effect from "effect/Effect";
1010
import * as Layer from "effect/Layer";
1111
import * as Option from "effect/Option";
12+
import * as Queue from "effect/Queue";
1213
import type * as Scope from "effect/Scope";
1314

1415
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
1516
import * as SlotGate from "../slots/SlotGate.ts";
16-
import { admitSend, reasonHere } from "./agentSlotRoutes.ts";
17+
import { admitSend, leaveLine, reasonHere } from "./agentSlotRoutes.ts";
1718

1819
type Request = ProviderContinuationRequests.ProviderContinuationRequest;
1920
interface Requests {
@@ -27,69 +28,104 @@ export const CONTINUATION_SLOT_RETRY = Duration.seconds(5);
2728
/** `null`: no such thread, or it is gone. */
2829
export type ContinuationThread = { readonly instanceId: ProviderInstanceId } | null;
2930

31+
/**
32+
* The request holding its slot (`end`) until upstream's dispatch of it ends, whichever way, so a
33+
* run that waits behind its thread's earlier dispatch still has it. One never dispatched frees it
34+
* at the gate's dispatch limit.
35+
*/
36+
const holdingSlot = (
37+
request: Request,
38+
end: (childThreadId: ThreadId | null) => Effect.Effect<void>,
39+
): Request => {
40+
const dispatchIfCurrent = request.dispatchIfCurrent;
41+
const clearIfCurrent = request.clearIfCurrent;
42+
const ended = end(request.threadId);
43+
return {
44+
...request,
45+
dispatchIfCurrent: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
46+
(dispatchIfCurrent === undefined ? Effect.asSome(effect) : dispatchIfCurrent(effect)).pipe(
47+
Effect.ensuring(ended),
48+
),
49+
...(clearIfCurrent === undefined
50+
? {}
51+
: { clearIfCurrent: () => clearIfCurrent().pipe(Effect.ensuring(ended)) }),
52+
};
53+
};
54+
3055
/**
3156
* `take` hands out a request into an idle thread only with a slot. Upstream's at once: a delegated
3257
* result (docs/fork/README.md) and a gone thread (upstream drops it and clears the adapter's latch).
33-
* An unreadable thread waits, as a refused one does.
58+
* An unreadable thread waits, as a refused one does. No ask ever holds up upstream's queue: each
59+
* request asks in its own fiber, so a slow count delays only that request.
3460
*/
3561
export const gateContinuations = <E>(
3662
requests: Requests,
3763
gate: Option.Option<SlotGate.SlotGate["Service"]>,
3864
threadOf: (threadId: ThreadId) => Effect.Effect<ContinuationThread, E>,
3965
scope: Scope.Scope,
40-
): Requests => {
41-
if (Option.isNone(gate)) return requests;
42-
/** Logged once until handed out. */
43-
const waiting = new Set<Request>();
66+
): Effect.Effect<Requests> => {
67+
if (Option.isNone(gate)) return Effect.succeed(requests);
68+
let places = 0;
4469

45-
/** `null` when the request may go to upstream now, else why it waits. */
46-
const waitsFor = Effect.fn("ContinuationSlot.waitsFor")(function* (request: Request) {
47-
if (request.delegatedCompletion !== undefined) return null;
70+
/** The request for upstream when it may go now (holding its slot), else why it waits. */
71+
const ask = Effect.fn("ContinuationSlot.ask")(function* (
72+
request: Request,
73+
place: SlotGate.SlotPlace,
74+
) {
4875
const thread = yield* threadOf(request.threadId).pipe(
4976
Effect.orElseSucceed(() => "unreadable" as const),
5077
);
5178
if (thread === "unreadable") return "the thread could not be read to check for a slot";
52-
if (thread === null) return null;
79+
if (thread === null) return request;
5380
const slot = yield* admitSend(gate, {
5481
callerThreadId: request.threadId,
5582
threadId: request.threadId,
5683
instanceId: thread.instanceId,
5784
keepsHeld: true,
85+
place,
86+
endsItself: true,
5887
});
59-
return slot.type === "refuse" ? reasonHere(slot.refusal) : null;
88+
return slot.type === "refuse" ? reasonHere(slot.refusal) : holdingSlot(request, slot.end);
6089
});
6190

62-
const putBack = Effect.fn("ContinuationSlot.putBack")(function* (
63-
request: Request,
64-
detail: string,
65-
) {
66-
if (!waiting.has(request)) {
67-
waiting.add(request);
68-
yield* Effect.logInfo("provider continuation waits for an agent slot", {
69-
threadId: request.threadId,
70-
providerThreadId: request.providerThreadId,
71-
detail,
72-
});
73-
}
74-
yield* Effect.sleep(CONTINUATION_SLOT_RETRY).pipe(
75-
Effect.andThen(requests.offer(request)),
76-
Effect.forkIn(scope),
77-
);
78-
});
79-
80-
const take: Effect.Effect<Request> = Effect.gen(function* () {
81-
while (true) {
82-
const request = yield* requests.take;
83-
const detail = yield* waitsFor(request);
84-
if (detail === null) {
85-
waiting.delete(request);
86-
return request;
91+
/** One request, until it may go: asked again every `CONTINUATION_SLOT_RETRY`, logged once. */
92+
const untilSlot = Effect.fn("ContinuationSlot.untilSlot")(
93+
function* (request: Request, place: SlotGate.SlotPlace, ready: Queue.Queue<Request>) {
94+
let logged = false;
95+
while (true) {
96+
const answer = yield* ask(request, place);
97+
if (typeof answer !== "string") {
98+
yield* Queue.offer(ready, answer);
99+
return;
100+
}
101+
if (!logged) {
102+
logged = true;
103+
yield* Effect.logInfo("provider continuation waits for an agent slot", {
104+
threadId: request.threadId,
105+
providerThreadId: request.providerThreadId,
106+
detail: answer,
107+
});
108+
}
109+
yield* Effect.sleep(CONTINUATION_SLOT_RETRY);
87110
}
88-
yield* putBack(request, detail);
89-
}
90-
});
111+
},
112+
// Stopped while it waits (the server stops): nothing is sent later, and its place goes.
113+
(effect, _request: Request, place: SlotGate.SlotPlace) =>
114+
Effect.ensuring(effect, leaveLine(gate, [place.key])),
115+
);
91116

92-
return { offer: requests.offer, take };
117+
return Effect.gen(function* () {
118+
const ready = yield* Queue.unbounded<Request>();
119+
// Upstream's queue is only read here, and never waits on an ask.
120+
const handOut = (request: Request): Effect.Effect<void> =>
121+
request.delegatedCompletion !== undefined
122+
? Effect.asVoid(Queue.offer(ready, request))
123+
: Effect.asVoid(
124+
Effect.forkIn(untilSlot(request, { key: `continuation:${places++}` }, ready), scope),
125+
);
126+
yield* requests.take.pipe(Effect.flatMap(handOut), Effect.forever, Effect.forkIn(scope));
127+
return { offer: requests.offer, take: Queue.take(ready) };
128+
});
93129
};
94130

95131
/** The queue the adapters offer to (memoized by reference), gated for upstream's worker only. */
@@ -99,7 +135,7 @@ export const layerOver = Layer.effect(
99135
const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
100136
const threads = yield* ThreadManagement.ThreadManagementService;
101137
const gate = yield* Effect.serviceOption(SlotGate.SlotGate);
102-
return gateContinuations(
138+
return yield* gateContinuations(
103139
requests,
104140
gate,
105141
(threadId) =>

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.