Skip to content

Commit 07889a1

Browse files
committed
fix(session): compare message order by time, not id strings, across the identifier wrap
The identifier encode is a 48-bit window of (timestamp_ms << 12 | counter) that wraps every ~2.18 years. Observed 2026-08-13->14: pre-wrap ids start msg_f... and post-wrap ids start msg_000..., and "f" > "0" as strings, so every code path comparing message ids as strings picks the wrong order across the wrap, deleting pre-wrap history on revert cleanup and exiting the run loop without calling the model. - message-v2: latest() orders by time.created, id tiebreak - prompt: runLoop exit compares time.created, not id - revert: range + cleanup use the boundary index on the time-ordered array - session: fork boundary by index - app: client sorts use cmpMessage (time-primary) - tests: regression for latest() across the wrap and cleanup keeping pre-wrap history
1 parent d83ffee commit 07889a1

7 files changed

Lines changed: 206 additions & 26 deletions

File tree

‎packages/app/src/context/server-session.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ type MessageApi = ServerApi["message"]
2727

2828
const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
2929
const cmpMessage = (a: Message, b: Message) => a.time.created - b.time.created || cmp(a.id, b.id)
30+
// Generic sort for message-like collections: time-primary when both sides carry
31+
// a creation time (required because Message ids wrap every ~2.18 years — the
32+
// Identifier encodes a 48-bit window of timestamp<<12 — after which string id
33+
// order no longer matches chronological order), falling back to id for types
34+
// without a time (e.g. parts).
35+
const cmpMessageOrId = <T extends { id: string }>(a: T, b: T) => {
36+
const at = (a as { time?: { created: number } }).time?.created
37+
const bt = (b as { time?: { created: number } }).time?.created
38+
return at !== undefined && bt !== undefined && at !== bt ? at - bt : cmp(a.id, b.id)
39+
}
3040
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
3141
const initialMessagePageSize = 20
3242
const historyMessagePageSize = 200
@@ -64,7 +74,7 @@ type MessagePage = {
6474
function legacyMessageSource(items: { info: Message; parts: Part[] }[]): SessionMessageInfo[] {
6575
return items
6676
.slice()
67-
.sort((a, b) => cmp(a.info.id, b.info.id))
77+
.sort((a, b) => cmpMessage(a.info, b.info))
6878
.map((item) => {
6979
if (item.info.role === "user") {
7080
return {
@@ -180,7 +190,7 @@ function reconcileFetched<T extends { id: string }>(
180190
if (!item) result.delete(id)
181191
}
182192
for (const id of options.removed ?? emptyIDs) result.delete(id)
183-
return [...result.values()].sort((a, b) => cmp(a.id, b.id))
193+
return [...result.values()].sort(cmpMessageOrId)
184194
}
185195

186196
type ServerSessionOptions = { retry?: typeof retry; protocol?: Promise<"v1" | "v2"> }
@@ -555,7 +565,7 @@ export function createServerSession(
555565
const source = pages.flatMap((page) => page.data).toReversed()
556566
const normalized = normalizeSessionMessages(sessionID, source)
557567
return {
558-
session: normalized.messages.sort((a, b) => cmp(a.id, b.id)),
568+
session: normalized.messages.sort(cmpMessage),
559569
part: [...normalized.parts.entries()]
560570
.map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) }))
561571
.sort((a, b) => cmp(a.id, b.id)),
@@ -572,7 +582,7 @@ export function createServerSession(
572582
})
573583
const items = (response.data ?? []).filter((item) => !!item?.info?.id)
574584
return {
575-
session: items.map((item) => cleanMessage(item.info)).sort((a, b) => cmp(a.id, b.id)),
585+
session: items.map((item) => cleanMessage(item.info)).sort(cmpMessage),
576586
part: items.map((item) => ({
577587
id: item.info.id,
578588
part: item.parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id)),
@@ -696,7 +706,7 @@ export function createServerSession(
696706
const normalized = normalizeSessionMessages(sessionID, source)
697707
return {
698708
...page,
699-
session: normalized.messages.sort((a, b) => cmp(a.id, b.id)),
709+
session: normalized.messages.sort(cmpMessage),
700710
part: [...normalized.parts.entries()]
701711
.map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) }))
702712
.sort((a, b) => cmp(a.id, b.id)),

‎packages/opencode/src/session/message-v2.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -642,23 +642,31 @@ export const filterCompactedEffect = Effect.fnUntraced(function* (sessionID: Ses
642642

643643
// filterCompacted reorders messages for model consumption
644644
// ([compaction-user, summary, ...retained tail..., continue-user]), so array
645-
// position is not chronological. Derive each binding by max id (MessageID
646-
// is monotonic via MessageID.ascending) so a pre-compaction overflowing tail
647-
// assistant doesn't get mistaken for the most recent turn. tasks are
645+
// position is not chronological. Derive each binding by creation time so a
646+
// pre-compaction overflowing tail assistant doesn't get mistaken for the most
647+
// recent turn. Message ids are NOT a reliable primary order here: Identifier
648+
// encodes a 48-bit window of (timestamp_ms << 12 | counter) that wraps every
649+
// ~2.18 years (observed 2026-08-13→14: pre-wrap ids start "msg_f…", post-wrap
650+
// ids start "msg_000…", and "f" > "0" as strings), so comparing ids as strings
651+
// picks the WRONG message across the wrap. Compare by time, with id as the
652+
// tiebreak — two messages created in the same millisecond are necessarily on
653+
// the same side of the wrap, so their ids remain comparable. tasks are
648654
// compaction/subtask parts attached to user messages newer than the latest
649655
// finished assistant — i.e. unprocessed work.
650656
export function latest(msgs: WithParts[]) {
657+
const isAfter = (a: { time: { created: number }; id: string }, b: { time: { created: number }; id: string }) =>
658+
a.time.created > b.time.created || (a.time.created === b.time.created && a.id > b.id)
651659
let user: User | undefined
652660
let assistant: Assistant | undefined
653661
let finished: Assistant | undefined
654662
for (const msg of msgs) {
655663
const info = msg.info
656-
if (info.role === "user" && (!user || info.id > user.id)) user = info
657-
if (info.role === "assistant" && (!assistant || info.id > assistant.id)) assistant = info
658-
if (info.role === "assistant" && info.finish && (!finished || info.id > finished.id)) finished = info
664+
if (info.role === "user" && (!user || isAfter(info, user))) user = info
665+
if (info.role === "assistant" && (!assistant || isAfter(info, assistant))) assistant = info
666+
if (info.role === "assistant" && info.finish && (!finished || isAfter(info, finished))) finished = info
659667
}
660668
const tasks = msgs.flatMap((m) =>
661-
finished && m.info.id <= finished.id
669+
finished && !isAfter(m.info, finished)
662670
? []
663671
: m.parts.filter((p): p is CompactionPart | SubtaskPart => p.type === "compaction" || p.type === "subtask"),
664672
)

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1120,7 +1120,7 @@ const layer = Layer.effect(
11201120
lastAssistant?.finish &&
11211121
!["tool-calls"].includes(lastAssistant.finish) &&
11221122
!hasToolCalls &&
1123-
lastUser.id < lastAssistant.id
1123+
lastUser.time.created < lastAssistant.time.created
11241124
) {
11251125
const orphan = lastAssistantMsg?.parts.find(
11261126
(part): part is SessionV1.ToolPart => part.type === "tool" && isOrphanedInterruptedTool(part),

‎packages/opencode/src/session/revert.ts‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ const layer = Layer.effect(
7171
if (session.revert?.snapshot) yield* snap.restore(session.revert.snapshot)
7272
yield* snap.revert(patches)
7373
if (rev.snapshot) rev.diff = yield* snap.diff(rev.snapshot)
74-
const range = all.filter((msg) => msg.info.id >= rev.messageID)
74+
const boundaryIndex = all.findIndex((msg) => msg.info.id === rev.messageID)
75+
const range = boundaryIndex < 0 ? [] : all.slice(boundaryIndex)
7576
const diffs = yield* summary.computeDiff({ messages: range })
7677
yield* storage.write(["session_diff", input.sessionID], diffs).pipe(Effect.ignore)
7778
yield* events.publish(Session.Event.Diff, { sessionID: input.sessionID, diff: diffs })
@@ -102,19 +103,27 @@ const layer = Layer.effect(
102103
const sessionID = session.id
103104
const msgs = yield* sessions.messages({ sessionID }).pipe(Effect.orDie)
104105
const messageID = session.revert.messageID
106+
// sessions.messages() returns messages oldest→newest (ordered by
107+
// time_created). The boundary message's position defines the rollback
108+
// point; everything from it onward (the boundary itself too, unless
109+
// partID is set) is removed. Compare by position, not by id string:
110+
// message ids are not orderable across the Identifier wrap (observed
111+
// 2026-08-13→14: pre-wrap ids start "msg_f…", post-wrap ids start
112+
// "msg_000…", "f" > "0" as strings), so a string comparison removes
113+
// the WRONG set — including, for a post-wrap boundary, the entire
114+
// pre-wrap history.
115+
const boundaryIndex = msgs.findIndex((msg) => msg.info.id === messageID)
105116
const remove = [] as SessionV1.WithParts[]
106117
let target: SessionV1.WithParts | undefined
107-
for (const msg of msgs) {
108-
if (msg.info.id < messageID) continue
109-
if (msg.info.id > messageID) {
118+
if (boundaryIndex >= 0) {
119+
for (let i = boundaryIndex; i < msgs.length; i++) {
120+
const msg = msgs[i]
121+
if (i === boundaryIndex && session.revert.partID) {
122+
target = msg
123+
continue
124+
}
110125
remove.push(msg)
111-
continue
112-
}
113-
if (session.revert.partID) {
114-
target = msg
115-
continue
116126
}
117-
remove.push(msg)
118127
}
119128
for (const msg of remove) {
120129
yield* sessions.removeMessage({ sessionID, messageID: msg.info.id })

‎packages/opencode/src/session/session.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -703,9 +703,14 @@ const layer: Layer.Layer<
703703
})
704704
const msgs = yield* messages({ sessionID: input.sessionID })
705705
const idMap = new Map<string, MessageID>()
706-
707-
for (const msg of msgs) {
708-
if (input.messageID && msg.info.id >= input.messageID) break
706+
// messages() is ordered oldest→newest by time_created; clone everything
707+
// strictly before the fork boundary. Compare by position, not id string
708+
// (ids wrap every ~2.18 years; a string comparison picks the wrong
709+
// boundary across the wrap).
710+
const boundaryIndex = input.messageID ? msgs.findIndex((msg) => msg.info.id === input.messageID) : -1
711+
for (let i = 0; i < msgs.length; i++) {
712+
if (boundaryIndex >= 0 && i >= boundaryIndex) break
713+
const msg = msgs[i]
709714
const newID = MessageID.ascending()
710715
idMap.set(msg.info.id, newID)
711716

‎packages/opencode/test/session/message-v2.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1749,4 +1749,37 @@ describe("session.message-v2.latest", () => {
17491749
expect(state.tasks).toHaveLength(1)
17501750
expect(state.tasks[0]).toMatchObject({ type: "compaction", auto: true })
17511751
})
1752+
1753+
// Regression: Identifier encodes (timestamp_ms << 12 | counter) in a 48-bit
1754+
// window that wraps every ~2.18 years. After the wrap (observed 2026-08-13→14)
1755+
// NEW ids start "msg_000…" and OLD ids start "msg_f…" — as strings "f" > "0",
1756+
// so max-by-id picks the WRONG (older) message across the wrap. latest() must
1757+
// order by creation time, with id only as a same-millisecond tiebreak.
1758+
test("latest() picks the chronologically-newest message across the ID wrap", () => {
1759+
const PRE_WRAP = 1_782_000_000_000
1760+
const POST_WRAP = 1_786_000_000_000
1761+
const oldUser = {
1762+
info: { ...userInfo(MessageID.make("msg_f26f00000000000000000001")), time: { created: PRE_WRAP } },
1763+
parts: [{ ...basePart("msg_f26f00000000000000000001", "p1"), type: "text", text: "old turn" }] as SessionV1.Part[],
1764+
}
1765+
const newUser = {
1766+
info: { ...userInfo(MessageID.make("msg_000000000000000000000001")), time: { created: POST_WRAP } },
1767+
parts: [{ ...basePart("msg_000000000000000000000001", "p1"), type: "text", text: "new turn" }] as SessionV1.Part[],
1768+
}
1769+
const oldAssistant = {
1770+
info: {
1771+
...assistantInfo(MessageID.make("msg_f26f00000000000000000002"), MessageID.make("msg_f26f00000000000000000001")),
1772+
finish: "stop",
1773+
time: { created: PRE_WRAP + 1 },
1774+
} as SessionV1.Assistant,
1775+
parts: [],
1776+
}
1777+
1778+
// Pre-wrap messages AFTER post-wrap messages in the array: id-based "max"
1779+
// would still pick the pre-wrap assistant as latest, time-based picks the
1780+
// post-wrap user as the last user and the pre-wrap assistant as finished.
1781+
const state = MessageV2.latest([oldUser, oldAssistant, newUser])
1782+
expect(state.user?.id).toBe(newUser.info.id)
1783+
expect(state.assistant?.id).toBe(oldAssistant.info.id)
1784+
})
17521785
})

‎packages/opencode/test/session/revert-compact.test.ts‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,4 +635,119 @@ describe("revert + compact workflow", () => {
635635
{ git: true },
636636
),
637637
)
638+
639+
// Regression: revert.cleanup previously compared message ids as STRINGS. After
640+
// the Identifier wrap (2026-08-13→14) pre-wrap ids start "msg_f…" and post-wrap
641+
// ids start "msg_000…" — "f" > "0" — so a staged revert on a post-wrap message
642+
// wiped the ENTIRE pre-wrap history on every prompt. cleanup must remove only
643+
// messages that come AFTER the boundary chronologically.
644+
it.live(
645+
"cleanup across the ID wrap keeps pre-wrap history, removes only post-boundary messages",
646+
provideTmpdirInstance(
647+
(dir) =>
648+
Effect.gen(function* () {
649+
const session = yield* Session.Service
650+
const revert = yield* SessionRevert.Service
651+
const info = yield* session.create({})
652+
const sessionID = info.id
653+
const model = { providerID: ProviderV2.ID.make("openai"), modelID: ModelV2.ID.make("gpt-4") }
654+
655+
const PRE = 1_782_000_000_000
656+
const POST = 1_786_000_000_000
657+
const oldUserID = MessageID.make("msg_f26f00000000000000000001")
658+
const oldAssistantID = MessageID.make("msg_f26f00000000000000000002")
659+
const boundaryID = MessageID.make("msg_000000000000000000000001")
660+
const afterID = MessageID.make("msg_000000000000000000000002")
661+
662+
yield* session.updateMessage({
663+
id: oldUserID,
664+
role: "user",
665+
sessionID,
666+
agent: "default",
667+
model,
668+
time: { created: PRE },
669+
})
670+
yield* session.updatePart({
671+
id: PartID.ascending(),
672+
messageID: oldUserID,
673+
sessionID,
674+
type: "text",
675+
text: "old turn",
676+
})
677+
yield* session.updateMessage({
678+
id: oldAssistantID,
679+
role: "assistant",
680+
sessionID,
681+
mode: "default",
682+
agent: "default",
683+
path: { cwd: dir, root: dir },
684+
cost: 0,
685+
tokens: { output: 0, input: 0, reasoning: 0, cache: { read: 0, write: 0 } },
686+
modelID: model.modelID,
687+
providerID: model.providerID,
688+
parentID: oldUserID,
689+
time: { created: PRE + 1 },
690+
})
691+
yield* session.updatePart({
692+
id: PartID.ascending(),
693+
messageID: oldAssistantID,
694+
sessionID,
695+
type: "text",
696+
text: "old reply",
697+
})
698+
yield* session.updateMessage({
699+
id: boundaryID,
700+
role: "user",
701+
sessionID,
702+
agent: "default",
703+
model,
704+
time: { created: POST },
705+
})
706+
yield* session.updatePart({
707+
id: PartID.ascending(),
708+
messageID: boundaryID,
709+
sessionID,
710+
type: "text",
711+
text: "revert to here",
712+
})
713+
yield* session.updateMessage({
714+
id: afterID,
715+
role: "assistant",
716+
sessionID,
717+
mode: "default",
718+
agent: "default",
719+
path: { cwd: dir, root: dir },
720+
cost: 0,
721+
tokens: { output: 0, input: 0, reasoning: 0, cache: { read: 0, write: 0 } },
722+
modelID: model.modelID,
723+
providerID: model.providerID,
724+
parentID: boundaryID,
725+
time: { created: POST + 1 },
726+
})
727+
yield* session.updatePart({
728+
id: PartID.ascending(),
729+
messageID: afterID,
730+
sessionID,
731+
type: "text",
732+
text: "after reply",
733+
})
734+
735+
yield* revert.revert({ sessionID, messageID: boundaryID })
736+
const sessionInfo = yield* session.get(sessionID)
737+
expect(sessionInfo.revert).toBeDefined()
738+
739+
yield* revert.cleanup(sessionInfo)
740+
741+
const remaining = (yield* session.messages({ sessionID })).map((m) => m.info.id)
742+
expect(remaining).toContain(oldUserID)
743+
expect(remaining).toContain(oldAssistantID)
744+
expect(remaining).not.toContain(boundaryID)
745+
expect(remaining).not.toContain(afterID)
746+
expect((yield* session.get(sessionID)).revert).toBeUndefined()
747+
748+
yield* session.remove(sessionID)
749+
}),
750+
{ git: true },
751+
),
752+
)
638753
})

0 commit comments

Comments
 (0)