fix(orchestrator): hydrate shell cache and group multi-environment projects (#3640)

Restore versioned shell-cache hydration, reconcile repository enrichment across multiple environments, and decode non-null settled shell timestamps correctly.
This commit is contained in:
Mike Olson authored and GitHub committed 2026-07-24 16:49:21 +02:00
1 parent c6b0ceba5d
commit aee7ff39d7
17 files changed
+1558 -62

No files matched your search

@@ -1,7 +1,14 @@
import type { ApplicationStoredEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import type { ApplicationStoredEvent, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { coalesceShellApplicationEvents } from "./ShellStream.ts";
import {
coalesceShellApplicationEvents,
composeShellStreamWithEnrichment,
shellStreamItemFromEnrichmentRefresh,
shellStreamItemsFromInitialSnapshot,
} from "./ShellStream.ts";
function project(sequence: number, id: string): ApplicationStoredEvent {
return {
@@ -18,6 +25,14 @@ function thread(sequence: number, id: string): ApplicationStoredEvent {
} as ApplicationStoredEvent;
}
const emptyShellSnapshot = {
schemaVersion: 1,
snapshotSequence: 0,
projects: [],
threads: [],
archivedThreads: [],
} as OrchestrationV2ShellSnapshot;
describe("coalesceShellApplicationEvents", () => {
it("keeps the newest event per aggregate and preserves sequence order", () => {
expect(
@@ -31,3 +46,131 @@ describe("coalesceShellApplicationEvents", () => {
).toEqual([4, 5, 6]);
});
});
describe("shellStreamItemFromEnrichmentRefresh", () => {
it("batches nearby completion roots onto one snapshot item", () => {
expect(
shellStreamItemFromEnrichmentRefresh({
snapshot: emptyShellSnapshot,
changes: [
{ workspaceRoot: "/workspace/a" },
{ workspaceRoot: "/workspace/b" },
{ workspaceRoot: "/workspace/a" },
],
}),
).toEqual({
kind: "snapshot",
snapshot: emptyShellSnapshot,
resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/b"],
});
});
});
describe("shellStreamItemsFromInitialSnapshot", () => {
it("emits unmarked authoritative then same-sequence marked enrichment when roots resolved", () => {
const snapshot = {
...emptyShellSnapshot,
snapshotSequence: 7,
} as OrchestrationV2ShellSnapshot;
expect(
shellStreamItemsFromInitialSnapshot({
snapshot,
resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/a"],
}),
).toEqual([
{ kind: "snapshot", snapshot },
{
kind: "snapshot",
snapshot,
resolvedRepositoryIdentityRoots: ["/workspace/a"],
},
]);
});
it("emits only the unmarked authoritative snapshot when no roots resolved", () => {
expect(
shellStreamItemsFromInitialSnapshot({
snapshot: emptyShellSnapshot,
resolvedRepositoryIdentityRoots: [],
}),
).toEqual([{ kind: "snapshot", snapshot: emptyShellSnapshot }]);
});
});
describe("composeShellStreamWithEnrichment", () => {
it.effect(
"emits every initial item before enrichment even when enrichment is already ready",
() =>
Effect.gen(function* () {
const initialSnapshot = {
...emptyShellSnapshot,
snapshotSequence: 5,
} as OrchestrationV2ShellSnapshot;
const enrichmentSnapshot = {
...emptyShellSnapshot,
snapshotSequence: 10,
} as OrchestrationV2ShellSnapshot;
const initialItems = shellStreamItemsFromInitialSnapshot({
snapshot: initialSnapshot,
resolvedRepositoryIdentityRoots: ["/workspace/a"],
});
// Enrichment stream is fully ready before the composed stream is pulled.
const enrichment = Stream.make(
shellStreamItemFromEnrichmentRefresh({
snapshot: enrichmentSnapshot,
changes: [{ workspaceRoot: "/workspace/b" }],
}),
);
const tail = Stream.make(
{ kind: "synchronized" as const },
{
kind: "project.removed" as const,
sequence: 6,
projectId: "project-a",
},
);
const items = Array.from(
yield* composeShellStreamWithEnrichment({
initial: Stream.fromIterable(initialItems),
tail,
enrichment,
}).pipe(Stream.runCollect),
);
expect(items.slice(0, initialItems.length)).toEqual(initialItems);
const enrichmentIndex = items.findIndex(
(item) =>
item.kind === "snapshot" &&
"resolvedRepositoryIdentityRoots" in item &&
item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
);
expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
for (let index = 0; index < initialItems.length; index++) {
expect(items[index]).toEqual(initialItems[index]);
}
}),
);
it.effect("still interleaves enrichment with the post-prefix tail after initials drain", () =>
Effect.gen(function* () {
const items = Array.from(
yield* composeShellStreamWithEnrichment({
initial: Stream.make("initial-unmarked", "initial-marked"),
tail: Stream.make("tail-a", "tail-b"),
enrichment: Stream.make("enrichment"),
}).pipe(Stream.runCollect),
);
expect(items.slice(0, 2)).toEqual(["initial-unmarked", "initial-marked"]);
expect(items).toContain("enrichment");
expect(items).toContain("tail-a");
expect(items).toContain("tail-b");
expect(items.indexOf("enrichment")).toBeGreaterThanOrEqual(2);
}),
);
});
@@ -1,10 +1,12 @@
import type {
ApplicationStoredEvent,
OrchestrationV2ArchivedShellStreamItem,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadShellSnapshot,
OrchestrationV2ShellStreamItem,
OrchestrationV2StoredEvent,
} from "@t3tools/contracts";
import * as Stream from "effect/Stream";
/** Keep only the newest shell-relevant event per project/thread aggregate. */
export function coalesceShellApplicationEvents(
@@ -23,6 +25,58 @@ export function coalesceShellApplicationEvents(
);
}
/**
* Emit the initial shell prefix strictly first, then merge the post-prefix
* tail with enrichment refreshes. Prevents a newer marked enrichment from
* landing before the unmarked authoritative initial snapshot.
*/
export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
readonly initial: Stream.Stream<A, E, R>;
readonly tail: Stream.Stream<A2, E2, R2>;
readonly enrichment: Stream.Stream<A3, E3, R3>;
}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
}
/** Build a shell snapshot stream item for a batched enrichment completion. */
export function shellStreamItemFromEnrichmentRefresh(input: {
readonly snapshot: OrchestrationV2ShellSnapshot;
readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
return {
kind: "snapshot",
snapshot: input.snapshot,
resolvedRepositoryIdentityRoots: [
...new Set(input.changes.map((change) => change.workspaceRoot)),
],
};
}
/**
* Initial subscribe frames: always emit the unmarked authoritative snapshot,
* then a same-sequence enrichment frame only when some roots already resolved.
*/
export function shellStreamItemsFromInitialSnapshot(input: {
readonly snapshot: OrchestrationV2ShellSnapshot;
readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
const authoritative = {
kind: "snapshot" as const,
snapshot: input.snapshot,
};
if (input.resolvedRepositoryIdentityRoots.length === 0) {
return [authoritative];
}
return [
authoritative,
{
kind: "snapshot" as const,
snapshot: input.snapshot,
resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
},
];
}
/** Converts a committed event and its resulting shell snapshot into one delta. */
export function shellStreamItemFromSnapshot(input: {
readonly stored: OrchestrationV2StoredEvent;
+4
View File
@@ -48,6 +48,10 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.forEach(
projects,
(project) =>
// Use immediately available enrichment only. Awaiting git-backed
// identity resolution can exceed the client shell-snapshot budget
// (ProcessRunner allows probes up to one minute). Background workers
// plus the WS enrichment subscription fill in repositoryIdentity.
projectEnrichment.getAvailable(project.workspaceRoot).pipe(
Effect.map((enrichment) => ({
...project,
@@ -104,9 +104,19 @@ const SharedApplicationDataPlaneTestLayer = Layer.merge(
).pipe(
Layer.provide(
Layer.succeed(ProjectEnrichmentService, {
peek: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
peek: () =>
Effect.succeed({
repositoryIdentity: null,
faviconPath: null,
repositoryIdentityResolved: false,
}),
request: () => Effect.void,
getAvailable: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
getAvailable: () =>
Effect.succeed({
repositoryIdentity: null,
faviconPath: null,
repositoryIdentityResolved: false,
}),
invalidate: () => Effect.void,
subscribeChanges: Effect.never,
}),
@@ -168,6 +168,110 @@ it.effect("keeps repository workers available when every favicon worker is hung"
}),
);
it.effect("getAvailable returns immediately while repository identity is still unresolved", () =>
Effect.gen(function* () {
const repositoryStarted = yield* Deferred.make<void>();
const releaseRepository = yield* Deferred.make<void>();
const metadataLayer = Layer.merge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (workspaceRoot) =>
Deferred.succeed(repositoryStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseRepository)),
Effect.as(identity(workspaceRoot)),
),
}),
Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`),
}),
);
yield* Effect.gen(function* () {
const service = yield* ProjectEnrichment.ProjectEnrichmentService;
// Non-blocking path must not wait on hung git/identity resolution.
const immediate = yield* service.getAvailable("/pending-identity");
assert.isNull(immediate.repositoryIdentity);
assert.isNull(immediate.faviconPath);
assert.isFalse(immediate.repositoryIdentityResolved);
yield* Deferred.await(repositoryStarted);
// Background lane still resolves after the snapshot path has returned.
yield* Deferred.succeed(releaseRepository, undefined);
const resolved = yield* waitForAvailable(
service,
"/pending-identity",
(value) => value.repositoryIdentity !== null,
);
assert.equal(resolved.repositoryIdentity?.canonicalKey, "example.test/v1/pending-identity");
assert.isTrue(resolved.repositoryIdentityResolved);
}).pipe(Effect.provide(makeLayer(metadataLayer)));
}),
);
it.effect(
"reports successful cached null as resolved while cold and failed lookups stay unresolved",
() =>
Effect.gen(function* () {
const repositoryStarted = yield* Deferred.make<void>();
const releaseRepository = yield* Deferred.make<void>();
const metadataLayer = Layer.merge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (workspaceRoot) => {
if (workspaceRoot === "/no-remote") {
return Effect.succeed(null);
}
if (workspaceRoot === "/fails") {
return Effect.die("repository resolver failed");
}
return Deferred.succeed(repositoryStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseRepository)),
Effect.as(identity(workspaceRoot)),
);
},
}),
Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
resolvePath: () => Effect.succeed(null),
}),
);
yield* Effect.gen(function* () {
const service = yield* ProjectEnrichment.ProjectEnrichmentService;
const changes = yield* service.subscribeChanges;
const cold = yield* service.peek("/never-requested");
assert.isNull(cold.repositoryIdentity);
assert.isFalse(cold.repositoryIdentityResolved);
const inFlight = yield* service.getAvailable("/in-flight");
assert.isNull(inFlight.repositoryIdentity);
assert.isFalse(inFlight.repositoryIdentityResolved);
yield* Deferred.await(repositoryStarted);
assert.isFalse((yield* service.peek("/in-flight")).repositoryIdentityResolved);
yield* service.request("/no-remote");
const nullChange = yield* PubSub.take(changes);
assert.equal(nullChange.workspaceRoot, "/no-remote");
assert.isTrue(nullChange.repositoryIdentityResolved);
assert.isNull(nullChange.enrichment.repositoryIdentity);
assert.isTrue(nullChange.enrichment.repositoryIdentityResolved);
// Warm success null stays resolved and does not republish.
const warmNull = yield* service.getAvailable("/no-remote");
assert.isNull(warmNull.repositoryIdentity);
assert.isTrue(warmNull.repositoryIdentityResolved);
yield* service.request("/fails");
const failChange = yield* PubSub.take(changes);
assert.equal(failChange.workspaceRoot, "/fails");
assert.isFalse(failChange.repositoryIdentityResolved);
const failed = yield* service.peek("/fails");
assert.isNull(failed.repositoryIdentity);
assert.isFalse(failed.repositoryIdentityResolved);
}).pipe(Effect.provide(makeLayer(metadataLayer)));
}),
);
it.effect("deduplicates requests, bounds pending work, and reloads invalidated roots", () =>
Effect.gen(function* () {
const firstStarted = yield* Deferred.make<void>();
@@ -24,6 +24,8 @@ const DEFAULT_FAILURE_TTL = Duration.seconds(5);
export interface ProjectEnrichment {
readonly repositoryIdentity: RepositoryIdentity | null;
readonly faviconPath: string | null;
/** True when identity resolution completed successfully, including cached null. */
readonly repositoryIdentityResolved: boolean;
}
export interface ProjectEnrichmentChange {
@@ -73,6 +75,13 @@ function availableValue<A, E>(cached: Option.Option<Exit.Exit<A, E>>): A | null
});
}
function isSuccessfullyResolved<A, E>(cached: Option.Option<Exit.Exit<A, E>>): boolean {
return Option.match(cached, {
onNone: () => false,
onSome: (exit) => Exit.isSuccess(exit),
});
}
interface EnrichmentWorkLane {
readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
readonly queue: Queue.Queue<string>;
@@ -159,12 +168,14 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
yield* PubSub.publish(changes, {
workspaceRoot,
repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),
repositoryIdentityResolved,
enrichment: {
repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
faviconPath: availableValue(faviconPath),
repositoryIdentityResolved,
},
});
},
@@ -227,6 +238,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
return {
repositoryIdentity: availableValue(repositoryIdentity),
faviconPath: availableValue(faviconPath),
repositoryIdentityResolved: isSuccessfullyResolved(repositoryIdentity),
};
});
+85 -23
View File
@@ -77,7 +77,10 @@ import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
import {
archivedShellStreamItemFromSnapshot,
coalesceShellApplicationEvents,
composeShellStreamWithEnrichment,
shellStreamItemFromEnrichmentRefresh,
shellStreamItemFromSnapshot,
shellStreamItemsFromInitialSnapshot,
} from "./orchestration-v2/ShellStream.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEventStore from "./persistence/Services/OrchestrationEventStore.ts";
@@ -449,13 +452,28 @@ const makeWsRpcLayer = (
Effect.forEach(
projects,
(project) =>
// Non-blocking: emit with cached identity (or null) and schedule
// background resolution. subscribeChanges is attached before
// loadSnapshot, so later identity completions push refreshed
// shells for multi-env grouping without blocking the initial
// snapshot or completion marker on slow git probes.
projectEnrichment.getAvailable(project.workspaceRoot).pipe(
Effect.map((enrichment) => ({
...project,
repositoryIdentity: enrichment.repositoryIdentity,
project: {
...project,
repositoryIdentity: enrichment.repositoryIdentity,
},
repositoryIdentityResolved: enrichment.repositoryIdentityResolved,
})),
),
{ concurrency: 16 },
).pipe(
Effect.map((enriched) => ({
projects: enriched.map((entry) => entry.project),
resolvedRepositoryIdentityRoots: enriched
.filter((entry) => entry.repositoryIdentityResolved)
.map((entry) => entry.project.workspaceRoot),
})),
),
);
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
@@ -740,8 +758,11 @@ const makeWsRpcLayer = (
} as const;
}),
);
const projects = yield* enrichProjectShells(base.projects);
return { ...base, projects };
const enriched = yield* enrichProjectShells(base.projects);
return {
snapshot: { ...base, projects: enriched.projects } as OrchestrationV2ShellSnapshot,
resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots,
};
});
const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* (
stored: Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
@@ -805,37 +826,74 @@ const makeWsRpcLayer = (
const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe(
Stream.filter((change) => change.repositoryIdentityResolved),
Stream.debounce("25 millis"),
Stream.mapEffect(() => loadSnapshot()),
Stream.map((snapshot) => ({ kind: "snapshot" as const, snapshot })),
Stream.groupedWithin(64, Duration.millis(25)),
Stream.mapEffect((changes) =>
loadSnapshot().pipe(
Effect.map(({ snapshot }) =>
shellStreamItemFromEnrichmentRefresh({
snapshot,
changes: Array.from(changes),
}),
),
),
),
);
// Always attach the enrichment subscription before the first load so
// completions that race HTTP snapshot fetch still push a refresh.
// When the client already holds a shell snapshot (cached, or loaded
// over HTTP) it passes that snapshot's sequence, and we resume by
// replaying application events after it instead of re-sending the
// whole projects/threads list over the socket. The event store
// subscribes to live events before reading the persisted tail, so no
// event published during the replay window is lost; overlapping events
// are deduped by sequence on the client.
// over HTTP) it passes that snapshot's sequence. We still emit one
// enriched snapshot up front: getAvailable may have been cold on the
// HTTP path (null identity), and enrichment PubSub events published
// before this subscribe attached are dropped. Rehydrating here fills
// repositoryIdentity for cross-environment project grouping even on
// afterSequence resumes. Application events after the sequence still
// stream as deltas; overlapping events are deduped by sequence on the
// client.
//
// After the unmarked authoritative frame, emit a same-sequence
// metadata-only frame for roots that already resolved successfully
// (including cached null). Cold/failed roots stay unmarked and use
// the PubSub enrichment path when they complete later.
const completionMarker =
input.requestCompletionMarker === true
? Stream.make({ kind: "synchronized" as const })
: Stream.empty;
const snapshotThenLive = (snapshot: OrchestrationV2ShellSnapshot) =>
Stream.concat(
Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), completionMarker),
liveFrom(snapshot.snapshotSequence),
const initialSnapshotItems = (loaded: {
readonly snapshot: OrchestrationV2ShellSnapshot;
readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
}) =>
Stream.fromIterable(
shellStreamItemsFromInitialSnapshot({
snapshot: loaded.snapshot,
resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots,
}),
);
// Initial unmarked (+ optional same-load marked) always drains first.
// Enrichment merges only with the post-prefix tail so a ready marked
// refresh cannot interleave before the authoritative initial frame.
const completionThenLive = (afterSequence: number) =>
Stream.concat(completionMarker, liveFrom(afterSequence));
const base = yield* Effect.gen(function* () {
const stream = yield* Effect.gen(function* () {
const loaded = yield* loadSnapshot();
const initial = initialSnapshotItems(loaded);
if (input.afterSequence === undefined) {
return snapshotThenLive(yield* loadSnapshot());
return composeShellStreamWithEnrichment({
initial,
tail: completionThenLive(loaded.snapshot.snapshotSequence),
enrichment: enrichmentRefreshes,
});
}
const highWater = yield* applicationEvents.latestApplicationSequence;
const replayGap = highWater - input.afterSequence;
if (replayGap < 0 || replayGap > 1_000) {
return snapshotThenLive(yield* loadSnapshot());
return composeShellStreamWithEnrichment({
initial,
tail: completionThenLive(loaded.snapshot.snapshotSequence),
enrichment: enrichmentRefreshes,
});
}
const replay = toShellStream(
@@ -844,7 +902,11 @@ const makeWsRpcLayer = (
throughSequence: highWater,
}),
);
return Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater));
return composeShellStreamWithEnrichment({
initial,
tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)),
enrichment: enrichmentRefreshes,
});
}).pipe(
Effect.mapError(
(cause) =>
@@ -855,7 +917,7 @@ const makeWsRpcLayer = (
),
);
return Stream.merge(base, enrichmentRefreshes).pipe(
return stream.pipe(
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
@@ -883,7 +945,7 @@ const makeWsRpcLayer = (
.pipe(
Effect.flatMap((snapshot) =>
enrichProjectShells(snapshot.projects).pipe(
Effect.map((projects) => ({ ...snapshot, projects })),
Effect.map(({ projects }) => ({ ...snapshot, projects })),
),
),
Effect.mapError(