Skip to content

Commit fb0b06f

Browse files
committed
fix(core): map imported message-ID collisions to a 409 conflict
Importing a session whose message IDs already exist (e.g. re-importing an export under a new session ID) hit the session_message UNIQUE constraint and died as a 500 with an empty body. Pre-check the settled message IDs (batched at 500, same as stats.ts) before any write and fail with the existing SessionTransfer.ImportConflictError, which the HTTP handler already maps to 409. Fixes anomalyco#54336
1 parent c93aaae commit fb0b06f

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

‎packages/core/src/session/transfer.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ export * as SessionTransfer from "./transfer.js"
33
import { SessionTransfer } from "@opencode/schema/session-transfer"
44
import { Tool } from "@opencode/schema/tool"
55
import { Skill } from "@opencode/schema/skill"
6-
import { eq } from "drizzle-orm"
6+
import { eq, inArray } from "drizzle-orm"
77
import { Clock, Context, DateTime, Effect, Layer, Schema } from "effect"
88
import { map } from "effect/Array"
99
import path from "path"
@@ -70,11 +70,21 @@ const layer = Layer.effect(
7070
.get()
7171
.pipe(Effect.orDie)
7272
if (recorded) return yield* new ImportConflictError({ sessionID })
73+
const settled = input.data.messages.filter(isSettled)
74+
for (const batch of batches(settled.map((message) => message.id))) {
75+
const taken = yield* db
76+
.select({ id: SessionMessageTable.id })
77+
.from(SessionMessageTable)
78+
.where(inArray(SessionMessageTable.id, batch))
79+
.get()
80+
.pipe(Effect.orDie)
81+
if (taken) return yield* new ImportConflictError({ sessionID })
82+
}
7383
if (input.data.info.parentID) yield* sessions.get(input.data.info.parentID)
7484
const project = yield* projects.resolve(input.location.directory)
7585
yield* upsertProject(db, project).pipe(Effect.orDie)
7686
const importedAt = yield* Clock.currentTimeMillis
77-
const messages = input.data.messages.filter(isSettled).map((message, index) => {
87+
const messages = settled.map((message, index) => {
7888
const encoded = encodeMessage(message)
7989
const { id: _, type, ...data } = encoded
8090
return {
@@ -168,6 +178,10 @@ function isSettled(message: SessionMessage.Info) {
168178
return true
169179
}
170180

181+
function batches<T>(items: T[]) {
182+
return Array.from({ length: Math.ceil(items.length / 500) }, (_, index) => items.slice(index * 500, (index + 1) * 500))
183+
}
184+
171185
function redact(kind: string, id: string, value: string) {
172186
return value.trim() ? `[redacted:${kind}:${id}]` : value
173187
}

‎packages/server/test/session-import.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ it.live("preserves imported parentID through HTTP import, read, and parent filte
5050
}).toEqual({ imported: parent.data.id, read: parent.data.id, children: [id] })
5151
}).pipe(Effect.scoped),
5252
)
53+
).pipe(Effect.scoped),
54+
)
5355

5456
it.live("upgrades native data in transcripts exported before v2.1", () =>
5557
Effect.gen(function* () {
@@ -130,6 +132,30 @@ it.live("rejects an invalid imported message without creating the session", () =
130132
expect(yield* request(`/api/session/${id}`, undefined, 404)).toMatchObject({ _tag: "SessionNotFoundError" })
131133
}).pipe(Effect.scoped),
132134
)
135+
136+
it.live("maps imported message-ID collisions to 409 without creating the session", () =>
137+
Effect.gen(function* () {
138+
const request = yield* setup
139+
const template = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", {}))
140+
const messages = [{ id: "msg_clash", type: "user", text: "Hello", time: { created: 1 } }]
141+
const first = Session.ID.create()
142+
yield* request("/api/experimental/session/import", {
143+
info: { ...template.data, id: first, title: "Original" },
144+
messages,
145+
})
146+
const second = Session.ID.create()
147+
const error = yield* request(
148+
"/api/experimental/session/import",
149+
{ info: { ...template.data, id: second, title: "Copy" }, messages },
150+
409,
151+
)
152+
expect(error).toMatchObject({ _tag: "ConflictError", resource: second })
153+
expect(yield* request(`/api/session/${second}`, undefined, 404)).toMatchObject({
154+
_tag: "SessionNotFoundError",
155+
sessionID: second,
156+
})
157+
}).pipe(Effect.scoped),
158+
)
133159
;["missing", "self"].forEach((parent) => {
134160
it.live(`rejects a ${parent} parent without creating the imported session`, () =>
135161
Effect.gen(function* () {

0 commit comments

Comments
 (0)