Skip to content

Commit f6c9eb5

Browse files
committed
fix: stop invalid message ref assignment on exhaustion
1 parent 8894095 commit f6c9eb5

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

lib/message-ids.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,14 +136,17 @@ export function assignMessageRefs(state: SessionState, messages: WithParts[]): n
136136
}
137137

138138
const existingRef = state.messageIds.byRawId.get(rawMessageId)
139-
if (existingRef) {
139+
if (existingRef !== undefined) {
140140
if (state.messageIds.byRef.get(existingRef) !== rawMessageId) {
141141
state.messageIds.byRef.set(existingRef, rawMessageId)
142142
}
143143
continue
144144
}
145145

146146
const ref = allocateNextMessageRef(state)
147+
if (!ref) {
148+
break
149+
}
147150
state.messageIds.byRawId.set(rawMessageId, ref)
148151
state.messageIds.byRef.set(ref, rawMessageId)
149152
assigned++

tests/message-ids.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,42 @@ test("checkSession resets message id aliases after native compaction", async ()
8787
assert.equal(state.messageIds.byRef.get("m0002"), "msg-user-follow-up")
8888
assert.equal(state.messageIds.nextRef, 3)
8989
})
90+
91+
test("assignMessageRefs stops cleanly when alias capacity is exhausted", () => {
92+
const sessionID = `ses_message_ids_exhausted_${Date.now()}`
93+
const state = createSessionState()
94+
state.messageIds.nextRef = 10000
95+
96+
const messages: WithParts[] = [
97+
{
98+
info: {
99+
id: "msg-a",
100+
role: "assistant",
101+
sessionID,
102+
agent: "assistant",
103+
time: { created: 1 },
104+
} as WithParts["info"],
105+
parts: [textPart("msg-a", sessionID, "msg-a-part", "A")],
106+
},
107+
{
108+
info: {
109+
id: "msg-b",
110+
role: "assistant",
111+
sessionID,
112+
agent: "assistant",
113+
time: { created: 2 },
114+
} as WithParts["info"],
115+
parts: [textPart("msg-b", sessionID, "msg-b-part", "B")],
116+
},
117+
]
118+
119+
const firstAssigned = assignMessageRefs(state, messages)
120+
const secondAssigned = assignMessageRefs(state, messages)
121+
122+
assert.equal(firstAssigned, 0)
123+
assert.equal(secondAssigned, 0)
124+
assert.equal(state.messageIds.byRawId.size, 0)
125+
assert.equal(state.messageIds.byRef.size, 0)
126+
assert.equal(state.messageIds.byRawId.get("msg-a"), undefined)
127+
assert.equal(state.messageIds.byRawId.get("msg-b"), undefined)
128+
})

0 commit comments

Comments
 (0)