Skip to content

Commit e078489

Browse files
author
StackMemory Bot (CLI)
committed
perf(provenant): optimize database queries and BFS traversal
- Replace findContradiction full table scan with SQL WHERE + LIKE prefix - Replace findQueueItem full table scan with SQL WHERE + LIKE prefix - Fix BFS queue.shift() O(n²) with index-based iteration O(n)
1 parent 4131848 commit e078489

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

packages/provenant/src/schema/database.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -489,21 +489,28 @@ export class Database {
489489
nodeAPrefix: string,
490490
nodeBPrefix: string
491491
): Contradiction | undefined {
492-
// Match by prefix (short IDs)
493-
const all = this.getPendingContradictions();
494-
return all.find(
495-
(c) =>
496-
(c.node_a.startsWith(nodeAPrefix) &&
497-
c.node_b.startsWith(nodeBPrefix)) ||
498-
(c.node_a.startsWith(nodeBPrefix) && c.node_b.startsWith(nodeAPrefix))
499-
);
492+
return this.db
493+
.prepare(
494+
`SELECT * FROM contradictions WHERE status = 'pending'
495+
AND ((node_a LIKE ? AND node_b LIKE ?) OR (node_a LIKE ? AND node_b LIKE ?))
496+
LIMIT 1`
497+
)
498+
.get(
499+
`${nodeAPrefix}%`,
500+
`${nodeBPrefix}%`,
501+
`${nodeBPrefix}%`,
502+
`${nodeAPrefix}%`
503+
) as Contradiction | undefined;
500504
}
501505

502506
// --- Review Queue helpers ---
503507

504508
findQueueItem(idPrefix: string): ReviewQueueItem | undefined {
505-
const pending = this.getPendingQueue();
506-
return pending.find((i) => i.id.startsWith(idPrefix));
509+
return this.db
510+
.prepare(
511+
'SELECT * FROM review_queue WHERE resolved_at IS NULL AND id LIKE ? LIMIT 1'
512+
)
513+
.get(`${idPrefix}%`) as ReviewQueueItem | undefined;
507514
}
508515

509516
resolveQueueItem(id: string): void {
@@ -580,8 +587,9 @@ export class Database {
580587
const queue: Array<{ node: string; depth: number }> = [
581588
{ node: startNode, depth: 0 },
582589
];
583-
while (queue.length > 0) {
584-
const current = queue.shift()!;
590+
let qi = 0;
591+
while (qi < queue.length) {
592+
const current = queue[qi++];
585593
const neighbors = adj.get(current.node);
586594
if (!neighbors) continue;
587595
for (const neighbor of neighbors) {

0 commit comments

Comments
 (0)