GeezerVison is showing github.com — fix(core): append V1 messages written after the migration completed by Veld101 · Pull Request #57080 · anomalyco/opencode
fix(core): append V1 messages written after the migration completed
#57080
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(2)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -537,7 +537,10 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
const db = (yield* Database.Service).db
const global = yield* Global.Service
const state = yield* readState(db)
if (state?.phase === "completed") return { status: "completed" as const }
if (state?.phase === "completed") {
yield* appendLateMessages(db)
return { status: "completed" as const }
}
if (!(yield* hasLegacySessions(db))) return { status: "completed" as const }
const now = Date.now()
yield* db.run(sql`
Expand Down
Expand Up
@@ -666,6 +669,9 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
set: { seq: transformed.watermark, owner_id: null },
})
.run()
// Record how far this session's legacy messages reached, so a later start can tell a message
// written afterwards from one V2 removed through a committed revert.
yield* writeImportedThrough(tx, next.id, latest(sourceMessages))
}),
)
.pipe(Effect.orDie)
Expand Down
Expand Up
@@ -699,6 +705,155 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
)
}
/**
* A pre-upgrade V1 client can keep appending to a session this process already imported. Completion was a
* permanent latch, so those messages never reached `session_message` and export silently truncated the
* session (#57000). Each imported session records how far its legacy messages reached, so only messages
* written later are added: a message V2 removed through a committed revert stays removed.
*/
function appendLateMessages(db: Database.Interface["db"]) {
return Effect.gen(function* () {
if (!(yield* hasLegacyTable(db, "message"))) return
const sessions = yield* db.all<{ id: string }>(sql`
SELECT DISTINCT m.session_id AS id
FROM message m
JOIN session_v2 projected_session ON projected_session.id = m.session_id
WHERE NOT EXISTS (SELECT 1 FROM session_message projected WHERE projected.id = m.id)
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
A legacy message with no session_message row isn't always a late V1 write. V2 deletes rows on purpose: RevertEvent.Committed in session/projector.ts removes every row from the revert point on. With this check, a V1 message that was imported and then reverted in V2 is re-appended at the end of the session on a later startup. I reproduced this by deleting an imported row the way a revert does, adding one new legacy message and running again: the reverted message came back at seq 1.
The append should be limited to legacy messages written after this session was imported, for example newer than a per-session high-water mark (legacy time_created or ID) recorded at import. "Not projected" alone doesn't tell you that.
Related: legacy messages that never decode (#53971 ) also match this check on every startup, so their sessions are read and transformed again each time.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
`)
yield* Effect.forEach(sessions, (session) => appendLateSession(db, session.id), { discard: true })
})
}
function appendLateSession(db: Database.Interface["db"], sessionID: string) {
return Effect.gen(function* () {
const session = yield* db
.select()
.from(SessionTable)
.where(eq(SessionTable.id, SessionSchema.ID.make(sessionID)))
.get()
// A session that is not projected yet belongs to the initial pass, which imports it in full.
if (!session) return
const sourceMessages = yield* db.all<SourceMessage>(
sql`SELECT id, session_id, time_created, time_updated, data FROM message WHERE session_id = ${sessionID}`,
)
const through = yield* readImportedThrough(db, sessionID)
// A database migrated before this watermark existed cannot tell a late message from one reverted in V2,
// so adopt what is already there and add nothing; messages written from now on are still picked up.
if (through === undefined) {
yield* writeImportedThrough(db, sessionID, latest(sourceMessages))
return
}
const projected = yield* db.all<{ id: string; seq: number }>(
sql`SELECT id, seq FROM session_message WHERE session_id = ${sessionID} ORDER BY seq`,
)
const known = new Set(projected.map((row) => row.id))
const lateSources = sourceMessages.filter((row) => row.time_created > through && !known.has(row.id))
if (lateSources.length === 0) return
const late = new Set(lateSources.map((row) => row.id))
const sourceParts = yield* db.all<SourcePart>(
sql`SELECT id, message_id, session_id, time_created, time_updated, data FROM part WHERE session_id = ${sessionID}`,
)
const transformed = transformSession({ session, messages: sourceMessages, parts: sourceParts })
// The legacy tool notice is synthesized rather than a V1 message, and already sits where the import put it.
const messages = transformed.messages.filter((message) => late.has(message.id))
const lateIDs = new Set(messages.map((message) => message.id))
yield* Effect.forEach(
transformed.warnings.filter((warning) => warning.messageID !== undefined && lateIDs.has(warning.messageID)),
(warning) => Effect.logWarning("Skipped V1 migration row", warning),
)
// Totals are added as the late messages' own amounts. Writing `transformed.session` would replace the
// live row's cost and tokens with V1-only sums and clear `revert` and `time_compacting` (#57000 review).
const added = transformSession({
session,
messages: lateSources,
parts: sourceParts.filter((row) => late.has(row.message_id)),
}).session
const first = (projected.at(-1)?.seq ?? -1) + 1
const sequence = yield* db.get<{ seq: number }>(
sql`SELECT seq FROM event_sequence WHERE aggregate_id = ${sessionID}`,
)
// Appending must never rewind the aggregate sequence: V2 may already be past the migrated watermark.
const watermark = Math.max(sequence?.seq ?? -1, first + messages.length - 1)
// Every message past the watermark counts as handled, including ones the transform drops, so a row that
// can never be projected is not reconsidered on every start.
const reached = latest(lateSources)
yield* db
.transaction((tx) =>
Effect.gen(function* () {
yield* Effect.forEach(messages, (message, index) =>
tx
.insert(SessionMessageTable)
.values({
id: SessionMessage.ID.make(message.id),
session_id: SessionSchema.ID.make(message.session_id),
type: message.type,
seq: first + index,
time_created: message.time_created,
time_updated: message.time_updated,
data: sql`${JSON.stringify(message.data)}`,
})
.run(),
)
yield* tx
.update(SessionTable)
.set({
cost: sql`${SessionTable.cost} + ${added.cost}`,
tokens_input: sql`${SessionTable.tokens_input} + ${added.tokens_input}`,
tokens_output: sql`${SessionTable.tokens_output} + ${added.tokens_output}`,
tokens_reasoning: sql`${SessionTable.tokens_reasoning} + ${added.tokens_reasoning}`,
tokens_cache_read: sql`${SessionTable.tokens_cache_read} + ${added.tokens_cache_read}`,
tokens_cache_write: sql`${SessionTable.tokens_cache_write} + ${added.tokens_cache_write}`,
})
.where(eq(SessionTable.id, session.id))
.run()
yield* tx
.insert(EventSequenceTable)
.values({ aggregate_id: session.id, seq: watermark })
.onConflictDoUpdate({ target: EventSequenceTable.aggregate_id, set: { seq: watermark } })
.run()
yield* writeImportedThrough(tx, sessionID, reached)
}),
)
.pipe(Effect.orDie)
})
}
type ThroughWriter = Pick<Database.Interface["db"], "insert">
/** The newest legacy `time_created` a session has already imported, absent before watermarks existed. */
function readImportedThrough(db: Database.Interface["db"], sessionID: string) {
return db
.select({ value: KVTable.value })
.from(KVTable)
.where(eq(KVTable.key, importedThroughKey(sessionID)))
.get()
.pipe(
Effect.map((row) => {
const value = row?.value
if (!value || typeof value !== "object" || !("through" in value)) return undefined
return typeof value.through === "number" ? value.through : undefined
}),
Effect.orDie,
)
}
function writeImportedThrough(db: ThroughWriter, sessionID: string, through: number) {
return db
.insert(KVTable)
.values({ key: importedThroughKey(sessionID), value: { through } })
.onConflictDoUpdate({ target: KVTable.key, set: { value: { through }, time_updated: Date.now() } })
.run()
.pipe(Effect.orDie)
}
function importedThroughKey(sessionID: string) {
return `migration.v1-v2:through:${sessionID}`
}
function latest(messages: ReadonlyArray<SourceMessage>) {
return messages.reduce((newest, message) => Math.max(newest, message.time_created), 0)
}
function nextPath(options: Options, data: string) {
if (options.nextDatabasePath) return options.nextDatabasePath
if (process.env.OPENCODE_DB === ":memory:") return undefined
Expand Down
Expand Up
@@ -1127,9 +1282,13 @@ function parseState(input: unknown): MigrationState | undefined {
if (typeof input.cursor === "string") return { phase: "sessions", cursor: input.cursor }
}
function hasLegacySessions (db: Database.Interface["db"]) {
return db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session' `).pipe(
function hasLegacyTable (db: Database.Interface["db"], table: "session" | "message" ) {
return db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${table} `).pipe(
Effect.map((row) => row !== undefined),
Effect.orDie,
)
}
function hasLegacySessions(db: Database.Interface["db"]) {
return hasLegacyTable(db, "session")
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -1370,6 +1370,177 @@ describe("V1Migration database workflow", () => {
)
})
// A pre-upgrade V1 client can keep appending to a session V2 has already imported. The completion
// latch meant those messages never reached session_message, so export silently truncated the session.
test("appends legacy messages written after the import completed", async () => {
await database(
Effect.gen(function* () {
const { db } = yield* Database.Service
yield* db.run(
sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/tmp/test', 1, 2, '[]')`,
)
yield* db.run(
sql`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated) VALUES ('ses_test', 'global', 'test', '/tmp/test', 'Test', '1', 1, 2)`,
)
const insertLegacy = (message: V1Migration.SourceMessage) =>
db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${message.id}, 'ses_test', ${message.time_created}, ${message.time_updated}, ${message.data})`,
)
const first = user("msg_000000000010aaaaaaaaaaaaaa", {}, 10)
const second = user("msg_000000000020aaaaaaaaaaaaaa", {}, 20)
yield* insertLegacy(first)
yield* insertLegacy(second)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
expect(yield* db.all(sql`SELECT id, seq FROM session_message ORDER BY seq`)).toEqual([
{ id: first.id, seq: 0 },
{ id: second.id, seq: 1 },
])
// V2 keeps writing to the session after the import, and advances the aggregate sequence.
yield* db.run(
sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('msg_from_v2', 'ses_test', 'user', 2, 30, 31, '{"text":"from v2","time":{"created":30}}')`,
)
yield* db.run(sql`UPDATE event_sequence SET seq = 5 WHERE aggregate_id = 'ses_test'`)
const third = user("msg_000000000030aaaaaaaaaaaaaa", {}, 40)
const fourth = user("msg_000000000040aaaaaaaaaaaaaa", {}, 50)
yield* insertLegacy(third)
yield* insertLegacy(fourth)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
// The late messages append after what is already projected: nothing is deleted or renumbered.
expect(yield* db.all(sql`SELECT id, seq FROM session_message ORDER BY seq`)).toEqual([
{ id: first.id, seq: 0 },
{ id: second.id, seq: 1 },
{ id: "msg_from_v2", seq: 2 },
{ id: third.id, seq: 3 },
{ id: fourth.id, seq: 4 },
])
// Appending must not rewind the aggregate sequence, which would corrupt the event log.
expect(yield* db.get(sql`SELECT seq FROM event_sequence WHERE aggregate_id = 'ses_test'`)).toEqual({ seq: 5 })
// A third run finds nothing to append and leaves the projection alone.
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
expect((yield* db.get<{ value: number }>(sql`SELECT COUNT(*) AS value FROM session_message`))?.value).toBe(5)
}),
)
})
// V2 removes rows on a committed revert, so "absent from session_message" alone cannot mean "never
// imported". The per-session watermark keeps a reverted message from coming back.
test("does not re-append a legacy message a V2 revert removed", async () => {
await database(
Effect.gen(function* () {
const { db } = yield* Database.Service
yield* db.run(
sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/tmp/test', 1, 2, '[]')`,
)
yield* db.run(
sql`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated) VALUES ('ses_test', 'global', 'test', '/tmp/test', 'Test', '1', 1, 2)`,
)
const first = user("msg_000000000010aaaaaaaaaaaaaa", {}, 10)
const second = user("msg_000000000020aaaaaaaaaaaaaa", {}, 20)
for (const message of [first, second])
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${message.id}, 'ses_test', ${message.time_created}, ${message.time_updated}, ${message.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
// RevertEvent.Committed deletes the projection from the boundary on and clears the session's revert.
yield* db.run(sql`DELETE FROM session_message WHERE id = ${second.id}`)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
expect((yield* db.all<{ id: string }>(sql`SELECT id FROM session_message`)).map((row) => row.id)).toEqual([first.id])
}),
)
})
// `transformed.session` is a V1-only recomputation, so writing it over the live row would replace V2's
// totals and clear revert and time_compacting. Only the appended messages' own amounts may be added.
test("adds appended totals to V2 session state instead of replacing it", async () => {
await database(
Effect.gen(function* () {
const { db } = yield* Database.Service
yield* db.run(
sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/tmp/test', 1, 2, '[]')`,
)
yield* db.run(
sql`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated) VALUES ('ses_test', 'global', 'test', '/tmp/test', 'Test', '1', 1, 2)`,
)
const first = user("msg_000000000010aaaaaaaaaaaaaa", {}, 10)
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${first.id}, 'ses_test', ${first.time_created}, ${first.time_updated}, ${first.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
// V2 continues the session: it owns the totals and carries live revert and compaction state.
yield* db.run(
sql`UPDATE session_v2 SET cost = 42, tokens_input = 7, tokens_output = 8, agent = 'v2-agent', revert = '{"messageID":"' || ${first.id} || '"}', time_compacting = 99 WHERE id = 'ses_test'`,
)
const prompt = user("msg_000000000030aaaaaaaaaaaaaa", {}, 30)
const reply = assistant("msg_000000000040aaaaaaaaaaaaaa", prompt.id, {}, 40)
for (const message of [prompt, reply])
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${message.id}, 'ses_test', ${message.time_created}, ${message.time_updated}, ${message.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
const row = yield* db.get(
sql`SELECT cost, tokens_input, tokens_output, agent, revert, time_compacting FROM session_v2 WHERE id = 'ses_test'`,
)
expect(row).toEqual({
cost: 43,
tokens_input: 9,
tokens_output: 11,
agent: "v2-agent",
revert: `{"messageID":"${first.id}"}`,
time_compacting: 99,
})
}),
)
})
// Databases migrated before watermarks existed cannot tell a late message from a reverted one, so the
// first run adopts what is there without appending, and later messages are then picked up normally.
test("adopts a completed database that has no watermark", async () => {
await database(
Effect.gen(function* () {
const { db } = yield* Database.Service
yield* db.run(
sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/tmp/test', 1, 2, '[]')`,
)
yield* db.run(
sql`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated) VALUES ('ses_test', 'global', 'test', '/tmp/test', 'Test', '1', 1, 2)`,
)
const first = user("msg_000000000010aaaaaaaaaaaaaa", {}, 10)
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${first.id}, 'ses_test', ${first.time_created}, ${first.time_updated}, ${first.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
yield* db.run(sql`DELETE FROM kv WHERE key = 'migration.v1-v2:through:ses_test'`)
const second = user("msg_000000000020aaaaaaaaaaaaaa", {}, 20)
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${second.id}, 'ses_test', ${second.time_created}, ${second.time_updated}, ${second.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
expect((yield* db.all<{ id: string }>(sql`SELECT id FROM session_message`)).map((row) => row.id)).toEqual([first.id])
const third = user("msg_000000000030aaaaaaaaaaaaaa", {}, 30)
yield* db.run(
sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (${third.id}, 'ses_test', ${third.time_created}, ${third.time_updated}, ${third.data})`,
)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
expect((yield* db.all<{ id: string }>(sql`SELECT id FROM session_message ORDER BY seq`)).map((row) => row.id)).toEqual([
first.id,
third.id,
])
}),
)
})
test("serializes concurrent callers and migrates each session once", async () => {
await database(
Effect.gen(function* () {
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.