Skip to content

Commit 9b70f2d

Browse files
committed
fix(plugin): recover gracefully from tagger UNIQUE constraint violations
When a tag already exists in the DB but not in the in-memory assignments map (e.g., after a partial batch failure lost in-memory state), the tagger now catches SQLITE_CONSTRAINT_UNIQUE, looks up the existing tag number from DB, and binds it in-memory instead of crashing the entire transform pass.
1 parent 407cdd3 commit 9b70f2d

1 file changed

Lines changed: 24 additions & 4 deletions

File tree

  • packages/plugin/src/features/magic-context

packages/plugin/src/features/magic-context/tagger.ts

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,30 @@ export function createTagger(): Tagger {
8989
const current = counters.get(sessionId) ?? 0;
9090
const next = current + 1;
9191

92-
db.transaction(() => {
93-
insertTag(db, sessionId, messageId, type, byteSize, next, reasoningByteSize);
94-
getUpsertCounterStatement(db).run(sessionId, next);
95-
})();
92+
try {
93+
db.transaction(() => {
94+
insertTag(db, sessionId, messageId, type, byteSize, next, reasoningByteSize);
95+
getUpsertCounterStatement(db).run(sessionId, next);
96+
})();
97+
} catch (error: unknown) {
98+
// Benign duplicate: the tag already exists in the DB from a previous pass
99+
// whose in-memory state was lost (e.g., error in a different tag within the
100+
// same batch). Recover by binding the existing tag number from DB.
101+
if (
102+
error instanceof Error &&
103+
"code" in error &&
104+
error.code === "SQLITE_CONSTRAINT_UNIQUE"
105+
) {
106+
const row = db
107+
.prepare("SELECT tag_number FROM tags WHERE session_id = ? AND message_id = ?")
108+
.get(sessionId, messageId) as { tag_number: number } | null;
109+
if (row) {
110+
sessionAssignments.set(messageId, row.tag_number);
111+
return row.tag_number;
112+
}
113+
}
114+
throw error;
115+
}
96116

97117
counters.set(sessionId, next);
98118
sessionAssignments.set(messageId, next);

0 commit comments

Comments
 (0)