Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: task dup detection (#3735)

Eric Hayesd2ecdd4249d0
diff --git a/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.json b/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.json
deleted file mode 100644
index 0e311a34a1..0000000000
--- a/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT COUNT(*) AS \"count!\"\n FROM \"Document\" d\n JOIN document_sub_type dst\n ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN task_duplicate_embedding e ON e.document_id = d.id\n WHERE d.\"deletedAt\" IS NULL\n AND ($1::bool OR e.document_id IS NULL)\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "count!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Bool"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c"
-}
diff --git a/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.json b/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.json
deleted file mode 100644
index 02dbdeac4b..0000000000
--- a/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n e.document_id,\n d.name AS \"name!\",\n e.content,\n 1 - (e.embedding <=> $3::text::vector) AS \"vector_score!\"\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n WHERE d.\"deletedAt\" IS NULL\n AND (\n d.owner = $1\n OR ($2::uuid IS NOT NULL AND tt.team_id = $2)\n )\n ORDER BY e.embedding <=> $3::text::vector\n LIMIT $4\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "document_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "name!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "content",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "vector_score!",
- "type_info": "Float8"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid",
- "Text",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- null
- ]
- },
- "hash": "44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338"
-}
diff --git a/rust/cloud-storage/.sqlx/query-758f208ea073a48e9be9919a0dce43648c19b5a092049b7cb0a6382e931371a1.json b/rust/cloud-storage/.sqlx/query-758f208ea073a48e9be9919a0dce43648c19b5a092049b7cb0a6382e931371a1.json
new file mode 100644
index 0000000000..0084440a91
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-758f208ea073a48e9be9919a0dce43648c19b5a092049b7cb0a6382e931371a1.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SET LOCAL hnsw.iterative_scan = relaxed_order",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "758f208ea073a48e9be9919a0dce43648c19b5a092049b7cb0a6382e931371a1"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9b7bc338faac59d4da4d6ccdc478ba67be32356a3b2b62660982ca8932a0d2f7.json b/rust/cloud-storage/.sqlx/query-9b7bc338faac59d4da4d6ccdc478ba67be32356a3b2b62660982ca8932a0d2f7.json
new file mode 100644
index 0000000000..c83112aadc
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9b7bc338faac59d4da4d6ccdc478ba67be32356a3b2b62660982ca8932a0d2f7.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "TRUNCATE TABLE task_duplicate_embedding",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "9b7bc338faac59d4da4d6ccdc478ba67be32356a3b2b62660982ca8932a0d2f7"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.json b/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.json
deleted file mode 100644
index eef301d54f..0000000000
--- a/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)\n SELECT doc_id, $1, content, embedding_text::vector\n FROM UNNEST($2::text[], $3::text[], $4::text[])\n AS t(doc_id, content, embedding_text)\n ON CONFLICT (document_id) DO UPDATE\n SET model = EXCLUDED.model,\n content = EXCLUDED.content,\n embedding = EXCLUDED.embedding,\n updated_at = NOW()\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "TextArray",
- "TextArray",
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff"
-}
diff --git a/rust/cloud-storage/.sqlx/query-ae1b88cef7fd6cc6ef1c302a0f3a04d156d39f39abea24050e63caf56267898a.json b/rust/cloud-storage/.sqlx/query-ae1b88cef7fd6cc6ef1c302a0f3a04d156d39f39abea24050e63caf56267898a.json
new file mode 100644
index 0000000000..e4b3c2a5e5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ae1b88cef7fd6cc6ef1c302a0f3a04d156d39f39abea24050e63caf56267898a.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH query AS (\n SELECT key, vec::vector AS vec\n FROM unnest($1::text[], $2::text[]) AS t(key, vec)\n ),\n scored AS (\n SELECT\n e.document_id,\n e.search_key,\n e.content,\n e.embedding::text AS embedding_text,\n MAX(1 - (e.embedding <=> q.vec))::real AS score\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n CROSS JOIN query q\n WHERE d.\"deletedAt\" IS NULL\n AND (\n d.owner = $3\n OR ($4::uuid IS NOT NULL AND tt.team_id = $4)\n )\n AND ($5::text IS NULL OR e.document_id <> $5)\n AND (\n NOT $6\n OR NOT EXISTS (\n SELECT 1\n FROM task_duplicate_match m\n WHERE m.task_id = LEAST($5, e.document_id)\n AND m.duplicate_task_id = GREATEST($5, e.document_id)\n AND m.status = 'dismissed'\n )\n )\n GROUP BY e.document_id, e.search_key, e.content, e.embedding\n ),\n ranked AS (\n SELECT document_id, MAX(score) AS best\n FROM scored\n GROUP BY document_id\n ORDER BY best DESC\n LIMIT $7\n )\n SELECT\n s.document_id AS \"document_id!\",\n s.search_key AS \"search_key!\",\n s.content AS \"content!\",\n s.embedding_text AS \"embedding_text!\",\n s.score AS \"score!\"\n FROM scored s\n JOIN ranked r ON r.document_id = s.document_id\n ORDER BY r.best DESC, s.document_id, s.score DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "search_key!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "content!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "embedding_text!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "score!",
+ "type_info": "Float4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "TextArray",
+ "Text",
+ "Uuid",
+ "Text",
+ "Bool",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "ae1b88cef7fd6cc6ef1c302a0f3a04d156d39f39abea24050e63caf56267898a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d35bd972bde3e682873d7088574ab3afced6278d25e630969724dd5837182f0c.json b/rust/cloud-storage/.sqlx/query-d35bd972bde3e682873d7088574ab3afced6278d25e630969724dd5837182f0c.json
new file mode 100644
index 0000000000..ba803da97e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d35bd972bde3e682873d7088574ab3afced6278d25e630969724dd5837182f0c.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT dst.document_id\n FROM document_sub_type dst\n JOIN \"Document\" d ON d.id = dst.document_id\n WHERE dst.sub_type = 'task'\n AND d.\"deletedAt\" IS NULL\n AND (\n $1\n OR NOT EXISTS (\n SELECT 1\n FROM task_duplicate_embedding tde\n WHERE tde.document_id = dst.document_id\n )\n )\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "d35bd972bde3e682873d7088574ab3afced6278d25e630969724dd5837182f0c"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.json b/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.json
deleted file mode 100644
index 27b0cf9c29..0000000000
--- a/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT d.id AS \"document_id!\", d.name\n FROM \"Document\" d\n JOIN document_sub_type dst\n ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN task_duplicate_embedding e ON e.document_id = d.id\n WHERE d.\"deletedAt\" IS NULL\n AND ($1::bool OR e.document_id IS NULL)\n AND d.id > $2\n ORDER BY d.id\n LIMIT $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "document_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Bool",
- "Text",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826"
-}
diff --git a/rust/cloud-storage/.sqlx/query-d990b4285faa94bcc23b8e4ebd3c433d0dd69045b66f7cf5952f1126115dec84.json b/rust/cloud-storage/.sqlx/query-d990b4285faa94bcc23b8e4ebd3c433d0dd69045b66f7cf5952f1126115dec84.json
new file mode 100644
index 0000000000..0cfdf07faf
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d990b4285faa94bcc23b8e4ebd3c433d0dd69045b66f7cf5952f1126115dec84.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO task_duplicate_embedding (document_id, search_key, content, embedding)\n SELECT $1, sk, ct, emb::vector\n FROM unnest($2::text[], $3::text[], $4::text[]) AS t(sk, ct, emb)\n ON CONFLICT (document_id, search_key) DO UPDATE\n SET content = EXCLUDED.content,\n embedding = EXCLUDED.embedding,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d990b4285faa94bcc23b8e4ebd3c433d0dd69045b66f7cf5952f1126115dec84"
+}
diff --git a/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json b/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json
deleted file mode 100644
index f8ffdb3e70..0000000000
--- a/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)\n VALUES ($1, $2, $3, $4::text::vector)\n ON CONFLICT (document_id) DO UPDATE\n SET model = EXCLUDED.model,\n content = EXCLUDED.content,\n embedding = EXCLUDED.embedding,\n updated_at = NOW()\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758"
-}
diff --git a/rust/cloud-storage/.sqlx/query-f6bc8c7f62c44aa50928badd81140cddf46a772f8a638259541b05f006bd4c1c.json b/rust/cloud-storage/.sqlx/query-f6bc8c7f62c44aa50928badd81140cddf46a772f8a638259541b05f006bd4c1c.json
new file mode 100644
index 0000000000..92d4487785
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-f6bc8c7f62c44aa50928badd81140cddf46a772f8a638259541b05f006bd4c1c.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, name\n FROM \"Document\"\n WHERE id = ANY($1)\n AND \"deletedAt\" IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "f6bc8c7f62c44aa50928badd81140cddf46a772f8a638259541b05f006bd4c1c"
+}
diff --git a/rust/cloud-storage/.sqlx/query-faf5532927a794d4e40350f17e0633ba54b8185f1e6aeac32a8d1bfca35a43d3.json b/rust/cloud-storage/.sqlx/query-faf5532927a794d4e40350f17e0633ba54b8185f1e6aeac32a8d1bfca35a43d3.json
new file mode 100644
index 0000000000..9ec28469b0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-faf5532927a794d4e40350f17e0633ba54b8185f1e6aeac32a8d1bfca35a43d3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name FROM \"Document\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "faf5532927a794d4e40350f17e0633ba54b8185f1e6aeac32a8d1bfca35a43d3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json b/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json
deleted file mode 100644
index 806dd516a2..0000000000
--- a/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n e.document_id,\n e.content,\n 1 - (e.embedding <=> $2::text::vector) AS \"vector_score!\"\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n WHERE e.document_id <> $1\n AND d.\"deletedAt\" IS NULL\n AND (\n d.owner = $3\n OR ($4::uuid IS NOT NULL AND tt.team_id = $4)\n )\n AND NOT EXISTS (\n SELECT 1\n FROM task_duplicate_match m\n WHERE (\n m.task_id = LEAST($1, e.document_id)\n AND m.duplicate_task_id = GREATEST($1, e.document_id)\n AND m.status = 'dismissed'\n )\n )\n ORDER BY e.embedding <=> $2::text::vector\n LIMIT $5\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "document_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "content",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "vector_score!",
- "type_info": "Float8"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Text",
- "Uuid",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- null
- ]
- },
- "hash": "fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5"
-}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b9474d39ee..533c7ba491 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3427,6 +3427,7 @@ dependencies = [
"documents",
"dynamodb_client",
"email",
+ "embedding",
"entity_access",
"entity_access_management",
"foreign_entity",
@@ -4134,6 +4135,14 @@ dependencies = [
"regex",
]
+[[package]]
+name = "embedding"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-openai",
+]
+
[[package]]
name = "encoding_rs"
version = "0.8.35"
@@ -11440,11 +11449,21 @@ version = "0.1.0"
dependencies = [
"agent",
"anyhow",
- "async-openai",
"async-trait",
+ "aws-sdk-secretsmanager",
+ "clap",
"connection_gateway_client",
+ "embedding",
+ "futures",
+ "lexical_client",
+ "macro_aws_config",
"macro_db_migrator",
+ "macro_entrypoint",
+ "macro_env",
+ "macro_env_var",
+ "macro_middleware",
"model-entity",
+ "secretsmanager_client",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 14eaf468d1..38936b8325 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -27,6 +27,7 @@ members = [
"email_service",
"email_sfs_delete_handler",
"email_suppression_handler",
+ "embedding",
"foreign_entity",
"image_optimizer",
"image_proxy_service",
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 74ef0ca924..e54c719a9d 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -13,10 +13,6 @@ path = "src/main.rs"
name = "document_storage_service_openapi"
path = "src/openapi.rs"
-[[bin]]
-name = "backfill_task_embeddings"
-path = "src/bin/backfill_task_embeddings.rs"
-
[features]
connection_gateway = []
default = ["connection_gateway", "location_check"]
@@ -59,6 +55,7 @@ cowlike = { path = "../cowlike" }
crm = { path = "../crm" }
document_sub_type = { path = "../document_sub_type" }
documents_hex = { path = "../documents", package = "documents" }
+embedding = { path = "../embedding" }
task_dedup = { path = "../task_dedup" }
dynamodb_client = { path = "../dynamodb_client" }
email = { path = "../email", features = ["outbound", "ports"] }
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_task_embeddings.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_task_embeddings.rs
deleted file mode 100644
index b7f12a888d..0000000000
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_task_embeddings.rs
+++ /dev/null
@@ -1,581 +0,0 @@
-//! One-off backfill: populate `task_duplicate_embedding` for existing tasks.
-//!
-//! Duplicate detection (see the `task_dedup` crate) only embeds a task into the
-//! pgvector table when the task is *created*. Tasks that existed before that
-//! feature shipped have no embedding, so new tasks can never match against them.
-//! This binary walks every existing task document and upserts its embedding using
-//! the exact same content shape and model the live pipeline uses
-//! (`task_embedding_content` + `text-embedding-3-small`), so backfilled vectors
-//! are directly comparable to ones written at create time.
-//!
-//! It only writes the vector table (`task_duplicate_embedding`). It does NOT run
-//! duplicate detection or create `task_duplicate_match` rows.
-//!
-//! ## Production-scale behavior
-//!
-//! - **Tasks only**: an inner join on `document_sub_type = 'task'` — the same
-//! predicate the dedup pipeline uses — so plain markdown notes are excluded.
-//! - **No double-inserts**: writes go through an upsert keyed on the
-//! `document_id` primary key, so re-runs update rather than duplicate.
-//! - **Cancel / resume**: work is keyset-paginated by `Document.id` and each
-//! batch is upserted as soon as it is embedded. By default (no `--force`) the
-//! query skips tasks that already have an embedding, so a re-run after a
-//! Ctrl-C (or crash) simply continues with whatever is left — no checkpoint
-//! file required.
-//! - **Never poisons the table**: embeddings come from [`OpenAiTaskEmbedder`],
-//! which errors instead of falling back to a local hash vector. On a transient
-//! error (429 / 5xx / network) the batch is retried with backoff and, if it
-//! still fails, left for the next run. On a hard rejection (e.g. an input over
-//! the token limit) the batch is split to isolate and drop only the offending
-//! task. Oversized content is also pre-truncated to stay under the limit.
-//! - **Gentle on dependencies**: bounded concurrency for both lexical-service
-//! reads and OpenAI requests, and many tasks embedded per OpenAI request.
-//!
-//! ## Running
-//!
-//! Requires the same environment a `document_storage_service` deploy has:
-//! `DATABASE_URL`, `LEXICAL_SERVICE_URL`, `INTERNAL_API_SECRET_KEY`, AWS creds
-//! (to resolve the internal secret), and `OPENAI_API_KEY` (required — the
-//! backfill refuses to run without it).
-//!
-//! ```bash
-//! # dry run — counts tasks that would be embedded, touches nothing else
-//! cargo run -p document_storage_service --bin backfill_task_embeddings -- --dry-run
-//!
-//! # real backfill (idempotent: skips tasks that already have an embedding)
-//! cargo run -p document_storage_service --bin backfill_task_embeddings
-//!
-//! # re-embed every task, with tuned throughput
-//! cargo run -p document_storage_service --bin backfill_task_embeddings -- \
-//! --force --batch-size 96 --request-concurrency 4 --lexical-concurrency 16
-//! ```
-
-use std::future::Future;
-use std::pin::Pin;
-use std::sync::Arc;
-use std::sync::atomic::{AtomicUsize, Ordering};
-
-use anyhow::Context;
-use clap::Parser;
-use futures::StreamExt;
-use lexical_client::LexicalClient;
-use macro_entrypoint::MacroEntrypoint;
-use macro_env::Environment;
-use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use secretsmanager_client::SecretManager;
-use sqlx::PgPool;
-use sqlx::postgres::PgPoolOptions;
-use task_dedup::TaskDedupConfig;
-use task_dedup::domain::service::task_embedding_content;
-use task_dedup::outbound::embedding::{EmbedError, OpenAiTaskEmbedder};
-use task_dedup::outbound::postgres::{PgTaskDedupRepo, TaskEmbeddingUpsert};
-
-/// Backfills task embeddings into the `task_duplicate_embedding` pgvector table.
-#[derive(Debug, clap::Parser)]
-#[command(name = "backfill_task_embeddings", about, long_about = None)]
-struct Args {
- /// Re-embed every task, including ones that already have an embedding.
- #[arg(long)]
- force: bool,
- /// Count work without fetching content, embedding, or writing.
- #[arg(long)]
- dry_run: bool,
- /// Optional cap on the number of tasks processed (handy for a smoke test).
- #[arg(long)]
- limit: Option<usize>,
- /// Rows fetched from Postgres per keyset page.
- #[arg(long, default_value_t = 500, value_parser = clap::value_parser!(i64).range(1..))]
- page_size: i64,
- /// Task texts sent per OpenAI embeddings request.
- #[arg(long, default_value_t = 96, value_parser = positive_usize)]
- batch_size: usize,
- /// Concurrent OpenAI embedding requests.
- #[arg(long, default_value_t = 4, value_parser = positive_usize)]
- request_concurrency: usize,
- /// Concurrent lexical-service markdown fetches.
- #[arg(long, default_value_t = 16, value_parser = positive_usize)]
- lexical_concurrency: usize,
- /// Max characters of embedding content (keeps inputs under the token limit).
- //
- // text-embedding-3-small caps at 8191 tokens; ~4 chars/token, so 24k chars
- // (~6k tokens) stays comfortably under the limit.
- #[arg(long, default_value_t = 24_000, value_parser = positive_usize)]
- max_content_chars: usize,
-}
-
-/// Parses a `usize` and rejects zero (clap's `RangedU64ValueParser` doesn't
-/// cover `usize`).
-fn positive_usize(value: &str) -> Result<usize, String> {
- let parsed: usize = value
- .parse()
- .map_err(|_| format!("`{value}` is not an integer"))?;
- if parsed == 0 {
- return Err("value must be greater than 0".to_string());
- }
- Ok(parsed)
-}
-
-/// A task document selected for embedding.
-struct TaskRow {
- document_id: String,
- name: String,
-}
-
-/// A task whose body has been fetched and is ready to embed. `truncated` is only
-/// counted once the embedding is actually written, so it stays a subset of the
-/// embedded total.
-#[derive(Clone)]
-struct Prepared {
- upsert: TaskEmbeddingUpsert,
- truncated: bool,
-}
-
-/// Running tallies for the backfill. Failures are split by whether a re-run can
-/// fix them (`*_failed` / `*_retryable`) or not (`embed_dropped`), so the final
-/// report shows whether the approach actually works rather than lumping all
-/// failures together.
-#[derive(Default)]
-struct Counters {
- /// Embeddings successfully written.
- embedded: AtomicUsize,
- /// Successful embeddings whose content was truncated (subset of `embedded`).
- truncated: AtomicUsize,
- /// Couldn't fetch the task body from lexical-service. Retryable on re-run.
- lexical_failed: AtomicUsize,
- /// OpenAI transient errors (429/5xx) exhausted retries. Retryable on re-run.
- embed_retryable: AtomicUsize,
- /// OpenAI hard-rejected the input (e.g. over the token limit). A re-run will
- /// NOT fix these — this is the bucket that signals "can't embed this task".
- embed_dropped: AtomicUsize,
- /// Embedding produced but the DB upsert failed. Retryable on re-run.
- upsert_failed: AtomicUsize,
-}
-
-impl Counters {
- /// Failures that a re-run is expected to resolve.
- fn retryable(&self) -> usize {
- self.lexical_failed.load(Ordering::Relaxed)
- + self.embed_retryable.load(Ordering::Relaxed)
- + self.upsert_failed.load(Ordering::Relaxed)
- }
-}
-
-/// Formats `n` as a percentage of `total` with one decimal place.
-fn pct(n: usize, total: usize) -> String {
- if total == 0 {
- return "0.0%".to_string();
- }
- format!("{:.1}%", (n as f64 / total as f64) * 100.0)
-}
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
- let args = Args::parse();
- let config = TaskDedupConfig::default();
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be set")?;
- let pool = PgPoolOptions::new()
- .min_connections(2)
- .max_connections((args.request_concurrency as u32 + 2).max(4))
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let backlog = count_pending(&pool, args.force).await?;
- // `--limit` caps how many tasks we process, so cap the reported count too.
- let pending = match args.limit {
- Some(limit) => backlog.min(i64::try_from(limit).unwrap_or(i64::MAX)),
- None => backlog,
- };
- tracing::info!(
- pending,
- force = args.force,
- dry_run = args.dry_run,
- page_size = args.page_size,
- batch_size = args.batch_size,
- request_concurrency = args.request_concurrency,
- lexical_concurrency = args.lexical_concurrency,
- model = %config.embedding_model,
- "task embedding backfill starting"
- );
-
- if args.dry_run {
- tracing::info!(pending, "dry run: would embed this many tasks");
- return Ok(());
- }
-
- // Fail loudly if OpenAI isn't configured — a local fallback embedding would
- // silently poison the vector table.
- let embedder = Arc::new(OpenAiTaskEmbedder::from_env(
- config.embedding_model.clone(),
- )?);
- let lexical_client = Arc::new(build_lexical_client().await?);
- let repo = Arc::new(PgTaskDedupRepo::new(pool.clone()));
- let counters = Arc::new(Counters::default());
-
- let mut cursor = String::new();
- let mut processed = 0usize;
- loop {
- let remaining = args.limit.map(|limit| limit.saturating_sub(processed));
- if remaining == Some(0) {
- break;
- }
- let page_size = match remaining {
- Some(remaining) => args.page_size.min(remaining as i64),
- None => args.page_size,
- };
-
- let page = fetch_page(&pool, args.force, &cursor, page_size).await?;
- if page.is_empty() {
- break;
- }
- cursor = page.last().expect("page is non-empty").document_id.clone();
- processed += page.len();
-
- // 1. Fetch each task's markdown body (bounded concurrency).
- let prepared: Vec<Prepared> = futures::stream::iter(page)
- .map(|task| {
- let lexical_client = lexical_client.clone();
- let counters = counters.clone();
- let max_chars = args.max_content_chars;
- async move {
- match fetch_task_markdown(&lexical_client, &task.document_id).await {
- Ok(markdown) => {
- let (content, truncated) =
- build_content(&task.name, &markdown, max_chars);
- Some(Prepared {
- upsert: TaskEmbeddingUpsert {
- document_id: task.document_id,
- content,
- embedding: Vec::new(),
- },
- truncated,
- })
- }
- Err(error) => {
- counters.lexical_failed.fetch_add(1, Ordering::Relaxed);
- tracing::warn!(
- error = ?error,
- document_id = %task.document_id,
- "failed to fetch task markdown; will retry on next run"
- );
- None
- }
- }
- }
- })
- .buffer_unordered(args.lexical_concurrency)
- .filter_map(|item| async move { item })
- .collect()
- .await;
-
- // 2. Embed + upsert in batches (bounded concurrency).
- let model = config.embedding_model.clone();
- futures::stream::iter(prepared.chunks(args.batch_size).map(<[_]>::to_vec))
- .map(|batch| {
- let embedder = embedder.clone();
- let repo = repo.clone();
- let counters = counters.clone();
- let model = model.clone();
- async move { embed_and_upsert(&embedder, &repo, &model, batch, &counters).await }
- })
- .buffer_unordered(args.request_concurrency)
- .collect::<Vec<()>>()
- .await;
-
- let embedded = counters.embedded.load(Ordering::Relaxed);
- tracing::info!(
- processed,
- embedded,
- success_rate = %pct(embedded, processed),
- lexical_failed = counters.lexical_failed.load(Ordering::Relaxed),
- embed_retryable = counters.embed_retryable.load(Ordering::Relaxed),
- embed_dropped = counters.embed_dropped.load(Ordering::Relaxed),
- upsert_failed = counters.upsert_failed.load(Ordering::Relaxed),
- "backfill progress"
- );
- }
-
- report_summary(processed, &counters);
- Ok(())
-}
-
-/// Emits a final breakdown so the operator can see the failure rate as a cut of
-/// total tasks and judge whether the backfill is working.
-fn report_summary(processed: usize, counters: &Counters) {
- let embedded = counters.embedded.load(Ordering::Relaxed);
- let truncated = counters.truncated.load(Ordering::Relaxed);
- let lexical_failed = counters.lexical_failed.load(Ordering::Relaxed);
- let embed_retryable = counters.embed_retryable.load(Ordering::Relaxed);
- let embed_dropped = counters.embed_dropped.load(Ordering::Relaxed);
- let upsert_failed = counters.upsert_failed.load(Ordering::Relaxed);
- let retryable = counters.retryable();
-
- tracing::info!(
- total = processed,
- embedded,
- success_rate = %pct(embedded, processed),
- truncated,
- truncated_rate = %pct(truncated, processed),
- lexical_failed,
- embed_retryable,
- upsert_failed,
- retryable_failed = retryable,
- retryable_rate = %pct(retryable, processed),
- embed_dropped,
- dropped_rate = %pct(embed_dropped, processed),
- "task embedding backfill complete"
- );
-
- // Human-readable block — easy to eyeball the failure cut at the end of a run.
- tracing::info!(
- "{}",
- format!(
- concat!(
- "\n==== task embedding backfill summary ====\n",
- " total tasks processed : {total}\n",
- " embedded (success) : {embedded} ({embedded_pct})\n",
- " of which truncated : {truncated} ({truncated_pct})\n",
- " retryable failures : {retryable} ({retryable_pct}) <- re-run the backfill to clear these\n",
- " - lexical fetch : {lexical_failed}\n",
- " - openai transient : {embed_retryable}\n",
- " - db upsert : {upsert_failed}\n",
- " permanent drops : {embed_dropped} ({dropped_pct}) <- re-run will NOT fix; content rejected by openai\n",
- "========================================="
- ),
- total = processed,
- embedded = embedded,
- embedded_pct = pct(embedded, processed),
- truncated = truncated,
- truncated_pct = pct(truncated, processed),
- retryable = retryable,
- retryable_pct = pct(retryable, processed),
- lexical_failed = lexical_failed,
- embed_retryable = embed_retryable,
- upsert_failed = upsert_failed,
- embed_dropped = embed_dropped,
- dropped_pct = pct(embed_dropped, processed),
- )
- );
-
- if retryable > 0 {
- tracing::warn!(
- retryable,
- "{} of tasks were left un-embedded by transient errors; re-run the backfill to retry them",
- pct(retryable, processed),
- );
- }
- if embed_dropped > 0 {
- tracing::warn!(
- embed_dropped,
- "{} of tasks could not be embedded at all (openai rejected the content); a re-run will not fix these",
- pct(embed_dropped, processed),
- );
- }
-}
-
-/// Counts tasks that would be embedded (used for `--dry-run` and the start log).
-async fn count_pending(pool: &PgPool, force: bool) -> anyhow::Result<i64> {
- let count = sqlx::query_scalar!(
- r#"
- SELECT COUNT(*) AS "count!"
- FROM "Document" d
- JOIN document_sub_type dst
- ON dst.document_id = d.id AND dst.sub_type = 'task'
- LEFT JOIN task_duplicate_embedding e ON e.document_id = d.id
- WHERE d."deletedAt" IS NULL
- AND ($1::bool OR e.document_id IS NULL)
- "#,
- force,
- )
- .fetch_one(pool)
- .await
- .context("failed to count task documents")?;
- Ok(count)
-}
-
-/// Fetches one keyset page of task documents ordered by id.
-async fn fetch_page(
- pool: &PgPool,
- force: bool,
- cursor: &str,
- page_size: i64,
-) -> anyhow::Result<Vec<TaskRow>> {
- let rows = sqlx::query!(
- r#"
- SELECT d.id AS "document_id!", d.name
- FROM "Document" d
- JOIN document_sub_type dst
- ON dst.document_id = d.id AND dst.sub_type = 'task'
- LEFT JOIN task_duplicate_embedding e ON e.document_id = d.id
- WHERE d."deletedAt" IS NULL
- AND ($1::bool OR e.document_id IS NULL)
- AND d.id > $2
- ORDER BY d.id
- LIMIT $3
- "#,
- force,
- cursor,
- page_size,
- )
- .fetch_all(pool)
- .await
- .context("failed to fetch task page")?;
-
- Ok(rows
- .into_iter()
- .map(|row| TaskRow {
- document_id: row.document_id,
- name: row.name,
- })
- .collect())
-}
-
-/// Builds the production embedding content and truncates it to `max_chars`.
-/// Returns the content and whether it was truncated.
-fn build_content(name: &str, markdown: &str, max_chars: usize) -> (String, bool) {
- let content = task_embedding_content(name, markdown);
- if content.chars().count() <= max_chars {
- return (content, false);
- }
- let truncated: String = content.chars().take(max_chars).collect();
- (truncated, true)
-}
-
-/// Embeds a batch and upserts the successful results, updating counters.
-async fn embed_and_upsert(
- embedder: &OpenAiTaskEmbedder,
- repo: &PgTaskDedupRepo,
- model: &str,
- mut batch: Vec<Prepared>,
- counters: &Counters,
-) {
- let contents: Vec<String> = batch
- .iter()
- .map(|item| item.upsert.content.clone())
- .collect();
- // embed_resilient records embed_retryable / embed_dropped for None slots.
- let embeddings = embed_resilient(embedder, &contents, counters).await;
-
- let mut upserts = Vec::with_capacity(batch.len());
- let mut truncated = 0usize;
- for (item, embedding) in batch.drain(..).zip(embeddings) {
- if let Some(embedding) = embedding {
- if item.truncated {
- truncated += 1;
- }
- upserts.push(TaskEmbeddingUpsert {
- embedding,
- ..item.upsert
- });
- }
- }
-
- if upserts.is_empty() {
- return;
- }
-
- match repo.bulk_upsert_embeddings(model, &upserts).await {
- Ok(()) => {
- counters
- .embedded
- .fetch_add(upserts.len(), Ordering::Relaxed);
- // Counted only now, so `truncated` stays a subset of `embedded`.
- counters.truncated.fetch_add(truncated, Ordering::Relaxed);
- }
- Err(error) => {
- // The rows weren't written, so count them as retryable for a re-run.
- counters
- .upsert_failed
- .fetch_add(upserts.len(), Ordering::Relaxed);
- tracing::error!(error = ?error, count = upserts.len(), "failed to upsert embeddings");
- }
- }
-}
-
-/// Embeds `contents`, returning one slot per input: `Some(vector)` on success,
-/// `None` for inputs that couldn't be embedded this run.
-///
-/// The embedder ([`OpenAiTaskEmbedder`]) already retries rate limits and 5xx
-/// responses with exponential backoff. A remaining [`EmbedError::Transient`]
-/// leaves the whole batch for the next run; an [`EmbedError::Fatal`] (e.g. an
-/// oversized input) splits the batch to isolate and drop only the offending
-/// input(s).
-type EmbedFuture<'a> = Pin<Box<dyn Future<Output = Vec<Option<Vec<f32>>>> + Send + 'a>>;
-
-fn embed_resilient<'a>(
- embedder: &'a OpenAiTaskEmbedder,
- contents: &'a [String],
- counters: &'a Counters,
-) -> EmbedFuture<'a> {
- Box::pin(async move {
- if contents.is_empty() {
- return Vec::new();
- }
- match embedder.embed_batch(contents).await {
- Ok(vectors) => vectors.into_iter().map(Some).collect(),
- Err(EmbedError::Transient(error)) => {
- tracing::warn!(
- error,
- "embeddings batch failed transiently; leaving for next run"
- );
- counters
- .embed_retryable
- .fetch_add(contents.len(), Ordering::Relaxed);
- vec![None; contents.len()]
- }
- Err(EmbedError::Fatal(error)) => {
- if contents.len() == 1 {
- counters.embed_dropped.fetch_add(1, Ordering::Relaxed);
- tracing::warn!(
- error,
- "dropping a task whose content OpenAI rejected (likely over the token limit)"
- );
- return vec![None];
- }
- let mid = contents.len() / 2;
- let mut left = embed_resilient(embedder, &contents[..mid], counters).await;
- let right = embed_resilient(embedder, &contents[mid..], counters).await;
- left.extend(right);
- left
- }
- }
- })
-}
-
-/// Reconstructs a task's markdown body from lexical-service's AI parse, joining
-/// each node's human-readable content. This is the same source `read_content`
-/// uses to feed markdown task bodies to the model.
-async fn fetch_task_markdown(
- lexical_client: &LexicalClient,
- document_id: &str,
-) -> anyhow::Result<String> {
- let parsed = lexical_client.parse_markdown_for_ai(document_id).await?;
- Ok(parsed
- .data
- .into_iter()
- .map(|node| node.content)
- .collect::<Vec<_>>()
- .join("\n"))
-}
-
-/// Builds the lexical-service client, resolving the internal auth secret exactly
-/// like `main.rs` does so this works against local, develop, and prod.
-async fn build_lexical_client() -> anyhow::Result<LexicalClient> {
- let lexical_service_url =
- std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be set")?;
- let env = Environment::new_or_prod();
- let aws_config = macro_aws_config::get_macro_aws_config().await;
- let secretsmanager_client = secretsmanager_client::SecretsManager::new(
- aws_sdk_secretsmanager::Client::new(&aws_config),
- );
- let internal_api_secret = secretsmanager_client
- .get_maybe_secret_value(env, InternalApiSecretKey::new()?)
- .await
- .context("unable to resolve internal api secret")?;
- Ok(LexicalClient::new(
- internal_api_secret.as_ref().to_string(),
- lexical_service_url,
- ))
-}
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index ea76eefc44..9d4b6c90f3 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -71,6 +71,12 @@ maybe_env_var! {
pub struct LivekitTranscriptionAgentName;
}
+maybe_env_var! {
+ /// OpenAI API key used to generate task embeddings. Optional — task
+ /// embeddings will fail until it is configured.
+ pub struct OpenaiApiKey;
+}
+
maybe_env_var! {
/// Shared secret for internal call endpoints (e.g. transcript ingestion from the agent).
pub struct InternalCallSecret;
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 0e3411e28b..65a54d024e 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -59,6 +59,7 @@ use email::{
domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},
outbound::EmailPgRepo,
};
+use embedding::embedding_provider::openai::TextEmbedding3Small;
use foreign_entity::{
domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
@@ -90,8 +91,10 @@ use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImp
use task_dedup::{
TaskDedupConfig, TaskDedupService,
outbound::{
- connection_gateway::ConnectionGatewayTaskDedupNotifier, embedding::OpenAiTaskEmbedder,
- judge::AgentDuplicateJudge, postgres::PgTaskDedupRepo, reranker::NoOpTaskReranker,
+ connection_gateway::ConnectionGatewayTaskDedupNotifier,
+ judge::AgentDuplicateJudge,
+ postgres::{PgTaskMatchRepo, PgTaskVectorDb},
+ reranker::NoOpReranker,
},
};
@@ -573,17 +576,33 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = Arc::new(sqs_client);
let conn_gateway_client = Arc::new(conn_gateway_client);
let task_dedup_config = TaskDedupConfig::default();
+ // Local reads the OpenAI key from the environment; dev/prod pull the same
+ // `openai-key` secret the backfill entrypoint uses. Fail fast if it's empty
+ // so the service never starts with a broken task-dedup embedder.
+ let openai_api_key = match config.environment {
+ Environment::Local => config::OpenaiApiKey::new()
+ .map(|v| v.as_ref().to_owned())
+ .unwrap_or_default(),
+ _ => secretsmanager_client
+ .get_secret_value("openai-key")
+ .await
+ .context("unable to get OpenAI embedding secret")?
+ .to_string(),
+ };
+ anyhow::ensure!(
+ !openai_api_key.trim().is_empty(),
+ "OpenAI API key is required for task dedup embeddings",
+ );
let task_dedup_service = Arc::new(TaskDedupService::new(
task_dedup_config.clone(),
- Arc::new(PgTaskDedupRepo::new(db.clone())),
- Arc::new(OpenAiTaskEmbedder::new(
- task_dedup_config.embedding_model.clone(),
- )),
- Arc::new(NoOpTaskReranker),
+ TextEmbedding3Small::new(openai_api_key),
+ PgTaskVectorDb::new(db.clone()),
+ NoOpReranker,
Arc::new(AgentDuplicateJudge::new()),
Arc::new(ConnectionGatewayTaskDedupNotifier::new(
conn_gateway_client.clone(),
)),
+ Arc::new(PgTaskMatchRepo::new(db.clone())),
));
let channels_repo = PgChannelsRepo::new(db.clone());
let bots_repo = bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone());
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index 2bfb29639b..ad34be360a 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -41,7 +41,7 @@ use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use sqlx::PgPool;
-use task_dedup::TaskDedupService;
+use task_dedup::PgTaskDedupService;
#[cfg(feature = "document_create")]
use self::create_markdown::create_markdown_handler;
@@ -110,7 +110,7 @@ pub struct DocumentRouterState<T, Svc> {
/// The database pool (used by middleware for document lookups).
pub pool: PgPool,
/// Task duplicate detection service.
- pub task_dedup_service: Arc<TaskDedupService>,
+ pub task_dedup_service: Arc<PgTaskDedupService>,
/// Backend-owned document creation use case.
#[cfg(feature = "document_create_adapters")]
pub creator: DefaultDocumentCreator<T>,
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs b/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs
index ec8ae15275..7c48676b11 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs
@@ -16,7 +16,9 @@ use model::response::GenericSuccessResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::access_level::{OwnerAccessLevel, ViewAccessLevel};
use serde::{Deserialize, Serialize};
-use task_dedup::{NewTask, TaskDedupError, TaskDedupService, TaskDuplicate, TaskSimilarityResult};
+use task_dedup::{
+ NewTask, PgTaskDedupService, TaskDedupError, TaskDuplicate, TaskSimilarityResult,
+};
use uuid::Uuid;
use super::{DocumentRouterState, Params};
@@ -175,7 +177,7 @@ pub async fn delete_this_duplicate_task_handler<T: DocumentService, Svc: EntityA
}
/// Spawn duplicate detection for a newly created task.
-pub fn spawn_task_duplicate_detection(task_dedup_service: Arc<TaskDedupService>, task: NewTask) {
+pub fn spawn_task_duplicate_detection(task_dedup_service: Arc<PgTaskDedupService>, task: NewTask) {
tokio::spawn(async move {
let _ = task_dedup_service
.detect_new_task(task)
diff --git a/rust/cloud-storage/embedding/.gitignore b/rust/cloud-storage/embedding/.gitignore
new file mode 100644
index 0000000000..ea8c4bf7f3
--- /dev/null
+++ b/rust/cloud-storage/embedding/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/rust/cloud-storage/embedding/Cargo.toml b/rust/cloud-storage/embedding/Cargo.toml
new file mode 100644
index 0000000000..fd8ff0be14
--- /dev/null
+++ b/rust/cloud-storage/embedding/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "embedding"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+anyhow = { workspace = true }
+async-openai = { workspace = true }
diff --git a/rust/cloud-storage/embedding/src/embedding_provider/mod.rs b/rust/cloud-storage/embedding/src/embedding_provider/mod.rs
new file mode 100644
index 0000000000..a55ab072bb
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/embedding_provider/mod.rs
@@ -0,0 +1,3 @@
+//! Concrete [`EmbeddingModel`](crate::EmbeddingModel) implementations.
+
+pub mod openai;
diff --git a/rust/cloud-storage/embedding/src/embedding_provider/openai.rs b/rust/cloud-storage/embedding/src/embedding_provider/openai.rs
new file mode 100644
index 0000000000..3239288676
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/embedding_provider/openai.rs
@@ -0,0 +1,109 @@
+//! [`EmbeddingModel`] backed by OpenAI's [embeddings API].
+//!
+//! [embeddings API]: https://platform.openai.com/docs/guides/embeddings
+
+use std::borrow::Cow;
+
+use anyhow::Context;
+use async_openai::{
+ Client,
+ config::OpenAIConfig,
+ types::embeddings::{CreateEmbeddingRequestArgs, EmbeddingInput},
+};
+
+use crate::{Embeddable, Embedding, EmbeddingModel, LabeledEmbedding, SearchKey};
+
+/// Number of dimensions produced by [`EMBEDDING_MODEL`].
+pub const DIMS: usize = 1536;
+
+/// The OpenAI model used to produce embeddings.
+pub const EMBEDDING_MODEL: &str = "text-embedding-3-small";
+
+/// An [`EmbeddingModel`] that calls OpenAI's embeddings API.
+pub struct TextEmbedding3Small {
+ client: Client<OpenAIConfig>,
+}
+
+impl TextEmbedding3Small {
+ /// Creates an embedder authenticated with `api_key`.
+ ///
+ /// The key is used directly — nothing is read from the environment.
+ pub fn new(api_key: impl Into<String>) -> Self {
+ let config = OpenAIConfig::new().with_api_key(api_key);
+ Self {
+ client: Client::with_config(config),
+ }
+ }
+
+ /// Creates an embedder from a pre-configured OpenAI client.
+ ///
+ /// Use this to customize the API base, organization, HTTP client, etc.
+ pub fn with_client(client: Client<OpenAIConfig>) -> Self {
+ Self { client }
+ }
+}
+
+impl EmbeddingModel<DIMS> for TextEmbedding3Small {
+ async fn embed(
+ &self,
+ content: &(dyn Embeddable + Sync),
+ ) -> anyhow::Result<Vec<LabeledEmbedding<'static, DIMS>>> {
+ // Take ownership of the content up front: results are `'static`, and we
+ // must not hold a borrow of `content` across the await point.
+ let fields: Vec<(SearchKey, String)> = content
+ .embedding_content()
+ .into_iter()
+ .map(|(key, text)| (key, text.into_owned()))
+ .collect();
+
+ // OpenAI rejects empty input, so short-circuit when there's nothing to embed.
+ if fields.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let request = CreateEmbeddingRequestArgs::default()
+ .model(EMBEDDING_MODEL)
+ .input(EmbeddingInput::StringArray(
+ fields.iter().map(|(_, text)| text.clone()).collect(),
+ ))
+ .dimensions(DIMS as u32)
+ .build()?;
+
+ let response = self.client.embeddings().create(request).await?;
+
+ if response.data.len() != fields.len() {
+ anyhow::bail!(
+ "OpenAI returned {} embeddings for {} inputs",
+ response.data.len(),
+ fields.len(),
+ );
+ }
+
+ // Reassemble in input order using each embedding's `index`; the API does
+ // not guarantee response ordering.
+ let mut vectors: Vec<Option<Vec<f32>>> = (0..fields.len()).map(|_| None).collect();
+ for embedding in response.data {
+ let index = embedding.index as usize;
+ let slot = vectors
+ .get_mut(index)
+ .with_context(|| format!("OpenAI returned out-of-range index {index}"))?;
+ *slot = Some(embedding.embedding);
+ }
+
+ fields
+ .into_iter()
+ .zip(vectors)
+ .map(|((search_key, content), vector)| {
+ let vector = vector.context("OpenAI omitted an embedding for an input")?;
+ let embedding: Embedding<DIMS> = vector.try_into().map_err(|v: Vec<f32>| {
+ anyhow::anyhow!("expected {DIMS} dimensions, got {}", v.len())
+ })?;
+ Ok(LabeledEmbedding {
+ search_key,
+ content: Cow::Owned(content),
+ embedding,
+ })
+ })
+ .collect()
+ }
+}
diff --git a/rust/cloud-storage/embedding/src/entity/mod.rs b/rust/cloud-storage/embedding/src/entity/mod.rs
new file mode 100644
index 0000000000..0d744ed386
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/entity/mod.rs
@@ -0,0 +1,3 @@
+//! Embeddable impls for entities
+mod task;
+pub use task::*;
diff --git a/rust/cloud-storage/embedding/src/entity/task.rs b/rust/cloud-storage/embedding/src/entity/task.rs
new file mode 100644
index 0000000000..3ea81ca9fd
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/entity/task.rs
@@ -0,0 +1,69 @@
+//! Task embedding
+use crate::Embeddable;
+use std::borrow::Cow;
+
+static TITLE: &str = "title";
+static BODY: &str = "body";
+
+/// A task
+pub struct Task<'a> {
+ /// task name
+ pub title: Cow<'a, str>,
+ /// task body
+ pub body: Cow<'a, str>,
+}
+
+impl<'a> Embeddable for Task<'a> {
+ fn embedding_content(&self) -> Vec<(crate::SearchKey, crate::Content<'a>)> {
+ let mut fields = Vec::with_capacity(2);
+ if !self.title.trim().is_empty() {
+ fields.push((TITLE, self.title.clone()));
+ }
+ if !self.body.trim().is_empty() {
+ fields.push((BODY, self.body.clone()));
+ }
+ fields
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn keys_and_text(task: &Task<'_>) -> Vec<(&'static str, String)> {
+ task.embedding_content()
+ .into_iter()
+ .map(|(key, text)| (key, text.into_owned()))
+ .collect()
+ }
+
+ #[test]
+ fn embeds_title_when_task_has_no_body() {
+ let task = Task {
+ title: Cow::Borrowed("Title"),
+ body: Cow::Borrowed(""),
+ };
+
+ assert_eq!(keys_and_text(&task), vec![("title", "Title".to_string())]);
+ }
+
+ #[test]
+ fn embeds_body_when_task_has_no_title() {
+ let task = Task {
+ title: Cow::Borrowed(""),
+ body: Cow::Borrowed("Body"),
+ };
+
+ assert_eq!(keys_and_text(&task), vec![("body", "Body".to_string())]);
+ }
+
+ #[test]
+ fn embeds_nothing_when_task_has_no_title_or_body() {
+ let task = Task {
+ title: Cow::Borrowed(" "),
+ body: Cow::Borrowed("\n\t"),
+ };
+
+ assert!(keys_and_text(&task).is_empty());
+ }
+}
diff --git a/rust/cloud-storage/embedding/src/lib.rs b/rust/cloud-storage/embedding/src/lib.rs
new file mode 100644
index 0000000000..88a206e878
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/lib.rs
@@ -0,0 +1,142 @@
+//! Traits and types for embedding content, storing it in a vector database, and
+//! reranking search results.
+#![deny(missing_docs)]
+
+use std::borrow::Cow;
+
+pub mod embedding_provider;
+pub mod entity;
+#[cfg(test)]
+mod test;
+
+/// Identifies a distinct embeddable field within a piece of content.
+///
+/// A single value can expose multiple searchable fields (e.g. `"title"` and
+/// `"body"`); the key labels which field a given [`Content`] or [`Embedding`]
+/// corresponds to.
+pub type SearchKey = &'static str;
+
+/// Text to be embedded or searched, borrowed or owned.
+pub type Content<'a> = Cow<'a, str>;
+
+/// A fixed-size embedding vector of `DIMS` dimensions.
+pub type Embedding<const DIMS: usize> = [f32; DIMS];
+
+/// An embedding paired with the [`SearchKey`] identifying which field it
+/// represents.
+///
+/// Used as the query input to [`VectorDb::cosine_search`], where no source text
+/// is available. See [`LabeledEmbedding`] when the originating [`Content`] is
+/// also known.
+pub struct KeyedEmbedding<const DIMS: usize> {
+ /// Identifies which field this embedding represents.
+ pub search_key: SearchKey,
+ /// The embedding vector.
+ pub embedding: Embedding<DIMS>,
+}
+
+/// A single embedded field: its embedding paired with the [`SearchKey`] and
+/// [`Content`] it was produced from.
+pub struct LabeledEmbedding<'a, const DIMS: usize> {
+ /// Identifies which field of the source content this embedding represents.
+ pub search_key: SearchKey,
+ /// The text that was embedded.
+ pub content: Content<'a>,
+ /// The embedding vector for [`content`](Self::content).
+ pub embedding: Embedding<DIMS>,
+}
+
+/// A stored embedding matched by a search, together with its similarity to the
+/// query.
+pub struct Match<const DIMS: usize> {
+ /// similarity to the query
+ pub score: f32,
+ /// The matched embedding and the content it was produced from.
+ pub embedding: LabeledEmbedding<'static, DIMS>,
+}
+
+/// The matches belonging to a single entity, grouped under its metadata.
+pub struct SearchResults<T, const DIMS: usize> {
+ /// Caller-supplied data identifying the matched entity (e.g. its document id).
+ pub metadata: T,
+ /// The entity's matching embeddings, ordered from most to least similar.
+ pub matches: Vec<Match<DIMS>>,
+}
+
+/// A type whose content can be turned into embeddable fields.
+pub trait Embeddable {
+ /// Returns the embeddable fields of this value, each keyed by its
+ /// [`SearchKey`].
+ fn embedding_content<'a>(&'a self) -> Vec<(SearchKey, Content<'a>)>;
+}
+
+/// A model that turns [`Embeddable`] content into `DIMS`-dimensional embeddings.
+pub trait EmbeddingModel<const DIMS: usize> {
+ /// Embeds each field of `content`, returning one [`LabeledEmbedding`] per
+ /// [`SearchKey`] the content exposes.
+ fn embed(
+ &self,
+ content: &(dyn Embeddable + Sync),
+ ) -> impl Future<Output = anyhow::Result<Vec<LabeledEmbedding<'static, DIMS>>>> + Send;
+}
+
+/// A candidate paired with the relevance score a [`RerankModel`] assigned it.
+///
+/// Higher scores indicate greater relevance to the query.
+pub struct Reranked<T> {
+ /// The payload carried through from the original candidate.
+ pub item: T,
+ /// Relevance score for this candidate; higher is more relevant.
+ pub score: f32,
+}
+
+/// A model that reorders a set of candidates by their relevance to a query.
+///
+/// Unlike [`EmbeddingModel`], a reranker scores the query directly against each
+/// candidate's content (e.g. a cross-encoder) rather than comparing
+/// precomputed embeddings. It is typically used as a refinement step over the
+/// coarse [`SearchResults`] returned by [`VectorStore::cosine_search`], which it
+/// consumes directly.
+pub trait RerankModel<const DIMS: usize> {
+ /// Score each candidate against `query` using the [`Content`] of its matched
+ /// fields, returning the candidates ordered from most to least relevant.
+ ///
+ /// Each candidate is supplied as the [`SearchResults`] produced by
+ /// [`VectorStore::cosine_search`]; its `metadata` (e.g. the source entity's
+ /// id) is carried through to the corresponding [`Reranked`] result
+ /// untouched.
+ fn rerank<'a, T: Send>(
+ &self,
+ query: Content<'a>,
+ candidates: Vec<SearchResults<T, DIMS>>,
+ ) -> impl Future<Output = anyhow::Result<Vec<Reranked<T>>>> + Send;
+}
+
+/// A store of `DIMS`-dimensional embeddings supporting upserts and similarity
+/// search.
+pub trait VectorStore<const DIMS: usize> {
+ /// Error returned by the store's operations.
+ type Error: Send;
+ /// Caller-supplied data associated with a set of embeddings and returned by
+ /// searches (e.g. the source document's identifier).
+ type Metadata: Send;
+ /// caller supplied search parameters
+ /// eg: limit, user, team, etc
+ type SearchParameters: Send;
+
+ /// Inserts or updates the `embeddings`, associating them with `metadata`.
+ fn upsert_embeddings<'a>(
+ &self,
+ metadata: Self::Metadata,
+ embeddings: Vec<LabeledEmbedding<'a, DIMS>>,
+ ) -> impl Future<Output = Result<(), Self::Error>> + Send;
+
+ /// Returns up to `limit` entities whose stored embeddings are most similar
+ /// to `query` by cosine similarity, each grouped into a [`SearchResults`]
+ /// and ordered from most to least similar.
+ fn cosine_search(
+ &self,
+ query: Vec<KeyedEmbedding<DIMS>>,
+ params: Self::SearchParameters,
+ ) -> impl Future<Output = Result<Vec<SearchResults<Self::Metadata, DIMS>>, Self::Error>> + Send;
+}
diff --git a/rust/cloud-storage/embedding/src/test.rs b/rust/cloud-storage/embedding/src/test.rs
new file mode 100644
index 0000000000..15a318bcbb
--- /dev/null
+++ b/rust/cloud-storage/embedding/src/test.rs
@@ -0,0 +1,4 @@
+#[test]
+fn meaningless_test_to_make_ci_pass() {
+ assert!(true)
+}
diff --git a/rust/cloud-storage/lexical_client/src/parse_markdown.rs b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
index c611de6bbb..e3efc8e985 100644
--- a/rust/cloud-storage/lexical_client/src/parse_markdown.rs
+++ b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
@@ -23,6 +23,11 @@ struct MarkdownSnapshotRequest<'a> {
markdown: &'a str,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+struct MarkdownResponse {
+ data: String,
+}
+
impl From<LexicalResponseItem> for MarkdownParseResult {
fn from(result: LexicalResponseItem) -> MarkdownParseResult {
MarkdownParseResult {
@@ -52,6 +57,14 @@ impl LexicalClient {
Ok(data.data.into_iter().map(Into::into).collect())
}
+ /// Fetches the full document rendered as a single plain markdown string.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn get_markdown(&self, document_id: &str) -> Result<String> {
+ let url = format!("{}/markdown/{}", self.url, document_id);
+ let response: MarkdownResponse = self.get_json(&url).await?;
+ Ok(response.data)
+ }
+
#[tracing::instrument(skip(self), err)]
pub async fn parse_markdown_for_ai(&self, document_id: &str) -> Result<CognitionResponseData> {
let url = format!("{}/cognition/{}", self.url, document_id);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260602152450_add_search_key_task_dedup.sql b/rust/cloud-storage/macro_db_client/migrations/20260602152450_add_search_key_task_dedup.sql
new file mode 100644
index 0000000000..b4292a4478
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260602152450_add_search_key_task_dedup.sql
@@ -0,0 +1,40 @@
+-- Support multiple embeddings per task (one per "part", identified by search_key).
+-- Wipe existing rows: the old table held a single whole-task embedding per
+-- document, which is incompatible with the new per-part model. The pipeline
+-- re-embeds everything after this migration.
+TRUNCATE TABLE task_duplicate_embedding;
+
+-- Duplicate detection only ever uses one embedding model, so the per-row model
+-- column is dead weight; drop it.
+ALTER TABLE task_duplicate_embedding
+ DROP COLUMN model;
+
+ALTER TABLE task_duplicate_embedding
+ ADD COLUMN search_key TEXT NOT NULL;
+
+-- Replace the single-column primary key (document_id) with a composite key so a
+-- task can have one row per search_key.
+ALTER TABLE task_duplicate_embedding
+ DROP CONSTRAINT task_duplicate_embedding_pkey,
+ ADD PRIMARY KEY (document_id, search_key);
+
+-- Supports vector queries filtered by part, e.g.
+-- WHERE search_key = $1 ORDER BY embedding <=> $2
+CREATE INDEX task_duplicate_embedding_search_key
+ ON task_duplicate_embedding
+ USING btree (search_key);
+
+-- Swap the IVFFlat vector index (created in 20260528120000) for HNSW. HNSW pairs
+-- better with pgvector 0.8 iterative index scans for filtered queries
+-- (WHERE search_key = ...): the scan keeps pulling candidates from the index
+-- until enough rows pass the filter, preserving recall without a per-search_key
+-- partial index. HNSW also needs no size-based retuning as IVFFlat's `lists`
+-- does. Cheap to build here because the table was just truncated.
+--
+-- Enable iterative scans at query time (off by default), e.g. per transaction:
+-- SET LOCAL hnsw.iterative_scan = relaxed_order;
+DROP INDEX IF EXISTS task_duplicate_embedding_vector_idx;
+
+CREATE INDEX task_duplicate_embedding_vector_idx
+ ON task_duplicate_embedding
+ USING hnsw (embedding vector_cosine_ops);
diff --git a/rust/cloud-storage/task_dedup/Cargo.toml b/rust/cloud-storage/task_dedup/Cargo.toml
index 9408e6a817..d8f31000b5 100644
--- a/rust/cloud-storage/task_dedup/Cargo.toml
+++ b/rust/cloud-storage/task_dedup/Cargo.toml
@@ -4,12 +4,36 @@ name = "task_dedup"
publish = false
version = "0.1.0"
+[[bin]]
+name = "backfill_task_embeddings"
+path = "src/bin/backfill_task_embeddings.rs"
+required-features = ["backfill"]
+
+[features]
+# Pulls in everything the `backfill_task_embeddings` binary needs. The library
+# itself does not require any of these, so default builds stay lean.
+backfill = [
+ "dep:aws-sdk-secretsmanager",
+ "dep:clap",
+ "dep:futures",
+ "dep:lexical_client",
+ "dep:macro_aws_config",
+ "dep:macro_entrypoint",
+ "dep:macro_env",
+ "dep:macro_middleware",
+ "dep:secretsmanager_client",
+ "dep:tokio",
+ "dep:macro_env_var"
+]
+
+default = ["backfill"]
+
[dependencies]
agent = { path = "../agent" }
anyhow = { workspace = true }
-async-openai = { workspace = true }
async-trait = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client" }
+embedding = { path = "../embedding" }
model-entity = { path = "../model-entity" }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -19,6 +43,24 @@ tracing = { workspace = true }
utoipa = { workspace = true }
uuid = { workspace = true }
+# Optional — only compiled in for the `backfill` feature (the backfill binary).
+aws-sdk-secretsmanager = { workspace = true, optional = true }
+clap = { workspace = true, optional = true }
+futures = { workspace = true, optional = true }
+lexical_client = { path = "../lexical_client", optional = true }
+macro_aws_config = { path = "../macro_aws_config", optional = true }
+macro_entrypoint = { path = "../macro_entrypoint", optional = true }
+macro_env = { path = "../macro_env", optional = true }
+macro_middleware = { path = "../macro_middleware", default-features = false, features = [
+ "auth",
+], optional = true }
+secretsmanager_client = { path = "../secretsmanager_client", optional = true }
+tokio = { workspace = true, features = [
+ "macros",
+ "rt-multi-thread",
+], optional = true }
+macro_env_var = { path = "../macro_env_var", optional = true }
+
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
new file mode 100644
index 0000000000..2595b1f2a4
--- /dev/null
+++ b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
@@ -0,0 +1,422 @@
+use std::borrow::Cow;
+use std::io::Write;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use anyhow::Context as _;
+use anyhow::{Result, anyhow, bail};
+use clap::Parser;
+use embedding::embedding_provider::openai::TextEmbedding3Small;
+use embedding::entity::Task;
+use embedding::{EmbeddingModel, VectorStore};
+use futures::StreamExt;
+use lexical_client::LexicalClient;
+use macro_env_var::env_var;
+use secretsmanager_client::{SecretManager, SecretsManager};
+use task_dedup::outbound::postgres::PgTaskVectorDb;
+
+/// Target environment for the backfill.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
+enum Env {
+ /// Local development: read all config from the environment / `.env`.
+ Local,
+ /// Dev environment: resolve DB URL and secrets from AWS.
+ Dev,
+ /// Production environment: resolve DB URL and secrets from AWS.
+ Prod,
+}
+
+impl Env {
+ /// The environment suffix used in per-environment secret names
+ /// (e.g. `macrodb-password-dev`).
+ fn suffix(self) -> &'static str {
+ match self {
+ Env::Local => "local",
+ Env::Dev => "dev",
+ Env::Prod => "prod",
+ }
+ }
+
+ /// Hard-coded lexical-service URL for the environment.
+ fn lexical_service_url(self) -> &'static str {
+ match self {
+ Env::Local => "http://localhost:8096",
+ Env::Dev => "https://lexical-service-dev.macroverse.workers.dev",
+ Env::Prod => "https://lexical-service.macroverse.workers.dev",
+ }
+ }
+}
+
+/// Backfills task embeddings into the `task_duplicate_embedding` pgvector table.
+#[derive(Debug, clap::Parser)]
+#[command(name = "backfill_task_embeddings", about, long_about = None)]
+struct Args {
+ /// Environment to run against: local | dev | prod.
+ #[arg(value_enum)]
+ env: Env,
+ /// Re-embed every task, including ones that already have an embedding.
+ #[arg(long)]
+ force: bool,
+ /// Count work without fetching content, embedding, or writing.
+ #[arg(long)]
+ dry_run: bool,
+ /// Delete existing embedding set
+ #[arg(long)]
+ clear: bool,
+ /// Optional cap on the number of tasks processed (handy for a smoke test).
+ #[arg(long)]
+ limit: Option<usize>,
+ /// Number of tasks to embed and write concurrently.
+ #[arg(long, default_value_t = 8)]
+ concurrency: usize,
+}
+
+/// Running tallies for the backfill. Failures are split by stage so the final
+/// report shows where work was lost; `*_failed` failures are all retryable by
+/// re-running (the embedding client does not distinguish permanent rejections).
+#[derive(Default)]
+struct Counters {
+ /// Embeddings successfully written.
+ succeeded: AtomicUsize,
+ /// Failed
+ failed: AtomicUsize,
+ /// Total
+ total: AtomicUsize,
+}
+
+#[derive(Default, Clone)]
+struct Stats(Arc<Counters>);
+
+impl Stats {
+ /// Records a failure and returns the running count of tasks processed so far.
+ pub fn fail(&self) -> usize {
+ self.0.failed.fetch_add(1, Ordering::Relaxed);
+ self.0.total.fetch_add(1, Ordering::Relaxed) + 1
+ }
+
+ /// Records a success and returns the running count of tasks processed so far.
+ pub fn success(&self) -> usize {
+ self.0.succeeded.fetch_add(1, Ordering::Relaxed);
+ self.0.total.fetch_add(1, Ordering::Relaxed) + 1
+ }
+
+ pub fn summary(&self) {
+ println!("________________________________________");
+ println!(
+ "succeeded: {}/{}",
+ self.0.succeeded.load(Ordering::Relaxed),
+ self.0.total.load(Ordering::Relaxed)
+ );
+ println!(
+ "failed: {}/{}",
+ self.0.failed.load(Ordering::Relaxed),
+ self.0.total.load(Ordering::Relaxed)
+ );
+ println!("________________________________________");
+ }
+}
+
+fn confirm(s: &str) -> Result<()> {
+ println!("{}", s);
+ print!("Confirm [y/n]: ");
+ std::io::stdout().flush()?;
+ let mut buf = String::new();
+ std::io::stdin().read_line(&mut buf)?;
+ if buf.to_lowercase().trim() == "y" {
+ Ok(())
+ } else {
+ Err(anyhow!("declined"))
+ }
+}
+
+env_var! {
+ struct Vars {
+ DatabaseUrl,
+ LexicalServiceUrl,
+ InternalApiSecretKey,
+ OpenaiApiKey,
+ }
+}
+
+/// The fully-resolved config the backfill needs, regardless of where each value
+/// came from (local env vars vs. AWS Secrets Manager).
+struct ResolvedConfig {
+ database_url: String,
+ lexical_service_url: String,
+ internal_api_secret_key: String,
+ openai_api_key: String,
+}
+
+impl ResolvedConfig {
+ /// Local config: every value comes straight from the environment / `.env`,
+ /// matching the original setup.
+ fn local() -> Result<Self> {
+ let vars = Vars::new()?;
+ Ok(Self {
+ // The repo `.env` ships the docker-network DB host (`@postgres`),
+ // which isn't resolvable from the host shell, so hardcode the
+ // localhost URL for local runs.
+ database_url: "postgres://user:password@localhost:5432/macrodb".to_string(),
+ // The repo `.env` ships the docker-network lexical host
+ // (`http://lexical-service:8096`); use the localhost URL for local runs.
+ lexical_service_url: Env::Local.lexical_service_url().to_string(),
+ internal_api_secret_key: vars.internal_api_secret_key.as_ref().to_string(),
+ openai_api_key: vars.openai_api_key.as_ref().to_string(),
+ })
+ }
+
+ /// Dev/prod config, resolved from AWS: the lexical URL is hard-coded per
+ /// environment, the database URL is read from the `macro-db-<env>` secret via
+ /// the `aws` CLI (the same primary-writer secret the deployed services use),
+ /// and the OpenAI and internal-auth secrets are fetched from Secrets Manager
+ /// with the in-process SDK.
+ async fn remote(env: Env) -> Result<Self> {
+ // Make sure AWS calls target real AWS rather than a LocalStack override
+ // that may be lingering in the env.
+ // SAFETY: runs once at startup before any other thread reads the env.
+ unsafe { std::env::remove_var("LOCAL_AWS_URL") };
+
+ let database_url = fetch_database_url(env)?;
+
+ let secrets = SecretsManager::new(aws_sdk_secretsmanager::Client::new(
+ &macro_aws_config::get_macro_aws_config().await,
+ ));
+ let openai_api_key = secrets.get_secret_value("openai-key").await?;
+ let internal_api_secret_key = secrets
+ .get_secret_value(format!(
+ "document-storage-service-auth-key-{}",
+ env.suffix()
+ ))
+ .await?;
+
+ Ok(Self {
+ database_url,
+ lexical_service_url: env.lexical_service_url().to_string(),
+ internal_api_secret_key: internal_api_secret_key.as_ref().to_string(),
+ openai_api_key: openai_api_key.as_ref().to_string(),
+ })
+ }
+
+ fn print(&self) {
+ println!("________________________________________");
+ println!("DATABASE_URL: {}", masked_db_url(&self.database_url));
+ println!("LEXICAL_SERVICE_URL: {}", self.lexical_service_url);
+ println!("________________________________________");
+ }
+}
+
+/// Masks the password in a `postgres://user:password@host/...` URL for logging.
+fn masked_db_url(url: &str) -> String {
+ url.split_once("://")
+ .and_then(|(scheme, rest)| {
+ let (creds, host) = rest.split_once('@')?;
+ let user = creds.split_once(':').map_or(creds, |(user, _)| user);
+ Some(format!("{scheme}://{user}:******@{host}"))
+ })
+ .unwrap_or_else(|| url.to_string())
+}
+
+/// Fetches the full `DATABASE_URL` for `env` from AWS Secrets Manager by shelling
+/// out to the `aws` CLI. Reads the `macro-db-<env>` secret — the primary-writer
+/// connection string the deployed services use — which already contains a
+/// ready-to-use `postgres://…` URL, so nothing needs to be assembled.
+///
+/// The `aws` CLI must be on `PATH` and authenticated (e.g. `aws sso login`).
+fn fetch_database_url(env: Env) -> Result<String> {
+ let secret_id = format!("macro-db-{}", env.suffix());
+ println!("fetching DATABASE_URL from secret {secret_id}");
+
+ let output = std::process::Command::new("aws")
+ .args([
+ "secretsmanager",
+ "get-secret-value",
+ "--secret-id",
+ &secret_id,
+ "--query",
+ "SecretString",
+ "--output",
+ "text",
+ "--region",
+ "us-east-1",
+ ])
+ .output()
+ .with_context(|| format!("failed to run `aws` to read secret {secret_id}"))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ bail!(
+ "`aws secretsmanager get-secret-value` failed for {secret_id} \
+ (check AWS auth / permissions): {}",
+ stderr.trim()
+ );
+ }
+
+ let database_url = String::from_utf8(output.stdout)
+ .context("aws output was not valid UTF-8")?
+ .trim()
+ .to_string();
+ if database_url.is_empty() {
+ bail!("secret {secret_id} resolved to an empty value");
+ }
+ Ok(database_url)
+}
+
+struct Context {
+ pg: sqlx::PgPool,
+ lexical: LexicalClient,
+ embedder: TextEmbedding3Small,
+ vector_db: PgTaskVectorDb,
+}
+
+impl Context {
+ async fn connect(config: ResolvedConfig) -> Result<Self> {
+ let pg = sqlx::PgPool::connect(&config.database_url)
+ .await
+ .map_err(anyhow::Error::from)?;
+ let lexical =
+ LexicalClient::new(config.internal_api_secret_key, config.lexical_service_url);
+ let embedder = TextEmbedding3Small::new(config.openai_api_key);
+ let vector_db = PgTaskVectorDb::new(pg.clone());
+ Ok(Self {
+ pg,
+ lexical,
+ embedder,
+ vector_db,
+ })
+ }
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let args = Args::parse();
+
+ // Local reads everything from the environment / `.env`; dev and prod hard-code
+ // their URLs and pull secrets from AWS Secrets Manager.
+ let config = match args.env {
+ Env::Local => ResolvedConfig::local()?,
+ env => ResolvedConfig::remote(env).await?,
+ };
+ config.print();
+ let context = Context::connect(config).await?;
+
+ if args.clear {
+ confirm("Are you sure you want to clear all vectors")?;
+ confirm("Are you really sure")?;
+ return clear_vectors(&context).await;
+ }
+
+ let task_set = fetch_task_set(&context, &args).await?;
+ let total = task_set.len();
+ println!("found {total} task(s) to embed");
+ if args.dry_run {
+ return Ok(());
+ }
+
+ // Embed and store each task concurrently, capped at `--concurrency`. Each
+ // task is independent, so a single failure is recorded and the rest carry
+ // on; re-running picks up whatever did not get written. The running
+ // "<n>/<total>" reflects completion order, not input order.
+ let stats = Stats::default();
+ futures::stream::iter(task_set)
+ .for_each_concurrent(args.concurrency, |document_id| {
+ let context = &context;
+ let stats = stats.clone();
+ async move {
+ match embed_and_store(context, &document_id).await {
+ Ok(()) => {
+ let n = stats.success();
+ println!("{n}/{total} success");
+ }
+ Err(error) => {
+ let n = stats.fail();
+ println!("{n}/{total} failure");
+ println!("{error:#}");
+ }
+ }
+ }
+ })
+ .await;
+
+ stats.summary();
+ Ok(())
+}
+
+/// Returns the document ids of the tasks to embed.
+///
+/// With `--force` this is every task. Otherwise it's only the tasks that do not
+/// yet have any row in `task_duplicate_embedding`, so a re-run picks up where a
+/// previous one left off. `--limit` caps the result for smoke tests.
+async fn fetch_task_set(ctx: &Context, args: &Args) -> Result<Vec<String>> {
+ // LIMIT needs a bind value; map "no cap" to i64::MAX so the same query
+ // serves both the capped and uncapped cases. `force` is bound too, so a
+ // single query covers both modes: when true it short-circuits the
+ // NOT EXISTS filter and returns every task.
+ let limit = args.limit.map_or(i64::MAX, |n| n as i64);
+
+ sqlx::query_scalar!(
+ r#"
+ SELECT dst.document_id
+ FROM document_sub_type dst
+ JOIN "Document" d ON d.id = dst.document_id
+ WHERE dst.sub_type = 'task'
+ AND d."deletedAt" IS NULL
+ AND (
+ $1
+ OR NOT EXISTS (
+ SELECT 1
+ FROM task_duplicate_embedding tde
+ WHERE tde.document_id = dst.document_id
+ )
+ )
+ LIMIT $2
+ "#,
+ args.force,
+ limit
+ )
+ .fetch_all(&ctx.pg)
+ .await
+ .map_err(anyhow::Error::from)
+}
+
+/// Embeds a single task and upserts its field embeddings into the vector db.
+///
+/// Builds the embeddable [`Task`], runs it through the OpenAI embedder, and
+/// hands the resulting per-field embeddings to the [`PgTaskVectorDb`] vector
+/// store — the same insert path the live duplicate-detection service uses. A
+/// task with no embeddable text (empty title and body) is a no-op.
+async fn embed_and_store(ctx: &Context, document_id: &str) -> Result<()> {
+ let task = fetch_md_task(ctx, document_id).await?;
+ let embeddings = ctx.embedder.embed(&task).await?;
+ if embeddings.is_empty() {
+ return Ok(());
+ }
+ ctx.vector_db
+ .upsert_embeddings(document_id.to_string(), embeddings)
+ .await?;
+ Ok(())
+}
+
+/// Builds the embeddable [`Task`] for a single document: its `Document.name`
+/// becomes the title and the lexical service's rendered markdown becomes the
+/// body. Map this over a task set to get the entities to embed.
+async fn fetch_md_task(ctx: &Context, document_id: &str) -> Result<Task<'static>> {
+ let title = sqlx::query_scalar!(r#"SELECT name FROM "Document" WHERE id = $1"#, document_id)
+ .fetch_one(&ctx.pg)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let body = ctx.lexical.get_markdown(document_id).await?;
+
+ Ok(Task {
+ title: Cow::Owned(title),
+ body: Cow::Owned(body),
+ })
+}
+
+async fn clear_vectors(ctx: &Context) -> Result<()> {
+ sqlx::query!("TRUNCATE TABLE task_duplicate_embedding")
+ .execute(&ctx.pg)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(())
+}
diff --git a/rust/cloud-storage/task_dedup/src/domain/models.rs b/rust/cloud-storage/task_dedup/src/domain/models.rs
index 8a77bf4d73..38bf4de607 100644
--- a/rust/cloud-storage/task_dedup/src/domain/models.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/models.rs
@@ -1,5 +1,8 @@
//! Domain models for task duplicate detection.
+use std::borrow::Cow;
+
+use embedding::entity::Task;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -18,6 +21,38 @@ pub struct NewTask {
pub markdown: String,
}
+impl NewTask {
+ /// Borrows this task as an [`Embeddable`](embedding::Embeddable) entity so its
+ /// title and body are embedded as separate fields.
+ pub fn as_embeddable(&self) -> Task<'_> {
+ Task {
+ title: Cow::Borrowed(self.title.as_str()),
+ body: Cow::Borrowed(self.markdown.as_str()),
+ }
+ }
+}
+
+/// Filters applied to a task vector search.
+///
+/// This is the [`VectorDb::SearchParameters`](embedding::VectorDb::SearchParameters)
+/// for the task duplicate store: it scopes a cosine search to the tasks a user is
+/// allowed to see and optionally excludes the query task itself and any pairs the
+/// user has already dismissed.
+#[derive(Debug, Clone)]
+pub struct TaskSearchParameters {
+ /// Owner whose tasks are in scope.
+ pub owner: String,
+ /// Team whose shared tasks are also in scope, when set.
+ pub team_id: Option<Uuid>,
+ /// Maximum number of candidate tasks to return.
+ pub limit: i64,
+ /// Document id to exclude from results (the query task itself), when set.
+ pub exclude_document_id: Option<String>,
+ /// When true, drop candidates already dismissed against
+ /// [`exclude_document_id`](Self::exclude_document_id).
+ pub exclude_dismissed: bool,
+}
+
/// A duplicate task candidate shown on the task surface.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -34,17 +69,6 @@ pub struct TaskDuplicate {
pub judge_reason: Option<String>,
}
-/// Candidate returned by the retrieval layer before judging.
-#[derive(Debug, Clone)]
-pub struct TaskDuplicateCandidate {
- /// Candidate task document id.
- pub document_id: String,
- /// Candidate embedding content.
- pub content: String,
- /// Candidate vector similarity.
- pub vector_score: f64,
-}
-
/// A similar existing task computed for an unsaved draft, returned to the task
/// composer without persisting any embedding or match state.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
@@ -58,20 +82,6 @@ pub struct TaskSimilarityResult {
pub vector_score: f64,
}
-/// Candidate returned by the similarity-search retrieval layer, carrying the
-/// task display name so the composer can render a match without a match row.
-#[derive(Debug, Clone)]
-pub struct TaskSimilarityCandidate {
- /// Candidate task document id.
- pub document_id: String,
- /// Candidate task display name.
- pub name: String,
- /// Candidate embedding content.
- pub content: String,
- /// Candidate vector similarity.
- pub vector_score: f64,
-}
-
/// Output from a duplicate judge.
#[derive(Debug, Clone)]
pub struct JudgeResult {
diff --git a/rust/cloud-storage/task_dedup/src/domain/ports.rs b/rust/cloud-storage/task_dedup/src/domain/ports.rs
index e0466a6e48..2989194c82 100644
--- a/rust/cloud-storage/task_dedup/src/domain/ports.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/ports.rs
@@ -1,33 +1,19 @@
//! Ports for the task duplicate detection pipeline.
+//!
+//! Embedding, reranking, and vector storage are provided by the [`embedding`]
+//! crate's traits ([`EmbeddingModel`](embedding::EmbeddingModel),
+//! [`RerankModel`](embedding::RerankModel), [`VectorDb`](embedding::VectorDb)) and
+//! injected into [`TaskDedupService`](crate::domain::service::TaskDedupService) as
+//! generic type parameters. The ports defined here cover only the
+//! task-duplicate-specific concerns the embedding crate does not: judging,
+//! match-state persistence, and live notifications.
+
+use std::collections::HashMap;
use async_trait::async_trait;
use uuid::Uuid;
-use super::models::{
- JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate,
- TaskSimilarityCandidate,
-};
-
-/// Embeds task text into a vector representation.
-#[async_trait]
-pub trait TaskEmbedder: Send + Sync {
- /// Embeds `content`.
- async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>>;
-}
-
-/// Reranks retrieved candidates against the query task before judging or
-/// surfacing them.
-///
-/// This is the cross-encoder stage of the retrieve → rerank → judge pipeline: a
-/// trained relevance model (e.g. a Cohere/Voyage/Jina rerank connection) scores
-/// each candidate jointly with the query, which a bi-encoder vector search
-/// cannot. Implementations return one score per document, aligned by index.
-#[async_trait]
-pub trait TaskReranker: Send + Sync {
- /// Returns a relevance score for each entry of `documents` against `query`,
- /// in the same order. Higher means more relevant.
- async fn rerank(&self, query: &str, documents: &[String]) -> anyhow::Result<Vec<f64>>;
-}
+use super::models::{JudgeResult, TaskDedupError, TaskDuplicate};
/// Applies a semantic duplicate judgement after vector retrieval and reranking.
#[async_trait]
@@ -36,42 +22,19 @@ pub trait TaskDuplicateJudge: Send + Sync {
async fn judge(&self, left: &str, right: &str) -> JudgeResult;
}
-/// Persists embeddings, retrieves candidates, and manages match state.
+/// Persists and queries duplicate match state.
+///
+/// Embeddings and candidate retrieval live behind the embedding crate's
+/// [`VectorDb`](embedding::VectorDb); this port owns the match graph that vector
+/// search feeds into.
#[async_trait]
-pub trait TaskDedupRepo: Send + Sync {
- /// Upserts the current task embedding.
- async fn upsert_embedding(
- &self,
- document_id: &str,
- model: &str,
- content: &str,
- embedding: &[f32],
- ) -> Result<(), TaskDedupError>;
-
- /// Retrieves vector candidates for a task.
- async fn candidates(
- &self,
- task: &NewTask,
- embedding: &[f32],
- limit: i64,
- ) -> Result<Vec<TaskDuplicateCandidate>, TaskDedupError>;
-
- /// Retrieves vector candidates for an unsaved task scoped to `owner` and an
- /// optional `team_id`, without any self- or dismissed-match exclusion.
- async fn similarity_candidates(
- &self,
- owner: &str,
- team_id: Option<Uuid>,
- embedding: &[f32],
- limit: i64,
- ) -> Result<Vec<TaskSimilarityCandidate>, TaskDedupError>;
-
+pub trait TaskMatchRepo: Send + Sync {
/// Upserts an active duplicate match.
async fn upsert_match(
&self,
task_id: &str,
duplicate_task_id: &str,
- vector_score: f64,
+ similarity_score: f64,
judge_model: Option<&str>,
judge_reason: Option<&str>,
) -> Result<(), TaskDedupError>;
@@ -112,6 +75,13 @@ pub trait TaskDedupRepo: Send + Sync {
/// Dismisses a match without document-side filtering.
async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError>;
+
+ /// Returns the display name of each requested task document, keyed by
+ /// document id. Missing or deleted documents are omitted.
+ async fn task_names(
+ &self,
+ document_ids: &[String],
+ ) -> Result<HashMap<String, String>, TaskDedupError>;
}
/// Sends live updates for documents whose duplicate state changed.
diff --git a/rust/cloud-storage/task_dedup/src/domain/service.rs b/rust/cloud-storage/task_dedup/src/domain/service.rs
index 7aeb79fe03..1582545712 100644
--- a/rust/cloud-storage/task_dedup/src/domain/service.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/service.rs
@@ -3,15 +3,18 @@
#[cfg(test)]
mod test;
-use std::collections::HashSet;
+use std::borrow::Cow;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
+use embedding::entity::Task;
+use embedding::{Content, EmbeddingModel, KeyedEmbedding, RerankModel, SearchResults, VectorStore};
use uuid::Uuid;
-use super::models::{NewTask, TaskDedupError, TaskDuplicate, TaskSimilarityResult};
-use super::ports::{
- TaskDedupNotifier, TaskDedupRepo, TaskDuplicateJudge, TaskEmbedder, TaskReranker,
+use super::models::{
+ NewTask, TaskDedupError, TaskDuplicate, TaskSearchParameters, TaskSimilarityResult,
};
+use super::ports::{TaskDedupNotifier, TaskDuplicateJudge, TaskMatchRepo};
/// Configuration for the task duplicate detection pipeline.
#[derive(Debug, Clone)]
@@ -41,34 +44,59 @@ impl Default for TaskDedupConfig {
}
}
+/// A candidate task surfaced by vector retrieval, collapsed from the per-field
+/// [`SearchResults`] into a single score and a reconstructed text used for
+/// reranking and judging.
+struct Candidate {
+ document_id: String,
+ /// The candidate's stored field contents joined back together.
+ content: String,
+ /// Best cosine similarity across the query × stored field cross-product.
+ vector_score: f64,
+}
+
/// Task duplicate detection service.
+///
+/// Embedding (`E`), vector storage (`V`), and reranking (`R`) are supplied by the
+/// [`embedding`] crate's traits. They are generic rather than `dyn` because those
+/// traits use return-position `impl Trait` / associated types and are not
+/// object-safe. The judge, notifier, and match repo remain `dyn` ports.
#[derive(Clone)]
-pub struct TaskDedupService {
+pub struct TaskDedupService<const DIMS: usize, E, V, R> {
config: TaskDedupConfig,
- repo: Arc<dyn TaskDedupRepo>,
- embedder: Arc<dyn TaskEmbedder>,
- reranker: Arc<dyn TaskReranker>,
+ embedder: E,
+ vector_db: V,
+ reranker: R,
judge: Arc<dyn TaskDuplicateJudge>,
notifier: Arc<dyn TaskDedupNotifier>,
+ matches: Arc<dyn TaskMatchRepo>,
}
-impl TaskDedupService {
- /// Creates a new service from its ports.
+impl<const DIMS: usize, E, V, R> TaskDedupService<DIMS, E, V, R>
+where
+ E: EmbeddingModel<DIMS> + Send + Sync,
+ V: VectorStore<DIMS, Metadata = String, SearchParameters = TaskSearchParameters> + Send + Sync,
+ V::Error: Into<anyhow::Error>,
+ R: RerankModel<DIMS> + Send + Sync,
+{
+ /// Creates a new service from its dependencies.
pub fn new(
config: TaskDedupConfig,
- repo: Arc<dyn TaskDedupRepo>,
- embedder: Arc<dyn TaskEmbedder>,
- reranker: Arc<dyn TaskReranker>,
+ embedder: E,
+ vector_db: V,
+ reranker: R,
judge: Arc<dyn TaskDuplicateJudge>,
notifier: Arc<dyn TaskDedupNotifier>,
+ matches: Arc<dyn TaskMatchRepo>,
) -> Self {
Self {
config,
- repo,
embedder,
+ vector_db,
reranker,
judge,
notifier,
+ matches,
}
}
@@ -77,7 +105,7 @@ impl TaskDedupService {
&self,
document_id: &str,
) -> Result<Vec<TaskDuplicate>, TaskDedupError> {
- self.repo.active_duplicates(document_id).await
+ self.matches.active_duplicates(document_id).await
}
/// Dismisses visible matches.
@@ -94,7 +122,7 @@ impl TaskDedupService {
let mut affected_document_ids = HashSet::new();
for match_id in &unique_match_ids {
- if !self.repo.match_contains(document_id, *match_id).await? {
+ if !self.matches.match_contains(document_id, *match_id).await? {
return Err(TaskDedupError::MatchNotFound);
}
affected_document_ids.extend(self.match_document_ids(*match_id).await?);
@@ -102,7 +130,7 @@ impl TaskDedupService {
for match_id in unique_match_ids {
let dismissed = self
- .repo
+ .matches
.dismiss_match(document_id, match_id, dismissed_by)
.await?;
if !dismissed {
@@ -120,7 +148,7 @@ impl TaskDedupService {
document_id: &str,
match_id: Uuid,
) -> Result<(), TaskDedupError> {
- if self.repo.match_contains(document_id, match_id).await? {
+ if self.matches.match_contains(document_id, match_id).await? {
Ok(())
} else {
Err(TaskDedupError::MatchNotFound)
@@ -130,7 +158,7 @@ impl TaskDedupService {
/// Dismisses a match by id.
pub async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError> {
let affected_document_ids = self.match_document_ids(match_id).await?;
- self.repo.dismiss_match_by_id(match_id).await?;
+ self.matches.dismiss_match_by_id(match_id).await?;
self.notify_documents(affected_document_ids).await;
Ok(())
}
@@ -147,34 +175,57 @@ impl TaskDedupService {
title: &str,
markdown: &str,
) -> Result<Vec<TaskSimilarityResult>, TaskDedupError> {
- let content = task_embedding_content(title, markdown);
- let embedding = self.embedder.embed(&content).await?;
-
- let candidates = self
- .repo
- .similarity_candidates(
- owner,
- team_id,
- &embedding,
- self.config.vector_candidate_limit,
- )
- .await?;
-
- let candidates = candidates
+ let embeddable = Task {
+ title: Cow::Borrowed(title),
+ body: Cow::Borrowed(markdown),
+ };
+ let labeled = self.embedder.embed(&embeddable).await?;
+ if labeled.is_empty() {
+ return Ok(Vec::new());
+ }
+ let query: Vec<KeyedEmbedding<DIMS>> = labeled
+ .iter()
+ .map(|field| KeyedEmbedding {
+ search_key: field.search_key,
+ embedding: field.embedding,
+ })
+ .collect();
+
+ let params = TaskSearchParameters {
+ owner: owner.to_string(),
+ team_id,
+ limit: self.config.vector_candidate_limit,
+ exclude_document_id: None,
+ exclude_dismissed: false,
+ };
+ let results = self
+ .vector_db
+ .cosine_search(query, params)
+ .await
+ .map_err(|error| TaskDedupError::Dependency(error.into()))?;
+
+ let query_content = full_text(title, markdown);
+ let ranked = self
+ .rerank(&query_content, results)
+ .await?
.into_iter()
- .filter(|candidate| candidate.vector_score >= self.config.min_vector_similarity)
+ .take(self.config.duplicate_limit.max(0) as usize)
.collect::<Vec<_>>();
- let ranked = self
- .rerank(&content, candidates, |candidate| candidate.content.as_str())
- .await?;
+ let document_ids = ranked
+ .iter()
+ .map(|candidate| candidate.document_id.clone())
+ .collect::<Vec<_>>();
+ let names = self.matches.task_names(&document_ids).await?;
Ok(ranked
.into_iter()
- .take(self.config.duplicate_limit.max(0) as usize)
.map(|candidate| TaskSimilarityResult {
+ task_name: names
+ .get(&candidate.document_id)
+ .cloned()
+ .unwrap_or_default(),
task_id: candidate.document_id,
- task_name: candidate.name,
vector_score: candidate.vector_score,
})
.collect())
@@ -183,38 +234,52 @@ impl TaskDedupService {
/// Detects duplicates for a newly-created task and sends live updates for
/// documents that now have active matches.
pub async fn detect_new_task(&self, task: NewTask) -> Result<Vec<String>, TaskDedupError> {
- let content = task_embedding_content(&task.title, &task.markdown);
- let embedding = self.embedder.embed(&content).await?;
+ let embeddable = task.as_embeddable();
+ let labeled = self.embedder.embed(&embeddable).await?;
+ if labeled.is_empty() {
+ return Ok(Vec::new());
+ }
let mut changed_document_ids = HashSet::new();
- self.repo
- .upsert_embedding(
- &task.document_id,
- &self.config.embedding_model,
- &content,
- &embedding,
- )
- .await?;
-
- let candidates = self
- .repo
- .candidates(&task, &embedding, self.config.vector_candidate_limit)
- .await?;
+ // Build the query before moving the labeled embeddings into the store;
+ // the vectors are `Copy` so this borrows rather than clones the content.
+ let query: Vec<KeyedEmbedding<DIMS>> = labeled
+ .iter()
+ .map(|field| KeyedEmbedding {
+ search_key: field.search_key,
+ embedding: field.embedding,
+ })
+ .collect();
+
+ self.vector_db
+ .upsert_embeddings(task.document_id.clone(), labeled)
+ .await
+ .map_err(|error| TaskDedupError::Dependency(error.into()))?;
+
+ let params = TaskSearchParameters {
+ owner: task.owner.clone(),
+ team_id: task.team_id,
+ limit: self.config.vector_candidate_limit,
+ exclude_document_id: Some(task.document_id.clone()),
+ exclude_dismissed: true,
+ };
+ let results = self
+ .vector_db
+ .cosine_search(query, params)
+ .await
+ .map_err(|error| TaskDedupError::Dependency(error.into()))?;
// Gate by the vector-similarity floor, rerank the survivors, then send
// only the top `max_judge_candidates` (by rerank score) to the LLM judge.
- let candidates = candidates
- .into_iter()
- .filter(|candidate| candidate.vector_score >= self.config.min_vector_similarity)
- .collect::<Vec<_>>();
+ let query_content = full_text(&task.title, &task.markdown);
let judge_candidates = self
- .rerank(&content, candidates, |candidate| candidate.content.as_str())
+ .rerank(&query_content, results)
.await?
.into_iter()
.take(self.config.max_judge_candidates);
for candidate in judge_candidates {
- let judge = self.judge.judge(&content, &candidate.content).await;
+ let judge = self.judge.judge(&query_content, &candidate.content).await;
if !judge.is_duplicate {
continue;
}
@@ -226,7 +291,7 @@ impl TaskDedupService {
.await?;
let reason = inferred_judge_reason(judge.reason.as_deref());
for (left, right) in complete_graph_pairs(&component) {
- self.repo
+ self.matches
.upsert_match(
left,
right,
@@ -242,7 +307,7 @@ impl TaskDedupService {
}
for changed_document_id in &changed_document_ids {
- self.repo
+ self.matches
.trim_matches(changed_document_id, self.config.duplicate_limit)
.await?;
}
@@ -250,7 +315,7 @@ impl TaskDedupService {
let mut active_document_ids = Vec::new();
for changed_document_id in changed_document_ids {
if !self
- .repo
+ .matches
.active_duplicates(&changed_document_id)
.await?
.is_empty()
@@ -263,37 +328,66 @@ impl TaskDedupService {
Ok(active_document_ids)
}
- /// Reranks `candidates` against `query` and returns them ordered by
- /// descending relevance score. Candidates with equal scores keep their input
- /// (vector-similarity) order. An empty input skips the reranker entirely.
- async fn rerank<C: Send>(
+ /// Collapses a single entity's per-field [`SearchResults`] into a
+ /// [`Candidate`]: the vector score is the best similarity across the query ×
+ /// stored-field cross-product, and the content is the entity's matched field
+ /// texts joined back together for judging. Returns `None` when the entity
+ /// falls below the configured similarity floor.
+ fn collapse(&self, result: &SearchResults<String, DIMS>) -> Option<Candidate> {
+ let vector_score = result
+ .matches
+ .iter()
+ .map(|matched| matched.score as f64)
+ .fold(f64::NEG_INFINITY, f64::max);
+ if !vector_score.is_finite() || vector_score < self.config.min_vector_similarity {
+ return None;
+ }
+ let content = result
+ .matches
+ .iter()
+ .map(|matched| matched.embedding.content.as_ref())
+ .collect::<Vec<_>>()
+ .join("\n");
+ Some(Candidate {
+ document_id: result.metadata.clone(),
+ content,
+ vector_score,
+ })
+ }
+
+ /// Drops results below the similarity floor, reranks the survivors against
+ /// `query`, and returns them as [`Candidate`]s ordered by descending
+ /// relevance. The reranker only carries each result's `document_id` through,
+ /// so the collapsed content and vector score are looked back up afterwards.
+ /// An empty survivor set skips the reranker entirely.
+ async fn rerank(
&self,
query: &str,
- candidates: Vec<C>,
- content_of: impl Fn(&C) -> &str,
- ) -> Result<Vec<C>, TaskDedupError> {
- if candidates.is_empty() {
- return Ok(candidates);
+ results: Vec<SearchResults<String, DIMS>>,
+ ) -> Result<Vec<Candidate>, TaskDedupError> {
+ let mut lookup: HashMap<String, Candidate> = HashMap::new();
+ let mut survivors: Vec<SearchResults<String, DIMS>> = Vec::new();
+ for result in results {
+ let Some(candidate) = self.collapse(&result) else {
+ continue;
+ };
+ lookup.insert(candidate.document_id.clone(), candidate);
+ survivors.push(result);
}
- let documents = candidates
- .iter()
- .map(|candidate| content_of(candidate).to_string())
- .collect::<Vec<_>>();
- let scores = self.reranker.rerank(query, &documents).await?;
- if scores.len() != candidates.len() {
- return Err(TaskDedupError::Dependency(anyhow::anyhow!(
- "reranker returned {} scores for {} documents",
- scores.len(),
- candidates.len()
- )));
+ if survivors.is_empty() {
+ return Ok(Vec::new());
}
- let mut scored = candidates.into_iter().zip(scores).collect::<Vec<_>>();
- scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
- Ok(scored
+ let reranked = self
+ .reranker
+ .rerank(Content::Borrowed(query), survivors)
+ .await
+ .map_err(TaskDedupError::Dependency)?;
+
+ Ok(reranked
.into_iter()
- .map(|(candidate, _score)| candidate)
+ .filter_map(|scored| lookup.remove(&scored.item))
.collect())
}
@@ -313,7 +407,7 @@ impl TaskDedupService {
}
async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {
- let document_ids = self.repo.match_document_ids(match_id).await?;
+ let document_ids = self.matches.match_document_ids(match_id).await?;
if document_ids.is_empty() {
Err(TaskDedupError::MatchNotFound)
} else {
@@ -328,7 +422,7 @@ impl TaskDedupService {
let seeds = document_ids.into_iter().collect::<HashSet<_>>();
let seed_list = seeds.iter().cloned().collect::<Vec<_>>();
let mut component = self
- .repo
+ .matches
.active_duplicate_component(&seed_list)
.await?
.into_iter()
@@ -341,8 +435,9 @@ impl TaskDedupService {
}
}
-/// Builds the text embedded for a task.
-pub fn task_embedding_content(title: &str, markdown: &str) -> String {
+/// Builds the full task text used as the rerank/judge query, joining the title
+/// and body the same way they read to a user.
+fn full_text(title: &str, markdown: &str) -> String {
format!("{}\n{}", title.trim(), markdown.trim())
}
diff --git a/rust/cloud-storage/task_dedup/src/domain/service/test.rs b/rust/cloud-storage/task_dedup/src/domain/service/test.rs
index 1e249dfb03..04947ab2f4 100644
--- a/rust/cloud-storage/task_dedup/src/domain/service/test.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/service/test.rs
@@ -1,57 +1,194 @@
-//! Service-level pipeline tests against in-memory mock ports.
+//! Service-level pipeline tests against in-memory mock dependencies.
//!
-//! These exercise [`TaskDedupService`] end to end without a database: the repo,
-//! embedder, reranker, judge, and notifier are all mocked here so each stage of
-//! the retrieve → rerank → judge → persist → notify pipeline can be asserted in
-//! isolation.
+//! These exercise [`TaskDedupService`] end to end without a database: the
+//! embedder, vector store, reranker, judge, notifier, and match repo are all
+//! mocked here so each stage of the retrieve → rerank → judge → persist → notify
+//! pipeline can be asserted in isolation.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
+use embedding::{
+ Content, Embeddable, EmbeddingModel, KeyedEmbedding, LabeledEmbedding, Match, RerankModel,
+ Reranked, SearchResults, VectorStore,
+};
use uuid::Uuid;
use super::{TaskDedupConfig, TaskDedupService};
use crate::domain::models::{
- JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate,
- TaskSimilarityCandidate,
-};
-use crate::domain::ports::{
- TaskDedupNotifier, TaskDedupRepo, TaskDuplicateJudge, TaskEmbedder, TaskReranker,
+ JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskSearchParameters,
};
+use crate::domain::ports::{TaskDedupNotifier, TaskDuplicateJudge, TaskMatchRepo};
+
+/// Small embedding width so mock vectors stay tiny.
+const DIMS: usize = 4;
+
+type MockService = TaskDedupService<DIMS, MockEmbedder, MockVectorDb, MockReranker>;
// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------
+/// Embedder that emits a zero vector per field exposed by the content.
struct MockEmbedder;
-#[async_trait]
-impl TaskEmbedder for MockEmbedder {
- async fn embed(&self, _content: &str) -> anyhow::Result<Vec<f32>> {
- Ok(vec![0.0; 4])
+impl EmbeddingModel<DIMS> for MockEmbedder {
+ async fn embed(
+ &self,
+ content: &(dyn Embeddable + Sync),
+ ) -> anyhow::Result<Vec<LabeledEmbedding<'static, DIMS>>> {
+ Ok(content
+ .embedding_content()
+ .into_iter()
+ .map(|(search_key, text)| LabeledEmbedding {
+ search_key,
+ content: Content::Owned(text.into_owned()),
+ embedding: [0.0; DIMS],
+ })
+ .collect())
}
}
-/// Reranker that scores documents from a content→score map (default 0.0) and
-/// records every call so tests can assert it ran on each path.
+/// Vector store returning preset `(document_id, content, score)` candidates, each
+/// as a single-field [`SearchResults`]. Records upserts and the last search
+/// parameters so the detect/similarity paths can be asserted.
+#[derive(Clone, Default)]
+struct MockVectorDb {
+ inner: Arc<MockVectorDbInner>,
+}
+
#[derive(Default)]
+struct MockVectorDbInner {
+ results: Vec<(String, String, f32)>,
+ upserted: Mutex<Vec<String>>,
+ last_params: Mutex<Option<TaskSearchParameters>>,
+}
+
+impl MockVectorDb {
+ fn with_results(results: Vec<(&str, &str, f32)>) -> Self {
+ Self {
+ inner: Arc::new(MockVectorDbInner {
+ results: results
+ .into_iter()
+ .map(|(id, content, score)| (id.to_string(), content.to_string(), score))
+ .collect(),
+ ..Default::default()
+ }),
+ }
+ }
+}
+
+impl VectorStore<DIMS> for MockVectorDb {
+ type Error = anyhow::Error;
+ type Metadata = String;
+ type SearchParameters = TaskSearchParameters;
+
+ async fn upsert_embeddings<'a>(
+ &self,
+ metadata: String,
+ _embeddings: Vec<LabeledEmbedding<'a, DIMS>>,
+ ) -> anyhow::Result<()> {
+ self.inner.upserted.lock().unwrap().push(metadata);
+ Ok(())
+ }
+
+ async fn cosine_search(
+ &self,
+ _query: Vec<KeyedEmbedding<DIMS>>,
+ params: TaskSearchParameters,
+ ) -> anyhow::Result<Vec<SearchResults<String, DIMS>>> {
+ *self.inner.last_params.lock().unwrap() = Some(params);
+ Ok(self
+ .inner
+ .results
+ .iter()
+ .map(|(id, content, score)| SearchResults {
+ metadata: id.clone(),
+ matches: vec![Match {
+ score: *score,
+ embedding: LabeledEmbedding {
+ search_key: "title",
+ content: Content::Owned(content.clone()),
+ embedding: [0.0; DIMS],
+ },
+ }],
+ })
+ .collect())
+ }
+}
+
+/// Reranker that scores candidates from a content→score map (default 0.0),
+/// returning them sorted by descending score (stable for ties) and recording
+/// every call so tests can assert it ran on each path.
+#[derive(Clone, Default)]
struct MockReranker {
+ inner: Arc<MockRerankerInner>,
+}
+
+#[derive(Default)]
+struct MockRerankerInner {
scores: HashMap<String, f64>,
calls: Mutex<Vec<(String, Vec<String>)>>,
}
-#[async_trait]
-impl TaskReranker for MockReranker {
- async fn rerank(&self, query: &str, documents: &[String]) -> anyhow::Result<Vec<f64>> {
- self.calls
+impl MockReranker {
+ fn new(scores: &[(&str, f64)]) -> Self {
+ Self {
+ inner: Arc::new(MockRerankerInner {
+ scores: scores.iter().map(|(k, v)| (k.to_string(), *v)).collect(),
+ calls: Mutex::default(),
+ }),
+ }
+ }
+
+ fn calls(&self) -> Vec<(String, Vec<String>)> {
+ self.inner.calls.lock().unwrap().clone()
+ }
+}
+
+impl<const DIMS: usize> RerankModel<DIMS> for MockReranker {
+ async fn rerank<'a, T: Send>(
+ &self,
+ query: Content<'a>,
+ candidates: Vec<SearchResults<T, DIMS>>,
+ ) -> anyhow::Result<Vec<Reranked<T>>> {
+ // Reconstruct each candidate's content the same way the service does so
+ // the content→score map keys still line up.
+ let documents = candidates
+ .iter()
+ .map(|result| {
+ result
+ .matches
+ .iter()
+ .map(|matched| matched.embedding.content.as_ref())
+ .collect::<Vec<_>>()
+ .join("\n")
+ })
+ .collect::<Vec<_>>();
+ self.inner
+ .calls
.lock()
.unwrap()
- .push((query.to_string(), documents.to_vec()));
- Ok(documents
- .iter()
- .map(|document| self.scores.get(document).copied().unwrap_or(0.0))
- .collect())
+ .push((query.into_owned(), documents.clone()));
+
+ let mut scored = candidates
+ .into_iter()
+ .zip(documents)
+ .map(|(result, content)| {
+ let score = self.inner.scores.get(&content).copied().unwrap_or(0.0) as f32;
+ Reranked {
+ item: result.metadata,
+ score,
+ }
+ })
+ .collect::<Vec<_>>();
+ scored.sort_by(|a, b| {
+ b.score
+ .partial_cmp(&a.score)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+ Ok(scored)
}
}
@@ -106,22 +243,19 @@ struct RecordedMatch {
judge_model: Option<String>,
}
-/// In-memory repo: preset retrieval results + a live match store, recording the
-/// writes (embeddings, matches, trims) the service performs.
+/// In-memory match repo: a live match store recording the writes (matches,
+/// trims) the service performs.
#[derive(Default)]
-struct MockRepo {
- candidates: Vec<TaskDuplicateCandidate>,
- similarity_candidates: Vec<TaskSimilarityCandidate>,
+struct MockMatchRepo {
/// Extra documents `active_duplicate_component` folds in beyond the seeds,
/// to exercise duplicate-graph closure.
component_extra: Vec<String>,
matches: Mutex<Vec<MatchRow>>,
- upserted_embeddings: Mutex<Vec<String>>,
upserted_matches: Mutex<Vec<RecordedMatch>>,
trimmed: Mutex<Vec<(String, i64)>>,
}
-impl MockRepo {
+impl MockMatchRepo {
fn add_active_match(&self, task_id: &str, duplicate_task_id: &str) -> Uuid {
let id = Uuid::new_v4();
self.matches.lock().unwrap().push(MatchRow {
@@ -137,40 +271,7 @@ impl MockRepo {
}
#[async_trait]
-impl TaskDedupRepo for MockRepo {
- async fn upsert_embedding(
- &self,
- document_id: &str,
- _model: &str,
- _content: &str,
- _embedding: &[f32],
- ) -> Result<(), TaskDedupError> {
- self.upserted_embeddings
- .lock()
- .unwrap()
- .push(document_id.to_string());
- Ok(())
- }
-
- async fn candidates(
- &self,
- _task: &NewTask,
- _embedding: &[f32],
- _limit: i64,
- ) -> Result<Vec<TaskDuplicateCandidate>, TaskDedupError> {
- Ok(self.candidates.clone())
- }
-
- async fn similarity_candidates(
- &self,
- _owner: &str,
- _team_id: Option<Uuid>,
- _embedding: &[f32],
- _limit: i64,
- ) -> Result<Vec<TaskSimilarityCandidate>, TaskDedupError> {
- Ok(self.similarity_candidates.clone())
- }
-
+impl TaskMatchRepo for MockMatchRepo {
async fn upsert_match(
&self,
task_id: &str,
@@ -293,29 +394,22 @@ impl TaskDedupRepo for MockRepo {
}
Ok(())
}
+
+ async fn task_names(
+ &self,
+ document_ids: &[String],
+ ) -> Result<HashMap<String, String>, TaskDedupError> {
+ Ok(document_ids
+ .iter()
+ .map(|id| (id.clone(), format!("{id} name")))
+ .collect())
+ }
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
-fn candidate(id: &str, content: &str, vector_score: f64) -> TaskDuplicateCandidate {
- TaskDuplicateCandidate {
- document_id: id.to_string(),
- content: content.to_string(),
- vector_score,
- }
-}
-
-fn sim_candidate(id: &str, content: &str, vector_score: f64) -> TaskSimilarityCandidate {
- TaskSimilarityCandidate {
- document_id: id.to_string(),
- name: format!("{id} name"),
- content: content.to_string(),
- vector_score,
- }
-}
-
fn new_task(document_id: &str) -> NewTask {
NewTask {
document_id: document_id.to_string(),
@@ -326,35 +420,48 @@ fn new_task(document_id: &str) -> NewTask {
}
}
-fn reranker(scores: &[(&str, f64)]) -> Arc<MockReranker> {
- Arc::new(MockReranker {
- scores: scores.iter().map(|(k, v)| (k.to_string(), *v)).collect(),
- calls: Mutex::default(),
- })
-}
-
-fn judge(duplicates: &[&str]) -> Arc<MockJudge> {
- Arc::new(MockJudge {
- duplicates: duplicates.iter().map(|s| s.to_string()).collect(),
- calls: Mutex::default(),
- })
+/// Builds a service, returning it alongside the mocks the test asserts on.
+struct Harness {
+ service: MockService,
+ vector_db: MockVectorDb,
+ reranker: MockReranker,
+ judge: Arc<MockJudge>,
+ notifier: Arc<MockNotifier>,
+ matches: Arc<MockMatchRepo>,
}
fn build(
config: TaskDedupConfig,
- repo: &Arc<MockRepo>,
- reranker: &Arc<MockReranker>,
- judge: &Arc<MockJudge>,
- notifier: &Arc<MockNotifier>,
-) -> TaskDedupService {
- TaskDedupService::new(
+ vector_db: MockVectorDb,
+ reranker: MockReranker,
+ judge: Arc<MockJudge>,
+ notifier: Arc<MockNotifier>,
+ matches: Arc<MockMatchRepo>,
+) -> Harness {
+ let service = TaskDedupService::new(
config,
- repo.clone(),
- Arc::new(MockEmbedder),
+ MockEmbedder,
+ vector_db.clone(),
reranker.clone(),
judge.clone(),
notifier.clone(),
- )
+ matches.clone(),
+ );
+ Harness {
+ service,
+ vector_db,
+ reranker,
+ judge,
+ notifier,
+ matches,
+ }
+}
+
+fn judge(duplicates: &[&str]) -> Arc<MockJudge> {
+ Arc::new(MockJudge {
+ duplicates: duplicates.iter().map(|s| s.to_string()).collect(),
+ calls: Mutex::default(),
+ })
}
fn judged_right_sides(judge: &MockJudge) -> Vec<String> {
@@ -373,32 +480,38 @@ fn judged_right_sides(judge: &MockJudge) -> Vec<String> {
#[tokio::test]
async fn detect_creates_match_reranks_and_notifies() {
- let repo = Arc::new(MockRepo {
- candidates: vec![candidate("A", "cand-a", 0.9)],
- ..Default::default()
- });
- let reranker = reranker(&[]);
- let judge = judge(&["cand-a"]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![("A", "cand-a", 0.9)]),
+ MockReranker::new(&[]),
+ judge(&["cand-a"]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- let mut active = service.detect_new_task(new_task("NEW")).await.unwrap();
+ let mut active = h.service.detect_new_task(new_task("NEW")).await.unwrap();
active.sort();
// Embedding persisted for the new task.
assert_eq!(
- *repo.upserted_embeddings.lock().unwrap(),
+ *h.vector_db.inner.upserted.lock().unwrap(),
vec!["NEW".to_string()]
);
+ // The detect path scopes and excludes the query task and dismissed pairs.
+ let params = h
+ .vector_db
+ .inner
+ .last_params
+ .lock()
+ .unwrap()
+ .clone()
+ .unwrap();
+ assert_eq!(params.exclude_document_id.as_deref(), Some("NEW"));
+ assert!(params.exclude_dismissed);
+
// A single ordered match was written, tagged with the judge's model.
- let upserts = repo.upserted_matches.lock().unwrap();
+ let upserts = h.matches.upserted_matches.lock().unwrap();
assert_eq!(upserts.len(), 1);
assert_eq!(upserts[0].task_id, "A");
assert_eq!(upserts[0].duplicate_task_id, "NEW");
@@ -406,14 +519,15 @@ async fn detect_creates_match_reranks_and_notifies() {
drop(upserts);
// The reranker ran in the judge path.
- assert_eq!(reranker.calls.lock().unwrap().len(), 1);
+ assert_eq!(h.reranker.calls().len(), 1);
// Both sides were trimmed and notified, and returned as active.
assert_eq!(active, vec!["A".to_string(), "NEW".to_string()]);
- let mut notified = notifier.notified.lock().unwrap().clone();
+ let mut notified = h.notifier.notified.lock().unwrap().clone();
notified.sort();
assert_eq!(notified, vec!["A".to_string(), "NEW".to_string()]);
- let trimmed: HashSet<String> = repo
+ let trimmed: HashSet<String> = h
+ .matches
.trimmed
.lock()
.unwrap()
@@ -425,83 +539,73 @@ async fn detect_creates_match_reranks_and_notifies() {
#[tokio::test]
async fn detect_skips_candidates_below_vector_similarity() {
- let repo = Arc::new(MockRepo {
- candidates: vec![candidate("A", "cand-a", 0.9), candidate("B", "cand-b", 0.5)],
- ..Default::default()
- });
- let reranker = reranker(&[]);
- let judge = judge(&["cand-a", "cand-b"]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![("A", "cand-a", 0.9), ("B", "cand-b", 0.5)]),
+ MockReranker::new(&[]),
+ judge(&["cand-a", "cand-b"]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- service.detect_new_task(new_task("NEW")).await.unwrap();
+ h.service.detect_new_task(new_task("NEW")).await.unwrap();
// B (0.5 < 0.74) never reaches the reranker or the judge.
- let calls = reranker.calls.lock().unwrap();
+ let calls = h.reranker.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].1, vec!["cand-a".to_string()]);
- drop(calls);
- assert_eq!(judged_right_sides(&judge), vec!["cand-a".to_string()]);
+ assert_eq!(judged_right_sides(&h.judge), vec!["cand-a".to_string()]);
}
#[tokio::test]
async fn detect_caps_judge_calls_at_max_candidates() {
- let repo = Arc::new(MockRepo {
- candidates: vec![
- candidate("A", "cand-a", 0.90),
- candidate("B", "cand-b", 0.85),
- candidate("C", "cand-c", 0.80),
- ],
- ..Default::default()
- });
- let reranker = reranker(&[]); // uniform → preserves vector order
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
let config = TaskDedupConfig {
max_judge_candidates: 2,
..Default::default()
};
- let service = build(config, &repo, &reranker, &judge, &notifier);
+ let h = build(
+ config,
+ MockVectorDb::with_results(vec![
+ ("A", "cand-a", 0.90),
+ ("B", "cand-b", 0.85),
+ ("C", "cand-c", 0.80),
+ ]),
+ MockReranker::new(&[]), // uniform → preserves vector order
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
+ );
- service.detect_new_task(new_task("NEW")).await.unwrap();
+ h.service.detect_new_task(new_task("NEW")).await.unwrap();
// Only the top 2 (by preserved order) are judged; C is dropped.
assert_eq!(
- judged_right_sides(&judge),
+ judged_right_sides(&h.judge),
vec!["cand-a".to_string(), "cand-b".to_string()]
);
}
#[tokio::test]
async fn detect_uses_rerank_order_to_pick_judged_candidate() {
- let repo = Arc::new(MockRepo {
- // A leads by vector score, but the reranker prefers B.
- candidates: vec![
- candidate("A", "cand-a", 0.90),
- candidate("B", "cand-b", 0.80),
- ],
- ..Default::default()
- });
- let reranker = reranker(&[("cand-a", 0.1), ("cand-b", 0.9)]);
- let judge = judge(&["cand-b"]);
- let notifier = Arc::new(MockNotifier::default());
let config = TaskDedupConfig {
max_judge_candidates: 1,
..Default::default()
};
- let service = build(config, &repo, &reranker, &judge, &notifier);
+ let h = build(
+ config,
+ // A leads by vector score, but the reranker prefers B.
+ MockVectorDb::with_results(vec![("A", "cand-a", 0.90), ("B", "cand-b", 0.80)]),
+ MockReranker::new(&[("cand-a", 0.1), ("cand-b", 0.9)]),
+ judge(&["cand-b"]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
+ );
- service.detect_new_task(new_task("NEW")).await.unwrap();
+ h.service.detect_new_task(new_task("NEW")).await.unwrap();
// Rerank promoted B above A, so B is the only candidate judged and matched.
- assert_eq!(judged_right_sides(&judge), vec!["cand-b".to_string()]);
- let upserts = repo.upserted_matches.lock().unwrap();
+ assert_eq!(judged_right_sides(&h.judge), vec!["cand-b".to_string()]);
+ let upserts = h.matches.upserted_matches.lock().unwrap();
assert_eq!(upserts.len(), 1);
let pair = (
upserts[0].task_id.clone(),
@@ -512,51 +616,43 @@ async fn detect_uses_rerank_order_to_pick_judged_candidate() {
#[tokio::test]
async fn detect_ignores_non_duplicate_judgement() {
- let repo = Arc::new(MockRepo {
- candidates: vec![candidate("A", "cand-a", 0.9)],
- ..Default::default()
- });
- let reranker = reranker(&[]);
- let judge = judge(&[]); // judge says "not a duplicate"
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![("A", "cand-a", 0.9)]),
+ MockReranker::new(&[]),
+ judge(&[]), // judge says "not a duplicate"
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- let active = service.detect_new_task(new_task("NEW")).await.unwrap();
+ let active = h.service.detect_new_task(new_task("NEW")).await.unwrap();
assert!(active.is_empty());
- assert!(repo.upserted_matches.lock().unwrap().is_empty());
- assert!(notifier.notified.lock().unwrap().is_empty());
+ assert!(h.matches.upserted_matches.lock().unwrap().is_empty());
+ assert!(h.notifier.notified.lock().unwrap().is_empty());
}
#[tokio::test]
async fn detect_closes_duplicate_component() {
- let repo = Arc::new(MockRepo {
- candidates: vec![candidate("A", "cand-a", 0.9)],
+ let matches = Arc::new(MockMatchRepo {
// An existing duplicate edge pulls C into the component.
component_extra: vec!["C".to_string()],
..Default::default()
});
- let reranker = reranker(&[]);
- let judge = judge(&["cand-a"]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![("A", "cand-a", 0.9)]),
+ MockReranker::new(&[]),
+ judge(&["cand-a"]),
+ Arc::new(MockNotifier::default()),
+ matches,
);
- service.detect_new_task(new_task("NEW")).await.unwrap();
+ h.service.detect_new_task(new_task("NEW")).await.unwrap();
// The full {A, C, NEW} component is closed into every pair.
- let mut pairs: Vec<(String, String)> = repo
+ let mut pairs: Vec<(String, String)> = h
+ .matches
.upserted_matches
.lock()
.unwrap()
@@ -580,26 +676,21 @@ async fn detect_closes_duplicate_component() {
#[tokio::test]
async fn similarity_search_filters_ranks_and_persists_nothing() {
- let repo = Arc::new(MockRepo {
- similarity_candidates: vec![
- sim_candidate("X", "cx", 0.9),
- sim_candidate("Y", "cy", 0.5), // below floor
- sim_candidate("Z", "cz", 0.8),
- ],
- ..Default::default()
- });
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![
+ ("X", "cx", 0.9),
+ ("Y", "cy", 0.5), // below floor
+ ("Z", "cz", 0.8),
+ ]),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- let results = service
+ let results = h
+ .service
.similarity_search("owner", None, "title", "body")
.await
.unwrap();
@@ -607,37 +698,45 @@ async fn similarity_search_filters_ranks_and_persists_nothing() {
// Y filtered out; X and Z surface in (preserved) order.
let ids: Vec<&str> = results.iter().map(|r| r.task_id.as_str()).collect();
assert_eq!(ids, vec!["X", "Z"]);
+ // Names are resolved via the match repo.
+ assert_eq!(results[0].task_name, "X name");
// The reranker ran on the survivors only.
- let calls = reranker.calls.lock().unwrap();
+ let calls = h.reranker.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].1, vec!["cx".to_string(), "cz".to_string()]);
- drop(calls);
+
+ // The similarity path does not scope-exclude self or dismissed pairs.
+ let params = h
+ .vector_db
+ .inner
+ .last_params
+ .lock()
+ .unwrap()
+ .clone()
+ .unwrap();
+ assert!(params.exclude_document_id.is_none());
+ assert!(!params.exclude_dismissed);
// Nothing was judged or persisted.
- assert!(judge.calls.lock().unwrap().is_empty());
- assert!(repo.upserted_embeddings.lock().unwrap().is_empty());
- assert!(repo.upserted_matches.lock().unwrap().is_empty());
+ assert!(h.judge.calls.lock().unwrap().is_empty());
+ assert!(h.vector_db.inner.upserted.lock().unwrap().is_empty());
+ assert!(h.matches.upserted_matches.lock().unwrap().is_empty());
}
#[tokio::test]
async fn similarity_search_orders_by_rerank_score() {
- let repo = Arc::new(MockRepo {
- similarity_candidates: vec![sim_candidate("X", "cx", 0.9), sim_candidate("Z", "cz", 0.8)],
- ..Default::default()
- });
- let reranker = reranker(&[("cx", 0.1), ("cz", 0.9)]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::with_results(vec![("X", "cx", 0.9), ("Z", "cz", 0.8)]),
+ MockReranker::new(&[("cx", 0.1), ("cz", 0.9)]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- let results = service
+ let results = h
+ .service
.similarity_search("owner", None, "title", "body")
.await
.unwrap();
@@ -648,24 +747,25 @@ async fn similarity_search_orders_by_rerank_score() {
#[tokio::test]
async fn similarity_search_truncates_to_duplicate_limit() {
- let repo = Arc::new(MockRepo {
- similarity_candidates: vec![
- sim_candidate("A", "ca", 0.95),
- sim_candidate("B", "cb", 0.90),
- sim_candidate("C", "cc", 0.85),
- ],
- ..Default::default()
- });
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
let config = TaskDedupConfig {
duplicate_limit: 2,
..Default::default()
};
- let service = build(config, &repo, &reranker, &judge, &notifier);
+ let h = build(
+ config,
+ MockVectorDb::with_results(vec![
+ ("A", "ca", 0.95),
+ ("B", "cb", 0.90),
+ ("C", "cc", 0.85),
+ ]),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
+ );
- let results = service
+ let results = h
+ .service
.similarity_search("owner", None, "title", "body")
.await
.unwrap();
@@ -680,71 +780,69 @@ async fn similarity_search_truncates_to_duplicate_limit() {
#[tokio::test]
async fn dismiss_matches_dismisses_and_notifies_both_sides() {
- let repo = Arc::new(MockRepo::default());
- let match_id = repo.add_active_match("D", "O");
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let matches = Arc::new(MockMatchRepo::default());
+ let match_id = matches.add_active_match("D", "O");
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::default(),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ matches,
);
- service
+ h.service
.dismiss_matches("D", &[match_id], "user")
.await
.unwrap();
- assert!(service.active_duplicates("D").await.unwrap().is_empty());
- let mut notified = notifier.notified.lock().unwrap().clone();
+ assert!(h.service.active_duplicates("D").await.unwrap().is_empty());
+ let mut notified = h.notifier.notified.lock().unwrap().clone();
notified.sort();
assert_eq!(notified, vec!["D".to_string(), "O".to_string()]);
}
#[tokio::test]
async fn dismiss_matches_errors_when_match_missing() {
- let repo = Arc::new(MockRepo::default());
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::default(),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ Arc::new(MockMatchRepo::default()),
);
- let error = service
+ let error = h
+ .service
.dismiss_matches("D", &[Uuid::new_v4()], "user")
.await
.unwrap_err();
assert!(matches!(error, TaskDedupError::MatchNotFound));
- assert!(notifier.notified.lock().unwrap().is_empty());
+ assert!(h.notifier.notified.lock().unwrap().is_empty());
}
#[tokio::test]
async fn ensure_match_contains_checks_membership() {
- let repo = Arc::new(MockRepo::default());
- let match_id = repo.add_active_match("D", "O");
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let matches = Arc::new(MockMatchRepo::default());
+ let match_id = matches.add_active_match("D", "O");
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::default(),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ matches,
);
- service.ensure_match_contains("D", match_id).await.unwrap();
+ h.service
+ .ensure_match_contains("D", match_id)
+ .await
+ .unwrap();
- let error = service
+ let error = h
+ .service
.ensure_match_contains("D", Uuid::new_v4())
.await
.unwrap_err();
@@ -753,43 +851,39 @@ async fn ensure_match_contains_checks_membership() {
#[tokio::test]
async fn dismiss_match_by_id_dismisses_and_notifies() {
- let repo = Arc::new(MockRepo::default());
- let match_id = repo.add_active_match("D", "O");
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let matches = Arc::new(MockMatchRepo::default());
+ let match_id = matches.add_active_match("D", "O");
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::default(),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ matches,
);
- service.dismiss_match_by_id(match_id).await.unwrap();
+ h.service.dismiss_match_by_id(match_id).await.unwrap();
- assert!(service.active_duplicates("D").await.unwrap().is_empty());
- let mut notified = notifier.notified.lock().unwrap().clone();
+ assert!(h.service.active_duplicates("D").await.unwrap().is_empty());
+ let mut notified = h.notifier.notified.lock().unwrap().clone();
notified.sort();
assert_eq!(notified, vec!["D".to_string(), "O".to_string()]);
}
#[tokio::test]
async fn active_duplicates_returns_the_other_side() {
- let repo = Arc::new(MockRepo::default());
- repo.add_active_match("D", "O");
- let reranker = reranker(&[]);
- let judge = judge(&[]);
- let notifier = Arc::new(MockNotifier::default());
- let service = build(
+ let matches = Arc::new(MockMatchRepo::default());
+ matches.add_active_match("D", "O");
+ let h = build(
TaskDedupConfig::default(),
- &repo,
- &reranker,
- &judge,
- &notifier,
+ MockVectorDb::default(),
+ MockReranker::new(&[]),
+ judge(&[]),
+ Arc::new(MockNotifier::default()),
+ matches,
);
- let duplicates = service.active_duplicates("D").await.unwrap();
+ let duplicates = h.service.active_duplicates("D").await.unwrap();
assert_eq!(duplicates.len(), 1);
assert_eq!(duplicates[0].task_id, "O");
}
diff --git a/rust/cloud-storage/task_dedup/src/lib.rs b/rust/cloud-storage/task_dedup/src/lib.rs
index 6f7a66f912..e2caf39e8a 100644
--- a/rust/cloud-storage/task_dedup/src/lib.rs
+++ b/rust/cloud-storage/task_dedup/src/lib.rs
@@ -1,15 +1,26 @@
#![deny(missing_docs)]
//! Task duplicate detection.
//!
-//! The crate keeps the duplicate-detection workflow behind domain ports so the
-//! embedding model, candidate retrieval, judge, persistence repo, and live
-//! update transport can be swapped independently.
+//! The crate keeps the duplicate-detection workflow behind ports so the judge,
+//! match persistence, and live-update transport can be swapped independently.
+//! Embedding, reranking, and vector storage are provided by the [`embedding`]
+//! crate's traits and injected as generic parameters into [`TaskDedupService`].
pub mod domain;
pub mod outbound;
+use embedding::embedding_provider::openai::{DIMS, TextEmbedding3Small};
+
pub use domain::models::{
- JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate,
- TaskSimilarityResult,
+ JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskSearchParameters, TaskSimilarityResult,
};
pub use domain::service::{TaskDedupConfig, TaskDedupService};
+use outbound::postgres::PgTaskVectorDb;
+use outbound::reranker::NoOpReranker;
+
+/// The production task-dedup service: OpenAI `text-embedding-3-small` embeddings,
+/// a Postgres/pgvector store, and the no-op reranker. Consumers depend on this
+/// concrete type so the generic [`TaskDedupService`] parameters do not leak into
+/// axum state and handler signatures.
+pub type PgTaskDedupService =
+ TaskDedupService<DIMS, TextEmbedding3Small, PgTaskVectorDb, NoOpReranker>;
diff --git a/rust/cloud-storage/task_dedup/src/outbound/embedding.rs b/rust/cloud-storage/task_dedup/src/outbound/embedding.rs
deleted file mode 100644
index b1e0cbe908..0000000000
--- a/rust/cloud-storage/task_dedup/src/outbound/embedding.rs
+++ /dev/null
@@ -1,213 +0,0 @@
-//! Embedding adapter for task duplicate detection.
-//!
-//! Embeddings are produced exclusively by OpenAI through the [`async-openai`]
-//! client. There is deliberately no local/offline fallback: if OpenAI is
-//! unavailable the call errors so the caller can skip (live path) or retry
-//! (backfill) rather than silently writing a non-comparable vector into the
-//! shared pgvector column.
-//!
-//! [`async-openai`]: https://docs.rs/async-openai
-
-use anyhow::Context;
-use async_openai::Client;
-use async_openai::config::OpenAIConfig;
-use async_openai::error::OpenAIError;
-use async_openai::types::embeddings::{CreateEmbeddingRequestArgs, EmbeddingInput};
-use async_trait::async_trait;
-
-use crate::domain::ports::TaskEmbedder;
-
-/// Expected embedding dimensions for the current default embedding model.
-pub const EMBEDDING_DIM: usize = 1536;
-
-/// Why a batch embedding request could not be produced.
-///
-/// This is the only OpenAI-derived type the crate exposes: callers (e.g. the
-/// embedding backfill) classify a failure as worth retrying versus worth
-/// isolating without depending on `async-openai` themselves.
-#[derive(Debug, thiserror::Error)]
-pub enum EmbedError {
- /// The request was rejected and retrying it unchanged will not help — e.g.
- /// an input over the model's token limit. Splitting the batch can isolate
- /// the offending input.
- #[error("openai rejected the embeddings request: {0}")]
- Fatal(String),
- /// A transient failure (rate limit, 5xx, network, or a malformed response)
- /// that is worth retrying later.
- #[error("openai embeddings temporarily unavailable: {0}")]
- Transient(String),
-}
-
-impl From<OpenAIError> for EmbedError {
- fn from(error: OpenAIError) -> Self {
- match error {
- // 4xx request rejections (e.g. context-length-exceeded) come back as
- // an ApiError tagged `invalid_request_error`; retrying won't help.
- OpenAIError::ApiError(api)
- if api.r#type.as_deref() == Some("invalid_request_error") =>
- {
- EmbedError::Fatal(api.to_string())
- }
- // Our own request/response validation (bad dimensions, count
- // mismatch, builder errors): the specific request is unusable, so
- // treat it as fatal and let bisection isolate it.
- OpenAIError::InvalidArgument(message) => EmbedError::Fatal(message),
- // Everything else — server errors the client already retried, rate
- // limits, network errors, malformed bodies — is transient.
- other => EmbedError::Transient(other.to_string()),
- }
- }
-}
-
-/// Embeds task text with OpenAI's embeddings API.
-///
-/// The [`async-openai`](https://docs.rs/async-openai) client owns request
-/// construction, response parsing, and rate-limit/5xx backoff. This type only
-/// adds the project-specific concern of validating the vector dimensionality
-/// before it reaches the fixed-width pgvector column.
-pub struct OpenAiTaskEmbedder {
- model: String,
- client: Client<OpenAIConfig>,
-}
-
-impl OpenAiTaskEmbedder {
- /// Builds an embedder for the given model, reading `OPENAI_API_KEY` from the
- /// environment if present.
- ///
- /// Unlike [`Self::from_env`] this never fails to construct: when the key is
- /// missing the embedder is still created and every embed call fails loudly
- /// at request time. This keeps long-lived services (which build the embedder
- /// during startup) booting in environments where embeddings are optional,
- /// without ever degrading to a local fallback vector.
- pub fn new(model: impl Into<String>) -> Self {
- let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_default();
- if api_key.trim().is_empty() {
- tracing::warn!(
- "OPENAI_API_KEY is not set; task embeddings will fail until it is configured"
- );
- }
- Self::with_api_key(model, api_key)
- }
-
- /// Builds an embedder, requiring `OPENAI_API_KEY` to be set and non-empty.
- ///
- /// Intended for one-off jobs (e.g. the embedding backfill) that should fail
- /// immediately rather than start without a working embedder.
- pub fn from_env(model: impl Into<String>) -> anyhow::Result<Self> {
- let api_key = std::env::var("OPENAI_API_KEY")
- .map_err(|_| anyhow::anyhow!("OPENAI_API_KEY must be set for the task embedder"))?;
- anyhow::ensure!(!api_key.trim().is_empty(), "OPENAI_API_KEY is empty");
- Ok(Self::with_api_key(model, api_key))
- }
-
- fn with_api_key(model: impl Into<String>, api_key: String) -> Self {
- let config = OpenAIConfig::new().with_api_key(api_key);
- Self {
- model: model.into(),
- client: Client::with_config(config),
- }
- }
-
- /// Embeds a batch of inputs in a single request, returning one vector per
- /// input in the same order. Returns an empty vec for an empty input.
- ///
- /// The underlying client retries rate limits and 5xx responses with
- /// exponential backoff. Remaining failures are classified into
- /// [`EmbedError::Transient`] (retry later) and [`EmbedError::Fatal`] (e.g.
- /// an input over the token limit — isolate it) so backfills can react.
- pub async fn embed_batch(&self, inputs: &[String]) -> Result<Vec<Vec<f32>>, EmbedError> {
- if inputs.is_empty() {
- return Ok(Vec::new());
- }
-
- let request = CreateEmbeddingRequestArgs::default()
- .model(self.model.clone())
- .input(EmbeddingInput::StringArray(inputs.to_vec()))
- .build()?;
-
- let mut response = self.client.embeddings().create(request).await?;
-
- if response.data.len() != inputs.len() {
- return Err(EmbedError::Fatal(format!(
- "expected {} embeddings, got {}",
- inputs.len(),
- response.data.len()
- )));
- }
-
- // OpenAI tags each embedding with its input index; sort so the returned
- // order matches `inputs` regardless of response ordering.
- response.data.sort_by_key(|embedding| embedding.index);
-
- response
- .data
- .into_iter()
- .map(|embedding| {
- if embedding.embedding.len() != EMBEDDING_DIM {
- return Err(EmbedError::Fatal(format!(
- "expected {EMBEDDING_DIM} embedding dimensions, got {}",
- embedding.embedding.len()
- )));
- }
- Ok(embedding.embedding)
- })
- .collect()
- }
-}
-
-#[async_trait]
-impl TaskEmbedder for OpenAiTaskEmbedder {
- async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>> {
- let inputs = [content.to_string()];
- self.embed_batch(&inputs)
- .await?
- .pop()
- .context("OpenAI returned no embedding for input")
- }
-}
-
-/// Deterministic, offline embedder used only by tests so duplicate-detection
-/// logic can be exercised without calling OpenAI.
-#[cfg(test)]
-pub struct LocalTaskEmbedder;
-
-#[cfg(test)]
-#[async_trait]
-impl TaskEmbedder for LocalTaskEmbedder {
- async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>> {
- Ok(local_embedding(content))
- }
-}
-
-/// Deterministic local embedding used only by tests. Hashes each token into a
-/// fixed bucket so semantically identical inputs produce identical vectors,
-/// which is enough for the pgvector similarity tests.
-#[cfg(test)]
-pub fn local_embedding(text: &str) -> Vec<f32> {
- let mut vector = vec![0.0_f32; EMBEDDING_DIM];
- for token in text
- .split(|ch: char| !ch.is_alphanumeric())
- .map(str::to_lowercase)
- .filter(|token| token.len() > 2)
- {
- let mut hash = 1469598103934665603_u64;
- for byte in token.as_bytes() {
- hash ^= u64::from(*byte);
- hash = hash.wrapping_mul(1099511628211);
- }
- let idx = (hash as usize) % EMBEDDING_DIM;
- let sign = if hash & 1 == 0 { 1.0 } else { -1.0 };
- vector[idx] += sign;
- }
-
- let norm = vector
- .iter()
- .map(|value| value * value)
- .sum::<f32>()
- .sqrt()
- .max(1.0);
- for value in &mut vector {
- *value /= norm;
- }
- vector
-}
diff --git a/rust/cloud-storage/task_dedup/src/outbound/judge.rs b/rust/cloud-storage/task_dedup/src/outbound/judge.rs
index dbdcd187f8..846dbaef78 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/judge.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/judge.rs
@@ -101,10 +101,23 @@ impl TaskDuplicateJudge for AgentDuplicateJudge {
}
}
-/// Deterministic judge for tests: treats two tasks as duplicates only when their
-/// embedding content is identical.
+/// Deterministic judge for tests: treats two tasks as duplicates when their
+/// texts contain the same set of word tokens, ignoring order and case. Order
+/// independence matters because a candidate's text is reconstructed by joining
+/// its embedded fields, whose order is not guaranteed.
pub struct LocalDuplicateJudge;
+/// Lowercased word tokens of `text`, sorted, for order-insensitive comparison.
+fn token_bag(text: &str) -> Vec<String> {
+ let mut tokens = text
+ .split(|ch: char| !ch.is_alphanumeric())
+ .filter(|token| !token.is_empty())
+ .map(str::to_lowercase)
+ .collect::<Vec<_>>();
+ tokens.sort();
+ tokens
+}
+
impl LocalDuplicateJudge {
/// Creates a local judge.
pub fn new() -> Self {
@@ -122,9 +135,9 @@ impl Default for LocalDuplicateJudge {
impl TaskDuplicateJudge for LocalDuplicateJudge {
async fn judge(&self, left: &str, right: &str) -> JudgeResult {
JudgeResult {
- is_duplicate: left.trim() == right.trim(),
+ is_duplicate: token_bag(left) == token_bag(right),
model: None,
- reason: Some("local exact-match judge".to_string()),
+ reason: Some("local token-bag judge".to_string()),
}
}
}
diff --git a/rust/cloud-storage/task_dedup/src/outbound/mod.rs b/rust/cloud-storage/task_dedup/src/outbound/mod.rs
index 781fb38710..436e82cb47 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/mod.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/mod.rs
@@ -1,7 +1,6 @@
//! Outbound adapters for task duplicate detection.
pub mod connection_gateway;
-pub mod embedding;
pub mod judge;
pub mod postgres;
pub mod reranker;
diff --git a/rust/cloud-storage/task_dedup/src/outbound/postgres.rs b/rust/cloud-storage/task_dedup/src/outbound/postgres.rs
index f2b527e913..6429d18445 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/postgres.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/postgres.rs
@@ -1,214 +1,235 @@
-//! Postgres task duplicate repo.
+//! Postgres adapters for task duplicate detection.
+//!
+//! [`PgTaskVectorDb`] implements the embedding crate's [`VectorDb`] over the
+//! `task_duplicate_embedding` table (one row per `(document_id, search_key)`
+//! field). [`PgTaskMatchRepo`] owns the duplicate match graph
+//! (`task_duplicate_match`).
#[cfg(test)]
mod test;
+use std::collections::HashMap;
+
+use anyhow::Context;
use async_trait::async_trait;
+use embedding::embedding_provider::openai::DIMS;
+use embedding::{Content, KeyedEmbedding, LabeledEmbedding, Match, SearchResults, VectorStore};
use sqlx::PgPool;
use uuid::Uuid;
-use crate::domain::models::{
- NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate, TaskSimilarityCandidate,
-};
-use crate::domain::ports::TaskDedupRepo;
+use crate::domain::models::{TaskDedupError, TaskDuplicate, TaskSearchParameters};
+use crate::domain::ports::TaskMatchRepo;
use crate::domain::service::ordered_pair;
-/// A single task embedding to upsert in bulk.
-#[derive(Clone)]
-pub struct TaskEmbeddingUpsert {
- /// Document id of the task.
- pub document_id: String,
- /// Embedded content (the output of `task_embedding_content`).
- pub content: String,
- /// Embedding vector.
- pub embedding: Vec<f32>,
-}
-
-/// Postgres-backed task duplicate repo using pgvector.
+/// Postgres/pgvector implementation of [`VectorDb`] for task embeddings.
+///
+/// Each task contributes one row per embeddable field (`title`, `body`); the
+/// composite primary key `(document_id, search_key)` keeps them distinct.
+///
+/// Duplicate detection uses a single embedding model everywhere, so no model
+/// identifier is stored per row.
#[derive(Clone)]
-pub struct PgTaskDedupRepo {
+pub struct PgTaskVectorDb {
pool: PgPool,
}
-impl PgTaskDedupRepo {
- /// Creates a Postgres repo.
+impl PgTaskVectorDb {
+ /// Creates a store over `pool`.
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
+}
+
+impl VectorStore<DIMS> for PgTaskVectorDb {
+ type Error = anyhow::Error;
+ type Metadata = String;
+ type SearchParameters = TaskSearchParameters;
- /// Upserts many task embeddings in a single statement. Like
- /// [`TaskDedupRepo::upsert_embedding`], existing rows are updated rather than
- /// duplicated (the `document_id` primary key drives the conflict). Used by
- /// the embedding backfill to avoid one round-trip per task.
- pub async fn bulk_upsert_embeddings(
+ async fn upsert_embeddings<'a>(
&self,
- model: &str,
- items: &[TaskEmbeddingUpsert],
- ) -> Result<(), TaskDedupError> {
- if items.is_empty() {
+ metadata: String,
+ embeddings: Vec<LabeledEmbedding<'a, DIMS>>,
+ ) -> anyhow::Result<()> {
+ if embeddings.is_empty() {
return Ok(());
}
- let document_ids: Vec<String> = items.iter().map(|item| item.document_id.clone()).collect();
- let contents: Vec<String> = items.iter().map(|item| item.content.clone()).collect();
- let embeddings: Vec<String> = items
+ let search_keys: Vec<String> = embeddings
+ .iter()
+ .map(|field| field.search_key.to_string())
+ .collect();
+ let contents: Vec<String> = embeddings
.iter()
- .map(|item| vector_sql_literal(&item.embedding))
+ .map(|field| field.content.as_ref().to_string())
+ .collect();
+ let vectors: Vec<String> = embeddings
+ .iter()
+ .map(|field| vector_sql_literal(&field.embedding))
.collect();
sqlx::query!(
r#"
- INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)
- SELECT doc_id, $1, content, embedding_text::vector
- FROM UNNEST($2::text[], $3::text[], $4::text[])
- AS t(doc_id, content, embedding_text)
- ON CONFLICT (document_id) DO UPDATE
- SET model = EXCLUDED.model,
- content = EXCLUDED.content,
+ INSERT INTO task_duplicate_embedding (document_id, search_key, content, embedding)
+ SELECT $1, sk, ct, emb::vector
+ FROM unnest($2::text[], $3::text[], $4::text[]) AS t(sk, ct, emb)
+ ON CONFLICT (document_id, search_key) DO UPDATE
+ SET content = EXCLUDED.content,
embedding = EXCLUDED.embedding,
updated_at = NOW()
"#,
- model,
- &document_ids,
+ metadata,
+ &search_keys,
&contents,
- &embeddings,
+ &vectors,
)
.execute(&self.pool)
.await?;
Ok(())
}
-}
-#[async_trait]
-impl TaskDedupRepo for PgTaskDedupRepo {
- async fn upsert_embedding(
+ async fn cosine_search(
&self,
- document_id: &str,
- model: &str,
- content: &str,
- embedding: &[f32],
- ) -> Result<(), TaskDedupError> {
- let embedding_sql = vector_sql_literal(embedding);
- sqlx::query!(
- r#"
- INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)
- VALUES ($1, $2, $3, $4::text::vector)
- ON CONFLICT (document_id) DO UPDATE
- SET model = EXCLUDED.model,
- content = EXCLUDED.content,
- embedding = EXCLUDED.embedding,
- updated_at = NOW()
- "#,
- document_id,
- model,
- content,
- embedding_sql,
- )
- .execute(&self.pool)
- .await?;
- Ok(())
- }
+ query: Vec<KeyedEmbedding<DIMS>>,
+ params: TaskSearchParameters,
+ ) -> anyhow::Result<Vec<SearchResults<String, DIMS>>> {
+ if query.is_empty() {
+ return Ok(Vec::new());
+ }
- async fn candidates(
- &self,
- task: &NewTask,
- embedding: &[f32],
- limit: i64,
- ) -> Result<Vec<TaskDuplicateCandidate>, TaskDedupError> {
- let embedding_sql = vector_sql_literal(embedding);
+ let query_keys: Vec<String> = query.iter().map(|q| q.search_key.to_string()).collect();
+ let query_vectors: Vec<String> = query
+ .iter()
+ .map(|q| vector_sql_literal(&q.embedding))
+ .collect();
+
+ // Each candidate field is scored by its best similarity to ANY query
+ // field, giving the full query × stored cross-product (title↔title,
+ // title↔body, body↔title, body↔body). Entities are ranked by their best
+ // field score and capped at `limit`; all of a kept entity's field rows
+ // are returned so the service can reconstruct its text.
+ //
+ // Iterative index scan keeps recall high despite the owner/team,
+ // self-, and dismissed-pair filters dropping rows after the HNSW scan.
+ // SET LOCAL binds to the transaction's connection, so the search must run
+ // in the same transaction to see it.
+ let mut tx = self.pool.begin().await?;
+ sqlx::query!("SET LOCAL hnsw.iterative_scan = relaxed_order")
+ .execute(&mut *tx)
+ .await?;
let rows = sqlx::query!(
r#"
+ WITH query AS (
+ SELECT key, vec::vector AS vec
+ FROM unnest($1::text[], $2::text[]) AS t(key, vec)
+ ),
+ scored AS (
+ SELECT
+ e.document_id,
+ e.search_key,
+ e.content,
+ e.embedding::text AS embedding_text,
+ MAX(1 - (e.embedding <=> q.vec))::real AS score
+ FROM task_duplicate_embedding e
+ JOIN "Document" d ON d.id = e.document_id
+ JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'
+ LEFT JOIN team_task tt ON tt.document_id = d.id
+ CROSS JOIN query q
+ WHERE d."deletedAt" IS NULL
+ AND (
+ d.owner = $3
+ OR ($4::uuid IS NOT NULL AND tt.team_id = $4)
+ )
+ AND ($5::text IS NULL OR e.document_id <> $5)
+ AND (
+ NOT $6
+ OR NOT EXISTS (
+ SELECT 1
+ FROM task_duplicate_match m
+ WHERE m.task_id = LEAST($5, e.document_id)
+ AND m.duplicate_task_id = GREATEST($5, e.document_id)
+ AND m.status = 'dismissed'
+ )
+ )
+ GROUP BY e.document_id, e.search_key, e.content, e.embedding
+ ),
+ ranked AS (
+ SELECT document_id, MAX(score) AS best
+ FROM scored
+ GROUP BY document_id
+ ORDER BY best DESC
+ LIMIT $7
+ )
SELECT
- e.document_id,
- e.content,
- 1 - (e.embedding <=> $2::text::vector) AS "vector_score!"
- FROM task_duplicate_embedding e
- JOIN "Document" d ON d.id = e.document_id
- JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'
- LEFT JOIN team_task tt ON tt.document_id = d.id
- WHERE e.document_id <> $1
- AND d."deletedAt" IS NULL
- AND (
- d.owner = $3
- OR ($4::uuid IS NOT NULL AND tt.team_id = $4)
- )
- AND NOT EXISTS (
- SELECT 1
- FROM task_duplicate_match m
- WHERE (
- m.task_id = LEAST($1, e.document_id)
- AND m.duplicate_task_id = GREATEST($1, e.document_id)
- AND m.status = 'dismissed'
- )
- )
- ORDER BY e.embedding <=> $2::text::vector
- LIMIT $5
+ s.document_id AS "document_id!",
+ s.search_key AS "search_key!",
+ s.content AS "content!",
+ s.embedding_text AS "embedding_text!",
+ s.score AS "score!"
+ FROM scored s
+ JOIN ranked r ON r.document_id = s.document_id
+ ORDER BY r.best DESC, s.document_id, s.score DESC
"#,
- task.document_id.as_str(),
- embedding_sql,
- task.owner.as_str(),
- task.team_id,
- limit,
+ &query_keys,
+ &query_vectors,
+ params.owner,
+ params.team_id,
+ params.exclude_document_id,
+ params.exclude_dismissed,
+ params.limit,
)
- .fetch_all(&self.pool)
+ .fetch_all(&mut *tx)
.await?;
+ tx.commit().await?;
- Ok(rows
- .into_iter()
- .map(|row| TaskDuplicateCandidate {
- document_id: row.document_id,
- content: row.content,
- vector_score: row.vector_score,
- })
- .collect())
+ // Group the flat (document_id, field) rows into one SearchResults per
+ // entity, preserving the best-first order established by the query.
+ let mut results: Vec<SearchResults<String, DIMS>> = Vec::new();
+ for row in rows {
+ let Some(search_key) = search_key_static(&row.search_key) else {
+ tracing::warn!(
+ search_key = %row.search_key,
+ document_id = %row.document_id,
+ "skipping task embedding row with unknown search_key"
+ );
+ continue;
+ };
+ let embedding = parse_vector(&row.embedding_text)
+ .with_context(|| format!("invalid stored embedding for {}", row.document_id))?;
+ let matched = Match {
+ score: row.score,
+ embedding: LabeledEmbedding {
+ search_key,
+ content: Content::Owned(row.content),
+ embedding,
+ },
+ };
+ match results.last_mut() {
+ Some(last) if last.metadata == row.document_id => last.matches.push(matched),
+ _ => results.push(SearchResults {
+ metadata: row.document_id,
+ matches: vec![matched],
+ }),
+ }
+ }
+ Ok(results)
}
+}
- async fn similarity_candidates(
- &self,
- owner: &str,
- team_id: Option<Uuid>,
- embedding: &[f32],
- limit: i64,
- ) -> Result<Vec<TaskSimilarityCandidate>, TaskDedupError> {
- let embedding_sql = vector_sql_literal(embedding);
- let rows = sqlx::query!(
- r#"
- SELECT
- e.document_id,
- d.name AS "name!",
- e.content,
- 1 - (e.embedding <=> $3::text::vector) AS "vector_score!"
- FROM task_duplicate_embedding e
- JOIN "Document" d ON d.id = e.document_id
- JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'
- LEFT JOIN team_task tt ON tt.document_id = d.id
- WHERE d."deletedAt" IS NULL
- AND (
- d.owner = $1
- OR ($2::uuid IS NOT NULL AND tt.team_id = $2)
- )
- ORDER BY e.embedding <=> $3::text::vector
- LIMIT $4
- "#,
- owner,
- team_id,
- embedding_sql,
- limit,
- )
- .fetch_all(&self.pool)
- .await?;
+/// Postgres-backed duplicate match graph.
+#[derive(Clone)]
+pub struct PgTaskMatchRepo {
+ pool: PgPool,
+}
- Ok(rows
- .into_iter()
- .map(|row| TaskSimilarityCandidate {
- document_id: row.document_id,
- name: row.name,
- content: row.content,
- vector_score: row.vector_score,
- })
- .collect())
+impl PgTaskMatchRepo {
+ /// Creates a match repo over `pool`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
}
+}
+#[async_trait]
+impl TaskMatchRepo for PgTaskMatchRepo {
async fn upsert_match(
&self,
task_id: &str,
@@ -433,14 +454,80 @@ impl TaskDedupRepo for PgTaskDedupRepo {
.await?;
Ok(())
}
+
+ async fn task_names(
+ &self,
+ document_ids: &[String],
+ ) -> Result<HashMap<String, String>, TaskDedupError> {
+ if document_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, name
+ FROM "Document"
+ WHERE id = ANY($1)
+ AND "deletedAt" IS NULL
+ "#,
+ document_ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(rows.into_iter().map(|row| (row.id, row.name)).collect())
+ }
}
-/// Converts an embedding vector into a pgvector literal.
+/// Formats an embedding as the pgvector text literal `[a,b,c]` used for the
+/// `text::vector` casts in the queries above.
pub fn vector_sql_literal(embedding: &[f32]) -> String {
- let values = embedding
- .iter()
- .map(|value| format!("{value:.8}"))
- .collect::<Vec<_>>()
- .join(",");
- format!("[{values}]")
+ let mut literal = String::with_capacity(embedding.len() * 8 + 2);
+ literal.push('[');
+ for (index, value) in embedding.iter().enumerate() {
+ if index > 0 {
+ literal.push(',');
+ }
+ literal.push_str(&value.to_string());
+ }
+ literal.push(']');
+ literal
+}
+
+/// Parses a pgvector text literal (`[a,b,c]`) back into a fixed-size embedding.
+fn parse_vector(text: &str) -> anyhow::Result<[f32; DIMS]> {
+ let inner = text.trim().trim_start_matches('[').trim_end_matches(']');
+ let mut embedding = [0.0_f32; DIMS];
+ let mut count = 0usize;
+ for part in inner.split(',') {
+ let part = part.trim();
+ if part.is_empty() {
+ continue;
+ }
+ if count >= DIMS {
+ anyhow::bail!("embedding has more than {DIMS} dimensions");
+ }
+ embedding[count] = part
+ .parse()
+ .with_context(|| format!("invalid embedding component {part:?}"))?;
+ count += 1;
+ }
+ if count != DIMS {
+ anyhow::bail!("expected {DIMS} dimensions, got {count}");
+ }
+ Ok(embedding)
+}
+
+/// Maps a `search_key` string read from the database back to one of the known
+/// static keys, so it satisfies the `&'static str` [`SearchKey`](embedding::SearchKey).
+///
+/// Returns `None` for unrecognized keys (e.g. a future field written by a newer
+/// build, or bad data). Callers skip those rows rather than leaking the string
+/// into `'static`, which would grow the heap permanently on a mixed-version
+/// rollout.
+fn search_key_static(key: &str) -> Option<&'static str> {
+ match key {
+ "title" => Some("title"),
+ "body" => Some("body"),
+ _ => None,
+ }
}
diff --git a/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs b/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs
index b10f07330d..87e5ff5993 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs
@@ -1,14 +1,16 @@
use std::sync::Arc;
+use embedding::embedding_provider::openai::DIMS;
+use embedding::{Content, Embeddable, EmbeddingModel, LabeledEmbedding};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::PgPool;
use super::*;
+use crate::domain::models::NewTask;
use crate::domain::ports::TaskDedupNotifier;
-use crate::domain::service::{TaskDedupConfig, TaskDedupService, task_embedding_content};
-use crate::outbound::embedding::{LocalTaskEmbedder, local_embedding};
+use crate::domain::service::{TaskDedupConfig, TaskDedupService};
use crate::outbound::judge::LocalDuplicateJudge;
-use crate::outbound::reranker::NoOpTaskReranker;
+use crate::outbound::reranker::NoOpReranker;
const OWNER: &str = "macro|[email protected]";
const TEAM_ID: Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");
@@ -16,6 +18,8 @@ const TASK_ONE: &str = "d1000000-0000-0000-0000-000000000001";
const TASK_TWO: &str = "d1000000-0000-0000-0000-000000000002";
const TASK_THREE: &str = "d1000000-0000-0000-0000-000000000003";
+type TestService = TaskDedupService<DIMS, LocalEmbedder, PgTaskVectorDb, NoOpReranker>;
+
struct NoopNotifier;
#[async_trait::async_trait]
@@ -25,15 +29,69 @@ impl TaskDedupNotifier for NoopNotifier {
}
}
-fn service(pool: PgPool) -> TaskDedupService {
- let config = TaskDedupConfig::default();
+/// Deterministic, offline embedder so duplicate-detection logic can be exercised
+/// without calling OpenAI. Each field is embedded independently with
+/// [`local_embedding`].
+struct LocalEmbedder;
+
+impl EmbeddingModel<DIMS> for LocalEmbedder {
+ async fn embed(
+ &self,
+ content: &(dyn Embeddable + Sync),
+ ) -> anyhow::Result<Vec<LabeledEmbedding<'static, DIMS>>> {
+ Ok(content
+ .embedding_content()
+ .into_iter()
+ .map(|(search_key, text)| LabeledEmbedding {
+ search_key,
+ embedding: local_embedding(text.as_ref()),
+ content: Content::Owned(text.into_owned()),
+ })
+ .collect())
+ }
+}
+
+/// Deterministic local embedding used only by tests. Hashes each token into a
+/// fixed bucket so semantically identical inputs produce identical vectors,
+/// which is enough for the pgvector similarity tests.
+fn local_embedding(text: &str) -> [f32; DIMS] {
+ let mut vector = [0.0_f32; DIMS];
+ for token in text
+ .split(|ch: char| !ch.is_alphanumeric())
+ .map(str::to_lowercase)
+ .filter(|token| token.len() > 2)
+ {
+ let mut hash = 1469598103934665603_u64;
+ for byte in token.as_bytes() {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(1099511628211);
+ }
+ let idx = (hash as usize) % DIMS;
+ let sign = if hash & 1 == 0 { 1.0 } else { -1.0 };
+ vector[idx] += sign;
+ }
+
+ let norm = vector
+ .iter()
+ .map(|value| value * value)
+ .sum::<f32>()
+ .sqrt()
+ .max(1.0);
+ for value in &mut vector {
+ *value /= norm;
+ }
+ vector
+}
+
+fn service(pool: PgPool) -> TestService {
TaskDedupService::new(
- config.clone(),
- Arc::new(PgTaskDedupRepo::new(pool)),
- Arc::new(LocalTaskEmbedder),
- Arc::new(NoOpTaskReranker),
+ TaskDedupConfig::default(),
+ LocalEmbedder,
+ PgTaskVectorDb::new(pool.clone()),
+ NoOpReranker,
Arc::new(LocalDuplicateJudge::new()),
Arc::new(NoopNotifier),
+ Arc::new(PgTaskMatchRepo::new(pool)),
)
}
@@ -78,21 +136,25 @@ async fn insert_team_task(pool: &PgPool, document_id: &str, task_num: i32) {
.unwrap();
}
-async fn insert_embedding(pool: &PgPool, document_id: &str, content: &str) {
- let embedding = vector_sql_literal(&local_embedding(content));
- sqlx::query!(
- r#"
- INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)
- VALUES ($1, $2, $3, $4::text::vector)
- "#,
- document_id,
- "text-embedding-3-small",
- content,
- embedding,
- )
- .execute(pool)
- .await
- .unwrap();
+/// Seeds the two per-field embeddings (`title`, `body`) a task would have after
+/// the live pipeline embedded it.
+async fn insert_task_embedding(pool: &PgPool, document_id: &str, title: &str, body: &str) {
+ for (search_key, text) in [("title", title), ("body", body)] {
+ let embedding = vector_sql_literal(&local_embedding(text));
+ sqlx::query!(
+ r#"
+ INSERT INTO task_duplicate_embedding (document_id, search_key, content, embedding)
+ VALUES ($1, $2, $3, $4::text::vector)
+ "#,
+ document_id,
+ search_key,
+ text,
+ embedding,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
}
async fn insert_match(pool: &PgPool, task_id: &str, duplicate_task_id: &str) -> Uuid {
@@ -131,6 +193,20 @@ async fn setup_tasks(pool: &PgPool) {
insert_team_task(pool, TASK_THREE, 3).await;
}
+const DETECTION_TITLE: &str = "Add duplicate task detection";
+const DETECTION_BODY: &str =
+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.";
+
+fn detection_task(document_id: &str) -> NewTask {
+ NewTask {
+ document_id: document_id.to_string(),
+ owner: OWNER.to_string(),
+ team_id: Some(TEAM_ID),
+ title: DETECTION_TITLE.to_string(),
+ markdown: DETECTION_BODY.to_string(),
+ }
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -138,61 +214,112 @@ async fn setup_tasks(pool: &PgPool) {
scripts("documents_test_data")
)
)]
-async fn bulk_upsert_embeddings_inserts_and_updates(pool: PgPool) {
+async fn upsert_embeddings_inserts_and_updates(pool: PgPool) {
setup_tasks(&pool).await;
- let repo = PgTaskDedupRepo::new(pool.clone());
-
- // Insert two embeddings in one call.
- repo.bulk_upsert_embeddings(
- "text-embedding-3-small",
- &[
- TaskEmbeddingUpsert {
- document_id: TASK_ONE.to_string(),
- content: "first".to_string(),
- embedding: local_embedding("first"),
- },
- TaskEmbeddingUpsert {
- document_id: TASK_TWO.to_string(),
- content: "second".to_string(),
- embedding: local_embedding("second"),
- },
- ],
+ let vector_db = PgTaskVectorDb::new(pool.clone());
+
+ // Insert a task's two fields.
+ vector_db
+ .upsert_embeddings(
+ TASK_ONE.to_string(),
+ vec![
+ LabeledEmbedding {
+ search_key: "title",
+ content: Content::Owned("first title".to_string()),
+ embedding: local_embedding("first title"),
+ },
+ LabeledEmbedding {
+ search_key: "body",
+ content: Content::Owned("first body".to_string()),
+ embedding: local_embedding("first body"),
+ },
+ ],
+ )
+ .await
+ .unwrap();
+
+ let count = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding WHERE document_id = $1"#,
+ TASK_ONE,
)
+ .fetch_one(&pool)
.await
.unwrap();
+ assert_eq!(count, 2);
- let count = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding"#)
- .fetch_one(&pool)
+ // Re-upsert the title field with new content: updates in place per
+ // (document_id, search_key), no duplicate row.
+ vector_db
+ .upsert_embeddings(
+ TASK_ONE.to_string(),
+ vec![LabeledEmbedding {
+ search_key: "title",
+ content: Content::Owned("first title updated".to_string()),
+ embedding: local_embedding("first title updated"),
+ }],
+ )
.await
.unwrap();
- assert_eq!(count, 2);
- // Re-upsert TASK_ONE with new content: updates in place, no duplicate row.
- repo.bulk_upsert_embeddings(
- "text-embedding-3-small",
- &[TaskEmbeddingUpsert {
- document_id: TASK_ONE.to_string(),
- content: "first updated".to_string(),
- embedding: local_embedding("first updated"),
- }],
+ let count = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding WHERE document_id = $1"#,
+ TASK_ONE,
)
+ .fetch_one(&pool)
.await
.unwrap();
-
- let count = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding"#)
- .fetch_one(&pool)
- .await
- .unwrap();
assert_eq!(count, 2);
let content = sqlx::query_scalar!(
- r#"SELECT content FROM task_duplicate_embedding WHERE document_id = $1"#,
+ r#"SELECT content FROM task_duplicate_embedding WHERE document_id = $1 AND search_key = 'title'"#,
TASK_ONE,
)
.fetch_one(&pool)
.await
.unwrap();
- assert_eq!(content, "first updated");
+ assert_eq!(content, "first title updated");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../documents/fixtures",
+ scripts("documents_test_data")
+ )
+)]
+async fn cross_field_match_query_title_to_stored_body(pool: PgPool) {
+ setup_tasks(&pool).await;
+ // TASK_TWO's BODY shares tokens only with the QUERY's TITLE. No same-key
+ // overlap exists, so this only surfaces if the cross-product is OR'd.
+ insert_task_embedding(
+ &pool,
+ TASK_TWO,
+ "alpha bravo charlie delta",
+ "echo foxtrot golf hotel",
+ )
+ .await;
+
+ let service = service(pool.clone());
+ let results = service
+ .similarity_search(
+ OWNER,
+ Some(TEAM_ID),
+ // query title == TASK_TWO body
+ "echo foxtrot golf hotel",
+ // query body matches nothing
+ "india juliet kilo lima",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ results
+ .iter()
+ .map(|r| r.task_id.as_str())
+ .collect::<Vec<_>>(),
+ vec![TASK_TWO],
+ "query-title vs stored-body should be an OR hit"
+ );
}
#[sqlx::test(
@@ -280,24 +407,11 @@ async fn deleted_duplicate_tasks_are_hidden(pool: PgPool) {
)]
async fn detection_inserts_match_for_similar_existing_task(pool: PgPool) {
setup_tasks(&pool).await;
-
- let existing = task_embedding_content(
- "Add duplicate task detection",
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",
- );
- insert_embedding(&pool, TASK_TWO, &existing).await;
+ insert_task_embedding(&pool, TASK_TWO, DETECTION_TITLE, DETECTION_BODY).await;
let service = service(pool.clone());
service
- .detect_new_task(NewTask {
- document_id: TASK_ONE.to_string(),
- owner: OWNER.to_string(),
- team_id: Some(TEAM_ID),
- title: "Add duplicate task detection".to_string(),
- markdown:
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill."
- .to_string(),
- })
+ .detect_new_task(detection_task(TASK_ONE))
.await
.unwrap();
@@ -316,24 +430,11 @@ async fn detection_inserts_match_for_similar_existing_task(pool: PgPool) {
async fn detection_closes_existing_duplicate_component(pool: PgPool) {
setup_tasks(&pool).await;
insert_match(&pool, TASK_TWO, TASK_THREE).await;
-
- let existing = task_embedding_content(
- "Add duplicate task detection",
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",
- );
- insert_embedding(&pool, TASK_TWO, &existing).await;
+ insert_task_embedding(&pool, TASK_TWO, DETECTION_TITLE, DETECTION_BODY).await;
let service = service(pool.clone());
service
- .detect_new_task(NewTask {
- document_id: TASK_ONE.to_string(),
- owner: OWNER.to_string(),
- team_id: Some(TEAM_ID),
- title: "Add duplicate task detection".to_string(),
- markdown:
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill."
- .to_string(),
- })
+ .detect_new_task(detection_task(TASK_ONE))
.await
.unwrap();
@@ -358,30 +459,18 @@ async fn detection_closes_existing_duplicate_component(pool: PgPool) {
)]
async fn similarity_search_returns_similar_without_persisting(pool: PgPool) {
setup_tasks(&pool).await;
-
- let similar = task_embedding_content(
- "Add duplicate task detection",
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",
- );
- insert_embedding(&pool, TASK_TWO, &similar).await;
- insert_embedding(
+ insert_task_embedding(&pool, TASK_TWO, DETECTION_TITLE, DETECTION_BODY).await;
+ insert_task_embedding(
&pool,
TASK_THREE,
- &task_embedding_content(
- "Fix unrelated billing copy",
- "Update subscription receipt text.",
- ),
+ "Fix unrelated billing copy",
+ "Update subscription receipt text.",
)
.await;
let service = service(pool.clone());
let results = service
- .similarity_search(
- OWNER,
- Some(TEAM_ID),
- "Add duplicate task detection",
- "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",
- )
+ .similarity_search(OWNER, Some(TEAM_ID), DETECTION_TITLE, DETECTION_BODY)
.await
.unwrap();
@@ -390,14 +479,14 @@ async fn similarity_search_returns_similar_without_persisting(pool: PgPool) {
assert_eq!(results[0].task_id, TASK_TWO);
assert_eq!(results[0].task_name, "Detect duplicate tasks");
- // Nothing was persisted for the unsaved task: no extra embedding rows
- // (only the two we seeded) and no match rows at all.
+ // Nothing was persisted for the unsaved task: only the seeded embeddings
+ // (two fields per seeded task) and no match rows at all.
let embedding_count =
sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding"#)
.fetch_one(&pool)
.await
.unwrap();
- assert_eq!(embedding_count, 2);
+ assert_eq!(embedding_count, 4);
let match_count =
sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_match"#)
diff --git a/rust/cloud-storage/task_dedup/src/outbound/reranker.rs b/rust/cloud-storage/task_dedup/src/outbound/reranker.rs
index 6305e34607..ec85628c54 100644
--- a/rust/cloud-storage/task_dedup/src/outbound/reranker.rs
+++ b/rust/cloud-storage/task_dedup/src/outbound/reranker.rs
@@ -1,20 +1,38 @@
//! Reranker adapters for task duplicate detection.
-use async_trait::async_trait;
+use embedding::{Content, RerankModel, Reranked, SearchResults};
-use crate::domain::ports::TaskReranker;
-
-/// No-op reranker: assigns every document the same score, leaving the upstream
-/// vector-similarity ordering untouched (the service sorts stably).
+/// No-op reranker: preserves the upstream vector-similarity ordering by handing
+/// every candidate back in input order, carrying its existing vector-similarity
+/// score through unchanged.
///
/// This is the default until a real cross-encoder is wired up. A production
/// implementation — e.g. a Cohere rerank connection — implements the same
-/// [`TaskReranker`] port and can be swapped in without touching the service.
-pub struct NoOpTaskReranker;
+/// [`RerankModel`] and can be swapped in without touching the service.
+#[derive(Clone, Copy, Default)]
+pub struct NoOpReranker;
-#[async_trait]
-impl TaskReranker for NoOpTaskReranker {
- async fn rerank(&self, _query: &str, documents: &[String]) -> anyhow::Result<Vec<f64>> {
- Ok(vec![0.0; documents.len()])
+impl<const DIMS: usize> RerankModel<DIMS> for NoOpReranker {
+ async fn rerank<'a, T: Send>(
+ &self,
+ _query: Content<'a>,
+ candidates: Vec<SearchResults<T, DIMS>>,
+ ) -> anyhow::Result<Vec<Reranked<T>>> {
+ Ok(candidates
+ .into_iter()
+ .map(|result| {
+ // Pass the best vector-similarity score through unchanged rather
+ // than imposing a rerank score of our own.
+ let score = result
+ .matches
+ .iter()
+ .map(|matched| matched.score)
+ .fold(f32::NEG_INFINITY, f32::max);
+ Reranked {
+ item: result.metadata,
+ score,
+ }
+ })
+ .collect())
}
}
diff --git a/rust/cloud-storage/task_dedup/tests/empty_task_embedding.rs b/rust/cloud-storage/task_dedup/tests/empty_task_embedding.rs
new file mode 100644
index 0000000000..80ebf3ca5f
--- /dev/null
+++ b/rust/cloud-storage/task_dedup/tests/empty_task_embedding.rs
@@ -0,0 +1,250 @@
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use embedding::{
+ Content, Embeddable, EmbeddingModel, KeyedEmbedding, LabeledEmbedding, RerankModel, Reranked,
+ SearchResults, VectorStore,
+};
+use task_dedup::domain::ports::{TaskDedupNotifier, TaskDuplicateJudge, TaskMatchRepo};
+use task_dedup::{
+ JudgeResult, NewTask, TaskDedupConfig, TaskDedupError, TaskDedupService, TaskDuplicate,
+ TaskSearchParameters,
+};
+use uuid::Uuid;
+
+const DIMS: usize = 4;
+
+type Service = TaskDedupService<DIMS, MockEmbedder, MockVectorDb, MockReranker>;
+
+struct MockEmbedder;
+
+impl EmbeddingModel<DIMS> for MockEmbedder {
+ async fn embed(
+ &self,
+ content: &(dyn Embeddable + Sync),
+ ) -> anyhow::Result<Vec<LabeledEmbedding<'static, DIMS>>> {
+ Ok(content
+ .embedding_content()
+ .into_iter()
+ .map(|(search_key, text)| LabeledEmbedding {
+ search_key,
+ content: Content::Owned(text.into_owned()),
+ embedding: [0.0; DIMS],
+ })
+ .collect())
+ }
+}
+
+#[derive(Clone, Default)]
+struct MockVectorDb {
+ upserted_embeddings: Arc<Mutex<Vec<Vec<(&'static str, String)>>>>,
+ last_query: Arc<Mutex<Option<Vec<&'static str>>>>,
+}
+
+impl VectorStore<DIMS> for MockVectorDb {
+ type Error = anyhow::Error;
+ type Metadata = String;
+ type SearchParameters = TaskSearchParameters;
+
+ async fn upsert_embeddings<'a>(
+ &self,
+ _metadata: String,
+ embeddings: Vec<LabeledEmbedding<'a, DIMS>>,
+ ) -> anyhow::Result<()> {
+ self.upserted_embeddings.lock().unwrap().push(
+ embeddings
+ .into_iter()
+ .map(|field| (field.search_key, field.content.into_owned()))
+ .collect(),
+ );
+ Ok(())
+ }
+
+ async fn cosine_search(
+ &self,
+ query: Vec<KeyedEmbedding<DIMS>>,
+ _params: TaskSearchParameters,
+ ) -> anyhow::Result<Vec<SearchResults<String, DIMS>>> {
+ *self.last_query.lock().unwrap() =
+ Some(query.into_iter().map(|field| field.search_key).collect());
+ Ok(Vec::new())
+ }
+}
+
+#[derive(Clone, Default)]
+struct MockReranker {
+ calls: Arc<Mutex<usize>>,
+}
+
+impl RerankModel<DIMS> for MockReranker {
+ async fn rerank<'a, T: Send>(
+ &self,
+ _query: Content<'a>,
+ _candidates: Vec<SearchResults<T, DIMS>>,
+ ) -> anyhow::Result<Vec<Reranked<T>>> {
+ *self.calls.lock().unwrap() += 1;
+ Ok(Vec::new())
+ }
+}
+
+struct MockJudge;
+
+#[async_trait]
+impl TaskDuplicateJudge for MockJudge {
+ async fn judge(&self, _left: &str, _right: &str) -> JudgeResult {
+ JudgeResult {
+ is_duplicate: false,
+ model: None,
+ reason: None,
+ }
+ }
+}
+
+struct MockNotifier;
+
+#[async_trait]
+impl TaskDedupNotifier for MockNotifier {
+ async fn notify_matches_updated(&self, _document_id: &str) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+struct MockMatchRepo;
+
+#[async_trait]
+impl TaskMatchRepo for MockMatchRepo {
+ async fn upsert_match(
+ &self,
+ _task_id: &str,
+ _duplicate_task_id: &str,
+ _similarity_score: f64,
+ _judge_model: Option<&str>,
+ _judge_reason: Option<&str>,
+ ) -> Result<(), TaskDedupError> {
+ Ok(())
+ }
+
+ async fn active_duplicate_component(
+ &self,
+ document_ids: &[String],
+ ) -> Result<Vec<String>, TaskDedupError> {
+ Ok(document_ids.to_vec())
+ }
+
+ async fn trim_matches(&self, _document_id: &str, _limit: i64) -> Result<(), TaskDedupError> {
+ Ok(())
+ }
+
+ async fn active_duplicates(
+ &self,
+ _document_id: &str,
+ ) -> Result<Vec<TaskDuplicate>, TaskDedupError> {
+ Ok(Vec::new())
+ }
+
+ async fn dismiss_match(
+ &self,
+ _document_id: &str,
+ _match_id: Uuid,
+ _dismissed_by: &str,
+ ) -> Result<bool, TaskDedupError> {
+ Ok(false)
+ }
+
+ async fn match_contains(
+ &self,
+ _document_id: &str,
+ _match_id: Uuid,
+ ) -> Result<bool, TaskDedupError> {
+ Ok(false)
+ }
+
+ async fn match_document_ids(&self, _match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {
+ Ok(Vec::new())
+ }
+
+ async fn dismiss_match_by_id(&self, _match_id: Uuid) -> Result<(), TaskDedupError> {
+ Ok(())
+ }
+
+ async fn task_names(
+ &self,
+ _document_ids: &[String],
+ ) -> Result<HashMap<String, String>, TaskDedupError> {
+ Ok(HashMap::new())
+ }
+}
+
+fn service(vector_db: MockVectorDb, reranker: MockReranker) -> Service {
+ TaskDedupService::new(
+ TaskDedupConfig::default(),
+ MockEmbedder,
+ vector_db,
+ reranker,
+ Arc::new(MockJudge),
+ Arc::new(MockNotifier),
+ Arc::new(MockMatchRepo),
+ )
+}
+
+fn new_task() -> NewTask {
+ NewTask {
+ document_id: "NEW".to_string(),
+ owner: "owner".to_string(),
+ team_id: None,
+ title: "Query title".to_string(),
+ markdown: "query body".to_string(),
+ }
+}
+
+#[tokio::test]
+async fn detect_embeds_title_when_task_has_no_body() {
+ let vector_db = MockVectorDb::default();
+ let svc = service(vector_db.clone(), MockReranker::default());
+ let mut task = new_task();
+ task.markdown.clear();
+
+ let active = svc.detect_new_task(task).await.unwrap();
+
+ assert!(active.is_empty());
+ assert_eq!(
+ *vector_db.upserted_embeddings.lock().unwrap(),
+ vec![vec![("title", "Query title".to_string())]]
+ );
+ assert_eq!(*vector_db.last_query.lock().unwrap(), Some(vec!["title"]));
+}
+
+#[tokio::test]
+async fn detect_embeds_body_when_task_has_no_title() {
+ let vector_db = MockVectorDb::default();
+ let svc = service(vector_db.clone(), MockReranker::default());
+ let mut task = new_task();
+ task.title.clear();
+
+ let active = svc.detect_new_task(task).await.unwrap();
+
+ assert!(active.is_empty());
+ assert_eq!(
+ *vector_db.upserted_embeddings.lock().unwrap(),
+ vec![vec![("body", "query body".to_string())]]
+ );
+ assert_eq!(*vector_db.last_query.lock().unwrap(), Some(vec!["body"]));
+}
+
+#[tokio::test]
+async fn detect_embeds_nothing_when_task_has_no_title_or_body() {
+ let vector_db = MockVectorDb::default();
+ let reranker = MockReranker::default();
+ let svc = service(vector_db.clone(), reranker.clone());
+ let mut task = new_task();
+ task.title = " ".to_string();
+ task.markdown = "\n\t".to_string();
+
+ let active = svc.detect_new_task(task).await.unwrap();
+
+ assert!(active.is_empty());
+ assert!(vector_db.upserted_embeddings.lock().unwrap().is_empty());
+ assert!(vector_db.last_query.lock().unwrap().is_none());
+ assert_eq!(*reranker.calls.lock().unwrap(), 0);
+}