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): keep blocks the url checks cannot fully verify (#124955)

Nicholas Waltz26332751556e
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index dc2650abb37c..59464e038376 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -470,9 +470,9 @@ The recorder streams each block into the encoder. Read a block as a stream: a Br
- The recorder reads a protocol-relative URL, such as `//cdn.example.com/a.png`, as `https`. It gets the same reference or `declined` marker 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.
- Some URLs stay as they arrived: relative URLs, remote URLs outside image slots (links, frames, text, CSS custom properties and other CSS properties), the `image-set()` candidates the recorder does not choose, URLs inside a compressed value that did not decode or that the decode budget skipped, and URL text written in another form than the recorder read it, for example with a CSS escape. The recorder counts the last kind as `outcome="unrewritten"`.
- Before the rewrite, the recorder writes again any JSON string that holds an escape capture would not write, for example `\/`, so an escaped URL is found too. A scheme matches in any letter case.
-- If a refused URL is still in a block after the rewrite, the recorder drops the block and counts it as `dropped_blocks_total{outcome="declined_unrewritten"}`, so no refused URL is stored.
+- If a refused URL is still in a block after the rewrite, the recorder writes the block again instead of dropping it. The second pass replaces the refused URL wherever its bytes are, also inside a longer URL. For a refused URL the stored bytes do not hold as the recorder read it, for example behind a CSS escape, it replaces every URL token that holds the URL's host with `imageurl:v4:declined:unchecked`. The recorder counts this as `url_fallbacks_total{reason="declined_kept"|"declined_unfound"}`. It drops the block, as `dropped_blocks_total{outcome="declined_unrewritten"}`, only when the second pass still leaves a refused URL, so no refused URL is stored.
- 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 recorder drops a block that it cannot check in full, and counts the reason in `dropped_blocks_total`: an image-slot URL longer than 8 KiB (`url_too_long`), more than 10,000 image-slot URLs (`too_many_urls`) or more than 2 MiB of them (`too_many_url_bytes`), or a mutation with more than 200,000 attribute changes (`too_many_attribute_items`). It sends no fetch job for a dropped block.
+- A block that the recorder cannot check in full is kept. Past 10,000 image-slot URLs (`too_many_urls`), 2 MiB of them (`too_many_url_bytes`) or 200,000 attribute changes in a mutation (`too_many_attribute_items`), the recorder names the URLs it read, and replaces every other remote URL token in the block, links and text included, with `imageurl:v4:declined:unchecked`. A replaced token runs to whitespace or the end of its JSON string, and to the `)`, `'` or `"` that ends a CSS URL, so the scrub never splits an escape. It counts these as `url_fallbacks_total{reason}` and the replaced tokens as `scrubbed_urls_total`. A URL of any length is named; one longer than the fetcher takes becomes `imageurl:v4:declined:too_long`. Only a block whose sealing fails is dropped.
- When the text of a rewritten URL also appears outside an image slot in the same block, it is replaced there too.
- `hash` is the first 22 characters of the base64url HMAC-SHA256, as in v3.
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 44d919155b8c..91cadf985c69 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/dom.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/dom.rs
@@ -25,8 +25,6 @@ pub const MAX_IMAGE_URLS: usize = 512;
/// Attribute changes read per mutation, as many as the nodes tracked. A mutation with more drops its block, because
/// the inspector does not name the URLs in the rest.
pub const MAX_ATTRIBUTE_ITEMS: usize = MAX_TRACKED_NODES;
-/// The longest remote URL a block may hold in an image slot: four times the longest the fetcher takes.
-pub const MAX_REMOTE_URL_BYTES: usize = 8 * 1024;
/// The distinct remote URLs in a block's image slots, and their bytes. The writer builds one matcher over them, and
/// the build takes memory in proportion to their bytes.
pub const MAX_BLOCK_REMOTE_URLS: usize = 10_000;
@@ -179,10 +177,9 @@ struct WindowDom {
}
/// Why the inspector stopped naming a block's remote image URLs. The writer replaces only the URLs it is given, so it
-/// drops the block.
+/// scrubs every other remote URL token in the block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UrlLimit {
- UrlLength,
UrlCount,
UrlBytes,
AttributeItems,
@@ -192,7 +189,6 @@ impl UrlLimit {
/// The outcome of the dropped block in the recorder's metrics.
pub fn label(self) -> &'static str {
match self {
- UrlLimit::UrlLength => "url_too_long",
UrlLimit::UrlCount => "too_many_urls",
UrlLimit::UrlBytes => "too_many_url_bytes",
UrlLimit::AttributeItems => "too_many_attribute_items",
@@ -200,7 +196,7 @@ impl UrlLimit {
}
}
-/// Distinct remote image URLs within [`MAX_REMOTE_URL_BYTES`], [`MAX_BLOCK_REMOTE_URLS`] and
+/// Distinct remote image URLs within [`MAX_BLOCK_REMOTE_URLS`] and
/// [`MAX_BLOCK_REMOTE_URL_BYTES`]. Past a limit it keeps no more, and `limit` says why.
#[derive(Debug, Default)]
pub struct RemoteUrls {
@@ -236,9 +232,9 @@ impl RemoteUrls {
if self.limit.is_some() || self.urls.contains(url) {
return;
}
- self.limit = if url.len() > MAX_REMOTE_URL_BYTES {
- Some(UrlLimit::UrlLength)
- } else if self.urls.len() >= MAX_BLOCK_REMOTE_URLS {
+ // A URL of any length is named: the policy declines one too long to fetch, and its bytes count toward the
+ // block's budget.
+ self.limit = if self.urls.len() >= MAX_BLOCK_REMOTE_URLS {
Some(UrlLimit::UrlCount)
} else if self.bytes + url.len() > MAX_BLOCK_REMOTE_URL_BYTES {
Some(UrlLimit::UrlBytes)
@@ -266,10 +262,11 @@ impl RemoteUrls {
}
pub fn extend(&mut self, other: RemoteUrls) {
- self.limit = self.limit.or(other.limit);
+ // The URLs go in before the other's limit, so that a part that hit a limit still names what it holds.
for url in &other.urls {
self.insert(url);
}
+ self.limit = self.limit.or(other.limit);
for (raw, (text, unfetched_type)) in other.srcsets.iter().flat_map(|s| &s.values) {
self.insert_srcset(raw, text, *unfetched_type);
}
@@ -2003,11 +2000,12 @@ mod tests {
urls.for_each(|u| remote.insert(&u));
remote.limit
};
- let longest = MAX_REMOTE_URL_BYTES;
+ let longest = 8 * 1024;
let most_long = MAX_BLOCK_REMOTE_URL_BYTES / longest;
for (urls, expected) in [
(vec![url(0, longest)], None),
- (vec![url(0, longest + 1)], Some(UrlLimit::UrlLength)),
+ // A URL of any length is named, and the policy declines it.
+ (vec![url(0, longest + 1)], None),
(
(0..MAX_BLOCK_REMOTE_URLS).map(|i| url(i, 40)).collect(),
None,
diff --git a/rust/ai-research/replay-recorder-v4/src/lib.rs b/rust/ai-research/replay-recorder-v4/src/lib.rs
index ce0d17aa5ad6..d50a0f954add 100644
--- a/rust/ai-research/replay-recorder-v4/src/lib.rs
+++ b/rust/ai-research/replay-recorder-v4/src/lib.rs
@@ -9,6 +9,7 @@ pub mod index;
pub mod limits;
pub mod process;
pub mod rewrite;
+pub mod scrub;
pub mod store;
pub mod teams;
pub mod urls;
diff --git a/rust/ai-research/replay-recorder-v4/src/rewrite.rs b/rust/ai-research/replay-recorder-v4/src/rewrite.rs
index 8e16b7024479..55ad67164aeb 100644
--- a/rust/ai-research/replay-recorder-v4/src/rewrite.rs
+++ b/rust/ai-research/replay-recorder-v4/src/rewrite.rs
@@ -9,7 +9,7 @@
//! were written again, so the rebuild never depends on a prediction of those bytes.
use std::borrow::Cow;
-use std::collections::{HashMap, HashSet};
+use std::collections::{BTreeMap, HashMap, HashSet};
use aho_corasick::{AhoCorasick, AhoCorasickKind, MatchKind};
use metrics::counter;
@@ -19,6 +19,7 @@ use replay_core_v4::scan::images::{extract_images, ImageLimits, ImageSink, AVIF_
use replay_core_v4::seal::{image_content_key, image_url_key};
use replay_core_v4::url_policy::is_remote;
+use crate::scrub::{Scrub, Scrubber};
use crate::urls::url_reference;
/// The bytes with each JSON string that holds an escape `write_json_string` does not write, such as `\/` or `\u0041`,
@@ -117,6 +118,7 @@ fn ends_with_escape(bytes: &[u8], at: usize) -> bool {
const SRCSET_KEY: &[u8] = br#""srcset":"#;
struct Target {
+ url: String,
replacement: Vec<u8>,
/// The policy's reason, for a declined URL.
declined: Option<&'static str>,
@@ -141,6 +143,65 @@ pub struct UrlRewrite {
team_id: i64,
key_month: String,
url_key: [u8; 32],
+ fallback: Fallback,
+ scrubber: Scrubber,
+ scrubbed: u64,
+ /// The JSON key whose value held the first declined URL that stayed, for the log. It names the shape without any URL.
+ kept_in: Option<String>,
+ counters: PassCounters,
+}
+
+/// The counter increments of one writer pass. The writer emits them only for the pass whose output it keeps, so a block
+/// written twice counts once.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct PassCounters {
+ srcset_rewrites: BTreeMap<&'static str, u64>,
+ url_rewrites: BTreeMap<(&'static str, &'static str), u64>,
+ pub removed_avif: u64,
+}
+
+impl PassCounters {
+ pub fn emit(&self) {
+ for (&outcome, &count) in &self.srcset_rewrites {
+ counter!("ai_research_v4_recorder_srcset_rewrites_total", "outcome" => outcome)
+ .increment(count);
+ }
+ for (&(outcome, reason), &count) in &self.url_rewrites {
+ counter!(
+ "ai_research_v4_recorder_image_url_rewrites_total",
+ "outcome" => outcome,
+ "reason" => reason,
+ )
+ .increment(count);
+ }
+ counter!("ai_research_v4_recorder_removed_images_total", "format" => "avif")
+ .increment(self.removed_avif);
+ }
+}
+
+/// How the writer handles what the first pass over a block left unsafe, instead of dropping the block.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct Fallback {
+ /// Replace a declined URL wherever its bytes are, also inside a longer URL that would otherwise keep it.
+ pub overwrite_declined: bool,
+ pub scrub: Scrub,
+ /// The metric label of why the fallback runs.
+ pub reason: Option<&'static str>,
+}
+
+/// What `finish` found about a block.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct RewriteReport {
+ /// No URL the policy declines can stay in the stored bytes.
+ pub safe: bool,
+ /// A declined URL stayed, as a second copy that the rewrite passed over.
+ pub declined_kept: bool,
+ /// The hosts of declined URLs the inspector named but the stored bytes do not hold as it read them. `None` when
+ /// one of them has no host to look for.
+ pub unfound_hosts: Option<Vec<String>>,
+ pub scrubbed: u64,
+ pub kept_in: Option<String>,
+ pub counters: PassCounters,
}
impl UrlRewrite {
@@ -165,6 +226,7 @@ impl UrlRewrite {
Err(decline) => (declined_marker(decline.label()), Some(decline.label())),
};
targets.push(Target {
+ url: url.clone(),
replacement: replacement.into_bytes(),
declined,
found: false,
@@ -237,9 +299,20 @@ impl UrlRewrite {
team_id,
key_month: key_month.to_owned(),
url_key,
+ fallback: Fallback::default(),
+ scrubber: Scrubber::new(&Scrub::Nothing),
+ scrubbed: 0,
+ kept_in: None,
+ counters: PassCounters::default(),
}
}
+ pub fn with_fallback(mut self, fallback: Fallback) -> Self {
+ self.scrubber = Scrubber::new(&fallback.scrub);
+ self.fallback = fallback;
+ self
+ }
+
/// The bytes with each srcset that holds a candidate the block cannot keep rebuilt from the candidates it keeps.
fn rebuild_srcsets<'b>(&mut self, bytes: &'b [u8]) -> Cow<'b, [u8]> {
let mut out: Option<Vec<u8>> = None;
@@ -271,8 +344,7 @@ impl UrlRewrite {
for url in covers {
self.targets[url].found = true;
}
- counter!("ai_research_v4_recorder_srcset_rewrites_total", "outcome" => outcome)
- .increment(1);
+ *self.counters.srcset_rewrites.entry(outcome).or_default() += 1;
let out = out.get_or_insert_with(|| Vec::with_capacity(bytes.len()));
out.extend_from_slice(&bytes[copied_to..start]);
write_json_string(&value, out);
@@ -287,12 +359,24 @@ impl UrlRewrite {
}
}
- /// The bytes with each srcset rebuilt and each URL replaced. Returns the input when it holds none.
- pub fn apply<'b>(&mut self, bytes: &'b [u8]) -> Cow<'b, [u8]> {
- match self.rebuild_srcsets(bytes) {
- Cow::Borrowed(bytes) => self.replace_urls(bytes),
- Cow::Owned(rebuilt) => Cow::Owned(self.replace_urls(&rebuilt).into_owned()),
+ /// The bytes with each URL replaced, and in a DOM event each inspected srcset rebuilt. Returns the input when it
+ /// holds none. Only a full snapshot or a mutation holds image slots, so a srcset in any other event, such as a
+ /// custom event's payload with the same value, is left to the rewrite of each URL.
+ pub fn apply<'b>(&mut self, bytes: &'b [u8], dom_event: bool) -> Cow<'b, [u8]> {
+ let replaced = if !dom_event {
+ self.replace_urls(bytes)
+ } else {
+ match self.rebuild_srcsets(bytes) {
+ Cow::Borrowed(bytes) => self.replace_urls(bytes),
+ Cow::Owned(rebuilt) => Cow::Owned(self.replace_urls(&rebuilt).into_owned()),
+ }
+ };
+ let (scrubbed, count) = self.scrubber.apply(&replaced);
+ if count == 0 {
+ return replaced;
}
+ self.scrubbed += count;
+ Cow::Owned(scrubbed.into_owned())
}
fn replace_urls<'b>(&mut self, bytes: &'b [u8]) -> Cow<'b, [u8]> {
@@ -304,9 +388,13 @@ impl UrlRewrite {
for found in matcher.find_iter(bytes) {
let (start, end) = (found.start(), found.end());
let index = found.pattern().as_usize();
- if start.checked_sub(1).is_some_and(|before| {
- continues_url(bytes[before]) && !ends_with_escape(bytes, start)
- }) || bytes.get(end).is_some_and(|&after| continues_url(after))
+ // A declined URL inside a longer URL is replaced too when the fallback asks, so that it cannot stay.
+ let overwrite =
+ self.fallback.overwrite_declined && self.targets[index].declined.is_some();
+ if !overwrite
+ && (start.checked_sub(1).is_some_and(|before| {
+ continues_url(bytes[before]) && !ends_with_escape(bytes, start)
+ }) || bytes.get(end).is_some_and(|&after| continues_url(after)))
{
continue;
}
@@ -325,36 +413,102 @@ impl UrlRewrite {
None => Cow::Borrowed(bytes),
};
if let Some(declined) = &self.declined {
- self.declined_kept |= declined.is_match(out.as_ref());
+ if let Some(kept) = declined.find(out.as_ref()) {
+ self.declined_kept = true;
+ if self.kept_in.is_none() {
+ self.kept_in =
+ Some(enclosing_key(&out, kept.start()).unwrap_or("?").to_owned());
+ }
+ }
}
out
}
/// Counts the block's URLs. One the block does not hold as the inspector read it, for example with a CSS escape,
- /// stays as it arrived. Returns false when a URL the policy declines stays, unreplaced or as a second copy that
- /// `apply` passed over, because the block must not be stored then.
- pub fn finish(self) -> bool {
+ /// stays as it arrived. The block is unsafe when a URL the policy declines can stay, unreplaced or as a second copy
+ /// that `apply` passed over, unless the fallback scrubbed every token that could hold it.
+ pub fn finish(self) -> RewriteReport {
+ let covered = |url: &str| match &self.fallback.scrub {
+ Scrub::AllRemote => true,
+ Scrub::Hosts(hosts) => {
+ url_host(url).is_some_and(|host| hosts.binary_search(&host).is_ok())
+ }
+ Scrub::Nothing => false,
+ };
+ let mut unfound_hosts = Some(Vec::new());
let mut safe = !self.declined_kept;
+ for target in &self.targets {
+ if !target.found && target.declined.is_some() && !covered(&target.url) {
+ safe = false;
+ match (url_host(&target.url), &mut unfound_hosts) {
+ (Some(host), Some(hosts)) => hosts.push(host),
+ _ => unfound_hosts = None,
+ }
+ }
+ }
+ // Many declined URLs share a host. The second pass binary-searches this list for every target, so it is sorted.
+ if let Some(hosts) = &mut unfound_hosts {
+ hosts.sort_unstable();
+ hosts.dedup();
+ }
+ let mut counters = self.counters;
for target in self.targets {
- safe &= target.found || target.declined.is_none();
let outcome = match (target.found, target.declined) {
(false, _) => "unrewritten",
(true, None) => "rewritten",
(true, Some(_)) => "declined",
};
- counter!(
- "ai_research_v4_recorder_image_url_rewrites_total",
- "outcome" => outcome,
- "reason" => target.declined.unwrap_or("none"),
- )
- .increment(1);
+ *counters
+ .url_rewrites
+ .entry((outcome, target.declined.unwrap_or("none")))
+ .or_default() += 1;
+ }
+ RewriteReport {
+ safe,
+ declined_kept: self.declined_kept,
+ unfound_hosts,
+ scrubbed: self.scrubbed,
+ kept_in: self.kept_in,
+ counters,
}
- safe
}
}
-/// The srcset with only the candidates the block keeps, each remote URL as its reference, how it was rebuilt, and the
-/// URL targets of the remote URLs it held. `None` when every candidate stays, because the URL targets then replace it.
+/// The key of the JSON object entry whose string value holds `at`, when it is a plain short key.
+fn enclosing_key(bytes: &[u8], at: usize) -> Option<&str> {
+ let mut open = at;
+ while open > 0 {
+ open -= 1;
+ if bytes[open] == b'"' && !(open > 0 && bytes[open - 1] == b'\\') {
+ break;
+ }
+ }
+ let colon = open.checked_sub(1).filter(|&c| bytes[c] == b':')?;
+ let key_end = colon.checked_sub(1).filter(|&e| bytes[e] == b'"')?;
+ let key_start = bytes[..key_end].iter().rposition(|&b| b == b'"')? + 1;
+ let key = std::str::from_utf8(&bytes[key_start..key_end]).ok()?;
+ (key.len() <= 40
+ && key
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || b == b'-'))
+ .then_some(key)
+}
+
+/// The host of a URL the inspector named, in lowercase, protocol-relative and backslash forms included.
+fn url_host(url: &str) -> Option<String> {
+ let with_scheme;
+ let url = if replay_core_v4::url_policy::is_protocol_relative(url) {
+ with_scheme = format!("https:{}", url.trim());
+ with_scheme.as_str()
+ } else {
+ url
+ };
+ url::Url::parse(url)
+ .ok()?
+ .host_str()
+ .map(str::to_ascii_lowercase)
+}
+
/// Where the JSON string that opens at `start` ends, after its closing quote.
fn string_end(bytes: &[u8], start: usize) -> Option<usize> {
let mut position = start + 1;
@@ -368,6 +522,8 @@ fn string_end(bytes: &[u8], start: usize) -> Option<usize> {
None
}
+/// The srcset with only the candidates the block keeps, each remote URL as its reference, how it was rebuilt, and the
+/// URL targets of the remote URLs it held. `None` when every candidate stays, because the URL targets then replace it.
fn rebuilt_srcset(
text: &str,
unfetched: &HashSet<String>,
@@ -423,7 +579,7 @@ mod tests {
fn rewrite(urls: &[&str], bytes: &str) -> String {
let urls: Vec<String> = urls.iter().map(|u| (*u).to_owned()).collect();
let mut rewrite = UrlRewrite::new(&urls, &[], 7, "2026-10", &TEAM_KEY);
- String::from_utf8(rewrite.apply(bytes.as_bytes()).into_owned()).unwrap()
+ String::from_utf8(rewrite.apply(bytes.as_bytes(), true).into_owned()).unwrap()
}
fn reference(url: &str) -> String {
@@ -462,13 +618,13 @@ mod tests {
&TEAM_KEY,
);
assert_eq!(
- String::from_utf8(rewrite.apply(event.as_bytes()).into_owned()).unwrap(),
+ String::from_utf8(rewrite.apply(event.as_bytes(), true).into_owned()).unwrap(),
format!(
r#"{{"srcset":"{ra} 1x,\n{rb} 2x,\t{} 3x"}}"#,
declined_marker("non_public_host")
)
);
- assert!(rewrite.finish());
+ assert!(rewrite.finish().safe);
}
#[test]
@@ -478,13 +634,13 @@ mod tests {
let canonical = canonical_strings(hidden.as_bytes());
let mut rewrite = UrlRewrite::new(&[url.to_owned()], &[], 7, "2026-10", &TEAM_KEY);
assert_eq!(
- String::from_utf8(rewrite.apply(&canonical).into_owned()).unwrap(),
+ String::from_utf8(rewrite.apply(&canonical, true).into_owned()).unwrap(),
format!(
r#"{{"src":"{}","alt":"a\nb"}}"#,
declined_marker("credential")
)
);
- assert!(rewrite.finish());
+ assert!(rewrite.finish().safe);
// An event capture wrote is left as it is.
let plain = r#"{"text":"a\"b\\c\u0001","n":1}"#;
assert!(matches!(
@@ -493,7 +649,7 @@ mod tests {
));
// A declined URL the block still holds fails the block.
let rewrite = UrlRewrite::new(&[url.to_owned()], &[], 7, "2026-10", &TEAM_KEY);
- assert!(!rewrite.finish());
+ assert!(!rewrite.finish().safe);
}
#[test]
@@ -520,7 +676,13 @@ mod tests {
// A second copy inside a longer URL stays as it is, so the block fails.
let url = "https://bucket.s3.amazonaws.com/a.png?X-Amz-Signature=abc123";
let mut rewrite = UrlRewrite::new(&[url.to_owned()], &[], 7, "2026-10", &TEAM_KEY);
- rewrite.apply(format!(r#"{{"src":"{url}","alt":"x{url}"}}"#).as_bytes());
- assert!(!rewrite.finish());
+ rewrite.apply(
+ format!(r#"{{"src":"{url}","alt":"x{url}"}}"#).as_bytes(),
+ true,
+ );
+ let report = rewrite.finish();
+ assert!(!report.safe);
+ // The log names where the copy stayed, without the URL.
+ assert_eq!(report.kept_in.as_deref(), Some("alt"));
}
}
diff --git a/rust/ai-research/replay-recorder-v4/src/scrub.rs b/rust/ai-research/replay-recorder-v4/src/scrub.rs
new file mode 100644
index 000000000000..58b609cff08a
--- /dev/null
+++ b/rust/ai-research/replay-recorder-v4/src/scrub.rs
@@ -0,0 +1,537 @@
+//! The fallback for a block whose remote URLs the writer could not all name or replace. Each remote URL token left in
+//! the stored bytes becomes [`UNCHECKED_MARKER`], so no URL the policy would refuse is stored, and the block is kept
+//! instead of dropped.
+//!
+//! The scrub reads the bytes one character at a time through their JSON escapes and CSS escapes, so it never splits an
+//! escape and the stored JSON stays valid. A URL token ends at whitespace or at the end of its JSON string. A URL that
+//! starts after `(`, `'` or `"` also ends at `)`, `'` or `"`, because CSS ends it there. The scrub does not know which
+//! slot a token sits in, so it also replaces URLs outside image slots, such as links and text. It runs only on the few
+//! blocks that need it.
+
+use std::borrow::Cow;
+
+use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
+
+/// What a scrubbed URL token becomes.
+pub const UNCHECKED_MARKER: &str = "imageurl:v4:declined:unchecked";
+
+/// Which URL tokens the scrub replaces.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub enum Scrub {
+ #[default]
+ Nothing,
+ /// Every token that `url_policy::is_remote` reads as remote: `http:` or `https:`, or two slashes or backslashes,
+ /// in any letter case and through any escape.
+ AllRemote,
+ /// Every token that holds one of these hosts, in any letter case. The list is sorted, without duplicates.
+ Hosts(Vec<String>),
+}
+
+pub struct Scrubber {
+ all_remote: bool,
+ hosts: Option<AhoCorasick>,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Kind {
+ Plain,
+ /// An unescaped `"`, which ends the JSON string.
+ StringEnd,
+ /// A character a CSS escape names. It is part of the URL whatever it is.
+ CssEscaped,
+}
+
+/// One character of the stored bytes and the bytes that spell it.
+#[derive(Clone, Copy)]
+struct Unit {
+ ch: u32,
+ len: usize,
+ kind: Kind,
+}
+
+/// The character that ends a URL besides whitespace and the end of its JSON string.
+#[derive(Clone, Copy)]
+enum Closer {
+ None,
+ Paren,
+ Apostrophe,
+ Quote,
+}
+
+enum Start {
+ Scheme,
+ Slashes,
+}
+
+fn is_space(ch: u32) -> bool {
+ ch <= u32::from(b' ')
+}
+
+fn is_char(ch: u32, byte: u8) -> bool {
+ ch == u32::from(byte)
+}
+
+/// A character that a relative path or a word can hold, so `//` after it starts no URL.
+fn continues_word(ch: u32) -> bool {
+ u8::try_from(ch)
+ .is_ok_and(|b| b.is_ascii_alphanumeric() || b"-._~/?#@!$&*+=%:;[]\\".contains(&b))
+}
+
+/// The character at `at` after its JSON escape, and its length in bytes.
+fn json_unit(bytes: &[u8], at: usize) -> (u32, usize) {
+ let byte = bytes[at];
+ if byte != b'\\' {
+ return (u32::from(byte), 1);
+ }
+ match bytes.get(at + 1) {
+ Some(b'u') => bytes
+ .get(at + 2..at + 6)
+ .and_then(|hex| std::str::from_utf8(hex).ok())
+ .and_then(|hex| u32::from_str_radix(hex, 16).ok())
+ .map_or((u32::from(byte), 1), |code| (code, 6)),
+ Some(&escaped) => {
+ let ch = match escaped {
+ b'n' => b'\n',
+ b'r' => b'\r',
+ b't' => b'\t',
+ b'b' => 0x08,
+ b'f' => 0x0c,
+ other => other,
+ };
+ (u32::from(ch), 2)
+ }
+ None => (u32::from(byte), 1),
+ }
+}
+
+/// The character at `at` after its JSON escape and a CSS escape inside it. A CSS hex escape takes the one whitespace
+/// after it, as CSS reads it.
+fn unit(bytes: &[u8], at: usize) -> Unit {
+ let (ch, len) = json_unit(bytes, at);
+ if len == 1 && is_char(ch, b'"') {
+ return Unit {
+ ch,
+ len,
+ kind: Kind::StringEnd,
+ };
+ }
+ let plain = Unit {
+ ch,
+ len,
+ kind: Kind::Plain,
+ };
+ if len == 1 || !is_char(ch, b'\\') {
+ return plain;
+ }
+ let mut end = at + len;
+ let (mut code, mut digits) = (0u32, 0);
+ while digits < 6 && end < bytes.len() {
+ let (next, next_len) = json_unit(bytes, end);
+ let Some(digit) = char::from_u32(next).and_then(|c| c.to_digit(16)) else {
+ break;
+ };
+ code = code * 16 + digit;
+ digits += 1;
+ end += next_len;
+ }
+ if digits > 0 {
+ if end < bytes.len() {
+ let (next, next_len) = json_unit(bytes, end);
+ if is_space(next) {
+ end += next_len;
+ }
+ }
+ return Unit {
+ ch: code,
+ len: end - at,
+ kind: Kind::CssEscaped,
+ };
+ }
+ if end >= bytes.len() {
+ return plain;
+ }
+ let (next, next_len) = json_unit(bytes, end);
+ if is_space(next) || (next_len == 1 && is_char(next, b'"')) {
+ return plain;
+ }
+ Unit {
+ ch: next,
+ len: len + next_len,
+ kind: Kind::CssEscaped,
+ }
+}
+
+fn lower(ch: u32) -> u32 {
+ u8::try_from(ch).map_or(ch, |b| u32::from(b.to_ascii_lowercase()))
+}
+
+/// Whether a remote URL starts at `at`, and how.
+fn remote_start(bytes: &[u8], at: usize) -> Option<Start> {
+ let mut chars = [0u32; 6];
+ let (mut pos, mut count) = (at, 0);
+ while count < chars.len() && pos < bytes.len() {
+ let next = unit(bytes, pos);
+ if next.kind == Kind::StringEnd {
+ break;
+ }
+ chars[count] = lower(next.ch);
+ pos += next.len;
+ count += 1;
+ }
+ let slash = |ch: u32| is_char(ch, b'/') || is_char(ch, b'\\');
+ if count >= 2 && slash(chars[0]) && slash(chars[1]) {
+ return Some(Start::Slashes);
+ }
+ // Outside CSS, `\\` is two backslashes rather than one escaped backslash, and a browser reads both as slashes.
+ let (first, first_len) = json_unit(bytes, at);
+ if slash(first) && at + first_len < bytes.len() && slash(json_unit(bytes, at + first_len).0) {
+ return Some(Start::Slashes);
+ }
+ let http = chars[..4]
+ .iter()
+ .zip(b"http")
+ .all(|(&ch, &b)| is_char(ch, b));
+ let colon_at = if is_char(chars[4], b's') { 5 } else { 4 };
+ (count > colon_at && http && is_char(chars[colon_at], b':')).then_some(Start::Scheme)
+}
+
+fn closer_after(prev: Option<Unit>) -> Closer {
+ match prev {
+ Some(Unit {
+ ch,
+ kind: Kind::Plain,
+ ..
+ }) if is_char(ch, b'(') => Closer::Paren,
+ Some(Unit {
+ ch,
+ kind: Kind::Plain,
+ ..
+ }) if is_char(ch, b'\'') => Closer::Apostrophe,
+ Some(Unit {
+ ch,
+ kind: Kind::Plain,
+ ..
+ }) if is_char(ch, b'"') => Closer::Quote,
+ _ => Closer::None,
+ }
+}
+
+fn ends_url(next: Unit, closer: Closer) -> bool {
+ match next.kind {
+ Kind::StringEnd => true,
+ Kind::CssEscaped => false,
+ Kind::Plain => {
+ is_space(next.ch)
+ || match closer {
+ Closer::None => false,
+ Closer::Paren => is_char(next.ch, b')'),
+ Closer::Apostrophe => is_char(next.ch, b'\''),
+ Closer::Quote => is_char(next.ch, b'"'),
+ }
+ }
+ }
+}
+
+/// The spans of the remote URL tokens, in order.
+fn url_spans(bytes: &[u8]) -> Vec<(usize, usize)> {
+ scan(bytes).urls
+}
+
+/// The remote URL tokens of the bytes and the insides of their JSON strings, each in order.
+struct Scan {
+ urls: Vec<(usize, usize)>,
+ strings: Vec<(usize, usize)>,
+}
+
+fn scan(bytes: &[u8]) -> Scan {
+ let mut spans = Vec::new();
+ let mut strings = Vec::new();
+ let mut string_start: Option<usize> = None;
+ let mut prev: Option<Unit> = None;
+ let mut at = 0;
+ while at < bytes.len() {
+ let current = unit(bytes, at);
+ if current.kind == Kind::StringEnd {
+ match string_start.take() {
+ Some(start) => strings.push((start, at)),
+ None => string_start = Some(at + 1),
+ }
+ }
+ let first = lower(current.ch);
+ let starts = string_start.is_some()
+ && current.kind != Kind::StringEnd
+ && (is_char(first, b'h') || is_char(first, b'/') || is_char(first, b'\\'))
+ && match remote_start(bytes, at) {
+ Some(Start::Scheme) => true,
+ Some(Start::Slashes) => !prev.is_some_and(|p| continues_word(p.ch)),
+ None => false,
+ };
+ if !starts {
+ prev = Some(current);
+ at += current.len;
+ continue;
+ }
+ let closer = closer_after(prev);
+ let mut end = at;
+ while end < bytes.len() {
+ let next = unit(bytes, end);
+ if ends_url(next, closer) {
+ break;
+ }
+ end += next.len;
+ }
+ spans.push((at, end));
+ prev = None;
+ at = end;
+ }
+ Scan {
+ urls: spans,
+ strings,
+ }
+}
+
+/// The token's characters after their JSON and CSS escapes, in lower case, so an escaped host still matches.
+fn decoded(bytes: &[u8], (start, end): (usize, usize)) -> String {
+ let mut text = String::new();
+ let mut at = start;
+ while at < end {
+ let next = unit(bytes, at);
+ text.extend(char::from_u32(lower(next.ch)));
+ at += next.len;
+ }
+ text
+}
+
+/// Whether the byte before `at` closes a JSON escape that ends a token, such as `\n`, rather than an escaped backslash.
+fn escape_ends_at(bytes: &[u8], at: usize) -> bool {
+ at >= 2
+ && matches!(bytes[at - 1], b'n' | b'r' | b't' | b'b' | b'f')
+ && bytes[..at - 1]
+ .iter()
+ .rev()
+ .take_while(|&&b| b == b'\\')
+ .count()
+ % 2
+ == 1
+}
+
+/// The span around a host that no URL token holds, such as a bare host in text. It ends at whitespace and quotes, which
+/// never sit inside an escape, so the span keeps every escape whole.
+fn bare_span(bytes: &[u8], start: usize, end: usize) -> (usize, usize) {
+ let mut first = start;
+ while first > 0
+ && bytes[first - 1] > b' '
+ && bytes[first - 1] != b'"'
+ && !escape_ends_at(bytes, first)
+ {
+ first -= 1;
+ }
+ let mut last = end;
+ while last < bytes.len() && bytes[last] > b' ' && bytes[last] != b'"' {
+ if bytes[last] == b'\\' {
+ let (ch, len) = json_unit(bytes, last);
+ if len > 1 && (is_space(ch) || is_char(ch, b'"')) {
+ break;
+ }
+ last += len;
+ } else {
+ last += 1;
+ }
+ }
+ (first, last.min(bytes.len()))
+}
+
+impl Scrubber {
+ pub fn new(scrub: &Scrub) -> Self {
+ let hosts = match scrub {
+ Scrub::Hosts(hosts) if !hosts.is_empty() => {
+ let mut hosts: Vec<String> =
+ hosts.iter().map(|host| host.to_ascii_lowercase()).collect();
+ hosts.sort_unstable();
+ hosts.dedup();
+ AhoCorasickBuilder::new()
+ .ascii_case_insensitive(true)
+ .match_kind(MatchKind::LeftmostFirst)
+ .build(&hosts)
+ .ok()
+ }
+ _ => None,
+ };
+ Self {
+ all_remote: *scrub == Scrub::AllRemote,
+ hosts,
+ }
+ }
+
+ /// The bytes with each URL token replaced, and how many were.
+ pub fn apply<'b>(&self, bytes: &'b [u8]) -> (Cow<'b, [u8]>, u64) {
+ let spans = if self.all_remote {
+ url_spans(bytes)
+ } else if let Some(hosts) = &self.hosts {
+ Self::host_spans(hosts, bytes)
+ } else {
+ Vec::new()
+ };
+ if spans.is_empty() {
+ return (Cow::Borrowed(bytes), 0);
+ }
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut copied_to = 0;
+ let mut replaced = 0;
+ for (start, end) in spans {
+ if end <= copied_to {
+ continue;
+ }
+ if start >= copied_to {
+ out.extend_from_slice(&bytes[copied_to..start]);
+ out.extend_from_slice(UNCHECKED_MARKER.as_bytes());
+ replaced += 1;
+ }
+ copied_to = end;
+ }
+ out.extend_from_slice(&bytes[copied_to..]);
+ (Cow::Owned(out), replaced)
+ }
+
+ /// The URL tokens that hold a host, and a bare span around each host no URL token holds, by start.
+ fn host_spans(hosts: &AhoCorasick, bytes: &[u8]) -> Vec<(usize, usize)> {
+ let Scan { urls, strings } = scan(bytes);
+ let mut spans: Vec<(usize, usize)> = urls
+ .into_iter()
+ .filter(|&span| hosts.is_match(decoded(bytes, span).as_bytes()))
+ .collect();
+ let inside = |list: &[(usize, usize)], (start, end): (usize, usize)| {
+ let first = list.partition_point(|&(_, list_end)| list_end < end);
+ list.get(first)
+ .filter(|&&(list_start, list_end)| list_start <= start && end <= list_end)
+ .copied()
+ };
+ let mut bare = Vec::new();
+ let mut covered_to = 0;
+ for found in hosts.find_iter(bytes) {
+ let host = (found.start(), found.end());
+ // A host outside a JSON string is part of a literal such as `null`, and an earlier span may already hold it.
+ if host.0 < covered_to || inside(&spans, host).is_some() {
+ continue;
+ }
+ let Some((string_start, string_end)) = inside(&strings, host) else {
+ continue;
+ };
+ let (start, end) = bare_span(bytes, host.0, host.1);
+ let span = (start.max(string_start), end.min(string_end));
+ covered_to = span.1;
+ bare.push(span);
+ }
+ spans.extend(bare);
+ spans.sort_unstable();
+ spans
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn scrub(scrub: Scrub, bytes: &str) -> (String, u64) {
+ let (out, count) = Scrubber::new(&scrub).apply(bytes.as_bytes());
+ let out = String::from_utf8(out.into_owned()).unwrap();
+ serde_json::from_str::<serde_json::Value>(&out).unwrap_or_else(|e| panic!("{out}: {e}"));
+ (out, count)
+ }
+
+ #[test]
+ fn replaces_every_remote_url_token_and_keeps_the_json_around_it() {
+ let m = UNCHECKED_MARKER;
+ for (input, expected) in [
+ (
+ r#"{"src":"https://cdn.example.com/a.png?x=1"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ (
+ r#"{"srcset":"HTTP://a.example.com/a.png 1x,\nhttps://b.example.com/b.png 2x"}"#
+ .to_owned(),
+ format!(r#"{{"srcset":"{m} 1x,\n{m} 2x"}}"#),
+ ),
+ (
+ r#"{"style":"background:url(\"//cdn.example.com/a.png\")"}"#.to_owned(),
+ format!(r#"{{"style":"background:url(\"{m}\")"}}"#),
+ ),
+ (
+ r#"{"style":"url('https://cdn.example.com/a.png') no-repeat"}"#.to_owned(),
+ format!(r#"{{"style":"url('{m}') no-repeat"}}"#),
+ ),
+ // A CSS escape is part of the URL a browser loads, the whitespace that ends a hex escape included.
+ (
+ r#"{"style":"url(https\\3a //cdn.example.com/a.png)"}"#.to_owned(),
+ format!(r#"{{"style":"url({m})"}}"#),
+ ),
+ (
+ r#"{"style":"url(\\2f\\2f bucket.example.com/a.png?sig=x)"}"#.to_owned(),
+ format!(r#"{{"style":"url({m})"}}"#),
+ ),
+ // A browser reads a backslash as a slash, and the inspector reads any host after two of them as remote.
+ (
+ r#"{"src":"\\\\10.0.0.7/a.png"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ (
+ r#"{"src":"\/\/[::1]/a.png"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ // Outside CSS, an apostrophe or a parenthesis is part of the URL, so the query after it goes too.
+ (
+ r#"{"src":"https://cdn.example.com/a'b(c).png?token=x"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ // An escaped backslash at the end goes whole, so the quote after it still ends the string.
+ (
+ r#"{"src":"https://cdn.example.com/a\\"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ // `http` inside a word, and a path's `//`, start no URL.
+ (
+ r#"{"text":"httpd at /a//b"}"#.to_owned(),
+ r#"{"text":"httpd at /a//b"}"#.to_owned(),
+ ),
+ ] {
+ assert_eq!(scrub(Scrub::AllRemote, &input).0, expected, "{input}");
+ }
+ }
+
+ #[test]
+ fn replaces_the_tokens_that_hold_a_host_in_any_form() {
+ let m = UNCHECKED_MARKER;
+ let (out, count) = scrub(
+ Scrub::Hosts(vec!["internal.example.com".to_owned()]),
+ r#"{"style":"url(https\\3a \\2f \\2f Internal.example.com\\2f a.png)","alt":"see internal.example.com/a'b?token=x\nnow","title":"other.example.com"}"#,
+ );
+ assert_eq!(
+ out,
+ format!(r#"{{"style":"url({m})","alt":"see {m}\nnow","title":"other.example.com"}}"#)
+ );
+ assert_eq!(count, 2);
+ }
+
+ #[test]
+ fn matches_a_host_only_as_the_browser_reads_it_inside_a_string() {
+ let m = UNCHECKED_MARKER;
+ for (host, input, expected) in [
+ (
+ "10.0.0.7",
+ r#"{"style":"url(https://10\\2e 0.0.7/a.png)"}"#.to_owned(),
+ format!(r#"{{"style":"url({m})"}}"#),
+ ),
+ (
+ "null",
+ r#"{"src":"https://null/a.png","alt":null}"#.to_owned(),
+ format!(r#"{{"src":"{m}","alt":null}}"#),
+ ),
+ ] {
+ assert_eq!(
+ scrub(Scrub::Hosts(vec![host.to_owned()]), &input).0,
+ expected,
+ "{input}"
+ );
+ }
+ }
+}
diff --git a/rust/ai-research/replay-recorder-v4/src/write.rs b/rust/ai-research/replay-recorder-v4/src/write.rs
index f5ae41548d11..748af3dce228 100644
--- a/rust/ai-research/replay-recorder-v4/src/write.rs
+++ b/rust/ai-research/replay-recorder-v4/src/write.rs
@@ -26,7 +26,8 @@ use tokio::sync::Semaphore;
use crate::batch::{Block, SessionKey};
use crate::index::{BlockIndexRow, ImageIndexRow};
-use crate::rewrite::{canonical_strings, UrlRewrite};
+use crate::rewrite::{canonical_strings, Fallback, RewriteReport, UrlRewrite};
+use crate::scrub::Scrub;
use crate::store::{BlobStore, StoreError};
/// Brotli settings for blocks, the same as the v3 lane, which uses the same C encoder. The lane keeps blocks for months
@@ -65,9 +66,13 @@ 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: a URL the policy declines stays in it, or the
- /// inspector did not name all its URLs.
+ /// Why the block must not be stored, as the outcome of its drop: a URL the policy declines stays in it even after
+ /// the fallback.
pub dropped: Option<&'static str>,
+ /// Why the writer used a fallback to keep the block, as a metric label.
+ pub fallback: Option<&'static str>,
+ /// The URL tokens the fallback replaced.
+ pub scrubbed: u64,
}
/// A block compressed once for all the attempts of its flush, with the images it moved out.
@@ -107,23 +112,13 @@ pub fn object_key(write_day: &str, at: DateTime<Utc>) -> String {
/// per event. Every image goes into this flush's packs, even one an earlier flush stored: a pack expires by its own
/// write time, so it must be no older than the blocks that reference it.
/// Expanded `cv` events can make a block far larger than its messages, so only one event is held at a time.
-pub fn prepare_block(
+fn prepare_block(
block: &Block,
team_key: &[u8; 32],
key_month: &str,
+ fallback: &Fallback,
out: &mut impl Write,
-) -> io::Result<(Vec<Image>, WriterCounts)> {
- // Fail closed: a URL the inspector did not name could be one the policy declines.
- if let Some(limit) = block.url_limit {
- let dropped = Some(limit.label());
- return Ok((
- Vec::new(),
- WriterCounts {
- dropped,
- ..WriterCounts::default()
- },
- ));
- }
+) -> io::Result<(Vec<Image>, WriterCounts, RewriteReport)> {
let content_key = image_content_key(team_key);
let mut rewrite = UrlRewrite::new(
&block.remote_urls,
@@ -131,10 +126,12 @@ pub fn prepare_block(
block.session.team_id,
key_month,
team_key,
- );
+ )
+ .with_fallback(fallback.clone());
let mut images = Vec::new();
let mut kept = HashSet::new();
let mut counts = WriterCounts::default();
+ let mut removed_avif = 0u64;
for message in &block.messages {
let mut window = Vec::new();
write_json_string(
@@ -157,7 +154,10 @@ pub fn prepare_block(
.as_deref()
.unwrap_or(&message.inner[event.span.0..event.span.1]),
);
- let event_bytes = rewrite.apply(&canonical);
+ // The inspector reads image slots in full snapshots and mutations only.
+ let dom_event =
+ event.kind == Some(2) || (event.kind == Some(3) && event.source == Some(0));
+ let event_bytes = rewrite.apply(&canonical, dom_event);
out.write_all(&event_bytes)?;
out.write_all(b"]\n")?;
let line = (window.len() + event_bytes.len() + 4) as u64;
@@ -171,19 +171,90 @@ pub fn prepare_block(
.map(|i| i.bytes.len() as u64)
.sum::<u64>();
counts.inline += sink.left_inline;
- counter!("ai_research_v4_recorder_removed_images_total", "format" => "avif")
- .increment(u64::from(sink.removed_avif));
+ removed_avif += u64::from(sink.removed_avif);
images.extend(
sink.images
.into_iter()
.filter(|image| kept.insert(image.reference.clone())),
);
}
- // Fail closed: the flush drops a block that still holds a declined URL, a credential or a private host.
- if !rewrite.finish() {
+ let mut report = rewrite.finish();
+ report.counters.removed_avif = removed_avif;
+ counts.scrubbed = report.scrubbed;
+ Ok((images, counts, report))
+}
+
+/// A block whose URLs the inspector did not all name has every remote URL token it did not name scrubbed, so that the
+/// block is kept without a URL nobody checked.
+fn first_fallback(block: &Block) -> Fallback {
+ match block.url_limit {
+ Some(limit) => Fallback {
+ overwrite_declined: true,
+ scrub: Scrub::AllRemote,
+ reason: Some(limit.label()),
+ },
+ None => Fallback::default(),
+ }
+}
+
+/// What the second pass does about what the first left unsafe: it overwrites each declined URL wherever it is, and
+/// scrubs the tokens that hold the host of a declined URL the stored bytes do not hold as the inspector read it.
+fn second_fallback(first: &Fallback, report: &RewriteReport) -> Fallback {
+ let scrub = match (&first.scrub, &report.unfound_hosts) {
+ (Scrub::AllRemote, _) | (_, None) => Scrub::AllRemote,
+ (_, Some(hosts)) if hosts.is_empty() => Scrub::Nothing,
+ (_, Some(hosts)) => Scrub::Hosts(hosts.clone()),
+ };
+ let reason = if report.unfound_hosts.as_ref().is_some_and(Vec::is_empty) {
+ "declined_kept"
+ } else {
+ "declined_unfound"
+ };
+ Fallback {
+ overwrite_declined: true,
+ scrub,
+ reason: first.reason.or(Some(reason)),
+ }
+}
+
+/// Writes a block's lines to an output from `open`. A block that the first pass leaves unsafe is written again to a
+/// fresh output with the fallback that makes it safe, so a block is dropped only when even that fails. Moves the
+/// images out and returns them with the output.
+pub fn write_block<W: Write>(
+ block: &Block,
+ team_key: &[u8; 32],
+ key_month: &str,
+ mut open: impl FnMut() -> io::Result<W>,
+) -> io::Result<(W, Vec<Image>, WriterCounts)> {
+ let first = first_fallback(block);
+ let mut out = open()?;
+ let (images, mut counts, report) = prepare_block(block, team_key, key_month, &first, &mut out)?;
+ if report.safe {
+ report.counters.emit();
+ counts.fallback = first.reason;
+ return Ok((out, images, counts));
+ }
+ let second = second_fallback(&first, &report);
+ if let Some(key) = &report.kept_in {
+ tracing::info!(
+ team_id = block.session.team_id,
+ key,
+ "a declined URL stayed inside a longer token"
+ );
+ }
+ // The second pass copies every image again, so the first pass's output and images go before it starts.
+ drop(out);
+ drop(images);
+ let mut out = open()?;
+ let (images, mut counts, report) =
+ prepare_block(block, team_key, key_month, &second, &mut out)?;
+ report.counters.emit();
+ counts.fallback = second.reason;
+ // Fail closed only when the fallback could not make the block safe either.
+ if !report.safe {
counts.dropped = Some("declined_unrewritten");
}
- Ok((images, counts))
+ Ok((out, images, counts))
}
fn block_encoder() -> Result<brotlic::BrotliEncoder, WriteError> {
@@ -220,11 +291,24 @@ pub fn compress_block(
let seal_error = |e: io::Error| WriteError::Seal(e.to_string());
// Lines go into the encoder as they are built, so memory follows the compressed block and not its plaintext.
// A brotli stream does not state its decompressed size, so a reader decompresses it as a stream.
- let encoder = brotlic::CompressorWriter::with_encoder(block_encoder()?, Vec::new());
// The encoder works on each write it gets, so small writes cost far more CPU than the same bytes in one.
- let mut lines = io::BufWriter::with_capacity(BLOCK_WRITE_BUFFER, encoder);
- let (images, counts) =
- prepare_block(block, team_key, key_month, &mut lines).map_err(seal_error)?;
+ let open = || {
+ block_encoder()
+ .map(|encoder| {
+ io::BufWriter::with_capacity(
+ BLOCK_WRITE_BUFFER,
+ brotlic::CompressorWriter::with_encoder(encoder, Vec::new()),
+ )
+ })
+ .map_err(|e| io::Error::other(e.to_string()))
+ };
+ let (lines, images, counts) =
+ write_block(block, team_key, key_month, open).map_err(seal_error)?;
+ if let Some(reason) = counts.fallback {
+ counter!("ai_research_v4_recorder_url_fallbacks_total", "reason" => reason).increment(1);
+ counter!("ai_research_v4_recorder_scrubbed_urls_total", "reason" => reason)
+ .increment(counts.scrubbed);
+ }
let encoder = lines.into_inner().map_err(|e| seal_error(e.into_error()))?;
let body = encoder
.into_inner()
@@ -610,13 +694,13 @@ mod tests {
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use replay_core_v4::envelope::open_frame;
- use replay_core_v4::inspect::dom::MAX_REMOTE_URL_BYTES;
use replay_core_v4::inspect::session::Moment;
use replay_core_v4::scan::message::read_message;
use serde_json::{json, Value};
use super::*;
use crate::batch::{Origin, Tp};
+ use replay_core_v4::inspect::dom::MAX_BLOCK_REMOTE_URLS;
#[derive(Default)]
struct MemoryStore {
@@ -715,8 +799,8 @@ mod tests {
inspected
.remote_urls
.extend(extra.iter().map(|url| (*url).to_owned()));
- let mut lines = Vec::new();
- let (_, counts) = prepare_block(&inspected, &[6; 32], "2026-10", &mut lines).unwrap();
+ let (lines, _, counts) =
+ write_block(&inspected, &[6; 32], "2026-10", || Ok(Vec::new())).unwrap();
if counts.dropped.is_some() {
return String::new();
}
@@ -749,15 +833,19 @@ mod tests {
)),
"{lines}"
);
- // A URL past the length cap is not named, so the block is not stored.
+ // A URL past the length the fetcher takes is named and declined.
let long = |len: usize| {
let url = format!("https://cdn.example.com/{}", "a".repeat(len - 24));
json!([{"type": 3, "timestamp": 1, "data": {"source": 0, "adds": [], "removes": [], "texts": [],
"attributes": [{"id": 99, "attributes": {"src": url}}]}}])
.to_string()
};
- assert!(!stored_lines(&long(MAX_REMOTE_URL_BYTES), &[]).is_empty());
- assert_eq!(stored_lines(&long(MAX_REMOTE_URL_BYTES + 1), &[]), "");
+ // A URL too long to fetch is declined, and the block is kept.
+ let long_lines = stored_lines(&long(16 * 1024), &[]);
+ assert!(
+ long_lines.contains(&crate::rewrite::declined_marker("too_long")),
+ "{long_lines}"
+ );
// Keys written with escapes hide no URL.
let escaped = events
.replace(r#""src""#, r#""\u0073rc""#)
@@ -795,12 +883,43 @@ mod tests {
"{lines}"
);
}
- // A declined URL the inspector named but the stored bytes do not show as it read it fails the whole block.
- let event =
- json!([{"type": 4, "timestamp": 1, "data": {"href": "https://app.example.com/"}}])
- .to_string();
- assert_eq!(stored_lines(&event, &[signed]), "");
+ // A declined URL the inspector named but the stored bytes do not show as it read it no longer fails the block:
+ // the writer scrubs every token that holds its host, and keeps the rest.
+ let event = json!([{"type": 4, "timestamp": 1, "data": {"href": "https://app.example.com/", "img": "https\\3a //bucket.s3.amazonaws.com/avatar.png"}}])
+ .to_string();
+ let lines = stored_lines(&event, &[signed]);
+ assert!(
+ lines.contains("https://app.example.com/")
+ && !lines.contains("bucket.s3.amazonaws.com"),
+ "{lines}"
+ );
assert!(!stored_lines(&event, &[public]).is_empty());
+ // A declined URL that a longer URL also holds is overwritten there too, and the block is kept.
+ let events = json!([{"type": 3, "timestamp": 1, "data": {"source": 0, "adds": [], "removes": [], "texts": [],
+ "attributes": [{"id": 99, "attributes": {"src": signed, "alt": format!("{signed}&size=2")}}]}}])
+ .to_string();
+ let lines = stored_lines(&events, &[]);
+ assert!(
+ !lines.is_empty() && !lines.contains("X-Amz-Signature"),
+ "{lines}"
+ );
+ }
+
+ #[test]
+ fn keeps_a_block_past_the_url_limit_without_a_url_it_did_not_check() {
+ let urls = MAX_BLOCK_REMOTE_URLS + 1;
+ let nodes: Vec<_> = (0..urls)
+ .map(|i| json!({"type": 2, "tagName": "img", "attributes": {"src": format!("https://cdn.example.com/{i}.png")}, "childNodes": [], "id": i + 2}))
+ .collect();
+ let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"type": 0, "id": 1, "childNodes": nodes}}}]).to_string();
+ let lines = stored_lines(&events, &[]);
+ // The inspector named the first URLs, which keep their references; the fallback scrubbed the rest.
+ assert!(
+ lines.contains("imageurl:v4:7:2026-10:"),
+ "named URLs keep their references"
+ );
+ assert!(lines.contains(crate::scrub::UNCHECKED_MARKER));
+ assert!(!lines.contains("https://"));
}
#[test]
@@ -925,7 +1044,34 @@ mod tests {
"{lines}"
);
- // A srcset key outside an image slot, here in a custom event, is no srcset of the DOM and stays as it is.
+ // A srcset key outside an image slot, here in a custom event, is no srcset of the DOM and stays as it is. With
+ // the same value as an inspected image slot, only the slot is rebuilt, and the custom event gets the rewrite of
+ // each URL that every copy of a named URL gets.
+ let value = "https://cdn.example.com/a.png 1x, https://10.0.0.7/a.png 2x";
+ let both = format!(
+ r#"[{{"type":3,"timestamp":1,"data":{{"source":0,"adds":[],"removes":[],"texts":[],"attributes":[{{"id":99,"attributes":{{"srcset":"{value}"}}}}]}}}},{{"type":5,"timestamp":2,"data":{{"tag":"app","payload":{{"srcset":"{value}"}}}}}}]"#
+ );
+ let lines = stored_lines(&both, &[]);
+ let reference = crate::urls::url_reference(
+ "https://cdn.example.com/a.png",
+ 7,
+ "2026-10",
+ &replay_core_v4::seal::image_url_key(&[6; 32]),
+ )
+ .unwrap()
+ .1;
+ let (dom, custom) = lines.split_once('\n').unwrap();
+ assert!(
+ dom.contains(&format!(r#""srcset":"{reference} 1x""#)),
+ "{dom}"
+ );
+ assert!(
+ custom.contains(&format!(
+ r#""srcset":"{reference} 1x, {} 2x""#,
+ crate::rewrite::declined_marker("non_public_host")
+ )),
+ "{custom}"
+ );
let custom = r#"[{"type":5,"timestamp":1,"data":{"tag":"app","payload":{"srcset":"https://cdn.example.com/a.png 1x, https://10.0.0.7/a.png 2x"}}}]"#;
let lines = stored_lines(custom, &[]);
assert!(
@@ -972,8 +1118,8 @@ mod tests {
keys.team_months.insert(7, [6; 32]);
let mut stats = BlockStats::default();
let jobs = crate::urls::fetch_jobs([(&block, &mut stats)], &keys, "2026-10", 1, &|_| false);
- let mut lines = Vec::new();
- prepare_block(&block, &[6; 32], "2026-10", &mut lines).unwrap();
+ let (lines, _, _) = write_block(&block, &[6; 32], "2026-10", || Ok(Vec::new())).unwrap();
+
let lines = String::from_utf8(lines).unwrap();
let reference = jobs["example.com"][0]["originalRef"].as_str().unwrap();
assert!(
@@ -1040,8 +1186,8 @@ mod tests {
let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"attributes": {"src": uri(b"logo")}}}}]);
let mut repeated = block("s", events.clone());
repeated.messages.extend(block("s", events).messages);
- let (images, counts) =
- prepare_block(&repeated, &[6; 32], "2026-10", &mut io::sink()).unwrap();
+ let (_, images, counts) =
+ write_block(&repeated, &[6; 32], "2026-10", || Ok(io::sink())).unwrap();
assert_eq!((images.len(), counts.extracted), (1, 2));
}