Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): add recently-emitted document store to embedding worker (#66306)

Oliver Brownee7f90dfb3d7b
diff --git a/posthog/api/embedding_worker.py b/posthog/api/embedding_worker.py
index e497e79f01f9..3713ba9b4092 100644
--- a/posthog/api/embedding_worker.py
+++ b/posthog/api/embedding_worker.py
@@ -34,7 +34,18 @@ class EmbeddingResponse:
did_truncate: bool
+@dataclass(frozen=True)
+class DocumentKey:
+ """The full embedding identity; document_id alone is not unique."""
+
+ product: str
+ document_type: str
+ rendering: str
+ document_id: str
+
+
_EMBEDDING_URL = EMBEDDING_API_URL + "/generate/ad_hoc"
+_RECENTLY_SEEN_URL = EMBEDDING_API_URL + "/recently_seen"
def _build_embedding_payload(team: Team, content: str, model: str | None, no_truncate: bool) -> dict:
@@ -161,3 +172,61 @@ def emit_embedding_request(
producer = get_producer(topic=KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC)
return producer.produce(topic=KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC, data=payload)
+
+
+def _build_recently_seen_payload(documents: list[DocumentKey], team_id: int) -> dict:
+ return {
+ "team_id": team_id,
+ "documents": [
+ {
+ "product": d.product,
+ "document_type": d.document_type,
+ "rendering": d.rendering,
+ "document_id": d.document_id,
+ }
+ for d in documents
+ ],
+ }
+
+
+def _parse_recently_seen_response(data: list[dict]) -> dict[DocumentKey, Optional[datetime]]:
+ results: dict[DocumentKey, Optional[datetime]] = {}
+ for item in data:
+ key = DocumentKey(
+ product=item["product"],
+ document_type=item["document_type"],
+ rendering=item["rendering"],
+ document_id=item["document_id"],
+ )
+ emitted_at = item.get("emitted_at")
+ results[key] = datetime.fromisoformat(emitted_at) if emitted_at else None
+ return results
+
+
+def get_recently_seen_documents(
+ documents: list[DocumentKey],
+ *,
+ team_id: int,
+ timeout: float | None = 30.0,
+) -> dict[DocumentKey, Optional[datetime]]:
+ """Return each document's worker emission time, or None when it is not cached."""
+ if not documents:
+ return {}
+ payload = _build_recently_seen_payload(documents, team_id)
+ response = internal_requests.post(_RECENTLY_SEEN_URL, json=payload, timeout=timeout)
+ response.raise_for_status()
+ return _parse_recently_seen_response(response.json())
+
+
+async def async_get_recently_seen_documents(
+ documents: list[DocumentKey],
+ *,
+ team_id: int,
+) -> dict[DocumentKey, Optional[datetime]]:
+ if not documents:
+ return {}
+ payload = _build_recently_seen_payload(documents, team_id)
+ async with internal_httpx_async_client(timeout=30.0) as client:
+ response = await client.post(_RECENTLY_SEEN_URL, json=payload)
+ response.raise_for_status()
+ return _parse_recently_seen_response(response.json())
diff --git a/posthog/api/test/test_embedding_worker.py b/posthog/api/test/test_embedding_worker.py
new file mode 100644
index 000000000000..68acc733d241
--- /dev/null
+++ b/posthog/api/test/test_embedding_worker.py
@@ -0,0 +1,69 @@
+from datetime import UTC, datetime
+
+from unittest.mock import MagicMock, patch
+
+from posthog.api.embedding_worker import DocumentKey, get_recently_seen_documents
+
+
+def _doc(document_id: str, product: str = "signals") -> DocumentKey:
+ return DocumentKey(
+ product=product,
+ document_type="signal",
+ rendering="plain",
+ document_id=document_id,
+ )
+
+
+class TestRecentlySeenLookup:
+ @patch("posthog.api.embedding_worker.internal_requests")
+ def test_maps_each_document_to_its_emit_time_keyed_by_full_identity(self, mock_requests):
+ seen = _doc("abc")
+ unseen = _doc("def")
+ other_product = _doc("abc", product="error_tracking")
+
+ mock_response = MagicMock()
+ mock_response.json.return_value = [
+ {
+ "product": "signals",
+ "document_type": "signal",
+ "rendering": "plain",
+ "document_id": "abc",
+ "emitted_at": "2026-06-26T12:00:00+00:00",
+ },
+ {
+ "product": "signals",
+ "document_type": "signal",
+ "rendering": "plain",
+ "document_id": "def",
+ "emitted_at": None,
+ },
+ {
+ "product": "error_tracking",
+ "document_type": "signal",
+ "rendering": "plain",
+ "document_id": "abc",
+ "emitted_at": None,
+ },
+ ]
+ mock_requests.post.return_value = mock_response
+
+ results = get_recently_seen_documents([seen, unseen, other_product], team_id=7)
+
+ assert results[seen] == datetime(2026, 6, 26, 12, 0, 0, tzinfo=UTC)
+ assert results[unseen] is None
+ assert results[other_product] is None
+
+ _, kwargs = mock_requests.post.call_args
+ assert kwargs["json"]["team_id"] == 7
+ assert {
+ "product": "error_tracking",
+ "document_type": "signal",
+ "rendering": "plain",
+ "document_id": "abc",
+ } in kwargs["json"]["documents"]
+ assert kwargs["timeout"] == 30.0
+
+ @patch("posthog.api.embedding_worker.internal_requests")
+ def test_empty_input_makes_no_request(self, mock_requests):
+ assert get_recently_seen_documents([], team_id=1) == {}
+ mock_requests.post.assert_not_called()
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index bd7c8b13ea14..a4cc108196b5 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4128,7 +4128,10 @@ name = "embedding-worker"
version = "0.1.0"
dependencies = [
"anyhow",
+ "aws-config",
+ "aws-sdk-dynamodb",
"axum 0.7.9",
+ "chrono",
"common-alloc",
"common-continuous-profiling",
"common-kafka",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 7f5f64bd8721..8e9157795fb6 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -229,6 +229,7 @@ quick_cache = "0.6.21"
ahash = "0.8.11"
aws-config = { version = "1.1.7", features = ["behavior-version-latest"] }
aws-sdk-s3 = "1.58.0"
+aws-sdk-dynamodb = "1.55.0"
aws-smithy-runtime-api = { version = "1.11.5", features = ["client"] }
aws-smithy-http-client = { version = "1.1.11", features = ["rustls-aws-lc"] }
mockall = "0.13.0"
diff --git a/rust/embedding-worker/Cargo.toml b/rust/embedding-worker/Cargo.toml
index b8b601ad5460..1f37acd8036c 100644
--- a/rust/embedding-worker/Cargo.toml
+++ b/rust/embedding-worker/Cargo.toml
@@ -28,6 +28,9 @@ leaky-bucket = "1.1.2" # Arguably we should just implement this, but :shrug:
moka.workspace = true
serde.workspace = true
rand.workspace = true
+chrono.workspace = true
+aws-config.workspace = true
+aws-sdk-dynamodb.workspace = true
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
diff --git a/rust/embedding-worker/src/app_context.rs b/rust/embedding-worker/src/app_context.rs
index a8c3e59ea997..3e66ce02cfb3 100644
--- a/rust/embedding-worker/src/app_context.rs
+++ b/rust/embedding-worker/src/app_context.rs
@@ -1,4 +1,4 @@
-use std::{collections::HashMap, time::Duration};
+use std::{collections::HashMap, sync::Arc, time::Duration};
use anyhow::Result;
use common_kafka::{
@@ -20,6 +20,7 @@ use crate::{
config::Config,
metrics_utils::{LIMITS_UPDATED, LIMIT_BALANCE},
organization::Organization,
+ recently_seen::{build_store, RecentlySeenStore},
};
pub struct AppContext {
@@ -31,6 +32,7 @@ pub struct AppContext {
pub config: Config,
pub client: reqwest::Client,
pub org_cache: Cache<i32, Option<Organization>>,
+ pub recently_seen: Arc<dyn RecentlySeenStore>,
rate_limits: RwLock<HashMap<String, Limiter>>,
}
@@ -74,6 +76,8 @@ impl AppContext {
.time_to_live(Duration::from_secs(30))
.build();
+ let recently_seen = build_store(&config).await?;
+
Ok(Self {
health_registry,
worker_liveness,
@@ -83,6 +87,7 @@ impl AppContext {
config,
client,
org_cache,
+ recently_seen,
rate_limits: Default::default(),
})
}
diff --git a/rust/embedding-worker/src/config.rs b/rust/embedding-worker/src/config.rs
index dd3c7494b744..c55293b229a9 100644
--- a/rust/embedding-worker/src/config.rs
+++ b/rust/embedding-worker/src/config.rs
@@ -52,6 +52,22 @@ pub struct Config {
// can't stall batch processing indefinitely.
#[envconfig(default = "10")]
pub embedding_request_timeout_seconds: u64,
+
+ #[envconfig(from = "RECENT_IDS_STORE", default = "memory")]
+ pub recent_ids_store: String,
+
+ #[envconfig(
+ from = "RECENT_IDS_DYNAMODB_TABLE",
+ default = "embedding_worker_recently_seen"
+ )]
+ pub recent_ids_dynamodb_table: String,
+
+ // TTL starts when the worker records the document, not from its timestamp.
+ #[envconfig(from = "RECENT_IDS_TTL_SECONDS", default = "604800")]
+ pub recent_ids_ttl_seconds: i64,
+
+ #[envconfig(from = "RECENT_IDS_AWS_REGION")]
+ pub aws_region: Option<String>,
}
impl Config {
diff --git a/rust/embedding-worker/src/lib.rs b/rust/embedding-worker/src/lib.rs
index db3714788f39..4dbc363cb518 100644
--- a/rust/embedding-worker/src/lib.rs
+++ b/rust/embedding-worker/src/lib.rs
@@ -34,6 +34,7 @@ pub mod app_context;
pub mod config;
pub mod metrics_utils;
pub mod organization;
+pub mod recently_seen;
pub async fn handle_batch(
requests: Vec<EmbeddingRequest>,
diff --git a/rust/embedding-worker/src/main.rs b/rust/embedding-worker/src/main.rs
index 735092d56d3d..6da00ce71d0d 100644
--- a/rust/embedding-worker/src/main.rs
+++ b/rust/embedding-worker/src/main.rs
@@ -1,4 +1,4 @@
-use std::{future::ready, sync::Arc};
+use std::{future::ready, sync::Arc, time::Instant};
use axum::{
extract::{Json, State},
@@ -6,6 +6,7 @@ use axum::{
routing::get,
Router,
};
+use chrono::{DateTime, Utc};
use common_kafka::kafka_consumer::RecvErr;
use common_metrics::{serve, setup_metrics_routes};
use common_types::embedding::{EmbeddingRecord, EmbeddingRequest};
@@ -14,10 +15,15 @@ use embedding_worker::{
app_context::AppContext,
config::Config,
handle_batch,
- metrics_utils::DROPPED_REQUESTS,
+ metrics_utils::{
+ DROPPED_REQUESTS, RECENTLY_SEEN_DOCUMENTS, RECENTLY_SEEN_OPERATIONS,
+ RECENTLY_SEEN_OPERATION_TIME,
+ },
+ recently_seen::{dedup_seen, DocumentKey, SeenRecord},
};
-use metrics::counter;
+use metrics::{counter, histogram};
+use serde::{Deserialize, Serialize};
use tokio::task::JoinHandle;
use tracing::level_filters::LevelFilter;
use tracing::{error, info};
@@ -54,6 +60,51 @@ async fn ad_hoc_handler(
}
}
+#[derive(Deserialize)]
+struct RecentlySeenRequest {
+ team_id: i32,
+ documents: Vec<DocumentKey>,
+}
+
+#[derive(Serialize)]
+struct RecentlySeenResult {
+ #[serde(flatten)]
+ document: DocumentKey,
+ emitted_at: Option<DateTime<Utc>>,
+}
+
+async fn recently_seen_handler(
+ State(context): State<Arc<AppContext>>,
+ Json(request): Json<RecentlySeenRequest>,
+) -> Json<Vec<RecentlySeenResult>> {
+ let started_at = Instant::now();
+ let lookup = context
+ .recently_seen
+ .lookup(request.team_id, request.documents)
+ .await;
+ histogram!(RECENTLY_SEEN_OPERATION_TIME, "operation" => "read")
+ .record(started_at.elapsed().as_secs_f64());
+ counter!(RECENTLY_SEEN_OPERATIONS, "operation" => "read").increment(1);
+ let hit_count = lookup
+ .values()
+ .filter(|emitted_at| emitted_at.is_some())
+ .count();
+ counter!(RECENTLY_SEEN_DOCUMENTS, "operation" => "read", "result" => "hit")
+ .increment(hit_count as u64);
+ counter!(RECENTLY_SEEN_DOCUMENTS, "operation" => "read", "result" => "miss")
+ .increment((lookup.len() - hit_count) as u64);
+
+ Json(
+ lookup
+ .into_iter()
+ .map(|(document, emitted_at)| RecentlySeenResult {
+ document,
+ emitted_at,
+ })
+ .collect(),
+ )
+}
+
fn start_health_liveness_server(config: &Config, context: Arc<AppContext>) -> JoinHandle<()> {
let config = config.clone();
let liveness_context = context.clone();
@@ -65,6 +116,7 @@ fn start_health_liveness_server(config: &Config, context: Arc<AppContext>) -> Jo
get(move || ready(liveness_context.health_registry.get_status())),
)
.route("/generate/ad_hoc", axum::routing::post(ad_hoc_handler))
+ .route("/recently_seen", axum::routing::post(recently_seen_handler))
.with_state(context);
let router = setup_metrics_routes(router);
let bind = format!("{}:{}", config.host, config.port);
@@ -174,6 +226,8 @@ async fn main() {
.flat_map(Vec::<EmbeddingRecord>::from)
.collect();
+ // Capture immediately before Kafka assigns ClickHouse inserted_at.
+ let emitted_at = Utc::now();
let emit_results = txn
.send_keyed_iter_to_kafka(
&context.config.output_topic,
@@ -208,5 +262,29 @@ async fn main() {
panic!("Failed to commit kafka transaction, {e:?}");
}
}
+
+ // Store only after commit so a hit never advertises uncommitted output.
+ let seen = dedup_seen(records.iter().map(|record| {
+ let key = DocumentKey {
+ product: record.product.clone(),
+ document_type: record.document_type.clone(),
+ rendering: record.rendering.clone(),
+ document_id: record.document_id.clone(),
+ };
+ SeenRecord {
+ team_id: record.team_id,
+ key,
+ emitted_at,
+ }
+ }));
+ if !seen.is_empty() {
+ let started_at = Instant::now();
+ context.recently_seen.record(&seen).await;
+ histogram!(RECENTLY_SEEN_OPERATION_TIME, "operation" => "write")
+ .record(started_at.elapsed().as_secs_f64());
+ counter!(RECENTLY_SEEN_OPERATIONS, "operation" => "write").increment(1);
+ counter!(RECENTLY_SEEN_DOCUMENTS, "operation" => "write", "result" => "attempted")
+ .increment(seen.len() as u64);
+ }
}
}
diff --git a/rust/embedding-worker/src/metrics_utils.rs b/rust/embedding-worker/src/metrics_utils.rs
index bc9ac3eeb459..413e25b047eb 100644
--- a/rust/embedding-worker/src/metrics_utils.rs
+++ b/rust/embedding-worker/src/metrics_utils.rs
@@ -14,6 +14,12 @@ pub const EMBEDDING_REQUEST_TIME: &str = "embedding_worker_embedding_request_tim
pub const EMBEDDING_TOTAL_TOKENS: &str = "embedding_worker_embedding_total_tokens";
pub const REQUESTS_SENT: &str = "embedding_worker_requests_sent";
pub const RESPONSES_RECEIVED: &str = "embedding_worker_responses_received";
+pub const RECENTLY_SEEN_DOCUMENTS: &str = "embedding_worker_recently_seen_documents";
+pub const RECENTLY_SEEN_OPERATIONS: &str = "embedding_worker_recently_seen_operations";
+pub const RECENTLY_SEEN_OPERATION_TIME: &str = "embedding_worker_recently_seen_operation_time";
+pub const RECENTLY_SEEN_RETRIES: &str = "embedding_worker_recently_seen_retries";
+pub const RECENTLY_SEEN_WRITE_ERRORS: &str = "embedding_worker_recently_seen_write_errors";
+pub const RECENTLY_SEEN_READ_ERRORS: &str = "embedding_worker_recently_seen_read_errors";
#[derive(Debug, Clone, Default)]
pub struct RequestLabels {
diff --git a/rust/embedding-worker/src/recently_seen/dynamo.rs b/rust/embedding-worker/src/recently_seen/dynamo.rs
new file mode 100644
index 000000000000..9b3bf9619256
--- /dev/null
+++ b/rust/embedding-worker/src/recently_seen/dynamo.rs
@@ -0,0 +1,237 @@
+use std::{collections::HashMap, time::Duration as StdDuration};
+
+use aws_config::retry::RetryConfig;
+use aws_sdk_dynamodb::types::{AttributeValue, KeysAndAttributes, PutRequest, WriteRequest};
+use axum::async_trait;
+use chrono::{DateTime, Duration, Utc};
+use metrics::counter;
+use rand::Rng;
+use tokio::time::sleep;
+use tracing::{error, warn};
+
+use crate::{
+ config::Config,
+ metrics_utils::{RECENTLY_SEEN_READ_ERRORS, RECENTLY_SEEN_RETRIES, RECENTLY_SEEN_WRITE_ERRORS},
+ recently_seen::{DocumentKey, RecentlySeenStore, SeenRecord},
+};
+const PK: &str = "pk";
+const SK: &str = "sk";
+const EMITTED_AT: &str = "emitted_at";
+const TTL_ATTR: &str = "expires_at";
+// DynamoDB caps BatchWriteItem at 25 items and BatchGetItem at 100 keys per request.
+const BATCH_WRITE_CHUNK: usize = 25;
+const BATCH_GET_CHUNK: usize = 100;
+const AWS_MAX_ATTEMPTS: u32 = 5;
+const UNPROCESSED_MAX_ATTEMPTS: usize = 5;
+const UNPROCESSED_INITIAL_BACKOFF_MS: u64 = 50;
+
+async fn backoff_before_retry(operation: &'static str, attempt: usize) {
+ counter!(RECENTLY_SEEN_RETRIES, "operation" => operation).increment(1);
+ let max_delay_ms = UNPROCESSED_INITIAL_BACKOFF_MS * 2_u64.pow((attempt - 1) as u32);
+ let delay_ms = rand::thread_rng().gen_range(max_delay_ms / 2..=max_delay_ms);
+ sleep(StdDuration::from_millis(delay_ms)).await;
+}
+
+fn partition_key(team_id: i32, key: &DocumentKey) -> String {
+ format!(
+ "{}#{}#{}#{}",
+ team_id, key.product, key.document_type, key.rendering
+ )
+}
+
+pub struct DynamoDbStore {
+ client: aws_sdk_dynamodb::Client,
+ table: String,
+ ttl: Duration,
+}
+
+pub async fn build_dynamodb_store(config: &Config) -> DynamoDbStore {
+ let ttl = Duration::seconds(config.recent_ids_ttl_seconds);
+ let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest())
+ .retry_config(RetryConfig::standard().with_max_attempts(AWS_MAX_ATTEMPTS));
+ if let Some(region) = &config.aws_region {
+ loader = loader.region(aws_sdk_dynamodb::config::Region::new(region.clone()));
+ }
+ let shared = loader.load().await;
+ let client = aws_sdk_dynamodb::Client::new(&shared);
+
+ DynamoDbStore {
+ client,
+ table: config.recent_ids_dynamodb_table.clone(),
+ ttl,
+ }
+}
+
+#[async_trait]
+impl RecentlySeenStore for DynamoDbStore {
+ async fn record(&self, documents: &[SeenRecord]) {
+ let expires_at = Utc::now().timestamp() + self.ttl.num_seconds();
+ for chunk in documents.chunks(BATCH_WRITE_CHUNK) {
+ let mut write_requests = Vec::with_capacity(chunk.len());
+ for doc in chunk {
+ let item = HashMap::from([
+ (
+ PK.to_string(),
+ AttributeValue::S(partition_key(doc.team_id, &doc.key)),
+ ),
+ (
+ SK.to_string(),
+ AttributeValue::S(doc.key.document_id.clone()),
+ ),
+ (
+ EMITTED_AT.to_string(),
+ AttributeValue::S(doc.emitted_at.to_rfc3339()),
+ ),
+ (
+ TTL_ATTR.to_string(),
+ AttributeValue::N(expires_at.to_string()),
+ ),
+ ]);
+ let put = PutRequest::builder()
+ .set_item(Some(item))
+ .build()
+ .expect("item is set");
+ write_requests.push(WriteRequest::builder().put_request(put).build());
+ }
+
+ let mut pending = write_requests;
+ for attempt in 1..=UNPROCESSED_MAX_ATTEMPTS {
+ let pending_count = pending.len();
+ let mut response = match self
+ .client
+ .batch_write_item()
+ .request_items(self.table.clone(), pending)
+ .send()
+ .await
+ {
+ Ok(response) => response,
+ Err(e) => {
+ error!("Failed to write recently-seen records to DynamoDB: {e:?}");
+ counter!(RECENTLY_SEEN_WRITE_ERRORS).increment(pending_count as u64);
+ break;
+ }
+ };
+
+ pending = response
+ .unprocessed_items
+ .as_mut()
+ .and_then(|items| items.remove(&self.table))
+ .unwrap_or_default();
+ if pending.is_empty() {
+ break;
+ }
+ if attempt == UNPROCESSED_MAX_ATTEMPTS {
+ warn!(
+ "DynamoDB left {} recently-seen records unprocessed after {attempt} attempts",
+ pending.len()
+ );
+ counter!(RECENTLY_SEEN_WRITE_ERRORS).increment(pending.len() as u64);
+ break;
+ }
+
+ backoff_before_retry("write", attempt).await;
+ }
+ }
+ }
+
+ async fn lookup(
+ &self,
+ team_id: i32,
+ keys: Vec<DocumentKey>,
+ ) -> HashMap<DocumentKey, Option<DateTime<Utc>>> {
+ let mut results: HashMap<DocumentKey, Option<DateTime<Utc>>> =
+ keys.iter().cloned().map(|k| (k, None)).collect();
+
+ for chunk in keys.chunks(BATCH_GET_CHUNK) {
+ // BatchGetItem rejects duplicate keys, so the reverse index also deduplicates.
+ let mut index: HashMap<(String, String), DocumentKey> = HashMap::new();
+ let mut request_keys = Vec::with_capacity(chunk.len());
+ for key in chunk {
+ let pk = partition_key(team_id, key);
+ let sk = key.document_id.clone();
+ if index
+ .insert((pk.clone(), sk.clone()), key.clone())
+ .is_some()
+ {
+ continue;
+ }
+ request_keys.push(HashMap::from([
+ (PK.to_string(), AttributeValue::S(pk)),
+ (SK.to_string(), AttributeValue::S(sk)),
+ ]));
+ }
+
+ let mut pending = KeysAndAttributes::builder()
+ .set_keys(Some(request_keys))
+ .projection_expression(format!("{PK}, {SK}, {EMITTED_AT}"))
+ .build()
+ .expect("keys are set");
+
+ for attempt in 1..=UNPROCESSED_MAX_ATTEMPTS {
+ let pending_count = pending.keys().len();
+ let mut response = match self
+ .client
+ .batch_get_item()
+ .request_items(self.table.clone(), pending)
+ .send()
+ .await
+ {
+ Ok(response) => response,
+ Err(e) => {
+ error!("Failed to read recently-seen records from DynamoDB: {e:?}");
+ counter!(RECENTLY_SEEN_READ_ERRORS).increment(pending_count as u64);
+ break;
+ }
+ };
+
+ if let Some(items) = response
+ .responses
+ .as_mut()
+ .and_then(|responses| responses.remove(&self.table))
+ {
+ for item in items {
+ let (Some(Ok(pk)), Some(Ok(sk))) = (
+ item.get(PK).map(AttributeValue::as_s),
+ item.get(SK).map(AttributeValue::as_s),
+ ) else {
+ continue;
+ };
+ if let Some(doc_key) = index.get(&(pk.clone(), sk.clone())) {
+ let emitted = item
+ .get(EMITTED_AT)
+ .and_then(|v| v.as_s().ok())
+ .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
+ .map(|dt| dt.with_timezone(&Utc));
+ results.insert(doc_key.clone(), emitted);
+ }
+ }
+ }
+
+ let Some(next_pending) = response
+ .unprocessed_keys
+ .as_mut()
+ .and_then(|keys| keys.remove(&self.table))
+ else {
+ break;
+ };
+ if next_pending.keys().is_empty() {
+ break;
+ }
+ pending = next_pending;
+
+ if attempt == UNPROCESSED_MAX_ATTEMPTS {
+ warn!(
+ "DynamoDB left {} recently-seen lookups unprocessed after {attempt} attempts",
+ pending.keys().len()
+ );
+ counter!(RECENTLY_SEEN_READ_ERRORS).increment(pending.keys().len() as u64);
+ break;
+ }
+
+ backoff_before_retry("read", attempt).await;
+ }
+ }
+
+ results
+ }
+}
diff --git a/rust/embedding-worker/src/recently_seen/in_memory.rs b/rust/embedding-worker/src/recently_seen/in_memory.rs
new file mode 100644
index 000000000000..f252236d783a
--- /dev/null
+++ b/rust/embedding-worker/src/recently_seen/in_memory.rs
@@ -0,0 +1,82 @@
+use std::collections::HashMap;
+
+use axum::async_trait;
+use chrono::{DateTime, Duration, Utc};
+use moka::sync::Cache;
+
+use crate::recently_seen::{DocumentKey, RecentlySeenStore, SeenRecord};
+
+const MAX_CAPACITY: u64 = 100_000;
+
+pub struct InMemoryStore {
+ entries: Cache<(i32, DocumentKey), DateTime<Utc>>,
+}
+
+impl InMemoryStore {
+ pub fn new(ttl: Duration) -> Self {
+ Self::with_capacity(ttl, MAX_CAPACITY)
+ }
+
+ fn with_capacity(ttl: Duration, max_capacity: u64) -> Self {
+ Self {
+ entries: Cache::builder()
+ .max_capacity(max_capacity)
+ .time_to_live(ttl.to_std().unwrap_or_default())
+ .build(),
+ }
+ }
+}
+
+#[async_trait]
+impl RecentlySeenStore for InMemoryStore {
+ async fn record(&self, documents: &[SeenRecord]) {
+ for doc in documents {
+ self.entries
+ .insert((doc.team_id, doc.key.clone()), doc.emitted_at);
+ }
+ }
+
+ async fn lookup(
+ &self,
+ team_id: i32,
+ keys: Vec<DocumentKey>,
+ ) -> HashMap<DocumentKey, Option<DateTime<Utc>>> {
+ keys.into_iter()
+ .map(|key| {
+ let emitted = self.entries.get(&(team_id, key.clone()));
+ (key, emitted)
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn record(id: &str) -> SeenRecord {
+ SeenRecord {
+ team_id: 1,
+ key: DocumentKey {
+ product: "signals".to_string(),
+ document_type: "signal".to_string(),
+ rendering: "plain".to_string(),
+ document_id: id.to_string(),
+ },
+ emitted_at: Utc::now(),
+ }
+ }
+
+ #[tokio::test]
+ async fn evicts_entries_when_capacity_is_reached() {
+ let store = InMemoryStore::with_capacity(Duration::hours(1), 1);
+ let first = record("first");
+ let second = record("second");
+
+ store.record(&[first.clone(), second.clone()]).await;
+ store.entries.run_pending_tasks();
+
+ let results = store.lookup(1, vec![first.key, second.key]).await;
+ assert_eq!(results.values().filter(|value| value.is_some()).count(), 1);
+ }
+}
diff --git a/rust/embedding-worker/src/recently_seen/mod.rs b/rust/embedding-worker/src/recently_seen/mod.rs
new file mode 100644
index 000000000000..8a16092a62e7
--- /dev/null
+++ b/rust/embedding-worker/src/recently_seen/mod.rs
@@ -0,0 +1,163 @@
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+};
+
+use anyhow::Result;
+use axum::async_trait;
+use chrono::{DateTime, Duration, Utc};
+
+use crate::{
+ config::Config,
+ recently_seen::{dynamo::build_dynamodb_store, in_memory::InMemoryStore},
+};
+
+pub mod dynamo;
+pub mod in_memory;
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+pub struct DocumentKey {
+ pub product: String,
+ pub document_type: String,
+ pub rendering: String,
+ pub document_id: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct SeenRecord {
+ pub team_id: i32,
+ pub key: DocumentKey,
+ pub emitted_at: DateTime<Utc>,
+}
+
+#[async_trait]
+pub trait RecentlySeenStore: Send + Sync {
+ /// Records are best effort; backend failures are logged and metered.
+ async fn record(&self, documents: &[SeenRecord]);
+
+ /// Missing and expired documents map to `None`.
+ async fn lookup(
+ &self,
+ team_id: i32,
+ keys: Vec<DocumentKey>,
+ ) -> HashMap<DocumentKey, Option<DateTime<Utc>>>;
+}
+
+pub async fn build_store(config: &Config) -> Result<Arc<dyn RecentlySeenStore>> {
+ match config.recent_ids_store.as_str() {
+ "dynamodb" => Ok(Arc::new(build_dynamodb_store(config).await)),
+ "memory" => Ok(Arc::new(InMemoryStore::new(Duration::seconds(
+ config.recent_ids_ttl_seconds,
+ )))),
+ other => Err(anyhow::anyhow!("Unknown RECENT_IDS_STORE '{other}'")),
+ }
+}
+
+/// Embedding records are per model; the store is per document.
+pub fn dedup_seen(records: impl IntoIterator<Item = SeenRecord>) -> Vec<SeenRecord> {
+ let mut seen = HashSet::new();
+ records
+ .into_iter()
+ .filter(|r| seen.insert((r.team_id, r.key.clone())))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn key(id: &str) -> DocumentKey {
+ DocumentKey {
+ product: "signals".to_string(),
+ document_type: "signal".to_string(),
+ rendering: "plain".to_string(),
+ document_id: id.to_string(),
+ }
+ }
+
+ #[tokio::test]
+ async fn records_and_looks_up_emit_times_scoped_by_team() {
+ let store = InMemoryStore::new(Duration::seconds(604800));
+ let ts = Utc::now();
+ store
+ .record(&[SeenRecord {
+ team_id: 1,
+ key: key("abc"),
+ emitted_at: ts,
+ }])
+ .await;
+
+ let hits = store.lookup(1, vec![key("abc"), key("missing")]).await;
+ assert_eq!(hits.get(&key("abc")), Some(&Some(ts)));
+ assert_eq!(hits.get(&key("missing")), Some(&None));
+
+ let other_team = store.lookup(2, vec![key("abc")]).await;
+ assert_eq!(other_team.get(&key("abc")), Some(&None));
+ }
+
+ #[tokio::test]
+ async fn distinguishes_same_id_across_dimensions() {
+ let store = InMemoryStore::new(Duration::seconds(604800));
+ let ts = Utc::now();
+ let signals_doc = key("dup");
+ let mut error_doc = key("dup");
+ error_doc.product = "error_tracking".to_string();
+
+ store
+ .record(&[SeenRecord {
+ team_id: 1,
+ key: signals_doc.clone(),
+ emitted_at: ts,
+ }])
+ .await;
+
+ let hits = store
+ .lookup(1, vec![signals_doc.clone(), error_doc.clone()])
+ .await;
+ assert_eq!(hits.get(&signals_doc), Some(&Some(ts)));
+ assert_eq!(hits.get(&error_doc), Some(&None));
+ }
+
+ #[tokio::test]
+ async fn ttl_starts_when_record_is_observed() {
+ let store = InMemoryStore::new(Duration::seconds(604800));
+ let stale = Utc::now() - chrono::Duration::weeks(1) - chrono::Duration::hours(1);
+ store
+ .record(&[SeenRecord {
+ team_id: 1,
+ key: key("old"),
+ emitted_at: stale,
+ }])
+ .await;
+
+ let hits = store.lookup(1, vec![key("old")]).await;
+ assert_eq!(hits.get(&key("old")), Some(&Some(stale)));
+ }
+
+ #[tokio::test]
+ async fn expired_records_are_not_returned() {
+ let store = InMemoryStore::new(Duration::seconds(-1));
+ store
+ .record(&[SeenRecord {
+ team_id: 1,
+ key: key("old"),
+ emitted_at: Utc::now(),
+ }])
+ .await;
+
+ let hits = store.lookup(1, vec![key("old")]).await;
+ assert_eq!(hits.get(&key("old")), Some(&None));
+ }
+
+ #[test]
+ fn dedup_collapses_per_model_records_to_one_per_document() {
+ let ts = Utc::now();
+ let record = |id: &str| SeenRecord {
+ team_id: 1,
+ key: key(id),
+ emitted_at: ts,
+ };
+ let deduped = dedup_seen(vec![record("a"), record("a"), record("b")]);
+ assert_eq!(deduped.len(), 2);
+ }
+}