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.

fix(ai-research-v4): store unread blocks and record why in the index (#130075)

Nicholas Waltzc4150b83e517
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/index-columns.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/index-columns.ts
index facd1232a1d5..fba292f04864 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/index-columns.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/index-columns.ts
@@ -183,6 +183,7 @@ export const BLOCK_INDEX_COLUMNS: readonly V4Column[] = [
{ name: 'surfacing_visited_url_fingerprints', elements: 'UTF8' },
{ name: 'surfacing_click_target_ids', elements: 'INT64' },
{ name: 'surfacing_form_field_ids', elements: 'INT64' },
+ ...optional('UTF8', 'unread_reason'),
]
export const INDEX_COLUMNS: Record<V4Index, readonly V4Column[]> = {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
index f04e04931009..0f70a276f8a1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
@@ -197,6 +197,7 @@ describe('indexRowsToParquet', () => {
'OPTIONAL group surfacing_form_field_ids LIST',
'REPEATED group surfacing_form_field_ids.list',
'REQUIRED INT64 surfacing_form_field_ids.list.element',
+ 'OPTIONAL BYTE_ARRAY unread_reason UTF8',
],
}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 7c9058bd23c9..a990d88afbe5 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -490,7 +490,7 @@ The recorder streams each block into the encoder. Read a block as a stream: a Br
- The writer rewrites each CSS text where the inspector read it, so that an offline render loads only images the block refers to. An `image-set()` keeps one candidate, because a renderer picks the candidate that fits its pixel ratio and does not fall back when that candidate fails. It keeps the highest resolution of a type the image fetcher stores among the candidates that can load: inline, accepted by the URL policy, or root-relative on a known page. Only that candidate gets a fetch job, and the other candidates leave the set. A set that holds an inline image keeps all its candidates, and each remote one gets its reference.
- A root-relative CSS `url(/…)` resolves against the origin of its window's latest page URL, from a Meta event or a custom event that names a page, such as `$url_changed`, with `https` in place of the page's scheme. It gets what the absolute URL gets: its reference, or the marker or the URL without its credentials when the URL policy refuses it. A C0 control or a space before the `/`, which the URL parser strips, does not change this. A path-relative `url(…)` stays as the page wrote it, so that no part of a page path, which can hold a token, reaches a fetch. rrweb writes snapshot CSS with absolute URLs, but sends rule text, adopted style sheets and style declarations as the page wrote them. Each window resolves its own texts, so the same rule in windows on two origins gets two references. An event resolves at most 1,024 relative URLs, a flush keeps at most 64 MiB of resolved URLs, and a page URL longer than 2,048 characters resolves none.
-- The recorder reads CSS with `cssparser`, which tokenizes as CSS Syntax 3 does, so names, escapes, comments, strings and bad URLs read as a browser reads them. So `background-\69mage`, `\75 rl(…)` and `background/**/:url("…"/**/)` count, and so does a `url(` that the end of the text closes. A bad URL such as `url(a(1).png)`, which no browser loads, does not count. An image URL that itself holds an escape gets the reference of the URL it decodes to, as a font URL does, and its whole `url()` is rewritten. A block whose `image-set()` holds such a candidate, or a candidate such as `cross-fade()` with a `url()` inside, is dropped, because the set keeps its candidate as the page wrote it. A block is also dropped when an escaped URL decodes to a remote URL that the URL parser does not read.
+- The recorder reads CSS with `cssparser`, which tokenizes as CSS Syntax 3 does, so names, escapes, comments, strings and bad URLs read as a browser reads them. So `background-\69mage`, `\75 rl(…)` and `background/**/:url("…"/**/)` count, and so does a `url(` that the end of the text closes. A bad URL such as `url(a(1).png)`, which no browser loads, does not count. An image URL that itself holds an escape gets the reference of the URL it decodes to, as a font URL does, and its whole `url()` is rewritten. A block whose `image-set()` holds such a candidate, or a candidate such as `cross-fade()` with a `url()` inside, gets `unread_reason`, because the set keeps its candidate as the page wrote it. So does a block with an escaped URL that decodes to a remote URL that the URL parser does not read.
- The writer rewrites only whole `url()` and `image-set()` functions, found as the inspector finds them, inside JSON strings that hold CSS: the values of `_cssText`, `style` (style diffs included), `textContent`, `rule`, `replace`, `replaceSync` and `value`. So a class name such as `bg-[url(/a.png)]`, a quoted string or a comment keeps its text, and the class's rule still matches. The recorder counts these as `ai_research_v4_recorder_css_rewrites_total{kind="image_set"|"relative_url", outcome="rewritten"}`.
- The recorder reads a protocol-relative URL, such as `//cdn.example.com/a.png`, as `https`. It gets the same reference as the `https` form, and the rewrite replaces the text as the block holds it. A browser reads a backslash as a slash there, so `\\cdn.example.com/a.png` counts too, and so does a URL such as `https:\\cdn.example.com/a.png` with any mix of slashes and backslashes after the scheme, or none: on a page of another scheme the browser loads `https:cdn.example.com/a.png` from that host. The URL parser drops ASCII tabs and line breaks anywhere in a URL, and C0 controls and spaces at either end, so the recorder drops them before it decides that a URL is remote, and `/\n/cdn.example.com/a.png` and `\u0001https://cdn.example.com/a.png` count too.
- Some URLs get no reference and keep their place without their credentials: relative URLs outside CSS, path-relative CSS URLs, root-relative CSS URLs that go past a budget or come before this process saw their window's page URL (after a restart or an eviction), and remote URLs in attributes that show no image. Those attributes are `href` and `src` of links, frames, scripts and other elements, `action`, `formaction`, `data`, `background`, `cite`, `longdesc`, `manifest`, `codebase`, `icon`, `imagesrcset` and the URL lists of `ping` and `attributionsrc`, and the `data-` attributes that lazy loaders use, such as `data-src` and `data-srcset`. So do `url()`s in CSS properties that show no image, such as `filter`, in SVG presentation attributes such as `fill`, `stroke`, `filter`, `clip-path`, `mask` and `marker-end`, and in `@import`. A URL with no credential there keeps every byte. On a page of its scheme a browser reads `https:a/b`, with no two slashes after the scheme, as a path on the page's host, so the recorder looks for a credential in both readings, and a URL whose credential is in what the URL parser alone reads as its host becomes its decline marker. The candidates of an `image-set()` that does not parse stay as they arrived.
@@ -498,7 +498,7 @@ The recorder streams each block into the encoder. Read a block as a stream: a Br
- v4 stores pages unscrubbed, so the recorder removes credentials only from URLs where a page can load them: URL attributes and CSS. A copy of a URL elsewhere, such as in `alt` or `title` text, a text node, a CSS selector, a custom event, a console log or a network body, keeps its text.
- The recorder reads object keys as the player does: it writes an escaped key, such as `"\u0073rc"`, in its plain form before it inspects the event, and it takes the last copy of a repeated key.
- The inspector records where each image slot, srcset and CSS string is, and the writer copies each event once and writes each reference, marker or URL without its credentials there. So a block has no limit on its URLs, and the writer finds no URL by its text. A URL of any length is named; one longer than the fetcher takes, 2,048 characters, becomes `imageurl:v4:declined:too_long`.
-- A block that the recorder cannot read in full is dropped, because a URL in the part it did not read went unchecked: CSS that nests rules or functions 75 deep (`too_many_nested_blocks`), compressed JSON that nests more than 1,024 deep, which the message read cannot see (`too_deep_json`), a mutation with more than 200,000 attribute changes (`too_many_attribute_items`), an event whose compressed strings did not decode or that a decode budget skipped (`undecoded_events`), a block whose edits do not fit in the flush's 256 MiB edit budget (`too_many_edits`), and a slot that the writer could not find again (`unplaced_slot`). The recorder counts these as `dropped_blocks_total{outcome}`.
+- A block that the recorder cannot read in full is stored, and its index row names the reason in `unread_reason`, because a URL in the part it did not read went unchecked and can stay as it arrived, with its credentials: CSS that nests rules or functions 75 deep (`too_many_nested_blocks`), compressed JSON that nests more than 1,024 deep, which the message read cannot see (`too_deep_json`), a mutation with more than 200,000 attribute changes (`too_many_attribute_items`), an event whose compressed strings did not decode or that a decode budget skipped (`undecoded_events`), a block whose edits do not fit in the flush's 256 MiB edit budget (`too_many_edits`), and a slot that the writer could not find again (`unplaced_slot`). The other URLs of such a block keep their references. A block past the edit budget is the exception: it keeps no edits, so all its URLs stay as they arrived, and it gets no fetch jobs, because no reference would name the files. The recorder counts these as `unread_blocks_total{outcome}`. A block is dropped only when sealing it panics, which `dropped_blocks_total{outcome}` counts.
- `hash` is the first 22 characters of the base64url HMAC-SHA256, as in v3.
### Layout
@@ -573,19 +573,19 @@ A block's `active_ms` can include time before its first event when the block con
This holds for the blocks that one recorder process inspected. After a rebalance or a restart, up to 5 seconds of a segment that spans the handover is lost. When two processes record overlapping parts of one session, the overlap can count twice.
`fold_session` in `replay-core-v4` implements this fold.
-| Group | Columns |
-| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Location | `team_id`, `session_id`, `key_month`, `block_s3_key`, `block_byte_start`, `block_byte_end` |
-| Kafka | `topic`, `partition`, `start_offset` (the flush's first offset on the partition), `end_offset` (the block's last offset), `flush_end_offset` (the last offset the flush covers), `flush_id`, `flushed_at_ms`, `flush_row_count`, `flush_row_index` |
-| Time | `first_ts_ms`, `last_ts_ms`, `event_count`, `byte_size`, `written_jsonl_bytes`, `max_written_event_bytes` |
-| Source | `snapshot_source`, `snapshot_library`, `host` |
-| Playability | `full_snapshots`, `events_before_first_full_snapshot`, `orphan_mutations`, `max_gap_ms`, `dom_nodes`, `dom_text_chars`, `remote_stylesheets`, `inline_stylesheets`, `iframes`, `canvases`, `videos`, `shadow_roots`, `cold_start`, `node_cap_reached`, `decode_failures`, `window_ids` |
-| Activity | `active_ms`, `clicks`, `mouse_interactions`, `rage_clicks`, `dead_clicks`, `keypresses`, `scrolls`, `mouse_moves`, `touches`, `touch_moves`, `selections`, `media_events`, `viewport_resizes`, `navigations`, `console_errors`, `console_warnings`, `network_requests`, `network_failures` |
-| Context | `viewport_width`, `viewport_height`, `viewport_ts_ms` (the time of the viewport event), `touch_input` |
-| Images | `images_extracted`, `image_bytes`, `images_inline`, `image_urls` |
-| Moments | `moments`: a list of `{kind, window_id, ts_ms, event_index}` for full snapshots, navigations, clicks and large DOM changes, and `moments_truncated` |
-| Sealed | `urls`: the visited URLs as a sealed index value, `urls_truncated`, and `url_fingerprints` |
-| Surfacing | The `surfacing_` columns: what ingestion's surfacing feature recorder records for the block as one batch. See [Surfacing features](#surfacing-features) |
+| Group | Columns |
+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Location | `team_id`, `session_id`, `key_month`, `block_s3_key`, `block_byte_start`, `block_byte_end` |
+| Kafka | `topic`, `partition`, `start_offset` (the flush's first offset on the partition), `end_offset` (the block's last offset), `flush_end_offset` (the last offset the flush covers), `flush_id`, `flushed_at_ms`, `flush_row_count`, `flush_row_index` |
+| Time | `first_ts_ms`, `last_ts_ms`, `event_count`, `byte_size`, `written_jsonl_bytes`, `max_written_event_bytes` |
+| Source | `snapshot_source`, `snapshot_library`, `host` |
+| Playability | `full_snapshots`, `events_before_first_full_snapshot`, `orphan_mutations`, `max_gap_ms`, `dom_nodes`, `dom_text_chars`, `remote_stylesheets`, `inline_stylesheets`, `iframes`, `canvases`, `videos`, `shadow_roots`, `cold_start`, `node_cap_reached`, `decode_failures`, `unread_reason`, `window_ids` |
+| Activity | `active_ms`, `clicks`, `mouse_interactions`, `rage_clicks`, `dead_clicks`, `keypresses`, `scrolls`, `mouse_moves`, `touches`, `touch_moves`, `selections`, `media_events`, `viewport_resizes`, `navigations`, `console_errors`, `console_warnings`, `network_requests`, `network_failures` |
+| Context | `viewport_width`, `viewport_height`, `viewport_ts_ms` (the time of the viewport event), `touch_input` |
+| Images | `images_extracted`, `image_bytes`, `images_inline`, `image_urls` |
+| Moments | `moments`: a list of `{kind, window_id, ts_ms, event_index}` for full snapshots, navigations, clicks and large DOM changes, and `moments_truncated` |
+| Sealed | `urls`: the visited URLs as a sealed index value, `urls_truncated`, and `url_fingerprints` |
+| Surfacing | The `surfacing_` columns: what ingestion's surfacing feature recorder records for the block as one batch. See [Surfacing features](#surfacing-features) |
- `full_snapshots` counts only snapshots that decoded.
- `events_before_first_full_snapshot` counts the session's events before its first decoded full snapshot.
@@ -596,6 +596,7 @@ This holds for the blocks that one recorder process inspected. After a rebalance
- `byte_size` counts the event bytes as they arrived. `written_jsonl_bytes` counts the block's lines as the recorder wrote them, after it expanded compressed values and removed images, and before Brotli. `max_written_event_bytes` is the longest of those lines. Use these two for memory and size limits.
- `mouse_interactions` counts every mouse interaction event, of every type. `clicks` counts only clicks. `touch_moves` counts touch move events; `touches` also counts touch starts and ends.
- `decode_failures` counts, once per event, a compressed value that did not decompress or that the decode budget skipped, a full snapshot the recorder could not decode or walk, a mutation that did not decode or held a node too deep to walk, and a style sheet rule whose compressed value failed. A message that did not read at all reaches no block, so this column does not count it. A block with failures has activity and DOM columns that can be too low.
+- `unread_reason` names why the recorder could not read a block in full, and is null otherwise. A session row keeps the reason of its first such block. A reader must not treat the URLs of such a block as checked.
- `moments` are hints for where to look, not checked baselines. A `full_snapshot` moment means the recorder decoded that snapshot. `full_snapshot_undecoded` marks an event tagged as a full snapshot that it did not decode. The list keeps the first 256 moments, and `moments_truncated` is true when it dropped more.
- `window_ids` lists the distinct window IDs of the block's events, the same IDs as in `moments`.
- `urls` holds at most 100 page URLs of up to 2 KiB each and 32 KiB in all. `urls_truncated` is true when the recorder left pages out.
diff --git a/rust/ai-research/replay-core-v4/src/inspect/dom.rs b/rust/ai-research/replay-core-v4/src/inspect/dom.rs
index 0b5a5151c5fa..98bd8e57bbfc 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/dom.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/dom.rs
@@ -190,7 +190,7 @@ struct WindowDom {
page_base: Option<Arc<Url>>,
}
-/// Why the inspector could not read a block in full. A URL in the part it did not read went unchecked, so the writer drops the block.
+/// Why the inspector could not read a block in full. A URL in the part it did not read went unchecked, and the block's index row names this reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UrlLimit {
AttributeItems,
@@ -200,7 +200,7 @@ pub enum UrlLimit {
}
impl UrlLimit {
- /// The outcome of the dropped block in the recorder's metrics.
+ /// Why the block has no full read, in the recorder's metrics and the block's index row.
pub fn label(self) -> &'static str {
match self {
UrlLimit::AttributeItems => "too_many_attribute_items",
@@ -308,9 +308,9 @@ impl Urls {
}
}
- /// A block past any limit is dropped, so it takes no more of the budget and builds no more edits.
+ /// A block past the edit budget keeps no edits, so it takes no more of the budget and builds no more edits.
fn take_edit_bytes(&mut self, budget: Option<&AtomicUsize>, bytes: usize) -> bool {
- if self.limit.is_some() {
+ if self.limit == Some(UrlLimit::Edits) {
return false;
}
let within_budget = budget.is_none_or(|budget| {
diff --git a/rust/ai-research/replay-core-v4/src/inspect/session.rs b/rust/ai-research/replay-core-v4/src/inspect/session.rs
index 23bd4ba3195e..2be2dbc32110 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/session.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/session.rs
@@ -71,11 +71,11 @@ pub struct Inspected {
/// Remote image URLs the block's DOM referenced, for the image fetcher.
pub image_urls: Vec<String>,
pub font_urls: Vec<String>,
- /// Set when the inspector could not read the block in full, so that the block must not be stored.
+ /// Set when the inspector could not read the block in full, so that a URL in the unread part stays as it arrived.
pub url_limit: Option<UrlLimit>,
/// Where the writer changes the block's events, in event order.
pub edits: Vec<EventEdits>,
- /// The inspector read a slot that the writer could not find again, so the block must not be stored.
+ /// The inspector read a slot that the writer could not find again, so that slot stays as it arrived.
pub unplaced: bool,
}
@@ -210,15 +210,20 @@ impl SessionInspector {
);
block.image_urls.extend(self.dom.take_image_urls());
block.font_urls.extend(self.dom.take_font_urls());
- block.url_limit = block.url_limit.or(self.dom.take_url_limit());
+ // The edit budget outranks a limit from earlier in the block, because only this limit leaves the block no edits.
+ let limit = self.dom.take_url_limit();
+ block.url_limit = if limit == Some(UrlLimit::Edits) {
+ limit
+ } else {
+ block.url_limit.or(limit)
+ };
let (edits, unplaced, edit_bytes) = self.dom.take_edits();
block.edit_bytes_taken += edit_bytes;
block.unplaced |= unplaced;
- if block.url_limit.is_none() && !edits.is_empty() {
- block.edits.push(EventEdits::new(index, edits));
- }
- if block.url_limit.is_some() {
+ if block.url_limit == Some(UrlLimit::Edits) {
block.release_edits();
+ } else if !edits.is_empty() {
+ block.edits.push(EventEdits::new(index, edits));
}
if observed.full_snapshot {
self.cold = false;
@@ -411,7 +416,7 @@ mod tests {
}
#[test]
- fn drops_a_block_whose_edits_the_flush_cannot_hold() {
+ fn clears_the_edits_of_a_block_the_flush_cannot_hold() {
let styled = |sheet: String| {
message(
json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": [
@@ -445,8 +450,23 @@ mod tests {
(blocks[1].url_limit, blocks[1].edits.len()),
(Some(UrlLimit::Edits), 0)
);
- // The dropped block stopped part way through its style sheet and gave back what it took.
+ // The second block stopped part way through its style sheet and gave back what it took.
assert_eq!(edit_budget.load(Ordering::Relaxed), held / 2);
+ // The edit budget replaces a limit that an earlier message of the block set.
+ let deep = styled(format!(
+ "{}.a{{color:red}}{}",
+ "@media all{".repeat(80),
+ "}".repeat(80)
+ ));
+ let mut block = BlockInspection::with_flush_budgets(
+ Arc::new(AtomicUsize::new(usize::MAX)),
+ Arc::new(AtomicUsize::new(0)),
+ );
+ let mut session = SessionInspector::default();
+ session.observe_message(&mut block, &deep);
+ assert_eq!(block.url_limit, Some(UrlLimit::NestedBlocks));
+ session.observe_message(&mut block, &remote);
+ assert_eq!(block.finish().url_limit, Some(UrlLimit::Edits));
// The writer leaves relative URLs as they are, so a sheet of them takes nothing.
let relative = styled(
(0..100)
diff --git a/rust/ai-research/replay-core-v4/src/inspect/stats.rs b/rust/ai-research/replay-core-v4/src/inspect/stats.rs
index f9d626aabb30..c8f43231f4a5 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/stats.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/stats.rs
@@ -28,6 +28,9 @@ pub struct BlockStats {
/// left as it arrived, and a full snapshot or mutation that inspection could not decode or walk. Each event counts
/// once. A message that does not read at all is skipped before it reaches a block, so it does not count here.
pub decode_failures: u32,
+ /// Why the recorder could not read the block in full, so a URL in the part it did not read went unchecked and stays
+ /// in the stored block. A session row keeps the reason of its first such block.
+ pub unread_reason: Option<String>,
/// The largest time between two events. When blocks overlap in time, [`BlockStats::merge`] cannot see how their
/// events interleave, so the folded value is an upper bound.
pub max_gap_ms: i64,
@@ -104,7 +107,7 @@ impl BlockStats {
self.viewport_height = height.or(self.viewport_height);
}
- /// Folds the next block in time into this one: sums, minimum and maximum times, the first host, the latest
+ /// Folds the next block in time into this one: sums, minimum and maximum times, the first host and unread reason, the latest
/// viewport and the pages in the order the session first saw them.
/// The blocks must come in [`fold_session`] order.
pub fn merge(&mut self, later: &BlockStats) {
@@ -114,6 +117,10 @@ impl BlockStats {
self.first_ts_ms = min_option(self.first_ts_ms, later.first_ts_ms);
self.last_ts_ms = self.last_ts_ms.max(later.last_ts_ms);
self.host = self.host.take().or_else(|| later.host.clone());
+ self.unread_reason = self
+ .unread_reason
+ .take()
+ .or_else(|| later.unread_reason.clone());
self.max_gap_ms = self.max_gap_ms.max(later.max_gap_ms);
self.dom_nodes = self.dom_nodes.max(later.dom_nodes);
self.dom_text_chars = self.dom_text_chars.max(later.dom_text_chars);
@@ -231,6 +238,7 @@ mod tests {
viewport_ts_ms: Some(first),
decode_failures: 1,
moments_truncated: first == 3_000,
+ unread_reason: (first >= 3_000).then(|| format!("reason at {first}")),
mouse_interactions: 2,
touch_moves: 3,
url_fingerprints: pages.collect(),
@@ -261,6 +269,7 @@ mod tests {
}
assert_eq!(session.max_gap_ms, 60_000);
assert_eq!(session.host.as_deref(), Some("first.example.com"));
+ assert_eq!(session.unread_reason.as_deref(), Some("reason at 3000"));
assert_eq!(session.viewport_width, Some(64_000));
assert_eq!(session.events_before_first_full_snapshot, 6);
assert_eq!(
diff --git a/rust/ai-research/replay-recorder-v4/src/batch.rs b/rust/ai-research/replay-recorder-v4/src/batch.rs
index 7b5270d13a43..5966a68354e0 100644
--- a/rust/ai-research/replay-recorder-v4/src/batch.rs
+++ b/rust/ai-research/replay-recorder-v4/src/batch.rs
@@ -98,7 +98,7 @@ pub struct Block {
/// Remote image URLs the block's DOM referenced.
pub image_urls: Vec<String>,
pub font_urls: Vec<String>,
- /// Set when the inspector could not read the block in full, so that the block must not be stored.
+ /// Set when the inspector could not read the block in full, so that a URL in the unread part stays as it arrived.
pub url_limit: Option<UrlLimit>,
pub edits: Vec<EventEdits>,
pub unplaced: bool,
@@ -127,7 +127,7 @@ const FLUSH_EVENTS_BUDGET: usize = 1024 * 1024 * 1024;
const FLUSH_RESOLVED_BUDGET: usize = 64 * 1024 * 1024;
/// The memory the blocks of one flush hold for their edits until they are written. A short repeated `url()` in a
-/// compressed style sheet takes more memory as an edit than it expands to, so a block past this is dropped.
+/// compressed style sheet takes more memory as an edit than it expands to, so a block past this keeps no edits.
const FLUSH_EDIT_BUDGET: usize = 256 * 1024 * 1024;
struct DecodeBudget {
diff --git a/rust/ai-research/replay-recorder-v4/src/flush.rs b/rust/ai-research/replay-recorder-v4/src/flush.rs
index 991aeba15af8..a65b1b123783 100644
--- a/rust/ai-research/replay-recorder-v4/src/flush.rs
+++ b/rust/ai-research/replay-recorder-v4/src/flush.rs
@@ -15,6 +15,7 @@ use metrics::counter;
use rdkafka::message::{Header, OwnedHeaders};
use rdkafka::producer::{FutureProducer, FutureRecord, Producer};
use rdkafka::util::Timeout;
+use replay_core_v4::inspect::dom::UrlLimit;
use replay_core_v4::inspect::stats::BlockStats;
use replay_core_v4::keys::batch::{FlushKeys, KeyStore, SessionId};
use replay_core_v4::keys::kms::AwsKms;
@@ -231,16 +232,6 @@ pub async fn write_flush(
Err(error) => return Err(error.into()),
}
}
- // Fail closed: a block that still holds a declined URL, a credential or a private host, is not stored.
- done.retain(|(index, block)| {
- let Some(outcome) = block.counts.dropped else {
- return true;
- };
- let session = &blocks[*index].session;
- tracing::warn!(team_id = session.team_id, session_id = %session.session_id, outcome, "a block is not stored");
- counter!("ai_research_v4_recorder_dropped_blocks_total", "outcome" => outcome).increment(1);
- false
- });
let (indices, mut sealed): (Vec<usize>, Vec<_>) = done.into_iter().unzip();
// This attempt's own copy: a retry fills the writer's columns again from zero.
@@ -254,12 +245,21 @@ pub async fn write_flush(
stats[index].url_fingerprints = std::mem::take(&mut block.url_fingerprints);
stats[index].surfacing.visited_url_fingerprints =
std::mem::take(&mut block.visited_url_fingerprints);
+ // A reader must see the reason: the block can hold a declined URL, a credential or a private host.
+ if let Some(outcome) = block.counts.unread {
+ let session = &blocks[index].session;
+ tracing::warn!(team_id = session.team_id, session_id = %session.session_id, outcome, "a block is stored without a full read");
+ counter!("ai_research_v4_recorder_unread_blocks_total", "outcome" => outcome)
+ .increment(1);
+ stats[index].unread_reason = Some(outcome.to_owned());
+ }
}
// Before the index is written: building the jobs counts each block's image URLs into its stats. A dropped block's
- // images are not stored, so the fetcher does not fetch them.
+ // images are not stored, and a block past the edit budget holds no reference to its images, so the fetcher does not
+ // fetch them.
let mut kept = vec![false; blocks.len()];
for &index in &indices {
- kept[index] = true;
+ kept[index] = blocks[index].url_limit != Some(UrlLimit::Edits);
}
let jobs = fetch_jobs(
&urls,
diff --git a/rust/ai-research/replay-recorder-v4/src/index.rs b/rust/ai-research/replay-recorder-v4/src/index.rs
index 96d806a55a34..4b7bae432dae 100644
--- a/rust/ai-research/replay-recorder-v4/src/index.rs
+++ b/rust/ai-research/replay-recorder-v4/src/index.rs
@@ -102,6 +102,7 @@ fn serialize_stats<S: Serializer>(stats: &&BlockStats, serializer: S) -> Result<
written_jsonl_bytes,
max_written_event_bytes,
decode_failures,
+ unread_reason,
moments_truncated,
mouse_interactions,
touch_moves,
@@ -164,6 +165,7 @@ fn serialize_stats<S: Serializer>(stats: &&BlockStats, serializer: S) -> Result<
image_urls
);
map.serialize_entry("host", host)?;
+ map.serialize_entry("unread_reason", unread_reason)?;
serialize_surfacing(&mut map, surfacing)?;
map.end()
}
@@ -575,6 +577,7 @@ mod tests {
("surfacing_visited_url_fingerprints", "LIST<UTF8>", true),
("surfacing_click_target_ids", "LIST<INT64>", true),
("surfacing_form_field_ids", "LIST<INT64>", true),
+ ("unread_reason", "UTF8", true),
];
const IMAGE_COLUMNS: &[(&str, &str, bool)] = &[
diff --git a/rust/ai-research/replay-recorder-v4/src/write.rs b/rust/ai-research/replay-recorder-v4/src/write.rs
index 53d2cb4aa573..62c469460c26 100644
--- a/rust/ai-research/replay-recorder-v4/src/write.rs
+++ b/rust/ai-research/replay-recorder-v4/src/write.rs
@@ -65,8 +65,8 @@ pub struct WriterCounts {
/// The bytes of the lines the writer gives the encoder, and the longest line.
pub jsonl_bytes: u64,
pub max_line_bytes: u64,
- /// Why the block must not be stored, as the outcome of its drop: the inspector could not read some of it.
- pub dropped: Option<&'static str>,
+ /// Why the inspector could not read some of the block, so a URL there can stay as it arrived.
+ pub unread: Option<&'static str>,
}
/// A block compressed once for all the attempts of its flush, with the images it moved out.
@@ -180,7 +180,7 @@ fn prepare_block(
Ok((images, counts))
}
-/// Why a block must not be stored: the inspector could not read some of it, so a URL there went unchecked.
+/// Why the inspector could not read some of a block, so a URL there went unchecked.
fn unread(block: &Block) -> Option<&'static str> {
if block.unplaced {
return Some("unplaced_slot");
@@ -202,26 +202,15 @@ fn unread(block: &Block) -> Option<&'static str> {
undecoded.then_some("undecoded_events")
}
-/// Writes a block's lines to an output from `open`, or drops a block that the inspector could not read in full.
-/// A dropped block gets a new output, so that none of its lines are stored.
pub fn write_block<W: Write>(
block: &Block,
team_key: &[u8; 32],
key_month: &str,
- mut open: impl FnMut() -> io::Result<W>,
+ open: impl FnOnce() -> io::Result<W>,
) -> io::Result<(W, Vec<Image>, WriterCounts)> {
- if let Some(reason) = unread(block) {
- let counts = WriterCounts {
- dropped: Some(reason),
- ..WriterCounts::default()
- };
- return Ok((open()?, Vec::new(), counts));
- }
let mut out = open()?;
- let (images, counts) = prepare_block(block, team_key, key_month, &mut out)?;
- if counts.dropped.is_some() {
- return Ok((open()?, images, counts));
- }
+ let (images, mut counts) = prepare_block(block, team_key, key_month, &mut out)?;
+ counts.unread = unread(block);
Ok((out, images, counts))
}
@@ -776,7 +765,7 @@ mod tests {
fn stored(inspected: Block) -> String {
let (lines, counts) = written(inspected);
- if counts.dropped.is_some() {
+ if counts.unread.is_some() {
return String::new();
}
lines
@@ -1080,7 +1069,7 @@ mod tests {
}
#[test]
- fn drops_a_block_the_inspector_could_not_read_in_full() {
+ fn stores_a_block_the_inspector_could_not_read_in_full_and_names_why() {
let deep_face = format!(
"{}@font-face{{font-family:Deep;src:url(\"https://fonts.example.com/deep.woff2?token=secret\")}}{}",
"@media all{".repeat(80),
@@ -1095,9 +1084,14 @@ mod tests {
json!({"type": 2, "tagName": "style", "attributes": {"_cssText": deep_face}, "childNodes": [], "id": 2}),
json!({"type": 2, "tagName": "div", "attributes": {"style": deep_value}, "childNodes": [], "id": 2}),
] {
- let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": [node]}}}]).to_string();
- let (_, counts) = written(block_of("kept", &events));
- assert_eq!(counts.dropped, Some("too_many_nested_blocks"));
+ let image = |id: i64| json!({"type": 2, "tagName": "img", "attributes": {"src": format!("https://cdn.example.com/read{id}.png")}, "childNodes": [], "id": id});
+ let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": [image(3), node, image(4)]}}}]).to_string();
+ let (lines, counts) = written(block_of("kept", &events));
+ assert_eq!(counts.unread, Some("too_many_nested_blocks"));
+ assert!(lines.contains("example.com/deep."), "{lines:.80}");
+ // A URL the inspector did read still gets its reference.
+ assert!(!lines.contains("/read"), "{lines:.80}");
+ assert_eq!(lines.matches("imageurl:v4:7:").count(), 2);
}
// posthog-js compresses these, so the message read does not see how deep they nest.
let cv = |value: Value| -> String {
@@ -1118,7 +1112,7 @@ mod tests {
json!({"type": 3, "timestamp": 1, "cv": "2024-10", "data": {"source": 8, "id": 3, "adds": cv(json!([{"rule": ".a{background:url(https://cdn.example.com/a.png?token=secret)}", "index": deep_index}]))}}),
] {
let (_, counts) = written(block_of("kept", &json!([event]).to_string()));
- assert_eq!(counts.dropped, Some("too_deep_json"), "{event:.80}");
+ assert_eq!(counts.unread, Some("too_deep_json"), "{event:.80}");
}
// cssparser reads a NUL in a string as U+FFFD, so the decoded URL is not in its token, only in the comment.
let nul_url = "url(\"https://cdn.example.com/a.png?X-Amz-Signature=abc123#\u{0}\"/*https://cdn.example.com/a.png?X-Amz-Signature=abc123#\u{FFFD}*/)";
@@ -1137,15 +1131,16 @@ mod tests {
let node = json!({"type": 2, "tagName": "div", "attributes": {"style": style}, "childNodes": [], "id": 2});
let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": [node]}}}]).to_string();
let (_, counts) = written(block_of("kept", &events));
- assert_eq!(counts.dropped, Some("unplaced_slot"), "{style}");
+ assert_eq!(counts.unread, Some("unplaced_slot"), "{style}");
}
- // The block would store an event that the flush did not decode as it arrived, with its URLs unread.
+ // The block stores an event that the flush did not decode as it arrived, with its URLs unread.
let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": []}}}]).to_string();
for expansion in [Expansion::Skipped, Expansion::Failed] {
let mut block = block_of("kept", &events);
block.messages[0].events[0].expansion = Some(expansion);
- let (_, counts) = written(block);
- assert_eq!(counts.dropped, Some("undecoded_events"));
+ let (lines, counts) = written(block);
+ assert_eq!(counts.unread, Some("undecoded_events"));
+ assert_eq!(lines.lines().count(), 1);
}
}
diff --git a/rust/ai-research/replay-recorder-v4/tests/pbt_escapes.rs b/rust/ai-research/replay-recorder-v4/tests/pbt_escapes.rs
index 4b48e18003c3..8bbe0e2e4677 100644
--- a/rust/ai-research/replay-recorder-v4/tests/pbt_escapes.rs
+++ b/rust/ai-research/replay-recorder-v4/tests/pbt_escapes.rs
@@ -135,7 +135,7 @@ impl Slot {
}
/// A set keeps its candidate as the page wrote it, so it cannot keep an escaped one, or one that another image function holds.
- fn drops_its_block(self, written: &str) -> bool {
+ fn leaves_its_block_unread(self, written: &str) -> bool {
match self {
Slot::ImageSet => written.contains('\\'),
Slot::CrossFade { in_image_set } => in_image_set,
@@ -623,11 +623,11 @@ fn events(tc: &TestCase, placed: &[Placed], shape: Shape) -> String {
with_json_escapes(tc, &Value::Array(events).to_string())
}
-fn drop_reasons(placed: &[Placed], shape: Shape) -> Vec<&'static str> {
+fn unread_reasons(placed: &[Placed], shape: Shape) -> Vec<&'static str> {
let mut reasons = Vec::new();
if placed
.iter()
- .any(|placed| placed.slot.drops_its_block(&placed.written))
+ .any(|placed| placed.slot.leaves_its_block_unread(&placed.written))
{
reasons.push("unplaced_slot");
}
@@ -678,7 +678,7 @@ fn block_of(events: &str) -> Option<Block> {
})
}
-/// The stored lines, or why the block is not stored. The recorder skips a message it cannot read.
+/// The stored lines, or why the block has no guarantee about its URLs. The recorder skips a message it cannot read.
fn stored(tc: &TestCase, events: &str) -> Result<String, &'static str> {
let Some(block) = block_of(events) else {
tc.event("unreadable_message");
@@ -686,8 +686,8 @@ fn stored(tc: &TestCase, events: &str) -> Result<String, &'static str> {
};
let (lines, _, counts): (Vec<u8>, _, WriterCounts) =
write_block(&block, &TEAM_KEY, KEY_MONTH, || Ok(Vec::new())).unwrap();
- tc.event(counts.dropped.unwrap_or("stored"));
- match counts.dropped {
+ tc.event(counts.unread.unwrap_or("stored"));
+ match counts.unread {
Some(reason) => Err(reason),
None => Ok(String::from_utf8(lines).unwrap()),
}
@@ -822,11 +822,11 @@ fn a_stored_block_holds_no_accepted_url_in_an_image_slot(tc: TestCase) {
#[hegel::test]
#[ignore = "a search for bugs, run on demand"]
-fn drops_a_block_only_for_a_reason_the_page_holds(tc: TestCase) {
+fn leaves_a_block_unread_only_for_a_reason_the_page_holds(tc: TestCase) {
let page = draw_page(&tc);
if let Err(reason) = stored(&tc, &page.events) {
assert!(
- drop_reasons(&page.placed, page.shape).contains(&reason),
+ unread_reasons(&page.placed, page.shape).contains(&reason),
"{reason}: {}",
page.events
);
@@ -844,7 +844,7 @@ fn each_spelling_of_a_url_gets_the_reference_its_fetch_job_names(tc: TestCase) {
let slots: Vec<Slot> = SLOTS
.iter()
.copied()
- .filter(|slot| !slot.drops_its_block("") && slot.names_an_accepted_url(shape))
+ .filter(|slot| !slot.leaves_its_block_unread("") && slot.names_an_accepted_url(shape))
.collect();
let count = tc.draw(gs::integers::<usize>().min_value(2).max_value(4));
let placed: Vec<Placed> = (0..count)