Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions packages/api/src/postgres/operations-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
import type { Database } from "./database";
import { rankField, searchMatches } from "../search";

const HIGHLIGHT_START = "<<<FACTORIZE_MATCH>>>";
const HIGHLIGHT_END = "<<<FACTORIZE_END>>>";

function markedMatch(value: string, fallback: string, query: string) {
const text = value || fallback, ranges: { start: number; end: number }[] = [];
let output = "", cursor = 0, start = text.indexOf(HIGHLIGHT_START);
while (start >= 0) {
const end = text.indexOf(HIGHLIGHT_END, start + HIGHLIGHT_START.length);
if (end < 0) break;
output += text.slice(cursor, start);
const matchStart = output.length;
output += text.slice(start + HIGHLIGHT_START.length, end);
ranges.push({ start: matchStart, end: output.length });
cursor = end + HIGHLIGHT_END.length;
start = text.indexOf(HIGHLIGHT_START, cursor);
}
output += text.slice(cursor);
return { text: output || fallback, ranges: ranges.length ? ranges : searchMatches(output || fallback, query) };
}

export class OperationsRepository {
constructor(private database: Database, private tenantId: string) {}
Expand All @@ -22,7 +43,7 @@ export class OperationsRepository {
SELECT 'job' kind,j.id::text id,j.name title,j.slug subtitle,'/jobs/'||j.id url,j.id::text source_id,j.name source_label,
CASE WHEN word_similarity($2,j.name) >= word_similarity($2,j.slug) THEN j.name ELSE j.slug END match_text,
GREATEST(word_similarity($2,j.name),word_similarity($2,j.slug)) score,
CASE WHEN lower(j.name)=$2 OR lower(j.slug)=$2 THEN 1 ELSE 2 END category,j.id::text stable_key
CASE WHEN lower(j.name)=$2 OR lower(j.slug)=$2 THEN 1 ELSE 2 END category,j.id::text stable_key,NULL match_excerpt
FROM app.jobs j WHERE j.tenant_id=$1 AND ($2 <% j.name OR $2 <% j.slug)
UNION ALL
SELECT 'run',r.id::text,coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),r.state,'/job-runs/'||r.id,r.id::text,
Expand All @@ -31,13 +52,21 @@ export class OperationsRepository {
WHEN word_similarity($2,r.run_name) >= word_similarity($2,r.issue_title) THEN coalesce(nullif(r.run_name,''),r.issue_id)
ELSE coalesce(nullif(r.issue_title,''),r.issue_id) END match_text,
GREATEST(similarity(r.issue_id,$2),word_similarity($2,r.run_name),word_similarity($2,r.issue_title)) score,
CASE WHEN lower(r.issue_id)=$2 THEN 0 WHEN lower(r.run_name)=$2 OR lower(r.issue_title)=$2 THEN 1 ELSE 2 END category,r.id::text stable_key
CASE WHEN lower(r.issue_id)=$2 THEN 0 WHEN lower(r.run_name)=$2 OR lower(r.issue_title)=$2 THEN 1 ELSE 2 END category,r.id::text stable_key,NULL match_excerpt
FROM app.runs r WHERE r.tenant_id=$1 AND (r.issue_id % $2 OR $2 <% r.run_name OR $2 <% r.issue_title)
UNION ALL
SELECT 'trace',e.id,e.title,left(e.preview_text,120),'/job-runs/'||e.run_id,e.run_id::text,
coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),e.title,
ts_rank(e.search_vector,websearch_to_tsquery('english',$2)),2,e.run_id::text||':'||e.sequence,
ts_headline('english',e.title||' '||e.preview_text,websearch_to_tsquery('english',$2),
'StartSel=<<<FACTORIZE_MATCH>>>,StopSel=<<<FACTORIZE_END>>>,MaxFragments=1,MaxWords=32,MinWords=8')
FROM app.run_trace_events e JOIN app.runs r ON r.tenant_id=e.tenant_id AND r.id=e.run_id
WHERE e.tenant_id=$1 AND e.search_vector @@ websearch_to_tsquery('english',$2)
) found ORDER BY category,score DESC,kind,stable_key LIMIT 100`, [this.tenantId, needle.toLowerCase()]);
return { items: rows.rows.map(row => ({
kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url,
source: { kind: row.kind, label: row.source_label, id: row.source_id },
match: { text: row.match_text, ranges: [] },
})) };
return { items: rows.rows.map(row => {
const ranked = row.kind === "trace" ? null : rankField(row.match_text, needle, row.kind === "job" ? "job" : "run");
const match = row.kind === "trace" ? markedMatch(row.match_excerpt, row.title, needle) : { text: row.match_text, ranges: ranked?.range ? [ranked.range] : searchMatches(row.match_text, needle) };
return { kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url, source: { kind: row.kind, label: row.source_label, id: row.source_id }, match };
}) };
}
}
68 changes: 68 additions & 0 deletions packages/api/test/search.postgres.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { readFile, readdir } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { Database } from "../src/postgres/database";
import { OperationsRepository } from "../src/postgres/operations-repository";

const url = process.env.AUTH_TEST_DATABASE_URL;

describe.skipIf(!url)("global search trigram matching (PostgreSQL)", () => {
let db: Database, admin: Database;
const databaseName = `search_test_${crypto.randomUUID().replaceAll("-", "")}`;
const tenant = crypto.randomUUID(), otherTenant = crypto.randomUUID();
const job = crypto.randomUUID(), otherJob = crypto.randomUUID();
const run = crypto.randomUUID(), typoRun = crypto.randomUUID(), privateRun = crypto.randomUUID();
const invocation = crypto.randomUUID(), typoInvocation = crypto.randomUUID(), privateInvocation = crypto.randomUUID();
const trigger = crypto.randomUUID(), typoTrigger = crypto.randomUUID(), privateTrigger = crypto.randomUUID();

beforeAll(async () => {
admin = new Database({ connectionString: url });
await admin.pool.query(`CREATE DATABASE ${databaseName}`);
const address = new URL(url!); address.pathname = `/${databaseName}`;
db = new Database({ connectionString: address.toString(), maxUses: Infinity });
const directory = new URL("../migrations/", import.meta.url);
for (const file of (await readdir(directory)).filter(file => file.endsWith(".sql")).sort()) await db.pool.query(await readFile(new URL(file, directory), "utf8"));

await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1),($2)", [tenant, otherTenant]);
await db.pool.query(`INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit)
VALUES ($1,$2,'Deployment Automation','deployment-automation','prompt','{}',1),($3,$4,'Private Deployment','private-deployment','prompt','{}',1)`, [tenant, job, otherTenant, otherJob]);
await db.pool.query(`INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES
($1,$2,$3,'manual','search'),($1,$4,$3,'manual','search-typo'),($5,$6,$7,'manual','search')`, [tenant, trigger, job, typoTrigger, otherTenant, privateTrigger, otherJob]);
await db.pool.query(`INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES
($1,$2,$3,'manual','search',$4,'{}'),($1,$5,$3,'manual','search-typo',$6,'{}'),($7,$8,$9,'manual','search',$10,'{}')`, [tenant, invocation, job, trigger, typoInvocation, typoTrigger, otherTenant, privateInvocation, otherJob, privateTrigger]);
await db.pool.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,issue_title,run_name,agent_name,state)
VALUES ($1,$2,$3,$4,'manual','GEN-2157','Fix punctuation in issue identifiers','Deploy GEN-2157','codex','succeeded'),
($1,$5,$3,$6,'manual','GEN-2158','A nearby but weaker identifier','Deploy GEN-2158','codex','succeeded'),
($7,$8,$9,$10,'manual','GEN-2157','Private issue','Private GEN-2157','codex','succeeded')`, [tenant, run, job, invocation, typoRun, typoInvocation, otherTenant, privateRun, otherJob, privateInvocation]);
await db.pool.query(`INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,event_type,title,preview_text)
VALUES ($1,$2,1,'trace-search','assistant_message','Rollback summary','The rollback completed successfully')`, [tenant, run]);
});

afterAll(async () => {
await db?.close();
await admin?.pool.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`);
await admin?.close();
});

it("matches missing punctuation and keeps exact identifiers ahead of weaker trigrams", async () => {
const items = (await new OperationsRepository(db, tenant).search("GEN2157")).items;
expect(items.filter(item => item.kind === "run").map(item => item.id)).toContain(run);
const exact = (await new OperationsRepository(db, tenant).search("GEN-2157")).items.filter(item => item.kind === "run");
expect(exact[0]?.id).toBe(run);
});

it("matches a representative job-name typo without substring filtering", async () => {
const items = (await new OperationsRepository(db, tenant).search("deplyment")).items;
expect(items.some(item => item.kind === "job" && item.id === job)).toBe(true);
});

it("excludes unrelated rows and preserves tenant isolation", async () => {
expect((await new OperationsRepository(db, tenant).search("zzzz-unrelated")).items).toEqual([]);
const items = (await new OperationsRepository(db, tenant).search("GEN2157")).items;
expect(items.every(item => item.id !== privateRun)).toBe(true);
});

it("keeps trace full-text search available", async () => {
const items = (await new OperationsRepository(db, tenant).search("rollback")).items;
expect(items).toEqual(expect.arrayContaining([expect.objectContaining({ kind: "trace", id: "trace-search" })]));
});
});
Loading