Skip to content

Commit 2b4a806

Browse files
fix(server): skip native sessions during bulk import (pingdotgg#15634)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 034b506 commit 2b4a806

3 files changed

Lines changed: 408 additions & 137 deletions

File tree

‎apps/server/src/orchestration-v2/EventSink.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,20 @@ export type EventSinkV2Error = typeof EventSinkV2Error.Type;
6767

6868
export interface EventSinkV2Shape {
6969
readonly write: (input: {
70+
/** Return no events if another thread owns this native session at commit time. */
71+
readonly unlessNativeThreadOwned?: Pick<
72+
OrchestrationV2ProviderThread,
73+
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
74+
>;
7075
readonly guardPendingUserInputCancellations?: boolean;
7176
readonly commandId?: CommandId;
7277
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
7378
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
7479
readonly writeWithEffects: (input: {
80+
readonly unlessNativeThreadOwned?: Pick<
81+
OrchestrationV2ProviderThread,
82+
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
83+
>;
7584
readonly guardPendingUserInputCancellations?: boolean;
7685
readonly commandId?: CommandId;
7786
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
@@ -369,6 +378,20 @@ const layerBase: Layer.Layer<
369378

370379
return yield* commitThenPublish(
371380
Effect.gen(function* () {
381+
// Check ownership in the same transaction that claims the native session.
382+
const imported = input.unlessNativeThreadOwned;
383+
if (imported?.nativeThreadRef != null) {
384+
const owners = yield* sql`
385+
SELECT provider_thread_id
386+
FROM orchestration_v2_projection_provider_threads
387+
WHERE driver = ${imported.driver}
388+
AND provider_instance_id = ${imported.providerInstanceId}
389+
AND thread_id IS NOT ${imported.appThreadId}
390+
AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
391+
LIMIT 1
392+
`;
393+
if (owners.length > 0) return [];
394+
}
372395
const normalized = yield* normalizeEvents(
373396
input.guardPendingUserInputCancellations === true
374397
? yield* guardUserInputCancellations(input.events)

0 commit comments

Comments
 (0)