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): bound robots parsing, url scrub and index rows (#127332)

Nicholas Waltz227eb42a0497
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.test.ts
index d3656d8c5eb9..141b274ecc87 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.test.ts
@@ -6,6 +6,7 @@ import {
ConfigurationFetchResult,
ConfigurationPolicyService,
HttpConfigurationFetcher,
+ collectRobots,
explicitFreshnessLifetimeMs,
parseRobotsPolicy,
responseOptOutReason,
@@ -134,6 +135,57 @@ describe('robots policy', () => {
await expect(parseRobotsPolicy(body, `${ORIGIN}/image.png`)).resolves.toMatchObject({ allowed })
})
+ it('keeps only the rules that apply to this bot, and decides the same URLs', async () => {
+ const robotsParser = await import('@trybyte/robotstxt-parser')
+ const body = [
+ 'Disallow: /no-group',
+ 'User-agent: otherbot',
+ 'User-agent: thirdbot',
+ 'Disallow: /other',
+ 'User-agent: otherbot',
+ 'User-agent: *',
+ 'Disallow: /wildcard',
+ 'User-agent: PostHogImageFetcherBot/1.0',
+ 'User-agent: otherbot',
+ 'Disallow: /first',
+ 'Disallow:',
+ 'User-agent: posthogimagefetcherbot',
+ 'Disallow: /second',
+ 'Allow: /second/public.png',
+ ].join('\n')
+
+ expect(collectRobots(body, robotsParser).applicableBody()).toBe(
+ [
+ 'User-agent:PostHogImageFetcherBot',
+ 'Disallow:/first',
+ 'Disallow:/second',
+ 'Allow:/second/public.png',
+ 'User-agent:*',
+ 'Disallow:/wildcard',
+ ].join('\n')
+ )
+ for (const [path, allowed] of [
+ ['/first/a.png', false],
+ ['/second/a.png', false],
+ ['/second/public.png', true],
+ ['/other/a.png', true],
+ ['/no-group/a.png', true],
+ ['/wildcard/a.png', true],
+ ] as const) {
+ await expect(parseRobotsPolicy(body, `${ORIGIN}${path}`)).resolves.toMatchObject({ allowed })
+ }
+ })
+
+ it('refuses a URL when only a shortened copy of a long Allow rule would permit it', async () => {
+ const accents = 'é'.repeat(300)
+ const body = `User-agent: *\nDisallow: /\nAllow: /${accents}${'*'.repeat(15_000)}/kept.png`
+
+ await expect(parseRobotsPolicy(body, `${ORIGIN}/${encodeURI(accents)}/other.png`)).resolves.toMatchObject({
+ allowed: false,
+ reason: 'robots_disallow',
+ })
+ })
+
it('applies a path-scoped Content-Signal only to a matching URL', async () => {
const body = 'User-agent: *\nContent-Signal: /private/ ai-train=no, search=yes\nAllow: /'
@@ -282,7 +334,7 @@ describe('ConfigurationPolicyService', () => {
await pass.check(`${ORIGIN}/first.png`, cache, NOW_MS)
await pass.check(`${ORIGIN}/second.png`, cache, NOW_MS)
- expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(1)
+ expect(parseRobots.mock.calls.filter(([body]) => body === 'User-agent:*\nAllow:/')).toHaveLength(1)
expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(1)
const revisedCache = new Map(
@@ -290,12 +342,12 @@ describe('ConfigurationPolicyService', () => {
)
await pass.check(`${ORIGIN}/third.png`, revisedCache, NOW_MS)
- expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(2)
+ expect(parseRobots.mock.calls.filter(([body]) => body === 'User-agent:*\nAllow:/')).toHaveLength(2)
expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(2)
await policy.createPass().check(`${ORIGIN}/fourth.png`, cache, NOW_MS)
- expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(3)
+ expect(parseRobots.mock.calls.filter(([body]) => body === 'User-agent:*\nAllow:/')).toHaveLength(3)
expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(3)
} finally {
parseRobots.mockRestore()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.ts
index d3f4ba19b2b9..2cf203e1c1ae 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/configuration-policy.ts
@@ -473,14 +473,82 @@ class ExtensionCollector implements RobotsParseHandler {
}
}
-function selectedExtensionFields(
+/** Collects only the rules that apply to this bot, because ParsedRobots keeps a copy of a group's rules for each of its user agents. */
+class RobotsCollector extends ExtensionCollector {
+ public readonly botRules: string[] = []
+ public readonly wildcardRules: string[] = []
+ private forBot = false
+ private forWildcard = false
+ private groupHasRules = false
+
+ constructor(private readonly maxLineLength: number) {
+ super()
+ }
+
+ override handleUserAgent(lineNum: number, value: string): void {
+ super.handleUserAgent(lineNum, value)
+ if (this.groupHasRules) {
+ this.forBot = false
+ this.forWildcard = false
+ this.groupHasRules = false
+ }
+ if (/^\*(?:\s|$)/.test(value)) {
+ this.forWildcard = true
+ } else if (/^[a-z_-]+/i.exec(value)?.[0].toLowerCase() === BOT_NAME.toLowerCase()) {
+ this.forBot = true
+ }
+ }
+
+ override handleAllow(_lineNum?: number, value = ''): void {
+ super.handleAllow()
+ this.addRule('Allow', value)
+ }
+
+ override handleDisallow(_lineNum?: number, value = ''): void {
+ super.handleDisallow()
+ this.addRule('Disallow', value)
+ }
+
+ /** The robots.txt that decides the same URLs for this bot, with one group for the bot and one for `*`. */
+ public applicableBody(): string {
+ return [
+ ...(this.botRules.length ? [`User-agent:${BOT_NAME}`, ...this.botRules] : []),
+ ...(this.wildcardRules.length ? ['User-agent:*', ...this.wildcardRules] : []),
+ ].join('\n')
+ }
+
+ private addRule(directive: string, value: string): void {
+ if (!value) {
+ return
+ }
+ this.groupHasRules = true
+ const line = `${directive}:${value}`
+ // The second parse truncates a line past the limit. A truncated Allow permits more than its rule, so it goes. A truncated Disallow only refuses more.
+ if (directive === 'Allow' && line.length > this.maxLineLength) {
+ return
+ }
+ if (this.forBot) {
+ this.botRules.push(line)
+ }
+ if (this.forWildcard) {
+ this.wildcardRules.push(line)
+ }
+ }
+}
+
+export function collectRobots(
body: string,
- parseRobotsTxt: typeof import('@trybyte/robotstxt-parser').parseRobotsTxt
-): Array<{ name: string; value: string }> {
- const collector = new ExtensionCollector()
+ { parseRobotsTxt, K_MAX_LINE_LEN }: typeof import('@trybyte/robotstxt-parser')
+): RobotsCollector {
+ // The parser keeps one character less than K_MAX_LINE_LEN on a line.
+ const collector = new RobotsCollector(K_MAX_LINE_LEN - 1)
parseRobotsTxt(body, collector)
+ return collector
+}
+
+function selectedExtensionFields(groups: ExtensionGroup[]): Array<{ name: string; value: string }> {
const bot = BOT_NAME.toLowerCase()
- const matches = collector.groups.map((group) => ({
+ const matches = groups.map((group) => ({
group,
specificity: Math.max(
...group.userAgents.map((agent) => (agent !== '*' && bot.startsWith(agent) ? agent.length : 0)),
@@ -509,10 +577,10 @@ export async function parseRobotsPolicy(
async function parseRobotsConfiguration(body: string): Promise<ParsedRobotsConfiguration> {
const robotsParser = await import('@trybyte/robotstxt-parser')
- const { ParsedRobots, parseRobotsTxt } = robotsParser
+ const collector = collectRobots(body, robotsParser)
return {
- matcher: ParsedRobots.parse(body),
- fields: selectedExtensionFields(body, parseRobotsTxt),
+ matcher: robotsParser.ParsedRobots.parse(collector.applicableBody()),
+ fields: selectedExtensionFields(collector.groups),
}
}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 361237b7ad7b..15b5b16328d3 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -482,7 +482,7 @@ The recorder streams each block into the encoder. Read a block as a stream: a Br
- 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 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.
-- 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.
+- 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 that starts after `(`, `'` or `"` runs to the `)`, `'` or `"` that ends it, a token that starts its JSON string runs to the end of the string, because a space does not end an attribute's URL, and any other token runs to whitespace, 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/scan/message.rs b/rust/ai-research/replay-core-v4/src/scan/message.rs
index 892935f1e483..22af60bf3200 100644
--- a/rust/ai-research/replay-core-v4/src/scan/message.rs
+++ b/rust/ai-research/replay-core-v4/src/scan/message.rs
@@ -197,6 +197,14 @@ fn read_inner(inner: Vec<u8>, max_events: usize) -> Result<Message, ReadError> {
{
return Err(ReadError::Malformed("$window_id is too long"));
}
+ // Each moment in an index row repeats the ID, and JSON writes a control character as six bytes. Without them, the
+ // longest ID keeps a row under the producer's message limit.
+ if window_id
+ .as_ref()
+ .is_some_and(|id| id.bytes().any(|byte| byte < b' '))
+ {
+ return Err(ReadError::Malformed("$window_id has a control character"));
+ }
let mut events = Vec::new();
for item in scan::array_items(&inner, items)? {
if events.len() >= max_events {
@@ -374,6 +382,10 @@ mod tests {
read("w".repeat(MAX_WINDOW_ID_BYTES + 1)).unwrap_err(),
ReadError::Malformed("$window_id is too long")
);
+ assert_eq!(
+ read("w\u{1}".to_owned()).unwrap_err(),
+ ReadError::Malformed("$window_id has a control character")
+ );
}
#[test]
diff --git a/rust/ai-research/replay-recorder-v4/src/index.rs b/rust/ai-research/replay-recorder-v4/src/index.rs
index 28b1c201e866..96d806a55a34 100644
--- a/rust/ai-research/replay-recorder-v4/src/index.rs
+++ b/rust/ai-research/replay-recorder-v4/src/index.rs
@@ -419,6 +419,9 @@ impl IndexMessage {
#[cfg(test)]
mod tests {
+ use replay_core_v4::inspect::session::MAX_MOMENTS_PER_BLOCK;
+ use replay_core_v4::inspect::stats::MAX_WINDOW_IDS;
+ use replay_core_v4::scan::message::MAX_WINDOW_ID_BYTES;
use serde_json::{json, Value};
use super::*;
@@ -685,6 +688,29 @@ mod tests {
};
let message = IndexMessage::block(&block).unwrap();
let value = assert_columns(&message.payload, BLOCK_COLUMNS);
+
+ // The longest window ID the reader accepts, in the characters JSON writes longest, keeps the row under the
+ // producer's default limit, so a rejected row cannot make its flush look incomplete.
+ let window = "\"".repeat(MAX_WINDOW_ID_BYTES);
+ let wide = BlockStats {
+ window_ids: vec![window.clone(); MAX_WINDOW_IDS],
+ ..BlockStats::default()
+ };
+ let crowded = vec![
+ Moment {
+ kind: "full_snapshot",
+ window_id: window.as_str().into(),
+ ts_ms: 0,
+ event_index: 0,
+ };
+ MAX_MOMENTS_PER_BLOCK
+ ];
+ let largest = BlockIndexRow {
+ stats: &wide,
+ moments: &crowded,
+ ..block
+ };
+ assert!(IndexMessage::block(&largest).unwrap().payload.len() < 1_000_000);
assert_eq!(
[
&value["first_ts_ms"],
diff --git a/rust/ai-research/replay-recorder-v4/src/scrub.rs b/rust/ai-research/replay-recorder-v4/src/scrub.rs
index 3eeaffd2dd3f..73077012b356 100644
--- a/rust/ai-research/replay-recorder-v4/src/scrub.rs
+++ b/rust/ai-research/replay-recorder-v4/src/scrub.rs
@@ -3,10 +3,11 @@
//! 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.
+//! escape and the stored JSON stays valid. A URL that starts after `(`, `'` or `"` ends at `)`, `'` or `"`, because CSS
+//! ends it there. A URL that starts its JSON string may be the whole value of an attribute, where a space does not end
+//! it, so it runs to the end of the string. Any other URL token ends at whitespace or at the end of its JSON string. 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;
@@ -47,10 +48,11 @@ struct Unit {
kind: Kind,
}
-/// The character that ends a URL besides whitespace and the end of its JSON string.
+/// The character that ends a URL besides the end of its JSON string.
#[derive(Clone, Copy)]
enum Closer {
- None,
+ Whitespace,
+ Nothing,
Paren,
Apostrophe,
Quote,
@@ -210,7 +212,11 @@ fn closer_after(prev: Option<Unit>) -> Closer {
kind: Kind::Plain,
..
}) if is_char(ch, b'"') => Closer::Quote,
- _ => Closer::None,
+ Some(Unit {
+ kind: Kind::StringEnd,
+ ..
+ }) => Closer::Nothing,
+ _ => Closer::Whitespace,
}
}
@@ -218,15 +224,13 @@ 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'"'),
- }
- }
+ Kind::Plain => match closer {
+ Closer::Whitespace => is_space(next.ch),
+ Closer::Nothing => false,
+ Closer::Paren => is_char(next.ch, b')'),
+ Closer::Apostrophe => is_char(next.ch, b'\''),
+ Closer::Quote => is_char(next.ch, b'"'),
+ },
}
}
@@ -448,7 +452,23 @@ mod tests {
(
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"}}"#),
+ format!(r#"{{"srcset":"{m}"}}"#),
+ ),
+ // A space inside a URL does not end it, so the query after the space goes too.
+ (
+ r#"{"src":"https://cdn.example.com/a b.png?access_token=x"}"#.to_owned(),
+ format!(r#"{{"src":"{m}"}}"#),
+ ),
+ (
+ r#"{"style":"background:url(\"https://cdn.example.com/a b.png?access_token=x\")"}"#
+ .to_owned(),
+ format!(r#"{{"style":"background:url(\"{m}\")"}}"#),
+ ),
+ // Inside text, whitespace still ends a URL.
+ (
+ r#"{"alt":"see https://a.example.com/a and https://b.example.com/b now"}"#
+ .to_owned(),
+ format!(r#"{{"alt":"see {m} and {m} now"}}"#),
),
(
r#"{"style":"background:url(\"//cdn.example.com/a.png\")"}"#.to_owned(),