Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix: task dedup (#3678)
Eric Hayes83eedf52af55
diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yamlindex 03cb89c90a..fc302a474e 100644--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml@@ -28,6 +28,7 @@ config:cloud-storage-service:meta_pixel_id: "639142540393286"cloud-storage-service:meta_access_token: meta-access-tokencloud-storage-service:anthropic_api_key: anthropic-api-key-dev+ cloud-storage-service:openai_api_key: openai-keycloud-storage-service:apple_bundle_id: apple-bundle-id-prodcloud-storage-service:documents_index_uses_join: "true"cloud-storage-service:chats_index_uses_join: "true"diff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yamlindex 9f93b9a913..c7f0f5b52d 100644--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml@@ -28,6 +28,7 @@ config:cloud-storage-service:meta_pixel_id: "639142540393286"cloud-storage-service:meta_access_token: meta-access-tokencloud-storage-service:anthropic_api_key: anthropic-api-key+ cloud-storage-service:openai_api_key: openai-keycloud-storage-service:apple_bundle_id: apple-bundle-id-prodcloud-storage-service:documents_index_uses_join: "true"cloud-storage-service:call_records_index_uses_join: "true"diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex a810717396..76e5690869 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -305,6 +305,14 @@ const ANTHROPIC_API_KEY = aws.secretsmanagerreturn secret.secretString;});+// OpenAI key used by task duplicate-detection embeddings (task_dedup). Resolved+// at deploy time and baked into the task definition, like ANTHROPIC_API_KEY.+const OPENAI_API_KEY = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: config.get('openai_api_key') ?? '',+ })+ .apply((secret) => secret.secretString);+// Cal.com webhook — HMAC secret, resolved at runtime via Secrets Manager.const CAL_WEBHOOK_SECRET_KEY = config.require('cal_webhook_secret_key');const calWebhookSecretKeyArn: pulumi.Output<string> = aws.secretsmanager@@ -418,6 +426,10 @@ const cloudStorageService = new CloudStorageService(name: 'ANTHROPIC_API_KEY',value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,},+ {+ name: 'OPENAI_API_KEY',+ value: pulumi.interpolate`${OPENAI_API_KEY}`,+ },{name: 'LIVEKIT_SERVER_URL',value: pulumi.interpolate`${LIVEKIT_SERVER_URL}`,diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex ab82614d03..b18a8bc393 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -187,7 +187,6 @@ export type TaskDuplicate = {taskId: string;taskName: string;vectorScore: number;- rerankScore: number;judgeReason?: string | null;};@@ -199,7 +198,6 @@ export type TaskSimilarityResult = {taskId: string;taskName: string;vectorScore: number;- rerankScore: number;};export type TaskSimilaritySearchResponse = {diff --git a/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json b/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.jsondeleted file mode 100644index a50b80bf97..0000000000--- a/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH ranked AS (\n SELECT\n id,\n ROW_NUMBER() OVER (\n ORDER BY rerank_score DESC, vector_score DESC, created_at DESC\n ) AS rn\n FROM task_duplicate_match\n WHERE status = 'active'\n AND (task_id = $1 OR duplicate_task_id = $1)\n )\n UPDATE task_duplicate_match m\n SET status = 'dismissed', updated_at = NOW()\n FROM ranked r\n WHERE m.id = r.id\n AND r.rn > $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Int8"- ]- },- "nullable": []- },- "hash": "0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13"-}diff --git a/rust/cloud-storage/.sqlx/query-170411ea24963c7605046d59dbf2bc32d23c2d62e36a11e3875a8b84e8f1e062.json b/rust/cloud-storage/.sqlx/query-170411ea24963c7605046d59dbf2bc32d23c2d62e36a11e3875a8b84e8f1e062.jsonnew file mode 100644index 0000000000..65a1903328--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-170411ea24963c7605046d59dbf2bc32d23c2d62e36a11e3875a8b84e8f1e062.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', $4, $5, $6)\n ON CONFLICT (task_id, duplicate_task_id) DO UPDATE\n SET status = 'active',\n vector_score = EXCLUDED.vector_score,\n judge_model = EXCLUDED.judge_model,\n judge_reason = EXCLUDED.judge_reason,\n updated_at = NOW()\n WHERE task_duplicate_match.status <> 'dismissed'\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Float8",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "170411ea24963c7605046d59dbf2bc32d23c2d62e36a11e3875a8b84e8f1e062"+}diff --git a/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.json b/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.jsonnew file mode 100644index 0000000000..0e311a34a1--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1c2963e1dca5cb84296b932a52c92e49805964e9b0226d00e60c38d04cc1554c.json@@ -0,0 +1,22 @@+{+ "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-20a52bc26743ce11459bb7c7cfda25dd6084c0d64e4dc99d3f0d802f0ae61136.json b/rust/cloud-storage/.sqlx/query-20a52bc26743ce11459bb7c7cfda25dd6084c0d64e4dc99d3f0d802f0ae61136.jsonnew file mode 100644index 0000000000..f9a64311a2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-20a52bc26743ce11459bb7c7cfda25dd6084c0d64e4dc99d3f0d802f0ae61136.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH ranked AS (\n SELECT\n id,\n ROW_NUMBER() OVER (\n ORDER BY vector_score DESC, created_at DESC\n ) AS rn\n FROM task_duplicate_match\n WHERE status = 'active'\n AND (task_id = $1 OR duplicate_task_id = $1)\n )\n UPDATE task_duplicate_match m\n SET status = 'dismissed', updated_at = NOW()\n FROM ranked r\n WHERE m.id = r.id\n AND r.rn > $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "20a52bc26743ce11459bb7c7cfda25dd6084c0d64e4dc99d3f0d802f0ae61136"+}diff --git a/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json b/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.jsondeleted file mode 100644index a3ad5805fa..0000000000--- a/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json+++ /dev/null@@ -1,20 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)\n ON CONFLICT (task_id, duplicate_task_id) DO UPDATE\n SET status = 'active',\n vector_score = EXCLUDED.vector_score,\n rerank_score = EXCLUDED.rerank_score,\n judge_model = EXCLUDED.judge_model,\n judge_reason = EXCLUDED.judge_reason,\n updated_at = NOW()\n WHERE task_duplicate_match.status <> 'dismissed'\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- "Float8",- "Float8",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149"-}diff --git a/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json b/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.jsondeleted file mode 100644index c21a7340d1..0000000000--- a/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe"-}diff --git a/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.json b/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.jsonnew file mode 100644index 0000000000..eef301d54f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a08095da37e733b97cbf41aa897b8c8aa67cb2b1a52ab9c0ec4ce6a1afa2ffff.json@@ -0,0 +1,17 @@+{+ "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-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json b/rust/cloud-storage/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.jsondeleted file mode 100644index 43b2b133c0..0000000000--- a/rust/cloud-storage/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json+++ /dev/null@@ -1,29 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "task_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "duplicate_task_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false- ]- },- "hash": "c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9"-}diff --git a/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.json b/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.jsonnew file mode 100644index 0000000000..27b0cf9c29--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-d5a8891e255d0a4af3adc455b2c40e760225f73e874fb82f17b7997682e9a826.json@@ -0,0 +1,30 @@+{+ "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-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json b/rust/cloud-storage/.sqlx/query-da11b9c3b9850e3a763035f7873921f7887f3bf828b5be3c7a599fade54a0dc1.jsonsimilarity index 57%rename from rust/cloud-storage/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.jsonrename to rust/cloud-storage/.sqlx/query-da11b9c3b9850e3a763035f7873921f7887f3bf828b5be3c7a599fade54a0dc1.jsonindex aa9684ef62..45d7afe7de 100644--- a/rust/cloud-storage/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json+++ b/rust/cloud-storage/.sqlx/query-da11b9c3b9850e3a763035f7873921f7887f3bf828b5be3c7a599fade54a0dc1.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n m.id,\n CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS \"other_task_id!\",\n d.name AS \"other_task_name!\",\n m.vector_score AS \"vector_score!\",\n m.rerank_score AS \"rerank_score!\",\n m.judge_reason\n FROM task_duplicate_match m\n JOIN \"Document\" d\n ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END\n WHERE m.status = 'active'\n AND (m.task_id = $1 OR m.duplicate_task_id = $1)\n AND d.\"deletedAt\" IS NULL\n ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC\n LIMIT 10\n ",+ "query": "\n SELECT\n m.id,\n CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS \"other_task_id!\",\n d.name AS \"other_task_name!\",\n m.vector_score AS \"vector_score!\",\n m.judge_reason\n FROM task_duplicate_match m\n JOIN \"Document\" d\n ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END\n WHERE m.status = 'active'\n AND (m.task_id = $1 OR m.duplicate_task_id = $1)\n AND d.\"deletedAt\" IS NULL\n ORDER BY m.vector_score DESC, m.created_at DESC\n LIMIT 10\n ","describe": {"columns": [{@@ -25,11 +25,6 @@},{"ordinal": 4,- "name": "rerank_score!",- "type_info": "Float8"- },- {- "ordinal": 5,"name": "judge_reason","type_info": "Text"}@@ -44,9 +39,8 @@null,false,false,- false,true]},- "hash": "72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8"+ "hash": "da11b9c3b9850e3a763035f7873921f7887f3bf828b5be3c7a599fade54a0dc1"}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a882de5708..e501d3590d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3388,6 +3388,7 @@ dependencies = ["call","channels","chrono",+ "clap","cloudfront_sign","comms","comms_db_client",@@ -11408,11 +11409,11 @@ version = "0.1.0"dependencies = ["agent","anyhow",+ "async-openai","async-trait","connection_gateway_client","macro_db_migrator","model-entity",- "reqwest 0.13.3","serde","serde_json","sqlx",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 2cd07447f6..91ad27095b 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -61,6 +61,7 @@ async-openai = { version = "0.36.1", features = ["byot","chat-completion","completions",+ "embedding",] }async-stream = "0.3.6"async-trait = "0.1.86"diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 0978d01ef7..aa2d51c902 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -13,6 +13,10 @@ 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"]@@ -40,6 +44,7 @@ cal = { path = "../cal", features = ["axum", "outbound"] }call = { path = "../call" }channels = { path = "../channels", features = ["inbound", "outbound"] }chrono = { workspace = true }+clap = { workspace = true }cloudfront_sign = { workspace = true }comms = { path = "../comms", features = ["inbound", "outbound"] }comms_db_client = { path = "../comms_db_client" }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.rsnew file mode 100644index 0000000000..b7f12a888d--- /dev/null+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_task_embeddings.rs@@ -0,0 +1,581 @@+//! 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/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex a8da0ac3f1..77197d1972 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -90,9 +90,8 @@ use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpuse task_dedup::{TaskDedupConfig, TaskDedupService,outbound::{- connection_gateway::ConnectionGatewayTaskDedupNotifier,- embedding::OpenAiOrLocalTaskEmbedder, judge::AgentDuplicateJudge,- postgres::PgTaskDedupRepo,+ connection_gateway::ConnectionGatewayTaskDedupNotifier, embedding::OpenAiTaskEmbedder,+ judge::AgentDuplicateJudge, postgres::PgTaskDedupRepo, reranker::NoOpTaskReranker,},};@@ -575,10 +574,11 @@ async fn main() -> anyhow::Result<()> {let task_dedup_service = Arc::new(TaskDedupService::new(task_dedup_config.clone(),Arc::new(PgTaskDedupRepo::new(db.clone())),- Arc::new(OpenAiOrLocalTaskEmbedder::new(+ Arc::new(OpenAiTaskEmbedder::new(task_dedup_config.embedding_model.clone(),)),- Arc::new(AgentDuplicateJudge::new(0.56)),+ Arc::new(NoOpTaskReranker),+ Arc::new(AgentDuplicateJudge::new()),Arc::new(ConnectionGatewayTaskDedupNotifier::new(conn_gateway_client.clone(),)),diff --git a/rust/cloud-storage/macro_db_client/migrations/20260601141834_drop_task_duplicate_match_rerank_score.sql b/rust/cloud-storage/macro_db_client/migrations/20260601141834_drop_task_duplicate_match_rerank_score.sqlnew file mode 100644index 0000000000..c07ec74f08--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260601141834_drop_task_duplicate_match_rerank_score.sql@@ -0,0 +1,5 @@+-- The deterministic lexical rerank stage has been removed from task duplicate+-- detection: candidates are now gated by vector similarity and decided by the+-- LLM judge alone, so the rerank score is no longer produced or stored.+ALTER TABLE task_duplicate_match+ DROP COLUMN rerank_score;diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json b/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.jsondeleted file mode 100644index a50b80bf97..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH ranked AS (\n SELECT\n id,\n ROW_NUMBER() OVER (\n ORDER BY rerank_score DESC, vector_score DESC, created_at DESC\n ) AS rn\n FROM task_duplicate_match\n WHERE status = 'active'\n AND (task_id = $1 OR duplicate_task_id = $1)\n )\n UPDATE task_duplicate_match m\n SET status = 'dismissed', updated_at = NOW()\n FROM ranked r\n WHERE m.id = r.id\n AND r.rn > $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Int8"- ]- },- "nullable": []- },- "hash": "0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.json b/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.jsondeleted file mode 100644index f2b540873e..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"Document\" (id, name, \"fileType\", owner)\n VALUES ($1, $2, 'md', $3)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json b/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.jsondeleted file mode 100644index a3ad5805fa..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json+++ /dev/null@@ -1,20 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)\n ON CONFLICT (task_id, duplicate_task_id) DO UPDATE\n SET status = 'active',\n vector_score = EXCLUDED.vector_score,\n rerank_score = EXCLUDED.rerank_score,\n judge_model = EXCLUDED.judge_model,\n judge_reason = EXCLUDED.judge_reason,\n updated_at = NOW()\n WHERE task_duplicate_match.status <> 'dismissed'\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- "Float8",- "Float8",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.json b/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.jsondeleted file mode 100644index def6c7e7bc..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO team_task (team_id, document_id, task_num)\n VALUES ($1, $2, $3)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Int4"- ]- },- "nullable": []- },- "hash": "57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.json b/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.jsondeleted file mode 100644index e031341d0a..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, 'task')\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json b/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.jsondeleted file mode 100644index 80b721af4a..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed',\n dismissed_by = $3,\n dismissed_at = NOW(),\n updated_at = NOW()\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json b/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.jsondeleted file mode 100644index 0d25c6312d..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n )\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "exists",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json b/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.jsondeleted file mode 100644index aa9684ef62..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json+++ /dev/null@@ -1,52 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n m.id,\n CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS \"other_task_id!\",\n d.name AS \"other_task_name!\",\n m.vector_score AS \"vector_score!\",\n m.rerank_score AS \"rerank_score!\",\n m.judge_reason\n FROM task_duplicate_match m\n JOIN \"Document\" d\n ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END\n WHERE m.status = 'active'\n AND (m.task_id = $1 OR m.duplicate_task_id = $1)\n AND d.\"deletedAt\" IS NULL\n ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC\n LIMIT 10\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "other_task_id!",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "other_task_name!",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "vector_score!",- "type_info": "Float8"- },- {- "ordinal": 4,- "name": "rerank_score!",- "type_info": "Float8"- },- {- "ordinal": 5,- "name": "judge_reason",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- null,- false,- false,- false,- true- ]- },- "hash": "72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.json b/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.jsondeleted file mode 100644index d798cffca4..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.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 ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json b/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.jsondeleted file mode 100644index c21a7340d1..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json b/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.jsondeleted file mode 100644index 75964adfc9..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', updated_at = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json b/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.jsondeleted file mode 100644index b80b95917b..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE \"Document\"\n SET \"deletedAt\" = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.json b/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.jsondeleted file mode 100644index 80ba0890a2..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.json+++ /dev/null@@ -1,17 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', 0.95, $4, 'test', 'same implementation work')\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- "Float8"- ]- },- "nullable": []- },- "hash": "b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json b/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.jsondeleted file mode 100644index 43b2b133c0..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json+++ /dev/null@@ -1,29 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "task_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "duplicate_task_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false- ]- },- "hash": "c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json b/rust/cloud-storage/task_dedup/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.jsondeleted file mode 100644index f8ffdb3e70..0000000000--- a/rust/cloud-storage/task_dedup/.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/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json b/rust/cloud-storage/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.jsondeleted file mode 100644index a5c0451b89..0000000000--- a/rust/cloud-storage/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "task_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "duplicate_task_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false- ]- },- "hash": "f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5"-}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json b/rust/cloud-storage/task_dedup/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.jsondeleted file mode 100644index 806dd516a2..0000000000--- a/rust/cloud-storage/task_dedup/.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/task_dedup/Cargo.toml b/rust/cloud-storage/task_dedup/Cargo.tomlindex 73c1fd7973..9408e6a817 100644--- a/rust/cloud-storage/task_dedup/Cargo.toml+++ b/rust/cloud-storage/task_dedup/Cargo.toml@@ -7,10 +7,10 @@ version = "0.1.0"[dependencies]agent = { path = "../agent" }anyhow = { workspace = true }+async-openai = { workspace = true }async-trait = { workspace = true }connection_gateway_client = { path = "../connection_gateway_client" }model-entity = { path = "../model-entity" }-reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/rust/cloud-storage/task_dedup/src/domain/models.rs b/rust/cloud-storage/task_dedup/src/domain/models.rsindex e0e53352b2..8a77bf4d73 100644--- a/rust/cloud-storage/task_dedup/src/domain/models.rs+++ b/rust/cloud-storage/task_dedup/src/domain/models.rs@@ -30,14 +30,11 @@ pub struct TaskDuplicate {pub task_name: String,/// Cosine similarity from vector search.pub vector_score: f64,- /// Deterministic rerank score.- pub rerank_score: f64,/// LLM judge explanation when available.pub judge_reason: Option<String>,}-/// Candidate returned by the retrieval layer before deterministic rerank and-/// judging.+/// Candidate returned by the retrieval layer before judging.#[derive(Debug, Clone)]pub struct TaskDuplicateCandidate {/// Candidate task document id.@@ -59,8 +56,6 @@ pub struct TaskSimilarityResult {pub task_name: String,/// Cosine similarity from vector search.pub vector_score: f64,- /// Deterministic rerank score.- pub rerank_score: f64,}/// Candidate returned by the similarity-search retrieval layer, carrying thediff --git a/rust/cloud-storage/task_dedup/src/domain/ports.rs b/rust/cloud-storage/task_dedup/src/domain/ports.rsindex fb1c41befc..e0466a6e48 100644--- a/rust/cloud-storage/task_dedup/src/domain/ports.rs+++ b/rust/cloud-storage/task_dedup/src/domain/ports.rs@@ -15,12 +15,25 @@ pub trait TaskEmbedder: Send + Sync {async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>>;}-/// Applies a semantic duplicate judgement after retrieval and deterministic-/// reranking.+/// 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>>;+}++/// Applies a semantic duplicate judgement after vector retrieval and reranking.#[async_trait]pub trait TaskDuplicateJudge: Send + Sync {/// Judges whether `left` and `right` represent the same task.- async fn judge(&self, left: &str, right: &str, rerank_score: f64) -> JudgeResult;+ async fn judge(&self, left: &str, right: &str) -> JudgeResult;}/// Persists embeddings, retrieves candidates, and manages match state.@@ -59,7 +72,6 @@ pub trait TaskDedupRepo: Send + Sync {task_id: &str,duplicate_task_id: &str,vector_score: f64,- rerank_score: f64,judge_model: Option<&str>,judge_reason: Option<&str>,) -> Result<(), TaskDedupError>;@@ -95,25 +107,11 @@ pub trait TaskDedupRepo: Send + Sync {match_id: Uuid,) -> Result<bool, TaskDedupError>;- /// Returns the other task id in a match.- async fn other_task_id(- &self,- document_id: &str,- match_id: Uuid,- ) -> Result<Option<String>, TaskDedupError>;-/// Returns the task document ids in a match.async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError>;/// Dismisses a match without document-side filtering.async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError>;-- /// Marks a match dismissed by a user.- async fn dismiss_match_by_id_for_user(- &self,- match_id: Uuid,- dismissed_by: &str,- ) -> Result<(), 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.rsindex d9c2966d4f..7aeb79fe03 100644--- a/rust/cloud-storage/task_dedup/src/domain/service.rs+++ b/rust/cloud-storage/task_dedup/src/domain/service.rs@@ -1,12 +1,17 @@//! Domain service for task duplicate detection.-use std::collections::{HashMap, HashSet};+#[cfg(test)]+mod test;++use std::collections::HashSet;use std::sync::Arc;use uuid::Uuid;use super::models::{NewTask, TaskDedupError, TaskDuplicate, TaskSimilarityResult};-use super::ports::{TaskDedupNotifier, TaskDedupRepo, TaskDuplicateJudge, TaskEmbedder};+use super::ports::{+ TaskDedupNotifier, TaskDedupRepo, TaskDuplicateJudge, TaskEmbedder, TaskReranker,+};/// Configuration for the task duplicate detection pipeline.#[derive(Debug, Clone)]@@ -17,10 +22,11 @@ pub struct TaskDedupConfig {pub vector_candidate_limit: i64,/// Maximum active duplicate matches to keep per task.pub duplicate_limit: i64,- /// Minimum vector score before reranking.+ /// Minimum vector similarity for a candidate to be considered.pub min_vector_similarity: f64,- /// Minimum deterministic rerank score before judging.- pub min_rerank_score: f64,+ /// Maximum candidates sent to the LLM judge per new task, in vector-score+ /// order. Bounds judge calls now that the cheap lexical pre-filter is gone.+ pub max_judge_candidates: usize,}impl Default for TaskDedupConfig {@@ -30,7 +36,7 @@ impl Default for TaskDedupConfig {vector_candidate_limit: 24,duplicate_limit: 5,min_vector_similarity: 0.74,- min_rerank_score: 0.42,+ max_judge_candidates: 10,}}}@@ -41,6 +47,7 @@ pub struct TaskDedupService {config: TaskDedupConfig,repo: Arc<dyn TaskDedupRepo>,embedder: Arc<dyn TaskEmbedder>,+ reranker: Arc<dyn TaskReranker>,judge: Arc<dyn TaskDuplicateJudge>,notifier: Arc<dyn TaskDedupNotifier>,}@@ -51,6 +58,7 @@ impl TaskDedupService {config: TaskDedupConfig,repo: Arc<dyn TaskDedupRepo>,embedder: Arc<dyn TaskEmbedder>,+ reranker: Arc<dyn TaskReranker>,judge: Arc<dyn TaskDuplicateJudge>,notifier: Arc<dyn TaskDedupNotifier>,) -> Self {@@ -58,6 +66,7 @@ impl TaskDedupService {config,repo,embedder,+ reranker,judge,notifier,}@@ -71,26 +80,6 @@ impl TaskDedupService {self.repo.active_duplicates(document_id).await}- /// Dismisses a visible match.- pub async fn dismiss_match(- &self,- document_id: &str,- match_id: Uuid,- dismissed_by: &str,- ) -> Result<(), TaskDedupError> {- let affected_document_ids = self.match_document_ids(match_id).await?;- let dismissed = self- .repo- .dismiss_match(document_id, match_id, dismissed_by)- .await?;- if dismissed {- self.notify_documents(affected_document_ids).await;- Ok(())- } else {- Err(TaskDedupError::MatchNotFound)- }- }-/// Dismisses visible matches.pub async fn dismiss_matches(&self,@@ -138,18 +127,6 @@ impl TaskDedupService {}}- /// Returns the other task in a duplicate match.- pub async fn other_task_id(- &self,- document_id: &str,- match_id: Uuid,- ) -> Result<String, TaskDedupError> {- self.repo- .other_task_id(document_id, match_id)- .await?- .ok_or(TaskDedupError::MatchNotFound)- }-/// 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?;@@ -158,24 +135,11 @@ impl TaskDedupService {Ok(())}- /// Marks a match dismissed by a user.- pub async fn dismiss_match_by_id_for_user(- &self,- match_id: Uuid,- dismissed_by: &str,- ) -> Result<(), TaskDedupError> {- let affected_document_ids = self.match_document_ids(match_id).await?;- self.repo- .dismiss_match_by_id_for_user(match_id, dismissed_by)- .await?;- self.notify_documents(affected_document_ids).await;- Ok(())- }-/// Finds existing tasks similar to an unsaved draft as the user composes it.///- /// Runs vector retrieval + deterministic rerank only (no judge) and- /// persists nothing: the embedding is computed in memory and discarded.+ /// Runs vector retrieval + rerank only (no judge) and persists nothing: the+ /// embedding is computed in memory and discarded. Results are ordered by the+ /// reranker's relevance score.pub async fn similarity_search(&self,owner: &str,@@ -196,38 +160,24 @@ impl TaskDedupService {).await?;- let mut results = Vec::new();- for candidate in candidates {- if candidate.vector_score < self.config.min_vector_similarity {- continue;- }+ let candidates = candidates+ .into_iter()+ .filter(|candidate| candidate.vector_score >= self.config.min_vector_similarity)+ .collect::<Vec<_>>();- let rerank_score = lexical_rerank_score(&content, &candidate.content);- if rerank_score < self.config.min_rerank_score {- continue;- }+ let ranked = self+ .rerank(&content, candidates, |candidate| candidate.content.as_str())+ .await?;- results.push(TaskSimilarityResult {+ Ok(ranked+ .into_iter()+ .take(self.config.duplicate_limit.max(0) as usize)+ .map(|candidate| TaskSimilarityResult {task_id: candidate.document_id,task_name: candidate.name,vector_score: candidate.vector_score,- rerank_score,- });- }-- results.sort_by(|a, b| {- b.rerank_score- .partial_cmp(&a.rerank_score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| {- b.vector_score- .partial_cmp(&a.vector_score)- .unwrap_or(std::cmp::Ordering::Equal)- })- });- results.truncate(self.config.duplicate_limit.max(0) as usize);-- Ok(results)+ })+ .collect())}/// Detects duplicates for a newly-created task and sends live updates for@@ -251,20 +201,20 @@ impl TaskDedupService {.candidates(&task, &embedding, self.config.vector_candidate_limit).await?;- for candidate in candidates {- if candidate.vector_score < self.config.min_vector_similarity {- continue;- }-- let rerank_score = lexical_rerank_score(&content, &candidate.content);- if rerank_score < self.config.min_rerank_score {- continue;- }+ // 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 judge_candidates = self+ .rerank(&content, candidates, |candidate| candidate.content.as_str())+ .await?+ .into_iter()+ .take(self.config.max_judge_candidates);- let judge = self- .judge- .judge(&content, &candidate.content, rerank_score)- .await;+ for candidate in judge_candidates {+ let judge = self.judge.judge(&content, &candidate.content).await;if !judge.is_duplicate {continue;}@@ -281,7 +231,6 @@ impl TaskDedupService {left,right,candidate.vector_score,- rerank_score,judge.model.as_deref(),Some(&reason),)@@ -314,6 +263,40 @@ 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>(+ &self,+ query: &str,+ candidates: Vec<C>,+ content_of: impl Fn(&C) -> &str,+ ) -> Result<Vec<C>, TaskDedupError> {+ if candidates.is_empty() {+ return Ok(candidates);+ }++ 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()+ )));+ }++ 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+ .into_iter()+ .map(|(candidate, _score)| candidate)+ .collect())+ }+async fn notify_documents<I>(&self, document_ids: I)whereI: IntoIterator<Item = String>,@@ -360,7 +343,7 @@ impl TaskDedupService {/// Builds the text embedded for a task.pub fn task_embedding_content(title: &str, markdown: &str) -> String {- format!("Title: {}\n\n{}", title.trim(), markdown.trim())+ format!("{}\n{}", title.trim(), markdown.trim())}/// Returns a stable ordered pair.@@ -386,86 +369,3 @@ fn inferred_judge_reason(reason: Option<&str>) -> String {_ => "duplicate graph closure".to_string(),}}--/// Deterministic lexical rerank score.-pub fn lexical_rerank_score(left: &str, right: &str) -> f64 {- let left_tokens = tokenize(left);- let right_tokens = tokenize(right);- if left_tokens.is_empty() || right_tokens.is_empty() {- return 0.0;- }-- let left_counts = token_counts(&left_tokens);- let right_counts = token_counts(&right_tokens);- let left_set: HashSet<&str> = left_tokens.iter().map(String::as_str).collect();- let right_set: HashSet<&str> = right_tokens.iter().map(String::as_str).collect();-- let overlap = left_set.intersection(&right_set).count() as f64;- let union = left_set.union(&right_set).count() as f64;- let jaccard = if union > 0.0 { overlap / union } else { 0.0 };-- let mut dot = 0.0;- for (token, left_count) in &left_counts {- if let Some(right_count) = right_counts.get(token) {- dot += f64::from(*left_count) * f64::from(*right_count);- }- }- let left_norm = left_counts- .values()- .map(|count| f64::from(*count) * f64::from(*count))- .sum::<f64>()- .sqrt();- let right_norm = right_counts- .values()- .map(|count| f64::from(*count) * f64::from(*count))- .sum::<f64>()- .sqrt();- let cosine = if left_norm > 0.0 && right_norm > 0.0 {- dot / (left_norm * right_norm)- } else {- 0.0- };-- (jaccard * 0.35) + (cosine * 0.65)-}--fn token_counts(tokens: &[String]) -> HashMap<&str, u16> {- let mut counts = HashMap::new();- for token in tokens {- *counts.entry(token.as_str()).or_insert(0) += 1;- }- counts-}--fn tokenize(text: &str) -> Vec<String> {- text.split(|ch: char| !ch.is_alphanumeric())- .map(str::to_lowercase)- .filter(|token| token.len() > 2 && !STOP_WORDS.contains(&token.as_str()))- .collect()-}--const STOP_WORDS: &[&str] = &[- "the", "and", "for", "with", "that", "this", "from", "into", "task", "todo", "make", "add",- "fix", "use", "using", "should", "would", "could", "will", "are", "was", "were", "has", "have",- "had", "you", "your", "our", "not", "but", "all", "any", "can",-];--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn lexical_rerank_separates_similar_and_unrelated_tasks() {- let similar = lexical_rerank_score(- "Use pgvector embeddings to detect duplicate tasks and show a duplicates pill",- "Detect duplicate tasks with pgvector embeddings and show duplicate suggestions",- );- let unrelated = lexical_rerank_score(- "Use pgvector embeddings to detect duplicate tasks and show a duplicates pill",- "Fix billing email copy and update subscription receipt text",- );-- assert!(similar > TaskDedupConfig::default().min_rerank_score);- assert!(unrelated < TaskDedupConfig::default().min_rerank_score);- }-}diff --git a/rust/cloud-storage/task_dedup/src/domain/service/test.rs b/rust/cloud-storage/task_dedup/src/domain/service/test.rsnew file mode 100644index 0000000000..1e249dfb03--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/domain/service/test.rs@@ -0,0 +1,795 @@+//! Service-level pipeline tests against in-memory mock ports.+//!+//! 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.++use std::collections::{HashMap, HashSet};+use std::sync::{Arc, Mutex};++use async_trait::async_trait;+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,+};++// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++struct MockEmbedder;++#[async_trait]+impl TaskEmbedder for MockEmbedder {+ async fn embed(&self, _content: &str) -> anyhow::Result<Vec<f32>> {+ Ok(vec![0.0; 4])+ }+}++/// 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.+#[derive(Default)]+struct MockReranker {+ 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+ .lock()+ .unwrap()+ .push((query.to_string(), documents.to_vec()));+ Ok(documents+ .iter()+ .map(|document| self.scores.get(document).copied().unwrap_or(0.0))+ .collect())+ }+}++/// Judge that calls a content a duplicate iff its right-hand text is in the+/// configured set, recording every (left, right) it sees.+#[derive(Default)]+struct MockJudge {+ duplicates: HashSet<String>,+ calls: Mutex<Vec<(String, String)>>,+}++#[async_trait]+impl TaskDuplicateJudge for MockJudge {+ async fn judge(&self, left: &str, right: &str) -> JudgeResult {+ self.calls+ .lock()+ .unwrap()+ .push((left.to_string(), right.to_string()));+ JudgeResult {+ is_duplicate: self.duplicates.contains(right),+ model: Some("mock-judge".to_string()),+ reason: Some("mock reason".to_string()),+ }+ }+}++#[derive(Default)]+struct MockNotifier {+ notified: Mutex<Vec<String>>,+}++#[async_trait]+impl TaskDedupNotifier for MockNotifier {+ async fn notify_matches_updated(&self, document_id: &str) -> anyhow::Result<()> {+ self.notified.lock().unwrap().push(document_id.to_string());+ Ok(())+ }+}++struct MatchRow {+ id: Uuid,+ task_id: String,+ duplicate_task_id: String,+ status: String,+ vector_score: f64,+ judge_reason: Option<String>,+}++struct RecordedMatch {+ task_id: String,+ duplicate_task_id: String,+ judge_model: Option<String>,+}++/// In-memory repo: preset retrieval results + a live match store, recording the+/// writes (embeddings, matches, trims) the service performs.+#[derive(Default)]+struct MockRepo {+ candidates: Vec<TaskDuplicateCandidate>,+ similarity_candidates: Vec<TaskSimilarityCandidate>,+ /// 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 {+ fn add_active_match(&self, task_id: &str, duplicate_task_id: &str) -> Uuid {+ let id = Uuid::new_v4();+ self.matches.lock().unwrap().push(MatchRow {+ id,+ task_id: task_id.to_string(),+ duplicate_task_id: duplicate_task_id.to_string(),+ status: "active".to_string(),+ vector_score: 0.9,+ judge_reason: Some("seed".to_string()),+ });+ id+ }+}++#[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())+ }++ async fn upsert_match(+ &self,+ task_id: &str,+ duplicate_task_id: &str,+ vector_score: f64,+ judge_model: Option<&str>,+ judge_reason: Option<&str>,+ ) -> Result<(), TaskDedupError> {+ self.upserted_matches.lock().unwrap().push(RecordedMatch {+ task_id: task_id.to_string(),+ duplicate_task_id: duplicate_task_id.to_string(),+ judge_model: judge_model.map(str::to_string),+ });++ let mut matches = self.matches.lock().unwrap();+ let exists = matches+ .iter()+ .any(|m| m.task_id == task_id && m.duplicate_task_id == duplicate_task_id);+ if !exists {+ matches.push(MatchRow {+ id: Uuid::new_v4(),+ task_id: task_id.to_string(),+ duplicate_task_id: duplicate_task_id.to_string(),+ status: "active".to_string(),+ vector_score,+ judge_reason: judge_reason.map(str::to_string),+ });+ }+ Ok(())+ }++ async fn active_duplicate_component(+ &self,+ document_ids: &[String],+ ) -> Result<Vec<String>, TaskDedupError> {+ let mut component: HashSet<String> = document_ids.iter().cloned().collect();+ component.extend(self.component_extra.iter().cloned());+ Ok(component.into_iter().collect())+ }++ async fn trim_matches(&self, document_id: &str, limit: i64) -> Result<(), TaskDedupError> {+ self.trimmed+ .lock()+ .unwrap()+ .push((document_id.to_string(), limit));+ Ok(())+ }++ async fn active_duplicates(+ &self,+ document_id: &str,+ ) -> Result<Vec<TaskDuplicate>, TaskDedupError> {+ let matches = self.matches.lock().unwrap();+ Ok(matches+ .iter()+ .filter(|m| {+ m.status == "active"+ && (m.task_id == document_id || m.duplicate_task_id == document_id)+ })+ .map(|m| {+ let other = if m.task_id == document_id {+ &m.duplicate_task_id+ } else {+ &m.task_id+ };+ TaskDuplicate {+ id: m.id,+ task_id: other.clone(),+ task_name: other.clone(),+ vector_score: m.vector_score,+ judge_reason: m.judge_reason.clone(),+ }+ })+ .collect())+ }++ async fn dismiss_match(+ &self,+ document_id: &str,+ match_id: Uuid,+ _dismissed_by: &str,+ ) -> Result<bool, TaskDedupError> {+ let mut matches = self.matches.lock().unwrap();+ for m in matches.iter_mut() {+ if m.id == match_id && (m.task_id == document_id || m.duplicate_task_id == document_id)+ {+ m.status = "dismissed".to_string();+ return Ok(true);+ }+ }+ Ok(false)+ }++ async fn match_contains(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<bool, TaskDedupError> {+ let matches = self.matches.lock().unwrap();+ Ok(matches.iter().any(|m| {+ m.id == match_id && (m.task_id == document_id || m.duplicate_task_id == document_id)+ }))+ }++ async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {+ let matches = self.matches.lock().unwrap();+ Ok(matches+ .iter()+ .find(|m| m.id == match_id)+ .map(|m| vec![m.task_id.clone(), m.duplicate_task_id.clone()])+ .unwrap_or_default())+ }++ async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError> {+ let mut matches = self.matches.lock().unwrap();+ for m in matches.iter_mut() {+ if m.id == match_id {+ m.status = "dismissed".to_string();+ }+ }+ Ok(())+ }+}++// ---------------------------------------------------------------------------+// 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(),+ owner: "owner".to_string(),+ team_id: None,+ title: "Query title".to_string(),+ markdown: "query body".to_string(),+ }+}++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(),+ })+}++fn build(+ config: TaskDedupConfig,+ repo: &Arc<MockRepo>,+ reranker: &Arc<MockReranker>,+ judge: &Arc<MockJudge>,+ notifier: &Arc<MockNotifier>,+) -> TaskDedupService {+ TaskDedupService::new(+ config,+ repo.clone(),+ Arc::new(MockEmbedder),+ reranker.clone(),+ judge.clone(),+ notifier.clone(),+ )+}++fn judged_right_sides(judge: &MockJudge) -> Vec<String> {+ judge+ .calls+ .lock()+ .unwrap()+ .iter()+ .map(|(_, right)| right.clone())+ .collect()+}++// ---------------------------------------------------------------------------+// detect_new_task+// ---------------------------------------------------------------------------++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let mut active = service.detect_new_task(new_task("NEW")).await.unwrap();+ active.sort();++ // Embedding persisted for the new task.+ assert_eq!(+ *repo.upserted_embeddings.lock().unwrap(),+ vec!["NEW".to_string()]+ );++ // A single ordered match was written, tagged with the judge's model.+ let upserts = repo.upserted_matches.lock().unwrap();+ assert_eq!(upserts.len(), 1);+ assert_eq!(upserts[0].task_id, "A");+ assert_eq!(upserts[0].duplicate_task_id, "NEW");+ assert_eq!(upserts[0].judge_model.as_deref(), Some("mock-judge"));+ drop(upserts);++ // The reranker ran in the judge path.+ assert_eq!(reranker.calls.lock().unwrap().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();+ notified.sort();+ assert_eq!(notified, vec!["A".to_string(), "NEW".to_string()]);+ let trimmed: HashSet<String> = repo+ .trimmed+ .lock()+ .unwrap()+ .iter()+ .map(|(doc, _)| doc.clone())+ .collect();+ assert_eq!(trimmed, HashSet::from(["A".to_string(), "NEW".to_string()]));+}++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ 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();+ 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()]);+}++#[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, ¬ifier);++ 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),+ 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, ¬ifier);++ 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!(upserts.len(), 1);+ let pair = (+ upserts[0].task_id.clone(),+ upserts[0].duplicate_task_id.clone(),+ );+ assert_eq!(pair, ("B".to_string(), "NEW".to_string()));+}++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let active = 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());+}++#[tokio::test]+async fn detect_closes_duplicate_component() {+ let repo = Arc::new(MockRepo {+ candidates: vec![candidate("A", "cand-a", 0.9)],+ // 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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ 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+ .upserted_matches+ .lock()+ .unwrap()+ .iter()+ .map(|m| (m.task_id.clone(), m.duplicate_task_id.clone()))+ .collect();+ pairs.sort();+ assert_eq!(+ pairs,+ vec![+ ("A".to_string(), "C".to_string()),+ ("A".to_string(), "NEW".to_string()),+ ("C".to_string(), "NEW".to_string()),+ ]+ );+}++// ---------------------------------------------------------------------------+// similarity_search+// ---------------------------------------------------------------------------++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let results = service+ .similarity_search("owner", None, "title", "body")+ .await+ .unwrap();++ // 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"]);++ // The reranker ran on the survivors only.+ let calls = reranker.calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].1, vec!["cx".to_string(), "cz".to_string()]);+ drop(calls);++ // 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());+}++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let results = service+ .similarity_search("owner", None, "title", "body")+ .await+ .unwrap();++ let ids: Vec<&str> = results.iter().map(|r| r.task_id.as_str()).collect();+ assert_eq!(ids, vec!["Z", "X"]);+}++#[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, ¬ifier);++ let results = service+ .similarity_search("owner", None, "title", "body")+ .await+ .unwrap();++ let ids: Vec<&str> = results.iter().map(|r| r.task_id.as_str()).collect();+ assert_eq!(ids, vec!["A", "B"]);+}++// ---------------------------------------------------------------------------+// dismissal + lookup+// ---------------------------------------------------------------------------++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ 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();+ 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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let error = service+ .dismiss_matches("D", &[Uuid::new_v4()], "user")+ .await+ .unwrap_err();++ assert!(matches!(error, TaskDedupError::MatchNotFound));+ assert!(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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ service.ensure_match_contains("D", match_id).await.unwrap();++ let error = service+ .ensure_match_contains("D", Uuid::new_v4())+ .await+ .unwrap_err();+ assert!(matches!(error, TaskDedupError::MatchNotFound));+}++#[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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ 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();+ 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(+ TaskDedupConfig::default(),+ &repo,+ &reranker,+ &judge,+ ¬ifier,+ );++ let duplicates = 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/outbound/embedding.rs b/rust/cloud-storage/task_dedup/src/outbound/embedding.rsindex 61395d6190..b1e0cbe908 100644--- a/rust/cloud-storage/task_dedup/src/outbound/embedding.rs+++ b/rust/cloud-storage/task_dedup/src/outbound/embedding.rs@@ -1,93 +1,177 @@-//! Embedding adapters for task duplicate detection.-+//! 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 serde_json::json;use crate::domain::ports::TaskEmbedder;/// Expected embedding dimensions for the current default embedding model.pub const EMBEDDING_DIM: usize = 1536;-/// Embedder that uses OpenAI when `OPENAI_API_KEY` is set and falls back to a-/// deterministic local embedding otherwise.-pub struct OpenAiOrLocalTaskEmbedder {+/// 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: reqwest::Client,+ client: Client<OpenAIConfig>,}-impl OpenAiOrLocalTaskEmbedder {- /// Creates a new embedder.+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: reqwest::Client::new(),+ client: Client::with_config(config),}}-}-#[async_trait]-impl TaskEmbedder for OpenAiOrLocalTaskEmbedder {- async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>> {- let Ok(api_key) = std::env::var("OPENAI_API_KEY") else {- return Ok(local_embedding(content));- };+ /// 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());+ }- if api_key.trim().is_empty() {- return Ok(local_embedding(content));+ 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()+ )));}- let response = self- .client- .post("https://api.openai.com/v1/embeddings")- .bearer_auth(api_key)- .json(&json!({- "model": self.model,- "input": content,- }))- .send()- .await;-- let response = match response.and_then(reqwest::Response::error_for_status) {- Err(error) => {- tracing::warn!(error=?error, "OpenAI embedding failed; using local task embedding");- return Ok(local_embedding(content));- }- Ok(response) => response,- };-- let response: serde_json::Value = match response.json().await {- Ok(response) => response,- Err(error) => {- tracing::warn!(error=?error, "OpenAI embedding JSON failed; using local task embedding");- return Ok(local_embedding(content));- }- };-- let embedding = response["data"][0]["embedding"]- .as_array()- .ok_or_else(|| anyhow::anyhow!("OpenAI embedding response missing data[0].embedding"))?- .iter()- .map(|value| {- value- .as_f64()- .map(|number| number as f32)- .ok_or_else(|| anyhow::anyhow!("OpenAI embedding value was not a number"))+ // 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::<anyhow::Result<Vec<_>>>()?;-- anyhow::ensure!(- embedding.len() == EMBEDDING_DIM,- "expected {EMBEDDING_DIM} embedding dimensions, got {}",- embedding.len()- );+ .collect()+ }+}- Ok(embedding)+#[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 local embedder for tests and offline development.+/// 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>> {@@ -95,7 +179,10 @@ impl TaskEmbedder for LocalTaskEmbedder {}}-/// Deterministic local embedding used for tests and API fallback.+/// 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 textdiff --git a/rust/cloud-storage/task_dedup/src/outbound/judge.rs b/rust/cloud-storage/task_dedup/src/outbound/judge.rsindex 311f88f673..dbdcd187f8 100644--- a/rust/cloud-storage/task_dedup/src/outbound/judge.rs+++ b/rust/cloud-storage/task_dedup/src/outbound/judge.rs@@ -9,10 +9,11 @@ use serde_json::json;use crate::domain::models::JudgeResult;use crate::domain::ports::TaskDuplicateJudge;-/// Judge that uses the agent structured completion path and falls back to-/// deterministic rerank thresholds otherwise.+/// Judge that decides duplicates via the agent structured completion path.+///+/// When the model call fails it defaults to *not* a duplicate, so an outage+/// can't fabricate matches.pub struct AgentDuplicateJudge {- fallback_threshold: f64,model: AgentModel,}@@ -23,37 +24,38 @@ struct DuplicateJudgeOutput {}impl AgentDuplicateJudge {- /// Creates a new judge.- pub fn new(fallback_threshold: f64) -> Self {+ /// Creates a new judge using the fast agent model.+ pub fn new() -> Self {Self {- fallback_threshold,model: AgentModel::Fast,}}/// Creates a new judge with an explicit agent model.- pub fn with_model(fallback_threshold: f64, model: AgentModel) -> Self {- Self {- fallback_threshold,- model,- }+ pub fn with_model(model: AgentModel) -> Self {+ Self { model }}- fn fallback(&self, rerank_score: f64, model: Option<String>, reason: &str) -> JudgeResult {+ fn unavailable(&self, reason: &str) -> JudgeResult {JudgeResult {- is_duplicate: rerank_score >= self.fallback_threshold,- model,+ is_duplicate: false,+ model: Some(self.model.to_string()),reason: Some(reason.to_string()),}}}+impl Default for AgentDuplicateJudge {+ fn default() -> Self {+ Self::new()+ }+}+#[async_trait]impl TaskDuplicateJudge for AgentDuplicateJudge {- async fn judge(&self, left: &str, right: &str, rerank_score: f64) -> JudgeResult {+ async fn judge(&self, left: &str, right: &str) -> JudgeResult {let model_name = self.model.to_string();- let prompt =- format!("Task A:\n{left}\n\nTask B:\n{right}\n\nRerank score: {rerank_score:.3}");+ let prompt = format!("Task A:\n{left}\n\nTask B:\n{right}");let schema = DynamicSchema {name: "TaskDuplicateJudgeOutput".to_string(),description: Some(@@ -85,11 +87,7 @@ impl TaskDuplicateJudge for AgentDuplicateJudge {.await;let Ok(value) = value else {- return self.fallback(- rerank_score,- Some(model_name),- "judge request failed; local rerank fallback",- );+ return self.unavailable("judge request failed; treated as not duplicate");};match serde_json::from_value::<DuplicateJudgeOutput>(value) {@@ -98,34 +96,35 @@ impl TaskDuplicateJudge for AgentDuplicateJudge {model: Some(model_name),reason: Some(parsed.reason),},- Err(_) => self.fallback(- rerank_score,- Some(model_name),- "judge JSON parse failed; local rerank fallback",- ),+ Err(_) => self.unavailable("judge JSON parse failed; treated as not duplicate"),}}}-/// Local judge for tests.-pub struct LocalDuplicateJudge {- threshold: f64,-}+/// Deterministic judge for tests: treats two tasks as duplicates only when their+/// embedding content is identical.+pub struct LocalDuplicateJudge;impl LocalDuplicateJudge {- /// Creates a local threshold judge.- pub fn new(threshold: f64) -> Self {- Self { threshold }+ /// Creates a local judge.+ pub fn new() -> Self {+ Self+ }+}++impl Default for LocalDuplicateJudge {+ fn default() -> Self {+ Self::new()}}#[async_trait]impl TaskDuplicateJudge for LocalDuplicateJudge {- async fn judge(&self, _left: &str, _right: &str, rerank_score: f64) -> JudgeResult {+ async fn judge(&self, left: &str, right: &str) -> JudgeResult {JudgeResult {- is_duplicate: rerank_score >= self.threshold,+ is_duplicate: left.trim() == right.trim(),model: None,- reason: Some("local rerank fallback".to_string()),+ reason: Some("local exact-match judge".to_string()),}}}diff --git a/rust/cloud-storage/task_dedup/src/outbound/mod.rs b/rust/cloud-storage/task_dedup/src/outbound/mod.rsindex 33c2ad9363..781fb38710 100644--- a/rust/cloud-storage/task_dedup/src/outbound/mod.rs+++ b/rust/cloud-storage/task_dedup/src/outbound/mod.rs@@ -4,3 +4,4 @@ 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.rsindex 93550a9adf..f2b527e913 100644--- a/rust/cloud-storage/task_dedup/src/outbound/postgres.rs+++ b/rust/cloud-storage/task_dedup/src/outbound/postgres.rs@@ -1,5 +1,8 @@//! Postgres task duplicate repo.+#[cfg(test)]+mod test;+use async_trait::async_trait;use sqlx::PgPool;use uuid::Uuid;@@ -10,6 +13,17 @@ use crate::domain::models::{use crate::domain::ports::TaskDedupRepo;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.#[derive(Clone)]pub struct PgTaskDedupRepo {@@ -21,6 +35,48 @@ impl PgTaskDedupRepo {pub fn new(pool: PgPool) -> Self {Self { pool }}++ /// 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(+ &self,+ model: &str,+ items: &[TaskEmbeddingUpsert],+ ) -> Result<(), TaskDedupError> {+ if items.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+ .iter()+ .map(|item| vector_sql_literal(&item.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,+ embedding = EXCLUDED.embedding,+ updated_at = NOW()+ "#,+ model,+ &document_ids,+ &contents,+ &embeddings,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }}#[async_trait]@@ -158,7 +214,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {task_id: &str,duplicate_task_id: &str,vector_score: f64,- rerank_score: f64,judge_model: Option<&str>,judge_reason: Option<&str>,) -> Result<(), TaskDedupError> {@@ -171,15 +226,13 @@ impl TaskDedupRepo for PgTaskDedupRepo {duplicate_task_id,status,vector_score,- rerank_score,judge_model,judge_reason)- VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)+ VALUES ($1, $2, $3, 'active', $4, $5, $6)ON CONFLICT (task_id, duplicate_task_id) DO UPDATESET status = 'active',vector_score = EXCLUDED.vector_score,- rerank_score = EXCLUDED.rerank_score,judge_model = EXCLUDED.judge_model,judge_reason = EXCLUDED.judge_reason,updated_at = NOW()@@ -189,7 +242,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {task_id,duplicate_task_id,vector_score,- rerank_score,judge_model,judge_reason,)@@ -243,7 +295,7 @@ impl TaskDedupRepo for PgTaskDedupRepo {SELECTid,ROW_NUMBER() OVER (- ORDER BY rerank_score DESC, vector_score DESC, created_at DESC+ ORDER BY vector_score DESC, created_at DESC) AS rnFROM task_duplicate_matchWHERE status = 'active'@@ -274,7 +326,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS "other_task_id!",d.name AS "other_task_name!",m.vector_score AS "vector_score!",- m.rerank_score AS "rerank_score!",m.judge_reasonFROM task_duplicate_match mJOIN "Document" d@@ -282,7 +333,7 @@ impl TaskDedupRepo for PgTaskDedupRepo {WHERE m.status = 'active'AND (m.task_id = $1 OR m.duplicate_task_id = $1)AND d."deletedAt" IS NULL- ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC+ ORDER BY m.vector_score DESC, m.created_at DESCLIMIT 10"#,document_id,@@ -297,7 +348,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {task_id: row.other_task_id,task_name: row.other_task_name,vector_score: row.vector_score,- rerank_score: row.rerank_score,judge_reason: row.judge_reason,}).collect())@@ -353,33 +403,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {Ok(exists.unwrap_or(false))}- async fn other_task_id(- &self,- document_id: &str,- match_id: Uuid,- ) -> Result<Option<String>, TaskDedupError> {- let row = sqlx::query!(- r#"- SELECT task_id, duplicate_task_id- FROM task_duplicate_match- WHERE id = $1- AND (task_id = $2 OR duplicate_task_id = $2)- "#,- match_id,- document_id,- )- .fetch_optional(&self.pool)- .await?;-- Ok(row.map(|row| {- if row.task_id == document_id {- row.duplicate_task_id- } else {- row.task_id- }- }))- }-async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {let row = sqlx::query!(r#"@@ -410,25 +433,6 @@ impl TaskDedupRepo for PgTaskDedupRepo {.await?;Ok(())}-- async fn dismiss_match_by_id_for_user(- &self,- match_id: Uuid,- dismissed_by: &str,- ) -> Result<(), TaskDedupError> {- sqlx::query!(- r#"- UPDATE task_duplicate_match- SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()- WHERE id = $1- "#,- match_id,- dismissed_by,- )- .execute(&self.pool)- .await?;- Ok(())- }}/// Converts an embedding vector into a pgvector literal.@@ -440,338 +444,3 @@ pub fn vector_sql_literal(embedding: &[f32]) -> String {.join(",");format!("[{values}]")}--#[cfg(test)]-mod tests {- use std::sync::Arc;-- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::PgPool;-- use super::*;- use crate::domain::ports::TaskDedupNotifier;- use crate::domain::service::{TaskDedupConfig, TaskDedupService, task_embedding_content};- use crate::outbound::embedding::{LocalTaskEmbedder, local_embedding};- use crate::outbound::judge::LocalDuplicateJudge;-- const OWNER: &str = "macro|[email protected]";- const TEAM_ID: Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");- 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";-- struct NoopNotifier;-- #[async_trait::async_trait]- impl TaskDedupNotifier for NoopNotifier {- async fn notify_matches_updated(&self, _document_id: &str) -> anyhow::Result<()> {- Ok(())- }- }-- fn service(pool: PgPool) -> TaskDedupService {- let config = TaskDedupConfig::default();- TaskDedupService::new(- config.clone(),- Arc::new(PgTaskDedupRepo::new(pool)),- Arc::new(LocalTaskEmbedder),- Arc::new(LocalDuplicateJudge::new(0.56)),- Arc::new(NoopNotifier),- )- }-- async fn insert_task(pool: &PgPool, id: &str, name: &str, owner: &str) {- sqlx::query!(- r#"- INSERT INTO "Document" (id, name, "fileType", owner)- VALUES ($1, $2, 'md', $3)- "#,- id,- name,- owner,- )- .execute(pool)- .await- .unwrap();-- sqlx::query!(- r#"- INSERT INTO document_sub_type (document_id, sub_type)- VALUES ($1, 'task')- "#,- id,- )- .execute(pool)- .await- .unwrap();- }-- async fn insert_team_task(pool: &PgPool, document_id: &str, task_num: i32) {- sqlx::query!(- r#"- INSERT INTO team_task (team_id, document_id, task_num)- VALUES ($1, $2, $3)- "#,- TEAM_ID,- document_id,- task_num,- )- .execute(pool)- .await- .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();- }-- async fn insert_match(- pool: &PgPool,- task_id: &str,- duplicate_task_id: &str,- rerank_score: f64,- ) -> Uuid {- let id = Uuid::new_v4();- let (task_id, duplicate_task_id) =- crate::domain::service::ordered_pair(task_id, duplicate_task_id);- sqlx::query!(- r#"- INSERT INTO task_duplicate_match (- id,- task_id,- duplicate_task_id,- status,- vector_score,- rerank_score,- judge_model,- judge_reason- )- VALUES ($1, $2, $3, 'active', 0.95, $4, 'test', 'same implementation work')- "#,- id,- task_id,- duplicate_task_id,- rerank_score,- )- .execute(pool)- .await- .unwrap();- id- }-- async fn setup_tasks(pool: &PgPool) {- insert_task(pool, TASK_ONE, "Add duplicate task detection", OWNER).await;- insert_task(pool, TASK_TWO, "Detect duplicate tasks", OWNER).await;- insert_task(pool, TASK_THREE, "Fix unrelated billing copy", OWNER).await;- insert_team_task(pool, TASK_ONE, 1).await;- insert_team_task(pool, TASK_TWO, 2).await;- insert_team_task(pool, TASK_THREE, 3).await;- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- async fn lists_active_duplicates_for_either_side_of_pair(pool: PgPool) {- setup_tasks(&pool).await;- let match_id = insert_match(&pool, TASK_TWO, TASK_ONE, 0.88).await;- let service = service(pool.clone());-- let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();- assert_eq!(duplicates.len(), 1);- assert_eq!(duplicates[0].id, match_id);- assert_eq!(duplicates[0].task_id, TASK_TWO);- assert_eq!(duplicates[0].task_name, "Detect duplicate tasks");- assert_eq!(- duplicates[0].judge_reason.as_deref(),- Some("same implementation work")- );-- let duplicates = service.active_duplicates(TASK_TWO).await.unwrap();- assert_eq!(duplicates.len(), 1);- assert_eq!(duplicates[0].task_id, TASK_ONE);- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- async fn dismissed_matches_are_hidden(pool: PgPool) {- setup_tasks(&pool).await;- let match_id = insert_match(&pool, TASK_ONE, TASK_TWO, 0.88).await;- let service = service(pool.clone());-- service- .dismiss_match(TASK_ONE, match_id, OWNER)- .await- .unwrap();-- let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();- assert!(duplicates.is_empty());- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- async fn deleted_duplicate_tasks_are_hidden(pool: PgPool) {- setup_tasks(&pool).await;- insert_match(&pool, TASK_ONE, TASK_TWO, 0.88).await;- let service = service(pool.clone());-- sqlx::query!(- r#"- UPDATE "Document"- SET "deletedAt" = NOW()- WHERE id = $1- "#,- TASK_TWO,- )- .execute(&pool)- .await- .unwrap();-- let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();- assert!(duplicates.is_empty());- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- 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;-- 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(),- })- .await- .unwrap();-- let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();- assert_eq!(duplicates.len(), 1);- assert_eq!(duplicates[0].task_id, TASK_TWO);- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- async fn detection_closes_existing_duplicate_component(pool: PgPool) {- setup_tasks(&pool).await;- insert_match(&pool, TASK_TWO, TASK_THREE, 0.88).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;-- 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(),- })- .await- .unwrap();-- let mut duplicate_ids = service- .active_duplicates(TASK_ONE)- .await- .unwrap()- .into_iter()- .map(|duplicate| duplicate.task_id)- .collect::<Vec<_>>();- duplicate_ids.sort();-- assert_eq!(duplicate_ids, vec![TASK_TWO, TASK_THREE]);- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))- )]- 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(- &pool,- TASK_THREE,- &task_embedding_content(- "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.",- )- .await- .unwrap();-- // Only the similar task is surfaced; the unrelated one is filtered out.- assert_eq!(results.len(), 1);- 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.- 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);-- let match_count =- sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_match"#)- .fetch_one(&pool)- .await- .unwrap();- assert_eq!(match_count, 0);- }-}diff --git a/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs b/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rsnew file mode 100644index 0000000000..b10f07330d--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/postgres/test.rs@@ -0,0 +1,408 @@+use std::sync::Arc;++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;++use super::*;+use crate::domain::ports::TaskDedupNotifier;+use crate::domain::service::{TaskDedupConfig, TaskDedupService, task_embedding_content};+use crate::outbound::embedding::{LocalTaskEmbedder, local_embedding};+use crate::outbound::judge::LocalDuplicateJudge;+use crate::outbound::reranker::NoOpTaskReranker;++const OWNER: &str = "macro|[email protected]";+const TEAM_ID: Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");+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";++struct NoopNotifier;++#[async_trait::async_trait]+impl TaskDedupNotifier for NoopNotifier {+ async fn notify_matches_updated(&self, _document_id: &str) -> anyhow::Result<()> {+ Ok(())+ }+}++fn service(pool: PgPool) -> TaskDedupService {+ let config = TaskDedupConfig::default();+ TaskDedupService::new(+ config.clone(),+ Arc::new(PgTaskDedupRepo::new(pool)),+ Arc::new(LocalTaskEmbedder),+ Arc::new(NoOpTaskReranker),+ Arc::new(LocalDuplicateJudge::new()),+ Arc::new(NoopNotifier),+ )+}++async fn insert_task(pool: &PgPool, id: &str, name: &str, owner: &str) {+ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, "fileType", owner)+ VALUES ($1, $2, 'md', $3)+ "#,+ id,+ name,+ owner,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"+ INSERT INTO document_sub_type (document_id, sub_type)+ VALUES ($1, 'task')+ "#,+ id,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_team_task(pool: &PgPool, document_id: &str, task_num: i32) {+ sqlx::query!(+ r#"+ INSERT INTO team_task (team_id, document_id, task_num)+ VALUES ($1, $2, $3)+ "#,+ TEAM_ID,+ document_id,+ task_num,+ )+ .execute(pool)+ .await+ .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();+}++async fn insert_match(pool: &PgPool, task_id: &str, duplicate_task_id: &str) -> Uuid {+ let id = Uuid::new_v4();+ let (task_id, duplicate_task_id) =+ crate::domain::service::ordered_pair(task_id, duplicate_task_id);+ sqlx::query!(+ r#"+ INSERT INTO task_duplicate_match (+ id,+ task_id,+ duplicate_task_id,+ status,+ vector_score,+ judge_model,+ judge_reason+ )+ VALUES ($1, $2, $3, 'active', 0.95, 'test', 'same implementation work')+ "#,+ id,+ task_id,+ duplicate_task_id,+ )+ .execute(pool)+ .await+ .unwrap();+ id+}++async fn setup_tasks(pool: &PgPool) {+ insert_task(pool, TASK_ONE, "Add duplicate task detection", OWNER).await;+ insert_task(pool, TASK_TWO, "Detect duplicate tasks", OWNER).await;+ insert_task(pool, TASK_THREE, "Fix unrelated billing copy", OWNER).await;+ insert_team_task(pool, TASK_ONE, 1).await;+ insert_team_task(pool, TASK_TWO, 2).await;+ insert_team_task(pool, TASK_THREE, 3).await;+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+async fn bulk_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"),+ },+ ],+ )+ .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);++ // 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"),+ }],+ )+ .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"#,+ TASK_ONE,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(content, "first updated");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+async fn lists_active_duplicates_for_either_side_of_pair(pool: PgPool) {+ setup_tasks(&pool).await;+ let match_id = insert_match(&pool, TASK_TWO, TASK_ONE).await;+ let service = service(pool.clone());++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].id, match_id);+ assert_eq!(duplicates[0].task_id, TASK_TWO);+ assert_eq!(duplicates[0].task_name, "Detect duplicate tasks");+ assert_eq!(+ duplicates[0].judge_reason.as_deref(),+ Some("same implementation work")+ );++ let duplicates = service.active_duplicates(TASK_TWO).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].task_id, TASK_ONE);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+async fn dismissed_matches_are_hidden(pool: PgPool) {+ setup_tasks(&pool).await;+ let match_id = insert_match(&pool, TASK_ONE, TASK_TWO).await;+ let service = service(pool.clone());++ service+ .dismiss_matches(TASK_ONE, &[match_id], OWNER)+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert!(duplicates.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+async fn deleted_duplicate_tasks_are_hidden(pool: PgPool) {+ setup_tasks(&pool).await;+ insert_match(&pool, TASK_ONE, TASK_TWO).await;+ let service = service(pool.clone());++ sqlx::query!(+ r#"+ UPDATE "Document"+ SET "deletedAt" = NOW()+ WHERE id = $1+ "#,+ TASK_TWO,+ )+ .execute(&pool)+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert!(duplicates.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+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;++ 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(),+ })+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].task_id, TASK_TWO);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+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;++ 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(),+ })+ .await+ .unwrap();++ let mut duplicate_ids = service+ .active_duplicates(TASK_ONE)+ .await+ .unwrap()+ .into_iter()+ .map(|duplicate| duplicate.task_id)+ .collect::<Vec<_>>();+ duplicate_ids.sort();++ assert_eq!(duplicate_ids, vec![TASK_TWO, TASK_THREE]);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../documents/fixtures",+ scripts("documents_test_data")+ )+)]+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(+ &pool,+ TASK_THREE,+ &task_embedding_content(+ "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.",+ )+ .await+ .unwrap();++ // Only the similar task is surfaced; the unrelated one is filtered out.+ assert_eq!(results.len(), 1);+ 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.+ 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);++ let match_count =+ sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_match"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(match_count, 0);+}diff --git a/rust/cloud-storage/task_dedup/src/outbound/reranker.rs b/rust/cloud-storage/task_dedup/src/outbound/reranker.rsnew file mode 100644index 0000000000..6305e34607--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/reranker.rs@@ -0,0 +1,20 @@+//! Reranker adapters for task duplicate detection.++use async_trait::async_trait;++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).+///+/// 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;++#[async_trait]+impl TaskReranker for NoOpTaskReranker {+ async fn rerank(&self, _query: &str, documents: &[String]) -> anyhow::Result<Vec<f64>> {+ Ok(vec![0.0; documents.len()])+ }+}