Skip to content

Commit e04f624

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 ffe6fed commit e04f624

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"
@@ -73,14 +73,24 @@ const layer = Layer.effect(
7373
.get()
7474
.pipe(Effect.orDie)
7575
if (recorded) return yield* new ImportConflictError({ sessionID })
76+
const settled = input.data.messages.filter(isSettled)
77+
for (const batch of batches(settled.map((message) => message.id))) {
78+
const taken = yield* db
79+
.select({ id: SessionMessageTable.id })
80+
.from(SessionMessageTable)
81+
.where(inArray(SessionMessageTable.id, batch))
82+
.get()
83+
.pipe(Effect.orDie)
84+
if (taken) return yield* new ImportConflictError({ sessionID })
85+
}
7686
if (input.data.info.parentID) yield* sessions.get(input.data.info.parentID)
7787
const project = yield* projects.resolve(input.location.directory)
7888
yield* upsertProject(db, project).pipe(Effect.orDie)
7989
const importedAt = yield* Clock.currentTimeMillis
8090
const subpath = RelativePath.make(
8191
path.relative(project.directory, input.location.directory).replaceAll("\\", "/"),
8292
)
83-
const messages = input.data.messages.filter(isSettled).map((message, index) => {
93+
const messages = settled.map((message, index) => {
8494
const encoded = encodeMessage(message)
8595
const { id: _, type, ...data } = encoded
8696
return {
@@ -205,6 +215,10 @@ function isSettled(message: SessionMessage.Info) {
205215
return true
206216
}
207217

218+
function batches<T>(items: T[]) {
219+
return Array.from({ length: Math.ceil(items.length / 500) }, (_, index) => items.slice(index * 500, (index + 1) * 500))
220+
}
221+
208222
function redact(kind: string, id: string, value: string) {
209223
return value.trim() ? `[redacted:${kind}:${id}]` : value
210224
}

‎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)