Skip to content

Commit f7fc964

Browse files
steipetehe-yufeng
andcommitted
fix(gateway): make redacted history dedupe collision-safe
Co-authored-by: Yufeng He <[email protected]>
1 parent 95cd967 commit f7fc964

2 files changed

Lines changed: 431 additions & 20 deletions

File tree

‎src/gateway/cli-session-history.merge.ts‎

Lines changed: 149 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -101,37 +101,150 @@ function hasSameExternalIdentity(existing: unknown, imported: unknown): boolean
101101
);
102102
}
103103

104-
function isEquivalentImportedMessage(existing: unknown, imported: unknown): boolean {
104+
function hasConflictingExternalIdentity(existing: unknown, imported: unknown): boolean {
105+
const existingIdentity = resolveImportedExternalIdentity(existing);
106+
const importedIdentity = resolveImportedExternalIdentity(imported);
107+
return Boolean(
108+
existingIdentity && importedIdentity && !hasSameExternalIdentity(existing, imported),
109+
);
110+
}
111+
112+
type ImportedMessageMatch = "lossless" | "lossy-redaction";
113+
114+
function resolveImportedMessageMatch(
115+
existing: unknown,
116+
imported: unknown,
117+
): ImportedMessageMatch | undefined {
105118
if (hasSameExternalIdentity(existing, imported)) {
106-
return true;
119+
return "lossless";
107120
}
108121

109122
const existingRole = resolveComparableRole(existing);
110123
const importedRole = resolveComparableRole(imported);
111124
if (!existingRole || existingRole !== importedRole) {
112-
return false;
125+
return undefined;
113126
}
114127

115128
const existingText = extractComparableText(existing);
116129
const importedText = extractComparableText(imported);
117130
if (!existingText || !importedText) {
118-
return false;
131+
return undefined;
119132
}
120-
// The gateway transcript persists the redacted form while the CLI import
121-
// keeps the full text, so also accept the redacted form of the import.
122-
// (Only mask the import side: masking is not idempotent, an already
123-
// masked token can degrade to "***" on a second pass.)
124-
if (existingText !== importedText && existingText !== redactSensitiveText(importedText)) {
125-
return false;
133+
let textMatch: ImportedMessageMatch;
134+
if (existingText === importedText) {
135+
textMatch = "lossless";
136+
} else if (hasConflictingExternalIdentity(existing, imported)) {
137+
return undefined;
138+
} else if (
139+
existingText === redactSensitiveText(importedText) ||
140+
redactSensitiveText(existingText) === importedText
141+
) {
142+
// Compare each original with one redaction pass of the other; never compare
143+
// two redacted results because masking is lossy and not idempotent.
144+
textMatch = "lossy-redaction";
145+
} else {
146+
return undefined;
126147
}
127148

128149
const existingTimestamp = resolveComparableTimestamp(existing);
129150
const importedTimestamp = resolveComparableTimestamp(imported);
130151
if (existingTimestamp === undefined || importedTimestamp === undefined) {
131-
return true;
152+
return textMatch;
153+
}
154+
155+
return Math.abs(existingTimestamp - importedTimestamp) <= DEDUPE_TIMESTAMP_WINDOW_MS
156+
? textMatch
157+
: undefined;
158+
}
159+
160+
function redactionVariantKey(role: string, redactedText: string): string {
161+
return `${role}\0${redactedText}`;
162+
}
163+
164+
function resolveLossyRedactionMatch(
165+
existing: unknown,
166+
imported: unknown,
167+
): { key: string; masked: unknown } | undefined {
168+
const existingRole = resolveComparableRole(existing);
169+
if (!existingRole || existingRole !== resolveComparableRole(imported)) {
170+
return undefined;
171+
}
172+
const existingText = extractComparableText(existing);
173+
const importedText = extractComparableText(imported);
174+
if (!existingText || !importedText) {
175+
return undefined;
176+
}
177+
if (existingText === redactSensitiveText(importedText)) {
178+
return { key: redactionVariantKey(existingRole, existingText), masked: existing };
132179
}
180+
return redactSensitiveText(existingText) === importedText
181+
? { key: redactionVariantKey(existingRole, importedText), masked: imported }
182+
: undefined;
183+
}
184+
185+
type RedactionVariant = { message: unknown; text: string };
186+
type RedactionVariantIndex = Map<string, RedactionVariant[]>;
187+
188+
function collectRedactionVariants(messages: unknown[]): RedactionVariantIndex {
189+
const variants: RedactionVariantIndex = new Map();
190+
for (const message of messages) {
191+
const role = resolveComparableRole(message);
192+
const text = extractComparableText(message);
193+
if (!role || !text) {
194+
continue;
195+
}
196+
const redacted = redactSensitiveText(text);
197+
if (redacted === text) {
198+
continue;
199+
}
200+
const key = redactionVariantKey(role, redacted);
201+
const entries = variants.get(key) ?? [];
202+
entries.push({ message, text });
203+
variants.set(key, entries);
204+
}
205+
return variants;
206+
}
207+
208+
function haveCompatibleTimestamps(left: unknown, right: unknown): boolean {
209+
const leftTimestamp = resolveComparableTimestamp(left);
210+
const rightTimestamp = resolveComparableTimestamp(right);
211+
return (
212+
leftTimestamp === undefined ||
213+
rightTimestamp === undefined ||
214+
Math.abs(leftTimestamp - rightTimestamp) <= DEDUPE_TIMESTAMP_WINDOW_MS
215+
);
216+
}
133217

134-
return Math.abs(existingTimestamp - importedTimestamp) <= DEDUPE_TIMESTAMP_WINDOW_MS;
218+
function hasUniqueCompatibleRedactionVariant(params: {
219+
existing: unknown;
220+
imported: unknown;
221+
variants: RedactionVariantIndex;
222+
cache: Map<unknown, Map<string, boolean>>;
223+
}): boolean {
224+
const lossyMatch = resolveLossyRedactionMatch(params.existing, params.imported);
225+
if (!lossyMatch) {
226+
return false;
227+
}
228+
const cachedByKey = params.cache.get(lossyMatch.masked);
229+
const cached = cachedByKey?.get(lossyMatch.key);
230+
if (cached !== undefined) {
231+
return cached;
232+
}
233+
const compatibleTexts = new Set<string>();
234+
for (const variant of params.variants.get(lossyMatch.key) ?? []) {
235+
if (!haveCompatibleTimestamps(lossyMatch.masked, variant.message)) {
236+
continue;
237+
}
238+
compatibleTexts.add(variant.text);
239+
if (compatibleTexts.size > 1) {
240+
break;
241+
}
242+
}
243+
const unique = compatibleTexts.size === 1;
244+
const nextCachedByKey = cachedByKey ?? new Map<string, boolean>();
245+
nextCachedByKey.set(lossyMatch.key, unique);
246+
params.cache.set(lossyMatch.masked, nextCachedByKey);
247+
return unique;
135248
}
136249

137250
function compareHistoryMessages(
@@ -155,9 +268,32 @@ export function mergeImportedChatHistoryMessages(params: {
155268
return params.localMessages;
156269
}
157270
const merged = params.localMessages.map((message, index) => ({ message, order: index }));
271+
const redactionVariants = collectRedactionVariants([
272+
...params.localMessages,
273+
...params.importedMessages,
274+
]);
275+
const redactionVariantCache = new Map<unknown, Map<string, boolean>>();
276+
158277
let nextOrder = merged.length;
159278
for (const imported of params.importedMessages) {
160-
if (merged.some((existing) => isEquivalentImportedMessage(existing.message, imported))) {
279+
const duplicate = merged.some((existing) => {
280+
const match = resolveImportedMessageMatch(existing.message, imported);
281+
if (match === "lossless") {
282+
return true;
283+
}
284+
if (match !== "lossy-redaction") {
285+
return false;
286+
}
287+
// A mask is not an identity. Only collapse it when every observed full
288+
// representation agrees; collisions stay visible rather than being guessed.
289+
return hasUniqueCompatibleRedactionVariant({
290+
existing: existing.message,
291+
imported,
292+
variants: redactionVariants,
293+
cache: redactionVariantCache,
294+
});
295+
});
296+
if (duplicate) {
161297
continue;
162298
}
163299
merged.push({ message: imported, order: nextOrder });

0 commit comments

Comments
 (0)