From d1d81523ca577db1ccdfbb3b0de100edc658daff Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 14:14:15 +0100 Subject: [PATCH 01/40] feat(map): add the search map core's document model, keys, query kinds and first layer A search drawn as a map needs to read pages as structure with no model and no I/O of its own. zephium-map is that core: one bounded document model built from HTML through a capped html5ever sink, canonical page and site keys, a conservative reading of what kind of search a query is, and a results page read into organic results with sitelinks, the official site, socials, video and images, with paid results and the engine's own links dropped. The results reader ports the rules of the Work reader and passes its saved pages for Google, DuckDuckGo, Bing, Brave and a custom engine. Validated on macOS arm64: fmt, clippy -D warnings and 56 nextest cases for the crate. Not run on Windows. --- Cargo.lock | 13 + crates/zephium-map/Cargo.toml | 17 + crates/zephium-map/src/doc.rs | 312 +++++++++ crates/zephium-map/src/doc/html.rs | 516 ++++++++++++++ crates/zephium-map/src/doc/html/arena.rs | 536 ++++++++++++++ crates/zephium-map/src/doc/html/decode.rs | 372 ++++++++++ crates/zephium-map/src/doc/html/sink.rs | 151 ++++ crates/zephium-map/src/doc/html/tests.rs | 341 +++++++++ crates/zephium-map/src/key.rs | 151 ++++ crates/zephium-map/src/lib.rs | 18 + crates/zephium-map/src/query.rs | 244 +++++++ crates/zephium-map/src/results.rs | 651 ++++++++++++++++++ crates/zephium-map/src/results/destination.rs | 143 ++++ crates/zephium-map/src/results/entity.rs | 376 ++++++++++ crates/zephium-map/tests/doc.rs | 385 +++++++++++ crates/zephium-map/tests/first_layer.rs | 352 ++++++++++ .../tests/fixtures/first-layer.html | 14 + .../tests/fixtures/heading-sitelinks.html | 5 + crates/zephium-map/tests/key.rs | 95 +++ crates/zephium-map/tests/query.rs | 184 +++++ crates/zephium-map/tests/reference.rs | 372 ++++++++++ 21 files changed, 5248 insertions(+) create mode 100644 crates/zephium-map/Cargo.toml create mode 100644 crates/zephium-map/src/doc.rs create mode 100644 crates/zephium-map/src/doc/html.rs create mode 100644 crates/zephium-map/src/doc/html/arena.rs create mode 100644 crates/zephium-map/src/doc/html/decode.rs create mode 100644 crates/zephium-map/src/doc/html/sink.rs create mode 100644 crates/zephium-map/src/doc/html/tests.rs create mode 100644 crates/zephium-map/src/key.rs create mode 100644 crates/zephium-map/src/lib.rs create mode 100644 crates/zephium-map/src/query.rs create mode 100644 crates/zephium-map/src/results.rs create mode 100644 crates/zephium-map/src/results/destination.rs create mode 100644 crates/zephium-map/src/results/entity.rs create mode 100644 crates/zephium-map/tests/doc.rs create mode 100644 crates/zephium-map/tests/first_layer.rs create mode 100644 crates/zephium-map/tests/fixtures/first-layer.html create mode 100644 crates/zephium-map/tests/fixtures/heading-sitelinks.html create mode 100644 crates/zephium-map/tests/key.rs create mode 100644 crates/zephium-map/tests/query.rs create mode 100644 crates/zephium-map/tests/reference.rs diff --git a/Cargo.lock b/Cargo.lock index 4b8866c43..2b6d4b31b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7826,6 +7826,19 @@ dependencies = [ "zephium-core", ] +[[package]] +name = "zephium-map" +version = "0.1.0" +dependencies = [ + "encoding_rs", + "html5ever 0.39.0", + "proptest", + "psl", + "thiserror 2.0.18", + "url", + "zephium-core", +] + [[package]] name = "zephium-mcp" version = "0.1.0" diff --git a/crates/zephium-map/Cargo.toml b/crates/zephium-map/Cargo.toml new file mode 100644 index 000000000..c20e96ba9 --- /dev/null +++ b/crates/zephium-map/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "zephium-map" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +html5ever = "=0.39.0" +encoding_rs = "=0.8.41" +psl = "=2.1.220" +thiserror.workspace = true +url.workspace = true +zephium-core.workspace = true + +[dev-dependencies] +proptest.workspace = true diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs new file mode 100644 index 000000000..c91dfc7c3 --- /dev/null +++ b/crates/zephium-map/src/doc.rs @@ -0,0 +1,312 @@ +use crate::key::{check_url, KeyError, MAX_URL_BYTES}; +use thiserror::Error; +use url::Url; + +mod html; + +pub const MAX_INPUT_BYTES: usize = 4 * 1024 * 1024; +pub const MAX_ARENA_ELEMENTS: usize = 131_072; +pub const MAX_ARENA_DEPTH: usize = 128; +pub const MAX_ARENA_TEXT_BYTES: usize = 1024 * 1024; +pub const MAX_NODES: usize = 16_384; +pub const MAX_DEPTH: usize = 64; +pub const MAX_TEXT_BYTES: usize = 512 * 1024; +pub const MAX_NODE_TEXT_BYTES: usize = 8192; +pub const MAX_HEAD_ITEMS: usize = 16; + +#[derive(Clone, Copy)] +pub struct DocLimits { + pub input_bytes: usize, + pub arena_elements: usize, + pub arena_depth: usize, + pub arena_text_bytes: usize, + pub nodes: usize, + pub depth: usize, + pub text_bytes: usize, + pub node_text_bytes: usize, + pub url_bytes: usize, +} +impl Default for DocLimits { + fn default() -> Self { + Self { + input_bytes: MAX_INPUT_BYTES, + arena_elements: MAX_ARENA_ELEMENTS, + arena_depth: MAX_ARENA_DEPTH, + arena_text_bytes: MAX_ARENA_TEXT_BYTES, + nodes: MAX_NODES, + depth: MAX_DEPTH, + text_bytes: MAX_TEXT_BYTES, + node_text_bytes: MAX_NODE_TEXT_BYTES, + url_bytes: MAX_URL_BYTES, + } + } +} +impl DocLimits { + pub const RESULTS: Self = Self { + input_bytes: 2 * 1024 * 1024, + arena_elements: 64 * 1024, + arena_depth: 96, + arena_text_bytes: 512 * 1024, + nodes: 8192, + depth: 48, + text_bytes: 192 * 1024, + node_text_bytes: 4096, + url_bytes: MAX_URL_BYTES, + }; + pub const SITE_PAGE: Self = Self { + input_bytes: 7 * 512 * 1024, + arena_elements: 96 * 1024, + arena_depth: 112, + arena_text_bytes: 768 * 1024, + nodes: 12 * 1024, + depth: 56, + text_bytes: 320 * 1024, + node_text_bytes: 6144, + url_bytes: MAX_URL_BYTES, + }; + pub const ARTICLE: Self = Self { + arena_elements: 80 * 1024, + nodes: 10 * 1024, + arena_text_bytes: 896 * 1024, + text_bytes: 448 * 1024, + node_text_bytes: 7168, + ..Self::SITE_PAGE + }; + + fn validate(self) -> Result { + if self.input_bytes > MAX_INPUT_BYTES + || self.arena_elements > MAX_ARENA_ELEMENTS + || self.arena_depth > MAX_ARENA_DEPTH + || self.arena_text_bytes > MAX_ARENA_TEXT_BYTES + || self.nodes > MAX_NODES + || self.depth > MAX_DEPTH + || self.text_bytes > MAX_TEXT_BYTES + || self.node_text_bytes > MAX_NODE_TEXT_BYTES + || self.url_bytes > MAX_URL_BYTES + { + Err(DocError::Limits) + } else { + Ok(self) + } + } +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum DocError { + #[error("limits exceed hard ceiling")] + Limits, + #[error("input exceeds parser budget")] + Input, + #[error("invalid document order or parent")] + Parent, + #[error("node count exceeds limit")] + Nodes, + #[error("depth exceeds limit")] + Depth, + #[error("text exceeds limit")] + Text, + #[error("invalid field for node role")] + Role, + #[error(transparent)] + Url(#[from] KeyError), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Landmark { + Main, + Navigation, + Banner, + Contentinfo, + Complementary, + Search, + Region, + Form, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + Document, + Group, + Landmark(Option), + Heading(Option), + Paragraph, + Text, + CodeBlock, + Link, + Image, + List, + ListItem, + Table, + Row, + Cell, + CellHeader, + Button, + Textbox, + Password, + Searchbox, + Checkbox, + Radio, + Combobox, + Listbox, + Option, + Spinbutton, + Slider, + Tab, + MenuItem, + Dialog, + Progress, + Status, + FrameBoundary, +} + +pub struct Node { + pub role: Role, + pub parent: Option, + pub name: String, + pub text: String, + pub destination: Option, + pub image_source: Option, + pub hidden: bool, + pub sponsored: bool, + pub element_id: Option, +} +impl Node { + pub fn accessible_name(&self) -> &str { + if self.name.is_empty() && matches!(self.role, Role::Heading(_) | Role::Link | Role::Button) + { + &self.text + } else { + &self.name + } + } + pub fn new(role: Role, parent: Option) -> Self { + Self { + role, + parent, + name: String::new(), + text: String::new(), + destination: None, + image_source: None, + hidden: false, + sponsored: false, + element_id: None, + } + } +} + +#[derive(Default)] +pub struct Head { + pub truncated: bool, + pub title: String, + pub canonical: Option, + pub site_name: String, + pub alternates: Vec, + pub linked_data: Vec, +} +pub struct Alternate { + pub url: Url, + pub media_type: String, + pub language: String, + pub title: String, +} + +pub struct Doc { + page: Url, + nodes: Vec, + head: Head, + truncated: bool, +} +impl Doc { + pub fn page(&self) -> &Url { + &self.page + } + pub fn nodes(&self) -> &[Node] { + &self.nodes + } + pub fn head(&self) -> &Head { + &self.head + } + pub fn truncated(&self) -> bool { + self.head.truncated || self.body_truncated() + } + pub fn body_truncated(&self) -> bool { + self.truncated + } +} + +pub struct DocBuilder { + doc: Doc, + limits: DocLimits, + text_bytes: usize, + path: Vec, +} +impl DocBuilder { + pub fn new(page: &Url, limits: DocLimits) -> Result { + let limits = limits.validate()?; + check_url(page, limits.url_bytes)?; + Ok(Self { + doc: Doc { + page: page.clone(), + nodes: Vec::new(), + head: Head::default(), + truncated: false, + }, + limits, + text_bytes: 0, + path: Vec::new(), + }) + } + + pub fn mark_truncated(&mut self) { + self.doc.truncated = true; + } + + pub fn push(&mut self, node: Node) -> Result { + let index = self.doc.nodes.len(); + if index >= self.limits.nodes { + return Err(DocError::Nodes); + } + let level = match node.parent { + None => 0, + Some(parent) => { + self.path + .iter() + .rposition(|&at| at == parent) + .ok_or(DocError::Parent)? + + 1 + } + }; + if level >= self.limits.depth { + return Err(DocError::Depth); + } + if matches!(node.role, Role::Heading(Some(n)) if !(1..=6).contains(&n)) + || node.destination.is_some() && node.role != Role::Link + || node.image_source.is_some() && node.role != Role::Image + { + return Err(DocError::Role); + } + for url in [&node.destination, &node.image_source] + .into_iter() + .flatten() + { + check_url(url, self.limits.url_bytes)?; + } + let size = node + .name + .len() + .saturating_add(node.text.len()) + .saturating_add(node.element_id.as_deref().map_or(0, str::len)); + if size > self.limits.node_text_bytes || size > self.limits.text_bytes - self.text_bytes { + return Err(DocError::Text); + } + self.text_bytes += size; + self.path.truncate(level); + self.path.push(index); + self.doc.nodes.push(node); + Ok(index) + } + + pub fn finish(self) -> Doc { + self.doc + } +} diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs new file mode 100644 index 000000000..5e760e775 --- /dev/null +++ b/crates/zephium-map/src/doc/html.rs @@ -0,0 +1,516 @@ +use super::*; +use arena::NodeRef; +use std::borrow::Cow; +mod arena; +mod decode; +mod sink; + +const GENERIC_TEXT_CHILDREN: usize = 8; + +impl Doc { + pub fn from_html( + page: &Url, + bytes: &[u8], + charset_label: Option<&str>, + limits: DocLimits, + ) -> Result { + let mut builder = DocBuilder::new(page, limits)?; + if bytes.len() > limits.input_bytes { + return Err(DocError::Input); + } + let dom = decode::parse(bytes, charset_label, limits); + let mut base = page.clone(); + let Some(root) = dom + .node(0) + .children() + .find(|n| tag_is(n, "html") && !hidden(n)) + else { + builder.doc.truncated |= dom.stopped || dom.lifted; + return Ok(builder.finish()); + }; + if let Some(head) = root.children().find(|n| tag_is(n, "head") && !hidden(n)) { + if let Some(element) = head + .children() + .find(|n| tag_is(n, "base") && !hidden(n) && n.has_attr("href")) + { + if let Some(url) = builder + .resolve(&element, "href", page) + .filter(|u| u.origin() == page.origin()) + { + base = url; + } + } + if builder.doc.truncated { + return Err(DocError::Url(KeyError::UrlLength)); + } + for n in head.children().filter(|n| !n.is_text() && !hidden(n)) { + builder.head_element(&n, &base); + } + builder.doc.head.truncated = std::mem::take(&mut builder.doc.truncated); + } + let body = root.children().find(|n| tag_is(n, "body")).or_else(|| { + (dom.lifted && limits.arena_depth == 1) + .then(|| dom.node(0).children().find(|n| tag_is(n, "body"))) + .flatten() + }); + if let Some(body) = body { + builder.walk(body, &base)?; + } + builder.doc.truncated |= dom.stopped || dom.lifted; + Ok(builder.finish()) + } +} + +fn tag_is(node: &NodeRef, tag: &str) -> bool { + node.tag() == tag +} +fn hidden(n: &NodeRef) -> bool { + n.hidden_by_lift() + || n.has_attr("hidden") + || n.attr("aria-hidden") + .is_some_and(|v| v.eq_ignore_ascii_case("true")) + || tag_is(n, "input") + && n.attr("type") + .is_some_and(|v| v.eq_ignore_ascii_case("hidden")) +} + +impl DocBuilder { + fn resolve(&mut self, node: &NodeRef, attr: &str, base: &Url) -> Option { + let raw = node.attr(attr)?; + if node.clipped(attr) || raw.len() > self.limits.url_bytes { + self.mark_truncated(); + return None; + } + if raw.trim().is_empty() { + return None; + } + let url = base.join(raw).ok()?; + match check_url(&url, self.limits.url_bytes) { + Ok(()) => Some(url), + Err(KeyError::UrlLength) => { + self.mark_truncated(); + None + } + Err(_) => None, + } + } + + fn bounded_prefix<'a>(&mut self, value: &'a str, room: usize) -> &'a str { + let end = value.floor_char_boundary(room.min(self.limits.text_bytes - self.text_bytes)); + if end < value.len() { + self.mark_truncated(); + } + &value[..end] + } + + fn head_text(&mut self, value: &str, room: usize) -> String { + let text = self.bounded_prefix(value, room); + self.text_bytes += text.len(); + text.to_owned() + } + + fn head_element(&mut self, node: &NodeRef, base: &Url) { + let limit = self.limits.node_text_bytes; + if node.loss() { + self.mark_truncated(); + } + match node.tag() { + "title" if self.doc.head.title.is_empty() => { + let raw = node + .children() + .find(|c| c.is_text()) + .map_or("", |c| c.text()); + let value = self.words(raw); + self.doc.head.title = self.head_text(&value, limit); + } + "meta" + if self.doc.head.site_name.is_empty() + && node + .attr("property") + .is_some_and(|v| v.eq_ignore_ascii_case("og:site_name")) => + { + if let Some(value) = node.attr("content") { + let text = self.words(value); + self.doc.head.site_name = self.head_text(&text, limit); + } + } + "link" => { + let rel = node.attr("rel").unwrap_or_default(); + let has = |word: &str| { + rel.split_ascii_whitespace() + .any(|v| v.eq_ignore_ascii_case(word)) + }; + if has("canonical") && self.doc.head.canonical.is_none() { + self.doc.head.canonical = self.resolve(node, "href", base); + } + if has("alternate") || has("feed") { + if self.doc.head.alternates.len() >= MAX_HEAD_ITEMS { + self.mark_truncated(); + return; + } + if let Some(url) = self.resolve(node, "href", base) { + let mut attr = + |name| self.head_text(node.attr(name).unwrap_or_default(), limit); + let alternate = Alternate { + url, + media_type: attr("type"), + language: attr("hreflang"), + title: attr("title"), + }; + self.doc.head.alternates.push(alternate); + } + } + } + "script" + if node + .attr("type") + .is_some_and(|v| v.trim().eq_ignore_ascii_case("application/ld+json")) => + { + let raw = node + .children() + .find(|c| c.is_text()) + .map_or("", |c| c.text()); + if node.loss() + || self.doc.head.linked_data.len() >= MAX_HEAD_ITEMS + || raw.len() > limit.min(self.limits.text_bytes - self.text_bytes) + { + self.mark_truncated(); + } else { + self.text_bytes += raw.len(); + self.doc.head.linked_data.push(raw.to_string()); + } + } + _ => (), + } + } + + fn append(&mut self, at: usize, raw: &str, verbatim: bool) { + let node = &self.doc.nodes[at]; + let room = self.limits.node_text_bytes + - node.text.len() + - node.name.len() + - node.element_id.as_deref().map_or(0, str::len); + let separator = !verbatim && !node.text.is_empty(); + let room = room.min(self.limits.text_bytes - self.text_bytes); + let extra = usize::from(separator); + let end = raw.floor_char_boundary(room.saturating_sub(extra)); + if end < raw.len() { + self.mark_truncated(); + } + if end > 0 { + self.text_bytes += extra + end; + let dest = &mut self.doc.nodes[at].text; + if separator { + dest.push(' '); + } + dest.push_str(&raw[..end]); + } + } + + fn words(&mut self, raw: &str) -> String { + let mut out = String::new(); + let cap = self + .limits + .node_text_bytes + .min(self.limits.text_bytes - self.text_bytes); + for word in raw + .split(|c: char| c.is_control() || c.is_whitespace()) + .filter(|word| !word.is_empty()) + { + let gap = usize::from(!out.is_empty()); + let end = word.floor_char_boundary(cap.saturating_sub(out.len() + gap)); + if end != 0 { + if gap != 0 { + out.push(' ') + } + out.push_str(&word[..end]); + } + if end < word.len() { + self.mark_truncated(); + break; + } + } + out + } + + fn capture_text( + &mut self, + parent: Option, + raw: &str, + verbatim: bool, + level: usize, + ) -> Result<(), DocError> { + let mut ancestor = parent; + let words = if verbatim { + Cow::Borrowed(raw) + } else { + Cow::Owned(self.words(raw)) + }; + if words.is_empty() { + return Ok(()); + } + let mut captured = false; + let mut inline = false; + let mut prose = false; + while let Some(at) = ancestor { + let n = &self.doc.nodes[at]; + ancestor = n.parent; + let takes_prose = matches!( + n.role, + Role::Paragraph + | Role::ListItem + | Role::Document + | Role::Cell + | Role::CellHeader + | Role::CodeBlock + ); + if n.role == Role::Text && !inline + || !prose && takes_prose + || matches!(n.role, Role::Heading(_) | Role::Link | Role::Button) + { + captured = true; + self.append(at, &words, verbatim); + } + inline |= self.doc.nodes[at].role == Role::Text; + prose |= takes_prose; + } + if !captured { + let (parent, _) = self.fit_parent(parent, level); + match self.push(Node::new(Role::Text, parent)) { + Ok(at) => self.append(at, &words, verbatim), + Err(DocError::Nodes | DocError::Depth) => self.mark_truncated(), + Err(e) => return Err(e), + } + } + Ok(()) + } + + fn fit_parent(&mut self, parent: Option, level: usize) -> (Option, usize) { + if level >= self.limits.depth { + self.mark_truncated(); + ( + parent.and_then(|at| self.doc.nodes[at].parent), + level.saturating_sub(1), + ) + } else { + (parent, level) + } + } + + fn walk(&mut self, body: NodeRef<'_>, base: &Url) -> Result<(), DocError> { + let mut pending = vec![(body, None, 0, false)]; + while let Some((n, parent, level, verbatim)) = pending.pop() { + if let Some(next) = n.sibling() { + pending.push((next, parent, level, verbatim)); + } + if n.is_text() { + self.capture_text(parent, n.text(), verbatim, level)?; + continue; + } + if self.doc.nodes.len() >= self.limits.nodes || self.limits.depth == 0 { + self.mark_truncated(); + continue; + } + if hidden(&n) + || matches!( + n.tag(), + "script" | "style" | "template" | "noscript" | "svg" | "head" + ) + { + continue; + } + if n.loss() { + self.mark_truncated() + } + let in_sink = + std::iter::successors(parent, |&at| self.doc.nodes[at].parent).any(|at| { + matches!( + self.doc.nodes[at].role, + Role::Heading(_) + | Role::Link + | Role::Button + | Role::Paragraph + | Role::ListItem + | Role::Document + | Role::CodeBlock + ) + }); + let role = + classify(&n, n.tag(), in_sink).filter(|r| !(verbatim && *r == Role::CodeBlock)); + let (parent, level) = if let Some(role) = role { + let (parent, level) = self.fit_parent(parent, level); + let mut node = Node::new(role, parent); + node.sponsored = ["data-layout", "data-type", "data-testid"] + .iter() + .any(|attr| n.attr(attr).is_some_and(|v| v.eq_ignore_ascii_case("ad"))) + || n.attr("rel").is_some_and(|v| { + v.split_ascii_whitespace() + .any(|w| w.eq_ignore_ascii_case("sponsored")) + }) + || n.attr("class") + .is_some_and(|v| v.split_ascii_whitespace().any(|w| w == "b_ad")); + + if role == Role::Link { + node.destination = self.resolve(&n, "href", base); + } + if role == Role::Image { + node.image_source = self.resolve(&n, "src", base); + } + let name = n + .attr("aria-label") + .filter(|v| !v.is_empty()) + .or_else(|| (role == Role::Image).then(|| n.attr("alt")).flatten()); + if let Some(name) = name { + node.name = self.words(name); + } + if let Some(id) = n.attr("id") { + if !n.clipped("id") + && id.len() + <= self + .limits + .node_text_bytes + .min(self.limits.text_bytes - self.text_bytes) + - node.name.len() + { + node.element_id = Some(id.to_string()); + } else { + self.mark_truncated(); + } + } + (Some(self.push(node)?), level + 1) + } else { + (parent, level) + }; + if let Some(child) = n.children().next() { + pending.push(( + child, + parent, + level, + verbatim || matches!(n.tag(), "pre" | "code"), + )); + } + } + Ok(()) + } +} + +fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option { + use super::Landmark as L; + use Role::*; + if let Some(raw) = n.attr("role") { + for token in raw.to_ascii_lowercase().split_ascii_whitespace() { + return Some(match token { + "none" | "presentation" => return None, + "group" | "figure" => Group, + "document" | "article" => Document, + "heading" => Heading(Some( + n.attr("aria-level") + .and_then(|v| v.parse().ok()) + .filter(|v| (1..=6).contains(v)) + .unwrap_or(2), + )), + "main" => Landmark(Some(L::Main)), + "navigation" => Landmark(Some(L::Navigation)), + "banner" => Landmark(Some(L::Banner)), + "contentinfo" => Landmark(Some(L::Contentinfo)), + "form" => Landmark(Some(L::Form)), + "complementary" => Landmark(Some(L::Complementary)), + "region" => Landmark(Some(L::Region)), + "search" => Landmark(Some(L::Search)), + "paragraph" => Paragraph, + "link" => Link, + "button" => Button, + "dialog" | "alertdialog" => Dialog, + "list" | "feed" => List, + "listitem" => ListItem, + "img" => Image, + "table" | "grid" => Table, + "row" => Row, + "cell" | "gridcell" => Cell, + "rowheader" | "columnheader" => CellHeader, + "textbox" => Textbox, + "searchbox" => Searchbox, + "checkbox" => Checkbox, + "radio" => Radio, + "combobox" => Combobox, + "listbox" => Listbox, + "option" => Role::Option, + "spinbutton" => Spinbutton, + "slider" => Slider, + "tab" => Tab, + "menuitem" => MenuItem, + "progressbar" => Progress, + "status" | "alert" => Status, + _ => continue, + }); + } + } + Some(match tag { + "span" | "small" + if n.children() + .any(|child| child.is_text() && !child.text().trim().is_empty()) => + { + Text + } + "body" | "div" + if !in_sink + && n.children() + .take(GENERIC_TEXT_CHILDREN) + .any(|c| c.is_text() && !c.text().trim().is_empty()) => + { + Paragraph + } + "body" | "div" | "fieldset" | "details" | "figure" => Group, + "article" => Document, + "main" => Landmark(Some(L::Main)), + "nav" => Landmark(Some(L::Navigation)), + "header" => Landmark(Some(L::Banner)), + "footer" => Landmark(Some(L::Contentinfo)), + "aside" => Landmark(Some(L::Complementary)), + "search" => Landmark(Some(L::Search)), + "section" | "form" + if ["aria-label", "aria-labelledby", "title"] + .iter() + .any(|k| n.has_attr(k)) => + { + Landmark(Some(if tag == "section" { L::Region } else { L::Form })) + } + "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => Heading(tag[1..].parse().ok()), + "p" | "blockquote" | "dt" | "dd" => Paragraph, + "pre" | "code" => CodeBlock, + "a" if n.has_attr("href") => Link, + "img" => Image, + "button" | "summary" => Button, + "input" => match n + .attr("type") + .unwrap_or_default() + .to_ascii_lowercase() + .as_str() + { + "search" => Searchbox, + "submit" | "button" | "reset" => Button, + "checkbox" => Checkbox, + "radio" => Radio, + "password" => Password, + "number" => Spinbutton, + "range" => Slider, + _ => Textbox, + }, + "textarea" => Textbox, + "select" => Combobox, + "option" => Role::Option, + "ul" | "ol" | "menu" => List, + "li" => ListItem, + "dialog" => Dialog, + "table" => Table, + "tr" => Row, + "td" => Cell, + "th" => CellHeader, + "progress" => Progress, + "iframe" => FrameBoundary, + _ => return None, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs new file mode 100644 index 000000000..65d9a3f1a --- /dev/null +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -0,0 +1,536 @@ +use super::DocLimits; +use html5ever::{local_name, ns, tendril::StrTendril, Attribute, LocalName}; + +// Zero is both the document handle and the null link. The document is never a child. +pub(super) type Id = u32; +pub(super) const IGNORED: Id = Id::MAX; +const TEXT: u8 = 1; +const OPAQUE: u8 = 2; +const NO_TEXT: u8 = 4; +const LOSS: u8 = 8; +const JSON: u8 = 16; +const HIDDEN_BY_LIFT: u8 = 32; +const ATTACHED: u8 = 64; +const ATTRIBUTE_NAMES: &[&str] = &[ + "href", + "src", + "role", + "aria-level", + "aria-hidden", + "aria-label", + "hidden", + "id", + "type", + "rel", + "name", + "property", + "content", + "charset", + "http-equiv", + "title", + "alt", + "itemprop", + "itemtype", + "datetime", + "class", + "data-layout", + "data-type", + "data-testid", + "aria-labelledby", + "hreflang", +]; +const ATTRIBUTES_PER_ELEMENT_BUDGET: usize = 4; + +#[derive(Default)] +struct Record { + tag: LocalName, + parent: Id, + first: Id, + last: Id, + prev: Id, + next: Id, + // Head of the attribute chain, or index into text runs. + data: u32, + depth: u8, + flags: u8, +} + +struct Attr { + next: u32, + start: u32, + len: u16, + key: u8, + clipped: bool, +} + +// Grow by separate slabs so a large page never reallocates and copies its full record array. +const SLAB_ITEMS: usize = 512; +struct Slabs { + chunks: Vec>, + len: usize, +} +impl Slabs { + fn new() -> Self { + Self { + chunks: Vec::new(), + len: 0, + } + } + fn len(&self) -> usize { + self.len + } + fn push(&mut self, item: T) { + let slot = self.len / SLAB_ITEMS; + if slot == self.chunks.len() { + self.chunks.push(if slot == 0 { + Vec::new() + } else { + Vec::with_capacity(SLAB_ITEMS) + }); + } + self.chunks[slot].push(item); + self.len += 1; + } +} +impl std::ops::Index for Slabs { + type Output = T; + fn index(&self, i: usize) -> &T { + &self.chunks[i / SLAB_ITEMS][i % SLAB_ITEMS] + } +} +impl std::ops::IndexMut for Slabs { + fn index_mut(&mut self, i: usize) -> &mut T { + &mut self.chunks[i / SLAB_ITEMS][i % SLAB_ITEMS] + } +} + +pub(super) struct Arena { + records: Slabs, + attributes: Slabs, + values: String, + runs: Slabs, + elements: usize, + bytes: usize, + limits: DocLimits, + pub(super) saw_table: bool, + pub(super) stopped: bool, + pub(super) lifted: bool, +} + +#[derive(Clone, Copy)] +pub(super) struct NodeRef<'a> { + arena: &'a Arena, + id: Id, +} + +impl<'a> NodeRef<'a> { + fn record(self) -> &'a Record { + &self.arena.records[self.id as usize] + } + pub(super) fn tag(self) -> &'a str { + &self.record().tag + } + pub(super) fn is_text(self) -> bool { + self.record().flags & TEXT != 0 + } + pub(super) fn text(self) -> &'a str { + if self.is_text() { + &self.arena.runs[self.record().data as usize] + } else { + "" + } + } + pub(super) fn loss(self) -> bool { + self.record().flags & LOSS != 0 + } + pub(super) fn hidden_by_lift(self) -> bool { + self.record().flags & HIDDEN_BY_LIFT != 0 + } + pub(super) fn sibling(self) -> Option { + let next = self.record().next; + (next != 0).then_some(self.arena.node(next)) + } + pub(super) fn children(self) -> impl Iterator { + let first = self.record().first; + std::iter::successors((first != 0).then_some(self.arena.node(first)), |n| { + let next = n.record().next; + (next != 0).then_some(self.arena.node(next)) + }) + } + fn attribute(self, key: &str) -> Option<&'a Attr> { + if self.is_text() { + return None; + } + let mut i = self.record().data; + while i != 0 { + let attr = &self.arena.attributes[(i - 1) as usize]; + if ATTRIBUTE_NAMES[attr.key as usize] == key { + return Some(attr); + } + i = attr.next; + } + None + } + pub(super) fn attr(self, key: &str) -> Option<&'a str> { + let attr = self.attribute(key)?; + let start = attr.start as usize; + Some(&self.arena.values[start..start + usize::from(attr.len)]) + } + pub(super) fn clipped(self, key: &str) -> bool { + self.attribute(key).is_some_and(|a| a.clipped) + } + pub(super) fn has_attr(self, key: &str) -> bool { + self.attribute(key).is_some() + } +} + +impl Arena { + pub(super) fn new(limits: DocLimits) -> Self { + let mut records = Slabs::new(); + records.push(Record::default()); + Self { + records, + attributes: Slabs::new(), + values: String::new(), + runs: Slabs::new(), + bytes: 0, + elements: 0, + saw_table: false, + stopped: false, + lifted: false, + limits, + } + } + pub(super) fn node(&self, id: Id) -> NodeRef<'_> { + NodeRef { arena: self, id } + } + pub(super) fn create(&mut self, tag: &LocalName, attrs: Vec) -> Id { + if self.stopped || self.elements >= self.limits.arena_elements { + self.stopped = true; + return IGNORED; + } + self.elements += 1; + self.saw_table |= tag.as_ref() == "table"; + let id = self.records.len() as Id; + // The tree builder's live handles keep exact names. Unknown names have no role. + self.records.push(Record { + tag: if !tag.is_dynamic() { + tag.clone() + } else { + local_name!("") + }, + flags: if matches!( + tag.as_ref(), + "script" | "style" | "template" | "svg" | "noscript" + ) { + OPAQUE + } else { + 0 + }, + ..Default::default() + }); + self.add_attrs(id, attrs); + if tag.as_ref() == "script" + && self + .node(id) + .attr("type") + .is_some_and(|v| v.trim().eq_ignore_ascii_case("application/ld+json")) + { + self.records[id as usize].flags = (self.records[id as usize].flags & !OPAQUE) | JSON; + } + id + } + pub(super) fn add_attrs(&mut self, id: Id, attrs: Vec) { + if self.stopped || id == IGNORED { + return; + } + for attr in attrs { + if attr.name.ns != ns!() { + continue; + } + let name = attr.name.local.as_ref(); + let Some(key) = ATTRIBUTE_NAMES.iter().position(|&k| k == name) else { + continue; + }; + if self.node(id).has_attr(name) { + continue; + } + if self.attributes.len() >= self.limits.arena_elements * ATTRIBUTES_PER_ELEMENT_BUDGET { + self.stopped = true; + break; + } + let cap = match name { + "href" | "src" => self.limits.url_bytes, + _ => super::MAX_NODE_TEXT_BYTES, + }; + let len = attr.value.floor_char_boundary(cap); + if len > self.limits.arena_text_bytes - self.bytes { + self.stopped = true; + break; + } + let clipped = len < attr.value.len(); + let n = &mut self.records[id as usize]; + if clipped { + n.flags |= LOSS + } + self.attributes.push(Attr { + next: n.data, + start: self.values.len() as u32, + len: len as u16, + key: key as u8, + clipped, + }); + n.data = self.attributes.len() as u32; + self.values.push_str(&attr.value[..len]); + self.bytes += len; + } + } + pub(super) fn detach(&mut self, id: Id) { + let n = &self.records[id as usize]; + let (parent, prev, next) = (n.parent, n.prev, n.next); + if prev != 0 { + self.records[prev as usize].next = next + } else if self.records[parent as usize].first == id { + self.records[parent as usize].first = next + } + if next != 0 { + self.records[next as usize].prev = prev + } else if self.records[parent as usize].last == id { + self.records[parent as usize].last = prev + } + let n = &mut self.records[id as usize]; + n.flags &= !ATTACHED; + n.parent = 0; + n.next = 0; + n.prev = 0; + } + pub(super) fn parent(&self, id: Id) -> Id { + self.records[id as usize].parent + } + pub(super) fn attached_parent(&self, id: Id) -> Option { + (id != IGNORED && self.records[id as usize].flags & ATTACHED != 0).then(|| self.parent(id)) + } + + pub(super) fn move_children(&mut self, from: Id, to: Id) { + if from == IGNORED || to == IGNORED { + return; + } + let last = self.records[from as usize].last; + let mut child = self.first(from); + while child != 0 && !self.stopped { + let next = self.records[child as usize].next; + self.insert(child, to, 0); + if child == last { + break; + } + child = next; + } + } + + fn first(&self, id: Id) -> Id { + self.records[id as usize].first + } + + pub(super) fn insert(&mut self, id: Id, mut parent: Id, mut before: Id) { + if self.stopped || id == IGNORED || parent == IGNORED { + return; + } + if self.limits.arena_depth == 0 { + self.stopped = true; + return; + } + let p = &self.records[parent as usize]; + let no_text = p.flags & (OPAQUE | NO_TEXT) != 0; + let mut hidden = p.flags & HIDDEN_BY_LIFT != 0; + if usize::from(p.depth) >= self.limits.arena_depth + && self.records[id as usize].flags & TEXT == 0 + { + self.lifted = true; + hidden |= super::hidden(&self.node(parent)) || no_text; + parent = p.parent; + before = 0; + } + if id == parent || id == before { + self.stopped = true; + return; + } + if self.first(id) != 0 { + let mut ancestor = parent; + while ancestor != 0 { + if ancestor == id { + self.stopped = true; + return; + } + ancestor = self.parent(ancestor); + } + } + self.detach(id); + let prev = if before == 0 { + self.records[parent as usize].last + } else { + self.records[before as usize].prev + }; + if prev != 0 { + self.records[prev as usize].next = id + } else { + self.records[parent as usize].first = id + } + if before != 0 { + self.records[before as usize].prev = id + } else { + self.records[parent as usize].last = id + } + let depth = self.records[parent as usize].depth + 1; + let n = &mut self.records[id as usize]; + n.parent = parent; + n.prev = prev; + n.next = before; + n.depth = depth; + n.flags = (n.flags & !(NO_TEXT | HIDDEN_BY_LIFT)) | ATTACHED; + if no_text { + n.flags |= NO_TEXT + } + if hidden { + n.flags |= HIDDEN_BY_LIFT + } + // Children may already exist during adoption-agency moves. Reapply depth and context. + if n.first != 0 { + self.move_children(id, id) + } + } + pub(super) fn text(&mut self, parent: Id, before: Id, value: &str) { + if self.stopped || parent == IGNORED || value.is_empty() { + return; + } + let p = &self.records[parent as usize]; + if p.flags & (OPAQUE | NO_TEXT) != 0 { + return; + } + let prev = if before == 0 { + p.last + } else { + self.records[before as usize].prev + }; + let existing = prev != 0 && self.node(prev).is_text(); + let mut length = value.len(); + if p.flags & JSON != 0 { + let used = if existing { + self.node(prev).text().len() + } else { + 0 + }; + let json_room = self.limits.node_text_bytes.saturating_sub(used); + if value.len() > json_room { + self.records[parent as usize].flags |= LOSS + } + length = length.min(json_room); + } + let room = self.limits.arena_text_bytes - self.bytes; + let len = value.floor_char_boundary(room.min(length)); + if len == 0 { + self.stopped |= length > room; + return; + } + if existing { + let run = self.records[prev as usize].data as usize; + self.runs[run].push_slice(&value[..len]); + } else { + if self.runs.len() > self.limits.arena_elements { + self.stopped = true; + return; + } + let id = self.records.len() as Id; + self.records.push(Record { + data: self.runs.len() as u32, + flags: TEXT, + ..Default::default() + }); + self.runs.push(StrTendril::from_slice(&value[..len])); + self.insert(id, parent, before); + } + self.bytes += len; + self.stopped |= length > room; + } +} + +#[cfg(test)] +impl Arena { + pub(super) fn element_count(&self) -> usize { + self.elements + } +} + +#[cfg(test)] +mod tests { + use super::*; + use html5ever::QualName; + + #[test] + fn record_layout_and_capacity() { + assert_eq!(std::mem::size_of::(), 40); + assert_eq!(std::mem::size_of::(), 12); + assert_eq!(std::mem::size_of::(), 16); + } + + #[test] + fn metadata_and_text_slots_have_independent_budgets() { + let limits = DocLimits { + arena_elements: 1, + ..Default::default() + }; + let attr = |name: &str| Attribute { + name: QualName::new(None, ns!(), LocalName::from(name)), + value: "".into(), + }; + let mut arena = Arena::new(limits); + let id = arena.create( + &local_name!("p"), + ATTRIBUTE_NAMES[..ATTRIBUTES_PER_ELEMENT_BUDGET] + .iter() + .map(|name| attr(name)) + .collect(), + ); + assert!(!arena.stopped); + arena.add_attrs( + id, + vec![attr(ATTRIBUTE_NAMES[ATTRIBUTES_PER_ELEMENT_BUDGET])], + ); + assert!(arena.stopped); + assert_eq!(arena.attributes.len(), ATTRIBUTES_PER_ELEMENT_BUDGET); + + let mut arena = Arena::new(limits); + let id = arena.create(&local_name!("div"), Vec::new()); + for _ in 0..=limits.arena_elements { + arena.text(id, 0, "t"); + assert!(!arena.stopped); + arena.detach(arena.first(id)); + } + arena.text(id, 0, "t"); + assert!(arena.stopped); + assert_eq!(arena.runs.len(), limits.arena_elements + 1); + } + + #[test] + fn large_retained_and_discarded_attributes() { + let huge = "a".repeat(1024 * 1024); + let attr = |name: &str| Attribute { + name: QualName::new(None, ns!(), LocalName::from(name)), + value: huge.as_str().into(), + }; + let mut arena = Arena::new(DocLimits::default()); + let id = arena.create( + &local_name!("p"), + vec![attr("data-unused"), attr("aria-label")], + ); + assert_eq!(arena.attributes.len(), 1); + assert_eq!(arena.values.len(), super::super::MAX_NODE_TEXT_BYTES); + assert!(arena.node(id).clipped("aria-label")); + assert!(!arena.node(id).has_attr("data-unused")); + for name in ["aria-label", "data-unused"] { + let html = format!("

before

after"); + let arena = super::super::decode::parse(html.as_bytes(), None, Default::default()); + assert!(arena.stopped); + assert!(arena.values.len() <= super::super::MAX_NODE_TEXT_BYTES); + } + } +} diff --git a/crates/zephium-map/src/doc/html/decode.rs b/crates/zephium-map/src/doc/html/decode.rs new file mode 100644 index 000000000..a2e084d31 --- /dev/null +++ b/crates/zephium-map/src/doc/html/decode.rs @@ -0,0 +1,372 @@ +use super::{ + arena::Arena, + sink::{Handle, Sink}, + DocLimits, +}; +use encoding_rs::{CoderResult, Encoding, UTF_8}; +use html5ever::{ + buffer_queue::BufferQueue, + tendril::StrTendril, + tokenizer::{Token, TokenSink, TokenSinkResult, Tokenizer}, + tree_builder::{Tracer, TreeBuilder, TreeBuilderOpts, TreeSink}, + TokenizerResult, +}; +use std::cell::Cell; + +pub(super) const CHUNK_BYTES: usize = 4096; +pub(super) const MAX_CHARSET_LABEL_BYTES: usize = 64; +const META_PREFIX_BYTES: usize = 4096; +// html5ever can buffer an unfinished token, foster-parented characters, and live handles +// without issuing any arena allocations. Bound that work independently of the sink. +const MAX_UNFINISHED_TOKEN_BYTES: usize = 64 * 1024; +const MAX_PENDING_TEXT_TOKENS: usize = 4096; +const MAX_LIVE_HANDLES: usize = 512; +const MAX_LIVE_MARKUP_BYTES: usize = super::MAX_ARENA_TEXT_BYTES; + +pub(super) fn charset(label: &[u8]) -> Option<&'static Encoding> { + (label.len() <= MAX_CHARSET_LABEL_BYTES) + .then(|| Encoding::for_label(label)) + .flatten() +} + +fn attrs_charset(mut bytes: &[u8]) -> Option<&'static Encoding> { + let mut content = None; + let mut pragma = None; + let mut direct = None; + while !bytes.is_empty() { + let end = bytes + .iter() + .position(|c| c.is_ascii_whitespace() || matches!(c, b'=' | b'/')) + .unwrap_or(bytes.len()); + if end == 0 { + bytes = &bytes[1..]; + continue; + } + let key = &bytes[..end]; + bytes = bytes[end..].trim_ascii_start(); + let mut value = &[][..]; + if let Some(rest) = bytes.strip_prefix(b"=") { + bytes = rest.trim_ascii_start(); + if let [quote @ (b'\'' | b'"'), rest @ ..] = bytes { + let end = rest.iter().position(|c| c == quote)?; + value = &rest[..end]; + bytes = &rest[end + 1..]; + } else { + let end = bytes + .iter() + .position(u8::is_ascii_whitespace) + .unwrap_or(bytes.len()); + value = &bytes[..end]; + bytes = &bytes[end..]; + } + } + if key.eq_ignore_ascii_case(b"charset") { + direct.get_or_insert(value); + } + if key.eq_ignore_ascii_case(b"http-equiv") { + pragma.get_or_insert(value); + } + if key.eq_ignore_ascii_case(b"content") { + content.get_or_insert(value); + } + } + if let Some(enc) = direct.and_then(charset) { + return Some(enc); + } + if !pragma?.eq_ignore_ascii_case(b"content-type") { + return None; + } + content?.split(|&c| c == b';').skip(1).find_map(|param| { + let eq = param.iter().position(|&c| c == b'=')?; + if !param[..eq].trim_ascii().eq_ignore_ascii_case(b"charset") { + return None; + } + let label = param[eq + 1..].trim_ascii(); + let label = match label { + [b'\'', v @ .., b'\''] | [b'"', v @ .., b'"'] => v, + _ => label, + }; + charset(label) + }) +} + +fn meta_charset(bytes: &[u8]) -> Option<&'static Encoding> { + let prefix = &bytes[..META_PREFIX_BYTES.min(bytes.len())]; + let mut bytes = prefix.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(prefix); + let mut raw: Option<&[u8]> = None; + let mut templates = 0usize; + while let Some(i) = bytes.iter().position(|&c| c == b'<') { + if raw.is_none() && templates == 0 && !bytes[..i].trim_ascii().is_empty() { + break; + } + bytes = &bytes[i + 1..]; + if let Some(tag) = raw { + let Some(rest) = bytes.strip_prefix(b"/") else { + continue; + }; + if !rest + .get(..tag.len()) + .is_some_and(|v| v.eq_ignore_ascii_case(tag)) + || !rest + .get(tag.len()) + .is_some_and(|v| v.is_ascii_whitespace() || matches!(v, b'>' | b'/')) + { + continue; + } + raw = None; + } + if let Some(comment) = bytes.strip_prefix(b"!--") { + let end = comment.windows(3).position(|w| w == b"-->")?; + bytes = &comment[end + 3..]; + continue; + } + let closing = bytes.starts_with(b"/"); + if closing { + bytes = &bytes[1..] + } + let split = bytes + .iter() + .position(|c| c.is_ascii_whitespace() || matches!(c, b'>' | b'/'))?; + let name = &bytes[..split]; + let rest = &bytes[split..]; + let mut quote = None; + let end = rest.iter().position(|&c| { + if quote == Some(c) { + quote = None + } else if quote.is_none() { + if c == b'>' { + return true; + } + if matches!(c, b'\'' | b'"') { + quote = Some(c) + } + } + false + })?; + bytes = &rest[end + 1..]; + if name.eq_ignore_ascii_case(b"template") { + if closing { + templates = templates.saturating_sub(1) + } else { + templates += 1 + } + } else if closing { + if templates == 0 + && [b"head".as_slice(), b"body", b"html", b"br"] + .iter() + .any(|n| name.eq_ignore_ascii_case(n)) + { + break; + } + } else if [ + b"script".as_slice(), + b"style", + b"title", + b"noscript", + b"noframes", + b"textarea", + ] + .iter() + .any(|t| name.eq_ignore_ascii_case(t)) + { + raw = Some(name); + } else if templates == 0 { + if name.eq_ignore_ascii_case(b"meta") { + if let Some(enc) = attrs_charset(&rest[..end]) { + return Some(enc); + } + } else if ![ + b"html".as_slice(), + b"head", + b"base", + b"basefont", + b"bgsound", + b"link", + b"!doctype", + ] + .iter() + .any(|t| name.eq_ignore_ascii_case(t)) + && !name.starts_with(b"?") + { + break; + } + } + } + None +} + +struct Tokens { + builder: TreeBuilder, + progressed: Cell, + pending_count: Cell, + pending_bytes: Cell, + text_limit: usize, +} +impl TokenSink for Tokens { + type Handle = Handle; + fn process_token(&self, token: Token, line: u64) -> TokenSinkResult { + let sink = &self.builder.sink; + if sink.arena.borrow().stopped { + return TokenSinkResult::Continue; + } + if matches!(token, Token::ParseError(_)) { + return TokenSinkResult::Continue; + } + self.progressed.set(true); + sink.received_text.set(false); + let bytes = match &token { + Token::CharacterTokens(t) => t.len(), + Token::NullCharacterToken => 1, + _ => 0, + }; + let result = self.builder.process_token(token, line); + if bytes == 0 || sink.received_text.get() || !sink.arena.borrow().saw_table { + self.pending_count.set(0); + self.pending_bytes.set(0); + } else { + self.pending_count.set(self.pending_count.get() + 1); + self.pending_bytes.set(self.pending_bytes.get() + bytes); + if self.pending_count.get() > MAX_PENDING_TEXT_TOKENS + || self.pending_bytes.get() > self.text_limit + { + sink.arena.borrow_mut().stopped = true; + } + } + result + } + fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool { + self.builder + .adjusted_current_node_present_but_not_in_html_namespace() + } + fn end(&self) { + self.builder.end() + } +} + +#[derive(Default)] +struct LiveMarkup { + handles: Cell, + bytes: Cell, +} +impl Tracer for LiveMarkup { + type Handle = Handle; + fn trace_handle(&self, handle: &Handle) { + self.handles.set(self.handles.get() + 1); + self.bytes + .set(self.bytes.get().saturating_add(handle.markup_bytes)); + } +} + +pub(super) fn parse(bytes: &[u8], label: Option<&str>, limits: DocLimits) -> Arena { + let enc = label + .and_then(|v| charset(v.as_bytes())) + .or_else(|| meta_charset(bytes)) + .unwrap_or(UTF_8); + let mut decoder = enc.new_decoder_without_bom_handling(); + let sink = Sink::new(Arena::new(limits)); + let builder = TreeBuilder::new( + sink, + TreeBuilderOpts { + scripting_enabled: false, + drop_doctype: true, + ..Default::default() + }, + ); + let tok = Tokenizer::new( + Tokens { + builder, + progressed: Cell::default(), + pending_count: Cell::default(), + pending_bytes: Cell::default(), + text_limit: limits.arena_text_bytes, + }, + Default::default(), + ); + let input = BufferQueue::default(); + let mut decoded = String::with_capacity(CHUNK_BYTES); + let mut unfinished = 0; + let mut chunks = bytes.chunks(CHUNK_BYTES).peekable(); + 'decode: while let Some(mut chunk) = chunks.next() { + let last = chunks.peek().is_none(); + loop { + decoded.clear(); + let (status, read, _) = decoder.decode_to_string(chunk, &mut decoded, last); + chunk = &chunk[read..]; + input.push_back(StrTendril::from_slice(&decoded)); + while !matches!(tok.feed(&input), TokenizerResult::Done) {} + let live = LiveMarkup::default(); + tok.sink.builder.trace_handles(&live); + if tok.sink.progressed.replace(false) { + unfinished = 0 + } + unfinished += decoded.len(); + let mut arena = tok.sink.builder.sink.arena.borrow_mut(); + if unfinished >= MAX_UNFINISHED_TOKEN_BYTES + || live.handles.get() > MAX_LIVE_HANDLES + || live.bytes.get() > MAX_LIVE_MARKUP_BYTES + { + arena.stopped = true + } + if arena.stopped { + break 'decode; + } + if status == CoderResult::InputEmpty { + break; + } + } + } + if !tok.sink.builder.sink.arena.borrow().stopped { + tok.end() + } + tok.sink.builder.sink.finish() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prescan_observes_head_and_quoted_markup() { + let meta = ""; + for markup in [ + format!("

{meta}"), + format!("body text{meta}"), + format!(""), + format!(""), + format!(""), + format!(""), + ] { + assert!(meta_charset(markup.as_bytes()).is_none()) + } + let valid = + format!("hello{meta}"); + assert_eq!(meta_charset(valid.as_bytes()), Some(encoding_rs::SHIFT_JIS)); + } + + #[test] + fn transient_parser_budgets() { + let l = DocLimits::default(); + let large_comment = format!("

end", "x".repeat(MAX_UNFINISHED_TOKEN_BYTES)); + assert!(parse(large_comment.as_bytes(), None, l).stopped); + let short_comment = format!( + "

end", + "x".repeat(MAX_UNFINISHED_TOKEN_BYTES - CHUNK_BYTES) + ); + assert!(!parse(short_comment.as_bytes(), None, l).stopped); + for (count, stopped) in [ + (MAX_PENDING_TEXT_TOKENS, false), + (MAX_PENDING_TEXT_TOKENS + 1, true), + ] { + let deferred = format!("{}
", "&".repeat(count)); + assert_eq!(parse(deferred.as_bytes(), None, l).stopped, stopped); + } + let attr = "x".repeat(CHUNK_BYTES); + let mut formatting = String::new(); + for id in 0..MAX_LIVE_MARKUP_BYTES / (2 * CHUNK_BYTES) { + formatting.push_str(&format!("")); + } + assert!(parse(formatting.as_bytes(), None, l).stopped); + let deep = format!("{}

end", "

".repeat(MAX_LIVE_HANDLES)); + assert!(parse(deep.as_bytes(), None, l).stopped); + } +} diff --git a/crates/zephium-map/src/doc/html/sink.rs b/crates/zephium-map/src/doc/html/sink.rs new file mode 100644 index 000000000..8bb609e76 --- /dev/null +++ b/crates/zephium-map/src/doc/html/sink.rs @@ -0,0 +1,151 @@ +use super::arena::{Arena, Id, IGNORED}; +use html5ever::{ + local_name, ns, + tendril::StrTendril, + tree_builder::{ElementFlags, NodeOrText, QuirksMode, TreeSink}, + Attribute, QualName, +}; +use std::{ + borrow::Cow, + cell::{Cell, RefCell}, +}; + +#[derive(Clone)] +pub(super) struct Handle { + id: Id, + name: QualName, + overflow_id: u32, + pub(super) markup_bytes: usize, + integration: bool, + fragment: bool, +} +impl Handle { + fn plain(id: Id) -> Self { + Self { + id, + name: QualName::new(None, ns!(html), local_name!("")), + overflow_id: 0, + markup_bytes: 0, + integration: false, + fragment: false, + } + } +} + +pub(super) struct Sink { + pub(super) arena: RefCell, + pub(super) received_text: Cell, + overflow_ids: Cell, +} + +impl Sink { + pub(super) fn new(arena: Arena) -> Self { + Self { + arena: RefCell::new(arena), + received_text: Cell::default(), + overflow_ids: Cell::default(), + } + } + + fn insert(&self, parent: Id, before: Id, child: NodeOrText) { + let mut arena = self.arena.borrow_mut(); + match child { + NodeOrText::AppendNode(h) => arena.insert(h.id, parent, before), + NodeOrText::AppendText(text) => { + self.received_text.set(true); + arena.text(parent, before, &text) + } + } + } +} +impl TreeSink for Sink { + type Handle = Handle; + type Output = Arena; + type ElemName<'a> = &'a QualName; + + fn finish(self) -> Arena { + self.arena.into_inner() + } + fn parse_error(&self, _: Cow<'static, str>) {} + fn get_document(&self) -> Handle { + Handle::plain(0) + } + fn elem_name<'a>(&'a self, h: &'a Handle) -> &'a QualName { + &h.name + } + fn create_element(&self, name: QualName, attrs: Vec, flags: ElementFlags) -> Handle { + // html5ever can keep the original tag (including discarded attributes) for reconstruction. + let markup_bytes = name.local.len() + + std::mem::size_of_val(attrs.as_slice()) + + attrs + .iter() + .map(|a| a.name.local.len() + a.value.len()) + .sum::(); + let id = self.arena.borrow_mut().create(&name.local, attrs); + // A single tree-builder step can create several implied elements after the last slot. + let overflow_id = if id == IGNORED { + let next = self.overflow_ids.get() + 1; + self.overflow_ids.set(next); + next + } else { + 0 + }; + Handle { + id, + name, + overflow_id, + markup_bytes, + integration: flags.mathml_annotation_xml_integration_point, + fragment: false, + } + } + fn create_comment(&self, _: StrTendril) -> Handle { + Handle::plain(IGNORED) + } + fn create_pi(&self, _: StrTendril, _: StrTendril) -> Handle { + Handle::plain(IGNORED) + } + fn append(&self, p: &Handle, c: NodeOrText) { + self.insert(p.id, 0, c) + } + fn append_based_on_parent_node(&self, element: &Handle, prev: &Handle, c: NodeOrText) { + let parent = self.arena.borrow().attached_parent(element.id); + if let Some(p) = parent { + self.insert(p, element.id, c) + } else { + self.append(prev, c) + } + } + fn append_doctype_to_document(&self, _: StrTendril, _: StrTendril, _: StrTendril) {} + fn get_template_contents(&self, target: &Handle) -> Handle { + // The ignored template subtree owns the fragment's child list. + Handle { + fragment: true, + ..target.clone() + } + } + fn same_node(&self, x: &Handle, y: &Handle) -> bool { + x.id == y.id && x.overflow_id == y.overflow_id && x.fragment == y.fragment + } + fn set_quirks_mode(&self, _: QuirksMode) {} + fn append_before_sibling(&self, s: &Handle, c: NodeOrText) { + let parent = self.arena.borrow().attached_parent(s.id); + if let Some(p) = parent { + self.insert(p, s.id, c) + } + } + fn add_attrs_if_missing(&self, h: &Handle, attrs: Vec) { + self.arena.borrow_mut().add_attrs(h.id, attrs) + } + fn remove_from_parent(&self, h: &Handle) { + if h.id != IGNORED && !self.arena.borrow().stopped { + self.arena.borrow_mut().detach(h.id) + } + } + fn reparent_children(&self, h: &Handle, p: &Handle) { + self.arena.borrow_mut().move_children(h.id, p.id); + } + fn is_mathml_annotation_xml_integration_point(&self, h: &Handle) -> bool { + h.integration + } +} diff --git a/crates/zephium-map/src/doc/html/tests.rs b/crates/zephium-map/src/doc/html/tests.rs new file mode 100644 index 000000000..050e0c798 --- /dev/null +++ b/crates/zephium-map/src/doc/html/tests.rs @@ -0,0 +1,341 @@ +use super::*; + +#[test] +fn parser_and_charset_boundary() { + let padded = format!( + "{:width$}", + "utf-8", + width = decode::MAX_CHARSET_LABEL_BYTES + ); + assert!(decode::charset(padded.as_bytes()).is_some()); + assert!(decode::charset((padded + " ").as_bytes()).is_none()); +} + +fn document(bytes: &[u8], limits: DocLimits) -> Doc { + Doc::from_html( + &Url::parse("https://example.com/").unwrap(), + bytes, + None, + limits, + ) + .unwrap() +} + +fn large_page() -> String { + const ELEMENTS: usize = 60_000; + const BYTES: usize = 3 * 1024 * 1024; + const LEVELS: usize = 40; + const CARDS: usize = 1000; + const TAIL: &str = "

Final heading

Last link

Final passage

"; + let mut html = String::with_capacity(BYTES); + html.push_str(""); + for _ in 0..LEVELS { + html.push_str("
") + } + for _ in 0..CARDS { + html.push_str("

Result

Read

Summary

") + } + for _ in 0..ELEMENTS - (3 + 2 + 3 + LEVELS + CARDS * 4) { + html.push_str("") + } + for _ in 0..LEVELS { + html.push_str("
") + } + html.push_str(" +
gophoto
"#; + let doc = defaults(html); + assert!(!doc.truncated()); + assert_eq!(doc.head().title, "Some title"); + assert_eq!( + doc.head().canonical.as_ref().unwrap().as_str(), + "https://example.com/resources/page" + ); + assert_eq!(doc.head().site_name, "An Example"); + assert_eq!(doc.head().linked_data, [" { \"name\": \"opaque\" } "]); + let alt = &doc.head().alternates[0]; + assert_eq!(alt.url.path(), "/resources/feed"); + assert_eq!(alt.media_type, "application/rss+xml"); + assert_eq!(alt.language, "en"); + assert_eq!(alt.title, "Recent items"); + assert!(doc.nodes().iter().any(|n| n + .destination + .as_ref() + .is_some_and(|u| u.path() == "/resources/go"))); + assert!(doc.nodes().iter().any(|n| n + .image_source + .as_ref() + .is_some_and(|u| u.path() == "/resources/pic.jpg") + && n.name == "photo")); + for base in [ + "https://other.example/", + "http://example.com/", + "https://example.com:444/", + "https://name@example.com/", + ] { + let doc = defaults(&format!("text")); + assert_eq!( + doc.nodes() + .iter() + .find_map(|n| n.destination.as_ref()) + .unwrap() + .as_str(), + "https://example.com/start/relative" + ); + } +} +#[test] +fn structure_visibility_and_raw_code() { + let doc=defaults("

first heading

+
  fn x() {\n    x +  1\n} 
NameA
+
Custom
+ forbiddenforbidden + jscredentialsdata
"); + assert!(doc.nodes().iter().all(|n| !n.text.contains("forbidden"))); + let role = |role| doc.nodes().iter().find(|n| n.role == role).unwrap(); + assert_eq!(role(Role::Heading(Some(3))).text, "first heading"); + assert_eq!( + role(Role::Heading(Some(3))).element_id.as_deref(), + Some("intro") + ); + assert_eq!(role(Role::CodeBlock).text, " fn x() {\n x + 1\n} "); + assert_eq!(role(Role::Heading(Some(4))).text, "Custom"); + assert_eq!(role(Role::CellHeader).text, "Name"); + assert_eq!(role(Role::Cell).text, "A"); + let link = role(Role::Link); + assert_eq!(link.name, "accessible"); + assert_eq!(link.text, "visible"); + assert_eq!( + doc.nodes()[link.parent.unwrap()].role, + Role::Landmark(Some(Landmark::Navigation)) + ); + assert_eq!( + doc.nodes() + .iter() + .filter(|n| n.destination.is_some()) + .count(), + 1 + ); + assert!(role(Role::Image).image_source.is_none()); +} +#[test] +fn hostile_sizes_are_refused_before_parsing() { + let nested = "
".repeat(10 * 1024 * 1024 / 5 + 1); + let links = "x".repeat(1_000_000); + for text in [&nested, &links] { + assert!(matches!( + parse(text.as_bytes(), DocLimits::default()), + Err(DocError::Input) + )); + } + let doc = parse(b"

bad\xff\0 unclosed", DocLimits::default()).unwrap(); + assert!(doc + .nodes() + .iter() + .any(|n| n.text.contains("bad�") && n.text.contains("unclosed"))); + assert!(parse(&vec![b' '; MAX_INPUT_BYTES], DocLimits::default()).is_ok()); + assert!(matches!( + parse(&vec![b' '; MAX_INPUT_BYTES + 1], DocLimits::default()), + Err(DocError::Input) + )); +} + +#[test] +fn builder_validates_preorder_and_refusals_leave_it_usable() { + let mut b = DocBuilder::new( + &page(), + DocLimits { + nodes: 4, + depth: 2, + node_text_bytes: 4, + text_bytes: 6, + ..Default::default() + }, + ) + .unwrap(); + let add = |text: &str, p| { + let mut n = Node::new(Role::Paragraph, p); + n.text = text.into(); + n + }; + assert_eq!(b.push(add("", Some(0))), Err(DocError::Parent)); + assert_eq!(b.push(add("abcd", None)), Ok(0)); + assert_eq!(b.push(add("", Some(2))), Err(DocError::Parent)); + assert_eq!(b.push(add("abcde", Some(0))), Err(DocError::Text)); + assert_eq!(b.push(add("ab", Some(0))), Ok(1)); + assert_eq!(b.push(add("", Some(1))), Err(DocError::Depth)); + assert_eq!(b.push(add("x", Some(0))), Err(DocError::Text)); + assert_eq!(b.push(add("", None)), Ok(2)); + assert_eq!(b.push(add("", Some(0))), Err(DocError::Parent)); + assert_eq!(b.push(add("", Some(2))), Ok(3)); + assert_eq!(b.push(add("", None)), Err(DocError::Nodes)); + assert_eq!(b.finish().nodes().len(), 4); +} +#[test] +fn html_limits_report_truncation_and_preserve_atomic_fields() { + for (html, limits) in [ + ( + "

0

1

", + DocLimits { + nodes: 2, + ..Default::default() + }, + ), + ( + "

Hello

", + DocLimits { + depth: 2, + ..Default::default() + }, + ), + ( + "

ééé", + DocLimits { + node_text_bytes: 5, + ..Default::default() + }, + ), + ( + "

x

y

", + DocLimits { + text_bytes: 1, + ..Default::default() + }, + ), + ( + "

s", + DocLimits { + node_text_bytes: 1, + ..Default::default() + }, + ), + ( + "", + DocLimits { + node_text_bytes: 1, + ..Default::default() + }, + ), + ] { + let doc = parse(html.as_bytes(), limits).unwrap(); + assert!(doc.truncated()); + assert!(doc.head().linked_data.is_empty()); + assert!(doc.nodes().iter().all( + |n| n.text.len() + n.name.len() <= limits.node_text_bytes && n.element_id.is_none() + )); + } + let head = ""; + for (count, truncated) in [(MAX_HEAD_ITEMS, false), (MAX_HEAD_ITEMS + 1, true)] { + let doc = defaults(&head.repeat(count)); + assert_eq!(doc.truncated(), truncated); + assert_eq!(doc.head().alternates.len(), MAX_HEAD_ITEMS); + assert_eq!(doc.head().linked_data.len(), MAX_HEAD_ITEMS); + } + let u = page(); + let l = DocLimits { + url_bytes: u.as_str().len(), + ..Default::default() + }; + let doc = parse(b"x", l).unwrap(); + assert!(doc.truncated()); + assert!(!doc.nodes().iter().any(|n| n.destination.is_some())); + assert!(matches!( + DocBuilder::new( + &u, + DocLimits { + url_bytes: l.url_bytes - 1, + ..l + } + ), + Err(DocError::Url(KeyError::UrlLength)) + )); +} +#[test] +fn absolute_ceilings_apply_to_callers() { + for limits in [ + DocLimits { + input_bytes: MAX_INPUT_BYTES + 1, + ..Default::default() + }, + DocLimits { + nodes: MAX_NODES + 1, + ..Default::default() + }, + DocLimits { + depth: MAX_DEPTH + 1, + ..Default::default() + }, + DocLimits { + text_bytes: MAX_TEXT_BYTES + 1, + ..Default::default() + }, + DocLimits { + node_text_bytes: MAX_NODE_TEXT_BYTES + 1, + ..Default::default() + }, + DocLimits { + url_bytes: MAX_URL_BYTES + 1, + ..Default::default() + }, + ] { + assert!(matches!( + DocBuilder::new(&page(), limits), + Err(DocError::Limits) + )); + } + let mut b = DocBuilder::new(&page(), DocLimits::default()).unwrap(); + for _ in 0..MAX_NODES { + b.push(Node::new(Role::Group, None)).unwrap(); + } + assert_eq!(b.push(Node::new(Role::Group, None)), Err(DocError::Nodes)); + let mut b = DocBuilder::new(&page(), DocLimits::default()).unwrap(); + for i in 0..MAX_DEPTH { + b.push(Node::new(Role::Group, i.checked_sub(1))).unwrap(); + } + assert_eq!( + b.push(Node::new(Role::Group, Some(MAX_DEPTH - 1))), + Err(DocError::Depth) + ); + let mut b = DocBuilder::new(&page(), DocLimits::default()).unwrap(); + let text = |size| { + let mut n = Node::new(Role::Paragraph, None); + n.text = "x".repeat(size); + n + }; + assert_eq!(b.push(text(MAX_NODE_TEXT_BYTES + 1)), Err(DocError::Text)); + for _ in 0..MAX_TEXT_BYTES / MAX_NODE_TEXT_BYTES { + b.push(text(MAX_NODE_TEXT_BYTES)).unwrap(); + } + assert_eq!(b.push(text(1)), Err(DocError::Text)); +} +#[test] +fn live_document_filters_hidden_descendants_and_validates_role_urls() { + let mut b = DocBuilder::new(&page(), Default::default()).unwrap(); + let mut root = Node::new(Role::Group, None); + root.hidden = true; + let p = b.push(root).unwrap(); + let mut h = Node::new(Role::Heading(None), Some(p)); + h.name = "Heading".into(); + let h = b.push(h).unwrap(); + let mut n = Node::new(Role::Link, Some(h)); + n.destination = Some(page()); + n.name = "Result".into(); + b.push(n).unwrap(); + let mut bad = Node::new(Role::Paragraph, None); + bad.destination = Some(page()); + assert_eq!(b.push(bad), Err(DocError::Role)); + assert_eq!( + b.push(Node::new(Role::Heading(Some(8)), None)), + Err(DocError::Role) + ); + let mut bad = Node::new(Role::Link, None); + bad.destination = Some(Url::parse("https://user@example.net").unwrap()); + assert!(matches!(b.push(bad), Err(DocError::Url(_)))); + let q = read_query("example").unwrap(); + assert!(matches!( + read_results(SearchEngine::Bing, None, &q, &b.finish()), + ResultsRead::Wall(Wall::Unreadable) + )); + let mut b = DocBuilder::new(&page(), Default::default()).unwrap(); + b.mark_truncated(); + assert!(b.finish().truncated()); +} + +#[test] +fn dropped_head_metadata_keeps_complete_organic_results_readable() { + let html=format!("

Acme

","x".repeat(MAX_NODE_TEXT_BYTES+1)); + let doc = defaults(&html); + assert!(doc.truncated() && doc.head().truncated); + assert!(!doc.body_truncated()); + assert!(matches!( + read_results(SearchEngine::Bing, None, &read_query("acme").unwrap(), &doc), + ResultsRead::FirstLayer(_) + )); + let html = format!( + "Next", + "x".repeat(MAX_URL_BYTES + 1) + ); + assert!(matches!( + parse(html.as_bytes(), DocLimits::default()), + Err(DocError::Url(KeyError::UrlLength)) + )); +} diff --git a/crates/zephium-map/tests/first_layer.rs b/crates/zephium-map/tests/first_layer.rs new file mode 100644 index 000000000..6e84026fb --- /dev/null +++ b/crates/zephium-map/tests/first_layer.rs @@ -0,0 +1,352 @@ +use url::Url; +use zephium_core::search::SearchEngine; +use zephium_map::{ + doc::{Doc, DocLimits}, + query::read_query, + results::*, +}; + +fn read(query: &str, html: &str) -> ResultsRead { + let url = Url::parse("https://search.example/results").unwrap(); + let doc = Doc::from_html(&url, html.as_bytes(), None, DocLimits::default()).unwrap(); + read_results( + SearchEngine::Custom, + None, + &read_query(query).unwrap(), + &doc, + ) +} +fn layer(query: &str, html: &str) -> FirstLayer { + match read(query, html) { + ResultsRead::FirstLayer(l) => l, + ResultsRead::Wall(w) => panic!("wall {w:?}"), + } +} +#[test] +fn extracts_first_layer() { + let l = layer("acme pricing", include_str!("fixtures/first-layer.html")); + assert_eq!(l.organic.len(), 4); + let official = l.official.unwrap(); + assert_eq!(official.organic_index, 1); + assert_eq!(official.evidence.position, 2); + assert!( + official.evidence.domain_match + && official.evidence.panel_website + && official.evidence.sitelinks + ); + let hit = &l.organic[1]; + assert_eq!( + hit.snippet.as_deref(), + Some("Visit Acme for its products, plans and documentation.") + ); + assert_eq!( + hit.sitelinks + .iter() + .map(|l| l.title.as_str()) + .collect::>(), + ["Pricing", "Documentation"] + ); + assert_eq!(l.video[0].title, "Acme training"); + assert_eq!( + l.social.iter().map(|p| p.network).collect::>(), + [Network::GitHub, Network::Twitter] + ); + assert_eq!(l.images.len(), 1); + assert_eq!(l.images[0].destination.as_str(), "https://acme.com/gallery"); + assert_eq!( + l.images[0].source.as_str(), + "https://cdn.acme.com/product.jpg" + ); + assert_eq!(l.images[0].title, "Acme product"); +} +#[test] +fn nested_heading_sitelinks_do_not_consume_later_cards() { + let l = layer("acme", include_str!("fixtures/heading-sitelinks.html")); + assert_eq!(l.organic.len(), 2); + assert_eq!(l.organic[0].sitelinks.len(), 2); + assert_eq!( + l.organic[0].snippet.as_deref(), + Some("Find specifications and support for Acme tools here.") + ); + assert_eq!(l.organic[1].title, "Acme news"); +} +fn card(target: &str, title: &str) -> String { + format!("") +} +#[test] +fn official_site_corpus() { + let cases = [ + ( + "stripe pricing", + "en.wikipedia.org stripe.com", + "stripe.com", + ), + ( + "github actions docs", + "docs.github.com microsoft.com", + "github.com", + ), + ( + "rust programming language", + "en.wikipedia.org github.com/rust-lang/rust rust-lang.org", + "rust-lang.org", + ), + ( + "wikipedia rust language", + "rust-lang.org en.wikipedia.org", + "wikipedia.org", + ), + ( + "tauri changelog", + "github.com/tauri-apps/tauri tauri.app", + "tauri.app", + ), + ( + "svelte docs", + "svelte-support.com docs.svelte.dev", + "svelte.dev", + ), + ( + "stripe", + "stripe.com.example.net s-tripe.com stripes.com", + "", + ), + ( + "postgres", + "github.com/postgres stackoverflow.com docs.postgres.com", + "postgres.com", + ), + ("mozilla", "mozilla-news.com mozilla.org", "mozilla.org"), + ("linear", "nytimes.com linear.app", "linear.app"), + ( + "vercel status", + "status.vercel.com vercel.com", + "vercel.com", + ), + ("netlify", "github.io reddit.com/r/netlify", ""), + ("docker", "docker.io/docs docker.com", "docker.io"), + ("rust", "en.wikipedia.org github.com", ""), + ("acme", "store.steampowered.com news.ycombinator.com", ""), + ("acme", "apps.apple.com play.google.com amazon.com", ""), + ("acme", "quora.com g2.com trustpilot.com", ""), + ("acme", "techcrunch.com reuters.com bbc.co.uk", ""), + ("acme", "acmeevil.com fake-acme.com acme-login.com", ""), + ("figma", "help.figma.com", "figma.com"), + ("gitlab releases", "about.gitlab.com", "gitlab.com"), + ("github", "gitlab.com github.com", "github.com"), + ("reddit community", "old.reddit.com", "reddit.com"), + ("amazon", "amazon.co.uk", "amazon.co.uk"), + ("bbc", "bbc.co.uk", "bbc.co.uk"), + ("youtube", "youtube.com", "youtube.com"), + ("bluesky", "bsky.app", "bsky.app"), + ("twitter", "x.com", "x.com"), + ("bitbucket", "bitbucket.org", "bitbucket.org"), + ("signal download", "support.signal.org", "signal.org"), + ("acme tools", "acmetools.co.uk", "acmetools.co.uk"), + ("acme", "acme.github.io", ""), + ("acme", "docs.acme.co.uk", "acme.co.uk"), + ("acme", "x.com/acme acme.app", "acme.app"), + ("acme vs stripe", "acme.app stripe.com", ""), + ("what is acme", "acme.app", ""), + ]; + for (query, sites, expected) in cases { + let html = sites + .split_whitespace() + .map(|s| card(s, "Result page")) + .collect::(); + let official = layer(query, &html).official; + assert_eq!( + official.as_ref().map(|v| v.site.as_str()).unwrap_or(""), + expected, + "{query} {sites}" + ); + } +} +#[test] +fn panel_evidence_requires_the_website_link_and_respects_intermediaries() { + for (host, eligible) in [ + ("different-brand.com", true), + ("github.com", false), + ("en.wikipedia.org", false), + ("apps.apple.com", false), + ("quora.com", false), + ("nytimes.com", false), + ("ebay.com", false), + ("linkedin.com", false), + ] { + let entry = card(host, "Acme"); + for (markup, match_expected) in [("
\">

b

", + " ?>

a

", + "<script>a", + "a < b <3 <<script", + ] { + assert_eq!(strip(kept).unwrap(), kept); + } + } + + #[test] + fn the_page_limit_applies_after_stripping() { + let at = "a".repeat(MAX_RESULTS_PAGE_BYTES); + assert_eq!(strip(&at).unwrap().len(), MAX_RESULTS_PAGE_BYTES); + let over = "a".repeat(MAX_RESULTS_PAGE_BYTES + 1); + assert_eq!(strip(&over), Err(Failure::Limit)); + let wrapped = format!( + "<p>a</p><script>{}</script>", + "x".repeat(MAX_RESULTS_PAGE_BYTES) + ); + assert_eq!(strip(&wrapped).unwrap(), "<p>a</p><script></script>"); + } + + #[test] + fn the_source_is_cut_at_a_character_boundary() { + let lead = "<p>a</p><script>"; + let fill = MAX_RESULTS_SOURCE_BYTES - lead.len() - 1; + let source = format!("{lead}{}é<p>after the cap</p>", "x".repeat(fill)); + assert!(!source.is_char_boundary(MAX_RESULTS_SOURCE_BYTES)); + assert_eq!(strip(&source).unwrap(), "<p>a</p><script>"); + assert_eq!(floor_boundary("é", 1), 0); + assert_eq!(floor_boundary("é", 9), 2); + } + + #[test] + fn a_page_over_the_parser_limit_parses_once_stripped() { + let url = url::Url::parse("https://duckduckgo.com/").unwrap(); + let html = format!( + "<main><article><h2><a href='https://acme.com/'>Acme</a></h2></article></main><script>{}</script>", + "x".repeat(MAX_RESULTS_PAGE_BYTES * 2) + ); + assert!(Doc::from_html(&url, html.as_bytes(), None, DocLimits::RESULTS).is_err()); + let page = ResultsPage { + html, + url, + truncated: false, + }; + assert!(parse(&page).is_ok()); + } +} diff --git a/crates/zephium-map-driver/src/public.rs b/crates/zephium-map-driver/src/public.rs new file mode 100644 index 000000000..5aaebdb76 --- /dev/null +++ b/crates/zephium-map-driver/src/public.rs @@ -0,0 +1,147 @@ +use std::{sync::Arc, time::Instant}; + +use zephium_map::session::{Expect, Failure, FetchResult}; +use zephium_public_fetch::{ + Expect as PublicExpect, PublicBody, PublicReader, ReadRefusal, ReadRequest, ReadSession, + StatusRefusal, +}; + +use crate::io::{FetchRequest, Fetcher, Reading}; + +/// One per map: reads share connections only within it. +pub struct PublicIo { + session: Arc<ReadSession>, +} + +impl PublicIo { + pub fn new(reader: &PublicReader) -> Self { + Self { + session: Arc::new(reader.session()), + } + } +} + +impl Fetcher for PublicIo { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + let session = Arc::clone(&self.session); + Box::pin(async move { + let now = Instant::now(); + let read = ReadRequest { + url: request.url, + expect: match request.expect { + Expect::Html => PublicExpect::Html, + Expect::Xml => PublicExpect::Xml, + Expect::Text => PublicExpect::Text, + }, + max_bytes: request.max_bytes as usize, + deadline: now.checked_add(request.timeout).unwrap_or(now), + }; + session + .read(read) + .await + .map(|body| fetch_result(body, request.expect)) + .map_err(failure) + }) + } +} + +fn fetch_result(body: PublicBody, expect: Expect) -> FetchResult { + let sniffed = match expect { + Expect::Html => "text/html", + Expect::Xml => "application/xml", + Expect::Text => "text/plain", + }; + FetchResult { + final_url: body.final_url, + content_type: match body.media_type.as_deref() { + Some("application/gzip" | "application/x-gzip") if expect == Expect::Xml => { + sniffed.into() + } + _ => body.media_type.unwrap_or_else(|| sniffed.into()), + }, + charset: body.charset, + bytes: body.bytes, + truncated: body.truncated, + } +} + +pub(crate) fn failure(refusal: ReadRefusal) -> Failure { + use ReadRefusal as R; + use StatusRefusal as S; + match refusal { + R::NotPublicHttps | R::RedirectRefused | R::TooManyRedirects | R::DnsRefused => { + Failure::External + } + R::ProxyUnsupported | R::RouteChanged | R::Transport | R::Status(S::Denied) => { + Failure::Unavailable + } + R::Timeout(_) => Failure::Timeout, + R::Status(S::Client) => Failure::Client, + R::Status(S::RateLimited | S::Server) => Failure::Server, + R::Status(S::Challenge) => Failure::Challenge, + R::Status(S::Unexpected) | R::Encoding => Failure::Unreadable, + R::WrongContentType => Failure::ContentType, + R::TooLarge(_) => Failure::Limit, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_reader_refusal_maps_to_the_bench_decision() { + use Failure as F; + let expected = [ + F::External, + F::External, + F::External, + F::External, + F::Unavailable, + F::Unavailable, + F::Timeout, + F::Timeout, + F::Timeout, + F::Timeout, + F::Unavailable, + F::Server, + F::Challenge, + F::Client, + F::Server, + F::Unreadable, + F::ContentType, + F::Limit, + F::Limit, + F::Unreadable, + F::Unavailable, + ]; + assert_eq!(ReadRefusal::ALL.map(failure), expected); + } + + #[test] + fn sniffed_and_compressed_sitemaps_keep_the_expected_media_type() { + let body = |media: Option<&str>| PublicBody { + final_url: url::Url::parse("https://acme.com/sitemap.xml").unwrap(), + hops: 0, + status: zephium_public_fetch::StatusClass::Ok, + media_type: media.map(str::to_owned), + charset: None, + bytes: Vec::new(), + truncated: false, + wire_bytes: 0, + timings: Default::default(), + }; + assert_eq!( + fetch_result(body(None), Expect::Html).content_type, + "text/html" + ); + assert_eq!( + fetch_result(body(Some("application/gzip")), Expect::Xml).content_type, + "application/xml" + ); + assert_eq!( + fetch_result(body(Some("application/gzip")), Expect::Html).content_type, + "application/gzip" + ); + } +} diff --git a/crates/zephium-map-driver/src/wire.rs b/crates/zephium-map-driver/src/wire.rs new file mode 100644 index 000000000..725f382a9 --- /dev/null +++ b/crates/zephium-map-driver/src/wire.rs @@ -0,0 +1,493 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use url::Url; +use zephium_map::{ + compare, + query::{self, SectionRole}, + results::{self, FirstLayer, Profile}, + session::{self, ReadState}, + site, +}; + +pub const MAX_TEXT_BYTES: usize = 300; +pub const MAX_PATH_CHARS: usize = 128; +pub const MAX_SECTIONS: usize = 32; +pub const MAX_CHILDREN: usize = 12; +pub const MAX_SOCIAL: usize = 10; +pub const MAX_ROWS: usize = 64; +pub const ID_BYTES: usize = 16; + +macro_rules! mirror { + ($name:ident from $engine:path { $($variant:ident),+ $(,)? }) => { + #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] + #[cfg_attr(feature = "ipc-types", derive(specta::Type))] + #[serde(rename_all = "snake_case")] + pub enum $name { + $($variant),+ + } + impl From<$engine> for $name { + fn from(value: $engine) -> Self { + match value { + $(<$engine>::$variant => Self::$variant),+ + } + } + } + }; +} + +mirror!(Role from SectionRole { + News, Product, Features, Solutions, Enterprise, Customers, Community, Security, Legal, + Contact, SignUp, Learn, Examples, Playground, Integrations, Home, Pricing, Documentation, + Api, Reference, Changelog, Releases, Status, Download, Install, Login, Blog, About, Careers, + Support, +}); +mirror!(Network from results::Network { + Twitter, GitHub, YouTube, LinkedIn, Discord, Reddit, Mastodon, Bluesky, Instagram, Facebook, +}); +mirror!(Tier from site::Tier { Primary, Secondary }); +mirror!(Confidence from query::Confidence { Low, High }); + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum StartRefusal { + NotAMap, + UnsupportedEngine, + Invalid, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum Failure { + Cancelled, + Blocked, + Challenge, + Consent, + NoResults, + Unreadable, + Unavailable, + Timeout, + Limit, + Missing, +} + +impl From<session::Failure> for Failure { + fn from(failure: session::Failure) -> Self { + use session::Failure as F; + match failure { + F::Cancelled => Self::Cancelled, + F::Missing | F::Client => Self::Missing, + F::Server | F::Unavailable => Self::Unavailable, + F::Unreadable | F::ContentType => Self::Unreadable, + F::Timeout => Self::Timeout, + F::External | F::Robots => Self::Blocked, + F::Challenge => Self::Challenge, + F::Consent => Self::Consent, + F::NoResults => Self::NoResults, + F::Limit => Self::Limit, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum Read { + Queued, + Read, + Refused, + Skipped, +} + +impl From<ReadState> for Read { + fn from(state: ReadState) -> Self { + match state { + ReadState::Queued => Self::Queued, + ReadState::Read => Self::Read, + ReadState::Refused { .. } => Self::Refused, + ReadState::Skipped { .. } => Self::Skipped, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Official { + pub title: String, + pub site: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Entry { + pub id: String, + pub tier: Tier, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option<Role>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option<String>, + pub off_site: bool, + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read: Option<Read>, + pub children: Vec<Entry>, + pub more: bool, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Notes { + pub shell: bool, + pub wall: bool, + pub robots_disallowed: bool, + pub truncated: bool, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Place { + pub title: String, + pub site: String, + pub host: String, + pub sections: Vec<Entry>, + pub focus: Option<String>, + pub social: Vec<Network>, + pub notes: Notes, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Row { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option<Role>, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub left: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub right: Option<String>, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Outcome { + Done, + Cancelled, + Failed { failure: Failure }, +} + +impl From<session::EndOutcome> for Outcome { + fn from(outcome: session::EndOutcome) -> Self { + match outcome { + session::EndOutcome::Done => Self::Done, + session::EndOutcome::Cancelled => Self::Cancelled, + session::EndOutcome::Failed { failure } => Self::Failed { + failure: failure.into(), + }, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Change { + FirstLayer { + seq: u32, + official: Option<Official>, + social: Vec<Network>, + organic: u8, + }, + Place { + seq: u32, + slot: u8, + place: Place, + stale: bool, + confidence: Confidence, + complete: bool, + }, + PlaceFailed { + seq: u32, + slot: u8, + failure: Failure, + }, + Compare { + seq: u32, + rows: Vec<Row>, + }, + End { + seq: u32, + outcome: Outcome, + elapsed_ms: u32, + }, +} + +impl Change { + pub fn seq(&self) -> u32 { + match self { + Self::FirstLayer { seq, .. } + | Self::Place { seq, .. } + | Self::PlaceFailed { seq, .. } + | Self::Compare { seq, .. } + | Self::End { seq, .. } => *seq, + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Target { + Entry { id: String }, + Site, + Social { network: Network }, +} + +#[derive(Default)] +pub(crate) struct Targets { + entries: BTreeMap<String, Url>, + site: Option<Url>, + social: BTreeMap<Network, Url>, +} + +impl Targets { + pub(crate) fn resolve(&self, target: &Target) -> Option<Url> { + let url = match target { + Target::Entry { id } => self.entries.get(id), + Target::Site => self.site.as_ref(), + Target::Social { network } => self.social.get(network), + }?; + (url.scheme() == "https").then(|| url.clone()) + } + + pub(crate) fn has(&self, id: &str) -> bool { + self.entries.contains_key(id) + } +} + +pub(crate) fn text(raw: &str) -> String { + let mut out = String::new(); + let mut space = false; + for c in zephium_map::clean_text(raw).chars() { + if c.is_whitespace() || c.is_control() { + space = !out.is_empty(); + continue; + } + if out.len() + c.len_utf8() + usize::from(space) > MAX_TEXT_BYTES { + break; + } + if std::mem::take(&mut space) { + out.push(' '); + } + out.push(c); + } + out +} + +fn address_shaped(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + lower.contains("://") + || lower.split(' ').any(|word| { + ["http:", "https:", "www."] + .iter() + .any(|prefix| word.starts_with(prefix)) + }) +} + +fn shown(raw: &str) -> Option<String> { + let text = text(raw); + (!text.is_empty() && !address_shaped(&text)).then_some(text) +} + +fn valid_id(id: &str) -> bool { + id.len() == ID_BYTES && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +fn scheme_like(segment: &str) -> bool { + segment.strip_suffix(':').is_some_and(|scheme| { + scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) +} + +pub(crate) fn path(url: &Url) -> String { + let mut out = String::new(); + for segment in url.path().split('/').filter(|s| !s.is_empty()) { + if scheme_like(segment) { + break; + } + out.push('/'); + out.push_str(segment); + } + if out.is_empty() { + out.push('/'); + } + match out.char_indices().nth(MAX_PATH_CHARS) { + Some((cut, _)) => out[..cut].to_owned(), + None => out, + } +} + +fn address(entry: &site::Entry) -> Url { + let mut url = entry.key.as_url().clone(); + if url.fragment().is_none() { + if let Some(fragment) = entry.locator.fragment() { + url.set_fragment(fragment.strip_prefix('#')); + } + } + url +} + +fn networks(profiles: &[Profile], social: &mut BTreeMap<Network, Url>) -> Vec<Network> { + let mut out = Vec::new(); + for profile in profiles { + let network = Network::from(profile.network); + if out.len() >= MAX_SOCIAL { + break; + } + if !out.contains(&network) { + out.push(network); + social.insert(network, profile.url.clone()); + } + } + out +} + +fn entry( + source: &site::Entry, + child: bool, + seen: &mut BTreeSet<String>, + targets: &mut BTreeMap<String, Url>, +) -> Option<Entry> { + let id = source.id.as_str(); + if !valid_id(id) || seen.contains(id) { + return None; + } + let path = path(source.key.as_url()); + let label = text(&source.label); + let label = if label.is_empty() { + return None; + } else if !address_shaped(&label) { + label + } else if path != "/" { + path.clone() + } else { + return None; + }; + seen.insert(id.to_owned()); + targets.insert(id.to_owned(), address(source)); + let mut children = Vec::new(); + let mut more = source.more > 0; + if child { + more |= !source.children.is_empty(); + } else { + let mut rest = source.children.iter(); + for next in rest.by_ref() { + if let Some(projected) = entry(next, true, seen, targets) { + children.push(projected); + if children.len() == MAX_CHILDREN { + break; + } + } + } + more |= rest.next().is_some(); + } + Some(Entry { + id: id.to_owned(), + tier: source.tier.into(), + label, + role: source.role.map(Role::from), + group: source.group.as_deref().and_then(shown), + off_site: source.off_site, + path, + read: source.read.map(Read::from), + children, + more, + }) +} + +pub(crate) fn place(source: &site::Place) -> (Place, Targets) { + let mut targets = Targets { + site: Some(source.entry.as_url().clone()), + ..Targets::default() + }; + let mut seen = BTreeSet::new(); + let mut ordered: Vec<_> = source.sections.iter().collect(); + ordered.sort_by_key(|e| e.tier != site::Tier::Primary); + let mut sections = Vec::new(); + for section in ordered { + if sections.len() == MAX_SECTIONS { + break; + } + if let Some(projected) = entry(section, false, &mut seen, &mut targets.entries) { + sections.push(projected); + } + } + let site = text(source.site.as_str()); + let place = Place { + title: shown(&source.title).unwrap_or_else(|| site.clone()), + host: text(&source.key.host), + site, + sections, + focus: source + .focus + .as_ref() + .map(|id| id.as_str()) + .filter(|id| seen.contains(*id)) + .map(str::to_owned), + social: networks(&source.social, &mut targets.social), + notes: Notes { + shell: source.notes.shell, + wall: source.notes.wall, + robots_disallowed: source.notes.robots_disallowed, + truncated: source.notes.truncated, + }, + }; + (place, targets) +} + +pub(crate) fn first_layer(layer: &FirstLayer) -> (Option<Official>, Vec<Network>, u8) { + let official = layer.organic.iter().find_map(|hit| { + let site = text(hit.official.as_ref()?.site.as_str()); + Some(Official { + title: shown(&hit.title).unwrap_or_else(|| site.clone()), + site, + }) + }); + let social = networks(&layer.social, &mut BTreeMap::new()); + let organic = u8::try_from(layer.organic.len()).unwrap_or(u8::MAX); + (official, social, organic) +} + +pub(crate) fn rows(source: &[compare::Row], left: &Targets, right: &Targets) -> Vec<Row> { + source + .iter() + .filter_map(|row| { + let side = |id: &Option<site::EntryId>, targets: &Targets| { + id.as_ref() + .map(|id| id.as_str()) + .filter(|id| valid_id(id) && targets.has(id)) + .map(str::to_owned) + }; + let (l, r) = (side(&row.left, left), side(&row.right, right)); + if l.is_none() && r.is_none() { + return None; + } + Some(Row { + role: row.role.map(Role::from), + label: shown(&row.label)?, + left: l, + right: r, + }) + }) + .take(MAX_ROWS) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/crates/zephium-map-driver/src/wire/tests.rs b/crates/zephium-map-driver/src/wire/tests.rs new file mode 100644 index 000000000..bd3cdca2d --- /dev/null +++ b/crates/zephium-map-driver/src/wire/tests.rs @@ -0,0 +1,343 @@ +use super::*; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use zephium_map::{site::SiteInputs, Doc, DocLimits}; + +fn base() -> Value { + let url = Url::parse("https://acme.com/").unwrap(); + let doc = Doc::from_html( + &url, + b"<title>Acme</title><nav><a href='/pricing'>Pricing</a><a href='/news'>News</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let inputs = SiteInputs { + result_section: None, + sitelinks: &[], + robots: None, + llms: None, + sitemaps: BTreeMap::new(), + pages: BTreeMap::new(), + }; + serde_json::to_value(site::read_site(&doc, &inputs).unwrap()).unwrap() +} + +fn id(n: usize) -> String { + format!("{n:016x}") +} + +fn section(id: &str, label: &str, key: &str, tier: &str) -> Value { + json!({ + "children": [], + "group": null, + "id": id, + "key": key, + "label": label, + "locator": {}, + "more": 0, + "off_site": false, + "role": null, + "sources": ["Footer"], + "tier": tier, + }) +} + +fn engine(value: Value) -> site::Place { + serde_json::from_value(value).unwrap() +} + +fn hostile() -> site::Place { + let mut place = base(); + place["title"] = json!(format!("\u{202e}Acme\u{7}\n{}", "T".repeat(1000))); + place["focus"] = json!("not-an-id"); + place["social"] = json!([ + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/acme"}, + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/other"}, + ]); + let mut sections = Vec::new(); + let mut long = section( + &id(1), + &format!("{}\u{0}\u{200b}{}", "L".repeat(200), "é".repeat(400)), + "https://acme.com/long?token=secret#frag", + "Secondary", + ); + long["group"] = json!("G".repeat(1000)); + sections.push(long); + sections.push(section( + &id(2), + "https://evil.example/path?x=1", + "https://acme.com/a", + "Primary", + )); + sections.push(section( + &id(3), + "visit www.evil.example now", + "https://acme.com/b", + "Primary", + )); + sections.push(section( + &id(8), + "https://evil.example/root", + "https://acme.com/", + "Primary", + )); + sections.push(section("ZZZZ", "Bad", "https://acme.com/c", "Primary")); + sections.push(section( + &id(4).to_uppercase().replace('0', "A"), + "Upper", + "https://acme.com/d", + "Primary", + )); + sections.push(section( + &id(5), + "Redirect", + "https://acme.com/go/https://evil.example/x?u=1", + "Primary", + )); + sections.push(section( + &id(6), + "Deep", + &format!("https://acme.com/{}", "p".repeat(300)), + "Primary", + )); + let mut parent = section(&id(7), "Parent", "https://acme.com/parent", "Primary"); + let mut children = Vec::new(); + for n in 0..20 { + let mut child = section( + &id(100 + n), + &format!("Child {n}"), + &format!("https://acme.com/parent/{n}?q=hidden"), + "Primary", + ); + if n == 0 { + child["children"] = json!([section( + &id(999), + "Grandchild", + "https://acme.com/grand", + "Primary" + )]); + } + children.push(child); + } + parent["children"] = Value::Array(children); + sections.push(parent); + sections.push(section( + &id(7), + "Duplicate", + "https://acme.com/dup", + "Primary", + )); + for n in 0..40 { + sections.push(section( + &id(200 + n), + &format!("Section {n}"), + &format!("https://acme.com/s/{n}?session=hidden"), + if n % 2 == 0 { "Secondary" } else { "Primary" }, + )); + } + place["sections"] = Value::Array(sections); + engine(place) +} + +fn entries(place: &Place) -> impl Iterator<Item = &Entry> { + place + .sections + .iter() + .flat_map(|s| std::iter::once(s).chain(&s.children)) +} + +#[test] +fn the_projection_bounds_a_hostile_place() { + let source = hostile(); + let (projected, targets) = place(&source); + let json = serde_json::to_string(&projected).unwrap(); + for banned in [ + "http", "://", "?", "token", "hidden", "evil", "frag", "secret", + ] { + assert!(!json.contains(banned), "{banned} in {json}"); + } + assert!(!json + .chars() + .any(|c| c.is_control() || c == '\u{202e}' || c == '\u{200b}')); + assert_eq!(projected.sections.len(), MAX_SECTIONS); + let tiers: Vec<_> = projected.sections.iter().map(|s| s.tier).collect(); + let mut sorted = tiers.clone(); + sorted.sort(); + assert_eq!(tiers, sorted); + assert!(projected.title.len() <= MAX_TEXT_BYTES && projected.title.starts_with("Acme T")); + assert_eq!(projected.site, "acme.com"); + assert_eq!(projected.host, "acme.com"); + assert_eq!(projected.focus, None); + assert_eq!(projected.social, [Network::GitHub]); + let mut ids = BTreeSet::new(); + for e in entries(&projected) { + assert!(valid_id(&e.id) && ids.insert(e.id.clone())); + assert!(e.label.len() <= MAX_TEXT_BYTES && !e.label.is_empty()); + assert!(e.group.as_ref().is_none_or(|g| g.len() <= MAX_TEXT_BYTES)); + assert!(e.path.starts_with('/') && e.path.chars().count() <= MAX_PATH_CHARS); + assert!(e.children.len() <= MAX_CHILDREN); + assert!(e.children.iter().all(|c| c.children.is_empty())); + } + let parent = projected + .sections + .iter() + .find(|s| s.label == "Parent") + .unwrap(); + assert_eq!(parent.children.len(), MAX_CHILDREN); + assert!(parent.more && parent.children[0].more); + assert!(!ids.contains(&id(999)) && !ids.contains(&id(8))); + let label = |n: usize| { + entries(&projected) + .find(|e| e.id == id(n)) + .map(|e| e.label.clone()) + }; + assert_eq!(label(2).as_deref(), Some("/a")); + assert_eq!(label(3).as_deref(), Some("/b")); + assert!(!json.contains("Duplicate") && !json.contains("Upper") && !json.contains("Bad")); + let long = entries(&projected).find(|e| e.id == id(1)).unwrap(); + assert!(long.label.len() > MAX_TEXT_BYTES - 2); + assert_eq!(long.group.as_ref().map(String::len), Some(MAX_TEXT_BYTES)); + let redirect = entries(&projected).find(|e| e.id == id(5)).unwrap(); + assert_eq!(redirect.path, "/go"); + let deep = entries(&projected).find(|e| e.id == id(6)).unwrap(); + assert_eq!(deep.path.chars().count(), MAX_PATH_CHARS); + assert_eq!( + targets + .resolve(&Target::Entry { id: id(1) }) + .map(|u| u.to_string()), + Some("https://acme.com/long?token=secret#frag".into()) + ); + assert_eq!(targets.resolve(&Target::Entry { id: id(999) }), None); +} + +#[test] +fn text_is_cleaned_then_clipped_at_a_character_boundary() { + assert_eq!(text(" a\u{0}\tb\u{feff}c \n "), "a bc"); + let clipped = text(&"é".repeat(MAX_TEXT_BYTES)); + assert_eq!(clipped.len(), MAX_TEXT_BYTES); + let odd = text(&format!("a{}", "é".repeat(MAX_TEXT_BYTES))); + assert_eq!(odd.len(), MAX_TEXT_BYTES - 1); + assert_eq!(text(&"a".repeat(MAX_TEXT_BYTES + 1)).len(), MAX_TEXT_BYTES); + assert!(address_shaped("HTTPS:example") && address_shaped("x WWW.a.b")); + assert!(!address_shaped("HTTP API") && !address_shaped("Pricing")); +} + +#[test] +fn targets_open_only_known_https_addresses() { + let mut value = base(); + value["entry"] = json!("http://acme.com/"); + let mut fragment = section(&id(1), "Pricing", "https://acme.com/pricing", "Primary"); + fragment["locator"] = json!({"element": "plans"}); + let mut route = section(&id(2), "Route", "https://acme.com/#/app", "Primary"); + route["locator"] = json!({"element": "ignored"}); + value["sections"] = json!([ + fragment, + route, + section(&id(3), "Plain", "http://acme.com/plain", "Primary"), + ]); + value["social"] = json!([ + {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/acme"}, + {"basis": "Navigation", "network": "Reddit", "url": "http://reddit.com/r/acme"}, + ]); + let (_, targets) = place(&engine(value)); + let open = |t: Target| targets.resolve(&t).map(|u| u.to_string()); + assert_eq!( + open(Target::Entry { id: id(1) }), + Some("https://acme.com/pricing#plans".into()) + ); + assert_eq!( + open(Target::Entry { id: id(2) }), + Some("https://acme.com/#/app".into()) + ); + assert_eq!(open(Target::Entry { id: id(3) }), None); + assert_eq!(open(Target::Entry { id: id(4) }), None); + assert_eq!(open(Target::Site), None); + assert_eq!( + open(Target::Social { + network: Network::GitHub + }), + Some("https://github.com/acme".into()) + ); + for network in [Network::Reddit, Network::Discord] { + assert_eq!(open(Target::Social { network }), None); + } + let (_, targets) = place(&engine(base())); + assert_eq!( + targets.resolve(&Target::Site).map(|u| u.to_string()), + Some("https://acme.com/".into()) + ); +} + +#[test] +fn rows_keep_only_projected_ids_and_are_capped() { + let (_, left) = place(&engine(base())); + let known = base()["sections"][0]["id"].as_str().unwrap().to_owned(); + let entry_id = |s: &str| -> Option<site::EntryId> { serde_json::from_value(json!(s)).ok() }; + let row = |label: &str, left: &str, right: &str| compare::Row { + role: None, + label: label.into(), + left: entry_id(left), + right: entry_id(right), + }; + let mut source = vec![ + compare::Row { + role: Some(SectionRole::Pricing), + ..row("Pricing", &known, &id(9)) + }, + row("Gone", &id(9), &id(9)), + row("https://evil.example/", &known, &known), + ]; + for _ in 0..MAX_ROWS + 5 { + source.push(row("Row", &known, &id(9))); + } + let rows = rows(&source, &left, &Targets::default()); + assert_eq!(rows.len(), MAX_ROWS); + assert_eq!( + rows[0], + Row { + role: Some(Role::Pricing), + label: "Pricing".into(), + left: Some(known), + right: None, + } + ); + assert!(rows + .iter() + .all(|r| r.label != "Gone" && !r.label.contains("evil"))); +} + +#[test] +fn every_engine_failure_has_a_wire_class() { + use session::Failure as F; + let all = [ + (F::Cancelled, Failure::Cancelled), + (F::Missing, Failure::Missing), + (F::Client, Failure::Missing), + (F::Server, Failure::Unavailable), + (F::Unreadable, Failure::Unreadable), + (F::Unavailable, Failure::Unavailable), + (F::Timeout, Failure::Timeout), + (F::External, Failure::Blocked), + (F::Robots, Failure::Blocked), + (F::Challenge, Failure::Challenge), + (F::Consent, Failure::Consent), + (F::NoResults, Failure::NoResults), + (F::Limit, Failure::Limit), + (F::ContentType, Failure::Unreadable), + ]; + for (engine, wire) in all { + assert_eq!(Failure::from(engine), wire); + } + assert_eq!( + serde_json::to_value(Change::End { + seq: 3, + outcome: Outcome::Failed { + failure: Failure::NoResults + }, + elapsed_ms: 7, + }) + .unwrap(), + json!({"type": "end", "seq": 3, "outcome": {"kind": "failed", "failure": "no_results"}, "elapsed_ms": 7}) + ); +} From 2a0f324f1075e88a5868de61abbc17de8c4126af Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:15:43 +0100 Subject: [PATCH 23/40] fix(fetch): hold route admission and permits for the whole read A read is dispatched only under the route generation it was admitted on, a resolver permit is held until proxy DNS returns, the global permit is released before waiting on a redirect host, a trailing-dot host shares its pool, and a zero byte cap is no longer raised to one. --- crates/zephium-public-fetch/src/content.rs | 28 ++++- crates/zephium-public-fetch/src/guard.rs | 2 +- crates/zephium-public-fetch/src/reader.rs | 112 ++++++++++++++---- crates/zephium-public-fetch/src/source.rs | 96 +++++++++++++++ .../zephium-public-fetch/src/tests/reads.rs | 56 +++++++++ .../zephium-public-fetch/src/tests/server.rs | 47 +++++++- 6 files changed, 307 insertions(+), 34 deletions(-) diff --git a/crates/zephium-public-fetch/src/content.rs b/crates/zephium-public-fetch/src/content.rs index 0c390119a..5a4e7d619 100644 --- a/crates/zephium-public-fetch/src/content.rs +++ b/crates/zephium-public-fetch/src/content.rs @@ -87,13 +87,15 @@ fn trimmed(head: &[u8]) -> &[u8] { &head[start..] } -fn starts_with_tag(head: &[u8], tags: &[&[u8]]) -> bool { +fn starts_with_tag(head: &[u8], tags: &[&[u8]], self_closing: bool) -> bool { tags.iter().any(|tag| { head.len() >= tag.len() && head[..tag.len()].eq_ignore_ascii_case(tag) - && head - .get(tag.len()) - .is_none_or(|next| next.is_ascii_whitespace() || *next == b'>') + && head.get(tag.len()).is_none_or(|next| { + next.is_ascii_whitespace() + || *next == b'>' + || self_closing && head[tag.len()..].starts_with(b"/>") + }) }) } @@ -109,13 +111,18 @@ pub(crate) fn looks_html(head: &[u8]) -> bool { b"<script", b"<meta", ], + false, ) } pub(crate) fn looks_xml(head: &[u8]) -> bool { let head = trimmed(head); head.starts_with(b"<?xml") - || starts_with_tag(head, &[b"<urlset", b"<sitemapindex", b"<rss", b"<feed"]) + || starts_with_tag( + head, + &[b"<urlset", b"<sitemapindex", b"<rss", b"<feed"], + true, + ) } pub(crate) fn looks_binary(head: &[u8]) -> bool { @@ -337,3 +344,14 @@ mod tests { } } } + +#[cfg(test)] +#[test] +fn known_xml_roots_allow_immediate_self_closing_delimiters() { + let admission = admit(Expect::Xml, None).unwrap(); + for body in [b"<rss/>".as_slice(), b"<rss />"] { + assert_eq!(check_body(Expect::Xml, admission, body), Ok(())); + assert!(check_body(Expect::Text, admit(Expect::Text, None).unwrap(), body).is_err()); + } + assert!(check_body(Expect::Xml, admission, b"<rss-extra/>").is_err()); +} diff --git a/crates/zephium-public-fetch/src/guard.rs b/crates/zephium-public-fetch/src/guard.rs index edf02987f..94d12cada 100644 --- a/crates/zephium-public-fetch/src/guard.rs +++ b/crates/zephium-public-fetch/src/guard.rs @@ -193,7 +193,7 @@ impl Drop for ResolverPermit { } } -async fn resolve_with( +pub(crate) async fn resolve_with( slots: Arc<ResolverSlots>, resolve: impl FnOnce() -> std::io::Result<reqwest::dns::Addrs> + Send + 'static, ) -> std::io::Result<reqwest::dns::Addrs> { diff --git a/crates/zephium-public-fetch/src/reader.rs b/crates/zephium-public-fetch/src/reader.rs index ed9ab5698..0e939a28a 100644 --- a/crates/zephium-public-fetch/src/reader.rs +++ b/crates/zephium-public-fetch/src/reader.rs @@ -1,9 +1,12 @@ use std::{ collections::HashMap, + future::{poll_fn, Future}, + net::ToSocketAddrs, sync::{ atomic::{AtomicU64, Ordering}, Arc, Mutex, PoisonError, }, + task::Poll, time::Instant, }; @@ -234,7 +237,7 @@ impl Drop for HostPermit { fn host_key(url: &url::Url) -> String { format!( "{}:{}", - url.host_str().unwrap_or_default(), + url.host_str().unwrap_or_default().trim_end_matches('.'), url.port_or_known_default().unwrap_or_default() ) } @@ -265,6 +268,7 @@ async fn host_permit(inner: &Arc<Inner>, url: &url::Url) -> Result<HostPermit, R struct ProxyOnly { host: String, + slots: Arc<ResolverSlots>, } impl reqwest::dns::Resolve for ProxyOnly { @@ -273,6 +277,7 @@ impl reqwest::dns::Resolve for ProxyOnly { // proxy's own; a destination resolved here would mean a direct path. let own = name.as_str().eq_ignore_ascii_case(&self.host); let host = self.host.clone(); + let slots = self.slots.clone(); Box::pin(async move { if !own { return Err(std::io::Error::new( @@ -281,12 +286,14 @@ impl reqwest::dns::Resolve for ProxyOnly { ) .into()); } - let addresses: Vec<_> = tokio::net::lookup_host((host.as_str(), 0)) - .await? - .take(guard::MAX_RESOLVED_ADDRESSES) - .collect(); - let addresses: reqwest::dns::Addrs = Box::new(addresses.into_iter()); - Ok(addresses) + Ok(guard::resolve_with(slots, move || { + let addresses: Vec<_> = (host.as_str(), 0) + .to_socket_addrs()? + .take(guard::MAX_RESOLVED_ADDRESSES) + .collect(); + Ok(Box::new(addresses.into_iter())) + }) + .await?) }) } } @@ -318,9 +325,10 @@ fn build_client(inner: &Inner, route: &Route) -> Result<reqwest::Client, ReadRef .proxy_url() .and_then(|url| reqwest::Proxy::all(url).ok()) .ok_or(ReadRefusal::ProxyUnsupported)?; - builder - .proxy(proxy) - .dns_resolver(Arc::new(ProxyOnly { host: host.clone() })) + builder.proxy(proxy).dns_resolver(Arc::new(ProxyOnly { + host: host.clone(), + slots: inner.resolver_slots.clone(), + })) } Route::Unsupported => return Err(ReadRefusal::ProxyUnsupported), }; @@ -414,9 +422,8 @@ fn send_refusal(error: &reqwest::Error, probe: &ReadProbe) -> ReadRefusal { } impl ReadSession { - fn client(&self) -> Result<reqwest::Client, ReadRefusal> { + fn client(&self, generation: u64, route: &Route) -> Result<reqwest::Client, ReadRefusal> { let inner = &self.reader.inner; - let (generation, route) = inner.routes.current(); let mut slot = self.client.lock().unwrap_or_else(PoisonError::into_inner); if let Some(current) = slot .as_ref() @@ -425,7 +432,7 @@ impl ReadSession { return Ok(current.client.clone()); } *slot = None; - let client = build_client(inner, &route)?; + let client = build_client(inner, route)?; *slot = Some(SessionClient { client: client.clone(), generation, @@ -439,6 +446,8 @@ impl ReadSession { let started = Instant::now(); let probe = Arc::new(ReadProbe::default()); let mut changed = inner.routes.changed(); + let admission = inner.routes.current(); + let generation = admission.0; let deadline = request.deadline.min(started + inner.limits.max_duration); let outcome = if deadline <= started { Err(ReadRefusal::Timeout(TimeoutPhase::Queue)) @@ -448,10 +457,11 @@ impl ReadSession { Ok(()) = changed.changed() => Err(ReadRefusal::RouteChanged), result = tokio::time::timeout_at( tokio::time::Instant::from_std(deadline), - self.attempt(&request, &probe, started), + self.attempt(&request, &probe, started, admission), ) => result.unwrap_or_else(|_| Err(probe.timeout())), } }; + let outcome = inner.routes.at_generation(generation, || outcome).flatten(); if matches!(outcome, Err(ReadRefusal::Timeout(TimeoutPhase::Connect))) { inner.routes.request_refresh(); } @@ -484,6 +494,7 @@ impl ReadSession { request: &ReadRequest, probe: &Arc<ReadProbe>, started: Instant, + admission: (u64, Route), ) -> Result<PublicBody, ReadRefusal> { let inner = &self.reader.inner; let limits = inner.limits; @@ -492,10 +503,11 @@ impl ReadSession { if !inner.policy.admits(&current) { return Err(ReadRefusal::NotPublicHttps); } - let client = self.client()?; + let (generation, route) = admission; + let client = self.client(generation, &route)?; let cap = request.max_bytes.clamp(1, limits.max_decoded_bytes); let mut host = host_permit(inner, &current).await?; - let _global = inner + let mut global = inner .global .clone() .acquire_owned() @@ -506,18 +518,27 @@ impl ReadSession { let mut visited = vec![current.clone()]; let (response, first_byte) = loop { probe.first_byte(); - let sending = client + let request = client .get(current.clone()) .header(ACCEPT, accept(request.expect)) - .header(ACCEPT_ENCODING, ACCEPTED_CODINGS) - .send(); + .header(ACCEPT_ENCODING, ACCEPTED_CODINGS); + let mut sending = std::pin::pin!(async { request.send().await }); + let admitted = poll_fn(|cx| { + match inner + .routes + .at_generation(generation, || sending.as_mut().poll(cx)) + { + Ok(polled) => polled.map(Ok), + Err(refusal) => Poll::Ready(Err(refusal)), + } + }); let response = probe .scope(tokio::time::timeout( limits.connect_timeout + limits.first_byte_timeout, - sending, + admitted, )) .await - .map_err(|_| probe.timeout())? + .map_err(|_| probe.timeout())?? .map_err(|error| { let refusal = send_refusal(&error, probe); if error.is_connect() && refusal == ReadRefusal::Transport { @@ -548,9 +569,16 @@ impl ReadSession { } drop(response); if host_key(&next) != host_key(&current) { + drop(global); drop(host); probe.queue(); host = host_permit(inner, &next).await?; + global = inner + .global + .clone() + .acquire_owned() + .await + .map_err(|_| ReadRefusal::Transport)?; } visited.push(next.clone()); current = next; @@ -594,10 +622,14 @@ impl ReadSession { } } drop(response); - let (bytes, truncated) = pipeline.finish().map_err(|_| ReadRefusal::Encoding)?; + let (mut bytes, mut truncated) = pipeline.finish().map_err(|_| ReadRefusal::Encoding)?; if !checked { content::check_body(request.expect, admission, &bytes)?; } + if request.max_bytes == 0 && !bytes.is_empty() { + bytes.clear(); + truncated = true; + } let (media_type, charset) = declared .map(|declared| (Some(declared.essence), declared.charset)) .unwrap_or_default(); @@ -619,3 +651,39 @@ impl ReadSession { }) } } + +#[cfg(test)] +mod tests { + use super::*; + use reqwest::dns::Resolve; + + #[test] + fn equivalent_dns_names_share_one_host_key() { + let bare = url::Url::parse("https://example.com/").unwrap(); + let rooted = url::Url::parse("https://example.com./").unwrap(); + assert_eq!(host_key(&bare), host_key(&rooted)); + } + + #[tokio::test] + async fn proxy_dns_refuses_when_the_physical_resolver_slot_is_busy() { + let slots = Arc::new(ResolverSlots::new(1)); + let proxy = ProxyOnly { + host: "127.0.0.1".into(), + slots: slots.clone(), + }; + let (started, ready) = tokio::sync::oneshot::channel(); + let (release, released) = std::sync::mpsc::channel(); + let worker = tokio::spawn(guard::resolve_with(slots, move || { + started.send(()).unwrap(); + released.recv().unwrap(); + Ok(Box::new(std::iter::empty())) + })); + ready.await.unwrap(); + let refused = proxy.resolve("127.0.0.1".parse().unwrap()).await; + release.send(()).unwrap(); + assert_eq!(worker.await.unwrap().unwrap().count(), 0); + assert!( + matches!(refused, Err(error) if error.downcast_ref::<std::io::Error>().is_some_and(|io| io.kind() == std::io::ErrorKind::WouldBlock)) + ); + } +} diff --git a/crates/zephium-public-fetch/src/source.rs b/crates/zephium-public-fetch/src/source.rs index 961065266..1d68d75fa 100644 --- a/crates/zephium-public-fetch/src/source.rs +++ b/crates/zephium-public-fetch/src/source.rs @@ -1,6 +1,8 @@ use std::{ fmt, + future::{poll_fn, Future}, sync::{Arc, Weak}, + task::Poll, time::Duration, }; @@ -154,6 +156,46 @@ impl RouteSource { (state.generation, state.effective.clone()) } + /// Runs one anonymous direct operation while its admitted route stays current. + /// The operation must not access or change this route source during a poll. + pub async fn while_direct<F: Future>( + &self, + operation: F, + ) -> Result<F::Output, crate::ReadRefusal> { + let mut changed = self.changed(); + let (generation, route) = self.current(); + if route != Route::Direct { + return Err(crate::ReadRefusal::ProxyUnsupported); + } + let mut operation = std::pin::pin!(operation); + let admitted = + poll_fn( + |cx| match self.at_generation(generation, || operation.as_mut().poll(cx)) { + Ok(polled) => polled.map(Ok), + Err(refusal) => Poll::Ready(Err(refusal)), + }, + ); + let output = tokio::select! { + biased; + Ok(()) = changed.changed() => return Err(crate::ReadRefusal::RouteChanged), + result = admitted => result?, + }; + self.at_generation(generation, || output) + } + + pub(crate) fn at_generation<T>( + &self, + generation: u64, + action: impl FnOnce() -> T, + ) -> Result<T, crate::ReadRefusal> { + let state = self.shared.state.borrow(); + if state.generation != generation { + return Err(crate::ReadRefusal::RouteChanged); + } + // The watch borrow holds route publication until this synchronous admission returns. + Ok(action()) + } + /// Asks for a system read soon; requests while one is due coalesce. pub(crate) fn request_refresh(&self) { let _ = self.shared.wake.try_send(()); @@ -511,3 +553,57 @@ mod tests { assert_eq!(calls.load(Ordering::Acquire), after); } } + +#[cfg(test)] +#[tokio::test] +async fn an_old_generation_is_refused_before_admission_even_if_its_class_returns() { + let routes = RouteSource::primed(Arc::new(|| Route::Direct), RouteSource::FIXTURE); + let (direct, _) = routes.current(); + routes.set_app_proxy(zephium_core::proxy::from_settings( + "http", + "proxy.example.com:3128", + )); + assert_eq!( + routes.at_generation(direct, || panic!("stale request must never dispatch")), + Err(crate::ReadRefusal::RouteChanged) + ); + routes.set_app_proxy(None); + assert_eq!(routes.route(), PublicRoute::Direct); + assert_eq!( + routes.at_generation(direct, || panic!("stale request must never dispatch")), + Err(crate::ReadRefusal::RouteChanged) + ); + assert_eq!(routes.at_generation(routes.current().0, || 7), Ok(7)); +} + +#[cfg(test)] +#[tokio::test] +async fn a_direct_operation_cannot_start_its_fallback_after_the_route_changes() { + let routes = RouteSource::primed(Arc::new(|| Route::Direct), RouteSource::FIXTURE); + let (reached, first) = tokio::sync::oneshot::channel(); + let (resume, release) = tokio::sync::oneshot::channel(); + let operation = tokio::spawn({ + let routes = routes.clone(); + async move { + routes + .while_direct(async { + reached.send(()).unwrap(); + assert!(release.await.is_ok()); + panic!("the fallback must not run on a stale route"); + }) + .await + } + }); + first.await.unwrap(); + routes.set_app_proxy(zephium_core::proxy::from_settings( + "http", + "proxy.example.com:3128", + )); + let _ = resume.send(()); + assert_eq!( + operation.await.unwrap(), + Err(crate::ReadRefusal::RouteChanged) + ); + routes.set_app_proxy(None); + assert_eq!(routes.while_direct(async { 7 }).await, Ok(7)); +} diff --git a/crates/zephium-public-fetch/src/tests/reads.rs b/crates/zephium-public-fetch/src/tests/reads.rs index acbb3c220..9fe76d097 100644 --- a/crates/zephium-public-fetch/src/tests/reads.rs +++ b/crates/zephium-public-fetch/src/tests/reads.rs @@ -1086,3 +1086,59 @@ async fn binary_is_refused_once_the_sniff_window_fills_not_at_the_end() { } assert!(reader.counters().wire_bytes < 1 << 20); } + +#[tokio::test] +async fn zero_body_cap_never_returns_payload_bytes() { + let server = Server::start(|_| ok("text/html", PAGE)); + let (reader, _) = reader(); + let body = reader + .read(ReadRequest { + max_bytes: 0, + ..html(server.url("/")) + }) + .await + .unwrap(); + assert!(body.truncated && body.bytes.is_empty()); +} + +#[tokio::test] +async fn cross_host_redirect_releases_global_capacity_before_waiting() { + let target = Server::start(|_| ok("text/html", PAGE)); + let landing = target.url("/landing"); + let (release, gated) = std::sync::mpsc::channel(); + let gated = std::sync::Mutex::new(gated); + let start = Server::start(move |_| { + gated + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(3)) + .unwrap(); + redirect(landing.as_str()) + }); + let (reader, _) = reader_with(ReaderLimits { + max_concurrent: 1, + max_per_host: 1, + ..limits() + }); + let first = tokio::spawn({ + let reader = reader.clone(); + let url = start.url("/"); + async move { reader.read(html(url)).await } + }); + wait_for(|| !start.seen().is_empty()).await; + let second = reader.read(html(target.url("/independent"))); + tokio::pin!(second); + std::future::poll_fn(|cx| { + use std::future::Future; + assert!(second.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + release.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(2), async { + assert!(second.await.is_ok()); + assert_eq!(first.await.unwrap().unwrap().hops, 1); + }) + .await + .unwrap(); +} diff --git a/crates/zephium-public-fetch/src/tests/server.rs b/crates/zephium-public-fetch/src/tests/server.rs index 7f77ad128..9f297afef 100644 --- a/crates/zephium-public-fetch/src/tests/server.rs +++ b/crates/zephium-public-fetch/src/tests/server.rs @@ -2,9 +2,10 @@ use std::{ io::{Read, Write}, net::{TcpListener, TcpStream}, sync::{ - atomic::{AtomicUsize, Ordering}, + atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, Mutex, }, + thread::JoinHandle, time::Duration, }; @@ -58,6 +59,8 @@ impl Gauge { } } +const ACCEPT_POLL: Duration = Duration::from_millis(5); + type Handler = dyn Fn(&Seen) -> Reply + Send + Sync; pub(crate) struct Server { @@ -66,6 +69,8 @@ pub(crate) struct Server { pub(crate) connections: Arc<AtomicUsize>, pub(crate) closed: Arc<AtomicUsize>, pub(crate) in_flight: Arc<Gauge>, + stopped: Arc<AtomicBool>, + accept: Option<JoinHandle<()>>, } impl Server { @@ -79,21 +84,33 @@ impl Server { ) -> Server { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - let server = Server { + listener.set_nonblocking(true).unwrap(); + let mut server = Server { port, seen: Arc::default(), connections: Arc::default(), closed: Arc::default(), in_flight: Arc::default(), + stopped: Arc::default(), + accept: None, }; let handler: Arc<Handler> = Arc::new(handler); let seen = server.seen.clone(); let connections = server.connections.clone(); let closed = server.closed.clone(); let own = server.in_flight.clone(); - std::thread::spawn(move || { - for stream in listener.incoming() { - let Ok(stream) = stream else { return }; + let stopped = server.stopped.clone(); + server.accept = Some(std::thread::spawn(move || { + while !stopped.load(Ordering::Acquire) { + let stream = match listener.accept() { + Ok((stream, _)) => stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::park_timeout(ACCEPT_POLL); + continue; + } + Err(_) => return, + }; + stream.set_nonblocking(false).unwrap(); connections.fetch_add(1, Ordering::AcqRel); let (handler, seen, closed, own, shared) = ( handler.clone(), @@ -107,7 +124,7 @@ impl Server { closed.fetch_add(1, Ordering::AcqRel); }); } - }); + })); server } @@ -120,6 +137,24 @@ impl Server { } } +impl Drop for Server { + fn drop(&mut self) { + self.stopped.store(true, Ordering::Release); + if let Some(accept) = self.accept.take() { + accept.thread().unpark(); + let _ = accept.join(); + } + } +} + +#[test] +fn dropping_server_joins_its_accepting_thread() { + let server = Server::start(|_| Reply::Hang); + let connections = Arc::downgrade(&server.connections); + drop(server); + assert!(connections.upgrade().is_none()); +} + fn read_head(stream: &mut TcpStream) -> Option<Seen> { let mut head = Vec::new(); let mut byte = [0u8; 1]; From c8c7191fd3509ceea9eabb1bf6748e90ffe40749 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:15:43 +0100 Subject: [PATCH 24/40] fix(agentic): keep a Work fetch under a direct route for its whole duration --- .../src/provider_transport/youtube_oembed.rs | 125 ++++++++++++++++-- crates/zephium-agentic/src/public_asset.rs | 86 +++++++++--- 2 files changed, 184 insertions(+), 27 deletions(-) diff --git a/crates/zephium-agentic/src/provider_transport/youtube_oembed.rs b/crates/zephium-agentic/src/provider_transport/youtube_oembed.rs index a4805a41d..55f3a2e07 100644 --- a/crates/zephium-agentic/src/provider_transport/youtube_oembed.rs +++ b/crates/zephium-agentic/src/provider_transport/youtube_oembed.rs @@ -1,7 +1,9 @@ //! A pasted YouTube link's real title and channel, from YouTube's public //! oEmbed endpoint. The address asked is built from a video ID parsed here, //! never from the pasted string, and only two plain-text fields are kept. -use crate::public_asset::{lookup_client, settled_route, PublicAssetError, RouteSource}; +use crate::public_asset::{ + lookup_client, with_direct_route, PublicAssetError, PublicRoute, RouteSource, +}; use std::time::Duration; const TIMEOUT: Duration = Duration::from_secs(5); @@ -102,14 +104,20 @@ pub async fn fetch(routes: &RouteSource, raw: &str) -> Result<YoutubeDetails, Pu let endpoint = video_id(raw) .and_then(|id| oembed_url(&id)) .ok_or(PublicAssetError::InvalidUrl)?; - let client = lookup_client(settled_route(routes).await, TIMEOUT)?; - let unavailable = |_| PublicAssetError::Unavailable; - let mut response = client - .get(endpoint) - .header(reqwest::header::ACCEPT, "application/json") - .send() - .await - .map_err(unavailable)?; + with_direct_route(routes, async { + let client = lookup_client(PublicRoute::Direct, TIMEOUT)?; + let response = client + .get(endpoint) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .await + .map_err(|_| PublicAssetError::Unavailable)?; + read_details(response).await + }) + .await +} + +async fn read_details(mut response: reqwest::Response) -> Result<YoutubeDetails, PublicAssetError> { if response.status() != reqwest::StatusCode::OK || response .content_length() @@ -118,7 +126,11 @@ pub async fn fetch(routes: &RouteSource, raw: &str) -> Result<YoutubeDetails, Pu return Err(PublicAssetError::Unavailable); } let mut body = Vec::new(); - while let Some(chunk) = response.chunk().await.map_err(unavailable)? { + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| PublicAssetError::Unavailable)? + { if body.len() + chunk.len() > MAX_BODY_BYTES { return Err(PublicAssetError::Unavailable); } @@ -195,3 +207,96 @@ mod tests { assert_eq!(got.channel.chars().count(), MAX_CHANNEL_CHARS); } } + +#[cfg(test)] +#[tokio::test] +async fn fetch_refuses_invalid_input_before_route_admission() { + let routes = RouteSource::new(&tokio::runtime::Handle::current()); + assert_eq!( + fetch(&routes, "https://example.com/not-a-video").await, + Err(PublicAssetError::InvalidUrl) + ); +} + +#[cfg(test)] +#[tokio::test] +async fn oembed_response_maps_status_size_and_json_failures() { + use std::io::{Read, Write}; + let valid = br#"{"title":"Title","author_name":"Channel"}"#; + let cases = [ + ( + "200 OK", + format!("Content-Length: {}\r\n", valid.len()), + valid.to_vec(), + true, + ), + ( + "503 Service Unavailable", + "Content-Length: 0\r\n".into(), + Vec::new(), + false, + ), + ( + "200 OK", + format!("Content-Length: {}\r\n", MAX_BODY_BYTES + 1), + Vec::new(), + false, + ), + ( + "200 OK", + "Content-Length: 1\r\n".into(), + b"{".to_vec(), + false, + ), + ( + "200 OK", + "Transfer-Encoding: chunked\r\n".into(), + { + let mut encoded = format!("{:x}\r\n", MAX_BODY_BYTES + 1).into_bytes(); + encoded.resize(encoded.len() + MAX_BODY_BYTES + 1, b'x'); + encoded.extend_from_slice(b"\r\n0\r\n\r\n"); + encoded + }, + false, + ), + ]; + for (status, header, body, accepted) in cases { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let address = listener.local_addr().unwrap(); + let worker = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(TIMEOUT)).unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + let mut byte = [0]; + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + write!( + stream, + "HTTP/1.1 {status}\r\n{header}Connection: close\r\n\r\n" + ) + .unwrap(); + let _ = stream.write_all(&body); + }); + let response = reqwest::Client::builder() + .no_proxy() + .timeout(TIMEOUT) + .build() + .unwrap() + .get(format!("http://{address}/")) + .send() + .await + .unwrap(); + let expected = if accepted { + Ok(YoutubeDetails { + title: "Title".into(), + channel: "Channel".into(), + }) + } else { + Err(PublicAssetError::Unavailable) + }; + assert_eq!(read_details(response).await, expected); + worker.join().unwrap(); + } +} diff --git a/crates/zephium-agentic/src/public_asset.rs b/crates/zephium-agentic/src/public_asset.rs index cbbf68254..f257a3b88 100644 --- a/crates/zephium-agentic/src/public_asset.rs +++ b/crates/zephium-agentic/src/public_asset.rs @@ -49,6 +49,17 @@ pub(crate) async fn settled_route(routes: &RouteSource) -> PublicRoute { within(routes.settled(), || routes.route(), ROUTE_SETTLE_WAIT).await } +pub(crate) async fn with_direct_route<T>( + routes: &RouteSource, + operation: impl Future<Output = Result<T, PublicAssetError>>, +) -> Result<T, PublicAssetError> { + direct(settled_route(routes).await)?; + routes + .while_direct(operation) + .await + .map_err(|_| PublicAssetError::RouteRefused)? +} + fn direct(route: PublicRoute) -> Result<(), PublicAssetError> { match route { PublicRoute::Direct => Ok(()), @@ -161,19 +172,23 @@ pub async fn fetch_public_image( routes: &RouteSource, url: &str, ) -> Result<Vec<u8>, PublicAssetError> { - image(settled_route(routes), public_resolver(), url).await + let parsed = image_target(url)?; + with_direct_route(routes, fetch_image(public_resolver(), url, parsed)).await } -async fn image( - route: impl Future<Output = PublicRoute>, - resolver: Arc<dyn Resolve>, - url: &str, -) -> Result<Vec<u8>, PublicAssetError> { +fn image_target(url: &str) -> Result<url::Url, PublicAssetError> { let parsed = url::Url::parse(url).map_err(|_| PublicAssetError::InvalidUrl)?; if !public_https(&parsed) { return Err(PublicAssetError::InvalidUrl); } - direct(route.await)?; + Ok(parsed) +} + +async fn fetch_image( + resolver: Arc<dyn Resolve>, + url: &str, + parsed: url::Url, +) -> Result<Vec<u8>, PublicAssetError> { let client = public_client(resolver)?; if let Some(variant) = display_variant(url).and_then(|v| url::Url::parse(&v).ok()) { if let Ok(bytes) = fetch_with(&client, variant).await { @@ -189,20 +204,23 @@ pub async fn fetch_public_record_image( routes: &RouteSource, raw: &str, ) -> Result<Vec<u8>, PublicAssetError> { - record_image(settled_route(routes), public_resolver(), raw).await + let target = record_target(raw)?; + with_direct_route(routes, fetch_record_image(public_resolver(), target)).await } -async fn record_image( - route: impl Future<Output = PublicRoute>, - resolver: Arc<dyn Resolve>, - raw: &str, -) -> Result<Vec<u8>, PublicAssetError> { +fn record_target(raw: &str) -> Result<crate::ContextNavigationTarget, PublicAssetError> { let target = crate::ContextNavigationTarget::parse(raw).map_err(|_| PublicAssetError::InvalidUrl)?; if !public_https(target.as_url()) || !crate::semantic_wire::model_safe_public_url(&target) { return Err(PublicAssetError::InvalidUrl); } - direct(route.await)?; + Ok(target) +} + +async fn fetch_record_image( + resolver: Arc<dyn Resolve>, + target: crate::ContextNavigationTarget, +) -> Result<Vec<u8>, PublicAssetError> { let client = public_client_builder(resolver) .redirect(Policy::none()) .build() @@ -235,6 +253,10 @@ fn public_client(resolver: Arc<dyn Resolve>) -> Result<Client, PublicAssetError> .build() .map_err(|_| PublicAssetError::Unavailable) } +fn permits_redirect(previous: usize, target: &url::Url) -> bool { + previous <= MAX_REDIRECTS && public_https(target) +} + fn public_client_builder(resolver: Arc<dyn Resolve>) -> reqwest::ClientBuilder { Client::builder() .no_proxy() @@ -242,10 +264,10 @@ fn public_client_builder(resolver: Arc<dyn Resolve>) -> reqwest::ClientBuilder { .https_only(true) .redirect(Policy::custom(|attempt| { // `previous()` starts with the original request, not a redirect. - if attempt.previous().len() > MAX_REDIRECTS || !public_https(attempt.url()) { - attempt.stop() - } else { + if permits_redirect(attempt.previous().len(), attempt.url()) { attempt.follow() + } else { + attempt.stop() } })) .referer(false) @@ -311,6 +333,26 @@ async fn fetch_bounded( #[cfg(test)] mod tests { + async fn image( + route: impl Future<Output = PublicRoute>, + resolver: Arc<dyn Resolve>, + url: &str, + ) -> Result<Vec<u8>, PublicAssetError> { + let parsed = image_target(url)?; + direct(route.await)?; + fetch_image(resolver, url, parsed).await + } + + async fn record_image( + route: impl Future<Output = PublicRoute>, + resolver: Arc<dyn Resolve>, + raw: &str, + ) -> Result<Vec<u8>, PublicAssetError> { + let target = record_target(raw)?; + direct(route.await)?; + fetch_record_image(resolver, target).await + } + #[tokio::test] async fn exact_record_fetch_refuses_private_and_secret_destinations_before_transport() { for url in [ @@ -615,3 +657,13 @@ mod tests { ); } } + +#[cfg(test)] +#[test] +fn public_redirect_policy_allows_three_hops_and_refuses_the_fourth() { + let target = url::Url::parse("https://example.com/asset.png").unwrap(); + assert!(permits_redirect(MAX_REDIRECTS, &target)); + assert!(!permits_redirect(MAX_REDIRECTS + 1, &target)); + let private = url::Url::parse("https://127.0.0.1/asset.png").unwrap(); + assert!(!permits_redirect(1, &private)); +} From 80797af8165c891aced357a70899d1a757b0baf6 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:15:43 +0100 Subject: [PATCH 25/40] fix(map): correct result, locator, navigation and text edge cases from review A deadline that passes before the results arrive fails the search, one sponsored label drops one result, route fragments survive destination cleanup, shell and wall places are not served from the memo, and a comparison side reports its anonymous-results failure. --- crates/zephium-map/src/doc/html.rs | 31 ++++- crates/zephium-map/src/doc/html/arena.rs | 14 ++- crates/zephium-map/src/doc/html/decode.rs | 12 +- crates/zephium-map/src/doc/html/tests.rs | 84 +++++++++++++ crates/zephium-map/src/key.rs | 5 +- crates/zephium-map/src/linked.rs | 7 +- crates/zephium-map/src/locator.rs | 1 + crates/zephium-map/src/passage.rs | 46 ++++++- crates/zephium-map/src/passage/question.rs | 115 +++++++++++------- crates/zephium-map/src/query.rs | 38 +++--- crates/zephium-map/src/results.rs | 35 +++++- crates/zephium-map/src/results/destination.rs | 4 +- crates/zephium-map/src/results/entity.rs | 8 ++ crates/zephium-map/src/session.rs | 66 ++++++++-- crates/zephium-map/src/session/memo.rs | 2 + crates/zephium-map/src/session/types.rs | 15 ++- crates/zephium-map/src/site.rs | 102 +++++++++++++--- crates/zephium-map/src/site/navigation.rs | 38 ++++-- crates/zephium-map/src/site/sitemap.rs | 3 + crates/zephium-map/tests/first_layer.rs | 35 ++++++ crates/zephium-map/tests/key.rs | 13 ++ crates/zephium-map/tests/passage.rs | 79 ++++++++++++ crates/zephium-map/tests/query.rs | 30 +++++ crates/zephium-map/tests/session.rs | 88 ++++++++++++++ crates/zephium-map/tests/site.rs | 111 +++++++++++++++++ 25 files changed, 864 insertions(+), 118 deletions(-) diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index b9600f9cf..445604cdc 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -298,8 +298,11 @@ impl DocBuilder { } } if !captured { + let excluded = self.lift_exclusions(parent, level); let (parent, _) = self.fit_parent(parent, level); - match self.push(Node::new(Role::Text, parent.map(|i| i as u32))) { + let mut node = Node::new(Role::Text, parent.map(|i| i as u32)); + node.marks.insert(excluded); + match self.push(node) { Ok(at) => self.append(at as usize, &words, verbatim), Err(DocError::Nodes | DocError::Depth) => self.mark_truncated(), Err(e) => return Err(e), @@ -308,6 +311,20 @@ impl DocBuilder { Ok(()) } + fn lift_exclusions(&self, parent: Option<usize>, level: usize) -> Marks { + let mut excluded = Marks::default(); + if level >= self.limits.depth as usize { + if let Some(at) = parent { + for mark in [Marks::ANCILLARY, Marks::GENERATED, Marks::SPONSORED] { + if self.doc.nodes[at].marks.has(mark) { + excluded.insert(mark); + } + } + } + } + excluded + } + fn fit_parent(&mut self, parent: Option<usize>, level: usize) -> (Option<usize>, usize) { if level >= self.limits.depth as usize { self.mark_truncated(); @@ -353,6 +370,9 @@ impl DocBuilder { { continue; } + if verbatim && tag_is(&n, "br") { + self.capture_text(parent, "\n", true, level)?; + } if n.loss() { self.mark_truncated() } @@ -401,11 +421,18 @@ impl DocBuilder { } else if tag_is(&n, "code") && in_sink && !verbatim { Some(Role::Text) } else { - classify(&n, n.tag(), in_sink).filter(|r| !(verbatim && *r == Role::CodeBlock)) + classify(&n, n.tag(), in_sink) + .filter(|r| !(verbatim && *r == Role::CodeBlock)) + .or_else(|| n.generated_by_lift().then_some(Role::Group)) }; let (parent, level) = if let Some(role) = role { + let excluded = self.lift_exclusions(parent, level); let (parent, level) = self.fit_parent(parent, level); let mut node = Node::new(role, parent.map(|i| i as u32)); + node.marks.insert(excluded); + if n.generated_by_lift() { + node.marks.insert(Marks::GENERATED); + } if ["data-layout", "data-type", "data-testid"] .iter() .any(|attr| n.attr(attr).is_some_and(|v| v.eq_ignore_ascii_case("ad"))) diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index 6ec56f1f8..f5d6cff3b 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -11,6 +11,7 @@ const LOSS: u8 = 8; const JSON: u8 = 16; const HIDDEN_BY_LIFT: u8 = 32; const ATTACHED: u8 = 64; +const GENERATED_BY_LIFT: u8 = 128; const ATTRIBUTE_NAMES: &[&str] = &[ "href", "src", @@ -146,6 +147,9 @@ impl<'a> NodeRef<'a> { pub(super) fn hidden_by_lift(self) -> bool { self.record().flags & HIDDEN_BY_LIFT != 0 } + pub(super) fn generated_by_lift(self) -> bool { + self.record().flags & GENERATED_BY_LIFT != 0 + } pub(super) fn sibling(self) -> Option<Self> { let next = self.record().next; (next != 0).then_some(self.arena.node(next)) @@ -353,11 +357,14 @@ impl Arena { let p = &self.records[parent as usize]; let no_text = p.flags & (OPAQUE | NO_TEXT) != 0; let mut hidden = p.flags & HIDDEN_BY_LIFT != 0; + let mut generated = p.flags & GENERATED_BY_LIFT != 0; if usize::from(p.depth) >= self.limits.arena_depth as usize && self.records[id as usize].flags & TEXT == 0 { self.lifted = true; - hidden |= super::hidden(&self.node(parent)) || no_text; + let lifted = self.node(parent); + hidden |= super::hidden(&lifted) || no_text; + generated |= super::marks(&lifted).has(super::Marks::GENERATED); parent = p.parent; before = 0; } @@ -397,7 +404,10 @@ impl Arena { n.prev = prev; n.next = before; n.depth = depth; - n.flags = (n.flags & !(NO_TEXT | HIDDEN_BY_LIFT)) | ATTACHED; + n.flags = (n.flags & !(NO_TEXT | HIDDEN_BY_LIFT | GENERATED_BY_LIFT)) | ATTACHED; + if generated { + n.flags |= GENERATED_BY_LIFT; + } if no_text { n.flags |= NO_TEXT } diff --git a/crates/zephium-map/src/doc/html/decode.rs b/crates/zephium-map/src/doc/html/decode.rs index 3081988c2..e206fc848 100644 --- a/crates/zephium-map/src/doc/html/decode.rs +++ b/crates/zephium-map/src/doc/html/decode.rs @@ -260,9 +260,17 @@ impl Tracer for LiveMarkup { pub(super) fn parse(bytes: &[u8], label: Option<&str>, limits: DocLimits) -> Arena { let enc = label .and_then(|v| charset(v.as_bytes())) - .or_else(|| meta_charset(bytes)) + .or_else(|| { + meta_charset(bytes).map(|hint| { + if hint == encoding_rs::UTF_16LE || hint == encoding_rs::UTF_16BE { + UTF_8 + } else { + hint + } + }) + }) .unwrap_or(UTF_8); - let mut decoder = enc.new_decoder_without_bom_handling(); + let mut decoder = enc.new_decoder(); let sink = Sink::new(Arena::new(limits)); let builder = TreeBuilder::new( sink, diff --git a/crates/zephium-map/src/doc/html/tests.rs b/crates/zephium-map/src/doc/html/tests.rs index 12c5caec8..9c1908fa6 100644 --- a/crates/zephium-map/src/doc/html/tests.rs +++ b/crates/zephium-map/src/doc/html/tests.rs @@ -373,3 +373,87 @@ fn large_inline_attributes_allow_later_content() { .iter() .all(|n| n.image_source.is_none() && !n.text.contains('Z'))); } + +#[test] +fn code_keeps_html_and_literal_line_breaks() { + let doc = document( + b"<pre><code># note<br>echo ready\nnext</code></pre>", + DocLimits::default(), + ); + assert!(doc + .nodes() + .iter() + .any(|n| n.role == Role::CodeBlock && n.text == "# note\necho ready\nnext")); +} + +#[test] +fn bom_takes_precedence_over_transport_and_meta() { + let page = Url::parse("https://example.com/").unwrap(); + let bytes = "\u{feff}<meta charset=windows-1252><p>café</p>".as_bytes(); + for label in [None, Some("windows-1252")] { + let doc = Doc::from_html(&page, bytes, label, DocLimits::default()).unwrap(); + assert!(doc.nodes().iter().any(|n| n.text == "café")); + } +} + +#[test] +fn html_meta_utf16_labels_describe_utf8() { + for meta in [ + "<meta charset=utf-16le>", + "<meta http-equiv=Content-Type content='text/html; charset=utf-16be'>", + ] { + let html = format!("{meta}<p>café</p>"); + assert!(document(html.as_bytes(), DocLimits::default()) + .nodes() + .iter() + .any(|n| n.text == "café")); + } + let page = Url::parse("https://example.com/").unwrap(); + let bytes: Vec<_> = "<p>café</p>" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + let doc = Doc::from_html(&page, &bytes, Some("utf-16le"), DocLimits::default()).unwrap(); + assert!(doc.nodes().iter().any(|n| n.text == "café")); +} + +#[test] +fn arena_and_document_lifts_preserve_generated_exclusion() { + let html = b"<main><div aria-label='AI overview'><p>Generated answer</p></div><div><p>Ordinary answer</p></div></main>"; + for limits in [ + DocLimits { + arena_depth: 4, + ..DocLimits::default() + }, + DocLimits { + depth: 3, + ..DocLimits::default() + }, + ] { + let doc = document(html, limits); + for (text, visible) in [("Generated answer", false), ("Ordinary answer", true)] { + let at = doc + .nodes() + .iter() + .position(|node| node.text == text) + .unwrap(); + assert_eq!(crate::visible(doc.nodes(), at), visible, "{text}"); + } + } +} + +#[test] +fn linked_answers_match_clean_text_but_never_empty_structural_nodes() { + let doc = document( + "<script type='application/ld+json'>{\"@type\":\"QAPage\",\"mainEntity\":{\"acceptedAnswer\":[{\"text\":\"a\u{200b}b\"},{\"text\":\" \"}]}}</script><main><p>a\u{200b}b</p><p>Unrelated</p></main>".as_bytes(), + DocLimits::default(), + ); + assert!(doc + .nodes() + .iter() + .any(|n| n.text == "ab" && n.marks.has(Marks::ACCEPTED))); + assert!(doc + .nodes() + .iter() + .all(|n| n.text == "ab" || !n.marks.has(Marks::ACCEPTED))); +} diff --git a/crates/zephium-map/src/key.rs b/crates/zephium-map/src/key.rs index e5e169261..ff2014656 100644 --- a/crates/zephium-map/src/key.rs +++ b/crates/zephium-map/src/key.rs @@ -164,7 +164,10 @@ impl PageKey { .filter(|s| keep_pair(s)) .map(normalize_percent) .collect(); - pairs.sort(); + pairs.sort_by(|a, b| { + let key = |pair: &str| pair.find('=').unwrap_or(pair.len()); + a[..key(a)].cmp(&b[..key(b)]) + }); if !pairs.is_empty() { value.push('?'); value.push_str(&pairs.join("&")); diff --git a/crates/zephium-map/src/linked.rs b/crates/zephium-map/src/linked.rs index 9cc07e46f..590779592 100644 --- a/crates/zephium-map/src/linked.rs +++ b/crates/zephium-map/src/linked.rs @@ -55,8 +55,11 @@ pub(crate) fn mark_answers(nodes: &mut [Node], head: &Head) { { ids.insert(id.to_owned(), mark); } - if let Some(text) = answer["text"].as_str().filter(|s| !s.is_empty()) { - texts.insert(crate::flatten(text), mark); + if let Some(text) = answer["text"].as_str() { + let key = crate::clean_text(&crate::flatten(text)); + if !key.is_empty() { + texts.insert(key, mark); + } } } } diff --git a/crates/zephium-map/src/locator.rs b/crates/zephium-map/src/locator.rs index 8de41948f..7ec6e78ca 100644 --- a/crates/zephium-map/src/locator.rs +++ b/crates/zephium-map/src/locator.rs @@ -219,6 +219,7 @@ impl Locator { (at + 1..nodes.len()) .find(|&i| { matches!(nodes[i].role,Role::Heading{level:l} if l<=level) + && crate::visible(nodes, i) || n.parent_index() .is_some_and(|p| !crate::ancestors(nodes, i).any(|a| a == p)) }) diff --git a/crates/zephium-map/src/passage.rs b/crates/zephium-map/src/passage.rs index 352343d8d..966b7d012 100644 --- a/crates/zephium-map/src/passage.rs +++ b/crates/zephium-map/src/passage.rs @@ -515,10 +515,7 @@ pub fn read_passages(q: &QueryRead, docs: &[&Doc]) -> Vec<Passage> { matches!(s.as_str(), "fix" | "solution" | "resolution" | "answer") }) }); - if !next.accepted - && !remedy - && (next.scope != b.scope || next.heading != b.heading) - { + if next.scope != b.scope || !remedy && next.heading != b.heading { break; } if next.accepted || docs[next.doc].nodes()[next.node].role == Role::CodeBlock { @@ -687,7 +684,11 @@ pub fn read_passages(q: &QueryRead, docs: &[&Doc]) -> Vec<Passage> { pub(crate) fn featured(q: &QueryRead, f: &Featured, result: &Organic) -> Option<Passage> { let terms = query_terms(q); let present: BTreeSet<_> = tokens(&f.text).collect(); - if terms.is_empty() || !terms.is_subset(&present) { + let title = tokens(&result.title).collect(); + if terms.is_empty() + || !terms.is_subset(&present) + || !question::TaskQualifiers::new(q.terms(), &title).permits(&f.text) + { return None; } let text = cut(&f.text, false)?.to_owned(); @@ -702,3 +703,38 @@ pub(crate) fn featured(q: &QueryRead, f: &Featured, result: &Organic) -> Option< confidence: Confidence::High, }) } + +#[cfg(test)] +#[test] +fn featured_excerpts_obey_the_same_task_qualifiers_as_articles() { + let q = crate::read_query("loom remove all spools").unwrap(); + let url = url::Url::parse("https://example.com/guide").unwrap(); + let key = crate::PageKey::from_url(&url).unwrap(); + let result = Organic { + key: key.clone(), + url, + title: "Loom guide".into(), + snippet: None, + rank: 1, + official: None, + discussion: false, + sitelinks: Vec::new(), + }; + for (text, accepted) in [ + ("Loom can remove all spools without thread.", false), + ("In Loom, remove all spools before restarting.", true), + ] { + assert_eq!( + featured( + &q, + &Featured { + text: text.into(), + cites: key.clone() + }, + &result + ) + .is_some(), + accepted + ); + } +} diff --git a/crates/zephium-map/src/passage/question.rs b/crates/zephium-map/src/passage/question.rs index 30437ece9..a8b585460 100644 --- a/crates/zephium-map/src/passage/question.rs +++ b/crates/zephium-map/src/passage/question.rs @@ -70,7 +70,7 @@ pub(super) fn contrast( if sides.iter().any(BTreeSet::is_empty) || sides[0] == sides[1] { return Vec::new(); } - let mut leads = [None, None]; + let mut leads = [Vec::new(), Vec::new()]; for (page, doc) in docs.iter().take(MAX_RESULT_PAGES).enumerate() { let title: BTreeSet<_> = tokens(&doc.head().title).collect(); let mut first = true; @@ -94,24 +94,27 @@ pub(super) fn contrast( .flat_map(|h| tokens(&doc.nodes()[h].text)) .collect(); for (i, side) in sides.iter().enumerate() { - if leads[i].is_none() - && [&heading, &title] - .iter() - .any(|label| side.is_subset(label) && !sides[1 - i].is_subset(label)) + if [&heading, &title] + .iter() + .any(|label| side.is_subset(label) && !sides[1 - i].is_subset(label)) && side.is_subset(&present) { - leads[i] = Some((page, b)); + if let Some(passage) = make(b, doc) { + leads[i].push(passage); + } } } first = false; } } } - if let [Some((left, a)), Some((right, b))] = leads { - if let Some((a, b)) = make(a, docs[left]).zip(make(b, docs[right])) { - if a.source.page_match() != b.source.page_match() { - return vec![a, b]; - } + let [left, right] = leads; + for a in left { + if let Some(b) = right + .iter() + .find(|b| a.source.page_match() != b.source.page_match()) + { + return vec![a, b.clone()]; } } Vec::new() @@ -121,6 +124,10 @@ pub(super) struct Question { context: u64, all: u64, task: bool, + qualifiers: TaskQualifiers, +} + +pub(super) struct TaskQualifiers { quantity: Option<String>, last: Option<String>, } @@ -153,44 +160,12 @@ impl Question { context, all: u64::MAX >> (MAX_CONTENT_TERMS - count), task: terms.first().is_some_and(|t| t == "how") || terms.iter().any(|t| action(t)), - last: terms.iter().position(|t| t == "last").and_then(|at| { - let tail = terms.get(at + 1..)?; - let noun = if tail.len() > 1 && title.contains(&tail[0]) { - &tail[1] - } else { - tail.first()? - }; - Some(noun.trim_end_matches('?').to_owned()) - }), - quantity: terms - .windows(2) - .find(|pair| pair[0] == "all") - .map(|pair| pair.join(" ")), + qualifiers: TaskQualifiers::new(terms, &title), } } pub(super) fn permits(&self, text: &str) -> bool { - if self.quantity.is_none() && self.last.is_none() { - return true; - } - let text = text.to_lowercase(); - let quantified = self.quantity.as_ref().is_none_or(|phrase| { - text.match_indices(phrase).any(|(i, _)| { - let rest = &text[i + phrase.len()..]; - !text[..i].ends_with(char::is_alphanumeric) - && (rest.is_empty() || rest.starts_with(['.', ',', ':', '!', '?', '\n'])) - }) - }); - quantified - && self.last.as_ref().is_none_or(|noun| { - let mut words = tokens(&text); - let mut previous = words.next(); - words.any(|word| { - let found = word == *noun && previous.as_deref() == Some("last"); - previous = Some(word); - found - }) - }) + self.qualifiers.permits(text) } pub(super) fn best( @@ -288,3 +263,53 @@ impl Question { } } } + +impl TaskQualifiers { + pub(super) fn new(terms: &[String], title: &BTreeSet<String>) -> Self { + Self { + last: terms.iter().position(|t| t == "last").and_then(|at| { + let tail = terms.get(at + 1..)?; + let noun = if tail.len() > 1 && title.contains(&tail[0]) { + &tail[1] + } else { + tail.first()? + }; + Some(noun.trim_end_matches('?').to_owned()) + }), + quantity: terms + .windows(2) + .find(|pair| pair[0] == "all") + .map(|pair| pair.join(" ")), + } + } + + pub(super) fn permits(&self, text: &str) -> bool { + if self.quantity.is_none() && self.last.is_none() { + return true; + } + let text = text.to_lowercase(); + let quantified = self.quantity.as_ref().is_none_or(|phrase| { + text.match_indices(phrase).any(|(i, _)| { + let rest = &text[i + phrase.len()..]; + !text[..i].ends_with(char::is_alphanumeric) + && (rest.is_empty() + || rest.starts_with(['.', ',', ':', '!', '?', '\n']) + || rest.starts_with(char::is_whitespace) + && matches!( + rest.split_whitespace().next(), + Some("before" | "after" | "when") + )) + }) + }); + quantified + && self.last.as_ref().is_none_or(|noun| { + let mut words = tokens(&text); + let mut previous = words.next(); + words.any(|word| { + let found = word == *noun && previous.as_deref() == Some("last"); + previous = Some(word); + found + }) + }) + } +} diff --git a/crates/zephium-map/src/query.rs b/crates/zephium-map/src/query.rs index 2ac1dfbe6..238c7dab4 100644 --- a/crates/zephium-map/src/query.rs +++ b/crates/zephium-map/src/query.rs @@ -358,11 +358,13 @@ pub fn read_query(text: &str) -> Result<QueryRead, QueryError> { .any(|frame| phrase.contains(frame)); let (entity, section) = split_section(&terms); let mut confidence = Confidence::High; - let kind = if pasted(text, &terms) { + let kind = if arithmetic(text) { + QueryKind::Instant + } else if pasted(text, &terms) { QueryKind::Passage { kind: PassageKind::Pasted, } - } else if instant(&terms, &phrase) { + } else if instant(&terms) { QueryKind::Instant } else if question || concept_comparison(&terms) { QueryKind::Passage { @@ -412,13 +414,16 @@ pub fn read_query(text: &str) -> Result<QueryRead, QueryError> { let entity = if fresh { entity .iter() - .filter(|w| { - !matches!( + .enumerate() + .filter(|(index, w)| { + !(matches!( w.as_str(), - "new" | "latest" | "news" | "announcement" | "announcements" - ) + "latest" | "news" | "announcement" | "announcements" + ) || *index == 0 + && w.as_str() == "new" + && fresh_word.is_some_and(|(word, _)| *word == "new")) }) - .cloned() + .map(|(_, word)| word.clone()) .collect() } else { entity.to_vec() @@ -468,7 +473,7 @@ pub fn read_query(text: &str) -> Result<QueryRead, QueryError> { }) } -fn instant(terms: &[String], phrase: &str) -> bool { +fn instant(terms: &[String]) -> bool { let words: Vec<_> = terms.iter().map(String::as_str).collect(); let number = |s: &str| s.parse::<f64>().is_ok_and(f64::is_finite); let unit = |s: &str| { @@ -541,16 +546,19 @@ fn instant(terms: &[String], phrase: &str) -> bool { CITIES.contains(&place.join(" ").as_str()) || words.first() == Some(&"weather") && place.is_empty() } - _ => { - phrase.bytes().any(|b| b.is_ascii_digit()) - && phrase.bytes().any(|b| b"+-*/".contains(&b)) - && phrase - .bytes() - .all(|b| b.is_ascii_digit() || b"+-*/(). ".contains(&b)) - } + _ => false, } } +fn arithmetic(text: &str) -> bool { + text.bytes().any(|b| b.is_ascii_digit()) + && text.bytes().any(|b| b"+-*/".contains(&b)) + && text + .bytes() + .all(|b| b.is_ascii_digit() || b.is_ascii_whitespace() || b"+-*/().".contains(&b)) + && !text.trim_start().starts_with('/') +} + fn listing(terms: &[String]) -> bool { let words: Vec<_> = terms.iter().map(String::as_str).collect(); match words.as_slice() { diff --git a/crates/zephium-map/src/results.rs b/crates/zephium-map/src/results.rs index 4a07f8c5c..70d044ce8 100644 --- a/crates/zephium-map/src/results.rs +++ b/crates/zephium-map/src/results.rs @@ -204,6 +204,8 @@ fn past_address(text: &str) -> Option<String> { if address_like(word) || *word == "›" || crumb { end = Some(at + 1); crumb = *word == "›"; + } else if end.is_some() { + break; } } let rest = words[end?..].join(" "); @@ -539,7 +541,14 @@ impl<'a> Page<'a> { .last() } - fn paid(&self, title: &Title, scope: Option<usize>, start: usize, end: usize) -> bool { + fn paid( + &self, + title: &Title, + scope: Option<usize>, + start: usize, + end: usize, + next_prefix: Option<usize>, + ) -> bool { if self.context[title.at].paid || matches!(title.destination, Err(Drop::Paid)) { return true; } @@ -564,7 +573,7 @@ impl<'a> Page<'a> { || (inside_end..end) .filter(|&i| !words(&self.nodes[i]).is_empty()) .take(LABELS_AFTER) - .any(label) + .any(|i| next_prefix.is_none_or(|start| i < start) && label(i)) { return true; } @@ -688,7 +697,18 @@ pub fn read_results_with_stats( .get(pos + 1) .map_or(page.nodes.len(), |n| scopes[pos + 1].unwrap_or(n.at)); let scope = scopes[pos]; - if page.paid(title, scope, start, end) { + let next_prefix = titles.get(pos + 1).and_then(|next| { + let next_start = scopes[pos + 1] + .filter(|&p| matches!(page.nodes[p].role, Role::Document | Role::ListItem)) + .or_else(|| scope.map(|i| page.context[i].end)) + .unwrap_or(title.at + 1); + (next_start..next.at) + .rev() + .filter(|&i| !words(&page.nodes[i]).is_empty()) + .take(LABELS_BEFORE) + .last() + }); + if page.paid(title, scope, start, end, next_prefix) { layer.dropped.paid += 1; excluded[scope.unwrap_or(title.at)..scope.map_or(end, |p| page.context[p].end)] .fill(true); @@ -833,3 +853,12 @@ impl Page<'_> { } } } + +#[cfg(test)] +#[test] +fn address_prefix_does_not_consume_address_like_title_words() { + assert_eq!( + past_address("example.net › docs New Node.js Guide").as_deref(), + Some("New Node.js Guide") + ); +} diff --git a/crates/zephium-map/src/results/destination.rs b/crates/zephium-map/src/results/destination.rs index 4336b1482..9090cba2d 100644 --- a/crates/zephium-map/src/results/destination.rs +++ b/crates/zephium-map/src/results/destination.rs @@ -98,7 +98,9 @@ impl Rules<'_> { } else { source.clone() }; - url.set_fragment(None); + if !url.fragment().is_some_and(crate::key::route) { + url.set_fragment(None); + } Ok(url) } } diff --git a/crates/zephium-map/src/results/entity.rs b/crates/zephium-map/src/results/entity.rs index 2ca1ce8ce..3aa42f346 100644 --- a/crates/zephium-map/src/results/entity.rs +++ b/crates/zephium-map/src/results/entity.rs @@ -175,6 +175,14 @@ fn profile(url: &Url, title: &str, entity: Option<&Entity>) -> Option<Network> { } let handle = match (net, section) { (Network::YouTube | Network::Mastodon, "") => last.strip_prefix('@')?, + (Network::GitHub, "") + if ["pricing", "login"] + .iter() + .any(|p| last.eq_ignore_ascii_case(p)) => + { + return None + } + (Network::Twitter, "") if last.eq_ignore_ascii_case("search") => return None, (Network::Twitter | Network::GitHub | Network::Instagram | Network::Facebook, "") => last, (Network::LinkedIn, "company" | "in" | "school") | (Network::Reddit, "r") diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index 72cd524cc..cdaf2a7eb 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -488,6 +488,20 @@ impl Session { } self.enqueue(Work::Entry(i), url); } + pub fn accepted_passage_pages(&self) -> usize { + self.articles.len() + + self + .sites + .iter() + .flatten() + .filter(|site| { + site.shared_passage.is_some() + && site.doc.is_some() + && site.place.as_ref().is_some_and(|place| !place.notes.wall) + }) + .count() + } + fn update_passages(&mut self, out: &mut Vec<Effect>) { let mut ordered: BTreeMap<_, _> = self.articles.iter().map(|(pos, doc)| (*pos, doc)).collect(); @@ -729,7 +743,15 @@ impl Session { self.elapsed = self.elapsed.max(time); if self.elapsed >= self.cfg.elapsed { self.budget(Budget::Elapsed); - self.finish(&mut out); + if self + .pending + .values() + .any(|pending| matches!(pending, Pending::Results)) + { + self.fail_initial_results(Failure::Timeout, &mut out); + } else { + self.finish(&mut out); + } return out; } } @@ -750,15 +772,7 @@ impl Session { Some(Pending::Results) => { self.counts(Phase::Results).completed += 1; if let Err(f) = result.and_then(|doc| self.results(doc, &mut out)) { - self.finished = true; - self.refused(Phase::Results, f); - self.emit( - MapEvent::End { - outcome: EndOutcome::Failed { failure: f }, - stats: self.stats.clone(), - }, - &mut out, - ); + self.fail_initial_results(f, &mut out); return out; } } @@ -771,9 +785,26 @@ impl Session { Ok(doc) => { if let Some(seed) = self.side_seed(&doc, &text) { self.lookup(i, seed, &mut out); + } else { + self.emit( + MapEvent::PlaceFailed { + slot: i as u8, + failure: Failure::Missing, + }, + &mut out, + ); } } - Err(f) => self.refused(Phase::AnonymousResults, f), + Err(failure) => { + self.refused(Phase::AnonymousResults, failure); + self.emit( + MapEvent::PlaceFailed { + slot: i as u8, + failure, + }, + &mut out, + ); + } } } _ => {} @@ -828,6 +859,19 @@ impl Session { self.schedule(&mut out); out } + fn fail_initial_results(&mut self, failure: Failure, out: &mut Vec<Effect>) { + self.finished = true; + self.pending.clear(); + self.refused(Phase::Results, failure); + self.emit( + MapEvent::End { + outcome: EndOutcome::Failed { failure }, + stats: self.stats.clone(), + }, + out, + ); + } + fn done(&mut self, out: &mut Vec<Effect>) { self.finished = true; self.pending.clear(); diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index f260155d6..44fbc7cc8 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -49,6 +49,8 @@ impl SiteMemo { || SiteKey::from_url(p.entry.as_url()).as_ref() != Some(&p.site) || p.title.len() > TITLE_BYTES || p.focus.is_some() + || p.notes.shell + || p.notes.wall || p.sections .iter() .filter(|e| e.tier == site::Tier::Primary) diff --git a/crates/zephium-map/src/session/types.rs b/crates/zephium-map/src/session/types.rs index 2d7f18678..b610001fa 100644 --- a/crates/zephium-map/src/session/types.rs +++ b/crates/zephium-map/src/session/types.rs @@ -305,7 +305,20 @@ impl FetchResult { Expect::Html => matches!(media.as_str(), "text/html" | "application/xhtml+xml"), Expect::Text => matches!(media.as_str(), "text/plain" | "text/markdown"), Expect::Xml => { - matches!(media.as_str(), "text/xml" | "application/xml") || media.ends_with("+xml") + matches!(media.as_str(), "text/xml" | "application/xml") + || media.split_once('/').is_some_and(|(kind, subtype)| { + let token = |value: &str| { + !value.is_empty() + && value.bytes().all(|b| { + b.is_ascii_alphanumeric() || b"!#$%&'*+-.^`_|~".contains(&b) + }) + }; + token(kind) + && token(subtype) + && subtype + .strip_suffix("+xml") + .is_some_and(|base| !base.is_empty()) + }) } } } diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 39f63d8c4..76af78100 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -331,6 +331,15 @@ impl Build<'_> { } } fn entry_for(&self, url: &Url, label: &str, source: Source) -> Option<Entry> { + self.entry_for_site(url, label, source, &self.site) + } + fn entry_for_site( + &self, + url: &Url, + label: &str, + source: Source, + scope: &SiteKey, + ) -> Option<Entry> { let key = PageKey::from_url(url).ok()?; let site = SiteKey::from_url(url)?; let label = clip(&crate::clean_text(label.trim()), TITLE_BYTES); @@ -339,7 +348,7 @@ impl Build<'_> { } let role = section_role(&label, url); let off_site = site != self.site; - if site != self.site + if &site != scope && !(matches!( source, Source::PrimaryNav | Source::MenuGroup | Source::Footer @@ -347,17 +356,7 @@ impl Build<'_> { { return None; } - let locator = if let Some(fragment) = url - .fragment() - .filter(|s| !s.is_empty() && !crate::key::route(s)) - { - Locator { - element: Some(LocatorText::new(&decode_fragment(fragment)).ok()?), - ..Default::default() - } - } else { - Locator::default() - }; + let locator = element_locator(url).ok()?; Some(Entry { id: EntryId::new(None, &key, &locator), read: None, @@ -397,8 +396,8 @@ impl Build<'_> { let globals: BTreeSet<_> = self .sections .iter() - .map(|e| e.key.page_match()) - .chain(std::iter::once(self.entry.page_match())) + .map(|e| (e.key.page_match(), e.locator.fragment())) + .chain(std::iter::once((self.entry.page_match(), None))) .collect(); let first_signup = self .sections @@ -417,7 +416,8 @@ impl Build<'_> { e.tier = Tier::Secondary; } e.children.retain(|c| { - c.sources.contains(&Source::Heading) || !globals.contains(&c.key.page_match()) + c.sources.contains(&Source::Heading) + || !globals.contains(&(c.key.page_match(), c.locator.fragment())) }); } self.sections.sort_by_cached_key(|e| (e.tier, demoted(e))); @@ -754,6 +754,19 @@ impl Place { entries } } +fn element_locator(url: &Url) -> Result<Locator, KeyError> { + let Some(fragment) = url + .fragment() + .filter(|s| !s.is_empty() && !crate::key::route(s)) + else { + return Ok(Locator::default()); + }; + Ok(Locator { + element: Some(LocatorText::new(&decode_fragment(fragment))?), + ..Default::default() + }) +} + fn decode_fragment(s: &str) -> String { url::form_urlencoded::parse( format!("id={}", s.replace('+', "%2B").replace('&', "%26")).as_bytes(), @@ -892,7 +905,25 @@ pub(crate) fn with_results( place, stats: PlaceStats::default(), }; - build.add_results(links, hint); + for (link, source) in links + .iter() + .take(MAX_SITELINKS) + .map(|link| (link, Source::EngineSitelink)) + .chain(hint.map(|link| (link, Source::EngineResult))) + { + if let Some(entry) = build.entry_for(&link.url, &link.title, source) { + if let Some(existing) = build + .sections + .iter_mut() + .find(|existing| existing.id == entry.id) + { + existing.add_sources(entry.sources); + } else { + build.section(entry); + } + } + } + build.stats.sitelinks_truncated = links.len() > MAX_SITELINKS; build.finish_sections(); build.notes.truncated |= build.stats.truncated(); build.check_ids()?; @@ -1096,3 +1127,42 @@ mod tests { } } } + +#[cfg(test)] +mod review_tests { + use super::*; + + #[test] + fn result_sitelink_merges_with_the_discovered_id_after_a_redirect() { + let base = Url::parse("https://example.com/").unwrap(); + let doc = |url: &Url, html: &str| { + Doc::from_html(url, html.as_bytes(), None, crate::DocLimits::SITE_PAGE).unwrap() + }; + let home = doc(&base, "<nav><a href='/docs'>Documentation</a></nav>"); + let original = base.join("/docs").unwrap(); + let landing = doc(&base.join("/guide").unwrap(), "<p>Guide</p>"); + let place = read_site( + &home, + &SiteInputs { + pages: [(PageKey::from_url(&original).unwrap(), &landing)].into(), + ..SiteInputs::default() + }, + ) + .unwrap(); + let discovered = place.sections[0].id.clone(); + let merged = with_results( + place, + &[Link { + url: original, + title: "Docs".into(), + }], + None, + None, + ) + .unwrap(); + assert_eq!(merged.sections.len(), 1); + assert!(merged.sections[0].id == discovered); + assert_eq!(merged.sections[0].key.as_url().path(), "/guide"); + assert!(merged.sections[0].sources.contains(&Source::EngineSitelink)); + } +} diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index 0a6bbfbbd..5a691afa3 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -12,10 +12,12 @@ impl Build<'_> { } && visible(nodes, i) && !ancestors(nodes, i).any(|a| { - nodes[a].role - == Role::Landmark { - landmark: Some(Landmark::Complementary), + matches!( + nodes[a].role, + Role::Landmark { + landmark: Some(Landmark::Complementary | Landmark::Contentinfo), } + ) }) }); let mut owners = BTreeMap::new(); @@ -132,9 +134,17 @@ impl Build<'_> { && matches!( n.role, Role::Landmark { - landmark: Some(Landmark::Navigation | Landmark::Banner) + landmark: Some(Landmark::Navigation | Landmark::Banner), } ) + && !ancestors(nodes, i).any(|a| { + matches!( + nodes[a].role, + Role::Landmark { + landmark: Some(Landmark::Contentinfo), + } + ) + }) }) { return; } @@ -247,6 +257,11 @@ impl Build<'_> { let Ok(key) = PageKey::from_url(doc.page()) else { return; }; + if !crate::key::same_page(doc.page(), self.sections[index].key.as_url()) + || doc.page().fragment().is_some() + { + self.sections[index].locator = element_locator(doc.page()).unwrap_or_default(); + } self.sections[index].key = key.clone(); self.sections[index].off_site = SiteKey::from_url(key.as_url()).as_ref() != Some(&self.site); @@ -344,14 +359,13 @@ impl Build<'_> { let child = self .entry_for(url, n.accessible_name(), Source::SectionSidebar) .or_else(|| { - if SiteKey::from_url(url)? != SiteKey::from_url(doc.page())? { - return None; - } - let mut e = - self.sections[index].leaf(Source::SectionSidebar, n.accessible_name()); - e.key = PageKey::from_url(url).ok()?; - e.role = section_role(&e.label, url); - Some(e) + let scope = SiteKey::from_url(doc.page())?; + self.entry_for_site( + url, + n.accessible_name(), + Source::SectionSidebar, + &scope, + ) }); if let Some(mut e) = child.filter(|e| { let page = e.key.page_match(); diff --git a/crates/zephium-map/src/site/sitemap.rs b/crates/zephium-map/src/site/sitemap.rs index c15083c27..d7639e4a2 100644 --- a/crates/zephium-map/src/site/sitemap.rs +++ b/crates/zephium-map/src/site/sitemap.rs @@ -123,6 +123,9 @@ impl Sitemap { }; value.push(c); } + Event::CData(_) | Event::GeneralRef(_) if depth == 0 => { + return Err(XmlError::Malformed); + } Event::DocType(_) => return Err(XmlError::Malformed), Event::Empty(tag) if depth == 0 => { if root || !matches!(tag.local_name().as_ref(), "urlset" | "sitemapindex") { diff --git a/crates/zephium-map/tests/first_layer.rs b/crates/zephium-map/tests/first_layer.rs index dc6790899..1a72eeaa9 100644 --- a/crates/zephium-map/tests/first_layer.rs +++ b/crates/zephium-map/tests/first_layer.rs @@ -378,3 +378,38 @@ fn repeat_count(html: &str) -> u32 { ); stats.repeat } + +#[test] +fn one_unscoped_paid_label_only_marks_the_following_card() { + let l = layer("acme", "<main><h2><a href='https://acme.com/'>Acme</a></h2><p>Sponsored</p><h2><a href='https://promotion.example/'>Promotion</a></h2></main>"); + assert_eq!(l.dropped.paid, 1); + assert_eq!( + l.organic + .iter() + .map(|hit| hit.title.as_str()) + .collect::<Vec<_>>(), + ["Acme"] + ); +} + +#[test] +fn a_unique_trailing_paid_label_still_marks_its_card() { + let l = layer("acme", "<main><h2><a href='https://promotion.example/'>Promotion</a></h2><p>Sponsored</p><p>One</p><p>Two</p><p>Three</p><p>Four</p><h2><a href='https://acme.com/'>Acme</a></h2></main>"); + assert_eq!(l.dropped.paid, 1); + assert_eq!(l.organic[0].title, "Acme"); +} + +#[test] +fn both_direct_and_wrapped_result_destinations_keep_route_fragments() { + let first = card("example.net/app#/docs", "Docs"); + let second = "<article><h2><a href='/url?q=https%3A%2F%2Fexample.net%2Fapp%23%2Fpricing'>Pricing</a></h2></article>"; + let ordinary = card("example.net/plain#heading", "Plain"); + let l = layer("acme", &format!("<main>{first}{second}{ordinary}</main>")); + assert_eq!( + l.organic + .iter() + .map(|hit| hit.url.fragment()) + .collect::<Vec<_>>(), + [Some("/docs"), Some("/pricing"), None] + ); +} diff --git a/crates/zephium-map/tests/key.rs b/crates/zephium-map/tests/key.rs index 6e5f9232f..6e5c176bf 100644 --- a/crates/zephium-map/tests/key.rs +++ b/crates/zephium-map/tests/key.rs @@ -155,3 +155,16 @@ fn place_keys_scope_hosts_and_tenants() { assert_eq!(place("www.acme.com/deep"), place("acme.com/")); assert_ne!(place("docs.acme.com/"), place("acme.com/")); } + +#[test] +fn page_match_preserves_relative_order_of_repeated_parameters() { + let original = key("https://example.com/?sort=name&count=10&sort=date").page_match(); + assert_eq!( + original, + key("https://example.com/?count=10&sort=name&sort=date").page_match() + ); + assert_ne!( + original, + key("https://example.com/?sort=date&count=10&sort=name").page_match() + ); +} diff --git a/crates/zephium-map/tests/passage.rs b/crates/zephium-map/tests/passage.rs index 979a221ee..fb499e40b 100644 --- a/crates/zephium-map/tests/passage.rs +++ b/crates/zephium-map/tests/passage.rs @@ -530,3 +530,82 @@ fn textual_list_values_keep_inline_content_and_the_subject_heading() { let answers = read_passages(&read_query("loom storage default").unwrap(), &[&page]); assert_eq!(answers[0].text, "Storage\nDefault mode Read only"); } + +#[test] +fn accepted_answers_do_not_cross_unrelated_issue_headings() { + let page = doc("issues", "<main><h2>Bucket failure</h2><pre>TypeError: invalid bucket</pre><h2>Printer setup</h2><div itemprop='acceptedAnswer'><pre>printer.reset()</pre></div></main>"); + let query = read_query("TypeError: invalid bucket").unwrap(); + assert_eq!( + read_passages(&query, &[&page])[0].text, + "TypeError: invalid bucket" + ); +} + +#[test] +fn timing_clause_can_follow_an_unrestricted_task_quantity() { + let page = doc( + "guide", + "<title>Loom guide</title><p>Remove all spools before restarting.</p>", + ); + let q = read_query("loom remove all spools").unwrap(); + assert_eq!( + read_passages(&q, &[&page])[0].text, + "Remove all spools before restarting." + ); +} + +#[test] +fn comparison_skips_an_alias_to_find_a_distinct_second_source() { + let a = doc( + "codes", + "<h1>471 Empty</h1><p>Code 471 means the box is empty.</p>", + ); + let alias = doc( + "codes/", + "<h1>472 Full</h1><p>Code 472 means the box is full.</p>", + ); + let b = doc( + "full", + "<h1>472 Full</h1><p>Code 472 means the box is full.</p>", + ); + let q = read_query("difference between 471 and 472").unwrap(); + let answer = read_passages(&q, &[&a, &alias, &b]); + assert_eq!(answer.len(), 2); + assert_eq!(answer[1].source.as_url().path(), "/full"); +} + +#[test] +fn invisible_heading_does_not_end_the_visible_anchor_scope() { + use zephium_map::{ + doc::{Marks, Role}, + key::{LocatorText, TextQuote}, + }; + let url = Url::parse("https://example.com/").unwrap(); + let mut b = DocBuilder::new(&url, DocLimits::ARTICLE).unwrap(); + let main = b.push(Node::new(Role::Group, None)).unwrap(); + let mut heading = Node::new(Role::Heading { level: Some(2) }, Some(main)); + heading.element_id = Some("first".into()); + b.push(heading).unwrap(); + let mut hidden = Node::new(Role::Heading { level: Some(2) }, Some(main)); + hidden.marks.insert(Marks::GENERATED); + b.push(hidden).unwrap(); + let mut p = Node::new(Role::Paragraph, Some(main)); + p.text = "Repeated phrase".into(); + let first = b.push(p).unwrap(); + b.push(Node::new(Role::Heading { level: Some(2) }, Some(main))) + .unwrap(); + let mut p = Node::new(Role::Paragraph, Some(main)); + p.text = "Repeated phrase".into(); + b.push(p).unwrap(); + let locator = Locator { + element: Some(LocatorText::new("first").unwrap()), + quote: Some(TextQuote { + start: LocatorText::new("Repeated phrase").unwrap(), + prefix: None, + suffix: None, + end: None, + }), + position: None, + }; + assert_eq!(locator.resolve(&b.finish()), Some(first..first + 1)); +} diff --git a/crates/zephium-map/tests/query.rs b/crates/zephium-map/tests/query.rs index c39d33a47..7d851ded7 100644 --- a/crates/zephium-map/tests/query.rs +++ b/crates/zephium-map/tests/query.rs @@ -464,3 +464,33 @@ fn action_words_need_a_following_term() { ); } } + +#[test] +fn arithmetic_division_and_file_paths_are_distinct() { + for query in ["10 /2", "10 / 2", "10/2"] { + assert!(matches!( + read_query(query).unwrap().kind(), + QueryKind::Instant + )); + } + for query in ["/usr/bin", "/2"] { + assert!(matches!( + read_query(query).unwrap().kind(), + QueryKind::Passage { + kind: PassageKind::Pasted + } + )); + } +} + +#[test] +fn freshness_removes_qualifiers_without_removing_new_from_names() { + assert!(matches!( + read_query("new york transit news").unwrap().kind(), + QueryKind::Place { entity, fresh: true, .. } if entity == &["new", "york", "transit"] + )); + assert!(matches!( + read_query("new openai model").unwrap().kind(), + QueryKind::Place { entity, fresh: true, .. } if entity == &["openai", "model"] + )); +} diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index 9600660a9..b98191e91 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -1419,3 +1419,91 @@ fn unusable_bodies_still_spend_the_default_six_mib() { assert_eq!(result.stats.phases[&Phase::Llms].started, 0); assert!(result.stats.budgets.contains(&Budget::TotalBytes)); } + +#[test] +fn elapsed_before_initial_results_ends_in_a_typed_timeout() { + let (mut session, _) = Session::start(cfg(), "acme").unwrap(); + let effects = session.handle(Input::Elapsed { time: MAX_ELAPSED }); + assert!(matches!( + effects.as_slice(), + [Effect::Emit { event: MapEvent::End { outcome: EndOutcome::Failed { failure: Failure::Timeout }, stats }, .. }] + if stats.phases[&Phase::Results].refused[&Failure::Timeout] == 1 + )); +} + +#[test] +fn missing_comparison_side_reports_result_refusals_and_absent_seeds() { + for (reply, expected) in [ + (Err(Failure::Unavailable), Failure::Unavailable), + (Ok(doc(ENGINE, "<p>No results found</p>")), Failure::Missing), + ] { + let (mut session, start) = Session::start(cfg(), "acme vs other").unwrap(); + let mut effects: VecDeque<_> = session + .handle(Input::Results { + id: start[1].id(), + result: Ok(doc(ENGINE, RESULT)), + }) + .into(); + let id = loop { + match effects.pop_front().unwrap() { + Effect::ReadResultsAnonymously { id, .. } => break id, + Effect::LookupSite { id, .. } => { + effects.extend(session.handle(Input::Cache { id, memo: None })) + } + Effect::Fetch { id, url, .. } => effects.extend(session.handle(response( + id, + &url, + "text/plain", + "User-agent: *\n", + ))), + _ => {} + } + }; + assert!(session.handle(Input::Results { id, result: reply }).iter().any(|effect| matches!( + effect, Effect::Emit { event: MapEvent::PlaceFailed { slot: 1, failure }, .. } if *failure == expected + ))); + } +} + +#[test] +fn shell_and_wall_memos_cannot_short_circuit_entry_reads() { + let base = run(cfg(), "acme", RESULT, |_| None); + let memo = base.memo.unwrap(); + for field in ["shell", "wall"] { + let mut data: serde_json::Value = serde_json::from_slice(&memo).unwrap(); + data["payload"]["place"]["notes"][field] = serde_json::Value::Bool(true); + let raw = serde_json::to_vec(&data).unwrap(); + let next = run(cfg(), "acme", RESULT, |e| match e { + Effect::LookupSite { id, .. } => Some(Input::Cache { + id: *id, + memo: Some(raw.clone()), + }), + _ => None, + }); + assert_eq!(next.stats.rejected_memos, 1); + assert!(next.trace.iter().any(|item| item == "fetch acme.com/")); + } +} + +#[test] +fn sitemap_fetch_requires_a_valid_media_type_essence() { + for media in [ + "not-a-media-type+xml", + "/rdf+xml", + "application/xml/rdf+xml", + ] { + let r = run(cfg(), "acme", RESULT, |e| match e { + Effect::Fetch { id, url, .. } if url.path() == "/sitemap.xml" => { + Some(response(*id, url, media, "<urlset/>")) + } + _ => None, + }); + assert_eq!( + r.stats.phases[&Phase::Sitemap] + .refused + .get(&Failure::ContentType), + Some(&1), + "{media}" + ); + } +} diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index 865292f1c..4b88fd882 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -671,3 +671,114 @@ fn surplus_role_entries_keep_the_first_in_site_order() { .collect(); assert_eq!(labels(&place.sections), expected); } + +#[test] +fn footer_navigation_does_not_hide_primary_link_clusters() { + let home = doc("/", "<main><ul><li><a href='/docs'>Docs</a></li><li><a href='/pricing'>Pricing</a></li><li><a href='/download'>Download</a></li><li><a href='/about'>About</a></li></ul></main><footer><nav><a href='/privacy'>Privacy</a></nav></footer>"); + let place = read_site(&home, &SiteInputs::default()).unwrap(); + assert!(place.sections.iter().any(|e| e.label == "Docs" + && e.sources.contains(&Source::LinkCluster) + && e.tier == Tier::Primary)); + assert!(place + .sections + .iter() + .any(|e| e.label == "Privacy" && e.sources.contains(&Source::Footer))); +} + +#[test] +fn nested_menu_links_keep_distinct_anchors_on_the_parent_page() { + let home = doc("/", "<nav><ul><li><a href='/pricing'>Pricing</a><ul><li><a href='/pricing#students'>Students</a></li><li><a href='/pricing'>Same page</a></li></ul></li></ul></nav>"); + let place = read_site(&home, &SiteInputs::default()).unwrap(); + assert_eq!(labels(&place.sections[0].children), ["Students"]); + assert_eq!( + place.sections[0].children[0].locator.fragment().as_deref(), + Some("#students") + ); +} + +#[test] +fn delegated_sidebar_links_keep_their_real_destination_and_require_a_label() { + let home = doc( + "/", + "<nav><a href='https://guides.example/docs'>Documentation</a></nav>", + ); + let docs = doc( + "https://guides.example/docs", + "<aside><a href='/setup#linux'>Linux setup</a><a href='/empty'></a></aside>", + ); + let place = read_site( + &home, + &SiteInputs { + pages: [(PageKey::from_url(docs.page()).unwrap(), &docs)].into(), + ..SiteInputs::default() + }, + ) + .unwrap(); + let section = &place.sections[0]; + let child = section + .children + .iter() + .find(|e| e.label == "Linux setup") + .unwrap(); + assert!(child.off_site); + assert_eq!(child.key.as_url().path(), "/setup"); + assert_eq!(child.locator.fragment().as_deref(), Some("#linux")); + assert!(section.children.iter().all(|e| !e.label.is_empty())); +} + +#[test] +fn section_landing_updates_the_key_and_locator_together() { + let home = doc("/", "<nav><a href='/docs#install'>Documentation</a></nav>"); + for (landing, expected) in [ + ("/docs", Some("#install")), + ("/guide#setup", Some("#setup")), + ("/guide", None), + ] { + let docs = doc(landing, "<p>Guide</p>"); + let place = read_site( + &home, + &SiteInputs { + pages: [(key("/docs"), &docs)].into(), + ..SiteInputs::default() + }, + ) + .unwrap(); + let section = &place.sections[0]; + assert_eq!(section.key.as_url().path(), docs.page().path()); + assert_eq!(section.locator.fragment().as_deref(), expected); + } +} + +#[test] +fn site_profiles_ignore_known_service_routes() { + let doc = doc("/", "<nav><a href='https://github.com/pricing'>Pricing</a><a href='https://github.com/login'>Login</a><a href='https://x.com/search'>Search</a><a href='https://github.com/acme'>Acme</a></nav>"); + let place = read_site(&doc, &SiteInputs::default()).unwrap(); + assert_eq!( + place + .social + .iter() + .map(|profile| profile.url.path()) + .collect::<Vec<_>>(), + ["/acme"] + ); +} + +#[test] +fn sitemap_rejects_character_data_outside_the_root() { + let source = url("/sitemap.xml"); + for text in [ + "<![CDATA[extra]]><urlset/>", + "<urlset/><![CDATA[extra]]>", + "<urlset/>&#32;", + ] { + assert!(matches!( + Sitemap::parse(text.as_bytes(), &source), + Err(XmlError::Malformed) + )); + } + assert!(Sitemap::parse( + b"<urlset><url><loc><![CDATA[https://workshop.example/docs]]></loc></url></urlset>", + &source + ) + .is_ok()); +} From 70143c5555dbd50178beeebdf8b0386e3b71f323 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:15:43 +0100 Subject: [PATCH 26/40] fix(xtask): tighten map bench replay, resume and scoring edge cases --- xtask/src/map_bench/corpus.rs | 39 +++++++- xtask/src/map_bench/probe.rs | 23 ++++- xtask/src/map_bench/run.rs | 80 ++++++++------- xtask/src/map_bench/run/tests.rs | 76 ++++++++++++++ xtask/src/map_bench/run/tests/session.rs | 121 ++++++++++++++++++++--- xtask/src/map_bench/session.rs | 67 +++++-------- xtask/src/map_bench/store.rs | 20 ++-- 7 files changed, 320 insertions(+), 106 deletions(-) diff --git a/xtask/src/map_bench/corpus.rs b/xtask/src/map_bench/corpus.rs index 228d6705a..7278e4776 100644 --- a/xtask/src/map_bench/corpus.rs +++ b/xtask/src/map_bench/corpus.rs @@ -26,6 +26,19 @@ pub(super) enum Kind { List, } +impl From<&zephium_map::QueryKind> for Kind { + fn from(kind: &zephium_map::QueryKind) -> Self { + use zephium_map::QueryKind; + match kind { + QueryKind::Instant => Self::Instant, + QueryKind::List => Self::List, + QueryKind::Place { .. } => Self::Place, + QueryKind::Compare { .. } => Self::Compare, + QueryKind::Passage { .. } => Self::Passage, + } + } +} + impl Kind { pub(super) fn label(self) -> &'static str { match self { @@ -368,6 +381,15 @@ pub(super) fn fixture(text: &str) -> CorpusQuery { parse(text).expect("test corpus").remove(0) } +#[cfg(test)] +pub(super) fn load_external_fixture(paths: &[PathBuf]) -> Result<Option<Corpus>> { + if paths.iter().any(|path| path.exists()) { + Corpus::load(paths).map(Some) + } else { + Ok(None) + } +} + #[cfg(test)] mod tests { use super::*; @@ -380,8 +402,7 @@ mod tests { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../../zephium-audit/impl/search-map"); let paths = [root.join("corpus-v0.toml"), root.join("corpus-v1.toml")]; - if paths.iter().all(|path| path.is_file()) { - let corpus = Corpus::load(&paths).expect("both real corpora"); + if let Some(corpus) = load_external_fixture(&paths).expect("both real corpora") { assert_eq!(corpus.hashes.len(), 2); for kind in [ Kind::Place, @@ -530,3 +551,17 @@ mod tests { assert!(Corpus::load(&[two]).is_err()); } } + +#[cfg(test)] +#[test] +fn a_partially_installed_external_corpus_is_an_error() { + let root = tempfile::tempdir().unwrap(); + let paths = [root.path().join("v0.toml"), root.path().join("v1.toml")]; + assert!(load_external_fixture(&paths).unwrap().is_none()); + std::fs::write( + &paths[0], + "[[query]]\nid='v0'\ntext='Acme'\nkind='place'\nsite='example.com'\n", + ) + .unwrap(); + assert!(load_external_fixture(&paths).is_err()); +} diff --git a/xtask/src/map_bench/probe.rs b/xtask/src/map_bench/probe.rs index f5a174e96..4b265c9f8 100644 --- a/xtask/src/map_bench/probe.rs +++ b/xtask/src/map_bench/probe.rs @@ -3,8 +3,8 @@ use zephium_public_fetch::{ReadRefusal, ReaderLimits, StatusRefusal}; use super::corpus::{CorpusQuery, Kind}; use super::engine::{ - BenchIo, Engine, Expectation, FetchRefusal, FetchRequest, FetchResult, Outcome, ProbeFetch, - ProbeSite, RobotsStop, + BenchIo, Engine, EngineFailure, Expectation, FetchRefusal, FetchRequest, FetchResult, Outcome, + ProbeFetch, ProbeSite, RobotsStop, }; pub(super) struct ProbeEngine; @@ -12,6 +12,11 @@ pub(super) struct ProbeEngine; impl Engine for ProbeEngine { fn run(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Outcome { let mut outcome = Outcome::empty(query.label.kind); + let Ok(measured) = zephium_map::read_query(&query.text) else { + outcome.failure = Some(EngineFailure::InvalidInput); + return outcome; + }; + outcome.kind = Kind::from(measured.kind()); let sites = match query.label.kind { Kind::Place => query.site.as_slice(), Kind::Compare => &query.sites, @@ -302,4 +307,18 @@ mod tests { assert!(io.calls.is_empty()); } } + + #[test] + fn probe_measures_kind_independently_of_the_corpus_label() { + let query = crate::map_bench::corpus::fixture( + "[[query]]\nid='q'\ntext='Example docs'\nkind='instant'", + ); + let mut io = FakeIo { + calls: vec![], + results: VecDeque::new(), + }; + let outcome = ProbeEngine.run(&query, &mut io); + assert_eq!(outcome.kind, Kind::Place); + assert!(outcome.probe.is_empty()); + } } diff --git a/xtask/src/map_bench/run.rs b/xtask/src/map_bench/run.rs index 039401ce4..4fead8928 100644 --- a/xtask/src/map_bench/run.rs +++ b/xtask/src/map_bench/run.rs @@ -19,8 +19,7 @@ use super::engine::{ }; use super::score::{self, Reason, Score, Verdict}; use super::store::{ - self, optional_json, query_dir, write_json, Journal, MatchPolicy, RecordedMatch, ResultsSlot, - Transfer, + self, query_dir, write_json, Journal, MatchPolicy, RecordedMatch, ResultsSlot, Transfer, }; use super::{platform, BenchError, Options, Result}; @@ -347,6 +346,14 @@ impl Source for PublicSource { } impl Measure { + fn include_prior_wire(&mut self, prior: u64) -> Result<()> { + self.wire_bytes = self + .wire_bytes + .checked_add(prior) + .ok_or(BenchError::new("wire_bytes_overflow"))?; + Ok(()) + } + fn delta(self, before: &Self) -> Self { Self { requests: self.requests.saturating_sub(before.requests), @@ -617,7 +624,9 @@ fn execute(engine: &mut dyn Engine, query: &CorpusQuery, io: &mut QueryIo<'_>) - }; let failure = io.failure.or(match outcome.failure { Some(EngineFailure::InvalidInput) => Some(Reason::EngineInvalidInput), - Some(EngineFailure::SessionFailed) if outcome.no_official_site => None, + Some(EngineFailure::SessionFailed) if outcome.no_official_site => { + (!outcome.valid()).then_some(Reason::InvalidOutcome) + } Some(EngineFailure::SessionFailed) => Some(Reason::EngineSessionFailed), Some(_) => Some(Reason::EngineFault), None if !outcome.valid() => Some(Reason::InvalidOutcome), @@ -692,7 +701,7 @@ fn record_query( measure.wall = wall; (measure.cpu_ns, measure.peak_rss_delta_bytes) = cost; measure.requests += prior_reads; - measure.wire_bytes += prior_wire; + measure.include_prior_wire(prior_wire)?; measure.decoded_bytes += prior_decoded; for (class, count) in prior_refusals { *measure.refusals.entry(class).or_default() += count; @@ -715,7 +724,7 @@ pub(super) fn pending<'a>( break; } let path = query_dir(root, &query.label.id, false)?; - if !store::exists(&path.join(OUTCOME))? { + if !store::exists(&path.join(OUTCOME))? || !store::exists(&path.join(MEASURE))? { pending.push(query); } } @@ -789,20 +798,6 @@ fn record_queries( if let Err(error) = record_query(root, query, engine, source, clock) { failed = true; eprintln!("map bench: {}", error.for_query(&query.label.id)); - let checkpoint = (|| { - let path = query_dir(root, &query.label.id, true)?; - save_outcome( - &path.join(OUTCOME), - QueryResult::unavailable( - Verdict::Fail, - Reason::ArtifactError, - Activity::default(), - ), - ) - })(); - if let Err(error) = checkpoint { - eprintln!("map bench: {}", error.for_query(&query.label.id)); - } } } if failed { @@ -899,7 +894,7 @@ pub(super) fn latest_replay(root: &Path) -> Result<Option<(PathBuf, ReplayManife if !store::directory(&parent, false)? { return Ok(None); } - let mut latest = None::<(PathBuf, ReplayManifest)>; + let mut latest = None::<(u128, Result<PathBuf>)>; for entry in store::children(&parent)? { let entry = entry.map_err(|error| BenchError::io("list_replay", &error))?; let name = entry.file_name(); @@ -910,30 +905,41 @@ pub(super) fn latest_replay(root: &Path) -> Result<Option<(PathBuf, ReplayManife if name != format!("{timestamp:039}") || latest .as_ref() - .is_some_and(|(_, replay)| timestamp <= replay.started_unix_ns) + .is_some_and(|(newest, _)| timestamp <= *newest) { continue; } let path = entry.path(); - if !store::directory(&path, false)? { - continue; - } - if let Some(manifest) = optional_json::<ReplayManifest>(&path.join(REPLAY))? { - if manifest.started_unix_ns != timestamp - || manifest.corpus_sha256.is_empty() - || manifest.corpus_sha256.len() > MAX_CORPUS_FILES - || !manifest - .corpus_sha256 - .iter() - .all(|hash| store::valid_digest(hash)) - { - return Err(BenchError::new("invalid_replay_manifest")); + let published = store::directory(&path, false).and_then(|directory| { + if directory { + store::exists(&path.join(REPLAY)) + } else { + Ok(false) } - validate_labels(&manifest.queries)?; - latest = Some((path, manifest)); + }); + match published { + Ok(false) => {} + Ok(true) => latest = Some((timestamp, Ok(path))), + Err(error) => latest = Some((timestamp, Err(error))), } } - Ok(latest) + let Some((timestamp, path)) = latest else { + return Ok(None); + }; + let path = path?; + let manifest: ReplayManifest = store::read_json(&path.join(REPLAY))?; + if manifest.started_unix_ns != timestamp + || manifest.corpus_sha256.is_empty() + || manifest.corpus_sha256.len() > MAX_CORPUS_FILES + || !manifest + .corpus_sha256 + .iter() + .all(|hash| store::valid_digest(hash)) + { + return Err(BenchError::new("invalid_replay_manifest")); + } + validate_labels(&manifest.queries)?; + Ok(Some((path, manifest))) } #[cfg(test)] diff --git a/xtask/src/map_bench/run/tests.rs b/xtask/src/map_bench/run/tests.rs index 946ce5c32..74888454c 100644 --- a/xtask/src/map_bench/run/tests.rs +++ b/xtask/src/map_bench/run/tests.rs @@ -702,3 +702,79 @@ Destinations scored as matched_locale — 0. } mod session; + +#[test] +fn resume_retries_a_checkpoint_without_a_measurement() { + let root = tempfile::tempdir().unwrap(); + let query = place("unfinished"); + let path = query_dir(root.path(), &query.label.id, true).unwrap(); + save_outcome( + &path.join(OUTCOME), + QueryResult::unavailable(Verdict::Fail, Reason::ArtifactError, Activity::default()), + ) + .unwrap(); + assert_eq!(pending(root.path(), [&query], 1).unwrap().len(), 1); + write_json(&path.join(MEASURE), &Measure::default()).unwrap(); + assert!(pending(root.path(), [&query], 1).unwrap().is_empty()); +} + +#[test] +fn invalid_outcomes_cannot_claim_the_no_site_exception() { + struct Invalid; + impl Engine for Invalid { + fn run(&mut self, _: &CorpusQuery, _: &mut dyn BenchIo) -> Outcome { + let mut outcome = Outcome::empty(Kind::Place); + outcome.failure = Some(EngineFailure::SessionFailed); + outcome.no_official_site = true; + outcome.entries.push(Entry { + focus: false, + url: Url::parse("https://example.com/").unwrap(), + depth: Depth::One, + source: "x".repeat(crate::map_bench::engine::MAX_SOURCE_BYTES + 1), + tags: BTreeSet::new(), + }); + outcome + } + } + let root = tempfile::tempdir().unwrap(); + let mut io = QueryIo::new(root.path(), Journal::default(), SESSION_CLOCK, None); + let result = execute(&mut Invalid, &place("invalid"), &mut io); + assert!(result.outcome.is_none()); + assert_eq!(result.score.reason, Reason::InvalidOutcome); +} + +#[test] +fn latest_replay_reads_only_the_newest_published_manifest() { + let root = tempfile::tempdir().unwrap(); + let directory = |stamp: u128| root.path().join("replay").join(format!("{stamp:039}")); + for stamp in [1, 2, 3] { + fs::create_dir_all(directory(stamp)).unwrap(); + } + fs::write(directory(1).join(REPLAY), b"invalid").unwrap(); + write_json( + &directory(2).join(REPLAY), + &ReplayManifest { + started_unix_ns: 2, + corpus_sha256: vec![store::digest(b"corpus")], + queries: vec![place("example").label], + }, + ) + .unwrap(); + assert_eq!(latest_replay(root.path()).unwrap().unwrap().0, directory(2)); + fs::write(directory(3).join(REPLAY), b"invalid").unwrap(); + assert!(latest_replay(root.path()).is_err()); +} + +#[test] +fn recording_refuses_a_wire_total_above_u64() { + let mut measure = Measure { + wire_bytes: 1, + ..Measure::default() + }; + measure.include_prior_wire(u64::MAX - 1).unwrap(); + assert_eq!(measure.wire_bytes, u64::MAX); + assert_eq!( + measure.include_prior_wire(1).unwrap_err().class, + "wire_bytes_overflow" + ); +} diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index d24bbad7e..2538331a6 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -6,6 +6,7 @@ struct ScriptedSource { calls: Vec<FetchRequest>, elapsed: Duration, reversed: bool, + delay_html: Duration, } impl ScriptedSource { @@ -16,6 +17,7 @@ impl ScriptedSource { calls: Vec::new(), elapsed: Duration::ZERO, reversed: false, + delay_html: Duration::ZERO, } } } @@ -28,12 +30,16 @@ impl Source for ScriptedSource { fn submit(&mut self, token: usize, request: FetchRequest, start: Duration) { let result = (self.respond)(&request); + let delay = if request.expect == Expectation::Html { + self.delay_html + } else { + Duration::ZERO + }; self.calls.push(request); - let delay = if self.reversed { [3, 1, 2][token] } else { 1 }; let end = if self.reversed { - Duration::from_secs(delay) + start } else { - self.elapsed.max(start) + Duration::from_millis(delay) + self.elapsed.max(start) + Duration::from_millis(1) + delay }; let total = end - start; self.pending.push(Completed { @@ -49,12 +55,24 @@ impl Source for ScriptedSource { } fn next(&mut self) -> Option<Completed> { - let (index, _) = self - .pending - .iter() - .enumerate() - .min_by_key(|(_, item)| (item.transfer.end, item.token))?; - let completed = self.pending.swap_remove(index); + let order = |token| [3, 1, 2][token]; + let (index, _) = self.pending.iter().enumerate().min_by_key(|(_, item)| { + if self.reversed { + (Duration::ZERO, order(item.token)) + } else { + (item.transfer.end, item.token) + } + })?; + let mut completed = self.pending.swap_remove(index); + if self.reversed { + let ready = self + .pending + .iter() + .map(|item| item.transfer.start) + .fold(completed.transfer.start.max(self.elapsed), Duration::max); + completed.transfer.end = ready + Duration::from_millis(1); + completed.transfer.total = completed.transfer.end - completed.transfer.start; + } self.elapsed = completed.transfer.end; Some(completed) } @@ -430,10 +448,9 @@ fn actual_corpus_synthetic_entity_findings() { evidence.join("corpus-v0.toml"), evidence.join("corpus-v1.toml"), ]; - if !paths.iter().all(|path| path.is_file()) { + let Some(corpus) = crate::map_bench::corpus::load_external_fixture(&paths).unwrap() else { return; - } - let corpus = Corpus::load(&paths).unwrap(); + }; let mut source = ScriptedSource::new(|_| refuse(StatusRefusal::Client)); let mut missing = Vec::new(); for query in corpus @@ -769,3 +786,83 @@ fn replay_prefers_an_unclaimed_exact_row_then_uses_the_first_compatible_row() { assert_eq!(io.activity.matched_relaxed, 1); assert_eq!(io.fetch(req), Err(FetchRefusal::NotRecorded)); } + +#[test] +fn replay_response_refusal_requires_time_to_observe_it() { + let root = tempfile::tempdir().unwrap(); + let path = query_dir(root.path(), "refusal", true).unwrap(); + let req = request("/docs", Expectation::Html); + save_row(root.path(), &path, &req, refuse(StatusRefusal::Denied)); + assert_eq!( + replay_row(&path, &req, req.max_bytes, 9), + Err(FetchRefusal::NotRecorded) + ); + assert_eq!( + replay_row(&path, &req, req.max_bytes, 10), + refuse(StatusRefusal::Denied) + ); +} + +#[test] +fn completion_order_fixture_accepts_late_submissions() { + let mut source = ScriptedSource::new(|_| refuse(StatusRefusal::Denied)); + source.reversed = true; + for (token, start) in [8, 10, 12].into_iter().enumerate() { + source.submit( + token, + request("/docs", Expectation::Html), + Duration::from_secs(start), + ); + } + for token in [1, 2, 0] { + let result = source.next().unwrap(); + assert_eq!(result.token, token); + assert!(result.transfer.end >= result.transfer.start); + } +} + +#[test] +fn passage_page_counts_only_after_session_acceptance() { + let root = tempfile::tempdir().unwrap(); + for (id, delay, expected) in [ + ("in-time", Duration::ZERO, 1), + ("late", zephium_map::session::MAX_ELAPSED, 0), + ] { + let query = session_query(id, "how to reset timer", "kind='passage'\nanswer='side button'\nfrom=['example.com']\npages=['https://example.com/empty']"); + let path = query_dir(root.path(), &query.label.id, true).unwrap(); + let mut source = ScriptedSource::new(|request| { + if request.url.path() == "/robots.txt" { + scripted_body(request, "text/plain", "User-agent: *\n") + } else { + scripted_body(request, "text/html", "<p>Geese migrate in autumn.</p>") + } + }); + source.delay_html = delay; + let mut io = QueryIo::new( + &path, + Journal::default(), + SESSION_CLOCK, + Some(Live { + root: root.path(), + source: &mut source, + started: Instant::now(), + prior_elapsed: Duration::ZERO, + }), + ); + let output = execute( + &mut crate::map_bench::session::SessionEngine, + &query, + &mut io, + ); + let outcome = output.outcome.unwrap(); + assert!(outcome.passages.is_empty()); + assert_eq!( + outcome + .stats + .get("passage_pages_read") + .copied() + .unwrap_or(0), + expected + ); + } +} diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index b192991c5..9fdaea443 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -91,8 +91,9 @@ impl Driver { let input = self .immediate .pop_front() + .map(|input| (input, false)) .or_else(|| self.completion(query, io)); - let Some(input) = input else { + let Some((input, listed)) = input else { self.outcome .failure .get_or_insert(EngineFailure::MissingTerminal); @@ -100,7 +101,15 @@ impl Driver { }; effects = session.handle(Input::Elapsed { time: io.elapsed() }); if !effects.iter().any(is_terminal) { + let before = listed.then(|| session.accepted_passage_pages()); effects.extend(session.handle(input)); + if before.is_some_and(|count| session.accepted_passage_pages() > count) { + *self + .outcome + .stats + .entry("passage_pages_read".into()) + .or_default() += 1; + } } } let expected = match query.label.kind { @@ -119,24 +128,6 @@ impl Driver { self.outcome .stats .insert("official_sites".into(), self.lookups as u64); - if query.label.kind == Kind::Passage { - let completed = self - .outcome - .stats - .get("phase.Passage.completed") - .copied() - .unwrap_or(0); - let refuses = self - .outcome - .stats - .range("phase.Passage.refused.".to_owned()..) - .take_while(|(key, _)| key.starts_with("phase.Passage.refused.")) - .map(|(_, count)| *count) - .sum::<u64>(); - if completed > 0 && completed == query.pages.len() as u64 && completed <= refuses { - self.outcome.stats.insert("passage_pages_read".into(), 0); - } - } for (index, place) in self.places.into_iter().enumerate() { if let Some(place) = place { flatten_place(&mut self.outcome, index, place); @@ -145,7 +136,7 @@ impl Driver { self.outcome } - fn completion(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Option<Input> { + fn completion(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Option<(Input, bool)> { if self.in_flight.is_empty() { return None; } @@ -157,24 +148,20 @@ impl Driver { self.outcome.failure = Some(EngineFailure::UnexpectedCompletion); return None; }; - if expect == Expectation::Html + let listed = expect == Expectation::Html && listed_page(query, &url) && result.as_ref().is_ok_and(|body| { !body.truncated && SiteKey::from_url(&url) == SiteKey::from_url(&body.final_url) - }) - { - *self - .outcome - .stats - .entry("passage_pages_read".into()) - .or_default() += 1; - } - Some(Input::Fetch { - id, - result: result - .map(|body| session_body(body, expect)) - .map_err(failure), - }) + }); + Some(( + Input::Fetch { + id, + result: result + .map(|body| session_body(body, expect)) + .map_err(failure), + }, + listed, + )) } fn effect(&mut self, effect: Effect, query: &CorpusQuery, io: &mut dyn BenchIo) { @@ -281,15 +268,7 @@ impl Driver { fn emit(&mut self, event: MapEvent, io: &dyn BenchIo) { match event { - MapEvent::Kind { kind } => { - self.outcome.kind = match kind { - QueryKind::Instant => Kind::Instant, - QueryKind::List => Kind::List, - QueryKind::Place { .. } => Kind::Place, - QueryKind::Compare { .. } => Kind::Compare, - QueryKind::Passage { kind: _ } => Kind::Passage, - } - } + MapEvent::Kind { kind } => self.outcome.kind = Kind::from(&kind), MapEvent::FirstLayer { layer } if !self.outcome.synthetic_results => { self.outcome .milestones diff --git a/xtask/src/map_bench/store.rs b/xtask/src/map_bench/store.rs index d93bebc66..787dd929c 100644 --- a/xtask/src/map_bench/store.rs +++ b/xtask/src/map_bench/store.rs @@ -438,13 +438,13 @@ impl RequestRow { } fn answers(&self, request: &FetchRequest) -> bool { + let completion = self.elapsed_at_start.map_or(self.timings.total, |start| { + self.elapsed_at_return + .saturating_sub(start) + .max(self.timings.total) + }); match (&self.result_class, &self.body) { (ResultClass::Body(_), Some(body)) => { - let completion = self.elapsed_at_start.map_or(self.timings.total, |start| { - self.elapsed_at_return - .saturating_sub(start) - .max(self.timings.total) - }); request.timeout >= completion && if body.truncated { request.max_bytes <= self.cap @@ -453,7 +453,9 @@ impl RequestRow { } } (ResultClass::Refused(FetchRefusal::Reader(class)), None) => match class { - ReadRefusal::TooLarge(_) => request.max_bytes <= self.cap, + ReadRefusal::TooLarge(_) => { + request.max_bytes <= self.cap && request.timeout >= completion + } ReadRefusal::Timeout(_) => request.timeout <= self.timeout, ReadRefusal::NotPublicHttps | ReadRefusal::RedirectRefused @@ -461,10 +463,10 @@ impl RequestRow { | ReadRefusal::DnsRefused | ReadRefusal::ProxyUnsupported | ReadRefusal::RouteChanged - | ReadRefusal::Status(_) - | ReadRefusal::WrongContentType - | ReadRefusal::Encoding | ReadRefusal::Transport => true, + ReadRefusal::Status(_) | ReadRefusal::WrongContentType | ReadRefusal::Encoding => { + request.timeout >= completion + } }, _ => false, } From 4c429d1d4cc731580b468ad1baf405c4ae671776 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:54:10 +0100 Subject: [PATCH 27/40] fix(fetch): refuse to read around a per-interface proxy on macOS A dictionary that enables nothing at the top level but carries a proxy, a PAC address or auto-discovery under a scoped interface entry went direct. Any such entry, or one that cannot be read, now refuses. --- .../src/platform/macos.rs | 70 +++++++++-- .../zephium-public-fetch/src/platform/mod.rs | 112 +++++++++++++++++- 2 files changed, 173 insertions(+), 9 deletions(-) diff --git a/crates/zephium-public-fetch/src/platform/macos.rs b/crates/zephium-public-fetch/src/platform/macos.rs index 73a074ec3..d8aaca838 100644 --- a/crates/zephium-public-fetch/src/platform/macos.rs +++ b/crates/zephium-public-fetch/src/platform/macos.rs @@ -1,9 +1,12 @@ use system_configuration::core_foundation::{ - base::CFType, dictionary::CFDictionary, number::CFNumber, string::CFString, + base::{CFType, TCFType}, + dictionary::CFDictionary, + number::CFNumber, + string::CFString, }; use system_configuration::dynamic_store::SCDynamicStoreBuilder; -use super::{mac_route, MacProxies}; +use super::{mac_route, Flag, MacProxies, Scoped, MAX_SCOPED_ENTRIES, SCOPED_ENABLE_KEYS}; use crate::route::Route; fn number(proxies: &CFDictionary<CFString, CFType>, key: &'static str) -> Option<i64> { @@ -20,20 +23,71 @@ fn text(proxies: &CFDictionary<CFString, CFType>, key: &'static str) -> Option<S .map(|value| value.to_string()) } -pub(crate) fn system_route() -> Route { - let Some(store) = SCDynamicStoreBuilder::new("zephium-public-fetch").build() else { - return Route::Unsupported; +fn flag(proxies: &CFDictionary<CFString, CFType>, key: &'static str) -> Flag { + match proxies.find(CFString::from_static_string(key)) { + None => Flag::Absent, + Some(value) => value + .downcast::<CFNumber>() + .and_then(|value| value.to_i64()) + .map_or(Flag::Other, Flag::Number), + } +} + +fn scoped(proxies: &CFDictionary<CFString, CFType>) -> Scoped { + let Some(value) = proxies.find(CFString::from_static_string("__SCOPED__")) else { + return Scoped::Absent; }; - let Some(proxies) = store.get_proxies() else { - return Route::Unsupported; + let Some(scoped) = value.downcast::<CFDictionary>() else { + return Scoped::Unreadable; }; + if scoped.len() > MAX_SCOPED_ENTRIES { + return Scoped::Unreadable; + } + let (_, values) = scoped.get_keys_and_values(); + Scoped::Entries( + values + .into_iter() + .map(|value| { + if value.is_null() { + return None; + } + // SAFETY: `value` is a non-null value of `scoped`, which is alive and retains it; + // the get rule takes our own reference. + let value = unsafe { CFType::wrap_under_get_rule(value) }; + let entry = value.downcast::<CFDictionary>()?; + // SAFETY: `entry` is a live CFDictionary (checked by `downcast`) from a property + // list, so every key and value is a CF object and may be read as `CFType`. + let entry: CFDictionary<CFString, CFType> = + unsafe { TCFType::wrap_under_get_rule(entry.as_concrete_TypeRef()) }; + Some(SCOPED_ENABLE_KEYS.map(|key| flag(&entry, key))) + }) + .collect(), + ) +} + +fn read() -> Option<MacProxies> { + let store = SCDynamicStoreBuilder::new("zephium-public-fetch").build()?; + let proxies = store.get_proxies()?; let enabled = |key| number(&proxies, key) == Some(1); - mac_route(&MacProxies { + Some(MacProxies { auto_config: enabled("ProxyAutoConfigEnable"), auto_discovery: enabled("ProxyAutoDiscoveryEnable"), https: enabled("HTTPSEnable"), https_host: text(&proxies, "HTTPSProxy"), https_port: number(&proxies, "HTTPSPort"), socks: enabled("SOCKSEnable"), + scoped: scoped(&proxies), }) } + +pub(crate) fn system_route() -> Route { + read().map_or(Route::Unsupported, |proxies| mac_route(&proxies)) +} + +#[cfg(test)] +mod tests { + #[test] + fn reading_this_hosts_scoped_proxy_dictionary_returns() { + let _ = super::read(); + } +} diff --git a/crates/zephium-public-fetch/src/platform/mod.rs b/crates/zephium-public-fetch/src/platform/mod.rs index d2e4f8928..dd9d31dbd 100644 --- a/crates/zephium-public-fetch/src/platform/mod.rs +++ b/crates/zephium-public-fetch/src/platform/mod.rs @@ -28,11 +28,64 @@ pub(crate) struct MacProxies { pub(crate) https_host: Option<String>, pub(crate) https_port: Option<i64>, pub(crate) socks: bool, + pub(crate) scoped: Scoped, +} + +#[cfg(any(target_os = "macos", test))] +pub(crate) const MAX_SCOPED_ENTRIES: usize = 64; + +/// Per-interface keys under `__SCOPED__` that route traffic through a proxy. +#[cfg(any(target_os = "macos", test))] +pub(crate) const SCOPED_ENABLE_KEYS: [&str; 5] = [ + "HTTPEnable", + "HTTPSEnable", + "SOCKSEnable", + "ProxyAutoConfigEnable", + "ProxyAutoDiscoveryEnable", +]; + +#[cfg(any(target_os = "macos", test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Flag { + Absent, + Number(i64), + Other, +} + +/// The `__SCOPED__` dictionary: one entry per interface, `None` for an entry +/// that is not a dictionary. +#[cfg(any(target_os = "macos", test))] +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum Scoped { + #[default] + Absent, + Unreadable, + Entries(Vec<Option<[Flag; SCOPED_ENABLE_KEYS.len()]>>), +} + +#[cfg(any(target_os = "macos", test))] +impl Scoped { + fn enables_anything(&self) -> bool { + match self { + Scoped::Absent => false, + Scoped::Unreadable => true, + Scoped::Entries(entries) => { + entries.len() > MAX_SCOPED_ENTRIES + || entries.iter().any(|entry| { + entry.is_none_or(|flags| { + flags + .iter() + .any(|flag| !matches!(flag, Flag::Absent | Flag::Number(0))) + }) + }) + } + } + } } #[cfg(any(target_os = "macos", test))] pub(crate) fn mac_route(proxies: &MacProxies) -> Route { - if proxies.auto_config || proxies.auto_discovery { + if proxies.auto_config || proxies.auto_discovery || proxies.scoped.enables_anything() { return Route::Unsupported; } if proxies.https { @@ -191,6 +244,63 @@ mod tests { assert_eq!(mac_route(&both), http("proxy.corp.example", 8080)); } + #[test] + fn a_scoped_interface_proxy_is_unsupported_and_a_harmless_one_is_not() { + let scoped = |scoped| MacProxies { + scoped, + ..MacProxies::default() + }; + let harmless = [ + Flag::Absent, + Flag::Number(0), + Flag::Absent, + Flag::Number(0), + Flag::Absent, + ]; + for entries in [ + vec![], + vec![Some([Flag::Absent; 5])], + vec![Some(harmless); 2], + ] { + assert_eq!(mac_route(&scoped(Scoped::Entries(entries))), Route::Direct); + } + assert_eq!( + mac_route(&scoped(Scoped::Entries(vec![ + Some(harmless); + MAX_SCOPED_ENTRIES + ]))), + Route::Direct + ); + for key in 0..SCOPED_ENABLE_KEYS.len() { + for value in [Flag::Number(1), Flag::Number(2), Flag::Other] { + let mut flags = harmless; + flags[key] = value; + let entries = vec![Some(harmless), Some(flags)]; + assert_eq!( + mac_route(&scoped(Scoped::Entries(entries))), + Route::Unsupported, + "{} {value:?}", + SCOPED_ENABLE_KEYS[key] + ); + } + } + let https = MacProxies { + https: true, + https_host: Some("proxy.corp.example".into()), + https_port: Some(8080), + scoped: Scoped::Entries(vec![Some([Flag::Number(1); 5])]), + ..MacProxies::default() + }; + assert_eq!(mac_route(&https), Route::Unsupported); + for unreadable in [ + Scoped::Unreadable, + Scoped::Entries(vec![Some(harmless), None]), + Scoped::Entries(vec![Some(harmless); MAX_SCOPED_ENTRIES + 1]), + ] { + assert_eq!(mac_route(&scoped(unreadable)), Route::Unsupported); + } + } + #[test] fn windows_settings_map_to_what_webview2_does_for_https() { let cases = [ From 66cdbacb9a5b950229be3024affe518857396386 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:54:10 +0100 Subject: [PATCH 28/40] fix(map): treat incomplete robots evidence as denial and keep evidence inside the place A truncated robots sample with no rule line, or an HTML prefix, denies. A redirected robots file governs the landed origin only when it is that origin's own file. A section landing on another tenant contributes nothing. A cleaned element id falls back to the quote, and formatting runs with no source whitespace no longer split a word. --- crates/zephium-map/src/doc.rs | 11 +++ crates/zephium-map/src/doc/html.rs | 33 +++++-- crates/zephium-map/src/doc/html/tests.rs | 36 +++++++- crates/zephium-map/src/linked.rs | 3 +- crates/zephium-map/src/locator.rs | 41 ++++++++- crates/zephium-map/src/passage.rs | 2 +- crates/zephium-map/src/robots.rs | 78 ++++++++++++++--- crates/zephium-map/src/session/scheduler.rs | 14 ++- crates/zephium-map/src/site.rs | 19 +++- crates/zephium-map/src/site/navigation.rs | 2 +- crates/zephium-map/tests/doc.rs | 6 +- crates/zephium-map/tests/session.rs | 97 +++++++++++++++++++-- crates/zephium-map/tests/site.rs | 2 +- 13 files changed, 305 insertions(+), 39 deletions(-) diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 4e7faae4b..08b4cb18a 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -193,11 +193,17 @@ pub struct Node { pub marks: Marks, pub language: Option<String>, pub element_id: Option<String>, + pub element_id_cleaned: bool, } impl Node { pub(crate) fn parent_index(&self) -> Option<usize> { self.parent.map(|i| i as usize) } + pub(crate) fn selector_id(&self) -> Option<&str> { + self.element_id + .as_deref() + .filter(|_| !self.element_id_cleaned) + } pub fn accessible_name(&self) -> &str { if self.name.is_empty() && matches!( @@ -222,6 +228,7 @@ impl Node { marks: Marks::default(), language: None, element_id: None, + element_id_cleaned: false, } } } @@ -271,6 +278,7 @@ pub struct DocBuilder { limits: DocLimits, text_bytes: usize, path: Vec<usize>, + gap: bool, } impl DocBuilder { pub fn new(page: &Url, limits: DocLimits) -> Result<Self, DocError> { @@ -286,6 +294,7 @@ impl DocBuilder { limits, text_bytes: 0, path: Vec::new(), + gap: false, }) } @@ -350,7 +359,9 @@ impl DocBuilder { n.text.retain(crate::visible_char); n.name.retain(crate::visible_char); if let Some(id) = &mut n.element_id { + let raw = id.len(); id.retain(crate::visible_char); + n.element_id_cleaned = id.len() != raw; } } self.doc.head.title.retain(crate::visible_char); diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index 445604cdc..7162dcb04 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -6,6 +6,9 @@ mod decode; mod sink; const GENERIC_TEXT_CHILDREN: usize = 8; +const FORMATTING_TAGS: &[&str] = &[ + "b", "i", "em", "u", "s", "small", "mark", "code", "sub", "sup", "wbr", +]; impl Doc { pub fn from_html( @@ -187,14 +190,14 @@ impl DocBuilder { } } - fn append(&mut self, at: usize, raw: &str, verbatim: bool) { + fn append(&mut self, at: usize, raw: &str, verbatim: bool, gap: bool) { let node = &self.doc.nodes[at]; let room = self.limits.node_text_bytes as usize - node.language.as_deref().map_or(0, str::len) - node.text.len() - node.name.len() - node.element_id.as_deref().map_or(0, str::len); - let separator = !verbatim && !node.text.is_empty(); + let separator = !verbatim && gap && !node.text.is_empty(); let room = room.min(self.limits.text_bytes as usize - self.text_bytes); let extra = usize::from(separator); let end = raw.floor_char_boundary(room.saturating_sub(extra)); @@ -243,14 +246,17 @@ impl DocBuilder { level: usize, ) -> Result<(), DocError> { let mut ancestor = parent; + let space = |c: char| c.is_control() || c.is_whitespace(); let words = if verbatim { Cow::Borrowed(raw) } else { Cow::Owned(self.words(raw)) }; if words.is_empty() { + self.gap |= !raw.is_empty(); return Ok(()); } + let gap = std::mem::replace(&mut self.gap, raw.ends_with(space)) || raw.starts_with(space); let mut captured = false; let mut inline = false; let mut prose = false; @@ -282,7 +288,7 @@ impl DocBuilder { ) { captured = true; - self.append(at, &words, verbatim); + self.append(at, &words, verbatim, gap); } inside_list_or_code |= matches!( self.doc.nodes[at].role, @@ -303,7 +309,7 @@ impl DocBuilder { let mut node = Node::new(Role::Text, parent.map(|i| i as u32)); node.marks.insert(excluded); match self.push(node) { - Ok(at) => self.append(at as usize, &words, verbatim), + Ok(at) => self.append(at as usize, &words, verbatim, gap), Err(DocError::Nodes | DocError::Depth) => self.mark_truncated(), Err(e) => return Err(e), } @@ -338,15 +344,21 @@ impl DocBuilder { } fn walk(&mut self, body: NodeRef<'_>, base: &Url) -> Result<(), DocError> { - let mut pending = vec![(body, None, 0, false)]; - while let Some((n, parent, level, verbatim)) = pending.pop() { + let mut pending = vec![Some((body, None, 0, false))]; + while let Some(step) = pending.pop() { + let Some((n, parent, level, verbatim)) = step else { + self.gap = true; + continue; + }; if let Some(next) = n.sibling() { - pending.push((next, parent, level, verbatim)); + pending.push(Some((next, parent, level, verbatim))); } if n.is_text() { self.capture_text(parent, n.text(), verbatim, level)?; continue; } + let formatting = FORMATTING_TAGS.contains(&n.tag()); + self.gap |= !formatting; if self.doc.nodes.len() >= self.limits.nodes as usize || self.limits.depth as usize == 0 { self.mark_truncated(); @@ -501,12 +513,15 @@ impl DocBuilder { (parent, level) }; if let Some(child) = n.children().next() { - pending.push(( + if !formatting { + pending.push(None); + } + pending.push(Some(( child, parent, level, verbatim || role == Some(Role::CodeBlock), - )); + ))); } } Ok(()) diff --git a/crates/zephium-map/src/doc/html/tests.rs b/crates/zephium-map/src/doc/html/tests.rs index 9c1908fa6..d676f45c1 100644 --- a/crates/zephium-map/src/doc/html/tests.rs +++ b/crates/zephium-map/src/doc/html/tests.rs @@ -234,7 +234,41 @@ fn adoption_agency_reparents_children_and_merges_root_attributes() { assert!(doc .nodes() .iter() - .any(|n| n.role == Role::Paragraph && n.text == "one two three four")); + .any(|n| n.role == Role::Paragraph && n.text == "onetwothreefour")); +} + +#[test] +fn only_formatting_runs_without_source_whitespace_join() { + let doc = document( + b"<main><p>micro<b>scope</b> of H<sub>2</sub>O and decline<code>_code</code></p>\ +<p><span>Git</span><span>Hub</span></p><p><kbd>Ctrl</kbd><kbd>K</kbd></p>\ +<p>plain <em>emphasis</em>, and<em> again</em>x<i>y</i><a href='/w'>link</a>z</p>\ +<p><strong>Ada Lovelace</strong>Analytical Engine</p>\ +<p>line<br>break</p><ul><li><p>one</p>two</li></ul><div>block<div>inner</div>after</div>\ +<table><tr><td>cell<td>next</tr></table><pre>keep <b>as</b>\nis</pre></main>", + Default::default(), + ); + let texts: Vec<_> = doc.nodes().iter().map(|n| n.text.as_str()).collect(); + for expected in [ + "microscope of H2O and decline_code", + "Git Hub", + "Ctrl K", + "plain emphasis, and againxy link z", + "Ada Lovelace Analytical Engine", + "line break", + "one two", + "block inner after", + "keep as\nis", + ] { + assert!(texts.contains(&expected), "{expected:?} in {texts:?}"); + } + let cells: Vec<_> = doc + .nodes() + .iter() + .filter(|n| n.role == Role::Cell) + .map(|n| n.text.as_str()) + .collect(); + assert_eq!(cells, ["cell", "next"]); } #[test] diff --git a/crates/zephium-map/src/linked.rs b/crates/zephium-map/src/linked.rs index 590779592..703a25061 100644 --- a/crates/zephium-map/src/linked.rs +++ b/crates/zephium-map/src/linked.rs @@ -69,8 +69,7 @@ pub(crate) fn mark_answers(nodes: &mut [Node], head: &Head) { } for n in nodes { if let Some(&mark) = n - .element_id - .as_ref() + .selector_id() .and_then(|id| ids.get(id)) .or_else(|| texts.get(&n.text)) { diff --git a/crates/zephium-map/src/locator.rs b/crates/zephium-map/src/locator.rs index 7ec6e78ca..ad8142719 100644 --- a/crates/zephium-map/src/locator.rs +++ b/crates/zephium-map/src/locator.rs @@ -208,9 +208,10 @@ impl Locator { pub fn resolve(&self, doc: &Doc) -> Option<std::ops::Range<u32>> { let nodes = doc.nodes(); let element = self.element.as_ref().and_then(|id| { - let mut matches = nodes.iter().enumerate().filter(|(i, n)| { - n.element_id.as_deref() == Some(id.as_str()) && crate::visible(nodes, *i) - }); + let mut matches = nodes + .iter() + .enumerate() + .filter(|(i, n)| n.selector_id() == Some(id.as_str()) && crate::visible(nodes, *i)); let (at, n) = matches.next()?; if matches.next().is_some() { return None; @@ -284,3 +285,37 @@ impl Locator { element.map(|e| e.start..e.start + 1) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_cleaned_id_falls_back_to_its_quote_and_never_captures_an_unchanged_id() { + let doc = Doc::from_html( + &url::Url::parse("https://example.com/").unwrap(), + "<main><h2 id='a\u{200b}b'>First topic</h2><p>one</p><h2 id='ab'>Second topic</h2><p>two</p></main>".as_bytes(), + None, + crate::DocLimits::default(), + ) + .unwrap(); + let nodes = doc.nodes(); + let at = |text: &str| nodes.iter().position(|n| n.text == text).unwrap(); + let (first, second) = (at("First topic"), at("Second topic")); + assert_eq!(nodes[first].element_id.as_deref(), Some("ab")); + let locate = + |i: usize| Locator::for_text(&doc, i, &nodes[i].text, nodes[i].selector_id()).unwrap(); + let cleaned = locate(first); + assert!(cleaned.element.is_none() && cleaned.quote.is_some()); + assert_eq!(cleaned.resolve(&doc).map(|r| r.start), Some(first as u32)); + let kept = locate(second); + assert_eq!(kept.element.as_ref().map(LocatorText::as_str), Some("ab")); + assert_eq!(kept.fragment().as_deref(), Some("#ab")); + assert_eq!(kept.resolve(&doc).map(|r| r.start), Some(second as u32)); + let element = Locator { + element: kept.element, + ..Locator::default() + }; + assert_eq!(element.resolve(&doc).map(|r| r.start), Some(second as u32)); + } +} diff --git a/crates/zephium-map/src/passage.rs b/crates/zephium-map/src/passage.rs index 966b7d012..5380b595b 100644 --- a/crates/zephium-map/src/passage.rs +++ b/crates/zephium-map/src/passage.rs @@ -378,7 +378,7 @@ fn make(b: &Block<'_>, doc: &Doc) -> Option<Passage> { doc, b.node, text.get(b.quote_offset..)?, - heading.and_then(|n| n.element_id.as_deref()), + heading.and_then(|n| n.selector_id()), )?; Some(Passage { text: text.to_string(), diff --git a/crates/zephium-map/src/robots.rs b/crates/zephium-map/src/robots.rs index e18289ca4..4fdf6a33e 100644 --- a/crates/zephium-map/src/robots.rs +++ b/crates/zephium-map/src/robots.rs @@ -50,9 +50,21 @@ impl Robots { pub fn parse(text: &str) -> Self { Self::from_sample(text.as_bytes(), false) } - pub(crate) fn from_sample(bytes: &[u8], truncated: bool) -> Self { + pub fn from_sample(bytes: &[u8], truncated: bool) -> Self { let prefix = &bytes[..bytes.len().min(MAX_ROBOTS_BYTES)]; - let complete = if truncated || prefix.len() < bytes.len() { + let readable = match std::str::from_utf8(prefix) { + Ok(text) => text, + Err(e) => std::str::from_utf8(&prefix[..e.valid_up_to()]).unwrap_or_default(), + }; + if readable + .trim_start_matches(|c: char| c == '\u{feff}' || c.is_whitespace()) + .starts_with('<') + || prefix.contains(&0) + { + return Self::unavailable(false); + } + let truncated = truncated || prefix.len() < bytes.len(); + let complete = if truncated { prefix .iter() .rposition(|&b| matches!(b, b'\r' | b'\n')) @@ -64,19 +76,12 @@ impl Robots { return Self::unavailable(false); }; let limited = || Self::empty(RobotsOutcome::Limit); - if text - .trim_start_matches('\u{feff}') - .trim_start() - .starts_with('<') - || text.contains('\0') - { - return Self::unavailable(false); - } let mut result = Self::empty(RobotsOutcome::Parsed); - result.truncated = truncated || bytes.len() > MAX_ROBOTS_BYTES; + result.truncated = truncated; let mut groups = [Vec::new(), Vec::new()]; let mut selected = 0; let mut directives = false; + let mut read_rule = false; let mut specific = false; let mut rules = 0; for line in text.trim_start_matches('\u{feff}').split(['\r', '\n']) { @@ -100,6 +105,7 @@ impl Robots { } "allow" | "disallow" => { directives = true; + read_rule = true; if selected == 0 || value.is_empty() { continue; } @@ -129,6 +135,11 @@ impl Robots { _ => {} } } + if truncated && !read_rule { + let mut unread = Self::unavailable(false); + unread.truncated = true; + return unread; + } result.rules = std::mem::take(&mut groups[usize::from(specific)]); result } @@ -210,4 +221,49 @@ mod tests { RobotsOutcome::Unreadable ); } + + #[test] + fn a_truncated_sample_without_a_complete_rule_denies() { + for (sample, truncated) in [ + (&b"U"[..], true), + (b"User-agent: *\nDisallow: /", true), + ( + b"\xef\xbb\xbf <!doctype html><html><body>User-agent: *", + true, + ), + (b" <html>\nUser-agent: *\nDisallow: /private\n", true), + (b"<html>\nUser-agent: *\nAllow: /\n", false), + (b"# robots for example\n# Disallow: /\n#", true), + ( + b"User-agent: *\nSitemap: https://example.com/map.xml\nDisa", + true, + ), + ] { + let parsed = Robots::from_sample(sample, truncated); + assert_eq!(parsed.outcome, RobotsOutcome::Unreadable, "{sample:?}"); + assert!(!parsed.allows("/")); + assert!(parsed.sitemaps.is_empty()); + } + let prefix = b"User-agent: *\nDisallow: /private\nUser-agent: zeph"; + let parsed = Robots::from_sample(prefix, true); + assert_eq!(parsed.outcome, RobotsOutcome::Parsed); + assert!(parsed.allows("/") && !parsed.allows("/private")); + let other = Robots::from_sample(b"User-agent: other\nDisallow: /\nUser", true); + assert_eq!(other.outcome, RobotsOutcome::Parsed); + assert!(other.allows("/")); + } + + #[test] + fn an_untruncated_empty_or_comment_only_file_allows_all() { + for text in ["", "\n", "# nothing here\n# Disallow: /", "User-agent: *\n"] { + let parsed = Robots::parse(text); + assert_eq!(parsed.outcome, RobotsOutcome::Parsed, "{text:?}"); + assert!(parsed.allows("/")); + } + let oversized = format!( + "{}User-agent: *\nDisallow: /", + "#\n".repeat(MAX_ROBOTS_BYTES) + ); + assert_eq!(Robots::parse(&oversized).outcome, RobotsOutcome::Unreadable); + } } diff --git a/crates/zephium-map/src/session/scheduler.rs b/crates/zephium-map/src/session/scheduler.rs index fbcdc519d..7b667cb85 100644 --- a/crates/zephium-map/src/session/scheduler.rs +++ b/crates/zephium-map/src/session/scheduler.rs @@ -274,13 +274,19 @@ impl Session { return Err(Failure::ContentType); } if let Work::Section(i, ref key) = job.work { - if SiteKey::from_url(&job.url) != SiteKey::from_url(&r.final_url) { + let other_tenant = self.sites[i].as_ref().is_some_and(|s| { + let place = s.place.as_ref().map_or(&s.seed.site, |p| &p.key); + place.tenant.is_some() + && PlaceKey::from_url(&r.final_url).as_ref() != Some(place) + }); + if other_tenant || SiteKey::from_url(&job.url) != SiteKey::from_url(&r.final_url) { if let Some((s, landing)) = self.sites[i] .as_mut() .zip(PageKey::from_url(&r.final_url).ok()) { s.external.insert(key.clone(), landing); } + return Err(Failure::External); } } if PageKey::from_url(&r.final_url).is_err() @@ -302,7 +308,11 @@ impl Session { Ok(r) }); if job.work == Work::Robots { - let landing = result.as_ref().ok().map(|r| origin(&r.final_url)); + let landing = result.as_ref().ok().and_then(|r| { + let landing = origin(&r.final_url); + (r.final_url.as_str().strip_prefix(landing.as_str()) == Some("/robots.txt")) + .then_some(landing) + }); let policy = match result { Ok(r) => Robots::from_sample(&r.bytes, r.truncated), Err(f) => { diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 76af78100..204fc7f1f 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -761,8 +761,12 @@ fn element_locator(url: &Url) -> Result<Locator, KeyError> { else { return Ok(Locator::default()); }; + let id = decode_fragment(fragment); + if crate::clean_text(&id) != id { + return Ok(Locator::default()); + } Ok(Locator { - element: Some(LocatorText::new(&decode_fragment(fragment))?), + element: Some(LocatorText::new(&id)?), ..Default::default() }) } @@ -1126,6 +1130,19 @@ mod tests { assert_eq!(focus.key.as_url().path(), "/pricing"); } } + + #[test] + fn a_link_fragment_changed_by_cleaning_names_no_element() { + let locator = |raw: &str| element_locator(&Url::parse(raw).unwrap()).unwrap(); + assert!(locator("https://workshop.example/a#a%E2%80%8Bb") == Locator::default()); + assert_eq!( + locator("https://workshop.example/a#ab") + .element + .as_ref() + .map(LocatorText::as_str), + Some("ab") + ); + } } #[cfg(test)] diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index 5a691afa3..e22f88bfb 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -344,7 +344,7 @@ impl Build<'_> { continue; } let locator = if dated || n.element_id.is_some() { - Locator::for_text(doc, i, &n.text, n.element_id.as_deref()) + Locator::for_text(doc, i, &n.text, n.selector_id()) } else { None }; diff --git a/crates/zephium-map/tests/doc.rs b/crates/zephium-map/tests/doc.rs index df858c6b2..01e58972e 100644 --- a/crates/zephium-map/tests/doc.rs +++ b/crates/zephium-map/tests/doc.rs @@ -395,11 +395,15 @@ fn dropped_head_metadata_keeps_complete_organic_results_readable() { #[test] fn page_strings_strip_directional_and_zero_width_controls() { - let doc=defaults("<title>A\u{202e}cme</title><main><h2 id='a\u{200b}b'>A\u{2066}B</h2><a aria-label='X\u{feff}Y' href='/'>Link</a></main>"); + let doc=defaults("<title>A\u{202e}cme</title><main><h2 id='a\u{200b}b'>A\u{2066}B</h2><h3 id='kept'>Kept</h3><a aria-label='X\u{feff}Y' href='/'>Link</a></main>"); assert_eq!(doc.head().title, "Acme"); let heading = doc.nodes().iter().find(|n| n.element_id.is_some()).unwrap(); assert_eq!(heading.element_id.as_deref(), Some("ab")); + assert!(heading.element_id_cleaned); assert_eq!(heading.text, "AB"); + let kept = doc.nodes().iter().find(|n| n.text == "Kept").unwrap(); + assert_eq!(kept.element_id.as_deref(), Some("kept")); + assert!(!kept.element_id_cleaned); assert!(doc.nodes().iter().any(|n| n.name == "XY")); assert_eq!( zephium_map::key::LocatorText::new("a\u{200d}b") diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index b98191e91..419991937 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -778,6 +778,52 @@ fn cross_domain_section_redirect_only_changes_the_landing() { assert!(!r.trace.iter().any(|e| e.contains("other.example"))); } +#[test] +fn a_section_landing_in_another_tenant_contributes_nothing() { + let results = "<main><article><h2><a href='https://github.com/org/first'>GitHub first</a></h2></article></main>"; + let r = run(cfg(), "github", results, |e| { + match e { + Effect::Fetch { id, url, .. } if url.path() == "/org/first" => Some(response( + *id, + url, + "text/html", + "<title>first</title><nav><a href='/org/first/pricing'>Pricing</a><a href='/org/first/news'>News</a></nav>", + )), + Effect::Fetch { id, url, .. } if url.path() == "/org/first/pricing" => Some(response( + *id, + &Url::parse("https://github.com/org/second/pricing").unwrap(), + "text/html", + include_str!("fixtures/section-pricing.html"), + )), + Effect::Fetch { id, url, .. } if url.path() == "/org/first/news" => Some(response( + *id, + url, + "text/html", + include_str!("fixtures/section-changes.html"), + )), + _ => None, + } + }); + let place = r.places.last().unwrap(); + assert_eq!(place.key.tenant.as_deref(), Some("/org/first")); + let entry = |label: &str| place.sections.iter().find(|e| e.label == label).unwrap(); + let moved = entry("Pricing"); + assert_eq!(moved.key.as_str(), "https://github.com/org/second/pricing"); + assert!(moved.children.is_empty() && !moved.off_site); + assert!(moved.locator == Locator::default()); + assert_eq!( + moved.read, + Some(ReadState::Refused { + failure: Failure::External + }) + ); + assert!(!entry("News").children.is_empty()); + assert_eq!( + r.stats.phases[&Phase::Section].refused[&Failure::External], + 1 + ); +} + #[test] fn named_place_passage_shares_one_entry_read() { let r = run(cfg(), "how do acme.com timers work", RESULT, |e| match e { @@ -953,11 +999,13 @@ fn repository_memo_cannot_cross_tenants_or_store_result_evidence() { } #[test] -fn redirects_apply_robots_to_both_origins_only_at_the_robots_path() { - for (landing, allowed) in [ - ("https://www.acme.com/robots.txt", true), - ("https://other.com/robots.txt", false), - ("https://acme.com/consent", false), +fn a_redirected_robots_file_governs_the_landed_origin_only_as_its_own_file() { + for (landing, allowed, reads) in [ + ("https://www.acme.com/robots.txt", true, 1), + ("https://www.acme.com/en/robots.txt", true, 2), + ("https://www.acme.com/robots.txt?lang=en", true, 2), + ("https://other.com/robots.txt", false, 1), + ("https://acme.com/consent", false, 1), ] { let r = run(cfg(), "acme", RESULT, |e| match e { Effect::Fetch { id, url, .. } if url.path() == "/robots.txt" => Some(response( @@ -974,7 +1022,14 @@ fn redirects_apply_robots_to_both_origins_only_at_the_robots_path() { )), _ => None, }); - assert_eq!(r.stats.phases[&Phase::Robots].started, 1); + assert_eq!(r.stats.phases[&Phase::Robots].started, reads, "{landing}"); + assert_eq!( + r.trace + .iter() + .filter(|s| s.as_str() == "fetch www.acme.com/robots.txt") + .count() as u32, + reads - 1 + ); assert_eq!(!r.places.is_empty(), allowed); assert!(!r.trace.iter().any(|s| s.ends_with("/pricing"))); if allowed { @@ -1236,6 +1291,36 @@ fn robots_uses_its_own_ceiling_and_enforces_complete_rules_from_a_prefix() { assert!(run.places.last().unwrap().notes.robots_disallowed); } +#[test] +fn a_robots_sample_cut_before_any_rule_denies_the_site() { + let r = run( + Config { + text_bytes: 1, + ..cfg() + }, + "acme", + RESULT, + |effect| match effect { + Effect::Fetch { + id, url, max_bytes, .. + } if url.path() == "/robots.txt" => { + assert_eq!(*max_bytes, 1); + Some(response( + *id, + url, + "text/plain", + "User-agent: *\nAllow: /\n", + )) + } + Effect::Fetch { .. } => panic!("read without robots evidence"), + _ => None, + }, + ); + assert_eq!(r.stats.robots[&RobotsOutcome::Unreadable], 1); + assert_eq!(r.stats.phases[&Phase::Entry].refused[&Failure::Robots], 1); + assert!(r.places.is_empty()); +} + #[test] fn cached_place_recomputes_focus_for_the_current_query() { let first = run(cfg(), "acme pricing", RESULT, |_| None); diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index 4b88fd882..c86ab2517 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -261,7 +261,7 @@ fn hostile_inputs_fail_closed_or_keep_bounded_independent_evidence() { assert_eq!(labels(&p.sections), ["About"]); assert_eq!( Robots::parse(&"\n".repeat(1024 * 1024)).outcome, - RobotsOutcome::Parsed + RobotsOutcome::Unreadable ); } #[test] From fbf2d1f4608a35663f86705576caad607aecaefb Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 19:54:11 +0100 Subject: [PATCH 29/40] fix(xtask): check robots in the map probe with the engine's parser and make replay refusals exact --- xtask/src/map_bench/probe.rs | 283 +++++++++++++++++++---- xtask/src/map_bench/run/tests/session.rs | 33 ++- xtask/src/map_bench/store.rs | 11 +- 3 files changed, 283 insertions(+), 44 deletions(-) diff --git a/xtask/src/map_bench/probe.rs b/xtask/src/map_bench/probe.rs index 4b265c9f8..6b0283c4e 100644 --- a/xtask/src/map_bench/probe.rs +++ b/xtask/src/map_bench/probe.rs @@ -1,4 +1,7 @@ use url::Url; +use zephium_map::doc::MAX_CHARSET_LABEL_BYTES; +use zephium_map::session::MAX_MEDIA_TYPE_BYTES; +use zephium_map::{robots::Robots, PageKey, SiteKey}; use zephium_public_fetch::{ReadRefusal, ReaderLimits, StatusRefusal}; use super::corpus::{CorpusQuery, Kind}; @@ -56,11 +59,28 @@ fn probe(io: &mut dyn BenchIo, site: &str) -> ProbeSite { if result.robots_stop.is_some() { return result; } + let mut policies = vec![(site.to_owned(), policy(site, &robots))]; + if !policies[0].1.allows("/") { + result.robots_stop = Some(RobotsStop::BlocksAll); + return result; + } let home = fetch(io, site, "/", Expectation::Html); result.homepage = (&home).into(); let home = if home.is_err() && !site.starts_with("www.") { - let retry = fetch(io, &format!("www.{site}"), "/", Expectation::Html); + let www = format!("www.{site}"); + let robots = fetch(io, &www, "/robots.txt", Expectation::Text); + if let Some(stop) = robots_stop(&robots) { + result.robots_stop = Some(stop); + return result; + } + let www_policy = policy(&www, &robots); + if !www_policy.allows("/") { + result.robots_stop = Some(RobotsStop::BlocksAll); + return result; + } + policies.push((www.clone(), www_policy)); + let retry = fetch(io, &www, "/", Expectation::Html); result.www_retry = Some((&retry).into()); retry } else { @@ -70,8 +90,23 @@ fn probe(io: &mut dyn BenchIo, site: &str) -> ProbeSite { if let Ok(home) = home { if let Some(host) = home.final_url.host_str() { result.homepage_final_host = Some(host.to_owned()); - result.llms = (&fetch(io, host, "/llms.txt", Expectation::Text)).into(); - result.sitemap = (&fetch(io, host, "/sitemap.xml", Expectation::Xml)).into(); + let known = policies + .into_iter() + .find_map(|(origin, policy)| (origin == host).then_some(policy)); + let landed = known.or_else(|| { + let robots = fetch(io, host, "/robots.txt", Expectation::Text); + robots_stop(&robots) + .is_none() + .then(|| policy(host, &robots)) + }); + if let Some(landed) = landed { + if landed.allows("/llms.txt") { + result.llms = (&fetch(io, host, "/llms.txt", Expectation::Text)).into(); + } + if landed.allows("/sitemap.xml") { + result.sitemap = (&fetch(io, host, "/sitemap.xml", Expectation::Xml)).into(); + } + } } } result @@ -93,41 +128,53 @@ fn robots_stop(result: &FetchResult) -> Option<RobotsStop> { match result { Err(FetchRefusal::Interrupted) => Some(RobotsStop::Interrupted), Err(FetchRefusal::Reader(ReadRefusal::Timeout(_))) => Some(RobotsStop::Timeout), - Err(FetchRefusal::Reader(ReadRefusal::Status(StatusRefusal::Server))) => { - Some(RobotsStop::Server) - } - Ok(body) if blocks_all(&body.bytes) => Some(RobotsStop::BlocksAll), + Err(FetchRefusal::Reader(ReadRefusal::Status( + StatusRefusal::Server | StatusRefusal::RateLimited, + ))) => Some(RobotsStop::Server), _ => None, } } -fn blocks_all(bytes: &[u8]) -> bool { - let mut wildcard = false; - let mut saw_rule = false; - for raw in bytes.split(|&byte| byte == b'\n') { - let Ok(raw) = std::str::from_utf8(raw) else { - continue; - }; - let line = raw.trim().trim_start_matches('\u{feff}'); - let field = line.split('#').next().unwrap_or_default().trim(); - let Some((key, value)) = field.split_once(':') else { - continue; - }; - let key = key.trim(); - if key.eq_ignore_ascii_case("user-agent") { - if saw_rule { - wildcard = false; - saw_rule = false; - } - wildcard |= value.trim() == "*"; - } else if key.eq_ignore_ascii_case("allow") || key.eq_ignore_ascii_case("disallow") { - saw_rule = true; - if wildcard && line == "Disallow: /" { - return true; - } +/// The session engine's robots admission: `Session::receive` for `Work::Robots` +/// in `zephium-map/src/session/scheduler.rs`, fed by `failure` and `session_body` +/// in `map_bench/session.rs`. +fn policy(host: &str, result: &FetchResult) -> Robots { + let body = match result { + Ok(body) => body, + Err(FetchRefusal::Reader(ReadRefusal::Status(StatusRefusal::Client))) => { + return Robots::unavailable(true) } + Err(_) => return Robots::unavailable(false), + }; + let media = body + .media_type + .as_deref() + .unwrap_or("text/plain") + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + let site = Url::parse(&format!("https://{host}/")) + .ok() + .and_then(|url| SiteKey::from_url(&url)); + if body + .media_type + .as_ref() + .is_some_and(|m| m.len() > MAX_MEDIA_TYPE_BYTES) + || body + .charset + .as_ref() + .is_some_and(|c| c.len() > MAX_CHARSET_LABEL_BYTES) + || !matches!(media.as_str(), "text/plain" | "text/markdown") + || PageKey::from_url(&body.final_url).is_err() + || site.is_none() + || SiteKey::from_url(&body.final_url) != site + || !body.final_url.path().ends_with("/robots.txt") + { + return Robots::unavailable(false); } - false + Robots::from_sample(&body.bytes, body.truncated) } #[cfg(test)] @@ -205,7 +252,14 @@ mod tests { StatusRefusal::Client, ))), Err(FetchRefusal::Reader(ReadRefusal::Transport)), + Err(FetchRefusal::Reader(ReadRefusal::Status( + StatusRefusal::Client, + ))), body("https://docs.example.com/", b"home"), + body( + "https://docs.example.com/robots.txt", + b"User-agent: *\nDisallow: /private", + ), body("https://docs.example.com/llms.txt", b"llms"), body("https://docs.example.com/sitemap.xml", b"xml"), ] @@ -222,7 +276,15 @@ mod tests { [ ("https://example.com/robots.txt".into(), Expectation::Text), ("https://example.com/".into(), Expectation::Html), + ( + "https://www.example.com/robots.txt".into(), + Expectation::Text + ), ("https://www.example.com/".into(), Expectation::Html), + ( + "https://docs.example.com/robots.txt".into(), + Expectation::Text + ), ( "https://docs.example.com/llms.txt".into(), Expectation::Text @@ -280,15 +342,158 @@ mod tests { assert_eq!(io.calls.len(), 5); assert_eq!(io.calls[1].0, "https://b.com/robots.txt"); } - for robots in [ - "User-agent: *\n# Disallow: /", - "User-agent: *\nDisallow: / # comment", - "User-agent: specific\nDisallow: /", - "User-agent: *\nDisallow: /page", + for (robots, home) in [ + ("User-agent: *\n# Disallow: /", true), + ("User-agent: *\nDisallow: / # comment", false), + ("User-agent: specific\nDisallow: /", true), + ("User-agent: *\nDisallow: /page", true), + ("User-agent: other\nUser-agent: *\nDisallow: /", false), + ("User-agent: *\nDisallow: /\nAllow: /$", true), + ("<html><body>Not found</body></html>", false), ] { - assert!(!blocks_all(robots.as_bytes())); + let policy = policy( + "a.com", + &body("https://a.com/robots.txt", robots.as_bytes()), + ); + assert_eq!(policy.allows("/"), home, "{robots:?}"); + } + } + + #[test] + fn robots_refusals_follow_the_session_engine() { + let mut html = body("https://a.com/robots.txt", b"User-agent: *\nAllow: /"); + if let Ok(body) = &mut html { + body.media_type = Some("text/html".into()); } - assert!(blocks_all(b"User-agent: other\nUser-agent: *\nDisallow: /")); + let refused = |r: ReadRefusal| Err(FetchRefusal::Reader(r)); + let labelled = |media: usize, charset: usize| { + let mut robots = body("https://a.com/robots.txt", b"User-agent: *\nAllow: /"); + if let Ok(body) = &mut robots { + body.media_type = Some(format!("text/plain{}", " ".repeat(media - 10))); + body.charset = Some("u".repeat(charset)); + } + robots + }; + for (robots, allowed) in [ + ( + labelled(MAX_MEDIA_TYPE_BYTES, MAX_CHARSET_LABEL_BYTES), + true, + ), + (labelled(MAX_MEDIA_TYPE_BYTES + 1, 1), false), + (labelled(10, MAX_CHARSET_LABEL_BYTES + 1), false), + (refused(ReadRefusal::Status(StatusRefusal::Client)), true), + ( + body("https://a.com/robots.txt", b"User-agent: *\nAllow: /"), + true, + ), + ( + body("https://www.a.com/robots.txt", b"User-agent: *\nAllow: /"), + true, + ), + (refused(ReadRefusal::Transport), false), + (refused(ReadRefusal::WrongContentType), false), + (refused(ReadRefusal::Status(StatusRefusal::Denied)), false), + ( + refused(ReadRefusal::Status(StatusRefusal::Unexpected)), + false, + ), + (refused(ReadRefusal::Encoding), false), + ( + refused(ReadRefusal::TooLarge(zephium_public_fetch::SizeLimit::Wire)), + false, + ), + (refused(ReadRefusal::RedirectRefused), false), + (Err(FetchRefusal::Limit), false), + (html, false), + ( + body("https://other.com/robots.txt", b"User-agent: *\nAllow: /"), + false, + ), + ( + body("https://a.com/consent", b"User-agent: *\nAllow: /"), + false, + ), + ] { + assert_eq!(policy("a.com", &robots).allows("/"), allowed, "{robots:?}"); + } + let query = fixture("[[query]]\nid='q'\ntext='q'\nkind='place'\nsite='a.com'"); + let mut io = FakeIo { + calls: vec![], + results: [Err(FetchRefusal::Reader(ReadRefusal::Transport))].into(), + }; + let outcome = ProbeEngine.run(&query, &mut io); + assert_eq!(outcome.probe[0].robots_stop, Some(RobotsStop::BlocksAll)); + assert_eq!(io.calls.len(), 1); + let mut io = FakeIo { + calls: vec![], + results: [Err(FetchRefusal::Reader(ReadRefusal::Status( + StatusRefusal::RateLimited, + )))] + .into(), + }; + let outcome = ProbeEngine.run(&query, &mut io); + assert_eq!(outcome.probe[0].robots_stop, Some(RobotsStop::Server)); + } + + #[test] + fn each_requested_path_and_each_new_origin_is_checked_against_robots() { + let place = |site: &str| { + fixture(&format!( + "[[query]]\nid='q'\ntext='q'\nkind='place'\nsite='{site}'" + )) + }; + let mut io = FakeIo { + calls: vec![], + results: [ + body( + "https://a.com/robots.txt", + b"User-agent: *\nDisallow: /\nAllow: /$", + ), + body("https://a.com/", b"home"), + ] + .into(), + }; + let outcome = ProbeEngine.run(&place("a.com"), &mut io); + assert_eq!(outcome.probe[0].robots_stop, None); + assert!(outcome.probe[0].homepage.answered()); + assert_eq!(outcome.probe[0].llms, ProbeFetch::Skipped); + assert_eq!(outcome.probe[0].sitemap, ProbeFetch::Skipped); + assert_eq!(io.calls.len(), 2); + let mut io = FakeIo { + calls: vec![], + results: [ + body("https://a.com/robots.txt", b"User-agent: *\nAllow: /"), + Err(FetchRefusal::Reader(ReadRefusal::Transport)), + body( + "https://www.a.com/robots.txt", + b"User-agent: *\nDisallow: /", + ), + ] + .into(), + }; + let outcome = ProbeEngine.run(&place("a.com"), &mut io); + assert_eq!(outcome.probe[0].robots_stop, Some(RobotsStop::BlocksAll)); + assert_eq!(outcome.probe[0].www_retry, None); + assert_eq!(io.calls.last().unwrap().0, "https://www.a.com/robots.txt"); + assert!(io.results.is_empty()); + let mut io = FakeIo { + calls: vec![], + results: [ + body("https://a.com/robots.txt", b"User-agent: *\nAllow: /"), + body("https://docs.a.com/", b"home"), + body( + "https://docs.a.com/robots.txt", + b"User-agent: *\nDisallow: /llms.txt", + ), + body("https://docs.a.com/sitemap.xml", b"xml"), + ] + .into(), + }; + let outcome = ProbeEngine.run(&place("a.com"), &mut io); + assert_eq!(outcome.probe[0].llms, ProbeFetch::Skipped); + assert!(outcome.probe[0].sitemap.answered()); + assert_eq!(io.calls[2].0, "https://docs.a.com/robots.txt"); + assert_eq!(io.calls[3].0, "https://docs.a.com/sitemap.xml"); } #[test] diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 2538331a6..8c0d46c66 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -732,6 +732,7 @@ fn replay_uses_reader_time_for_journals_without_a_request_start() { #[test] fn replay_refusals_require_evidence_for_the_requested_limits() { + use zephium_public_fetch::SizeLimit; let root = tempfile::tempdir().unwrap(); let req = request("/docs", Expectation::Html); for (index, class) in ReadRefusal::ALL @@ -750,7 +751,10 @@ fn replay_refusals_require_evidence_for_the_requested_limits() { for cap in [req.max_bytes - 1, req.max_bytes, req.max_bytes + 1] { for timeout in [2999, 3000, 3001] { let compatible = match class { - FetchRefusal::Reader(ReadRefusal::TooLarge(_)) => cap <= req.max_bytes, + FetchRefusal::Reader(ReadRefusal::TooLarge(SizeLimit::Headers)) => true, + FetchRefusal::Reader( + ReadRefusal::TooLarge(SizeLimit::Wire) | ReadRefusal::Encoding, + ) => cap >= req.max_bytes, FetchRefusal::Reader(ReadRefusal::Timeout(_)) => timeout <= 3000, FetchRefusal::Reader(_) => true, _ => cap == req.max_bytes && timeout == 3000, @@ -767,6 +771,33 @@ fn replay_refusals_require_evidence_for_the_requested_limits() { ); } } + if matches!( + class, + FetchRefusal::Reader(ReadRefusal::TooLarge(_) | ReadRefusal::Encoding) + ) { + for (cap, timeout, answered) in [ + (req.max_bytes, 9, false), + (req.max_bytes, 10, true), + (req.max_bytes * 2, 9, false), + (req.max_bytes * 2, 10, true), + ( + 1, + 10, + class == FetchRefusal::Reader(ReadRefusal::TooLarge(SizeLimit::Headers)), + ), + ] { + let expected = if answered { + class + } else { + FetchRefusal::NotRecorded + }; + assert_eq!( + replay_row(&path, &req, cap, timeout), + Err(expected), + "{class:?} {cap} {timeout}" + ); + } + } } } diff --git a/xtask/src/map_bench/store.rs b/xtask/src/map_bench/store.rs index 787dd929c..d479c7264 100644 --- a/xtask/src/map_bench/store.rs +++ b/xtask/src/map_bench/store.rs @@ -6,7 +6,9 @@ use std::time::Duration; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use sha2::{Digest, Sha256}; use url::Url; -use zephium_public_fetch::{PublicBody, ReadRefusal, StatusClass, Timings, MAX_DECODED_BYTES}; +use zephium_public_fetch::{ + PublicBody, ReadRefusal, SizeLimit, StatusClass, Timings, MAX_DECODED_BYTES, +}; use super::corpus::valid_id; use super::engine::{ @@ -453,8 +455,9 @@ impl RequestRow { } } (ResultClass::Refused(FetchRefusal::Reader(class)), None) => match class { - ReadRefusal::TooLarge(_) => { - request.max_bytes <= self.cap && request.timeout >= completion + ReadRefusal::TooLarge(SizeLimit::Headers) => request.timeout >= completion, + ReadRefusal::TooLarge(SizeLimit::Wire) | ReadRefusal::Encoding => { + request.max_bytes >= self.cap && request.timeout >= completion } ReadRefusal::Timeout(_) => request.timeout <= self.timeout, ReadRefusal::NotPublicHttps @@ -464,7 +467,7 @@ impl RequestRow { | ReadRefusal::ProxyUnsupported | ReadRefusal::RouteChanged | ReadRefusal::Transport => true, - ReadRefusal::Status(_) | ReadRefusal::WrongContentType | ReadRefusal::Encoding => { + ReadRefusal::Status(_) | ReadRefusal::WrongContentType => { request.timeout >= completion } }, From 9d9176a4e07707a88488d94a2c5b130d1d618973 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 20:11:57 +0100 Subject: [PATCH 30/40] feat(map-driver): count the reads it starts and the bytes it hands on --- crates/zephium-map-driver/src/driver.rs | 22 +++++++++- crates/zephium-map-driver/src/driver/tests.rs | 41 ++++++++++++++++++- 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/zephium-map-driver/src/driver.rs b/crates/zephium-map-driver/src/driver.rs index 429b490bf..ae44076e4 100644 --- a/crates/zephium-map-driver/src/driver.rs +++ b/crates/zephium-map-driver/src/driver.rs @@ -1,7 +1,7 @@ use std::{ collections::{BTreeMap, HashMap, VecDeque}, sync::{ - atomic::{AtomicU32, Ordering}, + atomic::{AtomicU32, AtomicU64, Ordering}, Arc, Mutex, MutexGuard, PoisonError, }, time::Duration, @@ -42,6 +42,8 @@ pub struct MapRequest { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Counts { + pub fetches: u32, + pub bytes: u64, pub render_unavailable: u32, pub anonymous_unavailable: u32, pub truncated_results: u32, @@ -51,6 +53,8 @@ pub struct Counts { #[derive(Default)] struct Shared { targets: Mutex<[Option<Targets>; SLOTS]>, + fetches: AtomicU32, + bytes: AtomicU64, render_unavailable: AtomicU32, anonymous_unavailable: AtomicU32, truncated_results: AtomicU32, @@ -153,6 +157,8 @@ impl Driver { pub fn counts(&self) -> Counts { let load = |counter: &AtomicU32| counter.load(Ordering::Acquire); Counts { + fetches: load(&self.shared.fetches), + bytes: self.shared.bytes.load(Ordering::Acquire), render_unavailable: load(&self.shared.render_unavailable), anonymous_unavailable: load(&self.shared.anonymous_unavailable), truncated_results: load(&self.shared.truncated_results), @@ -294,6 +300,7 @@ impl Run { let mut session = self.session.take()?; let time = self.elapsed(); let cancelling = self.cancelling; + let shared = Arc::clone(&self.shared); let done = task::spawn_blocking(move || { let mut effects = if cancelling { Vec::new() @@ -302,6 +309,18 @@ impl Run { }; if let Some(input) = input { if !effects.iter().any(is_end) { + if let Input::Fetch { + result: Ok(answer), .. + } = &input + { + let size = answer.bytes.len() as u64; + let _ = + shared + .bytes + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + Some(n.saturating_add(size)) + }); + } effects.extend(session.handle(input)); } } @@ -468,6 +487,7 @@ impl Run { } let fetcher = Arc::clone(&self.io.fetch); let timeout = request.timeout; + bump(&self.shared.fetches); let read = self.reads.spawn(async move { let result = tokio::time::timeout(timeout, fetcher.fetch(request)) .await diff --git a/crates/zephium-map-driver/src/driver/tests.rs b/crates/zephium-map-driver/src/driver/tests.rs index 08ba2496c..a0557e7df 100644 --- a/crates/zephium-map-driver/src/driver/tests.rs +++ b/crates/zephium-map-driver/src/driver/tests.rs @@ -323,7 +323,15 @@ async fn a_place_streams_first_layer_then_places_then_one_end() { ] { assert_eq!(driver.target(slot, target), None); } - assert_eq!(driver.counts(), Counts::default()); + let counts = driver.counts(); + assert_eq!( + counts, + Counts { + fetches: counts.fetches, + bytes: counts.bytes, + ..Counts::default() + } + ); let fetched = fake.seen().fetches.len(); tokio::time::sleep(Duration::from_secs(30)).await; assert_eq!(fake.seen().fetches.len(), fetched); @@ -445,6 +453,37 @@ async fn the_driver_refuses_reads_over_the_ceilings() { assert_eq!(run.hosts.len(), MAX_CONCURRENT - 1); } +#[tokio::test] +async fn two_fetch_answers_are_counted_and_the_counts_survive_cancel() { + const ROBOTS: &str = "User-agent: *\nAllow: /\n"; + let fake = Arc::new(Fake::new(html(RESULT)).site( + "acme.com", + &[ + ("/robots.txt", Plan::Page("text/plain", ROBOTS.into())), + ("/", html(NAV)), + ], + )); + // The first layer fills the buffer so the first place blocks further effects. + let (driver, mut rx) = + Driver::start_buffered(request("acme"), io(&fake), &Handle::current(), 1).unwrap(); + let bytes = (ROBOTS.len() + NAV.len()) as u64; + tokio::time::timeout(FETCH_TIMEOUT, async { + while driver.counts().bytes < bytes { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + assert_eq!(driver.counts().fetches, 2); + assert_eq!(driver.counts().bytes, bytes); + driver.cancel(); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!(outcome(&changes).0, Outcome::Cancelled); + assert_eq!(driver.counts().fetches, 2); + assert_eq!(driver.counts().bytes, bytes); +} + #[tokio::test(start_paused = true)] async fn cancel_ends_once_and_starts_nothing_after() { let fake = Arc::new(Fake::new(html(RESULT)).site("acme.com", &[("/", Plan::Hang)])); From 5c22dd3e574ef899b5fc8a71204af20ca23f3aa4 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 20:11:57 +0100 Subject: [PATCH 31/40] feat(xtask): run a search map from the terminal --- Cargo.lock | 1 + xtask/Cargo.toml | 3 +- xtask/src/main.rs | 4 +- xtask/src/map_try.rs | 413 +++++++++++++++++++++++++++++ xtask/src/map_try/printer.rs | 260 ++++++++++++++++++ xtask/src/map_try/printer/tests.rs | 281 ++++++++++++++++++++ xtask/src/map_try/tests.rs | 293 ++++++++++++++++++++ 7 files changed, 1253 insertions(+), 2 deletions(-) create mode 100644 xtask/src/map_try.rs create mode 100644 xtask/src/map_try/printer.rs create mode 100644 xtask/src/map_try/printer/tests.rs create mode 100644 xtask/src/map_try/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 43dd7648e..482571f12 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7388,6 +7388,7 @@ dependencies = [ "zephium-blocker", "zephium-core", "zephium-map", + "zephium-map-driver", "zephium-public-fetch", ] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index d7a0aa6d6..4f02de376 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -26,9 +26,10 @@ tempfile.workspace = true time = { version = "0.3", features = ["parsing"] } toml = "0.9" psl = "=2.1.220" -tokio = { workspace = true, features = ["time"] } +tokio = { workspace = true, features = ["time", "signal"] } url.workspace = true zephium-map = { version = "=0.1.0", path = "../crates/zephium-map" } +zephium-map-driver = { version = "=0.1.0", path = "../crates/zephium-map-driver" } zephium-public-fetch = { version = "=0.1.0", path = "../crates/zephium-public-fetch" } [target.'cfg(target_os = "macos")'.dependencies] diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bcd8687fd..fbda8026c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14,6 +14,7 @@ mod foreground_rendering_boundary; mod macos_imports; mod macos_process_family; mod map_bench; +mod map_try; mod page_assist_boundary; mod page_reader_boundary; mod password_manager_qa; @@ -101,6 +102,7 @@ fn main() { exit(1); } } + Some("map") => exit(map_try::run(&arguments[1..])), Some("webext-suite") => { if let Err(error) = webext_suite::run(&arguments[1..]) { eprintln!("extension suite: {error}"); @@ -153,7 +155,7 @@ fn main() { } _ => { eprintln!( - "usage: cargo xtask <ci|webext-suite [--only NAME,...] [--soak]|blocker-bench --zephium PATH [--browsers LIST] [--runs N] [--only SITES] [--settle-ms N] [--youtube|--startup N] [--label NAME] [--compare RESULTS]|map-bench <record|replay|report> ...|check-frame-styles|check-macos-imports <binary>|check-engine-floors [--strict]|check-release-engine-security|check-release-assets <directory> <tag> <owner/repo>|check-agentic-probe-boundary|check-advisory-exceptions [--strict]|check-security-fork-locks|check-native-adapter-locks|check-blocker-security-fork|measure-macos-process-family --bundle-id ID --duration-seconds N [--interval-millis N] [--label LABEL]|serve-password-manager-webauthn-qa [--port PORT]|check-blocker-seed|materialize-blocker-seed-webkit --output PATH|{UPDATE_BLOCKER_SEED_USAGE}|blocker-prune <materialize|notify|hosts|build> ...|check-webview2-floor [--strict]>" + "usage: cargo xtask <ci|webext-suite [--only NAME,...] [--soak]|blocker-bench --zephium PATH [--browsers LIST] [--runs N] [--only SITES] [--settle-ms N] [--youtube|--startup N] [--label NAME] [--compare RESULTS]|map-bench <record|replay|report> ...|map <query> --site HOST [--site HOST] [--private]|check-frame-styles|check-macos-imports <binary>|check-engine-floors [--strict]|check-release-engine-security|check-release-assets <directory> <tag> <owner/repo>|check-agentic-probe-boundary|check-advisory-exceptions [--strict]|check-security-fork-locks|check-native-adapter-locks|check-blocker-security-fork|measure-macos-process-family --bundle-id ID --duration-seconds N [--interval-millis N] [--label LABEL]|serve-password-manager-webauthn-qa [--port PORT]|check-blocker-seed|materialize-blocker-seed-webkit --output PATH|{UPDATE_BLOCKER_SEED_USAGE}|blocker-prune <materialize|notify|hosts|build> ...|check-webview2-floor [--strict]>" ); exit(2); } diff --git a/xtask/src/map_try.rs b/xtask/src/map_try.rs new file mode 100644 index 000000000..b90634710 --- /dev/null +++ b/xtask/src/map_try.rs @@ -0,0 +1,413 @@ +mod printer; +#[cfg(test)] +mod tests; + +use std::{ + fmt::{self, Write as _}, + future::Future, + io::{self, Write}, + sync::Arc, + time::Instant, +}; + +use tokio::{runtime::Handle, sync::watch}; +use url::{Host, Url}; +use zephium_core::search::SearchEngine; +use zephium_map::{ + read_query, + session::{Failure, FetchResult}, + QueryKind, +}; +use zephium_map_driver::{ + wire::{Change, Outcome, StartRefusal}, + Counts, Driver, FetchRequest, Fetcher, Io, MapRequest, MemoryMemo, PublicIo, Reading, + ResultsPage, ResultsSource, SystemClock, +}; +use zephium_public_fetch::{ + guard::{public_target, MAX_HOST_BYTES}, + PublicReader, PublicRoute, ReaderLimits, RouteSource, +}; + +use self::printer::{intro, refusal, Printer}; + +const ENGINE: SearchEngine = SearchEngine::DuckDuckGo; +const MAX_SITES: usize = 2; +const MAX_DNS_LABEL_BYTES: usize = 63; + +#[derive(Debug, PartialEq, Eq)] +enum Error { + MissingQuery, + MissingSite, + BadHost, + TooManySites, + UnexpectedOption, + PlaceArity, + CompareArity, + Refused(StartRefusal), + Proxy, + Runtime, + Interrupt, + Stream, + Output, +} + +impl Error { + fn usage(&self) -> bool { + matches!( + self, + Self::MissingQuery + | Self::MissingSite + | Self::BadHost + | Self::TooManySites + | Self::UnexpectedOption + | Self::PlaceArity + | Self::CompareArity + ) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::MissingQuery => { + "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private]" + } + Self::MissingSite => "Usage error: specify a host with --site", + Self::BadHost => "Usage error: --site needs a bare public hostname", + Self::TooManySites => "Usage error: specify at most two sites", + Self::UnexpectedOption => { + "Usage error: only --site and one --private flag are supported" + } + Self::PlaceArity => "Usage error: a place query needs one --site", + Self::CompareArity => "Usage error: a comparison needs two --site flags", + Self::Refused(reason) => return f.write_str(refusal(*reason)), + Self::Proxy => "The reader refuses to go around a proxy. A direct route is required.", + Self::Runtime => "Could not start the map runtime.", + Self::Interrupt => "Could not listen for Ctrl-C.", + Self::Stream => "The map stopped without an outcome.", + Self::Output => "Could not write the map to the terminal.", + }) + } +} + +struct Options<'a> { + query: &'a str, + sites: Vec<Url>, + private: bool, +} + +impl<'a> Options<'a> { + fn parse(arguments: &'a [String]) -> Result<Self, Error> { + let (query, rest) = arguments.split_first().ok_or(Error::MissingQuery)?; + if query.starts_with("--") { + return Err(Error::MissingQuery); + } + + let mut options = Self { + query, + sites: Vec::new(), + private: false, + }; + let mut args = rest.iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--site" => { + if options.sites.len() == MAX_SITES { + return Err(Error::TooManySites); + } + let raw = args + .next() + .filter(|raw| !raw.starts_with("--")) + .ok_or(Error::MissingSite)?; + options.sites.push(site_url(raw).ok_or(Error::BadHost)?); + } + "--private" if !options.private => options.private = true, + _ => return Err(Error::UnexpectedOption), + } + } + if options.sites.is_empty() { + return Err(Error::MissingSite); + } + Ok(options) + } + + fn prepare(self) -> Result<(MapRequest, StandIn), Error> { + let query = read_query(self.query).map_err(|_| Error::Refused(StartRefusal::Invalid))?; + let titles = match query.kind() { + QueryKind::Place { entity, .. } => { + if self.sites.len() != 1 { + return Err(Error::PlaceArity); + } + vec![if entity.is_empty() { + self.query.to_owned() + } else { + original_terms(self.query, entity) + }] + } + QueryKind::Compare { left, right, .. } => { + if self.sites.len() != MAX_SITES { + return Err(Error::CompareArity); + } + vec![ + original_terms(self.query, left), + original_terms(self.query, right), + ] + } + _ => return Err(Error::Refused(StartRefusal::NotAMap)), + }; + let stand_in = StandIn::new(self.sites.iter().zip(titles.iter().map(String::as_str))); + let request = MapRequest { + query: self.query.to_owned(), + engine: ENGINE, + session_id: 1, + profile: "terminal".into(), + private: self.private, + }; + Ok((request, stand_in)) + } +} + +fn site_url(raw: &str) -> Option<Url> { + let bare = raw.strip_suffix('.').unwrap_or(raw); + if bare.is_empty() + || bare.len() > MAX_HOST_BYTES + || bare.chars().any(|c| { + c.is_whitespace() + || c.is_control() + || (c.is_ascii() && !(c.is_ascii_alphanumeric() || matches!(c, '-' | '.'))) + }) + { + return None; + } + let url = Url::parse(&format!("https://{bare}/")).ok()?; + let Host::Domain(domain) = url.host()? else { + return None; + }; + (domain.split('.').all(|label| { + !label.is_empty() + && label.len() <= MAX_DNS_LABEL_BYTES + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) && public_target(&url)) + .then_some(url) +} + +fn original_terms(text: &str, terms: &[String]) -> String { + let mut words = text.split_whitespace(); + terms + .iter() + .filter_map(|term| words.find(|word| word.to_lowercase() == *term)) + .collect::<Vec<_>>() + .join(" ") +} + +struct StandIn(String); + +impl StandIn { + fn new<'a>(results: impl IntoIterator<Item = (&'a Url, &'a str)>) -> Self { + let mut html = String::from("<main>"); + for (url, title) in results { + let _ = write!( + html, + "<article><h2><a href=\"{}\">{}</a></h2></article>", + escape_html(url.as_str()), + escape_html(title) + ); + } + html.push_str("</main>"); + Self(html) + } +} + +fn escape_html(text: &str) -> String { + let mut escaped = String::new(); + for ch in text.chars() { + match ch { + '&' => escaped.push_str("&amp;"), + '<' => escaped.push_str("&lt;"), + '>' => escaped.push_str("&gt;"), + '"' => escaped.push_str("&quot;"), + _ => escaped.push(ch), + } + } + escaped +} + +impl ResultsSource for StandIn { + fn load(&self, url: Url) -> Reading<Result<ResultsPage, Failure>> { + let html = self.0.clone(); + Box::pin(async move { + Ok(ResultsPage { + html, + url, + truncated: false, + }) + }) + } +} + +struct DirectIo { + routes: RouteSource, + public: PublicIo, +} + +impl Fetcher for DirectIo { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + let routes = self.routes.clone(); + let fetch = self.public.fetch(request); + Box::pin(async move { + // On the current-thread runtime, route publication cannot interleave + // between this check and the reader taking its route snapshot. + if routes.route() != PublicRoute::Direct { + return Err(Failure::Unavailable); + } + fetch.await + }) + } +} + +fn on_direct_route<T>( + route: PublicRoute, + start: impl FnOnce() -> Result<T, Error>, +) -> Result<T, Error> { + if route != PublicRoute::Direct { + return Err(Error::Proxy); + } + start() +} + +fn print_lines( + output: &mut impl Write, + lines: impl IntoIterator<Item = String>, +) -> Result<(), Error> { + for line in lines { + writeln!(output, "{line}").map_err(|_| Error::Output)?; + } + output.flush().map_err(|_| Error::Output) +} + +async fn live( + request: MapRequest, + results: StandIn, + output: &mut impl Write, +) -> Result<Outcome, Error> { + print_lines(output, [intro(&request.query)])?; + let runtime = Handle::current(); + let routes = RouteSource::new(&runtime); + routes.set_app_proxy(None); + let interrupt = tokio::signal::ctrl_c(); + tokio::pin!(interrupt); + let started = Instant::now(); + tokio::select! { + biased; + signal = &mut interrupt => { + signal.map_err(|_| Error::Interrupt)?; + let end = Change::End { seq: 0, outcome: Outcome::Cancelled, elapsed_ms: elapsed_ms(started) }; + print_lines(output, Printer::default().lines(&end, started.elapsed(), Counts::default()))?; + return Ok(Outcome::Cancelled); + } + () = routes.settled() => {} + } + + let changed = routes.changed(); + let (driver, changes) = on_direct_route(routes.route(), || { + let reader = PublicReader::new(ReaderLimits::default(), routes.clone()); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(DirectIo { + routes, + public: PublicIo::new(&reader), + }), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + Driver::start(request, io, &runtime).map_err(Error::Refused) + })?; + stream(&driver, changes, changed, interrupt, output).await +} + +fn elapsed_ms(started: Instant) -> u32 { + u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX) +} + +async fn stream( + driver: &Driver, + mut changes: tokio::sync::mpsc::Receiver<Change>, + mut route: watch::Receiver<PublicRoute>, + mut interrupt: impl Future<Output = io::Result<()>> + Unpin, + output: &mut impl Write, +) -> Result<Outcome, Error> { + let started = Instant::now(); + let mut printer = Printer::default(); + let mut cancelling = false; + let mut watching = true; + let mut interrupted_by = None; + loop { + let change = tokio::select! { + biased; + signal = &mut interrupt, if !cancelling => { + interrupted_by = signal.err().map(|_| Error::Interrupt); + driver.cancel(); + cancelling = true; + continue; + } + left = route.wait_for(|class| *class != PublicRoute::Direct), if !cancelling && watching => { + if left.is_err() { + watching = false; + continue; + } + interrupted_by = Some(Error::Proxy); + driver.cancel(); + cancelling = true; + continue; + } + change = changes.recv() => change.ok_or(Error::Stream)?, + }; + if let Change::End { outcome, .. } = change { + print_lines( + output, + printer.lines(&change, started.elapsed(), driver.counts()), + )?; + return interrupted_by.map_or(Ok(outcome), Err); + } + if !cancelling { + let lines = printer.lines(&change, started.elapsed(), Counts::default()); + if !lines.is_empty() { + print_lines(output, lines)?; + } + } + } +} + +fn execute(arguments: &[String]) -> Result<Outcome, Error> { + let (request, results) = Options::parse(arguments)?.prepare()?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| Error::Runtime)?; + let result = runtime.block_on(live(request, results, &mut io::stdout().lock())); + runtime.shutdown_background(); + result +} + +pub(crate) fn run(arguments: &[String]) -> i32 { + std::panic::set_hook(Box::new(|_| { + let _ = writeln!(io::stderr(), "Unexpected map runtime failure."); + })); + match execute(arguments) { + Ok(Outcome::Done) => 0, + Ok(Outcome::Cancelled) => 130, + Ok(Outcome::Failed { .. }) => 1, + Err(error) => { + let _ = writeln!(io::stderr(), "{error}"); + if error.usage() { + 2 + } else { + 1 + } + } + } +} diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs new file mode 100644 index 000000000..9f1f80d0f --- /dev/null +++ b/xtask/src/map_try/printer.rs @@ -0,0 +1,260 @@ +use std::{collections::BTreeMap, time::Duration}; + +use zephium_map_driver::{ + wire::{Change, Entry, Failure, Outcome, Place, Row, StartRefusal, Tier}, + Counts, +}; + +const COLUMNS: usize = 100; +const PLACE_INTERVAL: Duration = Duration::from_millis(500); +const TABLE_DIVIDER: &str = " | "; +const TABLE_CELL: usize = (COLUMNS - TABLE_DIVIDER.len()) / 2; +const ELLIPSIS: char = '…'; + +#[derive(Default)] +struct Slot { + printed: Option<Duration>, + labels: BTreeMap<String, String>, +} + +#[derive(Default)] +pub(super) struct Printer { + slots: [Slot; super::MAX_SITES], +} + +impl Printer { + pub(super) fn lines( + &mut self, + change: &Change, + elapsed: Duration, + counts: Counts, + ) -> Vec<String> { + match change { + Change::FirstLayer { + official, + social, + organic, + .. + } => { + let mut line = format!("First layer {organic} organic"); + if let Some(official) = official { + line.push_str(&format!( + " official {} ({})", + official.title, official.site + )); + } + if !social.is_empty() { + let networks = social + .iter() + .map(|network| format!("{network:?}")) + .collect::<Vec<_>>(); + line.push_str(&format!(" social {}", networks.join(", "))); + } + vec![clip(&line, COLUMNS)] + } + Change::Place { + slot, + place, + complete, + .. + } => { + let Some(state) = self.slots.get_mut(usize::from(*slot)) else { + return Vec::new(); + }; + state.labels = entries(place) + .map(|entry| (entry.id.clone(), entry.label.clone())) + .collect(); + if *complete + || state + .printed + .is_none_or(|last| elapsed.saturating_sub(last) > PLACE_INTERVAL) + { + state.printed = Some(elapsed); + place_lines(*slot, place) + } else { + Vec::new() + } + } + Change::PlaceFailed { slot, failure, .. } => { + if let Some(state) = self.slots.get_mut(usize::from(*slot)) { + state.labels.clear(); + state.printed = Some(elapsed); + } + vec![format!( + "Place {} failed {}", + u16::from(*slot) + 1, + failure_text(*failure) + )] + } + Change::Compare { rows, .. } => { + let mut lines = vec![table_line("Left", "Right")]; + lines.extend(rows.iter().map(|row| self.row(row))); + lines + } + Change::End { + outcome, + elapsed_ms, + .. + } => vec![end_line(*outcome, *elapsed_ms, counts)], + } + } + + fn row(&self, row: &Row) -> String { + let label = |slot: &Slot, id: &Option<String>| { + id.as_ref() + .and_then(|id| slot.labels.get(id)) + .map_or_else(|| "-".into(), |label| clip(label, TABLE_CELL)) + }; + table_line( + &label(&self.slots[0], &row.left), + &label(&self.slots[1], &row.right), + ) + } +} + +pub(super) fn intro(query: &str) -> String { + clip(&format!("Stand-in results page for {query}"), COLUMNS) +} + +pub(super) fn refusal(reason: StartRefusal) -> &'static str { + match reason { + StartRefusal::NotAMap => { + "Map refused This query does not describe a place or a comparison." + } + StartRefusal::UnsupportedEngine => "Map refused The search engine is unsupported.", + StartRefusal::Invalid => "Map refused The query is invalid or exceeds a limit.", + } +} + +fn failure_text(failure: Failure) -> &'static str { + match failure { + Failure::Cancelled => "cancelled", + Failure::Blocked => "access blocked", + Failure::Challenge => "site requires a challenge", + Failure::Consent => "site requires consent", + Failure::NoResults => "no usable results", + Failure::Unreadable => "page unreadable", + Failure::Unavailable => "page unavailable", + Failure::Timeout => "read timed out", + Failure::Limit => "read limit reached", + Failure::Missing => "page or result missing", + } +} + +fn end_line(outcome: Outcome, elapsed_ms: u32, counts: Counts) -> String { + let outcome = match outcome { + Outcome::Done => "Done".to_owned(), + Outcome::Cancelled => "Cancelled".to_owned(), + Outcome::Failed { failure } => format!("Failed ({})", failure_text(failure)), + }; + let suffix = format!( + " {elapsed_ms}ms reads {} data {:.1} MB renders wanted {}", + counts.fetches, + counts.bytes as f64 / 1_000_000.0, + counts.render_unavailable + ); + format!("{}{suffix}", clip(&outcome, COLUMNS - suffix.len())) +} + +fn table_line(left: &str, right: &str) -> String { + let pad = " ".repeat(TABLE_CELL.saturating_sub(columns(left))); + format!("{left}{pad}{TABLE_DIVIDER}{right}") +} + +fn entries(place: &Place) -> impl Iterator<Item = &Entry> { + place + .sections + .iter() + .flat_map(|section| std::iter::once(section).chain(&section.children)) +} + +fn place_lines(slot: u8, place: &Place) -> Vec<String> { + let heading = format!("Place {} ", u16::from(slot) + 1); + let (title, host) = pair( + &place.title, + &place.host, + COLUMNS - heading.len() - " ()".len(), + ); + let mut lines = vec![format!("{heading}{title} ({host})")]; + for tier in [Tier::Primary, Tier::Secondary] { + let mut sections = place + .sections + .iter() + .filter(|entry| entry.tier == tier) + .peekable(); + if tier == Tier::Secondary && sections.peek().is_some() { + lines.push(" --- Secondary ---".into()); + } + for section in sections { + lines.push(entry_line(section, place.focus.as_deref(), " ")); + for child in &section.children { + lines.push(entry_line(child, place.focus.as_deref(), " ")); + } + } + } + lines +} + +fn entry_line(entry: &Entry, focus: Option<&str>, indent: &str) -> String { + let mark = if Some(entry.id.as_str()) == focus { + "* " + } else { + "" + }; + let off_site = if entry.off_site { " [off-site]" } else { "" }; + let more = if entry.more { " [more]" } else { "" }; + let available = COLUMNS - indent.len() - mark.len() - off_site.len() - more.len() - " ".len(); + let (label, path) = pair(&entry.label, &entry.path, available); + format!("{indent}{mark}{label} {path}{off_site}{more}") +} + +fn pair(left: &str, right: &str, available: usize) -> (String, String) { + let right_min = columns(right).min(available / 2); + let left = clip(left, available - right_min); + let right = clip(right, available - columns(&left)); + (left, right) +} + +fn char_columns(ch: char) -> usize { + if ch.is_ascii() { + 1 + } else { + 2 + } +} + +fn columns(text: &str) -> usize { + text.chars().map(char_columns).sum() +} + +fn clip(text: &str, limit: usize) -> String { + let text: String = zephium_map::clean_text(text) + .chars() + .map(|ch| { + if ch.is_control() || ch.is_whitespace() { + ' ' + } else { + ch + } + }) + .collect(); + if columns(&text) <= limit { + return text; + } + let Some(available) = limit.checked_sub(char_columns(ELLIPSIS)) else { + return String::new(); + }; + let mut used = 0; + let mut out: String = text + .chars() + .take_while(|ch| { + used += char_columns(*ch); + used <= available + }) + .collect(); + out.push(ELLIPSIS); + out +} + +#[cfg(test)] +mod tests; diff --git a/xtask/src/map_try/printer/tests.rs b/xtask/src/map_try/printer/tests.rs new file mode 100644 index 000000000..4a72e080d --- /dev/null +++ b/xtask/src/map_try/printer/tests.rs @@ -0,0 +1,281 @@ +use super::*; +use zephium_map_driver::wire::{Confidence, Network, Official}; + +fn entry(id: &str, label: &str, path: &str) -> Entry { + Entry { + id: id.into(), + tier: Tier::Primary, + label: label.into(), + role: None, + group: None, + off_site: false, + path: path.into(), + read: None, + children: Vec::new(), + more: false, + } +} + +fn place(title: &str, host: &str, sections: Vec<Entry>) -> Place { + Place { + title: title.into(), + site: host.into(), + host: host.into(), + sections, + focus: None, + social: Vec::new(), + notes: Default::default(), + } +} + +fn changed(slot: u8, place: Place, complete: bool) -> Change { + Change::Place { + seq: 1, + slot, + place, + confidence: Confidence::High, + stale: false, + complete, + } +} + +#[test] +fn place_stream_golden() { + let first = Change::FirstLayer { + seq: 0, + official: Some(Official { + title: "Stripe".into(), + site: "stripe.com".into(), + }), + social: vec![Network::GitHub], + organic: 1, + }; + let mut place = place( + "Stripe", + "stripe.com", + vec![ + Entry { + tier: Tier::Secondary, + ..entry("about", "About", "/about") + }, + Entry { + children: vec![entry("tiers", "Tiers", "/pricing/tiers")], + more: true, + ..entry("pricing", "Pricing", "/pricing") + }, + Entry { + off_site: true, + ..entry("docs", "Docs", "/docs") + }, + ], + ); + place.focus = Some("tiers".into()); + let update = changed(0, place, true); + let end = Change::End { + seq: 2, + outcome: Outcome::Done, + elapsed_ms: 650, + }; + let counts = Counts { + fetches: 2, + bytes: 512, + render_unavailable: 1, + ..Counts::default() + }; + let mut printer = Printer::default(); + assert_eq!( + intro("Stripe Pricing"), + "Stand-in results page for Stripe Pricing" + ); + let mut lines = Vec::new(); + for change in [first, update, end] { + lines.extend(printer.lines(&change, Duration::ZERO, counts)); + } + assert_eq!( + lines.join("\n"), + concat!( + "First layer 1 organic official Stripe (stripe.com) social GitHub\n", + "Place 1 Stripe (stripe.com)\n", + " Pricing /pricing [more]\n", + " * Tiers /pricing/tiers\n", + " Docs /docs [off-site]\n", + " --- Secondary ---\n", + " About /about\n", + "Done 650ms reads 2 data 0.0 MB renders wanted 1" + ) + ); +} + +#[test] +fn comparison_uses_current_labels_for_each_side_including_throttled_updates() { + let mut printer = Printer::default(); + let print = |printer: &mut Printer, change: &Change| { + printer.lines(change, Duration::ZERO, Counts::default()) + }; + let left = changed( + 0, + place( + "Figma", + "figma.com", + vec![entry("price", "Plans", "/pricing")], + ), + false, + ); + let right = changed( + 1, + place( + "Sketch", + "sketch.com", + vec![ + entry("price", "Pricing", "/pricing"), + Entry { + children: vec![entry("help", "Tutorials", "/help/learn")], + ..entry("docs", "Documentation", "/docs") + }, + ], + ), + false, + ); + let updated_left = changed( + 0, + place( + "Figma", + "figma.com", + vec![entry("price", "Plans and Pricing", "/pricing")], + ), + false, + ); + assert!(!print(&mut printer, &left).is_empty()); + assert!(!print(&mut printer, &right).is_empty()); + assert!(print(&mut printer, &updated_left).is_empty()); + let compare = Change::Compare { + seq: 3, + rows: vec![ + Row { + role: None, + label: "Prices".into(), + left: Some("price".into()), + right: Some("price".into()), + }, + Row { + role: None, + label: "Learn".into(), + left: None, + right: Some("help".into()), + }, + ], + }; + assert_eq!( + print(&mut printer, &compare).join("\n"), + concat!( + "Left | Right\n", + "Plans and Pricing | Pricing\n", + "- | Tutorials", + ) + ); +} + +#[test] +fn failed_side_and_refusals_use_plain_words() { + let failed = Change::PlaceFailed { + seq: 2, + slot: 1, + failure: Failure::Challenge, + }; + let mut printer = Printer::default(); + assert_eq!( + printer.lines(&failed, Duration::ZERO, Counts::default()), + ["Place 2 failed site requires a challenge"] + ); + assert_eq!( + refusal(StartRefusal::NotAMap), + "Map refused This query does not describe a place or a comparison." + ); + assert_eq!( + refusal(StartRefusal::Invalid), + "Map refused The query is invalid or exceeds a limit." + ); + assert_eq!( + refusal(StartRefusal::UnsupportedEngine), + "Map refused The search engine is unsupported." + ); + let end = Change::End { + seq: 3, + outcome: Outcome::Cancelled, + elapsed_ms: 4, + }; + assert_eq!( + printer.lines(&end, Duration::ZERO, Counts::default()), + ["Cancelled 4ms reads 0 data 0.0 MB renders wanted 0"] + ); +} + +#[test] +fn throttles_partial_places_at_the_interval_and_prints_complete_immediately() { + let mut printer = Printer::default(); + let place = place("Figma", "figma.com", Vec::new()); + let partial = changed(0, place.clone(), false); + let complete = changed(0, place, true); + let print = |printer: &mut Printer, change: &Change, time| { + printer.lines(change, time, Counts::default()) + }; + assert!(!print(&mut printer, &partial, Duration::ZERO).is_empty()); + assert!(print(&mut printer, &partial, PLACE_INTERVAL).is_empty()); + let just_past = PLACE_INTERVAL + Duration::from_nanos(1); + assert!(!print(&mut printer, &partial, just_past).is_empty()); + assert!(!print(&mut printer, &complete, just_past).is_empty()); +} + +#[test] +fn clips_to_the_column_limit_and_removes_terminal_controls() { + assert_eq!(clip(&"a".repeat(COLUMNS), COLUMNS), "a".repeat(COLUMNS)); + assert_eq!( + clip(&"a".repeat(COLUMNS + 1), COLUMNS), + format!("{}…", "a".repeat(COLUMNS - 2)) + ); + assert_eq!(clip("Test\x1b[2J\u{202e}\n界", COLUMNS), "Test [2J 界"); + let long = "界".repeat(COLUMNS); + let place = place( + &long, + "figma.com", + vec![Entry { + off_site: true, + more: true, + ..entry("long", &long, &format!("/{long}")) + }], + ); + let lines = place_lines(0, &place); + assert!(lines.iter().all(|line| columns(line) <= COLUMNS)); + assert!(lines[0].ends_with("… (figma.com)")); + assert!(lines[1].ends_with("… [off-site] [more]")); + let mut printer = Printer::default(); + for slot in [0, 1] { + printer.lines( + &changed(slot, place.clone(), true), + Duration::ZERO, + Counts::default(), + ); + } + let line = printer.row(&Row { + role: None, + label: "Long".into(), + left: Some("long".into()), + right: Some("long".into()), + }); + assert!(columns(&line) <= COLUMNS); + assert_eq!(line.matches(ELLIPSIS).count(), 2); + let end = end_line( + Outcome::Failed { + failure: Failure::Challenge, + }, + u32::MAX, + Counts { + fetches: u32::MAX, + bytes: u64::MAX, + render_unavailable: u32::MAX, + ..Counts::default() + }, + ); + assert!(columns(&end) <= COLUMNS); + assert!(end.ends_with("renders wanted 4294967295")); +} diff --git a/xtask/src/map_try/tests.rs b/xtask/src/map_try/tests.rs new file mode 100644 index 000000000..bd4327e7d --- /dev/null +++ b/xtask/src/map_try/tests.rs @@ -0,0 +1,293 @@ +use super::*; +use zephium_map::{read_results, Doc, DocLimits, ResultsRead}; + +fn args(values: &[&str]) -> Vec<String> { + values.iter().map(|value| (*value).to_owned()).collect() +} + +#[test] +fn accepts_one_or_two_public_sites_in_order_and_passes_private_through() { + let arguments = args(&["Stripe Pricing", "--site", "Stripe.COM.", "--private"]); + let (request, _) = Options::parse(&arguments).unwrap().prepare().unwrap(); + assert_eq!(request.query, "Stripe Pricing"); + assert!(request.private); + let arguments = args(&[ + "Figma vs Sketch", + "--site", + "figma.com", + "--site", + "sketch.com", + ]); + let options = Options::parse(&arguments).unwrap(); + assert_eq!(options.sites[0].as_str(), "https://figma.com/"); + assert_eq!(options.sites[1].as_str(), "https://sketch.com/"); + assert!(!options.prepare().unwrap().0.private); + assert_eq!( + site_url("bücher.de").unwrap().host_str(), + Some("xn--bcher-kva.de") + ); + assert_eq!(site_url("stripe.com.").unwrap().path(), "/"); +} + +#[test] +fn refuses_malformed_options_and_arity() { + for (raw, error) in [ + (&[][..], Error::MissingQuery), + (&["--site", "stripe.com"], Error::MissingQuery), + (&["Stripe"], Error::MissingSite), + (&["Stripe", "--site"], Error::MissingSite), + (&["Stripe", "--site", "--private"], Error::MissingSite), + ( + &["Stripe", "--site", "stripe.com", "--help"], + Error::UnexpectedOption, + ), + ( + &["Stripe", "--site", "stripe.com", "--private", "--private"], + Error::UnexpectedOption, + ), + ( + &["Figma", "vs", "Sketch", "--site", "figma.com"], + Error::UnexpectedOption, + ), + ( + &["Stripe", "--site", "stripe.com", "--site", "figma.com"], + Error::PlaceArity, + ), + ( + &["Figma vs Sketch", "--site", "figma.com"], + Error::CompareArity, + ), + ( + &[ + "A vs B", + "--site", + "stripe.com", + "--site", + "figma.com", + "--site", + "sketch.com", + ], + Error::TooManySites, + ), + ( + &["2 + 2", "--site", "stripe.com"], + Error::Refused(StartRefusal::NotAMap), + ), + ( + &["", "--site", "stripe.com"], + Error::Refused(StartRefusal::Invalid), + ), + ] { + let arguments = args(raw); + assert_eq!( + Options::parse(&arguments).and_then(Options::prepare).err(), + Some(error), + "{raw:?}" + ); + } +} + +#[test] +fn rejects_each_non_public_or_non_bare_host_shape() { + for host in [ + "", + "https://stripe.com", + "stripe.com/", + "stripe.com/pricing", + "stripe.com:443", + "stripe.com:8443", + "user@stripe.com", + "user:password@stripe.com", + "stripe.com?x", + "stripe.com#here", + "stripe.com\\", + " stripe.com", + "stripe.com\n", + "stri\tpe.com", + "127.0.0.1", + "8.8.8.8", + "0x08080808", + "[2001:4860:4860::8888]", + "localhost", + "test.localhost", + "test.local", + "test.internal", + "stripe", + "stripe.invalid", + "test.onion", + "test.arpa", + "test.alt", + "com", + "co.uk", + "stripe%2ecom", + "stripe..com", + "stripe.com..", + "-stripe.com", + "stripe-.com", + "stripe_.com", + ] { + let arguments = args(&["Stripe", "--site", host]); + assert_eq!( + Options::parse(&arguments).err(), + Some(Error::BadHost), + "{host:?}" + ); + } + + let max_label = "a".repeat(MAX_DNS_LABEL_BYTES); + assert!(site_url(&format!("{max_label}.com")).is_some()); + assert!(site_url(&format!("{max_label}a.com")).is_none()); + let max_host = format!("{max_label}.{max_label}.{max_label}.{}.com", "a".repeat(57)); + assert_eq!(max_host.len(), MAX_HOST_BYTES); + assert!(site_url(&max_host).is_some()); + assert!(site_url(&format!("a{max_host}")).is_none()); +} + +#[test] +fn query_refusal_uses_the_engines_byte_and_term_limits() { + use zephium_map::query::{MAX_QUERY_BYTES, MAX_QUERY_TERMS}; + for query in [ + "a".repeat(MAX_QUERY_BYTES + 1), + "a ".repeat(MAX_QUERY_TERMS + 1), + ] { + let arguments = args(&[&query, "--site", "stripe.com"]); + assert_eq!( + Options::parse(&arguments).unwrap().prepare().err(), + Some(Error::Refused(StartRefusal::Invalid)) + ); + } +} + +#[tokio::test] +async fn the_engine_reads_one_and_two_stand_in_results_in_order() { + for (values, expected) in [ + ( + &["Stripe Pricing", "--site", "stripe.com"][..], + &[("Stripe", "https://stripe.com/")][..], + ), + ( + &[ + "Figma vs Sketch", + "--site", + "figma.com", + "--site", + "sketch.com", + ][..], + &[ + ("Figma", "https://figma.com/"), + ("Sketch", "https://sketch.com/"), + ][..], + ), + ] { + let arguments = args(values); + let (request, stand_in) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let url = request + .engine + .configured_search(&request.query, "") + .unwrap(); + let page = stand_in.load(url).await.unwrap(); + let doc = + Doc::from_html(&page.url, page.html.as_bytes(), None, DocLimits::RESULTS).unwrap(); + let query = read_query(&request.query).unwrap(); + let ResultsRead::FirstLayer { layer } = read_results(request.engine, None, &query, &doc) + else { + panic!("the stand-in must parse as results"); + }; + assert!(layer.social.is_empty()); + let actual = layer + .organic + .iter() + .map(|hit| { + assert!(hit.snippet.is_none()); + assert!(hit.sitelinks.is_empty()); + (hit.title.as_str(), hit.url.as_str()) + }) + .collect::<Vec<_>>(); + assert_eq!(actual, expected); + } +} + +#[test] +fn injected_non_direct_route_exits_before_creating_any_io() { + for route in [PublicRoute::Proxied, PublicRoute::Unsupported] { + assert_eq!( + on_direct_route::<()>(route, || panic!("I/O started")), + Err(Error::Proxy) + ); + } + assert_eq!(on_direct_route(PublicRoute::Direct, || Ok(7)), Ok(7)); + assert_eq!( + Error::Proxy.to_string(), + "The reader refuses to go around a proxy. A direct route is required." + ); +} + +#[tokio::test] +async fn an_interrupt_cancels_the_driver_and_prints_its_end() { + struct NoFetch; + impl Fetcher for NoFetch { + fn fetch(&self, _: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + panic!("the cancelled driver must not start a fetch"); + } + } + + let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); + let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(NoFetch), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::ready(Ok(())), + &mut output, + ) + .await; + assert_eq!(outcome, Ok(Outcome::Cancelled)); + assert_eq!(driver.counts(), Counts::default()); + let printed = std::str::from_utf8(&output).unwrap(); + assert_eq!(printed.lines().count(), 1); + assert!(printed.starts_with("Cancelled ")); + assert!(printed.ends_with("ms reads 0 data 0.0 MB renders wanted 0\n")); +} + +#[tokio::test] +async fn a_closed_route_watch_is_not_a_proxy() { + struct Refuse; + impl Fetcher for Refuse { + fn fetch(&self, _: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async { Err(Failure::Unavailable) }) + } + } + + let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); + let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Refuse), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (route, direct) = watch::channel(PublicRoute::Direct); + drop(route); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + ) + .await; + assert!(outcome.is_ok(), "{outcome:?}"); + let printed = std::str::from_utf8(&output).unwrap(); + assert!(printed.lines().count() > 1, "{printed}"); +} From 01277af20533e5ed7b903f1af1d45825a53bda46 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 23:47:13 +0100 Subject: [PATCH 32/40] fix(map): exclusion marks survive restructuring, remedies stay in their issue, task nouns and breadcrumbs read right --- crates/zephium-map/src/doc/html.rs | 69 +++++++++++++--------- crates/zephium-map/src/doc/html/arena.rs | 23 ++++---- crates/zephium-map/src/doc/html/tests.rs | 63 ++++++++++++++++++++ crates/zephium-map/src/passage.rs | 69 ++++++++++++++-------- crates/zephium-map/src/passage/question.rs | 38 ++++++++---- crates/zephium-map/src/results.rs | 15 ++++- crates/zephium-map/tests/passage.rs | 38 +++++++++--- 7 files changed, 228 insertions(+), 87 deletions(-) diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index 7162dcb04..802b22002 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -79,6 +79,10 @@ fn hidden(n: &NodeRef) -> bool { .is_some_and(|v| v.eq_ignore_ascii_case("hidden")) } +fn excluded(marks: Marks) -> bool { + marks.has(Marks::GENERATED) || marks.has(Marks::SPONSORED) +} + impl DocBuilder { fn resolve(&mut self, node: &NodeRef, attr: &str, base: &Url) -> Option<Url> { let raw = node.attr(attr)?; @@ -296,10 +300,8 @@ impl DocBuilder { ); inline |= self.doc.nodes[at].role == Role::Text; prose |= takes_prose; - if self.doc.nodes[at].marks.has(Marks::ANCILLARY) - || self.doc.nodes[at].marks.has(Marks::GENERATED) - || self.doc.nodes[at].marks.has(Marks::SPONSORED) - { + let marks = self.doc.nodes[at].marks; + if marks.has(Marks::ANCILLARY) || excluded(marks) { break; } } @@ -344,7 +346,7 @@ impl DocBuilder { } fn walk(&mut self, body: NodeRef<'_>, base: &Url) -> Result<(), DocError> { - let mut pending = vec![Some((body, None, 0, false))]; + let mut pending = vec![Some((body, None::<usize>, 0, false))]; while let Some(step) = pending.pop() { let Some((n, parent, level, verbatim)) = step else { self.gap = true; @@ -354,7 +356,11 @@ impl DocBuilder { pending.push(Some((next, parent, level, verbatim))); } if n.is_text() { - self.capture_text(parent, n.text(), verbatim, level)?; + if !excluded(n.lifted_marks()) + || parent.is_some_and(|at| excluded(self.doc.nodes[at].marks)) + { + self.capture_text(parent, n.text(), verbatim, level)?; + } continue; } let formatting = FORMATTING_TAGS.contains(&n.tag()); @@ -382,7 +388,9 @@ impl DocBuilder { { continue; } - if verbatim && tag_is(&n, "br") { + let mut node_marks = marks(&n); + node_marks.insert(n.lifted_marks()); + if verbatim && tag_is(&n, "br") && !excluded(node_marks) { self.capture_text(parent, "\n", true, level)?; } if n.loss() { @@ -433,31 +441,17 @@ impl DocBuilder { } else if tag_is(&n, "code") && in_sink && !verbatim { Some(Role::Text) } else { - classify(&n, n.tag(), in_sink) - .filter(|r| !(verbatim && *r == Role::CodeBlock)) - .or_else(|| n.generated_by_lift().then_some(Role::Group)) + match classify(&n, n.tag(), in_sink) { + Some(Role::CodeBlock) if verbatim => excluded(node_marks).then_some(Role::Text), + role => role.or_else(|| excluded(node_marks).then_some(Role::Group)), + } }; let (parent, level) = if let Some(role) = role { - let excluded = self.lift_exclusions(parent, level); + let lifted = self.lift_exclusions(parent, level); let (parent, level) = self.fit_parent(parent, level); let mut node = Node::new(role, parent.map(|i| i as u32)); - node.marks.insert(excluded); - if n.generated_by_lift() { - node.marks.insert(Marks::GENERATED); - } - if ["data-layout", "data-type", "data-testid"] - .iter() - .any(|attr| n.attr(attr).is_some_and(|v| v.eq_ignore_ascii_case("ad"))) - || n.attr("rel").is_some_and(|v| { - v.split_ascii_whitespace() - .any(|w| w.eq_ignore_ascii_case("sponsored")) - }) - || n.attr("class") - .is_some_and(|v| v.split_ascii_whitespace().any(|w| w == "b_ad")) - { - node.marks.insert(Marks::SPONSORED); - } - node.marks.insert(marks(&n)); + node.marks = node_marks; + node.marks.insert(lifted); if tag_is(&n, "p") { node.marks.insert(Marks::PROSE); } @@ -492,7 +486,12 @@ impl DocBuilder { if role == Role::CodeBlock { let class = n.attr("class").into_iter().chain( n.children() - .filter(|c| tag_is(c, "code")) + .filter(|c| { + tag_is(c, "code") + && !hidden(c) + && !excluded(marks(c)) + && !excluded(c.lifted_marks()) + }) .filter_map(|c| c.attr("class")), ); let language = class @@ -530,6 +529,18 @@ impl DocBuilder { fn marks(n: &NodeRef) -> Marks { let mut marks = Marks::default(); + if ["data-layout", "data-type", "data-testid"] + .iter() + .any(|attr| n.attr(attr).is_some_and(|v| v.eq_ignore_ascii_case("ad"))) + || n.attr("rel").is_some_and(|v| { + v.split_ascii_whitespace() + .any(|w| w.eq_ignore_ascii_case("sponsored")) + }) + || n.attr("class") + .is_some_and(|v| v.split_ascii_whitespace().any(|w| w == "b_ad")) + { + marks.insert(Marks::SPONSORED); + } for attr in [ "itemprop", "itemtype", diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index f5d6cff3b..fc186e2ff 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -1,4 +1,4 @@ -use super::DocLimits; +use super::{DocLimits, Marks}; use html5ever::{local_name, ns, tendril::StrTendril, Attribute, LocalName}; // Zero is both the document handle and the null link. The document is never a child. @@ -11,7 +11,6 @@ const LOSS: u8 = 8; const JSON: u8 = 16; const HIDDEN_BY_LIFT: u8 = 32; const ATTACHED: u8 = 64; -const GENERATED_BY_LIFT: u8 = 128; const ATTRIBUTE_NAMES: &[&str] = &[ "href", "src", @@ -54,6 +53,7 @@ struct Record { data: u32, depth: u8, flags: u8, + lifted_marks: Marks, } struct Attr { @@ -147,8 +147,8 @@ impl<'a> NodeRef<'a> { pub(super) fn hidden_by_lift(self) -> bool { self.record().flags & HIDDEN_BY_LIFT != 0 } - pub(super) fn generated_by_lift(self) -> bool { - self.record().flags & GENERATED_BY_LIFT != 0 + pub(super) fn lifted_marks(self) -> Marks { + self.record().lifted_marks } pub(super) fn sibling(self) -> Option<Self> { let next = self.record().next; @@ -357,14 +357,19 @@ impl Arena { let p = &self.records[parent as usize]; let no_text = p.flags & (OPAQUE | NO_TEXT) != 0; let mut hidden = p.flags & HIDDEN_BY_LIFT != 0; - let mut generated = p.flags & GENERATED_BY_LIFT != 0; + let mut lifted_marks = p.lifted_marks; if usize::from(p.depth) >= self.limits.arena_depth as usize && self.records[id as usize].flags & TEXT == 0 { self.lifted = true; let lifted = self.node(parent); hidden |= super::hidden(&lifted) || no_text; - generated |= super::marks(&lifted).has(super::Marks::GENERATED); + let marks = super::marks(&lifted); + for mark in [Marks::GENERATED, Marks::SPONSORED] { + if marks.has(mark) { + lifted_marks.insert(mark); + } + } parent = p.parent; before = 0; } @@ -404,10 +409,8 @@ impl Arena { n.prev = prev; n.next = before; n.depth = depth; - n.flags = (n.flags & !(NO_TEXT | HIDDEN_BY_LIFT | GENERATED_BY_LIFT)) | ATTACHED; - if generated { - n.flags |= GENERATED_BY_LIFT; - } + n.flags = (n.flags & !(NO_TEXT | HIDDEN_BY_LIFT)) | ATTACHED; + n.lifted_marks.insert(lifted_marks); if no_text { n.flags |= NO_TEXT } diff --git a/crates/zephium-map/src/doc/html/tests.rs b/crates/zephium-map/src/doc/html/tests.rs index d676f45c1..e233691f8 100644 --- a/crates/zephium-map/src/doc/html/tests.rs +++ b/crates/zephium-map/src/doc/html/tests.rs @@ -451,6 +451,40 @@ fn html_meta_utf16_labels_describe_utf8() { assert!(doc.nodes().iter().any(|n| n.text == "café")); } +#[test] +fn nested_code_preserves_exclusions_without_changing_ordinary_code() { + let doc = document( + b"<main><pre><code aria-label='AI overview'>Generated answer</code><code rel='sponsored'>Paid answer</code><code> run()\n</code></pre><a href='/docs'>Docs<code class='sponsored'>Paid label</code></a></main>", + DocLimits::default(), + ); + let visible: Vec<_> = doc + .nodes() + .iter() + .enumerate() + .filter(|(at, _)| crate::visible(doc.nodes(), *at)) + .map(|(_, node)| node) + .collect(); + assert_eq!( + visible + .iter() + .find(|node| node.role == Role::CodeBlock) + .unwrap() + .text, + " run()\n" + ); + assert_eq!( + visible + .iter() + .find(|node| node.role == Role::Link) + .unwrap() + .text, + "Docs" + ); + assert!(visible + .iter() + .all(|node| { !node.text.contains("Generated") && !node.text.contains("Paid") })); +} + #[test] fn arena_and_document_lifts_preserve_generated_exclusion() { let html = b"<main><div aria-label='AI overview'><p>Generated answer</p></div><div><p>Ordinary answer</p></div></main>"; @@ -476,6 +510,35 @@ fn arena_and_document_lifts_preserve_generated_exclusion() { } } +#[test] +fn arena_and_document_lifts_preserve_sponsored_exclusion() { + let html = b"<main><div class='sponsored'><p>Paid answer</p><a href='/paid'>Paid child</a></div><div><p>Ordinary answer</p></div></main>"; + for limits in [ + DocLimits { + arena_depth: 4, + ..DocLimits::default() + }, + DocLimits { + depth: 3, + ..DocLimits::default() + }, + ] { + let doc = document(html, limits); + for (text, visible) in [ + ("Paid answer", false), + ("Paid child", false), + ("Ordinary answer", true), + ] { + let at = doc + .nodes() + .iter() + .position(|node| node.text == text) + .unwrap(); + assert_eq!(crate::visible(doc.nodes(), at), visible, "{text}"); + } + } +} + #[test] fn linked_answers_match_clean_text_but_never_empty_structural_nodes() { let doc = document( diff --git a/crates/zephium-map/src/passage.rs b/crates/zephium-map/src/passage.rs index 5380b595b..1f4d75668 100644 --- a/crates/zephium-map/src/passage.rs +++ b/crates/zephium-map/src/passage.rs @@ -62,6 +62,7 @@ struct Block<'a> { text: Cow<'a, str>, node: usize, heading: Option<usize>, + heading_end: usize, scope: Option<usize>, accepted: bool, suggested: bool, @@ -155,6 +156,7 @@ fn blocks<'a>(page: usize, doc: &'a Doc, terms: &BTreeMap<String, usize>) -> Vec .fold(0u64, |mask, i| mask | (1 << i)) }; let mut headings = BTreeMap::<_, Vec<(u8, usize, u64)>>::new(); + let mut heading_ends = vec![nodes.len(); nodes.len()]; let mut definitions = BTreeMap::<_, (String, bool)>::new(); let mut headers = BTreeMap::<_, (String, usize)>::new(); let mut out = Vec::new(); @@ -181,7 +183,11 @@ fn blocks<'a>(page: usize, doc: &'a Doc, terms: &BTreeMap<String, usize>) -> Vec let path = headings.entry(scope).or_default(); if let Role::Heading { level } = n.role { let level = level.unwrap_or(1); - path.retain(|(prior, _, _)| *prior < level); + while path.last().is_some_and(|(prior, _, _)| *prior >= level) { + if let Some((_, closed, _)) = path.pop() { + heading_ends[closed] = i; + } + } path.push((level, i, relevant(&n.text))); continue; } @@ -338,10 +344,16 @@ fn blocks<'a>(page: usize, doc: &'a Doc, terms: &BTreeMap<String, usize>) -> Vec text, scope, heading: heading.map(|(i, _)| i), + heading_end: 0, accepted: ancestors(nodes, i).any(|a| nodes[a].marks.has(Marks::ACCEPTED)), suggested: ancestors(nodes, i).any(|a| nodes[a].marks.has(Marks::SUGGESTED)), }); } + for block in &mut out { + if let Some(heading) = block.heading { + block.heading_end = heading_ends[heading]; + } + } out } @@ -502,6 +514,8 @@ pub fn read_passages(q: &QueryRead, docs: &[&Doc]) -> Vec<Passage> { continue; } scores[i] = scores[i].max(1 + terms.len()); + let nodes = docs[b.doc].nodes(); + let issue_parent = b.heading.and_then(|h| nodes[h].parent_index()); for (distance, next) in blocks[i + 1..] .iter() .take(ERROR_FOLLOWING_BLOCKS) @@ -510,15 +524,17 @@ pub fn read_passages(q: &QueryRead, docs: &[&Doc]) -> Vec<Passage> { if next.doc != b.doc { break; } - let remedy = next.heading.is_some_and(|h| { - tokens(&docs[next.doc].nodes()[h].text).any(|s| { - matches!(s.as_str(), "fix" | "solution" | "resolution" | "answer") - }) + let nested_remedy = next.heading.is_some_and(|h| { + (b.node..b.heading_end).contains(&h) + && issue_parent.is_none_or(|p| ancestors(nodes, h).any(|a| a == p)) + && tokens(&nodes[h].text).any(|s| { + matches!(s.as_str(), "fix" | "solution" | "resolution" | "answer") + }) }); - if next.scope != b.scope || !remedy && next.heading != b.heading { + if next.scope != b.scope || !nested_remedy && next.heading != b.heading { break; } - if next.accepted || docs[next.doc].nodes()[next.node].role == Role::CodeBlock { + if next.accepted || nodes[next.node].role == Role::CodeBlock { scores[i + distance + 1] = scores[i + distance + 1] .max(terms.len() + ERROR_FOLLOWING_BLOCKS + 1 - distance); break; @@ -684,10 +700,9 @@ pub fn read_passages(q: &QueryRead, docs: &[&Doc]) -> Vec<Passage> { pub(crate) fn featured(q: &QueryRead, f: &Featured, result: &Organic) -> Option<Passage> { let terms = query_terms(q); let present: BTreeSet<_> = tokens(&f.text).collect(); - let title = tokens(&result.title).collect(); if terms.is_empty() || !terms.is_subset(&present) - || !question::TaskQualifiers::new(q.terms(), &title).permits(&f.text) + || !question::TaskQualifiers::new(q.terms(), &result.url).permits(&f.text) { return None; } @@ -707,7 +722,6 @@ pub(crate) fn featured(q: &QueryRead, f: &Featured, result: &Organic) -> Option< #[cfg(test)] #[test] fn featured_excerpts_obey_the_same_task_qualifiers_as_articles() { - let q = crate::read_query("loom remove all spools").unwrap(); let url = url::Url::parse("https://example.com/guide").unwrap(); let key = crate::PageKey::from_url(&url).unwrap(); let result = Organic { @@ -720,21 +734,24 @@ fn featured_excerpts_obey_the_same_task_qualifiers_as_articles() { discussion: false, sitelinks: Vec::new(), }; - for (text, accepted) in [ - ("Loom can remove all spools without thread.", false), - ("In Loom, remove all spools before restarting.", true), - ] { - assert_eq!( - featured( - &q, - &Featured { - text: text.into(), - cites: key.clone() - }, - &result - ) - .is_some(), - accepted - ); + for query in ["loom remove all spools", "how to remove all spools?"] { + let q = crate::read_query(query).unwrap(); + for (text, accepted) in [ + ("Loom can remove all spools without thread.", false), + ("In Loom, remove all spools before restarting.", true), + ] { + assert_eq!( + featured( + &q, + &Featured { + text: text.into(), + cites: key.clone() + }, + &result + ) + .is_some(), + accepted + ); + } } } diff --git a/crates/zephium-map/src/passage/question.rs b/crates/zephium-map/src/passage/question.rs index a8b585460..2e9542b3f 100644 --- a/crates/zephium-map/src/passage/question.rs +++ b/crates/zephium-map/src/passage/question.rs @@ -160,7 +160,7 @@ impl Question { context, all: u64::MAX >> (MAX_CONTENT_TERMS - count), task: terms.first().is_some_and(|t| t == "how") || terms.iter().any(|t| action(t)), - qualifiers: TaskQualifiers::new(terms, &title), + qualifiers: TaskQualifiers::new(terms, doc.page()), } } @@ -265,21 +265,33 @@ impl Question { } impl TaskQualifiers { - pub(super) fn new(terms: &[String], title: &BTreeSet<String>) -> Self { + pub(super) fn new(terms: &[String], source: &url::Url) -> Self { + let site = crate::SiteKey::from_url(source); + let entity = site + .as_ref() + .and_then(|site| site.as_str().split_once('.')) + .and_then(|(label, _)| tokens(label).next()); Self { last: terms.iter().position(|t| t == "last").and_then(|at| { - let tail = terms.get(at + 1..)?; - let noun = if tail.len() > 1 && title.contains(&tail[0]) { - &tail[1] - } else { - tail.first()? - }; - Some(noun.trim_end_matches('?').to_owned()) + let mut tail = terms[at + 1..].iter(); + let first = tokens(tail.next()?).next()?; + let qualifier = entity.as_ref() == Some(&first); + Some( + qualifier + .then(|| { + tail.next() + .and_then(|term| tokens(term).next()) + .filter(|noun| !STOP.contains(&noun.as_str())) + }) + .flatten() + .unwrap_or(first), + ) + }), + quantity: terms.windows(2).find(|pair| pair[0] == "all").map(|pair| { + let noun = pair[1].trim_matches(|c: char| !c.is_alphanumeric() && c != '_'); + let noun = if noun.is_empty() { &pair[1] } else { noun }; + format!("all {noun}") }), - quantity: terms - .windows(2) - .find(|pair| pair[0] == "all") - .map(|pair| pair.join(" ")), } } diff --git a/crates/zephium-map/src/results.rs b/crates/zephium-map/src/results.rs index 70d044ce8..dff1d083e 100644 --- a/crates/zephium-map/src/results.rs +++ b/crates/zephium-map/src/results.rs @@ -198,13 +198,15 @@ fn past_site(text: &str, url: &Url) -> Option<String> { fn past_address(text: &str) -> Option<String> { let words: Vec<&str> = text.split(' ').collect(); + let prefix = &words[..words.len().min(ADDRESS_WORDS)]; + let last_crumb = prefix.iter().rposition(|word| *word == "›"); let mut end = None; let mut crumb = false; - for (at, word) in words.iter().enumerate().take(ADDRESS_WORDS) { + for (at, word) in prefix.iter().enumerate() { if address_like(word) || *word == "›" || crumb { end = Some(at + 1); crumb = *word == "›"; - } else if end.is_some() { + } else if end.is_some() && last_crumb.is_none_or(|last| at > last) { break; } } @@ -862,3 +864,12 @@ fn address_prefix_does_not_consume_address_like_title_words() { Some("New Node.js Guide") ); } + +#[cfg(test)] +#[test] +fn address_prefix_consumes_multiword_breadcrumb_segments() { + assert_eq!( + past_address("example.net › getting started › install Install Guide").as_deref(), + Some("Install Guide") + ); +} diff --git a/crates/zephium-map/tests/passage.rs b/crates/zephium-map/tests/passage.rs index fb499e40b..c2b23418c 100644 --- a/crates/zephium-map/tests/passage.rs +++ b/crates/zephium-map/tests/passage.rs @@ -182,7 +182,7 @@ fn answer_marks_language_and_term_boundaries() { #[test] fn an_adjacent_solution_heading_can_scope_the_fix() { - let d=doc("a","<main><h2>Problem</h2><pre>TypeError: invalid bucket</pre><h2>Solution</h2><pre>bucket.reset()</pre></main>"); + let d=doc("a","<main><h2>Problem</h2><pre>TypeError: invalid bucket</pre><h3>Solution</h3><pre>bucket.reset()</pre></main>"); let q = read_query( "Traceback (most recent call last):\n /tmp/project.py:14\nTypeError: invalid bucket", ) @@ -533,8 +533,15 @@ fn textual_list_values_keep_inline_content_and_the_subject_heading() { #[test] fn accepted_answers_do_not_cross_unrelated_issue_headings() { - let page = doc("issues", "<main><h2>Bucket failure</h2><pre>TypeError: invalid bucket</pre><h2>Printer setup</h2><div itemprop='acceptedAnswer'><pre>printer.reset()</pre></div></main>"); let query = read_query("TypeError: invalid bucket").unwrap(); + for heading in ["Printer setup", "Printer solution"] { + let page = doc("issues", &format!("<main><h2>Bucket failure</h2><pre>TypeError: invalid bucket</pre><h2>{heading}</h2><div itemprop='acceptedAnswer'><pre>printer.reset()</pre></div></main>")); + assert_eq!( + read_passages(&query, &[&page])[0].text, + "TypeError: invalid bucket" + ); + } + let page = doc("issues", "<main><div><h2>Bucket failure</h2><pre>TypeError: invalid bucket</pre></div><div><h3>Printer solution</h3><pre>printer.reset()</pre></div></main>"); assert_eq!( read_passages(&query, &[&page])[0].text, "TypeError: invalid bucket" @@ -542,18 +549,35 @@ fn accepted_answers_do_not_cross_unrelated_issue_headings() { } #[test] -fn timing_clause_can_follow_an_unrestricted_task_quantity() { +fn a_last_task_noun_may_appear_in_the_title() { let page = doc( "guide", - "<title>Loom guide</title><p>Remove all spools before restarting.</p>", + "<title>Undo a commit in Git</title><p>To undo the last commit, use git revert.</p>", ); - let q = read_query("loom remove all spools").unwrap(); + let query = read_query("how to undo last commit in git").unwrap(); assert_eq!( - read_passages(&q, &[&page])[0].text, - "Remove all spools before restarting." + read_passages(&query, &[&page]) + .first() + .map(|p| p.text.as_str()), + Some("To undo the last commit, use git revert.") ); } +#[test] +fn timing_clause_can_follow_an_unrestricted_task_quantity() { + let page = doc( + "guide", + "<title>Loom guide</title><p>Remove all spools before restarting.</p>", + ); + for text in ["loom remove all spools", "how to remove all spools?"] { + let q = read_query(text).unwrap(); + assert_eq!( + read_passages(&q, &[&page]).first().map(|p| p.text.as_str()), + Some("Remove all spools before restarting.") + ); + } +} + #[test] fn comparison_skips_an_alias_to_find_a_distinct_second_source() { let a = doc( From ed394c9b9dc1b305d29a8c30ac8db5cfc8b65647 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 23:47:13 +0100 Subject: [PATCH 33/40] fix(xtask): probe checks robots where a redirect lands, resume keeps outcome and measurement paired --- xtask/src/map_bench/corpus.rs | 31 +++- xtask/src/map_bench/engine.rs | 14 +- xtask/src/map_bench/probe.rs | 197 ++++++++++++++++++----- xtask/src/map_bench/report.rs | 23 ++- xtask/src/map_bench/run.rs | 106 ++++++++---- xtask/src/map_bench/run/tests.rs | 45 ++++++ xtask/src/map_bench/run/tests/session.rs | 58 ++++++- xtask/src/map_bench/session.rs | 7 +- xtask/src/map_bench/store.rs | 16 ++ 9 files changed, 413 insertions(+), 84 deletions(-) diff --git a/xtask/src/map_bench/corpus.rs b/xtask/src/map_bench/corpus.rs index 7278e4776..c7c5a95a1 100644 --- a/xtask/src/map_bench/corpus.rs +++ b/xtask/src/map_bench/corpus.rs @@ -383,7 +383,19 @@ pub(super) fn fixture(text: &str) -> CorpusQuery { #[cfg(test)] pub(super) fn load_external_fixture(paths: &[PathBuf]) -> Result<Option<Corpus>> { - if paths.iter().any(|path| path.exists()) { + let mut present = false; + for path in paths { + if super::store::exists(path)? { + present = true; + } else { + for parent in path.ancestors().skip(1) { + if super::store::directory(parent, false)? { + break; + } + } + } + } + if present { Corpus::load(paths).map(Some) } else { Ok(None) @@ -397,6 +409,23 @@ mod tests { const PLACE: &str = "[[query]]\nid='test'\ntext='private search'\nkind='place'\nsite='example.com'\n"; + #[test] + fn external_fixture_only_skips_missing_paths() { + let temp = tempfile::tempdir().unwrap(); + let missing = temp.path().join("missing.toml"); + assert!(load_external_fixture(std::slice::from_ref(&missing)) + .unwrap() + .is_none()); + + let file = temp.path().join("file.toml"); + std::fs::write(&file, PLACE).unwrap(); + assert!(load_external_fixture(std::slice::from_ref(&file)) + .unwrap() + .is_some()); + assert!(load_external_fixture(&[file.clone(), missing.clone()]).is_err()); + assert!(load_external_fixture(&[missing, file.join("corpus.toml")]).is_err()); + } + #[test] fn actual_corpora_when_available() { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) diff --git a/xtask/src/map_bench/engine.rs b/xtask/src/map_bench/engine.rs index 7a127bc8b..1160c3d8c 100644 --- a/xtask/src/map_bench/engine.rs +++ b/xtask/src/map_bench/engine.rs @@ -30,7 +30,14 @@ pub(super) trait Engine { } pub(super) trait BenchIo { - fn fetch(&mut self, request: FetchRequest) -> FetchResult; + fn fetch(&mut self, request: FetchRequest) -> FetchResult { + self.fetch_checked(request, &mut |_, _| true) + } + fn fetch_checked( + &mut self, + request: FetchRequest, + admit: &mut LandingAdmission<'_>, + ) -> FetchResult; fn start_fetch(&mut self, request: FetchRequest) -> usize; fn next_fetch(&mut self) -> Option<(usize, FetchResult)>; fn results_page(&mut self, synthetic: Option<(&Url, Vec<u8>)>) -> ResultsPage; @@ -41,6 +48,8 @@ pub(super) trait BenchIo { fn elapsed(&self) -> Duration; } +pub(super) type LandingAdmission<'a> = dyn FnMut(&mut dyn BenchIo, &Url) -> bool + 'a; + #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub(super) enum Expectation { @@ -85,6 +94,7 @@ pub(super) enum FetchRefusal { Interrupted, Limit, Storage, + RobotsDenied, } impl FetchRefusal { @@ -106,6 +116,7 @@ impl fmt::Display for FetchRefusal { Self::Interrupted => formatter.write_str("Interrupted"), Self::Limit => formatter.write_str("Limit"), Self::Storage => formatter.write_str("Storage"), + Self::RobotsDenied => formatter.write_str("RobotsDenied"), } } } @@ -130,6 +141,7 @@ impl<'de> Deserialize<'de> for FetchRefusal { "Interrupted" => Ok(Self::Interrupted), "Limit" => Ok(Self::Limit), "Storage" => Ok(Self::Storage), + "RobotsDenied" => Ok(Self::RobotsDenied), _ => ReadRefusal::ALL .into_iter() .find(|refusal| refusal.to_string() == text) diff --git a/xtask/src/map_bench/probe.rs b/xtask/src/map_bench/probe.rs index 6b0283c4e..77ab40275 100644 --- a/xtask/src/map_bench/probe.rs +++ b/xtask/src/map_bench/probe.rs @@ -1,7 +1,9 @@ -use url::Url; +use std::collections::HashMap; +use url::{Origin, Position, Url}; use zephium_map::doc::MAX_CHARSET_LABEL_BYTES; use zephium_map::session::MAX_MEDIA_TYPE_BYTES; use zephium_map::{robots::Robots, PageKey, SiteKey}; +use zephium_public_fetch::guard::public_target; use zephium_public_fetch::{ReadRefusal, ReaderLimits, StatusRefusal}; use super::corpus::{CorpusQuery, Kind}; @@ -26,7 +28,9 @@ impl Engine for ProbeEngine { _ => &[], }; for site in sites { - outcome.probe.push(probe(io, site)); + if let Ok(site) = Url::parse(&format!("https://{site}/")) { + outcome.probe.push(probe(io, &site)); + } } outcome.stats.insert( "results_page_available".into(), @@ -45,8 +49,8 @@ impl Engine for ProbeEngine { } } -fn probe(io: &mut dyn BenchIo, site: &str) -> ProbeSite { - let robots = fetch(io, site, "/robots.txt", Expectation::Text); +fn probe(io: &mut dyn BenchIo, site: &Url) -> ProbeSite { + let robots = fetch_robots(io, site); let mut result = ProbeSite { robots: (&robots).into(), homepage: ProbeFetch::Skipped, @@ -59,17 +63,27 @@ fn probe(io: &mut dyn BenchIo, site: &str) -> ProbeSite { if result.robots_stop.is_some() { return result; } - let mut policies = vec![(site.to_owned(), policy(site, &robots))]; - if !policies[0].1.allows("/") { + let initial = policy(site, &robots); + if !initial.allows("/") { result.robots_stop = Some(RobotsStop::BlocksAll); return result; } + let mut policies = HashMap::from([(site.origin(), initial)]); - let home = fetch(io, site, "/", Expectation::Html); + let home = fetch_page(io, site.clone(), Expectation::Html, &mut policies); result.homepage = (&home).into(); - let home = if home.is_err() && !site.starts_with("www.") { - let www = format!("www.{site}"); - let robots = fetch(io, &www, "/robots.txt", Expectation::Text); + let retry_host = site.host_str().filter(|host| { + !host.starts_with("www.") + && home + .as_ref() + .is_err_and(|class| *class != FetchRefusal::RobotsDenied) + }); + let home = if let Some(host) = retry_host { + let mut www = site.clone(); + if www.set_host(Some(&format!("www.{host}"))).is_err() { + return result; + } + let robots = fetch_robots(io, &www); if let Some(stop) = robots_stop(&robots) { result.robots_stop = Some(stop); return result; @@ -79,48 +93,78 @@ fn probe(io: &mut dyn BenchIo, site: &str) -> ProbeSite { result.robots_stop = Some(RobotsStop::BlocksAll); return result; } - policies.push((www.clone(), www_policy)); - let retry = fetch(io, &www, "/", Expectation::Html); + policies.insert(www.origin(), www_policy); + let retry = fetch_page(io, www, Expectation::Html, &mut policies); result.www_retry = Some((&retry).into()); retry } else { home }; - if let Ok(home) = home { - if let Some(host) = home.final_url.host_str() { - result.homepage_final_host = Some(host.to_owned()); - let known = policies - .into_iter() - .find_map(|(origin, policy)| (origin == host).then_some(policy)); - let landed = known.or_else(|| { - let robots = fetch(io, host, "/robots.txt", Expectation::Text); - robots_stop(&robots) - .is_none() - .then(|| policy(host, &robots)) - }); - if let Some(landed) = landed { - if landed.allows("/llms.txt") { - result.llms = (&fetch(io, host, "/llms.txt", Expectation::Text)).into(); - } - if landed.allows("/sitemap.xml") { - result.sitemap = (&fetch(io, host, "/sitemap.xml", Expectation::Xml)).into(); - } + let landing = match home { + Ok(home) => home.final_url, + Err(FetchRefusal::RobotsDenied) => { + result.robots_stop = Some(RobotsStop::BlocksAll); + return result; + } + Err(_) => return result, + }; + result.homepage_final_host = landing.host_str().map(str::to_owned); + for (path, expect, slot) in [ + ("/llms.txt", Expectation::Text, &mut result.llms), + ("/sitemap.xml", Expectation::Xml, &mut result.sitemap), + ] { + if policies + .get(&landing.origin()) + .is_some_and(|p| p.allows(path)) + { + let page = fetch_page(io, at_path(&landing, path), expect, &mut policies); + *slot = (&page).into(); + if page == Err(FetchRefusal::RobotsDenied) { + result.robots_stop = Some(RobotsStop::BlocksAll); + break; } } } result } -fn fetch(io: &mut dyn BenchIo, host: &str, path: &str, expect: Expectation) -> FetchResult { - let url = Url::parse(&format!("https://{host}{path}")) - .map_err(|_| FetchRefusal::Reader(ReadRefusal::NotPublicHttps))?; +fn at_path(origin: &Url, path: &str) -> Url { + let mut url = origin.clone(); + url.set_path(path); + url.set_query(None); + url.set_fragment(None); + url +} + +fn request(url: Url, expect: Expectation) -> FetchRequest { let limits = ReaderLimits::default(); - io.fetch(FetchRequest { + FetchRequest { url, expect, max_bytes: limits.max_decoded_bytes, timeout: limits.max_duration, + } +} + +fn fetch_robots(io: &mut dyn BenchIo, origin: &Url) -> FetchResult { + io.fetch(request(at_path(origin, "/robots.txt"), Expectation::Text)) +} + +fn fetch_page( + io: &mut dyn BenchIo, + url: Url, + expect: Expectation, + policies: &mut HashMap<Origin, Robots>, +) -> FetchResult { + io.fetch_checked(request(url, expect), &mut |io, landing| { + if !public_target(landing) { + return false; + } + let policy = policies + .entry(landing.origin()) + .or_insert_with(|| policy(landing, &fetch_robots(io, landing))); + policy.allows(&landing[Position::BeforePath..Position::AfterQuery]) }) } @@ -138,7 +182,7 @@ fn robots_stop(result: &FetchResult) -> Option<RobotsStop> { /// The session engine's robots admission: `Session::receive` for `Work::Robots` /// in `zephium-map/src/session/scheduler.rs`, fed by `failure` and `session_body` /// in `map_bench/session.rs`. -fn policy(host: &str, result: &FetchResult) -> Robots { +fn policy(origin: &Url, result: &FetchResult) -> Robots { let body = match result { Ok(body) => body, Err(FetchRefusal::Reader(ReadRefusal::Status(StatusRefusal::Client))) => { @@ -155,9 +199,7 @@ fn policy(host: &str, result: &FetchResult) -> Robots { .unwrap_or_default() .trim() .to_ascii_lowercase(); - let site = Url::parse(&format!("https://{host}/")) - .ok() - .and_then(|url| SiteKey::from_url(&url)); + let site = SiteKey::from_url(origin); if body .media_type .as_ref() @@ -181,6 +223,7 @@ fn policy(host: &str, result: &FetchResult) -> Robots { mod tests { use super::*; use crate::map_bench::corpus::fixture; + use crate::map_bench::engine::LandingAdmission; use std::collections::VecDeque; use std::time::Duration; use zephium_public_fetch::{PublicBody, StatusClass, TimeoutPhase, Timings}; @@ -191,9 +234,18 @@ mod tests { } impl BenchIo for FakeIo { - fn fetch(&mut self, request: FetchRequest) -> FetchResult { + fn fetch_checked( + &mut self, + request: FetchRequest, + admit: &mut LandingAdmission<'_>, + ) -> FetchResult { self.calls.push((request.url.to_string(), request.expect)); - self.results.pop_front().expect("unexpected request") + let body = self.results.pop_front().expect("unexpected request")?; + if admit(self, &body.final_url) { + Ok(body) + } else { + Err(FetchRefusal::RobotsDenied) + } } fn results_page( @@ -352,7 +404,7 @@ mod tests { ("<html><body>Not found</body></html>", false), ] { let policy = policy( - "a.com", + &Url::parse("https://a.com/").unwrap(), &body("https://a.com/robots.txt", robots.as_bytes()), ); assert_eq!(policy.allows("/"), home, "{robots:?}"); @@ -414,7 +466,11 @@ mod tests { false, ), ] { - assert_eq!(policy("a.com", &robots).allows("/"), allowed, "{robots:?}"); + assert_eq!( + policy(&Url::parse("https://a.com/").unwrap(), &robots).allows("/"), + allowed, + "{robots:?}" + ); } let query = fixture("[[query]]\nid='q'\ntext='q'\nkind='place'\nsite='a.com'"); let mut io = FakeIo { @@ -496,6 +552,61 @@ mod tests { assert_eq!(io.calls[3].0, "https://docs.a.com/sitemap.xml"); } + #[test] + fn redirected_homepage_rejects_a_denied_path() { + let query = fixture("[[query]]\nid='q'\ntext='q'\nkind='place'\nsite='example.com'"); + let mut io = FakeIo { + calls: vec![], + results: [ + body( + "https://example.com/robots.txt", + b"User-agent: *\nDisallow: /private", + ), + body("https://example.com/private", b"denied"), + body("https://example.com/llms.txt", b"llms"), + body("https://example.com/sitemap.xml", b"sitemap"), + ] + .into(), + }; + let outcome = ProbeEngine.run(&query, &mut io); + let site = &outcome.probe[0]; + assert_eq!(site.robots_stop, Some(RobotsStop::BlocksAll)); + assert!(!site.homepage.answered()); + assert!(site.homepage_final_host.is_none()); + assert_eq!(io.calls.len(), 2); + } + + #[test] + fn redirected_homepage_rejects_a_denied_or_unknown_new_origin() { + let query = fixture("[[query]]\nid='q'\ntext='q'\nkind='place'\nsite='example.com'"); + for robots in [ + body( + "https://docs.example.com/robots.txt", + b"User-agent: *\nDisallow: /private", + ), + Err(FetchRefusal::Reader(ReadRefusal::Transport)), + ] { + let mut io = FakeIo { + calls: vec![], + results: [ + body("https://example.com/robots.txt", b"User-agent: *\nAllow: /"), + body("https://docs.example.com/private", b"denied"), + robots, + body("https://docs.example.com/llms.txt", b"llms"), + body("https://docs.example.com/sitemap.xml", b"sitemap"), + ] + .into(), + }; + let outcome = ProbeEngine.run(&query, &mut io); + let site = &outcome.probe[0]; + assert_eq!(site.robots_stop, Some(RobotsStop::BlocksAll)); + assert!(!site.homepage.answered()); + assert!(site.homepage_final_host.is_none()); + assert_eq!(io.calls.len(), 3); + assert_eq!(io.calls[2].0, "https://docs.example.com/robots.txt"); + } + } + #[test] fn other_kinds_stay_out() { for fields in [ diff --git a/xtask/src/map_bench/report.rs b/xtask/src/map_bench/report.rs index 0f66f25f1..8d7a5d4e3 100644 --- a/xtask/src/map_bench/report.rs +++ b/xtask/src/map_bench/report.rs @@ -367,6 +367,7 @@ impl Default for Accumulator { FetchRefusal::Interrupted, FetchRefusal::Limit, FetchRefusal::Storage, + FetchRefusal::RobotsDenied, ]) .map(|class| (class.to_string(), 0)) .collect(), @@ -516,14 +517,20 @@ impl Report { } let outcome = optional_json(&path.join(OUTCOME))?; let measure = optional_json(&path.join(MEASURE))?; - let outcome = outcome.unwrap_or_else(|| { - QueryResult::unavailable( - Verdict::NotRecorded, - Reason::RecordingMissing, - Default::default(), - ) - }); - recording.push(query, outcome, measure, false); + if let (Some(outcome), Some(measure)) = (outcome, measure) { + recording.push(query, outcome, Some(measure), false); + } else { + recording.push( + query, + QueryResult::unavailable( + Verdict::NotRecorded, + Reason::RecordingMissing, + Default::default(), + ), + None, + false, + ); + } } let engine = manifest.engine; let latest_replay = latest_replay(root)? diff --git a/xtask/src/map_bench/run.rs b/xtask/src/map_bench/run.rs index 4fead8928..1e651d689 100644 --- a/xtask/src/map_bench/run.rs +++ b/xtask/src/map_bench/run.rs @@ -15,7 +15,7 @@ use zephium_public_fetch::{ use super::corpus::{Corpus, CorpusQuery, QueryLabel, MAX_CORPUS_FILES, MAX_QUERIES}; use super::engine::{ redact_thread_panics, run_catching, Activity, BenchIo, Engine, EngineFailure, EngineKind, - FetchRefusal, FetchRequest, FetchResult, Outcome, ResultsPage, MAX_REQUESTS, + FetchRefusal, FetchRequest, FetchResult, LandingAdmission, Outcome, ResultsPage, MAX_REQUESTS, }; use super::score::{self, Reason, Score, Verdict}; use super::store::{ @@ -471,7 +471,10 @@ impl<'a> QueryIo<'a> { Ok(()) } - fn complete_live(&mut self) -> Option<(usize, FetchResult)> { + fn complete_live( + &mut self, + admit: Option<&mut LandingAdmission<'_>>, + ) -> Option<(usize, FetchResult)> { let live = self.live.as_mut()?; if self.active.is_empty() { return None; @@ -494,19 +497,69 @@ impl<'a> QueryIo<'a> { self.failure = Some(Reason::ArtifactError); } self.elapsed = self.elapsed.max(completed.transfer.end); + let root = live.root; + let mut denied_origin = None; + if let (Ok(body), Some(admit)) = (&completed.result, admit) { + if !admit(self, &body.final_url) { + denied_origin = Url::parse(&body.final_url.origin().ascii_serialization()).ok(); + completed.result = Err(FetchRefusal::RobotsDenied); + } + } let result = self .journal .finish( - live.root, + root, self.query, index, &completed.result, completed.transfer, + denied_origin, ) .map_or_else(|error| Err(self.refuse(error)), |()| completed.result); Some((completed.token, result)) } + fn next_fetch_with( + &mut self, + admit: Option<&mut LandingAdmission<'_>>, + ) -> Option<(usize, FetchResult)> { + let (token, result) = if let Some(((_, end, token), ready)) = self.ready.pop_first() { + self.elapsed = self.elapsed.max(end); + let result = match ready { + Ready::Recorded(matched) => match self.journal.result(matched.index, self.query) { + Ok(mut result) => { + if let Some(cap) = matched.relaxed_cap { + if let Ok(body) = &mut result { + body.bytes.truncate(cap); + } + self.activity.matched_relaxed += 1; + } + if let Some(admit) = admit { + if let Ok(body) = &result { + if !admit(self, &body.final_url) { + result = Err(FetchRefusal::RobotsDenied); + } + } else if let (Err(FetchRefusal::RobotsDenied), Some(origin)) = ( + &result, + self.journal.robots_denied_origin(matched.index).cloned(), + ) { + admit(self, &origin); + } + } + result + } + Err(error) => Err(self.refuse(error)), + }, + Ready::Refused(class) => Err(class), + }; + (token, result) + } else { + self.complete_live(admit)? + }; + self.activity.called(&result); + Some((token, result)) + } + fn load_results(&mut self, synthetic: Option<(&Url, Vec<u8>)>) -> Result<ResultsPage> { let (page, elapsed) = ResultsSlot::load(self.query)?; if let (ResultsPage::Unavailable, Some(live), Some((url, bytes))) = @@ -533,6 +586,16 @@ impl BenchIo for QueryIo<'_> { .map_or(Err(FetchRefusal::Storage), |(_, result)| result) } + fn fetch_checked( + &mut self, + request: FetchRequest, + admit: &mut LandingAdmission<'_>, + ) -> FetchResult { + self.start_fetch(request); + self.next_fetch_with(Some(admit)) + .map_or(Err(FetchRefusal::Storage), |(_, result)| result) + } + fn start_fetch(&mut self, request: FetchRequest) -> usize { let token = self.submitted; self.submitted = self.submitted.saturating_add(1); @@ -554,29 +617,7 @@ impl BenchIo for QueryIo<'_> { } fn next_fetch(&mut self) -> Option<(usize, FetchResult)> { - let (token, result) = if let Some(((_, end, token), ready)) = self.ready.pop_first() { - self.elapsed = self.elapsed.max(end); - let result = match ready { - Ready::Recorded(matched) => match self.journal.result(matched.index, self.query) { - Ok(mut result) => { - if let Some(cap) = matched.relaxed_cap { - if let Ok(body) = &mut result { - body.bytes.truncate(cap); - } - self.activity.matched_relaxed += 1; - } - result - } - Err(error) => Err(self.refuse(error)), - }, - Ready::Refused(class) => Err(class), - }; - (token, result) - } else { - self.complete_live()? - }; - self.activity.called(&result); - Some((token, result)) + self.next_fetch_with(None) } fn results_page(&mut self, synthetic: Option<(&Url, Vec<u8>)>) -> ResultsPage { @@ -664,6 +705,7 @@ fn record_query( engine: &mut dyn Engine, source: &mut dyn Source, clock: RunClock, + publish_outcome: impl FnOnce(&Path, QueryResult) -> Result<()>, ) -> Result<()> { let path = query_dir(root, &query.label.id, false)?; let resumed = store::directory(&path, false)?; @@ -709,8 +751,16 @@ fn record_query( if let Some(count) = output.activity.refusals.get("Limit") { measure.refusals.insert("Limit".into(), *count); } + let robots_denied = FetchRefusal::RobotsDenied.to_string(); + if let Some(count) = output.activity.refusals.get(&robots_denied) { + measure.refusals.insert(robots_denied, *count); + } + let outcome = path.join(OUTCOME); + if store::exists(&outcome)? { + fs::remove_file(&outcome).map_err(|error| BenchError::io("invalidate_outcome", &error))?; + } write_json(&path.join(MEASURE), &measure)?; - save_outcome(&path.join(OUTCOME), output) + publish_outcome(&outcome, output) } pub(super) fn pending<'a>( @@ -795,7 +845,7 @@ fn record_queries( if index > 0 { std::thread::sleep(pause); } - if let Err(error) = record_query(root, query, engine, source, clock) { + if let Err(error) = record_query(root, query, engine, source, clock, save_outcome) { failed = true; eprintln!("map bench: {}", error.for_query(&query.label.id)); } diff --git a/xtask/src/map_bench/run/tests.rs b/xtask/src/map_bench/run/tests.rs index 74888454c..3dc495ef0 100644 --- a/xtask/src/map_bench/run/tests.rs +++ b/xtask/src/map_bench/run/tests.rs @@ -572,6 +572,7 @@ fn report_matches_golden_and_hides_private_inputs() { }, &mut FakeSource::default(), PROBE_CLOCK, + save_outcome, ) .unwrap(); let first = query_dir(root.path(), "blocked", false).unwrap(); @@ -718,6 +719,50 @@ fn resume_retries_a_checkpoint_without_a_measurement() { assert!(pending(root.path(), [&query], 1).unwrap().is_empty()); } +#[test] +fn failed_outcome_publication_leaves_the_resumed_query_pending() { + let root = tempfile::tempdir().unwrap(); + let query = place("unfinished"); + let path = query_dir(root.path(), &query.label.id, true).unwrap(); + save_outcome( + &path.join(OUTCOME), + QueryResult::unavailable(Verdict::Fail, Reason::ArtifactError, Activity::default()), + ) + .unwrap(); + assert_eq!(pending(root.path(), [&query], 1).unwrap().len(), 1); + let mut engine = Script { + path: "/denied", + expect: Expectation::Text, + repeated: false, + }; + let mut source = FakeSource::default(); + let error = record_query( + root.path(), + &query, + &mut engine, + &mut source, + PROBE_CLOCK, + |_, _| { + let measure = store::read_json::<Measure>(&path.join(MEASURE)).unwrap(); + assert_eq!(measure.requests, 1); + Err(BenchError::new("publish_checkpoint")) + }, + ) + .unwrap_err(); + assert_eq!(error.class, "publish_checkpoint"); + assert_eq!(pending(root.path(), [&query], 1).unwrap().len(), 1); + record_query( + root.path(), + &query, + &mut engine, + &mut source, + PROBE_CLOCK, + save_outcome, + ) + .unwrap(); + assert!(pending(root.path(), [&query], 1).unwrap().is_empty()); +} + #[test] fn invalid_outcomes_cannot_claim_the_no_site_exception() { struct Invalid; diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 8c0d46c66..97dfef0f4 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -103,6 +103,52 @@ fn refuse(class: StatusRefusal) -> FetchResult { Err(FetchRefusal::Reader(ReadRefusal::Status(class))) } +#[test] +fn probe_does_not_persist_robots_denied_redirect_bodies() { + const DENIED_BODY: &str = "denied homepage body"; + let root = tempfile::tempdir().unwrap(); + let query = place("redirected"); + let mut source = ScriptedSource::new(|request| match request.url.path() { + "/robots.txt" => scripted_body( + request, + "text/plain", + if request.url.host_str() == Some("docs.example.com") { + "User-agent: *\nDisallow: /private" + } else { + "User-agent: *\nAllow: /" + }, + ) + .map(|mut body| { + body.wire_bytes = 0; + body + }), + "/" => scripted_body(request, "text/html", DENIED_BODY).map(|mut body| { + body.final_url = Url::parse("https://docs.example.com/private").unwrap(); + body + }), + _ => refuse(StatusRefusal::Client), + }); + let mut engine = crate::map_bench::probe::ProbeEngine; + record_query( + root.path(), + &query, + &mut engine, + &mut source, + PROBE_CLOCK, + save_outcome, + ) + .unwrap(); + let digest = store::digest(DENIED_BODY.as_bytes()); + let path = query_dir(root.path(), &query.label.id, false).unwrap(); + assert!(!root.path().join("bodies").join(&digest).exists()); + assert!(!path.join("bodies").join(digest).exists()); + let recorded: QueryResult = store::read_json(&path.join(OUTCOME)).unwrap(); + assert_eq!(recorded.score.reason, Reason::RobotsDenied); + assert_eq!(recorded.activity.site_requests, 3); + let replay = replay_query(root.path(), &query, &mut engine, PROBE_CLOCK, 0, None).unwrap(); + assert_eq!(recorded, replay); +} + fn site(request: &FetchRequest) -> FetchResult { match request.url.path() { "/robots.txt" => { @@ -147,7 +193,15 @@ const ACME: &str = "kind='place'\nsite='acme.com'\nwant=['acme.com/setup']\ngrou fn run_session(root: &Path, query: &CorpusQuery, source: &mut ScriptedSource) -> QueryResult { let mut engine = crate::map_bench::session::SessionEngine; - record_query(root, query, &mut engine, source, SESSION_CLOCK).unwrap(); + record_query( + root, + query, + &mut engine, + source, + SESSION_CLOCK, + save_outcome, + ) + .unwrap(); let path = query_dir(root, &query.label.id, false).unwrap(); let captured = store::read_json::<QueryResult>(&path.join(OUTCOME)).unwrap(); let destination = tempfile::tempdir().unwrap(); @@ -659,7 +713,7 @@ fn save_row(root: &Path, path: &Path, request: &FetchRequest, result: FetchResul wire_bytes: result.as_ref().ok().map(|body| body.wire_bytes), }; journal - .finish(root, path, index, &result, transfer) + .finish(root, path, index, &result, transfer, None) .unwrap(); } diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index 9fdaea443..3dd84f585 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -460,6 +460,7 @@ fn failure(refusal: FetchRefusal) -> Failure { | FetchRefusal::NotRecorded | FetchRefusal::Interrupted | FetchRefusal::Storage => Failure::Unavailable, + FetchRefusal::RobotsDenied => Failure::Robots, FetchRefusal::Reader(R::Timeout(_)) => Failure::Timeout, FetchRefusal::Reader(R::Status(S::Client)) => Failure::Client, FetchRefusal::Reader(R::Status(S::RateLimited | S::Server)) => Failure::Server, @@ -704,7 +705,11 @@ mod tests { } impl BenchIo for EffectsOnly { - fn fetch(&mut self, _: FetchRequest) -> FetchResult { + fn fetch_checked( + &mut self, + _: FetchRequest, + _: &mut super::super::engine::LandingAdmission<'_>, + ) -> FetchResult { panic!("expected asynchronous fetch"); } diff --git a/xtask/src/map_bench/store.rs b/xtask/src/map_bench/store.rs index d479c7264..a03f13b63 100644 --- a/xtask/src/map_bench/store.rs +++ b/xtask/src/map_bench/store.rs @@ -353,8 +353,13 @@ struct RequestRow { #[serde(default)] completion_order: Option<usize>, body: Option<BodyRef>, + #[serde(default, skip_serializing_if = "Option::is_none")] + robots_denied_origin: Option<JournalUrl>, } +#[derive(Deserialize, Serialize)] +struct JournalUrl(#[serde(with = "url_text")] Url); + #[derive(Deserialize, Serialize)] struct TransferTimes { queued: Option<Duration>, @@ -395,6 +400,7 @@ impl RequestRow { elapsed_at_return: elapsed, completion_order: None, body: None, + robots_denied_origin: None, } } @@ -635,6 +641,14 @@ impl Journal { .result(query) } + pub(super) fn robots_denied_origin(&self, index: usize) -> Option<&Url> { + self.0 + .get(index)? + .robots_denied_origin + .as_ref() + .map(|url| &url.0) + } + pub(super) fn elapsed(&self) -> Duration { self.0 .iter() @@ -665,6 +679,7 @@ impl Journal { index: usize, fetch: &FetchResult, transfer: Transfer, + robots_denied_origin: Option<Url>, ) -> Result<()> { let order = self.0.iter().filter_map(|row| row.completion_order).max(); let row = self @@ -672,6 +687,7 @@ impl Journal { .get_mut(index) .ok_or(BenchError::new("missing_request_reservation"))?; row.finish(root, query, fetch, transfer)?; + row.robots_denied_origin = robots_denied_origin.map(JournalUrl); row.completion_order = Some(order.map_or(0, |order| order + 1)); self.save(query) } From 0c83cfe1e8af3c55b800a56b556bf66fa54127ad Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sat, 21 Nov 2026 23:49:55 +0100 Subject: [PATCH 34/40] fix(fetch): refuse per-domain proxy settings on macOS --- .../src/platform/macos.rs | 3 +++ .../zephium-public-fetch/src/platform/mod.rs | 23 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/zephium-public-fetch/src/platform/macos.rs b/crates/zephium-public-fetch/src/platform/macos.rs index d8aaca838..ffde04a93 100644 --- a/crates/zephium-public-fetch/src/platform/macos.rs +++ b/crates/zephium-public-fetch/src/platform/macos.rs @@ -77,6 +77,9 @@ fn read() -> Option<MacProxies> { https_port: number(&proxies, "HTTPSPort"), socks: enabled("SOCKSEnable"), scoped: scoped(&proxies), + supplemental: proxies + .find(CFString::from_static_string("__SUPPLEMENTAL__")) + .is_some(), }) } diff --git a/crates/zephium-public-fetch/src/platform/mod.rs b/crates/zephium-public-fetch/src/platform/mod.rs index dd9d31dbd..b5e39aac8 100644 --- a/crates/zephium-public-fetch/src/platform/mod.rs +++ b/crates/zephium-public-fetch/src/platform/mod.rs @@ -29,6 +29,7 @@ pub(crate) struct MacProxies { pub(crate) https_port: Option<i64>, pub(crate) socks: bool, pub(crate) scoped: Scoped, + pub(crate) supplemental: bool, } #[cfg(any(target_os = "macos", test))] @@ -85,7 +86,11 @@ impl Scoped { #[cfg(any(target_os = "macos", test))] pub(crate) fn mac_route(proxies: &MacProxies) -> Route { - if proxies.auto_config || proxies.auto_discovery || proxies.scoped.enables_anything() { + if proxies.auto_config + || proxies.auto_discovery + || proxies.supplemental + || proxies.scoped.enables_anything() + { return Route::Unsupported; } if proxies.https { @@ -244,6 +249,22 @@ mod tests { assert_eq!(mac_route(&both), http("proxy.corp.example", 8080)); } + #[test] + fn per_domain_proxy_settings_are_unsupported() { + let supplemental = MacProxies { + supplemental: true, + ..MacProxies::default() + }; + assert_eq!(mac_route(&supplemental), Route::Unsupported); + let with_proxy = MacProxies { + https: true, + https_host: Some("proxy.corp.example".into()), + https_port: Some(8080), + ..supplemental + }; + assert_eq!(mac_route(&with_proxy), Route::Unsupported); + } + #[test] fn a_scoped_interface_proxy_is_unsupported_and_a_harmless_one_is_not() { let scoped = |scoped| MacProxies { From ff672e55b67a209c807df2989c390b51f819ad38 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 03:37:25 +0100 Subject: [PATCH 35/40] feat(map): read what was asked and open sections on demand A search now reads the entry page, the asked section and the site's own lists; any other section is read when it is opened, as one page under the same robots, redirect, size and time rules. The map handle outlives its search so a section can be opened later, also in a private map. The wire gains the other results by title and host, a display host for entries that leave the place, whether an entry can be opened, and the result of an open. The bench replays either section mode and compares an on-demand open with the eager read; the try-out can open rows. --- crates/zephium-map-driver/src/driver.rs | 300 ++++++++++-- crates/zephium-map-driver/src/driver/tests.rs | 214 ++++++++- crates/zephium-map-driver/src/lib.rs | 2 +- crates/zephium-map-driver/src/wire.rs | 175 ++++++- crates/zephium-map-driver/src/wire/tests.rs | 122 ++++- crates/zephium-map/src/session.rs | 354 +++++++++++++-- crates/zephium-map/src/session/memo.rs | 32 +- crates/zephium-map/src/session/scheduler.rs | 107 ++++- crates/zephium-map/src/session/types.rs | 15 + crates/zephium-map/src/site.rs | 110 ++++- crates/zephium-map/tests/session.rs | 426 ++++++++++++++++++ xtask/src/main.rs | 4 +- xtask/src/map_bench/run.rs | 200 +++++++- xtask/src/map_bench/section_flags.rs | 107 +++++ xtask/src/map_bench/session.rs | 115 ++++- xtask/src/map_bench/store.rs | 4 + xtask/src/map_try.rs | 100 +++- xtask/src/map_try/printer.rs | 34 +- xtask/src/map_try/printer/tests.rs | 3 + xtask/src/map_try/tests.rs | 105 +++++ 20 files changed, 2369 insertions(+), 160 deletions(-) create mode 100644 xtask/src/map_bench/section_flags.rs diff --git a/crates/zephium-map-driver/src/driver.rs b/crates/zephium-map-driver/src/driver.rs index ae44076e4..dc9fb9a40 100644 --- a/crates/zephium-map-driver/src/driver.rs +++ b/crates/zephium-map-driver/src/driver.rs @@ -15,19 +15,21 @@ use tokio::{ use url::Url; use zephium_core::search::SearchEngine; use zephium_map::{ + query::Confidence, read_query, - session::{Failure, Id, MAX_CONCURRENT, MAX_HOST_CONCURRENT}, + session::{Failure, HeldSite, Id, ReadState, Sections, MAX_CONCURRENT, MAX_HOST_CONCURRENT}, Config, Effect, Input, MapEvent, QueryKind, Session, }; use crate::{ io::{FetchRequest, Io}, page, - wire::{self, Change, StartRefusal, Target, Targets}, + wire::{self, Change, OpenRefusal, OpenResult, StartRefusal, Target, Targets}, }; pub const TICK: Duration = Duration::from_millis(250); pub const CHANGE_BUFFER: usize = 64; +pub const MAX_WAITING_OPENS: usize = 4; const SLOTS: usize = 2; pub struct MapRequest { @@ -52,7 +54,7 @@ pub struct Counts { #[derive(Default)] struct Shared { - targets: Mutex<[Option<Targets>; SLOTS]>, + published: Mutex<Published>, fetches: AtomicU32, bytes: AtomicU64, render_unavailable: AtomicU32, @@ -62,8 +64,10 @@ struct Shared { } impl Shared { - fn targets(&self) -> MutexGuard<'_, [Option<Targets>; SLOTS]> { - self.targets.lock().unwrap_or_else(PoisonError::into_inner) + fn published(&self) -> MutexGuard<'_, Published> { + self.published + .lock() + .unwrap_or_else(PoisonError::into_inner) } } @@ -71,10 +75,35 @@ fn bump(counter: &AtomicU32) { let _ = counter.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_add(1)); } +#[derive(Default)] +struct Published { + slots: [Option<PublishedPlace>; SLOTS], + also: Vec<Url>, +} + +struct PublishedPlace { + targets: Targets, + held: Option<Arc<HeldSite>>, + confidence: Confidence, + stale: bool, +} + +struct OpenRequest { + slot: u8, + id: String, +} + +enum Publication { + Place(usize, Box<PublishedPlace>), + PlaceFailed(usize), + Also(Vec<Url>), +} + pub struct Driver { cancel: watch::Sender<bool>, task: JoinHandle<()>, shared: Arc<Shared>, + opens: mpsc::Sender<OpenRequest>, } impl Driver { @@ -106,12 +135,14 @@ impl Driver { session_id: request.session_id, engine: request.engine, now: io.clock.unix(), + sections: Sections::Asked, ..Config::default() }; let (session, effects) = Session::start(config, &request.query).map_err(|_| StartRefusal::Invalid)?; let (tx, rx) = mpsc::channel(buffer); let (cancel, cancelled) = watch::channel(false); + let (opens, open_requests) = mpsc::channel(MAX_WAITING_OPENS); let shared = Arc::new(Shared::default()); let run = Run { started: io.clock.now(), @@ -129,6 +160,9 @@ impl Driver { cancelled, cancelling: false, unsent: None, + open_requests, + opening: None, + session_id: request.session_id, }; let task = runtime.spawn(run.run(effects)); Ok(( @@ -136,21 +170,56 @@ impl Driver { cancel, task, shared, + opens, }, rx, )) } pub fn cancel(&self) { + let _published = self.shared.published(); self.cancel.send_replace(true); } - /// Resolves against the last place emitted for `slot`; only `https` addresses come back. + pub fn open(&self, slot: u8, id: &str) -> Result<(), OpenRefusal> { + let published = self.shared.published(); + if *self.cancel.borrow() || self.opens.is_closed() { + return Err(OpenRefusal::Cancelled); + } + let place = published + .slots + .get(usize::from(slot)) + .and_then(Option::as_ref) + .ok_or(OpenRefusal::NoPlace)?; + if !place.targets.has(id) { + return Err(OpenRefusal::UnknownEntry); + } + place + .held + .as_ref() + .ok_or(OpenRefusal::NotOpenable)? + .check_open(id)?; + self.opens + .try_send(OpenRequest { + slot, + id: id.to_owned(), + }) + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => OpenRefusal::TooManyWaiting, + mpsc::error::TrySendError::Closed(_) => OpenRefusal::Cancelled, + }) + } + pub fn target(&self, slot: u8, target: &Target) -> Option<Url> { - self.shared - .targets() + let published = self.shared.published(); + if let Target::Also { index } = target { + return wire::also_target(&published.also, *index); + } + published + .slots .get(usize::from(slot))? .as_ref()? + .targets .resolve(target) } @@ -169,7 +238,9 @@ impl Driver { impl Drop for Driver { fn drop(&mut self) { + let _published = self.shared.published(); self.task.abort(); + self.cancel.send_replace(true); } } @@ -208,7 +279,10 @@ struct Run { started: Duration, cancelled: watch::Receiver<bool>, cancelling: bool, - unsent: Option<(usize, Targets)>, + unsent: Option<Publication>, + open_requests: mpsc::Receiver<OpenRequest>, + opening: Option<OpenRequest>, + session_id: u64, } fn is_end(effect: &Effect) -> bool { @@ -226,6 +300,13 @@ impl Run { loop { let next = match self.apply(effects).await { Applied::Stop => return, + Applied::Continue if self.session.is_none() => { + let Some(next) = self.next_open().await else { + return; + }; + effects = next; + continue; + } Applied::Cancel => Next::Cancel, Applied::Continue if *self.cancelled.borrow() => Next::Cancel, Applied::Continue if self.immediate.is_empty() => self.wait().await, @@ -234,10 +315,10 @@ impl Run { let input = match next { Next::Stop => return, Next::Cancel => { - self.reads.abort_all(); - self.tasks.clear(); - self.hosts.clear(); - self.immediate.clear(); + self.clear_reads(); + if self.opening.is_some() { + return; + } self.cancelling = true; Some(Input::Cancel) } @@ -251,6 +332,96 @@ impl Run { } } + fn clear_reads(&mut self) { + self.reads = JoinSet::new(); + self.tasks.clear(); + self.hosts.clear(); + self.immediate.clear(); + } + + async fn next_open(&mut self) -> Option<Vec<Effect>> { + loop { + let request = tokio::select! { + biased; + _ = self.cancelled.wait_for(|cancelled| *cancelled) => return None, + () = self.tx.closed() => return None, + request = self.open_requests.recv() => request?, + }; + let slot = request.slot; + let place = { + let published = self.shared.published(); + published.slots[usize::from(slot)] + .as_ref() + .and_then(|item| { + Some((item.held.as_ref()?.clone(), item.confidence, item.stale)) + }) + }; + if let Some((held, confidence, stale)) = place { + let cfg = Config { + session_id: self.session_id, + now: self.io.clock.unix(), + ..Config::default() + }; + if let Ok((session, effects)) = + Session::open(cfg, (*held).clone(), slot, &request.id, confidence, stale) + { + self.session = Some(session); + self.opening = Some(request); + self.started = self.io.clock.now(); + return Some(effects); + } + let (place, _) = wire::place(held.place(), Some(held.robots())); + let change = Change::Place { + seq: self.next_seq(), + slot, + place, + stale, + confidence: confidence.into(), + complete: true, + }; + if self.deliver(change).await != Applied::Continue { + return None; + } + } + let result = self.open_result(&request); + let change = Change::Opened { + seq: self.next_seq(), + slot, + id: request.id, + result, + }; + if self.deliver(change).await != Applied::Continue { + return None; + } + } + } + + fn open_result(&self, request: &OpenRequest) -> OpenResult { + let published = self.shared.published(); + let entry = published.slots[usize::from(request.slot)] + .as_ref() + .and_then(|slot| slot.held.as_ref()) + .and_then(|held| { + held.place() + .sections + .iter() + .find(|entry| entry.id.as_str() == request.id) + }); + match entry.and_then(|entry| entry.read) { + Some(ReadState::Read) => OpenResult::Read, + Some(ReadState::Refused { failure }) => OpenResult::Refused { + failure: failure.into(), + }, + _ => OpenResult::Refused { + failure: if entry.is_some() { + wire::Failure::Blocked + } else { + wire::Failure::Missing + }, + }, + } + } + async fn wait(&mut self) -> Next { let done = tokio::select! { changed = self.cancelled.changed() => { @@ -333,10 +504,12 @@ impl Run { Some(effects) } Err(_) => { - let end = self.end(wire::Outcome::Failed { - failure: wire::Failure::Unavailable, - }); - let _ = self.tx.send(end).await; + if self.opening.is_none() { + let end = self.end(wire::Outcome::Failed { + failure: wire::Failure::Unavailable, + }); + self.deliver(end).await; + } None } } @@ -350,20 +523,31 @@ impl Run { }; } let seq = change.seq(); + if seq == u32::MAX { + return Applied::Stop; + } tokio::select! { biased; - cancelled = self.cancelled.wait_for(|cancelled| *cancelled) => { + cancelled = async { self.cancelled.wait_for(|cancelled| *cancelled).await.is_ok() } => { self.seq = seq; self.unsent = None; - if cancelled.is_ok() { Applied::Cancel } else { Applied::Stop } + if cancelled { Applied::Cancel } else { Applied::Stop } } - sent = self.tx.send(change) => { - if sent.is_err() { - return Applied::Stop; + permit = self.tx.reserve() => { + let Ok(permit) = permit else { return Applied::Stop }; + let mut published = self.shared.published(); + if *self.cancelled.borrow() { + self.seq = seq; + self.unsent = None; + return Applied::Cancel; } - if let Some((index, targets)) = self.unsent.take() { - self.shared.targets()[index] = Some(targets); + match self.unsent.take() { + Some(Publication::Place(index, place)) => published.slots[index] = Some(*place), + Some(Publication::PlaceFailed(index)) => published.slots[index] = None, + Some(Publication::Also(targets)) => published.also = targets, + None => {} } + permit.send(change); Applied::Continue } } @@ -432,16 +616,34 @@ impl Run { } } Effect::Emit { event, .. } => { - let end = matches!(event, MapEvent::End { .. }); + if matches!(event, MapEvent::End { .. }) { + if let Some(request) = self.opening.take() { + let result = self.open_result(&request); + let change = Change::Opened { + seq: self.next_seq(), + slot: request.slot, + id: request.id, + result, + }; + if self.deliver(change).await != Applied::Continue { + return Applied::Stop; + } + } else if let Some(change) = self.project(event) { + let applied = self.deliver(change).await; + if applied != Applied::Continue { + return applied; + } + } + self.clear_reads(); + self.session = None; + return Applied::Continue; + } if let Some(change) = self.project(event) { let applied = self.deliver(change).await; if applied != Applied::Continue { return applied; } } - if end { - return Applied::Stop; - } } } } @@ -516,12 +718,25 @@ impl Run { fn project(&mut self, event: MapEvent) -> Option<Change> { Some(match event { MapEvent::FirstLayer { layer } => { - let (official, social, organic) = wire::first_layer(&layer); + let places = self + .session + .as_ref() + .map(|session| session.result_places().collect::<Vec<_>>()) + .unwrap_or_default(); + let wire::Layer { + official, + social, + organic, + also, + targets, + } = wire::first_layer(&layer, &places); + self.unsent = Some(Publication::Also(targets)); Change::FirstLayer { seq: self.next_seq(), official, social, organic, + also, } } MapEvent::Place { @@ -535,8 +750,20 @@ impl Run { if index >= SLOTS { return None; } - let (place, targets) = wire::place(&place); - self.unsent = Some((index, targets)); + let held = self + .session + .as_ref() + .and_then(|session| session.hold_place(slot, place.clone())); + let (place, targets) = wire::place(&place, held.as_ref().map(HeldSite::robots)); + self.unsent = Some(Publication::Place( + index, + Box::new(PublishedPlace { + targets, + held: held.map(Arc::new), + confidence, + stale, + }), + )); Change::Place { seq: self.next_seq(), slot, @@ -550,6 +777,7 @@ impl Run { if usize::from(slot) >= SLOTS { return None; } + self.unsent = Some(Publication::PlaceFailed(usize::from(slot))); Change::PlaceFailed { seq: self.next_seq(), slot, @@ -558,12 +786,16 @@ impl Run { } MapEvent::Compare { rows } => { let rows = { - let targets = self.shared.targets(); + let published = self.shared.published(); let none = Targets::default(); wire::rows( &rows, - targets[0].as_ref().unwrap_or(&none), - targets[1].as_ref().unwrap_or(&none), + published.slots[0] + .as_ref() + .map_or(&none, |slot| &slot.targets), + published.slots[1] + .as_ref() + .map_or(&none, |slot| &slot.targets), ) }; Change::Compare { diff --git a/crates/zephium-map-driver/src/driver/tests.rs b/crates/zephium-map-driver/src/driver/tests.rs index a0557e7df..f7a5883eb 100644 --- a/crates/zephium-map-driver/src/driver/tests.rs +++ b/crates/zephium-map-driver/src/driver/tests.rs @@ -205,7 +205,11 @@ fn start(fake: &Arc<Fake>, request: MapRequest) -> (Driver, mpsc::Receiver<Chang async fn rest(rx: &mut mpsc::Receiver<Change>) -> Vec<Change> { let mut out = Vec::new(); while let Some(change) = rx.recv().await { + let end = matches!(change, Change::End { .. }); out.push(change); + if end { + break; + } } out } @@ -289,6 +293,34 @@ async fn a_place_streams_first_layer_then_places_then_one_end() { .iter() .find(|e| e.label == "Pricing") .unwrap(); + assert!(pricing.open && pricing.read.is_none() && pricing.children.is_empty()); + let before = driver.counts(); + driver.open(0, &pricing.id).unwrap(); + let Some(Change::Place { + slot: 0, + place, + complete: true, + seq, + .. + }) = rx.recv().await + else { + panic!("expected complete replacement"); + }; + assert_eq!(seq, changes.last().unwrap().seq() + 1); + let opened = rx.recv().await.unwrap(); + assert_eq!( + opened, + Change::Opened { + seq: seq + 1, + slot: 0, + id: pricing.id.clone(), + result: OpenResult::Read, + } + ); + let pricing = place.sections.iter().find(|e| e.id == pricing.id).unwrap(); + assert!(!pricing.open); + assert_eq!(driver.counts().fetches, before.fetches + 1); + assert!(driver.counts().bytes > before.bytes); let tiers = pricing .children .iter() @@ -413,6 +445,9 @@ async fn the_driver_refuses_reads_over_the_ceilings() { cancelled: watch::channel(false).1, cancelling: false, unsent: None, + open_requests: mpsc::channel(MAX_WAITING_OPENS).1, + opening: None, + session_id: 0, }; for (n, host) in ["a.com", "a.com", "a.com", "b.com", "c.com", "d.com"] .into_iter() @@ -677,7 +712,7 @@ async fn a_private_map_never_reads_or_writes_the_memo() { )); assert_eq!(fake.seen().fetches.len(), fetched); let calls = fake.memo_calls.load(Ordering::SeqCst); - let (_driver, mut rx) = start( + let (driver, mut rx) = start( &fake, MapRequest { private: true, @@ -688,4 +723,181 @@ async fn a_private_map_never_reads_or_writes_the_memo() { checked(&private, 0); assert!(fake.seen().fetches.len() > fetched); assert_eq!(fake.memo_calls.load(Ordering::SeqCst), calls); + let Some(Change::Place { place, .. }) = last_for(&private, 0) else { + panic!("expected place") + }; + let pricing = place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap(); + driver.open(0, &pricing.id).unwrap(); + assert!(matches!( + rx.recv().await, + Some(Change::Place { complete: true, .. }) + )); + assert!(matches!( + rx.recv().await, + Some(Change::Opened { + result: OpenResult::Read, + .. + }) + )); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), calls); +} + +#[tokio::test(start_paused = true)] +async fn opens_wait_for_search_end_and_the_queue_refuses_at_capacity() { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/llms.txt", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + assert_eq!( + driver.open(1, "0000000000000000"), + Err(OpenRefusal::NoPlace) + ); + assert!(matches!(rx.recv().await, Some(Change::FirstLayer { .. }))); + let Some(Change::Place { + slot: 0, + place, + complete: false, + .. + }) = rx.recv().await + else { + panic!("expected a partial place"); + }; + assert_eq!( + driver.open(0, "0000000000000000"), + Err(OpenRefusal::UnknownEntry) + ); + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + for _ in 0..MAX_WAITING_OPENS { + assert_eq!(driver.open(0, id), Ok(())); + } + assert_eq!(driver.open(0, id), Err(OpenRefusal::TooManyWaiting)); + assert!(!fake + .seen() + .fetches + .iter() + .any(|path| path.ends_with("/pricing"))); + let changes = rest(&mut rx).await; + let mut seq = changes.last().unwrap().seq(); + for _ in 0..MAX_WAITING_OPENS { + let place = rx.recv().await.unwrap(); + assert!(matches!(place, Change::Place { complete: true, .. })); + assert_eq!(place.seq(), seq + 1); + let opened = rx.recv().await.unwrap(); + seq += 2; + assert_eq!( + opened, + Change::Opened { + seq, + slot: 0, + id: id.clone(), + result: OpenResult::Read + } + ); + } + assert_eq!(driver.open(0, id), Err(OpenRefusal::NotOpenable)); + assert_eq!( + fake.seen() + .fetches + .iter() + .filter(|path| path.ends_with("/pricing")) + .count(), + 1 + ); +} + +#[tokio::test(start_paused = true)] +async fn cancelling_or_dropping_during_an_open_aborts_it_silently() { + for cancel in [true, false] { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/pricing", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let Some(Change::Place { place, .. }) = last_for(&changes, 0) else { + panic!("expected place") + }; + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + driver.open(0, id).unwrap(); + until(&fake, "acme.com/pricing").await; + assert_eq!(active(&fake), 1); + if cancel { + driver.cancel(); + assert_eq!(driver.open(0, id), Err(OpenRefusal::Cancelled)); + assert_eq!(rx.recv().await, None); + } else { + drop(driver); + assert_eq!(rx.recv().await, None); + } + tokio::task::yield_now().await; + assert_eq!(active(&fake), 0); + } +} + +#[tokio::test(start_paused = true)] +async fn an_idle_map_keeps_no_periodic_clock_or_io_activity() { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let calls = fake.calls.load(Ordering::SeqCst); + let memo_calls = fake.memo_calls.load(Ordering::SeqCst); + for _ in 0..10 { + tokio::time::advance(TICK).await; + tokio::task::yield_now().await; + } + assert_eq!(fake.calls.load(Ordering::SeqCst), calls); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), memo_calls); + assert_eq!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)); + checked(&changes, 0); + driver.cancel(); + assert_eq!(rx.recv().await, None); +} + +#[tokio::test(start_paused = true)] +async fn comparison_also_targets_use_the_original_results_without_fetching_them() { + let results = BOTH.replace( + "</main>", + concat!( + "<article><h2><a href='https://reddit.com/r/example'>A discussion</a></h2></article>", + "<article><h2><a href='http://reviews.example/review'>A review</a></h2></article>", + "</main>" + ), + ); + let fake = Arc::new(acme(Fake::new(html(&results)))); + let (driver, mut rx) = start(&fake, request("acme vs other")); + let Some(Change::FirstLayer { also, .. }) = rx.recv().await else { + panic!("expected results") + }; + assert_eq!( + also.iter() + .map(|item| item.host.as_str()) + .collect::<Vec<_>>(), + ["reddit.com", "reviews.example"] + ); + assert_eq!( + driver + .target(0, &Target::Also { index: 0 }) + .unwrap() + .host_str(), + Some("reddit.com") + ); + assert_eq!(driver.target(1, &Target::Also { index: 1 }), None); + assert_eq!(driver.target(0, &Target::Also { index: 2 }), None); + let _ = rest(&mut rx).await; + assert!(!fake + .seen() + .fetches + .iter() + .any(|path| path.starts_with("reddit.com") || path.starts_with("reviews.example"))); } diff --git a/crates/zephium-map-driver/src/lib.rs b/crates/zephium-map-driver/src/lib.rs index 987de02af..e3b210631 100644 --- a/crates/zephium-map-driver/src/lib.rs +++ b/crates/zephium-map-driver/src/lib.rs @@ -7,7 +7,7 @@ mod page; mod public; pub mod wire; -pub use driver::{Counts, Driver, MapRequest, CHANGE_BUFFER, TICK}; +pub use driver::{Counts, Driver, MapRequest, CHANGE_BUFFER, MAX_WAITING_OPENS, TICK}; pub use io::{Clock, FetchRequest, Fetcher, Io, Reading, ResultsPage, ResultsSource, SystemClock}; pub use memo::{ Memo, MemoryMemo, MAX_MEMO_BYTES, MAX_MEMO_PLACES, MAX_MEMO_PROFILES, MAX_PROFILE_KEY_BYTES, diff --git a/crates/zephium-map-driver/src/wire.rs b/crates/zephium-map-driver/src/wire.rs index 725f382a9..7a64bcf46 100644 --- a/crates/zephium-map-driver/src/wire.rs +++ b/crates/zephium-map-driver/src/wire.rs @@ -6,8 +6,9 @@ use zephium_map::{ compare, query::{self, SectionRole}, results::{self, FirstLayer, Profile}, + robots::Robots, session::{self, ReadState}, - site, + site, PageKey, PlaceKey, SiteKey, }; pub const MAX_TEXT_BYTES: usize = 300; @@ -15,6 +16,8 @@ pub const MAX_PATH_CHARS: usize = 128; pub const MAX_SECTIONS: usize = 32; pub const MAX_CHILDREN: usize = 12; pub const MAX_SOCIAL: usize = 10; +pub const MAX_ALSO: usize = 8; +pub const MAX_HOST_BYTES: usize = 253; pub const MAX_ROWS: usize = 64; pub const ID_BYTES: usize = 16; @@ -57,6 +60,26 @@ pub enum StartRefusal { Invalid, } +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum OpenRefusal { + NoPlace, + UnknownEntry, + NotOpenable, + TooManyWaiting, + Cancelled, +} + +impl From<session::OpenRefusal> for OpenRefusal { + fn from(refusal: session::OpenRefusal) -> Self { + match refusal { + session::OpenRefusal::UnknownEntry => Self::UnknownEntry, + session::OpenRefusal::NotOpenable => Self::NotOpenable, + } + } +} + #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "ipc-types", derive(specta::Type))] #[serde(rename_all = "snake_case")] @@ -119,6 +142,23 @@ pub struct Official { pub site: String, } +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(rename_all = "snake_case")] +pub enum AlsoKind { + Page, + Discussion, + Video, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +pub struct Also { + pub title: String, + pub host: String, + pub kind: AlsoKind, +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "ipc-types", derive(specta::Type))] pub struct Entry { @@ -130,6 +170,9 @@ pub struct Entry { #[serde(default, skip_serializing_if = "Option::is_none")] pub group: Option<String>, pub off_site: bool, + pub open: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option<String>, pub path: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub read: Option<Read>, @@ -191,6 +234,14 @@ impl From<session::EndOutcome> for Outcome { } } +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum OpenResult { + Read, + Refused { failure: Failure }, +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "ipc-types", derive(specta::Type))] #[serde(tag = "type", rename_all = "snake_case")] @@ -200,6 +251,7 @@ pub enum Change { official: Option<Official>, social: Vec<Network>, organic: u8, + also: Vec<Also>, }, Place { seq: u32, @@ -223,6 +275,12 @@ pub enum Change { outcome: Outcome, elapsed_ms: u32, }, + Opened { + seq: u32, + slot: u8, + id: String, + result: OpenResult, + }, } impl Change { @@ -232,7 +290,8 @@ impl Change { | Self::Place { seq, .. } | Self::PlaceFailed { seq, .. } | Self::Compare { seq, .. } - | Self::End { seq, .. } => *seq, + | Self::End { seq, .. } + | Self::Opened { seq, .. } => *seq, } } } @@ -244,6 +303,7 @@ pub enum Target { Entry { id: String }, Site, Social { network: Network }, + Also { index: u8 }, } #[derive(Default)] @@ -259,6 +319,7 @@ impl Targets { Target::Entry { id } => self.entries.get(id), Target::Site => self.site.as_ref(), Target::Social { network } => self.social.get(network), + Target::Also { .. } => None, }?; (url.scheme() == "https").then(|| url.clone()) } @@ -343,6 +404,16 @@ fn address(entry: &site::Entry) -> Url { url } +fn hostname(url: &Url) -> Option<String> { + let host = url.domain()?.trim_end_matches('.'); + (!host.is_empty() + && host.len() <= MAX_HOST_BYTES + && host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))) + .then(|| host.to_ascii_lowercase()) +} + fn networks(profiles: &[Profile], social: &mut BTreeMap<Network, Url>) -> Vec<Network> { let mut out = Vec::new(); for profile in profiles { @@ -361,6 +432,8 @@ fn networks(profiles: &[Profile], social: &mut BTreeMap<Network, Url>) -> Vec<Ne fn entry( source: &site::Entry, child: bool, + place_host: Option<&str>, + open: bool, seen: &mut BTreeSet<String>, targets: &mut BTreeMap<String, Url>, ) -> Option<Entry> { @@ -388,7 +461,7 @@ fn entry( } else { let mut rest = source.children.iter(); for next in rest.by_ref() { - if let Some(projected) = entry(next, true, seen, targets) { + if let Some(projected) = entry(next, true, place_host, false, seen, targets) { children.push(projected); if children.len() == MAX_CHILDREN { break; @@ -404,6 +477,8 @@ fn entry( role: source.role.map(Role::from), group: source.group.as_deref().and_then(shown), off_site: source.off_site, + open, + host: hostname(source.key.as_url()).filter(|host| Some(host.as_str()) != place_host), path, read: source.read.map(Read::from), children, @@ -411,7 +486,10 @@ fn entry( }) } -pub(crate) fn place(source: &site::Place) -> (Place, Targets) { +pub(crate) fn place( + source: &site::Place, + robots: Option<&BTreeMap<String, Robots>>, +) -> (Place, Targets) { let mut targets = Targets { site: Some(source.entry.as_url().clone()), ..Targets::default() @@ -420,11 +498,20 @@ pub(crate) fn place(source: &site::Place) -> (Place, Targets) { let mut ordered: Vec<_> = source.sections.iter().collect(); ordered.sort_by_key(|e| e.tier != site::Tier::Primary); let mut sections = Vec::new(); + let host = hostname(source.entry.as_url()); for section in ordered { if sections.len() == MAX_SECTIONS { break; } - if let Some(projected) = entry(section, false, &mut seen, &mut targets.entries) { + let open = robots.is_some_and(|rules| source.entry_openable(&section.id, rules)); + if let Some(projected) = entry( + section, + false, + host.as_deref(), + open, + &mut seen, + &mut targets.entries, + ) { sections.push(projected); } } @@ -451,7 +538,15 @@ pub(crate) fn place(source: &site::Place) -> (Place, Targets) { (place, targets) } -pub(crate) fn first_layer(layer: &FirstLayer) -> (Option<Official>, Vec<Network>, u8) { +pub(crate) struct Layer { + pub official: Option<Official>, + pub social: Vec<Network>, + pub organic: u8, + pub also: Vec<Also>, + pub targets: Vec<Url>, +} + +pub(crate) fn first_layer(layer: &FirstLayer, places: &[(&PlaceKey, SiteKey)]) -> Layer { let official = layer.organic.iter().find_map(|hit| { let site = text(hit.official.as_ref()?.site.as_str()); Some(Official { @@ -459,9 +554,73 @@ pub(crate) fn first_layer(layer: &FirstLayer) -> (Option<Official>, Vec<Network> site, }) }); - let social = networks(&layer.social, &mut BTreeMap::new()); + let mut social_targets = BTreeMap::new(); + let social = networks(&layer.social, &mut social_targets); let organic = u8::try_from(layer.organic.len()).unwrap_or(u8::MAX); - (official, social, organic) + let mut seen: BTreeSet<_> = social_targets + .values() + .filter_map(|url| Some(PageKey::from_url(url).ok()?.page_match())) + .collect(); + let (also, targets) = layer + .organic + .iter() + .filter(|hit| hit.official.is_none()) + .map(|hit| { + ( + &hit.url, + &hit.title, + if hit.discussion { + AlsoKind::Discussion + } else { + AlsoKind::Page + }, + ) + }) + .chain( + layer + .video + .iter() + .map(|hit| (&hit.url, &hit.title, AlsoKind::Video)), + ) + .filter_map(|(url, title, kind)| { + let host = hostname(url)?; + let key = PageKey::from_url(url).ok()?.page_match(); + if places.iter().any(|(place, site)| { + if place.tenant.is_some() { + PlaceKey::from_url(url).as_ref() == Some(*place) + } else { + SiteKey::from_url(url).as_ref() == Some(site) + } + }) || !seen.insert(key) + { + return None; + } + let title = shown(title) + .filter(|text| { + !text.split_whitespace().any(|word| { + word.starts_with('/') + || word + .split_once('/') + .is_some_and(|(head, _)| head.contains('.')) + }) + }) + .unwrap_or_else(|| host.clone()); + Some((Also { title, host, kind }, url.clone())) + }) + .take(MAX_ALSO) + .unzip(); + Layer { + official, + social, + organic, + also, + targets, + } +} + +pub(crate) fn also_target(urls: &[Url], index: u8) -> Option<Url> { + let url = urls.get(usize::from(index))?; + (url.scheme() == "https").then(|| url.clone()) } pub(crate) fn rows(source: &[compare::Row], left: &Targets, right: &Targets) -> Vec<Row> { diff --git a/crates/zephium-map-driver/src/wire/tests.rs b/crates/zephium-map-driver/src/wire/tests.rs index bd3cdca2d..8a78cd714 100644 --- a/crates/zephium-map-driver/src/wire/tests.rs +++ b/crates/zephium-map-driver/src/wire/tests.rs @@ -3,6 +3,10 @@ use serde_json::{json, Value}; use std::collections::BTreeMap; use zephium_map::{site::SiteInputs, Doc, DocLimits}; +fn long_host() -> String { + format!("{}example.com", "ab.".repeat(MAX_HOST_BYTES / 3)) +} + fn base() -> Value { let url = Url::parse("https://acme.com/").unwrap(); let doc = Doc::from_html( @@ -101,6 +105,18 @@ fn hostile() -> site::Place { &format!("https://acme.com/{}", "p".repeat(300)), "Primary", )); + sections.push(section( + &id(9), + "Guide", + "https://docs.acme.com/guide", + "Primary", + )); + sections.push(section( + &id(10), + "Oversized host", + &format!("https://{}/guide", long_host()), + "Primary", + )); let mut parent = section(&id(7), "Parent", "https://acme.com/parent", "Primary"); let mut children = Vec::new(); for n in 0..20 { @@ -150,7 +166,11 @@ fn entries(place: &Place) -> impl Iterator<Item = &Entry> { #[test] fn the_projection_bounds_a_hostile_place() { let source = hostile(); - let (projected, targets) = place(&source); + let rules = BTreeMap::from([( + "https://acme.com".to_owned(), + Robots::parse("User-agent: *\nDisallow: /parent"), + )]); + let (projected, targets) = place(&source, Some(&rules)); let json = serde_json::to_string(&projected).unwrap(); for banned in [ "http", "://", "?", "token", "hidden", "evil", "frag", "secret", @@ -186,6 +206,7 @@ fn the_projection_bounds_a_hostile_place() { .unwrap(); assert_eq!(parent.children.len(), MAX_CHILDREN); assert!(parent.more && parent.children[0].more); + assert!(!parent.open && parent.children.iter().all(|child| !child.open)); assert!(!ids.contains(&id(999)) && !ids.contains(&id(8))); let label = |n: usize| { entries(&projected) @@ -196,6 +217,12 @@ fn the_projection_bounds_a_hostile_place() { assert_eq!(label(3).as_deref(), Some("/b")); assert!(!json.contains("Duplicate") && !json.contains("Upper") && !json.contains("Bad")); let long = entries(&projected).find(|e| e.id == id(1)).unwrap(); + assert!(long.open && long.host.is_none()); + let guide = entries(&projected).find(|e| e.id == id(9)).unwrap(); + assert!(guide.open); + assert_eq!(guide.host.as_deref(), Some("docs.acme.com")); + let oversized = entries(&projected).find(|e| e.id == id(10)).unwrap(); + assert!(!oversized.open && oversized.host.is_none()); assert!(long.label.len() > MAX_TEXT_BYTES - 2); assert_eq!(long.group.as_ref().map(String::len), Some(MAX_TEXT_BYTES)); let redirect = entries(&projected).find(|e| e.id == id(5)).unwrap(); @@ -209,6 +236,93 @@ fn the_projection_bounds_a_hostile_place() { Some("https://acme.com/long?token=secret#frag".into()) ); assert_eq!(targets.resolve(&Target::Entry { id: id(999) }), None); + + let organic = |raw: &str, title: String, discussion: bool, rank: u32| { + let url = Url::parse(raw).unwrap(); + results::Organic { + key: PageKey::from_url(&url).unwrap(), + url, + title, + rank, + discussion, + snippet: Some("secret snippet".into()), + official: None, + sitelinks: Vec::new(), + } + }; + let mut layer = FirstLayer { + social: source.social.clone(), + organic: vec![ + organic("https://acme.com/official", "Official".into(), false, 1), + organic("https://github.com/acme", "Social profile".into(), false, 2), + organic( + &format!("https://{}/oversized", long_host()), + "Oversized".into(), + false, + 3, + ), + organic( + "http://plain.example/hidden", + "https://abuse.example/secret".into(), + false, + 4, + ), + organic( + "https://FORUM.example/hidden", + format!("Line\u{7}\nHere {}", "é".repeat(MAX_TEXT_BYTES)), + true, + 5, + ), + ], + video: vec![results::Link { + url: Url::parse("https://video.example/movie").unwrap(), + title: "Film".into(), + }], + ..FirstLayer::default() + }; + let places = [(&source.key, source.site.clone())]; + let preview = first_layer(&layer, &places); + assert_eq!( + preview + .also + .iter() + .map(|result| result.kind) + .collect::<Vec<_>>(), + [AlsoKind::Page, AlsoKind::Discussion, AlsoKind::Video] + ); + for rank in 6..6 + MAX_ALSO { + layer.organic.push(organic( + &format!("https://result.example/{rank}"), + "Result".into(), + false, + rank as u32, + )); + } + let projected = first_layer(&layer, &places); + assert_eq!(projected.also.len(), MAX_ALSO); + assert_eq!(projected.also[0].title, "plain.example"); + assert_eq!(projected.also[1].host, "forum.example"); + assert!(projected.also[1].title.starts_with("Line Here ")); + assert!(projected.also[1].title.len() <= MAX_TEXT_BYTES); + assert_eq!(also_target(&projected.targets, 0), None); + assert_eq!( + also_target(&projected.targets, 1).unwrap().host_str(), + Some("forum.example") + ); + assert_eq!(also_target(&projected.targets, MAX_ALSO as u8), None); + let json = serde_json::to_string(&projected.also).unwrap(); + for banned in [ + "http", + "://", + "hidden", + "secret", + "video.example", + "github.com", + "acme.com", + ] { + assert!(!json.contains(banned)); + } + assert!(!json.contains("\\u0007") && !json.contains("\\n")); } #[test] @@ -240,7 +354,7 @@ fn targets_open_only_known_https_addresses() { {"basis": "Navigation", "network": "GitHub", "url": "https://github.com/acme"}, {"basis": "Navigation", "network": "Reddit", "url": "http://reddit.com/r/acme"}, ]); - let (_, targets) = place(&engine(value)); + let (_, targets) = place(&engine(value), None); let open = |t: Target| targets.resolve(&t).map(|u| u.to_string()); assert_eq!( open(Target::Entry { id: id(1) }), @@ -262,7 +376,7 @@ fn targets_open_only_known_https_addresses() { for network in [Network::Reddit, Network::Discord] { assert_eq!(open(Target::Social { network }), None); } - let (_, targets) = place(&engine(base())); + let (_, targets) = place(&engine(base()), None); assert_eq!( targets.resolve(&Target::Site).map(|u| u.to_string()), Some("https://acme.com/".into()) @@ -271,7 +385,7 @@ fn targets_open_only_known_https_addresses() { #[test] fn rows_keep_only_projected_ids_and_are_capped() { - let (_, left) = place(&engine(base())); + let (_, left) = place(&engine(base()), None); let known = base()["sections"][0]["id"].as_str().unwrap().to_owned(); let entry_id = |s: &str| -> Option<site::EntryId> { serde_json::from_value(json!(s)).ok() }; let row = |label: &str, left: &str, right: &str| compare::Row { diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index 2baed103c..b8bba4652 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -132,6 +132,8 @@ struct SiteState { clean: bool, stale: bool, external: BTreeMap<PageMatch, PageKey>, + asked: BTreeSet<site::EntryId>, + memo: Option<SiteMemo>, } impl SiteState { fn new(seed: Seed) -> Self { @@ -156,6 +158,8 @@ impl SiteState { clean: true, stale: false, external: BTreeMap::new(), + asked: BTreeSet::new(), + memo: None, } } } @@ -179,7 +183,8 @@ impl SiteState { } pub struct Session { cfg: Config, - query: QueryRead, + query: Option<QueryRead>, + opening: Option<Opening>, sequence: u32, elapsed: Duration, finished: bool, @@ -197,8 +202,94 @@ pub struct Session { first_passage: Option<Passage>, passages: Vec<Passage>, } + +#[derive(Clone, serde::Serialize)] +pub struct HeldSite { + payload: SitePayload, + memo: Option<SiteMemo>, +} + +impl HeldSite { + pub fn place(&self) -> &Place { + &self.payload.place + } + + pub fn robots(&self) -> &BTreeMap<String, Robots> { + &self.payload.robots + } + + pub fn check_open(&self, id: &str) -> Result<(), OpenRefusal> { + self.open_index(id).map(|_| ()) + } + + fn open_index(&self, id: &str) -> Result<usize, OpenRefusal> { + let place = self.place(); + if let Some(index) = place.sections.iter().position(|e| e.id.as_str() == id) { + return place + .entry_openable(&place.sections[index].id, self.robots()) + .then_some(index) + .ok_or(OpenRefusal::NotOpenable); + } + if place + .sections + .iter() + .flat_map(|e| &e.children) + .any(|e| e.id.as_str() == id) + { + return Err(OpenRefusal::NotOpenable); + } + Err(OpenRefusal::UnknownEntry) + } + + fn bounded(mut self) -> Option<Self> { + let place = self.place(); + if place.sections.len() > site::MAX_SECTIONS + || !place.sections.iter().all(|entry| { + entry.children.len() <= site::MAX_CHILDREN + && entry.children.iter().all(|child| child.children.is_empty()) + }) + || place.check_ids().is_err() + { + return None; + } + if !self.fits() { + self.memo = None; + if !self.fits() { + return None; + } + } + Some(self) + } + + fn fits(&mut self) -> bool { + // Reserve space for the longest serialized read state on every top-level row. + let state = ReadState::Skipped { + budget: Budget::HostConcurrent, + }; + let sections = &mut self.payload.place.sections; + let reads: Vec<_> = sections + .iter_mut() + .map(|entry| entry.read.replace(state)) + .collect(); + let fits = memo::encode_bounded(self).is_ok(); + for (entry, read) in self.payload.place.sections.iter_mut().zip(reads) { + entry.read = read; + } + fits + } +} + +struct Opening { + held: HeldSite, + slot: u8, + index: usize, + confidence: Confidence, + stale: bool, + clean: bool, +} + impl Session { - pub fn start(mut cfg: Config, query_text: &str) -> Result<(Self, Vec<Effect>), QueryError> { + pub fn start(cfg: Config, query_text: &str) -> Result<(Self, Vec<Effect>), QueryError> { let query = read_query(query_text)?; if cfg.custom_template.len() > crate::key::MAX_URL_BYTES { return Err(QueryError::Search); @@ -207,11 +298,105 @@ impl Session { .engine .configured_search(query_text, &cfg.custom_template) .ok_or(QueryError::Search)?; - cfg.tighten(); let kind = query.kind().clone(); - let mut s = Self { + let mut s = Self::new(cfg, Some(query)); + let mut out = Vec::new(); + s.emit(MapEvent::Kind { kind }, &mut out); + let id = s.id(); + s.pending.insert(id, Pending::Results); + s.counts(Phase::Results).started += 1; + out.push(Effect::LoadResults { id, url }); + Ok((s, out)) + } + + pub fn open( + cfg: Config, + held: HeldSite, + slot: u8, + id: &str, + confidence: Confidence, + stale: bool, + ) -> Result<(Self, Vec<Effect>), OpenRefusal> { + let index = held.open_index(id)?; + let url = held.place().sections[index].key.as_url().clone(); + let key = held.place().sections[index].key.page_match(); + let mut s = Self::new(cfg, None); + s.robots = held.robots().clone(); + s.opening = Some(Opening { + held, + slot, + index, + confidence, + stale, + clean: true, + }); + s.enqueue(Work::Section(usize::from(slot), key), url); + let mut out = Vec::new(); + s.schedule(&mut out); + Ok((s, out)) + } + + pub fn hold_place(&self, slot: u8, place: Place) -> Option<HeldSite> { + if let Some(open) = self.opening.as_ref().filter(|open| open.slot == slot) { + return Some(open.held.clone()); + } + let memo = self + .sites + .get(usize::from(slot)) + .and_then(Option::as_ref) + .and_then(|site| site.memo.clone()); + HeldSite { + payload: SitePayload { + robots: self.place_robots(&place), + place, + }, + memo, + } + .bounded() + } + + pub fn result_places(&self) -> impl Iterator<Item = (&PlaceKey, SiteKey)> { + self.sites + .iter() + .flatten() + .filter_map(|site| Some((&site.seed.site, SiteKey::from_url(&site.seed.url)?))) + } + + pub fn section_fetch(&self, id: Id) -> Option<(u8, &site::EntryId)> { + let Some(Pending::Job(Job { + work: Work::Section(slot, key), + .. + })) = self.pending.get(&id) + else { + return None; + }; + let site = self.sites.get(*slot)?.as_ref()?; + let entry = site.place.as_ref()?.sections.iter().find(|entry| { + entry.read == Some(ReadState::Queued) && site.discovered.get(&entry.id) == Some(key) + })?; + Some((*slot as u8, &entry.id)) + } + + fn place_robots(&self, place: &Place) -> BTreeMap<String, Robots> { + self.robots + .iter() + .filter(|(host, _)| { + Url::parse(host) + .ok() + .and_then(|url| SiteKey::from_url(&url)) + .as_ref() + == Some(&place.site) + }) + .map(|(host, rules)| (host.clone(), rules.clone())) + .collect() + } + + fn new(mut cfg: Config, query: Option<QueryRead>) -> Self { + cfg.tighten(); + Self { cfg, query, + opening: None, sequence: 0, elapsed: Duration::ZERO, finished: false, @@ -228,14 +413,7 @@ impl Session { articles: BTreeMap::new(), first_passage: None, passages: Vec::new(), - }; - let mut out = Vec::new(); - s.emit(MapEvent::Kind { kind }, &mut out); - let id = s.id(); - s.pending.insert(id, Pending::Results); - s.counts(Phase::Results).started += 1; - out.push(Effect::LoadResults { id, url }); - Ok((s, out)) + } } fn id(&mut self) -> Id { self.sequence += 1; @@ -281,6 +459,7 @@ impl Session { self.queue.push_back(Job { work, url }); } fn lookup(&mut self, side: usize, seed: Seed, out: &mut Vec<Effect>) { + let Some(query) = &self.query else { return }; self.unseeded[side] = None; if self.elapsed >= self.cfg.last_start { self.budget(Budget::LastStart); @@ -294,7 +473,7 @@ impl Session { return; } let site = seed.site.clone(); - let role = match self.query.kind() { + let role = match query.kind() { QueryKind::Place { section, .. } => section.map(|s| s.role), QueryKind::Compare { shared, .. } => shared.map(|s| s.role), _ => None, @@ -307,7 +486,7 @@ impl Session { entity, fresh: is_fresh, .. - } = self.query.kind() + } = query.kind() { fresh = *is_fresh; if let Some((brand, rest)) = entity.split_first() { @@ -359,10 +538,11 @@ impl Session { Seed::official(&self.read(doc, &read).ok()?) } fn results(&mut self, doc: Doc, out: &mut Vec<Effect>) -> Result<(), Failure> { + let query = self.query.as_ref().ok_or(Failure::Unreadable)?; let layer = match results::read_results_with_stats( self.cfg.engine, None, - &self.query, + query, &doc, &mut self.stats.results, ) { @@ -371,12 +551,12 @@ impl Session { }; let mut seeds = Vec::new(); let mut missing = Vec::new(); - match self.query.kind() { + match query.kind() { QueryKind::Instant | QueryKind::List => {} QueryKind::Place { .. } => { let seed = Seed::official(&layer).or_else(|| { let hit = layer.organic.first()?; - (self.query.confidence() == Confidence::High && !hit.sitelinks.is_empty()) + (query.confidence() == Confidence::High && !hit.sitelinks.is_empty()) .then(|| Seed::new(hit, Confidence::Low)) .flatten() }); @@ -400,19 +580,13 @@ impl Session { .organic .iter() .find(|hit| hit.key.page_match() == f.cites.page_match()) - .and_then(|r| passage::featured(&self.query, f, r)); + .and_then(|r| passage::featured(query, f, r)); } let count = self.cfg.result_pages as usize; - if layer.organic.len() > count { - self.budget(Budget::ResultPages); - } - for (i, r) in layer.organic.iter().take(count).enumerate() { - self.enqueue(Work::Passage(i), r.url.clone()); - } if let Some(hit) = layer.organic.first() { if let Some(site) = SiteKey::from_url(&hit.url) { let name = site.as_str().split('.').next().unwrap_or_default(); - if self.query.terms().iter().any(|w| { + if query.terms().iter().any(|w| { w.trim_end_matches('?') == site.as_str() || !hit.sitelinks.is_empty() && w == name }) { @@ -422,6 +596,12 @@ impl Session { } } } + if layer.organic.len() > count { + self.budget(Budget::ResultPages); + } + for (i, r) in layer.organic.iter().take(count).enumerate() { + self.enqueue(Work::Passage(i), r.url.clone()); + } } } self.emit(MapEvent::FirstLayer { layer }, out); @@ -467,7 +647,7 @@ impl Session { } state.stale = stale; let Ok(place) = site::with_results( - m.payload.place, + m.payload.place.clone(), &state.seed.links, state.section_hint.as_ref(), state.requested.as_ref(), @@ -481,19 +661,22 @@ impl Session { && state.section_hint.is_none() && (state.requested.is_none() || place.focus.is_some()); state.complete = complete; - self.emit_place(i, place, stale, confidence, complete, out); if complete { if let Some(pos) = shared_passage { self.queue.push_back(Job { work: Work::Passage(pos), - url, + url: url.clone(), }); } - for (host, rules) in m.payload.robots { - if !self.pending.values().any(|p|matches!(p,Pending::Job(j) if j.work==Work::Robots && origin(&j.url)==host)){ - self.robots.entry(host).or_insert(rules); + for (host, rules) in &m.payload.robots { + if !self.pending.values().any(|p|matches!(p,Pending::Job(j) if j.work==Work::Robots && origin(&j.url)==*host)){ + self.robots.entry(host.clone()).or_insert_with(|| rules.clone()); } } + state.memo = Some(m); + } + self.emit_place(i, place, stale, confidence, complete, out); + if complete { return; } } else if supplied { @@ -516,6 +699,9 @@ impl Session { } fn update_passages(&mut self, out: &mut Vec<Effect>) { + let Some(query) = self.query.as_ref() else { + return; + }; let mut ordered: BTreeMap<_, _> = self.articles.iter().map(|(pos, doc)| (*pos, doc)).collect(); for site in self.sites.iter().flatten() { @@ -525,7 +711,7 @@ impl Session { } let pages: Vec<_> = ordered.into_values().collect(); let mut passages: Vec<_> = self.first_passage.clone().into_iter().collect(); - for p in passage::read_passages(&self.query, &pages) { + for p in passage::read_passages(query, &pages) { if !passages .iter() .any(|f| f.source.page_match() == p.source.page_match()) @@ -599,12 +785,23 @@ impl Session { return; } } - let candidates: BTreeSet<_> = place - .fetch_sections() - .into_iter() - .map(|e| e.id.clone()) - .collect(); + let candidates: BTreeSet<_> = match self.cfg.sections { + Sections::All => place + .fetch_sections() + .into_iter() + .map(|e| e.id.clone()) + .collect(), + Sections::Asked => { + state + .asked + .extend(place.asked_sections(doc.page()).map(|e| e.id.clone())); + state.asked.clone() + } + }; for entry in &mut place.sections { + if self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) { + continue; + } let discovered = state .discovered .entry(entry.id.clone()) @@ -634,8 +831,11 @@ impl Session { let Some(place) = state.place.as_ref() else { return; }; - let keys: Vec<_> = place - .fetch_sections() + let entries: Vec<_> = match self.cfg.sections { + Sections::All => place.fetch_sections(), + Sections::Asked => place.sections.iter().collect(), + }; + let keys: Vec<_> = entries .into_iter() .filter(|e| e.read == Some(ReadState::Queued)) .map(|e| e.key.clone()) @@ -732,6 +932,10 @@ impl Session { match input { Input::Cancel => { self.stats.cancelled = true; + if self.opening.is_some() { + self.done(&mut out); + return out; + } for i in 0..self.sites.len() { let Some(state) = self.sites[i].as_mut() else { self.close_slot(i, Failure::Cancelled, &mut out); @@ -939,6 +1143,48 @@ impl Session { self.emit_place(i, place, s.stale, s.seed.confidence, true, out); } } + + fn finish_open(&mut self, out: &mut Vec<Effect>) { + let Some(open) = self.opening.as_ref() else { + return; + }; + let robots = self.place_robots(open.held.place()); + let Some(open) = self.opening.as_mut() else { + return; + }; + let mut updated = open.held.clone(); + updated.payload.robots = robots; + if let Some(updated) = updated.bounded() { + open.held = updated; + } + let remember = if open.clean && self.stats.budgets.is_empty() { + open.held.memo.clone().and_then(|mut memo| { + let mut updated = open.held.clone(); + memo.payload.robots.clone_from(&open.held.payload.robots); + let bytes = memo.encode().ok()?; + let site = memo.payload.place.key.clone(); + updated.memo = Some(memo); + let retained = updated.bounded()?; + retained.memo.as_ref()?; + open.held = retained; + Some((site, bytes)) + }) + } else { + None + }; + let (slot, place, stale, confidence) = ( + open.slot, + open.held.place().clone(), + open.stale, + open.confidence, + ); + self.emit_place(usize::from(slot), place, stale, confidence, true, out); + if let Some((site, memo)) = remember { + let id = self.id(); + out.push(Effect::RememberSite { id, site, memo }); + } + self.done(out); + } fn finish(&mut self, out: &mut Vec<Effect>) { if self.elapsed >= self.cfg.elapsed { let jobs: Vec<_> = self @@ -951,6 +1197,9 @@ impl Session { .chain(self.queue.drain(..)) .collect(); for job in jobs { + if self.opening.is_some() && matches!(job.work, Work::Section(..)) { + self.refused(Phase::Section, Failure::Timeout); + } self.set_read( &job, ReadState::Skipped { @@ -960,12 +1209,16 @@ impl Session { ); } } - if matches!(self.query.kind(), QueryKind::Passage { kind: _ }) - && self.sites.iter().any(Option::is_some) + if self.opening.is_some() { + self.finish_open(out); + return; + } + let kind = self.query.as_ref().map(|q| q.kind().clone()); + if matches!(kind, Some(QueryKind::Passage { .. })) && self.sites.iter().any(Option::is_some) { self.update_passages(out); } - if matches!(self.query.kind(), QueryKind::Passage { kind: _ }) + if matches!(kind, Some(QueryKind::Passage { .. })) && self.passages.is_empty() && self .stats @@ -982,7 +1235,9 @@ impl Session { } for i in 0..self.sites.len() { self.close_slot(i, Failure::Limit, out); - let Some(s) = &self.sites[i] else { continue }; + let Some(s) = &mut self.sites[i] else { + continue; + }; if s.clean && self.stats.budgets.is_empty() && s.place @@ -1012,13 +1267,18 @@ impl Session { read_at: self.cfg.now, payload: SitePayload { place, robots }, }; - if let Ok(memo) = memo.encode() { + if let Ok(bytes) = memo.encode() { + s.memo = Some(memo); let id = self.id(); - out.push(Effect::RememberSite { id, site, memo }); + out.push(Effect::RememberSite { + id, + site, + memo: bytes, + }); } } } - if let QueryKind::Compare { shared, .. } = self.query.kind() { + if let Some(QueryKind::Compare { shared, .. }) = kind { let place = |i: usize| self.sites[i].as_ref()?.place.as_ref(); if let Some((l, r)) = place(0).zip(place(1)) { self.emit( @@ -1032,7 +1292,7 @@ impl Session { self.done(out); } } -fn origin(url: &Url) -> String { +pub(crate) fn origin(url: &Url) -> String { url.origin().ascii_serialization() } mod scheduler; diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index 44fbc7cc8..72df80b8f 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -92,23 +92,27 @@ impl SiteMemo { return Err(MemoError::Version); } self.validate(&self.payload.place.key)?; - let mut bytes = Vec::new(); - struct Limited<'a>(&'a mut Vec<u8>); - impl std::io::Write for Limited<'_> { - fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { - if b.len() > MAX_MEMO_BYTES - self.0.len() { - return Err(std::io::ErrorKind::FileTooLarge.into()); - } - self.0.extend_from_slice(b); - Ok(b.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) + encode_bounded(self) + } +} + +pub(super) fn encode_bounded(value: &impl Serialize) -> Result<Vec<u8>, MemoError> { + let mut bytes = Vec::new(); + struct Limited<'a>(&'a mut Vec<u8>); + impl std::io::Write for Limited<'_> { + fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { + if b.len() > MAX_MEMO_BYTES - self.0.len() { + return Err(std::io::ErrorKind::FileTooLarge.into()); } + self.0.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) } - serde_json::to_writer(Limited(&mut bytes), self).map_err(|_| MemoError::Limit)?; - Ok(bytes) } + serde_json::to_writer(Limited(&mut bytes), value).map_err(|_| MemoError::Limit)?; + Ok(bytes) } fn valid_entry(e: &Entry, place: &Place, parent: Option<&Entry>) -> bool { let Some(site) = SiteKey::from_url(e.key.as_url()) else { diff --git a/crates/zephium-map/src/session/scheduler.rs b/crates/zephium-map/src/session/scheduler.rs index efe81ac3e..24b6b1d5f 100644 --- a/crates/zephium-map/src/session/scheduler.rs +++ b/crates/zephium-map/src/session/scheduler.rs @@ -130,7 +130,7 @@ impl Session { out, ); self.refused(phase, Failure::Robots); - if let Some(i) = job.work.side() { + if let Some(i) = job.work.side().filter(|_| self.opening.is_none()) { if let Some(s) = self.sites[i].as_mut() { s.denied = true; if !matches!( @@ -192,6 +192,31 @@ impl Session { } } pub(super) fn set_read(&mut self, job: &Job, read: ReadState, out: &mut Vec<Effect>) { + if let Some(open) = &mut self.opening { + if matches!(job.work, Work::Section(..)) { + let failure = match read { + ReadState::Refused { failure } => failure, + ReadState::Skipped { + budget: Budget::Elapsed, + } => Failure::Timeout, + _ => Failure::Limit, + }; + let place = &mut open.held.payload.place; + place.sections[open.index].read = Some(ReadState::Refused { failure }); + place.notes.robots_disallowed |= failure == Failure::Robots; + place.notes.truncated |= failure == Failure::Limit; + self.stats + .places + .entry(open.slot) + .or_default() + .section_page_truncated |= read + == ReadState::Refused { + failure: Failure::Limit, + }; + open.clean &= matches!(failure, Failure::Missing | Failure::Client); + } + return; + } match &job.work { Work::Section(i, key) => { if let Some(s) = &mut self.sites[*i] { @@ -281,13 +306,30 @@ impl Session { return Err(Failure::ContentType); } if let Work::Section(i, ref key) = job.work { - let other_tenant = self.sites[i].as_ref().is_some_and(|s| { - let place = s.place.as_ref().map_or(&s.seed.site, |p| &p.key); + let place_key = if let Some(open) = &self.opening { + Some(&open.held.place().key) + } else { + self.sites[i] + .as_ref() + .map(|s| s.place.as_ref().map_or(&s.seed.site, |p| &p.key)) + }; + let other_tenant = place_key.is_some_and(|place| { place.tenant.is_some() && PlaceKey::from_url(&r.final_url).as_ref() != Some(place) }); if other_tenant || SiteKey::from_url(&job.url) != SiteKey::from_url(&r.final_url) { - if let Some((s, landing)) = self.sites[i] + if let Some(open) = &mut self.opening { + open.held.payload.place.sections[open.index].off_site = true; + if let Ok(landing) = PageKey::from_url(&r.final_url) { + let mut updated = open.held.clone(); + let entry = &mut updated.payload.place.sections[open.index]; + entry.key = landing; + entry.locator = Locator::default(); + if let Some(updated) = updated.bounded() { + open.held = updated; + } + } + } else if let Some((s, landing)) = self.sites[i] .as_mut() .zip(PageKey::from_url(&r.final_url).ok()) { @@ -332,6 +374,15 @@ impl Session { } }; *self.stats.robots.entry(policy.outcome).or_default() += 1; + if let Some(open) = &mut self.opening { + let truncated = policy.truncated || policy.outcome == RobotsOutcome::Limit; + open.held.payload.place.notes.truncated |= truncated; + self.stats + .places + .entry(open.slot) + .or_default() + .robots_truncated |= truncated; + } if let Some(landing) = landing { self.robots.insert(landing, policy.clone()); } @@ -343,7 +394,7 @@ impl Session { if let Err(f) = applied { self.set_read(&job, ReadState::Refused { failure: f }, out); self.refused(phase, f); - if let Some(i) = side { + if let Some(i) = side.filter(|_| self.opening.is_none()) { if let Some(s) = self.sites[i].as_mut() { if f == Failure::Limit { s.cut.insert(phase); @@ -366,6 +417,52 @@ impl Session { self.stats.walls += 1; return Err(Failure::Challenge); } + if let Some(open) = &mut self.opening { + let (mut place, mut detail) = site::enrich_held( + open.held.place().clone(), + open.index, + &doc, + site::MAX_CHILDREN, + ); + place.check_ids().map_err(|_| Failure::Unreadable)?; + place.sections[open.index].read = Some(ReadState::Read); + let mut updated = open.held.clone(); + updated.payload.place = place; + if let Some(memo) = &mut updated.memo { + if let Some(index) = memo + .payload + .place + .sections + .iter() + .position(|e| e.key.page_match() == key) + { + let occupied = memo + .payload + .place + .sections + .iter() + .enumerate() + .filter(|(other, _)| *other != index) + .map(|(_, entry)| entry.children.len()) + .sum::<usize>(); + let cap = site::MAX_CHILDREN + .min(site::MAX_PLACE_CHILDREN.saturating_sub(occupied)); + let (place, _) = + site::enrich_held(memo.payload.place.clone(), index, &doc, cap); + if place.check_ids().is_ok() { + memo.payload.place = place; + } + } + } + open.held = updated.bounded().ok_or(Failure::Limit)?; + detail.robots_truncated = self + .stats + .places + .get(&open.slot) + .is_some_and(|prior| prior.robots_truncated); + self.stats.places.insert(open.slot, detail); + return Ok(()); + } if let Some(s) = self.sites[i].as_mut() { s.reads.insert(key, ReadState::Read); s.pages.insert( diff --git a/crates/zephium-map/src/session/types.rs b/crates/zephium-map/src/session/types.rs index b610001fa..ecb800c2a 100644 --- a/crates/zephium-map/src/session/types.rs +++ b/crates/zephium-map/src/session/types.rs @@ -18,6 +18,13 @@ pub const LAST_START: Duration = Duration::from_secs(10); pub const FETCH_TIMEOUT: Duration = Duration::from_secs(4); pub const MAX_MEDIA_TYPE_BYTES: usize = 256; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sections { + #[default] + All, + Asked, +} + #[derive(Clone)] pub struct Config { /// The caller assigns a distinct namespace to each live search and reuses it for replay. @@ -33,6 +40,7 @@ pub struct Config { pub html_bytes: u32, pub xml_bytes: u32, pub text_bytes: u32, + pub sections: Sections, pub section_pages: u32, pub result_pages: u32, pub elapsed: Duration, @@ -54,6 +62,7 @@ impl Default for Config { html_bytes: MAX_HTML_BYTES as u32, xml_bytes: MAX_XML_BYTES as u32, text_bytes: MAX_TEXT_BYTES as u32, + sections: Sections::All, section_pages: MAX_SECTION_PAGES as u32, result_pages: MAX_RESULT_PAGES as u32, elapsed: MAX_ELAPSED, @@ -195,6 +204,12 @@ pub enum ReadState { Refused { failure: Failure }, Skipped { budget: Budget }, } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpenRefusal { + UnknownEntry, + NotOpenable, +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EndOutcome { Done, diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 204fc7f1f..3d805afb2 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -9,7 +9,7 @@ use crate::{ clip, site_profile, Link, Profile, CHALLENGE, MAX_SITELINKS, MAX_SOCIAL, TITLE_BYTES, }, robots::{Robots, RobotsOutcome, MAX_SITEMAPS}, - session::ReadState, + session::{origin, Failure, ReadState}, visible, Doc, Locator, PageKey, PlaceKey, SectionRole, SiteKey, }; use serde::{Deserialize, Serialize}; @@ -717,9 +717,42 @@ impl Place { entry.id == *focus || entry.children.iter().any(|child| child.id == *focus) }) } + pub fn entry_openable(&self, id: &EntryId, robots: &BTreeMap<String, Robots>) -> bool { + let Some(entry) = self.sections.iter().find(|entry| &entry.id == id) else { + return false; + }; + !entry.off_site + && SiteKey::from_url(entry.key.as_url()).as_ref() == Some(&self.site) + && (self.key.tenant.is_none() + || PlaceKey::from_url(entry.key.as_url()).as_ref() == Some(&self.key)) + && entry.key.page_match() != self.entry.page_match() + && matches!( + entry.read, + None | Some(ReadState::Queued | ReadState::Skipped { .. }) + | Some(ReadState::Refused { + failure: Failure::Timeout | Failure::Unavailable | Failure::Server, + }) + ) + && robots.get(&origin(entry.key.as_url())).is_none_or(|rules| { + rules.allows( + &entry.key.as_url()[url::Position::BeforePath..url::Position::AfterQuery], + ) + }) + } + pub(crate) fn read_priority(&self, entry: &Entry) -> (bool, bool) { (!self.focuses(entry), entry.role.is_none()) } + pub(crate) fn asked_sections<'a>( + &'a self, + landing: &'a Url, + ) -> impl Iterator<Item = &'a Entry> { + self.sections.iter().filter(move |entry| { + entry.key.page_match() != self.entry.page_match() + && !crate::key::same_page(entry.key.as_url(), landing) + && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) + }) + } pub(crate) fn fetch_sections(&self) -> Vec<&Entry> { let mut entries: Vec<_> = self .sections @@ -892,6 +925,71 @@ impl Entry { } } +impl Build<'_> { + fn enrich_section(&mut self, index: usize, page: &Doc) { + let (mut preferred, others): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.sections[index].children) + .into_iter() + .partition(|e| e.sources.first() == Some(&Source::MenuGroup)); + self.sections[index].children.append(&mut preferred); + self.section_page(index, page); + for child in others { + self.child(index, child); + } + } +} + +pub(crate) fn enrich_held( + place: Place, + index: usize, + page: &Doc, + child_cap: usize, +) -> (Place, PlaceStats) { + let mut build = Build { + place, + index: Default::default(), + requested: None, + stats: PlaceStats::default(), + }; + let focus = build.focus.clone(); + let focused_child = build.sections[index] + .children + .iter() + .find(|entry| Some(&entry.id) == focus.as_ref()) + .cloned(); + build.enrich_section(index, page); + let siblings: BTreeSet<_> = build + .sections + .iter() + .map(|entry| (entry.key.page_match(), entry.locator.fragment())) + .chain(std::iter::once((build.entry.page_match(), None))) + .collect(); + let section = &mut build.sections[index]; + section.children.retain(|child| { + focus.as_ref() == Some(&child.id) + || child.sources.contains(&Source::Heading) + || !siblings.contains(&(child.key.page_match(), child.locator.fragment())) + }); + if let Some(focused) = focused_child { + if !section.children.iter().any(|e| e.id == focused.id) { + section.children.push(focused); + } + } + while section.children.len() > child_cap { + let Some(index) = section + .children + .iter() + .rposition(|e| Some(&e.id) != focus.as_ref()) + else { + break; + }; + section.children.remove(index); + section.more = section.more.saturating_add(1); + } + build.notes.truncated |= build.stats.truncated() || build.sections[index].more > 0; + (build.place, build.stats) +} + pub(crate) fn with_results( place: Place, links: &[Link], @@ -1038,15 +1136,7 @@ pub(crate) fn read_site_for( }) .collect(); for (i, page) in page_sections { - let (mut preferred, others): (Vec<_>, Vec<_>) = - std::mem::take(&mut place.sections[i].children) - .into_iter() - .partition(|e| e.sources.first() == Some(&Source::MenuGroup)); - place.sections[i].children.append(&mut preferred); - place.section_page(i, page); - for c in others { - place.child(i, c); - } + place.enrich_section(i, page); } place.stats.section_page_truncated |= inputs.pages.len() > MAX_SECTION_PAGES; if let Some(robots) = inputs.robots { diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index 8025b7685..a624a6e07 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -84,6 +84,7 @@ struct Run { conf: Vec<Confidence>, memo: Option<Vec<u8>>, passages: Vec<Vec<String>>, + held: Option<HeldSite>, } fn run( c: Config, @@ -100,6 +101,7 @@ fn run( conf: Vec::new(), memo: None, passages: Vec::new(), + held: None, }; let mut ids = BTreeSet::new(); while let Some(effect) = queue.pop_front() { @@ -173,6 +175,10 @@ fn run( } } assert_eq!(run.trace.last().unwrap(), "done"); + run.held = run + .places + .last() + .and_then(|place| session.hold_place(0, place.clone())); run } #[test] @@ -191,6 +197,426 @@ fn engine_only_and_no_site_evidence() { ); assert!(low.conf.iter().all(|c| *c == Confidence::Low) && !low.conf.is_empty()); } + +fn asked() -> Config { + Config { + sections: Sections::Asked, + ..cfg() + } +} + +fn section<'a>(place: &'a Place, label: &str) -> &'a Entry { + place + .sections + .iter() + .find(|entry| entry.label == label) + .unwrap() +} + +fn open(held: HeldSite, label: &str, cfg: Config) -> (Session, Vec<Effect>) { + let id = section(held.place(), label).id.clone(); + Session::open(cfg, held, 0, id.as_str(), Confidence::High, false) + .ok() + .unwrap() +} + +fn open_complete(mut session: Session, effects: Vec<Effect>) -> (HeldSite, bool, Stats) { + let mut events = effects.into_iter(); + let Some(Effect::Emit { + event: + MapEvent::Place { + place, + slot: 0, + complete: true, + .. + }, + .. + }) = events.next() + else { + panic!("open must emit one complete place"); + }; + let next = events.next().unwrap(); + let (remembered, end) = if matches!(next, Effect::RememberSite { .. }) { + (true, events.next().unwrap()) + } else { + (false, next) + }; + let Effect::Emit { + event: MapEvent::End { + outcome: EndOutcome::Done, + stats, + }, + .. + } = end + else { + panic!("open must end done"); + }; + assert!(events.next().is_none()); + assert!(session.handle(Input::Cancel).is_empty()); + (session.hold_place(0, place).unwrap(), remembered, stats) +} + +fn open_fetch(effects: &[Effect], path: &str) -> (Id, Url) { + let [Effect::Fetch { id, url, .. }] = effects else { + panic!("expected one read") + }; + assert_eq!(url.path(), path); + (*id, url.clone()) +} + +#[test] +fn asked_reads_only_focus_and_the_results_section_link() { + let unfocused = run(asked(), "acme", RESULT, |_| None); + assert!(!unfocused + .trace + .iter() + .any(|event| event.ends_with("/pricing") || event.ends_with("/news"))); + assert!(unfocused + .held + .unwrap() + .place() + .sections + .iter() + .all(|entry| entry.read.is_none())); + + let focused = run(asked(), "acme pricing", RESULT, |_| None); + let place = focused.held.as_ref().unwrap().place(); + assert_eq!(section(place, "Pricing").read, Some(ReadState::Read)); + assert_eq!(section(place, "News").read, None); + assert_eq!(focused.stats.phases[&Phase::Section].started, 1); + + let result = RESULT.replace( + "https://acme.com/'>Acme workshop", + "https://acme.com/guide'>Acme Docs", + ); + let both = run(asked(), "acme docs", &result, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<title>Acme</title><nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + )), + Effect::Fetch { id, url, .. } if matches!(url.path(), "/docs" | "/guide") => Some( + response(*id, url, "text/html", "<h2 id='intro'>Introduction</h2>"), + ), + _ => None, + }); + let place = both.held.as_ref().unwrap().place(); + assert_eq!(place.focus.as_ref(), Some(&section(place, "Docs").id)); + assert_eq!(section(place, "Docs").read, Some(ReadState::Read)); + assert!(section(place, "Acme Docs") + .sources + .contains(&Source::EngineResult)); + assert_eq!(section(place, "Acme Docs").read, Some(ReadState::Read)); + assert_eq!(section(place, "Pricing").read, None); + assert_eq!(both.stats.phases[&Phase::Section].started, 2); +} + +#[test] +fn open_from_a_fresh_memo_matches_the_eager_section_and_keeps_other_rows() { + let eager = run(cfg(), "acme", RESULT, |_| None); + let memo = run(asked(), "acme", RESULT, |_| None).memo.unwrap(); + let cached = run(asked(), "acme", RESULT, |effect| match effect { + Effect::LookupSite { id, .. } => Some(Input::Cache { + id: *id, + memo: Some(memo.clone()), + }), + _ => None, + }); + assert_eq!(cached.stats.fresh_memos, 1); + assert!(!cached.trace.iter().any(|event| event.starts_with("fetch"))); + let held = cached.held.unwrap(); + let entry_id = section(held.place(), "Pricing").id.clone(); + assert_eq!(held.check_open("unknown"), Err(OpenRefusal::UnknownEntry)); + assert!(matches!( + Session::open(asked(), held.clone(), 0, "unknown", Confidence::High, false), + Err(OpenRefusal::UnknownEntry) + )); + let news = serde_json::to_vec(section(held.place(), "News")).unwrap(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response( + id, + &url, + "text/html", + include_str!("fixtures/section-pricing.html"), + )); + let (opened, remembered, stats) = open_complete(session, effects); + assert!(remembered); + assert_eq!( + stats.phases.keys().copied().collect::<Vec<_>>(), + [Phase::Section] + ); + let pricing = section(opened.place(), "Pricing"); + let eager = section(eager.held.as_ref().unwrap().place(), "Pricing"); + assert_eq!(pricing.id, entry_id); + assert!(pricing.children == eager.children); + assert_eq!(pricing.more, eager.more); + assert_eq!( + serde_json::to_vec(section(opened.place(), "News")).unwrap(), + news + ); + assert_eq!( + opened.check_open(entry_id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + assert_eq!( + opened.check_open(pricing.children[0].id.as_str()), + Err(OpenRefusal::NotOpenable) + ); +} + +#[test] +fn opening_can_show_children_on_a_card_that_filled_its_discovery_budget() { + use zephium_map::site::{MAX_CHILDREN, MAX_PLACE_CHILDREN}; + let mut markup = String::from("<nav><a href='/pricing'>Pricing</a><ul>"); + for group in 0..MAX_PLACE_CHILDREN / MAX_CHILDREN { + markup.push_str(&format!( + "<li><a href='/group{group}'>Group {group}</a><ul>" + )); + for child in 0..MAX_CHILDREN { + markup.push_str(&format!( + "<li><a href='/group{group}/{child}'>Child {child}</a></li>" + )); + } + markup.push_str("</ul></li>"); + } + markup.push_str("</ul></nav>"); + let discovery = run(asked(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => { + Some(response(*id, url, "text/html", &markup)) + } + _ => None, + }); + let held = discovery.held.unwrap(); + let children = |place: &Place| { + place + .sections + .iter() + .map(|e| e.children.len()) + .sum::<usize>() + }; + assert_eq!(children(held.place()), MAX_PLACE_CHILDREN); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &url, "text/html", "<h2 id='plans'>Plans</h2>")); + let (opened, remembered, _) = open_complete(session, effects); + assert!(remembered); + assert_eq!(children(opened.place()), MAX_PLACE_CHILDREN + 1); + assert_eq!(section(opened.place(), "Pricing").children.len(), 1); +} + +#[test] +fn a_held_place_over_the_memo_ceiling_cannot_be_retained() { + let mut place = run(asked(), "acme", RESULT, |_| None).places.pop().unwrap(); + let (session, _) = Session::start(asked(), "acme").unwrap(); + assert!(session.hold_place(0, place.clone()).is_some()); + place.title = "X".repeat(MAX_MEMO_BYTES); + assert!(session.hold_place(0, place).is_none()); +} + +#[test] +fn open_fetches_robots_for_a_new_origin_and_never_retries_its_denial() { + let held = + run(asked(), "acme", RESULT, |effect| { + match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response(*id, url, "text/html", + "<nav><a href='https://docs.acme.com/guide'>Docs</a><a href='/about'>About</a></nav>")), + _ => None, + } + }) + .held + .unwrap(); + let entry_id = section(held.place(), "Docs").id.clone(); + let (mut session, effects) = open(held, "Docs", asked()); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert_eq!(url.host_str(), Some("docs.acme.com")); + let effects = session.handle(response( + id, + &url, + "text/plain", + "User-agent: *\nDisallow: /guide", + )); + let (refused, remembered, stats) = open_complete(session, effects); + assert!(!remembered); + assert_eq!(stats.phases[&Phase::Section].started, 0); + assert_eq!( + section(refused.place(), "Docs").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert_eq!( + refused.check_open(entry_id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + assert!(matches!( + Session::open( + asked(), + refused, + 0, + entry_id.as_str(), + Confidence::High, + false + ), + Err(OpenRefusal::NotOpenable) + )); +} + +#[test] +fn an_open_can_retry_a_transient_section_failure() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let entry_id = section(held.place(), "Pricing").id.clone(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(Input::Fetch { + id, + result: Err(Failure::Timeout), + }); + let (held, remembered, _) = open_complete(session, effects); + assert!(!remembered); + assert_eq!(held.check_open(entry_id.as_str()), Ok(())); + let (_, effects) = open(held, "Pricing", asked()); + open_fetch(&effects, "/pricing"); +} + +#[test] +fn off_place_redirects_and_other_tenants_do_not_enrich_the_row() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let tenant = run(asked(), "github", + "<main><h2><a href='https://github.com/org/first'>GitHub First</a></h2></main>", + |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/org/first" => Some(response(*id, url, "text/html", + "<nav><a href='/org/first/pricing'>Pricing</a><a href='/org/second/news'>News</a></nav>")), + _ => None, + }).held.unwrap(); + assert_eq!( + tenant.check_open(section(tenant.place(), "News").id.as_str()), + Err(OpenRefusal::NotOpenable) + ); + for (held, path, landing) in [ + (held, "/pricing", "https://other.example/plans"), + ( + tenant, + "/org/first/pricing", + "https://github.com/org/second/plans", + ), + ] { + let before = section(held.place(), "Pricing").id.clone(); + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, path); + let landing = Url::parse(landing).unwrap(); + let effects = session.handle(response( + id, + &landing, + "text/html", + "<h2 id='bad'>Other place</h2>", + )); + let (opened, remembered, _) = open_complete(session, effects); + let entry = section(opened.place(), "Pricing"); + assert_eq!(entry.id, before); + assert_eq!(entry.key.as_url(), &landing); + assert!(entry.off_site && entry.children.is_empty()); + assert_eq!( + entry.read, + Some(ReadState::Refused { + failure: Failure::External + }) + ); + assert!(!remembered); + } +} + +#[test] +fn open_respects_read_ceilings_media_and_truncation() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + for (config, budget) in [ + ( + Config { + section_pages: 0, + ..asked() + }, + Budget::SectionPages, + ), + ( + Config { + fetches: 0, + ..asked() + }, + Budget::Fetches, + ), + ( + Config { + html_bytes: 0, + ..asked() + }, + Budget::HtmlBytes, + ), + ( + Config { + timeout: Duration::ZERO, + ..asked() + }, + Budget::Timeout, + ), + ] { + let (session, effects) = open(held.clone(), "Pricing", config); + let (place, _, stats) = open_complete(session, effects); + assert!(stats.budgets.contains(&budget)); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Limit + }) + ); + } + for (bytes, truncated, media, failure) in [ + (9, false, "text/html", Failure::Limit), + (8, true, "text/html", Failure::Limit), + (8, false, "text/plain", Failure::ContentType), + ] { + let (mut session, effects) = open( + held.clone(), + "Pricing", + Config { + html_bytes: 8, + ..asked() + }, + ); + let (id, url) = open_fetch(&effects, "/pricing"); + let effects = session.handle(Input::Fetch { + id, + result: Ok(FetchResult { + final_url: url, + content_type: media.into(), + charset: None, + bytes: vec![b'a'; bytes], + truncated, + }), + }); + let (place, remembered, _) = open_complete(session, effects); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Refused { failure }) + ); + assert_eq!(place.place().notes.truncated, failure == Failure::Limit); + assert!(!remembered); + } + let (mut session, effects) = open(held, "Pricing", asked()); + assert!( + matches!(effects.as_slice(), [Effect::Fetch { max_bytes, timeout, .. }] + if *max_bytes == MAX_HTML_BYTES as u32 && *timeout == FETCH_TIMEOUT) + ); + let effects = session.handle(Input::Elapsed { time: MAX_ELAPSED }); + let (place, _, stats) = open_complete(session, effects); + assert!(stats.budgets.contains(&Budget::Elapsed)); + assert_eq!( + section(place.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Timeout + }) + ); +} #[test] fn fresh_place_streams_complete_replacements() { let r = run(cfg(), "acme news", RESULT, |_| None); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fbda8026c..888fe1f06 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14,6 +14,8 @@ mod foreground_rendering_boundary; mod macos_imports; mod macos_process_family; mod map_bench; +#[path = "map_bench/section_flags.rs"] +mod map_bench_section_flags; mod map_try; mod page_assist_boundary; mod page_reader_boundary; @@ -97,7 +99,7 @@ fn main() { } } Some("map-bench") => { - if let Err(error) = map_bench::run(&arguments[1..]) { + if let Err(error) = map_bench_section_flags::run(&arguments[1..]) { eprintln!("map bench: {error}"); exit(1); } diff --git a/xtask/src/map_bench/run.rs b/xtask/src/map_bench/run.rs index 1e651d689..f96b1fe9d 100644 --- a/xtask/src/map_bench/run.rs +++ b/xtask/src/map_bench/run.rs @@ -8,6 +8,10 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; use tokio::task::{Id as TaskId, JoinSet}; use url::Url; +use zephium_map::{ + session::{ReadState, Sections}, + Entry, +}; use zephium_public_fetch::{ PublicReader, ReadRefusal, ReadRequest, ReadSession, ReaderLimits, RouteSource, }; @@ -21,7 +25,7 @@ use super::score::{self, Reason, Score, Verdict}; use super::store::{ self, query_dir, write_json, Journal, MatchPolicy, RecordedMatch, ResultsSlot, Transfer, }; -use super::{platform, BenchError, Options, Result}; +use super::{platform, session, BenchError, Options, Result}; const SCHEMA: u32 = 1; pub(super) const BETWEEN_QUERIES: Duration = Duration::from_millis(500); @@ -29,6 +33,7 @@ pub(super) const MANIFEST: &str = "run.json"; pub(super) const OUTCOME: &str = "outcome.json"; pub(super) const MEASURE: &str = "measure.json"; pub(super) const REPLAY: &str = "replay.json"; +const SECTION_COMPARISON: &str = "sections.json"; #[derive(Debug, Deserialize, Serialize)] pub(super) struct RunManifest { @@ -385,6 +390,8 @@ struct QueryIo<'a> { failure: Option<Reason>, submitted: usize, claimed: BTreeSet<usize>, + open_record: Option<usize>, + matched: BTreeMap<usize, usize>, active: BTreeMap<usize, (usize, Option<u64>)>, ready: BTreeMap<(Option<usize>, Duration, usize), Ready>, } @@ -421,6 +428,8 @@ impl<'a> QueryIo<'a> { failure: None, submitted: 0, claimed: BTreeSet::new(), + open_record: None, + matched: BTreeMap::new(), active: BTreeMap::new(), ready: BTreeMap::new(), } @@ -447,14 +456,23 @@ impl<'a> QueryIo<'a> { }; if let Some(matched) = self.journal.find( &request, - |index| probe || !self.claimed.contains(&index), + |index| { + probe + || !self.claimed.contains(&index) + && (request.expect != super::engine::Expectation::Html + || self.open_record.is_none_or(|record| record == index)) + }, policy, ) { self.claimed.insert(matched.index); - self.ready.insert( - (Some(matched.order), matched.end, token), - Ready::Recorded(matched), - ); + self.matched.insert(token, matched.index); + let end = if self.open_record.is_some() { + self.elapsed.saturating_add(matched.duration) + } else { + matched.end + }; + self.ready + .insert((Some(matched.order), end, token), Ready::Recorded(matched)); } else if let Some(live) = &mut self.live { let index = self.journal.reserve(&request, self.query, live.elapsed())?; self.claimed.insert(index); @@ -880,6 +898,167 @@ fn replay_query( Ok(result) } +#[derive(Serialize)] +struct SectionComparison { + slot: u8, + id: String, + role: Option<String>, + state: &'static str, + read: Option<ReadState>, + requests: u64, + decoded_bytes: u64, + not_recorded: u64, + difference: Option<SectionDifference>, +} + +#[derive(Serialize)] +struct SectionDifference { + all_children: usize, + asked_children: usize, + all_more: u32, + asked_more: u32, + all_only: usize, + asked_only: usize, + changed: usize, +} + +fn section_difference(all: &Entry, asked: &Entry) -> Option<SectionDifference> { + if all.children == asked.children && all.more == asked.more { + return None; + } + let missing = |left: &Entry, right: &Entry| { + left.children + .iter() + .filter(|child| !right.children.iter().any(|other| child.id == other.id)) + .count() + }; + Some(SectionDifference { + all_children: all.children.len(), + asked_children: asked.children.len(), + all_more: all.more, + asked_more: asked.more, + all_only: missing(all, asked), + asked_only: missing(asked, all), + changed: all + .children + .iter() + .filter(|child| { + asked + .children + .iter() + .any(|other| child.id == other.id && *child != other) + }) + .count(), + }) +} + +fn compare_sections( + root: &Path, + query: &CorpusQuery, + clock: RunClock, + index: usize, +) -> Result<Vec<SectionComparison>> { + let path = query_dir(root, &query.label.id, false)?; + let replay_io = || -> Result<QueryIo<'_>> { + let mut io = QueryIo::new(&path, Journal::load(&path)?, clock, None); + io.query_index = index; + Ok(io) + }; + let mut all_io = replay_io()?; + let all = session::search(query, &mut all_io, Sections::All, true); + let asked = session::search(query, &mut replay_io()?, Sections::Asked, true); + let mut comparisons = Vec::new(); + for attempt in &all.sections { + let mut comparison = SectionComparison { + slot: attempt.slot, + id: attempt.id.as_str().to_owned(), + role: None, + state: "missing_recorded_response", + read: None, + requests: 0, + decoded_bytes: 0, + not_recorded: 0, + difference: None, + }; + if let Some(&record) = all_io.matched.get(&attempt.token) { + let slot = usize::from(attempt.slot); + let find = |capture: &session::Capture| -> Option<Entry> { + capture.places[slot] + .as_ref()? + .place() + .sections + .iter() + .find(|entry| entry.id == attempt.id) + .cloned() + }; + let baseline = find(&all); + comparison.role = baseline + .as_ref() + .and_then(|entry| entry.role) + .map(|role| format!("{role:?}")); + comparison.state = "missing_asked_place"; + if let Some(held) = &asked.places[slot] { + let mut open_io = replay_io()?; + open_io.open_record = Some(record); + let before = find(&asked); + if let Some(entry) = before + .as_ref() + .filter(|entry| entry.read == Some(ReadState::Read)) + { + comparison.state = "already_read"; + comparison.read = entry.read; + comparison.difference = baseline + .as_ref() + .and_then(|all| section_difference(all, entry)); + } else { + match session::open( + query, + &mut open_io, + held.clone(), + attempt.slot, + &comparison.id, + ) { + Ok(opened) => { + comparison.state = "opened"; + comparison.requests = open_io.activity.site_requests; + comparison.not_recorded = open_io.activity.not_recorded; + comparison.decoded_bytes = opened + .outcome + .stats + .iter() + .filter(|(key, _)| { + key.starts_with("phase.") && key.ends_with(".bytes") + }) + .map(|(_, bytes)| bytes) + .sum(); + if let Some(entry) = find(&opened) { + comparison.read = entry.read; + comparison.difference = baseline + .as_ref() + .and_then(|all| section_difference(all, &entry)); + } else { + comparison.state = "missing_opened_entry"; + } + } + Err(zephium_map::session::OpenRefusal::UnknownEntry) => { + comparison.state = "missing_asked_entry" + } + Err(zephium_map::session::OpenRefusal::NotOpenable) => { + comparison.state = "not_openable"; + comparison.read = before.as_ref().and_then(|entry| entry.read); + } + } + } + if baseline.is_none() { + comparison.state = "missing_all_entry"; + } + } + } + comparisons.push(comparison); + } + Ok(comparisons) +} + pub(super) fn replay( root: &Path, corpus: &Corpus, @@ -927,6 +1106,15 @@ pub(super) fn replay( }, )?; save_outcome(&path.join(OUTCOME), result)?; + if crate::map_bench_section_flags::get().compare + && matches!( + query.label.kind, + super::corpus::Kind::Place | super::corpus::Kind::Compare + ) + { + let comparisons = compare_sections(root, query, recorded.clock(), index)?; + write_json(&path.join(SECTION_COMPARISON), &comparisons)?; + } } let manifest = ReplayManifest { started_unix_ns, diff --git a/xtask/src/map_bench/section_flags.rs b/xtask/src/map_bench/section_flags.rs new file mode 100644 index 000000000..bb3a82e5e --- /dev/null +++ b/xtask/src/map_bench/section_flags.rs @@ -0,0 +1,107 @@ +use std::cell::Cell; + +use zephium_map::session::Sections; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SectionFlags { + pub(crate) sections: Sections, + pub(crate) compare: bool, +} + +thread_local! { + static FLAGS: Cell<SectionFlags> = const { Cell::new(SectionFlags { + sections: Sections::All, compare: false, + }) }; +} + +pub(crate) fn get() -> SectionFlags { + FLAGS.get() +} + +pub(crate) fn run(args: &[String]) -> Result<(), String> { + let (flags, forwarded) = parse(args)?; + if matches!(args, [help] if help == "--help") + || matches!(args, [mode, help] if mode == "replay" && help == "--help") + { + println!("Session replay options: [--sections all|asked] [--compare-sections]"); + } + let previous = FLAGS.replace(flags); + let result = crate::map_bench::run(&forwarded).map_err(|error| error.to_string()); + FLAGS.set(previous); + result +} + +fn parse(args: &[String]) -> Result<(SectionFlags, Vec<String>), String> { + let mut forwarded = Vec::new(); + let mut sections = None; + let mut compare = false; + let mut args_iter = args.iter(); + while let Some(argument) = args_iter.next() { + match argument.as_str() { + "--sections" if sections.is_none() => { + sections = Some(match args_iter.next().map(String::as_str) { + Some("all") => Sections::All, + Some("asked") => Sections::Asked, + _ => return Err("--sections requires all or asked".into()), + }); + } + "--compare-sections" if !compare => compare = true, + "--sections" | "--compare-sections" => { + return Err("duplicate session replay flag".into()) + } + _ => forwarded.push(argument.clone()), + } + } + if (sections.is_some() || compare) + && (args.first().is_none_or(|arg| arg != "replay") + || forwarded + .windows(2) + .any(|pair| pair == ["--engine", "probe"])) + { + return Err("section flags require session replay".into()); + } + Ok(( + SectionFlags { + sections: sections.unwrap_or_default(), + compare, + }, + forwarded, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flags_are_bounded_and_specific_to_session_replay() { + let parse = |args: &str| { + parse( + &args + .split_whitespace() + .map(str::to_owned) + .collect::<Vec<_>>(), + ) + }; + assert_eq!(parse("replay").unwrap().0.sections, Sections::All); + assert_eq!( + parse("replay --sections asked --compare-sections --engine session").unwrap(), + ( + SectionFlags { + sections: Sections::Asked, + compare: true + }, + vec!["replay".to_owned(), "--engine".into(), "session".into()] + ) + ); + for args in [ + "replay --sections", + "replay --sections both", + "replay --sections all --sections all", + "record --compare-sections", + "replay --engine probe --sections all", + ] { + assert!(parse(args).is_err()); + } + } +} diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index 3dd84f585..761843427 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -3,9 +3,10 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use url::Url; use zephium_core::search::SearchEngine; use zephium_map::session::{ - EndOutcome, Expect, Failure, FetchResult as SessionFetch, Id, Phase, Stats, MAX_CONCURRENT, - MAX_HOST_CONCURRENT, MAX_MEMO_BYTES, + EndOutcome, Expect, Failure, FetchResult as SessionFetch, HeldSite, Id, Phase, Sections, Stats, + MAX_CONCURRENT, MAX_HOST_CONCURRENT, MAX_MEMO_BYTES, }; +use zephium_map::{query::Confidence, site::EntryId}; use zephium_map::{ read_query, Config, Doc, DocLimits, Effect, FirstLayer, Input, MapEvent, Place, QueryKind, Session, SiteKey, Source, @@ -25,25 +26,69 @@ pub(super) struct SessionEngine; impl Engine for SessionEngine { fn run(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Outcome { - let mut driver = Driver::new(query); - if query.label.kind == Kind::Passage && query.pages.is_empty() { - driver.outcome.needs_results_page = true; - return driver.outcome; - } - let config = Config { - session_id: io.session_id(), - engine: SearchEngine::Google, - now: io.now(), - ..Config::default() - }; - let Ok((session, effects)) = Session::start(config, &query.text) else { - driver.outcome.failure = Some(EngineFailure::InvalidInput); - return driver.outcome; - }; - driver.run(session, effects, query, io) + search( + query, + io, + crate::map_bench_section_flags::get().sections, + false, + ) + .outcome } } +pub(super) struct SectionAttempt { + pub(super) token: usize, + pub(super) slot: u8, + pub(super) id: EntryId, +} + +pub(super) struct Capture { + pub(super) outcome: Outcome, + pub(super) places: [Option<HeldSite>; MAX_PLACES], + pub(super) sections: Vec<SectionAttempt>, +} + +pub(super) fn search( + query: &CorpusQuery, + io: &mut dyn BenchIo, + sections: Sections, + capture: bool, +) -> Capture { + let mut driver = Driver::new(query); + if query.label.kind == Kind::Passage && query.pages.is_empty() { + driver.outcome.needs_results_page = true; + return driver.capture(None); + } + let config = Config { + session_id: io.session_id(), + engine: SearchEngine::Google, + now: io.now(), + sections, + ..Config::default() + }; + let Ok((session, effects)) = Session::start(config, &query.text) else { + driver.outcome.failure = Some(EngineFailure::InvalidInput); + return driver.capture(None); + }; + driver.run(session, effects, query, io, capture) +} + +pub(super) fn open( + query: &CorpusQuery, + io: &mut dyn BenchIo, + held: HeldSite, + slot: u8, + id: &str, +) -> Result<Capture, zephium_map::session::OpenRefusal> { + let config = Config { + session_id: io.session_id(), + now: io.now(), + ..Config::default() + }; + let (session, effects) = Session::open(config, held, slot, id, Confidence::High, false)?; + Ok(Driver::new(query).run(session, effects, query, io, true)) +} + struct Driver { outcome: Outcome, places: [Option<Place>; MAX_PLACES], @@ -52,6 +97,7 @@ struct Driver { terminal: bool, immediate: VecDeque<Input>, in_flight: BTreeMap<usize, (Id, Url, Expectation)>, + sections: Vec<SectionAttempt>, } impl Driver { @@ -64,6 +110,7 @@ impl Driver { terminal: false, immediate: VecDeque::new(), in_flight: BTreeMap::new(), + sections: Vec::new(), } } @@ -73,10 +120,26 @@ impl Driver { mut effects: Vec<Effect>, query: &CorpusQuery, io: &mut dyn BenchIo, - ) -> Outcome { + capture: bool, + ) -> Capture { loop { for effect in effects { + let effect_id = effect.id(); + let section = capture.then(|| session.section_fetch(effect_id)).flatten(); self.effect(effect, query, io); + if let Some((slot, id)) = section { + if let Some((&token, _)) = self + .in_flight + .iter() + .find(|(_, (id, _, _))| *id == effect_id) + { + self.sections.push(SectionAttempt { + token, + slot, + id: id.clone(), + }); + } + } if self .outcome .failure @@ -128,12 +191,24 @@ impl Driver { self.outcome .stats .insert("official_sites".into(), self.lookups as u64); + self.capture(capture.then_some(&session)) + } + + fn capture(mut self, session: Option<&Session>) -> Capture { + let mut places = [None, None]; for (index, place) in self.places.into_iter().enumerate() { if let Some(place) = place { + if let Some(session) = session { + places[index] = session.hold_place(index as u8, place.clone()); + } flatten_place(&mut self.outcome, index, place); } } - self.outcome + Capture { + outcome: self.outcome, + places, + sections: self.sections, + } } fn completion(&mut self, query: &CorpusQuery, io: &mut dyn BenchIo) -> Option<(Input, bool)> { diff --git a/xtask/src/map_bench/store.rs b/xtask/src/map_bench/store.rs index a03f13b63..3e816a2c8 100644 --- a/xtask/src/map_bench/store.rs +++ b/xtask/src/map_bench/store.rs @@ -542,6 +542,7 @@ pub(super) enum MatchPolicy { pub(super) struct RecordedMatch { pub(super) index: usize, pub(super) end: Duration, + pub(super) duration: Duration, pub(super) order: usize, pub(super) relaxed_cap: Option<usize>, } @@ -619,6 +620,9 @@ impl Journal { let matched = |relaxed_cap| RecordedMatch { index, end: row.elapsed_at_return, + duration: row.elapsed_at_start.map_or(row.timings.total, |start| { + row.elapsed_at_return.saturating_sub(start) + }), order: row.completion_order.unwrap_or(index), relaxed_cap, }; diff --git a/xtask/src/map_try.rs b/xtask/src/map_try.rs index b90634710..3fe60d752 100644 --- a/xtask/src/map_try.rs +++ b/xtask/src/map_try.rs @@ -19,7 +19,7 @@ use zephium_map::{ QueryKind, }; use zephium_map_driver::{ - wire::{Change, Outcome, StartRefusal}, + wire::{Change, OpenResult, Outcome, StartRefusal, MAX_SECTIONS, MAX_TEXT_BYTES}, Counts, Driver, FetchRequest, Fetcher, Io, MapRequest, MemoryMemo, PublicIo, Reading, ResultsPage, ResultsSource, SystemClock, }; @@ -33,12 +33,14 @@ use self::printer::{intro, refusal, Printer}; const ENGINE: SearchEngine = SearchEngine::DuckDuckGo; const MAX_SITES: usize = 2; const MAX_DNS_LABEL_BYTES: usize = 63; +const MAX_OPEN_LABELS: usize = MAX_SECTIONS * MAX_SITES; #[derive(Debug, PartialEq, Eq)] enum Error { MissingQuery, MissingSite, BadHost, + BadOpenLabel, TooManySites, UnexpectedOption, PlaceArity, @@ -58,6 +60,7 @@ impl Error { Self::MissingQuery | Self::MissingSite | Self::BadHost + | Self::BadOpenLabel | Self::TooManySites | Self::UnexpectedOption | Self::PlaceArity @@ -70,13 +73,14 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::MissingQuery => { - "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private]" + "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private] [--open <label>]..." } Self::MissingSite => "Usage error: specify a host with --site", Self::BadHost => "Usage error: --site needs a bare public hostname", + Self::BadOpenLabel => "Usage error: invalid --open label or too many labels", Self::TooManySites => "Usage error: specify at most two sites", Self::UnexpectedOption => { - "Usage error: only --site and one --private flag are supported" + "Usage error: supported flags are --site, --private and --open" } Self::PlaceArity => "Usage error: a place query needs one --site", Self::CompareArity => "Usage error: a comparison needs two --site flags", @@ -94,6 +98,7 @@ struct Options<'a> { query: &'a str, sites: Vec<Url>, private: bool, + opens: Vec<&'a str>, } impl<'a> Options<'a> { @@ -107,6 +112,7 @@ impl<'a> Options<'a> { query, sites: Vec::new(), private: false, + opens: Vec::new(), }; let mut args = rest.iter(); while let Some(arg) = args.next() { @@ -122,6 +128,21 @@ impl<'a> Options<'a> { options.sites.push(site_url(raw).ok_or(Error::BadHost)?); } "--private" if !options.private => options.private = true, + "--open" => { + let label = args + .next() + .filter(|label| { + !label.starts_with("--") + && !label.trim().is_empty() + && label.len() <= MAX_TEXT_BYTES + && !label.chars().any(char::is_control) + }) + .ok_or(Error::BadOpenLabel)?; + if options.opens.len() == MAX_OPEN_LABELS { + return Err(Error::BadOpenLabel); + } + options.opens.push(label); + } _ => return Err(Error::UnexpectedOption), } } @@ -292,6 +313,7 @@ fn print_lines( async fn live( request: MapRequest, results: StandIn, + opens: Vec<&str>, output: &mut impl Write, ) -> Result<Outcome, Error> { print_lines(output, [intro(&request.query)])?; @@ -326,7 +348,7 @@ async fn live( }; Driver::start(request, io, &runtime).map_err(Error::Refused) })?; - stream(&driver, changes, changed, interrupt, output).await + stream(&driver, changes, changed, interrupt, output, opens).await } fn elapsed_ms(started: Instant) -> u32 { @@ -339,18 +361,24 @@ async fn stream( mut route: watch::Receiver<PublicRoute>, mut interrupt: impl Future<Output = io::Result<()>> + Unpin, output: &mut impl Write, + opens: Vec<&str>, ) -> Result<Outcome, Error> { let started = Instant::now(); let mut printer = Printer::default(); let mut cancelling = false; let mut watching = true; let mut interrupted_by = None; + let mut opens = opens.into_iter(); + let mut open_started = None; loop { let change = tokio::select! { biased; signal = &mut interrupt, if !cancelling => { interrupted_by = signal.err().map(|_| Error::Interrupt); driver.cancel(); + if open_started.is_some() { + return interrupted_by.map_or(Ok(Outcome::Cancelled), Err); + } cancelling = true; continue; } @@ -361,6 +389,9 @@ async fn stream( } interrupted_by = Some(Error::Proxy); driver.cancel(); + if open_started.is_some() { + return Err(Error::Proxy); + } cancelling = true; continue; } @@ -371,7 +402,39 @@ async fn stream( output, printer.lines(&change, started.elapsed(), driver.counts()), )?; - return interrupted_by.map_or(Ok(outcome), Err); + if outcome != Outcome::Done || cancelling { + return interrupted_by.map_or(Ok(outcome), Err); + } + open_started = start_open(driver, &printer, &mut opens, output)?; + if open_started.is_none() { + return Ok(outcome); + } + continue; + } + if let Change::Opened { result, .. } = change { + if let Some((time, before)) = open_started.take() { + let after = driver.counts(); + let status = match result { + OpenResult::Read => "read".to_owned(), + OpenResult::Refused { failure } => { + format!("refused ({})", printer::failure_text(failure)) + } + }; + print_lines( + output, + [format!( + "Opened {status} {}ms reads {} bytes {}", + time.elapsed().as_millis(), + after.fetches.saturating_sub(before.fetches), + after.bytes.saturating_sub(before.bytes), + )], + )?; + } + open_started = start_open(driver, &printer, &mut opens, output)?; + if open_started.is_none() { + return Ok(Outcome::Done); + } + continue; } if !cancelling { let lines = printer.lines(&change, started.elapsed(), Counts::default()); @@ -382,13 +445,36 @@ async fn stream( } } +fn start_open<'a>( + driver: &Driver, + printer: &Printer, + opens: &mut impl Iterator<Item = &'a str>, + output: &mut impl Write, +) -> Result<Option<(Instant, Counts)>, Error> { + for label in opens { + let before = driver.counts(); + let started = Instant::now(); + let message = match printer.section(label) { + Ok((slot, id)) => match driver.open(slot, id) { + Ok(()) => return Ok(Some((started, before))), + Err(refusal) => format!("Open refused ({refusal:?})"), + }, + Err(reason) => format!("Open refused ({reason})"), + }; + print_lines(output, [message])?; + } + Ok(None) +} + fn execute(arguments: &[String]) -> Result<Outcome, Error> { - let (request, results) = Options::parse(arguments)?.prepare()?; + let options = Options::parse(arguments)?; + let opens = options.opens.clone(); + let (request, results) = options.prepare()?; let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .map_err(|_| Error::Runtime)?; - let result = runtime.block_on(live(request, results, &mut io::stdout().lock())); + let result = runtime.block_on(live(request, results, opens, &mut io::stdout().lock())); runtime.shutdown_background(); result } diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs index 9f1f80d0f..1d112113b 100644 --- a/xtask/src/map_try/printer.rs +++ b/xtask/src/map_try/printer.rs @@ -15,6 +15,7 @@ const ELLIPSIS: char = '…'; struct Slot { printed: Option<Duration>, labels: BTreeMap<String, String>, + sections: Vec<(String, String)>, } #[derive(Default)] @@ -23,6 +24,20 @@ pub(super) struct Printer { } impl Printer { + pub(super) fn section(&self, label: &str) -> Result<(u8, &str), &'static str> { + let mut matches = self.slots.iter().enumerate().flat_map(|(index, slot)| { + slot.sections.iter().filter_map(move |(id, name)| { + name.eq_ignore_ascii_case(label.trim()) + .then_some((index as u8, id.as_str())) + }) + }); + let section = matches.next().ok_or("unknown label")?; + if matches.next().is_some() { + return Err("ambiguous label"); + } + Ok(section) + } + pub(super) fn lines( &mut self, change: &Change, @@ -34,6 +49,7 @@ impl Printer { official, social, organic, + also, .. } => { let mut line = format!("First layer {organic} organic"); @@ -50,7 +66,14 @@ impl Printer { .collect::<Vec<_>>(); line.push_str(&format!(" social {}", networks.join(", "))); } - vec![clip(&line, COLUMNS)] + let mut lines = vec![clip(&line, COLUMNS)]; + lines.extend(also.iter().map(|result| { + clip( + &format!(" {:?} {} ({})", result.kind, result.title, result.host), + COLUMNS, + ) + })); + lines } Change::Place { slot, @@ -64,6 +87,11 @@ impl Printer { state.labels = entries(place) .map(|entry| (entry.id.clone(), entry.label.clone())) .collect(); + state.sections = place + .sections + .iter() + .map(|entry| (entry.id.clone(), entry.label.clone())) + .collect(); if *complete || state .printed @@ -78,6 +106,7 @@ impl Printer { Change::PlaceFailed { slot, failure, .. } => { if let Some(state) = self.slots.get_mut(usize::from(*slot)) { state.labels.clear(); + state.sections.clear(); state.printed = Some(elapsed); } vec![format!( @@ -96,6 +125,7 @@ impl Printer { elapsed_ms, .. } => vec![end_line(*outcome, *elapsed_ms, counts)], + Change::Opened { .. } => Vec::new(), } } @@ -126,7 +156,7 @@ pub(super) fn refusal(reason: StartRefusal) -> &'static str { } } -fn failure_text(failure: Failure) -> &'static str { +pub(super) fn failure_text(failure: Failure) -> &'static str { match failure { Failure::Cancelled => "cancelled", Failure::Blocked => "access blocked", diff --git a/xtask/src/map_try/printer/tests.rs b/xtask/src/map_try/printer/tests.rs index 4a72e080d..7ed698df4 100644 --- a/xtask/src/map_try/printer/tests.rs +++ b/xtask/src/map_try/printer/tests.rs @@ -9,6 +9,8 @@ fn entry(id: &str, label: &str, path: &str) -> Entry { role: None, group: None, off_site: false, + open: false, + host: None, path: path.into(), read: None, children: Vec::new(), @@ -49,6 +51,7 @@ fn place_stream_golden() { }), social: vec![Network::GitHub], organic: 1, + also: Vec::new(), }; let mut place = place( "Stripe", diff --git a/xtask/src/map_try/tests.rs b/xtask/src/map_try/tests.rs index bd4327e7d..3009cd394 100644 --- a/xtask/src/map_try/tests.rs +++ b/xtask/src/map_try/tests.rs @@ -29,6 +29,41 @@ fn accepts_one_or_two_public_sites_in_order_and_passes_private_through() { assert_eq!(site_url("stripe.com.").unwrap().path(), "/"); } +#[test] +fn accepts_repeated_open_labels_and_enforces_their_bounds() { + let mut arguments = args(&[ + "Stripe", + "--site", + "stripe.com", + "--open", + "Docs", + "--open", + "Pricing", + ]); + assert_eq!( + Options::parse(&arguments).unwrap().opens, + ["Docs", "Pricing"] + ); + arguments.truncate(3); + for _ in 0..MAX_OPEN_LABELS { + arguments.extend(args(&["--open", "Docs"])); + } + assert!(Options::parse(&arguments).is_ok()); + arguments.extend(args(&["--open", "Docs"])); + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); + arguments.truncate(4); + for label in [ + "".to_owned(), + "Docs\nPricing".to_owned(), + "x".repeat(MAX_TEXT_BYTES + 1), + ] { + arguments.push(label); + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); + arguments.pop(); + } + assert_eq!(Options::parse(&arguments).err(), Some(Error::BadOpenLabel)); +} + #[test] fn refuses_malformed_options_and_arity() { for (raw, error) in [ @@ -248,6 +283,7 @@ async fn an_interrupt_cancels_the_driver_and_prints_its_end() { direct, std::future::ready(Ok(())), &mut output, + Vec::new(), ) .await; assert_eq!(outcome, Ok(Outcome::Cancelled)); @@ -285,9 +321,78 @@ async fn a_closed_route_watch_is_not_a_proxy() { direct, std::future::pending(), &mut output, + Vec::new(), ) .await; assert!(outcome.is_ok(), "{outcome:?}"); let printed = std::str::from_utf8(&output).unwrap(); assert!(printed.lines().count() > 1, "{printed}"); } + +#[tokio::test] +async fn labelled_opens_after_end_reprint_the_card_and_each_read_cost() { + struct Fixture; + impl Fetcher for Fixture { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async move { + let html = match request.url.path() { + "/" => "<nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + "/docs" => "<h2 id='first'>First guide</h2>", + "/pricing" => "<h2 id='teams'>Team plans</h2>", + _ => return Err(Failure::Missing), + }; + Ok(FetchResult { + final_url: request.url, + content_type: "text/html".into(), + charset: None, + bytes: html.as_bytes().to_vec(), + truncated: false, + }) + }) + } + } + let arguments = args(&[ + "Stripe", + "--site", + "stripe.com", + "--open", + "Docs", + "--open", + "Pricing", + ]); + let options = Options::parse(&arguments).unwrap(); + let opens = options.opens.clone(); + let (request, results) = options.prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Fixture), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + assert_eq!( + stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + opens + ) + .await, + Ok(Outcome::Done) + ); + let printed = std::str::from_utf8(&output).unwrap(); + let end = printed.find("Done").unwrap(); + let docs = printed.find("First guide").unwrap(); + let plans = printed.find("Team plans").unwrap(); + assert!(end < docs && docs < plans); + let opens: Vec<_> = printed + .lines() + .filter(|line| line.starts_with("Opened read")) + .collect(); + assert_eq!(opens.len(), 2); + assert!(opens.iter().all(|line| line.contains("reads 1 bytes "))); +} From eb3e96b5d893ed5497c87706fc0b74fbb799e759 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 04:18:13 +0100 Subject: [PATCH 36/40] feat(map): keep a place's rows to its sections Sign-in, sales and trial links leave the primary rows for a small action tier. A row is named by the link's own shortest text, falling back to its path when only a teaser sentence exists. The site's own home, placeholder groups, duplicates and locale variants are no longer rows, and rows keep the site's navigation order. When a query asks for a part the entry page does not show, one section chosen by role is read to find it. The bench scores card quality per defect class in both section modes. --- crates/zephium-map-driver/src/wire.rs | 52 +-- crates/zephium-map-driver/src/wire/tests.rs | 23 + crates/zephium-map/src/doc.rs | 6 +- crates/zephium-map/src/doc/html.rs | 24 + crates/zephium-map/src/doc/html/arena.rs | 13 + crates/zephium-map/src/session.rs | 88 ++-- crates/zephium-map/src/session/memo.rs | 11 +- crates/zephium-map/src/session/scheduler.rs | 10 +- crates/zephium-map/src/site.rs | 291 +++++++++--- crates/zephium-map/src/site/card.rs | 490 ++++++++++++++++++++ crates/zephium-map/src/site/navigation.rs | 47 +- crates/zephium-map/tests/card.rs | 244 ++++++++++ crates/zephium-map/tests/session.rs | 38 ++ crates/zephium-map/tests/site.rs | 6 +- xtask/src/map_bench/report.rs | 33 ++ xtask/src/map_bench/run/tests/session.rs | 16 + xtask/src/map_bench/score.rs | 3 + xtask/src/map_bench/session.rs | 32 +- xtask/src/map_bench/session/quality.rs | 123 +++++ xtask/src/map_try/printer.rs | 16 +- 20 files changed, 1403 insertions(+), 163 deletions(-) create mode 100644 crates/zephium-map/src/site/card.rs create mode 100644 crates/zephium-map/tests/card.rs create mode 100644 xtask/src/map_bench/session/quality.rs diff --git a/crates/zephium-map-driver/src/wire.rs b/crates/zephium-map-driver/src/wire.rs index 7a64bcf46..c3387110d 100644 --- a/crates/zephium-map-driver/src/wire.rs +++ b/crates/zephium-map-driver/src/wire.rs @@ -12,13 +12,13 @@ use zephium_map::{ }; pub const MAX_TEXT_BYTES: usize = 300; -pub const MAX_PATH_CHARS: usize = 128; -pub const MAX_SECTIONS: usize = 32; +pub use site::MAX_PATH_CHARS; +pub const MAX_SECTIONS: usize = site::MAX_SECTIONS; pub const MAX_CHILDREN: usize = 12; pub const MAX_SOCIAL: usize = 10; pub const MAX_ALSO: usize = 8; -pub const MAX_HOST_BYTES: usize = 253; -pub const MAX_ROWS: usize = 64; +pub use site::MAX_HOST_BYTES; +pub const MAX_ROWS: usize = 2 * MAX_SECTIONS; pub const ID_BYTES: usize = 16; macro_rules! mirror { @@ -48,7 +48,7 @@ mirror!(Role from SectionRole { mirror!(Network from results::Network { Twitter, GitHub, YouTube, LinkedIn, Discord, Reddit, Mastodon, Bluesky, Instagram, Facebook, }); -mirror!(Tier from site::Tier { Primary, Secondary }); +mirror!(Tier from site::Tier { Primary, Secondary, Action }); mirror!(Confidence from query::Confidence { Low, High }); #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] @@ -367,32 +367,7 @@ fn valid_id(id: &str) -> bool { id.len() == ID_BYTES && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) } -fn scheme_like(segment: &str) -> bool { - segment.strip_suffix(':').is_some_and(|scheme| { - scheme.starts_with(|c: char| c.is_ascii_alphabetic()) - && scheme - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) - }) -} - -pub(crate) fn path(url: &Url) -> String { - let mut out = String::new(); - for segment in url.path().split('/').filter(|s| !s.is_empty()) { - if scheme_like(segment) { - break; - } - out.push('/'); - out.push_str(segment); - } - if out.is_empty() { - out.push('/'); - } - match out.char_indices().nth(MAX_PATH_CHARS) { - Some((cut, _)) => out[..cut].to_owned(), - None => out, - } -} +pub(crate) use site::display_path as path; fn address(entry: &site::Entry) -> Url { let mut url = entry.key.as_url().clone(); @@ -405,13 +380,7 @@ fn address(entry: &site::Entry) -> Url { } fn hostname(url: &Url) -> Option<String> { - let host = url.domain()?.trim_end_matches('.'); - (!host.is_empty() - && host.len() <= MAX_HOST_BYTES - && host - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))) - .then(|| host.to_ascii_lowercase()) + site::display_hostname(url).map(str::to_owned) } fn networks(profiles: &[Profile], social: &mut BTreeMap<Network, Url>) -> Vec<Network> { @@ -496,10 +465,14 @@ pub(crate) fn place( }; let mut seen = BTreeSet::new(); let mut ordered: Vec<_> = source.sections.iter().collect(); - ordered.sort_by_key(|e| e.tier != site::Tier::Primary); + ordered.sort_by_key(|e| e.tier); let mut sections = Vec::new(); let host = hostname(source.entry.as_url()); + let mut actions = 0; for section in ordered { + if section.tier == site::Tier::Action && actions == site::MAX_ACTIONS { + continue; + } if sections.len() == MAX_SECTIONS { break; } @@ -512,6 +485,7 @@ pub(crate) fn place( &mut seen, &mut targets.entries, ) { + actions += usize::from(projected.tier == Tier::Action); sections.push(projected); } } diff --git a/crates/zephium-map-driver/src/wire/tests.rs b/crates/zephium-map-driver/src/wire/tests.rs index 8a78cd714..5b9417a56 100644 --- a/crates/zephium-map-driver/src/wire/tests.rs +++ b/crates/zephium-map-driver/src/wire/tests.rs @@ -455,3 +455,26 @@ fn every_engine_failure_has_a_wire_class() { json!({"type": "end", "seq": 3, "outcome": {"kind": "failed", "failure": "no_results"}, "elapsed_ms": 7}) ); } + +#[test] +fn action_tier_is_bounded_and_round_trips_with_its_target() { + let mut value = base(); + value["sections"] = Value::Array( + (0..=site::MAX_ACTIONS) + .map(|i| { + section( + &id(i), + "Enter", + &format!("https://acme.com/flow/{i}"), + "Action", + ) + }) + .collect(), + ); + let (card, targets) = place(&engine(value), None); + assert_eq!(card.sections.len(), site::MAX_ACTIONS); + for e in card.sections { + assert_eq!(serde_json::to_value(e.tier).unwrap(), "action"); + assert!(targets.has(&e.id)); + } +} diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 08b4cb18a..2aba29ca6 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -165,7 +165,7 @@ pub enum Role { } #[derive(Clone, Copy, Default, PartialEq, Eq)] -pub struct Marks(u8); +pub struct Marks(u16); impl Marks { pub const SPONSORED: Self = Self(1); pub const ACCEPTED: Self = Self(2); @@ -174,6 +174,8 @@ impl Marks { pub const FEATURED: Self = Self(16); pub const WIDGET: Self = Self(32); pub(crate) const ANCILLARY: Self = Self(64); + pub(crate) const LANGUAGE_HOST: Self = Self(512); + pub(crate) const ACTION: Self = Self(256); pub(crate) const PROSE: Self = Self(128); pub fn has(self, mark: Self) -> bool { self.0 & mark.0 != 0 @@ -186,6 +188,7 @@ pub struct Node { pub role: Role, pub parent: Option<u32>, pub name: String, + pub(crate) link_prefix_bytes: usize, pub text: String, pub destination: Option<Url>, pub image_source: Option<Url>, @@ -221,6 +224,7 @@ impl Node { role, parent, name: String::new(), + link_prefix_bytes: 0, text: String::new(), destination: None, image_source: None, diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index 802b22002..8c008a649 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -292,7 +292,11 @@ impl DocBuilder { ) { captured = true; + let first_link_run = n.role == Role::Link && n.text.is_empty(); self.append(at, &words, verbatim, gap); + if first_link_run { + self.doc.nodes[at].link_prefix_bytes = self.doc.nodes[at].text.len(); + } } inside_list_or_code |= matches!( self.doc.nodes[at].role, @@ -459,7 +463,27 @@ impl DocBuilder { node.marks.insert(Marks::ANCILLARY); } if role == Role::Link { + if n.has_attr("download") + || n.attr("class").is_some_and(|v| { + v.split_ascii_whitespace() + .any(|t| t.eq_ignore_ascii_case("cta")) + }) + { + node.marks.insert(Marks::ACTION); + } node.destination = self.resolve(&n, "href", base); + if node + .destination + .as_ref() + .and_then(Url::domain) + .and_then(|h| h.split_once('.')) + .zip(n.link_language()) + .is_some_and(|((prefix, _), lang)| { + prefix.len() == 2 && prefix.eq_ignore_ascii_case(lang) + }) + { + node.marks.insert(Marks::LANGUAGE_HOST); + } } if role == Role::Image { node.image_source = self.resolve(&n, "src", base); diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index fc186e2ff..fb1c8af33 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -38,6 +38,8 @@ const ATTRIBUTE_NAMES: &[&str] = &[ "data-testid", "aria-labelledby", "hreflang", + "lang", + "download", ]; const ATTRIBUTES_PER_ELEMENT_BUDGET: usize = 4; @@ -161,6 +163,17 @@ impl<'a> NodeRef<'a> { (next != 0).then_some(self.arena.node(next)) }) } + pub(super) fn link_language(self) -> Option<&'a str> { + self.attr("hreflang").or_else(|| { + std::iter::successors(Some(self), |n| { + n.arena + .attached_parent(n.id) + .filter(|&p| p != 0) + .map(|p| n.arena.node(p)) + }) + .find_map(|n| n.attr("lang")) + }) + } fn attribute(self, key: &str) -> Option<&'a Attr> { if self.is_text() { return None; diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index b8bba4652..1e1269c9a 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -133,6 +133,8 @@ struct SiteState { stale: bool, external: BTreeMap<PageMatch, PageKey>, asked: BTreeSet<site::EntryId>, + probed_section: bool, + eager: Vec<site::SectionRead>, memo: Option<SiteMemo>, } impl SiteState { @@ -159,6 +161,8 @@ impl SiteState { stale: false, external: BTreeMap::new(), asked: BTreeSet::new(), + probed_section: false, + eager: Vec::new(), memo: None, } } @@ -751,6 +755,7 @@ impl Session { ); } fn rebuild(&mut self, i: usize, out: &mut Vec<Effect>) { + let probe_available = !self.sites.iter().flatten().any(|s| s.probed_section); let Some(state) = self.sites[i].as_mut() else { return; }; @@ -763,7 +768,7 @@ impl Session { sitemaps: state.maps.iter().map(|(k, v)| (k.clone(), v)).collect(), pages: state.pages.iter().map(|(k, v)| (k.clone(), v)).collect(), }; - let Ok((mut place, mut detail)) = + let Ok((mut place, mut detail, eager)) = site::read_site_for(doc, &inputs, state.requested.as_ref()) else { state.entry_failure = Some(Failure::Unreadable); @@ -776,7 +781,7 @@ impl Session { detail.sitemap_truncated |= state.cut.contains(&Phase::Sitemap); detail.llms_truncated |= state.cut.contains(&Phase::Llms); place.notes.truncated |= detail.truncated(); - self.stats.places.insert(i as u8, detail); + if let Some(previous) = &state.place { place.keep_discovery(previous); if place.check_ids().is_err() { @@ -786,18 +791,35 @@ impl Session { } } let candidates: BTreeSet<_> = match self.cfg.sections { - Sections::All => place - .fetch_sections() - .into_iter() - .map(|e| e.id.clone()) - .collect(), + Sections::All => { + for read in &eager { + state + .discovered + .entry(read.id.clone()) + .or_insert_with(|| read.key.page_match()); + } + state.eager = eager; + state.eager.iter().map(|e| e.id.clone()).collect() + } Sections::Asked => { state .asked .extend(place.asked_sections(doc.page()).map(|e| e.id.clone())); + if place.focus.is_none() && state.asked.is_empty() && probe_available { + if let Some(entry) = state + .requested + .as_ref() + .and_then(|role| place.likely_section(role, doc.page())) + { + state.asked.insert(entry.id.clone()); + state.probed_section = true; + } + } state.asked.clone() } }; + detail.probed_section = state.probed_section; + self.stats.places.insert(i as u8, detail); for entry in &mut place.sections { if self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) { continue; @@ -831,15 +853,26 @@ impl Session { let Some(place) = state.place.as_ref() else { return; }; - let entries: Vec<_> = match self.cfg.sections { - Sections::All => place.fetch_sections(), - Sections::Asked => place.sections.iter().collect(), + let keys: Vec<_> = match self.cfg.sections { + Sections::All => state + .eager + .iter() + .filter(|r| { + state + .discovered + .get(&r.id) + .and_then(|key| state.reads.get(key)) + .is_none_or(|s| *s == ReadState::Queued) + }) + .map(|r| r.key.clone()) + .collect(), + Sections::Asked => place + .sections + .iter() + .filter(|e| e.read == Some(ReadState::Queued)) + .map(|e| e.key.clone()) + .collect(), }; - let keys: Vec<_> = entries - .into_iter() - .filter(|e| e.read == Some(ReadState::Queued)) - .map(|e| e.key.clone()) - .collect(); for key in keys { self.enqueue(Work::Section(i, key.page_match()), key.as_url().clone()); } @@ -874,26 +907,13 @@ impl Session { let Some(state) = &self.sites[i] else { continue; }; - let Some((doc, place)) = state.doc.as_ref().zip(state.place.as_ref()) else { - continue; - }; + let Some(doc) = &state.doc else { continue }; if state.maps_wanted >= MAX_SITEMAP_READS - || place - .sections - .iter() - .filter(|e| { - e.sources.iter().any(|s| { - matches!( - s, - Source::PrimaryNav - | Source::Footer - | Source::MenuGroup - | Source::Llms - ) - }) - }) - .count() - >= SITEMAP_SECTION_THRESHOLD + || self + .stats + .places + .get(&(i as u8)) + .is_some_and(|p| p.navigation_sections >= SITEMAP_SECTION_THRESHOLD) { continue; } diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index 72df80b8f..99df55755 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -3,7 +3,7 @@ use crate::results::{MAX_SOCIAL, TITLE_BYTES}; use crate::site::{MAX_CHILDREN, MAX_SECTIONS}; use serde::{Deserialize, Serialize}; -pub const MEMO_VERSION: u16 = 3; +pub const MEMO_VERSION: u16 = 4; pub const MAX_MEMO_BYTES: usize = 256 * 1024; pub const MEMO_TTL: u64 = 24 * 60 * 60; #[derive(Clone, Serialize, Deserialize)] @@ -65,6 +65,15 @@ impl SiteMemo { .windows(2) .any(|pair| pair[0].tier > pair[1].tier) || p.sections.iter().map(|e| e.children.len()).sum::<usize>() > site::MAX_PLACE_CHILDREN + || p.sections + .iter() + .filter(|e| e.tier == site::Tier::Action) + .count() + > site::MAX_ACTIONS + || p.sections.iter().any(|e| { + e.tier == site::Tier::Primary + && e.label.chars().count() > site::MAX_PRIMARY_LABEL_CHARS + }) || p.sections.len() > MAX_SECTIONS || p.social.len() > MAX_SOCIAL || !p.social.iter().all(|v| { diff --git a/crates/zephium-map/src/session/scheduler.rs b/crates/zephium-map/src/session/scheduler.rs index 24b6b1d5f..d062ec82e 100644 --- a/crates/zephium-map/src/session/scheduler.rs +++ b/crates/zephium-map/src/session/scheduler.rs @@ -5,7 +5,15 @@ impl Session { let Work::Section(i, key) = &job.work else { return None; }; - let place = self.sites[*i].as_ref()?.place.as_ref()?; + let state = self.sites[*i].as_ref()?; + if self.cfg.sections == Sections::All { + return state + .eager + .iter() + .find(|e| e.key.page_match() == *key) + .map(|e| e.priority); + } + let place = state.place.as_ref()?; let entry = place.sections.iter().find(|e| e.key.page_match() == *key)?; Some(place.read_priority(entry)) } diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 3d805afb2..4ee4b4f27 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -15,6 +15,10 @@ use crate::{ use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use url::Url; +mod card; +pub use card::{ + display_hostname, display_path, MAX_HOST_BYTES, MAX_PATH_CHARS, MAX_PRIMARY_LABEL_CHARS, +}; mod navigation; mod sitemap; pub use sitemap::{Sitemap, XmlError, MAX_SITEMAP_URLS, MAX_XML_BYTES, MAX_XML_DEPTH}; @@ -22,7 +26,8 @@ pub use sitemap::{Sitemap, XmlError, MAX_SITEMAP_URLS, MAX_XML_BYTES, MAX_XML_DE pub const ENTRY_ID_BYTES: usize = 16; pub const MAX_PRIMARY_SECTIONS: usize = 12; pub const MAX_SECONDARY_SECTIONS: usize = 20; -pub const MAX_SECTIONS: usize = MAX_PRIMARY_SECTIONS + MAX_SECONDARY_SECTIONS; +pub const MAX_ACTIONS: usize = 4; +pub const MAX_SECTIONS: usize = MAX_PRIMARY_SECTIONS + MAX_SECONDARY_SECTIONS + MAX_ACTIONS; pub const MAX_PLACE_CHILDREN: usize = 36; pub const MAX_CHILDREN: usize = 12; pub const MAX_SECTION_PAGES: usize = 6; @@ -50,6 +55,7 @@ pub enum Source { pub enum Tier { Primary, Secondary, + Action, } impl Source { fn tier(self) -> Tier { @@ -132,6 +138,8 @@ pub struct PlaceStats { pub sitelinks_truncated: bool, pub linked_data_truncated: bool, pub links_seen: u32, + pub(crate) navigation_sections: usize, + pub probed_section: bool, pub sitemap_urls: u32, pub section_pages: u32, } @@ -299,7 +307,19 @@ impl Focus { Some((!exact, path, label)) } } +pub(crate) struct SectionRead { + pub id: EntryId, + pub key: PageKey, + pub priority: (bool, bool), +} +struct LinkName { + text: String, + action: bool, + language_host: bool, + host_root: bool, +} struct Build<'a> { + names: std::collections::HashMap<EntryId, LinkName>, place: Place, index: std::collections::HashMap<(crate::PageMatch, Locator), usize>, requested: Option<&'a Focus>, @@ -375,6 +395,9 @@ impl Build<'_> { fn section(&mut self, entry: Entry) -> usize { let destination = (entry.key.page_match(), entry.locator.clone()); if let Some(&i) = self.index.get(&destination) { + if entry.tier == Tier::Action { + self.sections[i].tier = Tier::Action; + } self.sections[i].add_sources(entry.sources); return i; } @@ -387,8 +410,8 @@ impl Build<'_> { let requested = self.requested; self.sections[index].child(entry, requested); } - fn finish_sections(&mut self) { - let requested = self.requested; + fn finish_sections(&mut self, landing: Option<&Url>) { + self.edit_card(landing); let cluster_primary = !self .sections .iter() @@ -399,71 +422,49 @@ impl Build<'_> { .map(|e| (e.key.page_match(), e.locator.fragment())) .chain(std::iter::once((self.entry.page_match(), None))) .collect(); - let first_signup = self - .sections - .iter() - .find(|e| e.role == Some(SectionRole::SignUp)) - .map(|e| e.id.clone()); - let demoted = |e: &Entry| { - e.utility() - || e.role == Some(SectionRole::SignUp) && Some(&e.id) != first_signup.as_ref() - }; + let demoted = Entry::utility; for e in &mut self.sections { - if e.sources.contains(&Source::LinkCluster) && cluster_primary { + if e.tier != Tier::Action + && e.sources.contains(&Source::LinkCluster) + && cluster_primary + && !card::sentence(&e.label) + { e.tier = Tier::Primary; } - if demoted(e) { + if e.tier != Tier::Action && demoted(e) { e.tier = Tier::Secondary; } - e.children.retain(|c| { - c.sources.contains(&Source::Heading) - || !globals.contains(&(c.key.page_match(), c.locator.fragment())) + let mut children = std::mem::take(&mut e.children); + children.retain(|c| { + !card::child_self(c, e) && { + c.sources.contains(&Source::Heading) + || !globals.contains(&(c.key.page_match(), c.locator.fragment())) + } }); - } - self.sections.sort_by_cached_key(|e| (e.tier, demoted(e))); - let mut focus = None; - if let Some(request) = requested { - focus = self - .sections - .iter() - .flat_map(|e| std::iter::once((e, e)).chain(e.children.iter().map(move |c| (e, c)))) - .filter_map(|(p, e)| Some((request.rank(e)?, p, e))) - .min_by_key(|(rank, p, e)| (*rank, e.tier, p.id != e.id)) - .map(|(_, parent, entry)| (parent.id.clone(), entry.id.clone())); - } - let mut sections = std::mem::take(&mut self.sections); - for tier in [Tier::Primary, Tier::Secondary] { - let cap = match tier { - Tier::Primary => MAX_PRIMARY_SECTIONS, - Tier::Secondary => MAX_SECONDARY_SECTIONS, - }; - let priority = |entry: &Entry| { - ( - focus - .as_ref() - .is_some_and(|(parent, _)| parent == &entry.id), - entry.role.is_some(), - ) - }; - let mut kept = Vec::new(); - for e in sections.extract_if(.., |e| e.tier == tier) { - if kept.len() == cap { - self.stats.sections_truncated = true; - let rank = priority(&e); - let replace = kept - .iter() - .enumerate() - .rev() - .min_by_key(|(_, entry)| priority(entry)) - .filter(|(_, entry)| priority(entry) < rank); - let Some((index, _)) = replace else { continue }; - kept.remove(index); + let mut distinct = Vec::new(); + for child in children { + if !distinct.iter().any(|c| card::same_display(c, &child)) { + distinct.push(child); } - kept.push(e); } - self.sections.extend(kept); + e.children = distinct; } - self.focus = focus.map(|(_, id)| id); + self.sections.sort_by_cached_key(|e| { + let supplemental = e.tier == Tier::Primary + && !e.sources.iter().any(|s| { + matches!( + s, + Source::PrimaryNav | Source::MenuGroup | Source::LinkCluster + ) + }); + ( + e.tier, + e.utility(), + supplemental, + supplemental && e.role.is_none(), + ) + }); + self.select_sections(); let total: usize = self.sections.iter().map(|e| e.children.len()).sum(); for _ in MAX_PLACE_CHILDREN..total { if let Some(section) = self @@ -484,6 +485,69 @@ impl Build<'_> { } } } + fn select_sections(&mut self) { + let focus = self + .focus_entries() + .map(|(parent, entry)| (parent.clone(), entry.clone())); + let selected = self.shortlist(focus.as_ref().map(|(p, _)| p)); + self.stats.sections_truncated |= selected.len() < self.sections.len(); + self.place.sections.retain(|e| selected.contains(&e.id)); + self.focus = focus.map(|(_, id)| id); + } + fn shortlist(&self, focus: Option<&EntryId>) -> BTreeSet<EntryId> { + let mut selected = BTreeSet::new(); + for (tier, cap) in [ + (Tier::Primary, MAX_PRIMARY_SECTIONS), + (Tier::Secondary, MAX_SECONDARY_SECTIONS), + (Tier::Action, MAX_ACTIONS), + ] { + let mut rows: Vec<_> = self.sections.iter().filter(|e| e.tier == tier).collect(); + rows.sort_by_key(|e| { + ( + Some(&e.id) != focus, + tier == Tier::Action + && !e.sources.contains(&Source::PrimaryNav) + && !e.sources.contains(&Source::MenuGroup), + e.role.is_none(), + ) + }); + selected.extend(rows.into_iter().take(cap).map(|e| e.id.clone())); + } + selected + } + + fn focus_entries(&self) -> Option<(&EntryId, &EntryId)> { + let request = self.requested?; + self.sections + .iter() + .flat_map(|parent| { + std::iter::once(parent) + .chain(&parent.children) + .map(move |e| (parent, e)) + }) + .filter_map(|(parent, e)| Some((request.rank(e)?, parent, e))) + .min_by_key(|(rank, parent, e)| (*rank, e.tier, parent.id != e.id)) + .map(|(_, parent, e)| (&parent.id, &e.id)) + } + + fn eager_reads(&self) -> Vec<SectionRead> { + let focus = self.focus_entries().map(|(parent, _)| parent); + let visible = self.shortlist(focus); + let mut reads: Vec<_> = self + .fetch_sections() + .into_iter() + .filter(|e| visible.contains(&e.id)) + .collect(); + reads.sort_by_key(|e| (Some(&e.id) != focus, e.role.is_none(), e.tier)); + reads + .into_iter() + .map(|e| SectionRead { + id: e.id.clone(), + key: e.key.clone(), + priority: (Some(&e.id) != focus, e.role.is_none()), + }) + .collect() + } fn profile(&mut self, url: &Url, basis: ProfileBasis) -> bool { let Some(network) = site_profile(url) else { return false; @@ -753,7 +817,33 @@ impl Place { && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) }) } - pub(crate) fn fetch_sections(&self) -> Vec<&Entry> { + pub(crate) fn likely_section(&self, request: &Focus, landing: &Url) -> Option<&Entry> { + use SectionRole::*; + let affinity: &[SectionRole] = match request.role { + Changelog => &[Releases, News], + Releases => &[Changelog, News], + Api | Reference | Install => &[Documentation], + Documentation => &[Learn, Reference], + _ => &[], + }; + self.sections + .iter() + .filter(|e| { + !e.off_site + && e.tier != Tier::Action + && e.key.as_url().origin() == landing.origin() + && !crate::key::same_page(e.key.as_url(), landing) + }) + .filter_map(|e| Some((affinity.iter().position(|role| Some(*role) == e.role)?, e))) + .min_by_key(|(rank, e)| (*rank, e.tier)) + .map(|(_, e)| e) + } + fn fetch_sections(&self) -> Vec<&Entry> { + let globals: BTreeSet<_> = self + .sections + .iter() + .map(|e| (e.key.page_match(), e.locator.fragment())) + .collect(); let mut entries: Vec<_> = self .sections .iter() @@ -762,10 +852,10 @@ impl Place { return true; } e.key.page_match() != self.entry.page_match() - && !e - .children - .iter() - .any(|c| c.sources.first() == Some(&Source::MenuGroup)) + && !e.children.iter().any(|c| { + c.sources.first() == Some(&Source::MenuGroup) + && !globals.contains(&(c.key.page_match(), c.locator.fragment())) + }) && matches!( e.role, Some( @@ -847,6 +937,31 @@ impl Entry { fn utility(&self) -> bool { let label = self.label.to_lowercase(); self.role == Some(SectionRole::Legal) + || self + .locator + .element + .as_ref() + .is_some_and(|id| matches!(id.as_str(), "breadcrumb" | "breadcrumbs")) + || matches!( + normal(&label).as_str(), + "rss" + | "settings" + | "translations" + | "dashboard" + | "your account" + | "account" + | "ask ai" + | "search" + ) + || self + .key + .as_url() + .path() + .rsplit('/') + .next() + .is_some_and(|s| { + (s.starts_with("llms") && s.ends_with(".txt")) || s.ends_with(".xml") + }) || ["skip to", "language", "cookie", "select region"] .iter() .any(|s| label.contains(s)) @@ -869,7 +984,9 @@ impl Entry { } fn add_sources(&mut self, sources: impl IntoIterator<Item = Source>) { for source in sources { - self.tier = self.tier.min(source.tier()); + if self.tier != Tier::Action { + self.tier = self.tier.min(source.tier()); + } if !self.sources.contains(&source) { self.sources.push(source); } @@ -903,6 +1020,9 @@ impl Entry { existing.add_sources(entry.sources); return; } + if self.children.iter().any(|c| card::same_display(c, &entry)) { + return; + } if self.children.len() == MAX_CHILDREN && requested.is_some_and(|request| { request.rank(&entry).is_some_and(|rank| { @@ -946,6 +1066,7 @@ pub(crate) fn enrich_held( child_cap: usize, ) -> (Place, PlaceStats) { let mut build = Build { + names: Default::default(), place, index: Default::default(), requested: None, @@ -965,11 +1086,15 @@ pub(crate) fn enrich_held( .chain(std::iter::once((build.entry.page_match(), None))) .collect(); let section = &mut build.sections[index]; - section.children.retain(|child| { - focus.as_ref() == Some(&child.id) - || child.sources.contains(&Source::Heading) - || !siblings.contains(&(child.key.page_match(), child.locator.fragment())) + let mut opened_children = std::mem::take(&mut section.children); + opened_children.retain(|child| { + !card::child_self(child, section) && { + focus.as_ref() == Some(&child.id) + || child.sources.contains(&Source::Heading) + || !siblings.contains(&(child.key.page_match(), child.locator.fragment())) + } }); + section.children = opened_children; if let Some(focused) = focused_child { if !section.children.iter().any(|e| e.id == focused.id) { section.children.push(focused); @@ -997,6 +1122,7 @@ pub(crate) fn with_results( requested: Option<&Focus>, ) -> Result<Place, KeyError> { let mut build = Build { + names: Default::default(), index: place .sections .iter() @@ -1026,7 +1152,7 @@ pub(crate) fn with_results( } } build.stats.sitelinks_truncated = links.len() > MAX_SITELINKS; - build.finish_sections(); + build.finish_sections(None); build.notes.truncated |= build.stats.truncated(); build.check_ids()?; Ok(build.place) @@ -1038,13 +1164,13 @@ pub fn read_site_with_stats( doc: &Doc, inputs: &SiteInputs<'_>, ) -> Result<(Place, PlaceStats), KeyError> { - read_site_for(doc, inputs, None) + read_site_for(doc, inputs, None).map(|(place, stats, _)| (place, stats)) } pub(crate) fn read_site_for( doc: &Doc, inputs: &SiteInputs<'_>, requested: Option<&Focus>, -) -> Result<(Place, PlaceStats), KeyError> { +) -> Result<(Place, PlaceStats, Vec<SectionRead>), KeyError> { let key = PlaceKey::from_url(doc.page()).ok_or(KeyError::Url)?; let site = SiteKey::from_url(doc.page()).ok_or(KeyError::Url)?; let title = [ @@ -1056,6 +1182,7 @@ pub(crate) fn read_site_for( .find(|s| !s.trim().is_empty()) .unwrap_or_default(); let mut place = Build { + names: Default::default(), index: Default::default(), requested, stats: PlaceStats::default(), @@ -1146,10 +1273,23 @@ pub(crate) fn read_site_for( && !robots.allows(&e.key.as_url()[url::Position::BeforePath..]) }); } - place.finish_sections(); + place.stats.navigation_sections = place + .sections + .iter() + .filter(|e| { + e.sources.iter().any(|s| { + matches!( + s, + Source::PrimaryNav | Source::MenuGroup | Source::Llms | Source::Footer + ) + }) + }) + .count(); + let eager = place.eager_reads(); + place.finish_sections(Some(doc.page())); place.check_ids()?; place.notes.truncated = place.stats.truncated() || place.sections.iter().any(|e| e.more > 0); - Ok((place.place, place.stats)) + Ok((place.place, place.stats, eager)) } pub(crate) fn sitemap_priority(url: &Url, entry: &Url) -> (bool, bool, bool) { @@ -1209,7 +1349,8 @@ mod tests { let html = format!("<nav><ul>{links}{menu}</ul></nav>"); let doc = Doc::from_html(&root, html.as_bytes(), None, crate::DocLimits::SITE_PAGE).unwrap(); - let (place, _) = read_site_for(&doc, &SiteInputs::default(), Some(&request)).unwrap(); + let (place, _, _) = + read_site_for(&doc, &SiteInputs::default(), Some(&request)).unwrap(); assert_eq!(place.sections.len(), MAX_PRIMARY_SECTIONS); let focus = place .sections diff --git a/crates/zephium-map/src/site/card.rs b/crates/zephium-map/src/site/card.rs new file mode 100644 index 000000000..4f4499509 --- /dev/null +++ b/crates/zephium-map/src/site/card.rs @@ -0,0 +1,490 @@ +use super::*; +use crate::PageMatch; + +pub const MAX_PRIMARY_LABEL_CHARS: usize = 48; +pub const MAX_HOST_BYTES: usize = 253; +pub const MAX_PATH_CHARS: usize = 128; +const SENTENCE_WORDS: usize = 7; +const MIN_NAV_ROWS: usize = 3; +const MIN_DIRECTORY_ITEMS: usize = 3; + +fn locale(segment: &str) -> bool { + let (language, region) = segment + .split_once('-') + .map_or((segment, None), |(l, r)| (l, Some(r))); + language.len() == 2 + && language.bytes().all(|c| c.is_ascii_alphabetic()) + && region.is_none_or(|r| r.len() == 2 && r.bytes().all(|c| c.is_ascii_alphabetic())) +} + +impl Entry { + pub fn card_page(&self) -> PageMatch { + localized_key(&self.key) + } +} + +fn localized_key(key: &PageKey) -> PageMatch { + let mut url = key.as_url().clone(); + if let Some((first, rest)) = url.path().trim_matches('/').split_once('/') { + if locale(first) { + let path = format!("/{rest}"); + url.set_path(&path); + } + } + PageKey::from_url(&url).map_or_else(|_| key.page_match(), |k| k.page_match()) +} + +fn placeholder(label: &str) -> bool { + matches!( + normal(label).as_str(), + "" | "other" + | "more" + | "optional" + | "menu" + | "main navigation menu" + | "open sidebar" + | "learn more" + ) +} + +pub(super) fn sentence(label: &str) -> bool { + label.chars().count() > MAX_PRIMARY_LABEL_CHARS + || label.contains(". ") + || label.split_whitespace().count() >= SENTENCE_WORDS +} + +fn version_badge(label: &str) -> bool { + let Some(version) = label.strip_prefix('v') else { + return false; + }; + version.contains('.') + && version + .split('.') + .all(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) +} + +fn path_name(url: &Url) -> Option<String> { + let slug = url.path_segments()?.rfind(|s| !s.is_empty())?; + let name = slug + .trim_end_matches(".html") + .trim_end_matches(".md") + .replace(['-', '_'], " "); + (!name.is_empty() + && !sentence(&name) + && !placeholder(&name) + && name.chars().any(char::is_alphabetic) + && name.chars().all(|c| c.is_alphanumeric() || c == ' ')) + .then_some(name) +} + +pub(super) fn action(entry: &Entry) -> bool { + let url = entry.key.as_url(); + let path = url.path().trim_matches('/').to_ascii_lowercase(); + let last = path.rsplit('/').next().unwrap_or_default(); + let label = normal(&entry.label); + if matches!( + last, + "login" + | "signin" + | "sign-in" + | "sign_in" + | "register" + | "signup" + | "sign-up" + | "sign_up" + | "contact-sales" + | "request-demo" + | "book-demo" + ) || path.trim_end_matches(".md").ends_with("contact/sales") + || last.ends_with("enterprise-sales") + || last.ends_with(".dmg") + || last.ends_with(".msi") + || last.ends_with(".exe") + { + return true; + } + if path.starts_with("downloads/") + && label.contains("download") + && label.split_whitespace().next_back() == Some(last) + { + return true; + } + if matches!(last, "download" | "downloads" | "download.html") { + return false; + } + entry.tier == Tier::Action + || (last == "refer" && label.starts_with("refer ")) + || (matches!(last, "shell" | "app") && label.starts_with("launch ")) + || (last == "get-started" && label == "get started" && !path.contains('/')) + || matches!( + label.as_str(), + "sign in" + | "log in or sign up" + | "log in" + | "login" + | "sign up" + | "contact sales" + | "request a demo" + | "get a demo" + | "start free trial" + | "book a demo" + | "get started download" + | "new chat" + | "donate" + | "under attack" + ) +} + +fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> bool { + if entry.locator != Locator::default() { + return false; + } + let url = entry.key.as_url(); + if localized_key(&entry.key) == root.page_match() + || landing.is_some_and(|u| crate::key::same_page(u, url)) + { + return true; + } + let host = |u: &Url| u.domain().map(|h| h.trim_start_matches("www.").to_owned()); + if host(url) != host(root.as_url()) || url.query().is_some() { + return false; + } + let named_home = normal(&entry.label) + .split_whitespace() + .any(|w| matches!(w, "home" | "homepage")); + let brand = host(url).is_some_and(|h| { + h.split('.') + .next() + .is_some_and(|s| s.eq_ignore_ascii_case(&entry.label)) + }); + match url.path().trim_matches('/') { + "index.html" | "homepage" => true, + "home" => brand || named_home && !entry.label.eq_ignore_ascii_case("home"), + "product" => named_home, + path if locale(path) => named_home, + _ => false, + } +} + +impl Build<'_> { + fn link_name(&self, entry: &Entry) -> Option<&LinkName> { + self.names.get(&entry.id).or_else(|| { + self.names + .get(&EntryId::new(None, &entry.key, &entry.locator)) + }) + } + fn apply_link_name(&self, entry: &mut Entry) { + let is_action = action(entry); + if let Some(name) = self.link_name(entry) { + if !name.text.is_empty() { + entry.label.clone_from(&name.text); + if entry.off_site + && normal(&entry.label).starts_with("open on ") + && entry.role.is_some() + { + if let Some(name) = path_name(entry.key.as_url()) { + entry.label = name; + } + } + } + if name.action { + entry.tier = Tier::Action; + } + } + if is_action { + entry.tier = Tier::Action; + } + } + + pub(super) fn edit_card(&mut self, landing: Option<&Url>) { + let mut candidates = Vec::new(); + let entries = std::mem::take(&mut self.sections); + let saw_nav = entries + .iter() + .any(|e| e.sources.contains(&Source::PrimaryNav)); + let locale_paths: BTreeSet<_> = entries + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter_map(|e| { + let u = e.key.as_url(); + let path = u.path().trim_matches('/'); + (locale(path) + && u.domain().map(|h| h.trim_start_matches("www.")) + == Some(self.key.host.as_str()) + && !e.label.eq_ignore_ascii_case(path)) + .then_some(path.to_owned()) + }) + .collect(); + let home = |e: &Entry| { + self_link(e, &self.entry, landing) + || (locale_paths.len() > 1 + && e.locator == Locator::default() + && e.key.as_url().query().is_none() + && e.key + .as_url() + .domain() + .map(|h| h.trim_start_matches("www.")) + == Some(self.key.host.as_str()) + && locale_paths.contains(e.key.as_url().path().trim_matches('/'))) + }; + let originals: std::collections::HashMap<_, _> = entries + .iter() + .map(|e| ((e.key.page_match(), e.locator.clone()), e.id.clone())) + .collect(); + for mut entry in entries { + self.apply_link_name(&mut entry); + for child in &mut entry.children { + self.apply_link_name(child); + } + let remove = home(&entry) || placeholder(&entry.label); + let keep_members = !placeholder(&entry.label) || !entry.sources.contains(&Source::Llms); + for mut child in entry + .children + .extract_if(.., |c| remove || c.tier == Tier::Action) + { + if (keep_members || child.tier == Tier::Action) + && !placeholder(&child.label) + && !home(&child) + { + if let Some(id) = + originals.get(&(child.key.page_match(), child.locator.clone())) + { + child.id = id.clone(); + } + candidates.push(child); + } + } + if !remove { + candidates.push(entry); + } + } + // Prefer the site's navigation over a second representation in a list or result. + candidates.sort_by_key(|e| e.tier); + let roots: BTreeSet<_> = candidates + .iter() + .filter(|e| { + (e.key.as_url().path() == "/" || self.link_name(e).is_some_and(|n| n.host_root)) + && e.locator == Locator::default() + }) + .map(|e| e.key.as_url().host_str().map(str::to_owned)) + .collect(); + let mut destinations = std::collections::HashMap::new(); + let mut labels = BTreeMap::new(); + let mut editions = BTreeMap::new(); + for mut e in candidates { + if action(&e) { + e.tier = Tier::Action; + } else if e.tier == Tier::Primary + && ((e.key.as_url().host_str() != self.entry.as_url().host_str() + && roots.contains(&e.key.as_url().host_str().map(str::to_owned)) + && e.key.as_url().path().trim_matches('/').contains('/')) + || e.key.as_url().path().contains("/news/") && e.label.ends_with('!')) + { + e.tier = Tier::Secondary; + } else if e.tier == Tier::Primary && (sentence(&e.label) || version_badge(&e.label)) { + if let Some(name) = path_name(e.key.as_url()) { + e.label = name; + } else { + e.tier = Tier::Secondary; + } + } + let destination = (localized_key(&e.key), e.locator.clone()); + let label = crate::flatten(&e.label).to_lowercase(); + let edition = self + .link_name(&e) + .filter(|n| n.language_host) + .and_then(|_| e.key.as_url().domain()?.split_once('.')) + .map(|(_, host)| { + ( + host.to_owned(), + e.key.as_url()[url::Position::BeforePath..].to_owned(), + e.locator.fragment(), + ) + }); + if edition.is_some() { + e.tier = Tier::Secondary; + } + let existing = destinations + .get(&destination) + .or_else(|| edition.as_ref().and_then(|key| editions.get(key))) + .or_else(|| labels.get(&label)) + .copied(); + if let Some(i) = existing { + let kept: &mut Entry = &mut self.place.sections[i]; + let tier = kept.tier; + kept.add_sources(e.sources.iter().copied()); + kept.tier = if tier == Tier::Action || e.tier == Tier::Action { + Tier::Action + } else { + tier.min(e.tier) + }; + let children = std::mem::take(&mut e.children); + if destination != (localized_key(&kept.key), kept.locator.clone()) { + kept.child(e, self.requested); + } + for child in children { + kept.child(child, self.requested); + } + destinations.insert(destination, i); + labels.insert(label, i); + if let Some(key) = edition { + editions.insert(key, i); + } + } else { + let index = self.sections.len(); + destinations.insert(destination, index); + labels.insert(label, index); + if let Some(key) = edition { + editions.insert(key, index); + } + self.sections.push(e); + } + } + self.prefer_observed_directories(); + if saw_nav + && self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && !e.utility()) + .count() + < MIN_NAV_ROWS + { + for e in &mut self.sections { + if e.tier == Tier::Secondary + && e.sources.contains(&Source::Footer) + && !e.utility() + && !sentence(&e.label) + && e.role.is_some() + && section_role("", e.key.as_url()) == e.role + { + e.tier = Tier::Primary; + } + } + } + } + fn prefer_observed_directories(&mut self) { + let mut children = BTreeMap::<_, Vec<usize>>::new(); + for (i, e) in self.sections.iter().enumerate().filter(|(_, e)| { + e.tier == Tier::Primary + && !e + .children + .iter() + .any(|c| c.sources.contains(&Source::MenuGroup)) + }) { + let url = e.key.as_url(); + if let Some((parent, _)) = url.path().trim_end_matches('/').rsplit_once('/') { + if !parent.is_empty() { + children + .entry((url.origin().ascii_serialization(), parent.to_owned())) + .or_default() + .push(i); + } + } + } + let parents: BTreeMap<_, _> = self + .sections + .iter() + .enumerate() + .filter(|(_, e)| { + e.tier != Tier::Action + && e.locator == Locator::default() + && e.key.as_url().query().is_none() + }) + .map(|(i, e)| { + ( + ( + e.key.as_url().origin().ascii_serialization(), + e.key.as_url().path().trim_end_matches('/').to_owned(), + ), + i, + ) + }) + .collect(); + for (path, indices) in children { + let Some(&i) = parents.get(&path) else { + continue; + }; + let parent = &mut self.sections[i]; + let release_listing = matches!( + parent.role, + Some(SectionRole::Changelog | SectionRole::Releases) + ); + if release_listing + || (path.1.trim_matches('/').contains('/') && indices.len() >= MIN_DIRECTORY_ITEMS) + { + if let Some(name) = path_name(parent.key.as_url()) { + if parent.label.starts_with(char::is_numeric) || sentence(&parent.label) { + parent.label = name; + } + parent.tier = Tier::Primary; + for i in indices { + let child = &mut self.sections[i]; + if !release_listing || !child.sources.contains(&Source::Footer) { + child.tier = Tier::Secondary; + } + } + } + } + } + } +} + +pub(super) fn child_self(child: &Entry, parent: &Entry) -> bool { + child.locator == parent.locator && localized_key(&child.key) == localized_key(&parent.key) +} + +fn scheme_like(segment: &str) -> bool { + segment.strip_suffix(':').is_some_and(|scheme| { + scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) +} + +pub fn display_path(url: &Url) -> String { + let mut out = String::new(); + for segment in url.path().split('/').filter(|s| !s.is_empty()) { + if scheme_like(segment) { + break; + } + out.push('/'); + out.push_str(segment); + } + if out.is_empty() { + out.push('/'); + } + match out.char_indices().nth(MAX_PATH_CHARS) { + Some((cut, _)) => out[..cut].to_owned(), + None => out, + } +} + +pub(super) fn same_display(left: &Entry, right: &Entry) -> bool { + if left.key.as_url().domain() != right.key.as_url().domain() { + return false; + } + let name = |e: &Entry| { + let label = crate::flatten(&e.label).to_lowercase(); + if label.contains("://") + || label + .split_whitespace() + .any(|w| w.starts_with("http:") || w.starts_with("https:") || w.starts_with("www.")) + { + display_path(e.key.as_url()).to_lowercase() + } else { + label + } + }; + name(left) == name(right) && display_path(left.key.as_url()) == display_path(right.key.as_url()) +} + +pub fn display_hostname(url: &Url) -> Option<&str> { + let host = url.domain()?.trim_end_matches('.'); + (!host.is_empty() + && host.len() <= MAX_HOST_BYTES + && host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))) + .then_some(host) +} diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index e22f88bfb..48c0feecf 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -80,18 +80,53 @@ impl Build<'_> { { continue; } + let prefix = n.text.get(..n.link_prefix_bytes).filter(|s| { + !s.is_empty() + && n.text[s.len()..].starts_with(char::is_whitespace) + && s.chars().any(char::is_alphabetic) + && !matches!(normal(s).as_str(), "new" | "beta") + }); + let label = [Some(n.name.trim()), Some(n.text.trim()), prefix] + .into_iter() + .flatten() + .filter(|s| !s.is_empty()) + .min_by_key(|s| s.chars().count()) + .unwrap_or_default(); + let marked_action = n.marks.has(crate::doc::Marks::ACTION); let parent = ancestors(nodes, i).skip(1).find_map(|a| { owners .get(&a) .copied() .filter(|_| n.parent_index() != Some(a) || nodes[a].role == Role::ListItem) }); + let hint = |name: &str| LinkName { + text: clip(&crate::clean_text(name), TITLE_BYTES), + action: marked_action, + host_root: url.path() == "/" && url.query().is_none(), + language_host: n.marks.has(crate::doc::Marks::LANGUAGE_HOST), + }; if nav && !footer && parent.is_none() { - if let Some((item, label)) = ancestors(nodes, i) + if let Some((item, group)) = ancestors(nodes, i) .take_while(|&a| !matches!(nodes[a].role, Role::Landmark { landmark: _ })) .find_map(|a| menu_labels.get(&a).map(|s| (a, *s))) { - if let Some(section) = self.entry_for(url, label, Source::PrimaryNav) { + if let Some(section) = self.entry_for(url, group, Source::PrimaryNav) { + let name = if section_role(label, url).is_some() + && normal(label) + == normal( + url.path() + .trim_matches('/') + .rsplit('/') + .next() + .unwrap_or_default(), + ) { + label + } else { + group + }; + self.names + .entry(section.id.clone()) + .or_insert_with(|| hint(name)); let index = self.section(section); owners.insert(item, index); } @@ -108,6 +143,14 @@ impl Build<'_> { let Some(mut entry) = self.entry_for(url, n.accessible_name(), source) else { continue; }; + let name = self + .names + .entry(entry.id.clone()) + .or_insert_with(|| hint(label)); + name.action |= marked_action; + if card::sentence(&name.text) && !card::sentence(label) && !label.is_empty() { + name.text = clip(&crate::clean_text(label), TITLE_BYTES); + } if footer { entry.group = ancestors(nodes, i).find_map(|a| group_labels.get(&a).cloned()); } diff --git a/crates/zephium-map/tests/card.rs b/crates/zephium-map/tests/card.rs new file mode 100644 index 000000000..1d047da2e --- /dev/null +++ b/crates/zephium-map/tests/card.rs @@ -0,0 +1,244 @@ +use proptest::prelude::*; +use url::Url; +use zephium_map::{ + site::{read_site, MAX_ACTIONS, MAX_PRIMARY_LABEL_CHARS}, + Doc, DocLimits, Place, Tier, +}; + +fn card(markup: &str) -> Place { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html(&url, markup.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + read_site(&doc, &Default::default()).unwrap() +} + +#[test] +fn the_action_tray_observes_markup_destination_and_section_evidence() { + for count in [MAX_ACTIONS, MAX_ACTIONS + 1] { + let links: String = (0..count) + .map(|i| format!("<a download href='/asset/{i}'>Abrir {i}</a>")) + .collect(); + let p = card(&format!( + "<nav><a href='/download'>Download</a>{links}</nav>" + )); + let actions: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Action) + .collect(); + assert_eq!(actions.len(), MAX_ACTIONS); + assert_eq!( + actions.last().unwrap().label, + format!("Abrir {}", MAX_ACTIONS - 1) + ); + assert_eq!(p.sections[0].label, "Download"); + assert_eq!(p.sections[0].tier, Tier::Primary); + assert_eq!(p.notes.truncated, count > MAX_ACTIONS); + } + let p=card("<nav><a href='/auth/login'>Continuer</a><a href='/guides/get-started'>Get started</a><a href='/contact'>Contact</a></nav>"); + assert_eq!( + p.sections.iter().map(|e| e.tier).collect::<Vec<_>>(), + [Tier::Primary, Tier::Primary, Tier::Action] + ); +} + +#[test] +fn names_come_from_link_text_or_an_observed_path() { + let p=card("<nav><a href='/a'><p>Hilfe</p><p>Information für alle, die hier eine Antwort suchen.</p></a><a href='/research-notes'>Read all the stories that our researchers have published this year</a><a href='/12345'>Read everything that the team has shared with the community</a></nav>"); + assert_eq!( + p.sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Hilfe", "research notes"] + ); + assert_eq!(p.sections.last().unwrap().tier, Tier::Secondary); + for n in [MAX_PRIMARY_LABEL_CHARS, MAX_PRIMARY_LABEL_CHARS + 1] { + let label = "界".repeat(n); + let p = card(&format!("<nav><a href='/12345'>{label}</a></nav>")); + assert_eq!( + p.sections[0].tier == Tier::Primary, + n == MAX_PRIMARY_LABEL_CHARS + ); + } +} + +#[test] +fn home_and_unnamed_menu_owners_yield_their_named_destinations() { + let p=card("<nav><ul><li><a href='/'>Accueil</a><ul><li><a href='/agenda'>Agenda</a></li></ul></li><li><a href='/extras'>More</a><ul><li><a href='/archives'>Archives</a></li></ul></li><li><a href='/home'>Home</a></li></ul></nav>"); + assert_eq!( + p.sections + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Agenda", "Archives", "Home"] + ); +} + +#[test] +fn destination_label_and_localized_duplicates_keep_the_first_representative() { + let base = card("<nav><a href='/de/preise'>Preise</a></nav>"); + let merged=card("<nav><a href='/de/preise'>Preise</a><a href='/de/preise/'>Tarif</a><a href='/preise'>Kosten</a><a href='/business'>Preise</a></nav>"); + assert_eq!(merged.sections.len(), 1); + assert_eq!(merged.sections[0].id, base.sections[0].id); + assert_eq!( + merged.sections[0].children[0].key.as_url().path(), + "/business" + ); +} + +#[test] +fn sibling_identity_uses_display_host_and_path() { + let p=card("<nav><ul><li><a href='/learn'>Learn</a><ul><li><a href='https://alpha.workshop.example/?mode=1'>Manual</a></li><li><a href='https://alpha.workshop.example/?mode=2'>Manual</a></li><li><a href='https://beta.workshop.example/'>Manual</a></li></ul></li></ul></nav>"); + let children = &p.sections[0].children; + assert_eq!(children.len(), 2); + assert_eq!( + children[0].key.as_url().domain(), + Some("alpha.workshop.example") + ); + assert_eq!( + children[1].key.as_url().domain(), + Some("beta.workshop.example") + ); +} + +proptest! { + #[test] + fn surviving_ids_ignore_label_noise_and_action_insertion(slugs in proptest::collection::btree_set("[a-z]{4,10}",1..10)) { + let mut plain=String::from("<nav>"); + let mut noisy=String::from("<nav><a href='/'>Home</a><a href='/login'>Enter</a>"); + for slug in slugs { + plain.push_str(&format!("<a href='/pages/{slug}'>{slug}</a>")); + noisy.push_str(&format!("<a href='/pages/{slug}'><span>{slug}</span><span>A longer explanation</span></a><a href='/de/pages/{slug}'>{slug}</a>")); + } + let a=card(&(plain+"</nav>")); + let b=card(&(noisy+"</nav>")); + let ids=|p:Place|p.sections.into_iter().filter(|e|e.tier==Tier::Primary).map(|e|(e.label,e.id)).collect::<Vec<_>>(); + prop_assert_eq!(ids(a),ids(b)); + } +} + +#[test] +fn language_editions_need_a_matching_language_declaration() { + let p=card("<nav><div lang='ja'><a href='https://ja.workshop.example/'>日本語</a></div><a hreflang='de' href='https://de.workshop.example/'>Deutsch</a><a href='https://ai.workshop.example/'>Studio</a><a href='/go/'>Go</a></nav>"); + assert_eq!( + p.sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Studio", "Go"] + ); + let edition = p.sections.last().unwrap(); + assert_eq!(edition.label, "日本語"); + assert_eq!(edition.children[0].label, "Deutsch"); +} + +#[test] +fn sparse_navigation_uses_a_named_footer_section_without_promoting_ancillary_links() { + for (nav, footer_tier) in [ + ("", Tier::Primary), + ("<a href='/c'>Third</a>", Tier::Secondary), + ] { + let p=card(&format!("<nav><a href='/a'>First</a><a href='/b'>Second</a>{nav}</nav><footer><a href='/pricing'>Pricing</a><a href='/privacy'>Privacy</a></footer>")); + assert_eq!( + p.sections + .iter() + .find(|e| e.label == "Pricing") + .unwrap() + .tier, + footer_tier + ); + assert_eq!( + p.sections + .iter() + .find(|e| e.label == "Privacy") + .unwrap() + .tier, + Tier::Secondary + ); + } +} + +#[test] +fn repeated_locale_roots_are_not_sections_and_query_specific_routes_remain_distinct() { + let p=card("<nav><a href='/fr/'>Français</a><a href='/de'>Deutsch</a><a href='/products?t=one'>First</a><a href='/products?t=two'>Second</a></nav>"); + assert_eq!( + p.sections + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["First", "Second"] + ); +} + +#[test] +fn the_word_boundary_refuses_a_teaser_and_keeps_a_short_title() { + let p = card("<nav><a href='/one'>A B C D E F</a><a href='/two'>A B C D E F G</a></nav>"); + assert_eq!(p.sections[0].label, "A B C D E F"); + assert_eq!(p.sections[1].label, "two"); +} + +#[test] +fn an_observed_directory_represents_three_or_more_deep_sibling_articles() { + for (count, tier) in [(2, Tier::Secondary), (3, Tier::Primary)] { + let links: String = (0..count) + .map(|i| format!("<a href='/docs/manuals/tools/{i}'>Tool {i}</a>")) + .collect(); + let p = card(&format!( + "<nav>{links}</nav><footer><a href='/docs/manuals/tools'>42 tools</a></footer>" + )); + let directory = p + .sections + .iter() + .find(|e| e.key.as_url().path().ends_with("tools")) + .unwrap(); + assert_eq!(directory.tier, tier); + if count == 3 { + assert_eq!(directory.label, "tools"); + } + } +} + +#[test] +fn a_shared_clipped_path_does_not_create_indistinguishable_children() { + let common = "x".repeat(zephium_map::site::MAX_PATH_CHARS); + let p=card(&format!("<nav><ul><li><a href='/guide'>Guide</a><ul><li><a href='/{common}1'>Index</a></li><li><a href='/{common}2'>Index</a></li><li><a href='/{common}3'>Index C#</a></li><li><a href='/{common}4'>Index C++</a></li></ul></li></ul></nav>")); + assert_eq!( + p.sections[0] + .children + .iter() + .map(|e| e.label.as_str()) + .collect::<Vec<_>>(), + ["Index", "Index C#", "Index C++"] + ); +} + +#[test] +fn version_badges_release_items_and_breadcrumbs_do_not_displace_sections() { + let p = card("<nav><a href='/versions'>v3.4</a><a href='/changelog'>Changelog</a><a href='/changelog/cedar'>Cedar</a><a href='/changelog/feeds'>Feeds</a><a href='/topics#breadcrumbs'>Trail</a><a href='/topics#formats'>Formats</a></nav><footer><a href='/changelog/feeds'>Feeds</a></footer>"); + let primary: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .map(|e| e.label.as_str()) + .collect(); + assert_eq!(primary, ["versions", "Changelog", "Feeds", "Formats"]); + assert!(p + .sections + .iter() + .any(|e| e.label == "Cedar" && e.tier == Tier::Secondary)); +} + +#[test] +fn platform_download_calls_and_markdown_sales_contacts_are_actions() { + let p = card("<nav><a href='/downloads/solaris'>Download for Solaris</a><a href='/downloads/bsd'>BSD</a><a href='/contact/sales.md'>Talk to us</a></nav>"); + let actions: Vec<_> = p + .sections + .iter() + .filter(|e| e.tier == Tier::Action) + .map(|e| e.label.as_str()) + .collect(); + assert_eq!(actions, ["Download for Solaris", "Talk to us"]); + assert_eq!(p.sections[0].label, "BSD"); +} diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index a624a6e07..450ff8fa6 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -2018,3 +2018,41 @@ fn sitemap_fetch_requires_a_valid_media_type_essence() { ); } } + +#[test] +fn asked_probes_one_affine_section_and_focuses_only_observed_content() { + for has_match in [true, false] { + let run = run(asked(), "acme changelog", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/news'>News</a><a href='/releases'>Releases</a></nav>", + )), + Effect::Fetch { id, url, .. } if url.path() == "/releases" => Some(response( + *id, + url, + "text/html", + if has_match { + "<aside><a href='/changes'>Changelog</a></aside>" + } else { + "<aside><a href='/archive'>Archive</a></aside>" + }, + )), + _ => None, + }); + assert_eq!(run.stats.phases[&Phase::Section].started, 1); + assert!(run.stats.places[&0].probed_section); + assert!(!run.trace.iter().any(|s| s.ends_with("/news"))); + let p = run.places.last().unwrap(); + assert_eq!(p.focus.is_some(), has_match); + if has_match { + let found = section(p, "Releases") + .children + .iter() + .find(|e| e.label == "Changelog") + .unwrap(); + assert_eq!(p.focus.as_ref(), Some(&found.id)); + } + } +} diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index c86ab2517..de84733fc 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -47,7 +47,6 @@ fn ordered_site_with_all_evidence() { ("Careers", Some(Careers), Footer, false), ("Security", Some(Security), Footer, false), ("Examples", Some(Examples), LinkedData, false), - ("Home", Some(Home), LinkedData, false), ("Privacy", Some(Legal), Footer, false), ]; assert_eq!( @@ -342,7 +341,8 @@ fn labelled_menus_and_deep_landings_use_observed_destinations() { let deep = doc("/pricing", include_str!("fixtures/section-pricing.html")); let p = read_site(&deep, &Default::default()).unwrap(); assert_eq!(p.sections[0].key.as_url(), deep.page()); - assert_eq!(labels(&p.sections[0].children), ["Plan tiers", "Questions"]); + assert_eq!(labels(&p.sections), ["Plan tiers", "Questions"]); + assert!(p.sections.iter().all(|e| e.locator != Locator::default())); assert_eq!(p.entry.as_url().path(), "/"); } #[test] @@ -441,7 +441,7 @@ fn metadata_and_section_page_boundaries() { .iter() .map(|d| Link { url: d.page().clone(), - title: "Guide".into(), + title: format!("Guide {}", d.page().path()), }) .collect::<Vec<_>>(); let (p, stats) = read_site_with_stats( diff --git a/xtask/src/map_bench/report.rs b/xtask/src/map_bench/report.rs index 8d7a5d4e3..9f324c85e 100644 --- a/xtask/src/map_bench/report.rs +++ b/xtask/src/map_bench/report.rs @@ -93,6 +93,7 @@ struct Summary { struct SessionTotals { sites: u64, places_with_three_sections: u64, + card_quality: BTreeMap<&'static str, BTreeMap<&'static str, Defects>>, sources: Counts, shells: u64, walls: u64, @@ -104,6 +105,12 @@ struct SessionTotals { passage: Counts, } +#[derive(Default, Serialize)] +struct Defects { + rows: u64, + places: u64, +} + impl SessionTotals { fn collect(&mut self, label: &QueryLabel, result: &QueryResult, samples: &mut Samples) { let site_count = match label.kind { @@ -174,6 +181,18 @@ impl SessionTotals { if let Some(&sections) = outcome.stats.get(&format!("place.{index}.sections")) { if site_count > 0 { self.places_with_three_sections += u64::from(sections >= 3); + if let Some(mode) = ["all", "asked"] + .into_iter() + .find(|m| count(&format!("card.{m}")) > 0) + { + let quality = self.card_quality.entry(mode).or_default(); + for class in super::session::quality::CLASSES { + let rows = count(&format!("place.{index}.card.{class}")); + let defects = quality.entry(class).or_default(); + defects.rows = defects.rows.saturating_add(rows); + defects.places += u64::from(rows != 0); + } + } samples.sections.push(sections); samples .primary @@ -204,6 +223,20 @@ Places with at least 3 sections — {} of {} place and compare sites. ", self.places_with_three_sections, self.sites, ); + for (mode, quality) in &self.card_quality { + let _ = writeln!( + markdown, + "\n### Card quality ({mode})\n\n| Defect | Rows | Place cards |\n|---|---:|---:|" + ); + for (class, defects) in quality { + let _ = writeln!( + markdown, + "| {class} | {} | {} |", + defects.rows, defects.places + ); + } + markdown.push('\n'); + } markdown.push_str( "| Session activity | Count | | --- | ---: | diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 97dfef0f4..32faa2fa6 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -597,6 +597,22 @@ This run used synthetic results pages. Group checks and first-layer latency were Places with at least 3 sections — 1 of 1 place and compare sites. + +### Card quality (all) + +| Defect | Rows | Place cards | +|---|---:|---:| +| action | 0 | 0 | +| detail | 0 | 0 | +| duplicate | 0 | 0 | +| nameless | 0 | 0 | +| off_host_root_children | 0 | 0 | +| off_host_without_display | 0 | 0 | +| order | 0 | 0 | +| self | 0 | 0 | +| sentence | 0 | 0 | +| utility | 0 | 0 | + | Session activity | Count | | --- | ---: | | Shells | 0 | diff --git a/xtask/src/map_bench/score.rs b/xtask/src/map_bench/score.rs index a2455a488..e6ae9e738 100644 --- a/xtask/src/map_bench/score.rs +++ b/xtask/src/map_bench/score.rs @@ -169,6 +169,9 @@ pub(super) fn score(query: &CorpusQuery, outcome: &Outcome, activity: &Activity) .then(|| query.group.difference(&outcome.groups).copied().collect()); let missing_count = missing_groups.as_ref().map_or(0, Vec::len); let matched = |entry: &super::engine::Entry| { + if entry.tags.contains("action") { + return None; + } query .want .iter() diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index 761843427..5011e8bd3 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -48,6 +48,8 @@ pub(super) struct Capture { pub(super) sections: Vec<SectionAttempt>, } +pub(super) mod quality; + pub(super) fn search( query: &CorpusQuery, io: &mut dyn BenchIo, @@ -59,6 +61,14 @@ pub(super) fn search( driver.outcome.needs_results_page = true; return driver.capture(None); } + driver.outcome.stats.insert( + match sections { + Sections::Asked => "card.asked", + Sections::All => "card.all", + } + .into(), + 1, + ); let config = Config { session_id: io.session_id(), engine: SearchEngine::Google, @@ -570,6 +580,7 @@ fn flatten_stats(outcome: &mut Outcome, stats: Stats) { put("rejected_memos", stats.rejected_memos.into()); for (index, notes) in stats.places { for (key, value) in [ + ("probed_section", notes.probed_section), ("robots_truncated", notes.robots_truncated), ("entry_truncated", notes.entry_truncated), ("sections_truncated", notes.sections_truncated), @@ -640,9 +651,12 @@ fn source_tag(source: Source) -> &'static str { } fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { - let mut put = |key, value| { + let mut put = |key: &str, value| { outcome.stats.insert(format!("place.{index}.{key}"), value); }; + for (class, count) in quality::CLASSES.into_iter().zip(quality::measure(&place)) { + put(&format!("card.{class}"), count); + } let notes = place.notes; for (key, value) in [ ("shell", notes.shell), @@ -657,7 +671,14 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .filter(|e| e.tier == zephium_map::Tier::Primary) .count(); put("primary", primary as u64); - put("secondary", (place.sections.len() - primary) as u64); + put( + "secondary", + place + .sections + .iter() + .filter(|e| e.tier == zephium_map::Tier::Secondary) + .count() as u64, + ); put("sections", place.sections.len() as u64); put( "children", @@ -701,9 +722,14 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .iter() .map(|&source| source_tag(source).into()) .chain(std::iter::once( - match entry.tier { + match if section.tier == zephium_map::Tier::Action { + section.tier + } else { + entry.tier + } { zephium_map::Tier::Primary => "primary", zephium_map::Tier::Secondary => "secondary", + zephium_map::Tier::Action => "action", } .into(), )) diff --git a/xtask/src/map_bench/session/quality.rs b/xtask/src/map_bench/session/quality.rs new file mode 100644 index 000000000..fe312e68e --- /dev/null +++ b/xtask/src/map_bench/session/quality.rs @@ -0,0 +1,123 @@ +use std::collections::BTreeSet; +use zephium_map::{site::MAX_PRIMARY_LABEL_CHARS, Place, SectionRole, Source, Tier}; + +pub(in crate::map_bench) const CLASSES: [&str; 10] = [ + "action", + "sentence", + "self", + "nameless", + "duplicate", + "off_host_without_display", + "order", + "utility", + "detail", + "off_host_root_children", +]; + +pub(super) fn measure(place: &Place) -> [u64; CLASSES.len()] { + let mut counts = [0; CLASSES.len()]; + let mut labels = BTreeSet::new(); + let mut destinations = BTreeSet::new(); + let mut lower_priority = false; + for entry in place.sections.iter().filter(|e| e.tier == Tier::Primary) { + let url = entry.key.as_url(); + let label = entry.label.to_lowercase(); + let path = url.path().trim_matches('/'); + let leaf = path.rsplit('/').next().unwrap_or_default(); + let action = matches!( + leaf, + "signup" | "sign-up" | "login" | "register" | "signin" | "contact-sales" + ) || path.ends_with("contact/sales") + || matches!( + label.as_str(), + "sign in" + | "sign up" + | "log in" + | "request a demo" + | "contact sales" + | "start free trial" + ); + let sentence = entry.label.chars().count() > MAX_PRIMARY_LABEL_CHARS + || label.contains(". ") + || label.split_whitespace().count() >= 7; + let home = entry.key.page_match() == place.entry.page_match() + && entry.locator == Default::default(); + let nameless = matches!( + label.as_str(), + "" | "more" | "other" | "optional" | "menu" | "learn more" + ); + let fresh_label = labels.insert(label.clone()); + let fresh_destination = destinations.insert((entry.card_page(), entry.locator.fragment())); + let utility = entry.role == Some(SectionRole::Legal) + || matches!( + label.as_str(), + "settings" | "rss" | "account" | "dashboard" | "translations" | "search" + ) + || leaf.ends_with(".xml") + || leaf.starts_with("llms") && leaf.ends_with(".txt"); + let detail = entry.locator.element.is_some() + && url.host_str() != place.entry.as_url().host_str() + && path.contains('/'); + let minor = action || home || nameless || utility || detail; + let direct = entry.sources.contains(&Source::PrimaryNav) + || entry.sources.contains(&Source::MenuGroup); + let order = !minor && direct && lower_priority; + lower_priority |= minor || !direct; + for (n, hit) in counts.iter_mut().zip([ + action, + sentence, + home, + nameless, + !fresh_label || !fresh_destination, + false, + order, + utility, + detail, + false, + ]) { + *n += u64::from(hit); + } + } + for child in place.sections.iter().flat_map(|e| &e.children) { + let url = child.key.as_url(); + if url.path() == "/" && url.host_str() != place.entry.as_url().host_str() { + counts[9] += 1; + counts[5] += u64::from(zephium_map::site::display_hostname(url).is_none()); + } + } + counts +} + +#[cfg(test)] +mod tests { + use super::*; + use url::Url; + use zephium_map::{site::read_site, Doc, DocLimits, PageKey}; + + #[test] + fn counts_rows_for_independent_defects_and_checks_the_root_child_host() { + let url = Url::parse("https://acme.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>First</a><a href='/b'>Second</a><a href='/c'>Third</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut p = read_site(&doc, &Default::default()).unwrap(); + p.sections[0].label = "More".into(); + p.sections[0].key = p.entry.clone(); + p.sections[1].key = PageKey::from_url(&url.join("/login").unwrap()).unwrap(); + p.sections[2].label = "More".into(); + let mut child = p.sections[1].clone(); + child.key = PageKey::from_url(&Url::parse("https://docs.acme.example/").unwrap()).unwrap(); + p.sections[2].children.push(child); + let scores: std::collections::BTreeMap<_, _> = + CLASSES.into_iter().zip(measure(&p)).collect(); + assert_eq!(scores["nameless"], 2); + for class in ["action", "self", "duplicate", "off_host_root_children"] { + assert_eq!(scores[class], 1); + } + assert_eq!(scores["off_host_without_display"], 0); + } +} diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs index 1d112113b..5c207355a 100644 --- a/xtask/src/map_try/printer.rs +++ b/xtask/src/map_try/printer.rs @@ -206,14 +206,14 @@ fn place_lines(slot: u8, place: &Place) -> Vec<String> { COLUMNS - heading.len() - " ()".len(), ); let mut lines = vec![format!("{heading}{title} ({host})")]; - for tier in [Tier::Primary, Tier::Secondary] { + for tier in [Tier::Primary, Tier::Secondary, Tier::Action] { let mut sections = place .sections .iter() .filter(|entry| entry.tier == tier) .peekable(); - if tier == Tier::Secondary && sections.peek().is_some() { - lines.push(" --- Secondary ---".into()); + if tier != Tier::Primary && sections.peek().is_some() { + lines.push(format!(" --- {tier:?} ---")); } for section in sections { lines.push(entry_line(section, place.focus.as_deref(), " ")); @@ -234,7 +234,15 @@ fn entry_line(entry: &Entry, focus: Option<&str>, indent: &str) -> String { let off_site = if entry.off_site { " [off-site]" } else { "" }; let more = if entry.more { " [more]" } else { "" }; let available = COLUMNS - indent.len() - mark.len() - off_site.len() - more.len() - " ".len(); - let (label, path) = pair(&entry.label, &entry.path, available); + let display = entry + .host + .as_ref() + .map(|host| format!("{host}{}", entry.path)); + let (label, path) = pair( + &entry.label, + display.as_deref().unwrap_or(&entry.path), + available, + ); format!("{indent}{mark}{label} {path}{off_site}{more}") } From 9d296e4de97084c250d7bf0cb91ede2ea0b40d65 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 04:49:53 +0100 Subject: [PATCH 37/40] feat(map): draw a site's menus as rows with their items inside A named navigation group with two or more items is one primary row and its items are its children, whether or not the group has a page of its own. A group without a page is a row that cannot be opened but can show its children (menu_only, mirrored on the wire). Collapsed panels named by aria-controls and linked menu items are read as navigation evidence under the parser's text budget. Sections that come only from llms.txt or a sitemap merge into the navigation row with the same role and stand as rows only when navigation is sparse or the role is missing. Names derived from a path are capitalised. A place with fewer than three rows is marked thin. The bench scores each of these. Memo version 5. --- crates/zephium-map-driver/src/wire.rs | 22 +- crates/zephium-map-driver/src/wire/tests.rs | 30 ++ crates/zephium-map/src/doc.rs | 2 + crates/zephium-map/src/doc/html.rs | 92 +++- crates/zephium-map/src/doc/html/arena.rs | 1 + crates/zephium-map/src/session.rs | 4 +- crates/zephium-map/src/session/memo.rs | 20 +- crates/zephium-map/src/site.rs | 183 +++++-- crates/zephium-map/src/site/card.rs | 158 +++++- crates/zephium-map/src/site/menus.rs | 537 ++++++++++++++++++++ crates/zephium-map/src/site/navigation.rs | 13 +- crates/zephium-map/tests/card.rs | 138 ++++- crates/zephium-map/tests/session.rs | 2 +- crates/zephium-map/tests/site.rs | 22 +- xtask/src/map_bench/run/tests/session.rs | 9 +- xtask/src/map_bench/session.rs | 3 + xtask/src/map_bench/session/quality.rs | 69 ++- xtask/src/map_try/printer.rs | 7 + xtask/src/map_try/printer/tests.rs | 1 + 19 files changed, 1214 insertions(+), 99 deletions(-) create mode 100644 crates/zephium-map/src/site/menus.rs diff --git a/crates/zephium-map-driver/src/wire.rs b/crates/zephium-map-driver/src/wire.rs index c3387110d..2569d0814 100644 --- a/crates/zephium-map-driver/src/wire.rs +++ b/crates/zephium-map-driver/src/wire.rs @@ -170,6 +170,8 @@ pub struct Entry { #[serde(default, skip_serializing_if = "Option::is_none")] pub group: Option<String>, pub off_site: bool, + #[serde(default)] + pub menu_only: bool, pub open: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub host: Option<String>, @@ -183,6 +185,8 @@ pub struct Entry { #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "ipc-types", derive(specta::Type))] pub struct Notes { + #[serde(default)] + pub thin: bool, pub shell: bool, pub wall: bool, pub robots_disallowed: bool, @@ -308,7 +312,7 @@ pub enum Target { #[derive(Default)] pub(crate) struct Targets { - entries: BTreeMap<String, Url>, + entries: BTreeMap<String, Option<Url>>, site: Option<Url>, social: BTreeMap<Network, Url>, } @@ -316,7 +320,7 @@ pub(crate) struct Targets { impl Targets { pub(crate) fn resolve(&self, target: &Target) -> Option<Url> { let url = match target { - Target::Entry { id } => self.entries.get(id), + Target::Entry { id } => self.entries.get(id)?.as_ref(), Target::Site => self.site.as_ref(), Target::Social { network } => self.social.get(network), Target::Also { .. } => None, @@ -404,25 +408,29 @@ fn entry( place_host: Option<&str>, open: bool, seen: &mut BTreeSet<String>, - targets: &mut BTreeMap<String, Url>, + targets: &mut BTreeMap<String, Option<Url>>, ) -> Option<Entry> { let id = source.id.as_str(); if !valid_id(id) || seen.contains(id) { return None; } - let path = path(source.key.as_url()); + let path = if source.menu_only { + String::new() + } else { + path(source.key.as_url()) + }; let label = text(&source.label); let label = if label.is_empty() { return None; } else if !address_shaped(&label) { label - } else if path != "/" { + } else if !path.is_empty() && path != "/" { path.clone() } else { return None; }; seen.insert(id.to_owned()); - targets.insert(id.to_owned(), address(source)); + targets.insert(id.to_owned(), (!source.menu_only).then(|| address(source))); let mut children = Vec::new(); let mut more = source.more > 0; if child { @@ -446,6 +454,7 @@ fn entry( role: source.role.map(Role::from), group: source.group.as_deref().and_then(shown), off_site: source.off_site, + menu_only: source.menu_only, open, host: hostname(source.key.as_url()).filter(|host| Some(host.as_str()) != place_host), path, @@ -503,6 +512,7 @@ pub(crate) fn place( .map(str::to_owned), social: networks(&source.social, &mut targets.social), notes: Notes { + thin: source.notes.thin, shell: source.notes.shell, wall: source.notes.wall, robots_disallowed: source.notes.robots_disallowed, diff --git a/crates/zephium-map-driver/src/wire/tests.rs b/crates/zephium-map-driver/src/wire/tests.rs index 5b9417a56..66c4b2248 100644 --- a/crates/zephium-map-driver/src/wire/tests.rs +++ b/crates/zephium-map-driver/src/wire/tests.rs @@ -478,3 +478,33 @@ fn action_tier_is_bounded_and_round_trips_with_its_target() { assert!(targets.has(&e.id)); } } + +#[test] +fn a_menu_only_row_projects_children_without_registering_a_page_target() { + let url = Url::parse("https://acme.com/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><div><button>Tools</button><a href='/a'>Alpha</a><a href='/b'>Beta</a></div></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let source = site::read_site(&doc, &Default::default()).unwrap(); + let (card, targets) = place(&source, Some(&Default::default())); + let menu = &card.sections[0]; + assert!(card.notes.thin && menu.menu_only && !menu.open && menu.path.is_empty()); + assert!(targets.has(&menu.id)); + assert!(targets + .resolve(&Target::Entry { + id: menu.id.clone() + }) + .is_none()); + assert_eq!(menu.children.len(), 2); + for child in &menu.children { + assert!(targets + .resolve(&Target::Entry { + id: child.id.clone() + }) + .is_some()); + } +} diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 2aba29ca6..72b7a8fa4 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -255,6 +255,7 @@ pub struct Alternate { pub struct Doc { page: Url, + pub(crate) menu_links: std::collections::BTreeMap<usize, Vec<(Url, String)>>, nodes: Vec<Node>, head: Head, truncated: bool, @@ -291,6 +292,7 @@ impl DocBuilder { Ok(Self { doc: Doc { page: page.clone(), + menu_links: Default::default(), nodes: Vec::new(), head: Head::default(), truncated: false, diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index 8c008a649..aaeb9cf69 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -349,6 +349,91 @@ impl DocBuilder { } } + fn disclosure_links(&mut self, button: NodeRef<'_>, base: &Url, index: usize) { + let Some(id) = button + .attr("aria-controls") + .filter(|s| !s.is_empty() && !button.clipped("aria-controls")) + else { + return; + }; + let Some(panel) = + std::iter::successors(button.sibling(), |n| n.sibling()).find(|n| !n.is_text()) + else { + return; + }; + if panel.attr("id") != Some(id) + || panel.clipped("id") + || panel.hidden_by_lift() + || panel.has_attr("hidden") + || panel.attr("aria-hidden") != Some("true") + || !super::super::ancestors(&self.doc.nodes, index).any(|a| { + matches!( + self.doc.nodes[a].role, + Role::Landmark { + landmark: Some(Landmark::Navigation) + } + ) + }) + { + return; + } + // Collapsed panel links belong to the control. Its hidden text never enters the document. + let mut links = Vec::new(); + let mut pending = panel + .children() + .next() + .map(|n| (n, None)) + .into_iter() + .collect::<Vec<_>>(); + while let Some((n, anchor)) = pending.pop() { + if let Some(next) = n.sibling() { + pending.push((next, anchor)); + } + if hidden(&n) + || excluded(marks(&n)) + || excluded(n.lifted_marks()) + || matches!( + n.tag(), + "script" | "style" | "template" | "noscript" | "svg" + ) + { + continue; + } + let mut anchor: Option<usize> = anchor; + if n.tag() == "a" { + anchor = None; + if let Some(url) = self + .resolve(&n, "href", base) + .filter(|_| !n.has_attr("download")) + { + let size = url.as_str().len(); + if size > self.limits.text_bytes as usize - self.text_bytes { + self.mark_truncated(); + break; + } + self.text_bytes += size; + let label = self.head_text( + n.attr("aria-label").unwrap_or_default(), + self.limits.node_text_bytes as usize, + ); + anchor = Some(links.len()); + links.push((url, label)); + } + } else if let Some(i) = anchor { + let label = &mut links[i].1; + if label.is_empty() && n.is_text() && !n.text().trim().is_empty() { + *label = self.head_text(n.text().trim(), self.limits.node_text_bytes as usize); + } + } + if let Some(child) = n.children().next() { + pending.push((child, anchor)); + } + } + if !links.is_empty() { + self.doc.menu_links.insert(index, links); + } + } + fn walk(&mut self, body: NodeRef<'_>, base: &Url) -> Result<(), DocError> { let mut pending = vec![Some((body, None::<usize>, 0, false))]; while let Some(step) = pending.pop() { @@ -531,7 +616,11 @@ impl DocBuilder { - node.element_id.as_deref().map_or(0, str::len); node.language = language.filter(|s| s.len() <= room).map(str::to_owned); } - (Some(self.push(node)? as usize), level + 1) + let index = self.push(node)? as usize; + if role == Role::Button { + self.disclosure_links(n, base, index); + } + (Some(index), level + 1) } else { (parent, level) }; @@ -654,6 +743,7 @@ fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { "spinbutton" => Spinbutton, "slider" => Slider, "tab" => Tab, + "menuitem" if tag == "a" && n.has_attr("href") => Link, "menuitem" => MenuItem, "progressbar" => Progress, "status" | "alert" => Status, diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index fb1c8af33..19a94544c 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -37,6 +37,7 @@ const ATTRIBUTE_NAMES: &[&str] = &[ "data-type", "data-testid", "aria-labelledby", + "aria-controls", "hreflang", "lang", "download", diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index 1e1269c9a..78ae215ec 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -821,7 +821,9 @@ impl Session { detail.probed_section = state.probed_section; self.stats.places.insert(i as u8, detail); for entry in &mut place.sections { - if self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) { + if entry.menu_only + || self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) + { continue; } let discovered = state diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index 99df55755..d39462f26 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -3,7 +3,7 @@ use crate::results::{MAX_SOCIAL, TITLE_BYTES}; use crate::site::{MAX_CHILDREN, MAX_SECTIONS}; use serde::{Deserialize, Serialize}; -pub const MEMO_VERSION: u16 = 4; +pub const MEMO_VERSION: u16 = 5; pub const MAX_MEMO_BYTES: usize = 256 * 1024; pub const MEMO_TTL: u64 = 24 * 60 * 60; #[derive(Clone, Serialize, Deserialize)] @@ -49,6 +49,13 @@ impl SiteMemo { || SiteKey::from_url(p.entry.as_url()).as_ref() != Some(&p.site) || p.title.len() > TITLE_BYTES || p.focus.is_some() + || p.notes.thin + != (p + .sections + .iter() + .filter(|e| e.tier == site::Tier::Primary) + .count() + < site::MIN_NAV_ROWS) || p.notes.shell || p.notes.wall || p.sections @@ -136,6 +143,17 @@ fn valid_entry(e: &Entry, place: &Place, parent: Option<&Entry>) -> bool { if site != place.site && !delegated && !(site_nav && site::external_role(e.role)) { return false; } + if e.menu_only + && (parent.is_some() + || e.key != place.entry + || e.locator != Locator::default() + || e.tier != site::Tier::Primary + || e.children.is_empty() + || e.id != site::EntryId::menu(&place.entry, &e.label) + || !e.navigation_row()) + { + return false; + } if e.off_site != (site != place.site) { return false; } diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index 4ee4b4f27..cd10d37db 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -15,10 +15,12 @@ use crate::{ use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use url::Url; +pub const MIN_NAV_ROWS: usize = 3; mod card; pub use card::{ display_hostname, display_path, MAX_HOST_BYTES, MAX_PATH_CHARS, MAX_PRIMARY_LABEL_CHARS, }; +mod menus; mod navigation; mod sitemap; pub use sitemap::{Sitemap, XmlError, MAX_SITEMAP_URLS, MAX_XML_BYTES, MAX_XML_DEPTH}; @@ -70,10 +72,10 @@ pub struct EntryId(String); impl EntryId { fn new(parent: Option<&EntryId>, key: &PageKey, locator: &Locator) -> Self { // FNV-1a over length-delimited discovery fields, independent of Rust's Hash implementation. - let mut hash = 0xcbf29ce484222325u64; + let matched = key.page_match(); let q = locator.quote.as_ref(); - for part in [ + Self::hash([ parent.map(|p| p.0.as_str()), Some(matched.as_str()), locator.element.as_ref().map(LocatorText::as_str), @@ -81,7 +83,18 @@ impl EntryId { q.map(|q| q.start.as_str()), q.and_then(|q| q.end.as_ref()).map(LocatorText::as_str), q.and_then(|q| q.suffix.as_ref()).map(LocatorText::as_str), - ] { + ]) + } + pub(crate) fn menu(root: &PageKey, label: &str) -> Self { + Self::hash([ + Some("menu"), + Some(root.page_match().as_str()), + Some(&normal(label)), + ]) + } + fn hash<'a>(parts: impl IntoIterator<Item = Option<&'a str>>) -> Self { + let mut hash = 0xcbf29ce484222325u64; + for part in parts { let bytes = part.unwrap_or_default().as_bytes(); for b in (bytes.len() as u32) .to_be_bytes() @@ -115,6 +128,12 @@ pub struct Entry { pub label: String, pub role: Option<SectionRole>, pub sources: Vec<Source>, + #[serde(default)] + pub menu_only: bool, + #[serde(default)] + pub menu_item: bool, + #[serde(default)] + pub path_name: bool, pub off_site: bool, pub group: Option<String>, pub children: Vec<Entry>, @@ -122,6 +141,8 @@ pub struct Entry { } #[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PlaceNotes { + #[serde(default)] + pub thin: bool, pub shell: bool, pub wall: bool, pub robots_disallowed: bool, @@ -231,7 +252,7 @@ fn normal(s: &str) -> String { .join(" ") } pub(crate) fn section_role(name: &str, url: &Url) -> Option<SectionRole> { - for value in [ + [ name, url.path() .trim_matches('/') @@ -241,18 +262,24 @@ pub(crate) fn section_role(name: &str, url: &Url) -> Option<SectionRole> { url.host_str() .and_then(|h| h.split('.').next()) .unwrap_or_default(), - ] { - let label = normal(value); - if let Some((_, role)) = SECTION_WORDS.iter().find(|(w, _)| { - label.match_indices(w).any(|(i, _)| { - (i == 0 || label.as_bytes()[i - 1] == b' ') - && label.as_bytes().get(i + w.len()).is_none_or(|b| *b == b' ') - }) - }) { - return Some(*role); - } + ] + .into_iter() + .find_map(label_role) + .or_else(|| { + (url.path() == "/" && name.eq_ignore_ascii_case("home")).then_some(SectionRole::Home) + }) +} +fn label_role(value: &str) -> Option<SectionRole> { + let label = normal(value); + if let Some((_, role)) = SECTION_WORDS.iter().find(|(w, _)| { + label.match_indices(w).any(|(i, _)| { + (i == 0 || label.as_bytes()[i - 1] == b' ') + && label.as_bytes().get(i + w.len()).is_none_or(|b| *b == b' ') + }) + }) { + return Some(*role); } - (url.path() == "/" && name.eq_ignore_ascii_case("home")).then_some(SectionRole::Home) + None } pub(crate) fn external_role(role: Option<SectionRole>) -> bool { matches!( @@ -319,6 +346,7 @@ struct LinkName { host_root: bool, } struct Build<'a> { + llms_headings: BTreeMap<EntryId, String>, names: std::collections::HashMap<EntryId, LinkName>, place: Place, index: std::collections::HashMap<(crate::PageMatch, Locator), usize>, @@ -379,6 +407,9 @@ impl Build<'_> { let locator = element_locator(url).ok()?; Some(Entry { id: EntryId::new(None, &key, &locator), + menu_only: false, + menu_item: false, + path_name: false, read: None, tier: source.tier(), key, @@ -410,12 +441,39 @@ impl Build<'_> { let requested = self.requested; self.sections[index].child(entry, requested); } - fn finish_sections(&mut self, landing: Option<&Url>) { + fn finish_sections(&mut self, landing: Option<&Url>, menus: Option<menus::Menus>) { + for e in &mut self.sections { + if e.sources + .first() + .is_some_and(|s| matches!(s, Source::Llms | Source::Sitemap)) + { + e.role = label_role(&e.label); + } + } + let saw_nav = self + .sections + .iter() + .any(|e| e.sources.contains(&Source::PrimaryNav)); self.edit_card(landing); let cluster_primary = !self .sections .iter() - .any(|e| e.tier == Tier::Primary && !e.utility()); + .any(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()); + if cluster_primary { + for e in &mut self.sections { + if e.tier != Tier::Action + && e.sources.contains(&Source::LinkCluster) + && !card::sentence(&e.label) + { + e.tier = Tier::Primary; + } + } + } + if let Some(menus) = menus { + menus.apply(self); + } + self.fill_from_footer(saw_nav); + self.merge_supplements(); let globals: BTreeSet<_> = self .sections .iter() @@ -424,13 +482,6 @@ impl Build<'_> { .collect(); let demoted = Entry::utility; for e in &mut self.sections { - if e.tier != Tier::Action - && e.sources.contains(&Source::LinkCluster) - && cluster_primary - && !card::sentence(&e.label) - { - e.tier = Tier::Primary; - } if e.tier != Tier::Action && demoted(e) { e.tier = Tier::Secondary; } @@ -449,14 +500,10 @@ impl Build<'_> { } e.children = distinct; } + self.sections + .retain(|e| !e.menu_only || !e.children.is_empty()); self.sections.sort_by_cached_key(|e| { - let supplemental = e.tier == Tier::Primary - && !e.sources.iter().any(|s| { - matches!( - s, - Source::PrimaryNav | Source::MenuGroup | Source::LinkCluster - ) - }); + let supplemental = e.tier == Tier::Primary && !e.navigation_row(); ( e.tier, e.utility(), @@ -465,6 +512,12 @@ impl Build<'_> { ) }); self.select_sections(); + self.notes.thin = self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .count() + < MIN_NAV_ROWS; let total: usize = self.sections.iter().map(|e| e.children.len()).sum(); for _ in MAX_PLACE_CHILDREN..total { if let Some(section) = self @@ -682,6 +735,10 @@ impl Build<'_> { i } }; + let id = self.sections[parent].id.clone(); + self.llms_headings + .entry(id) + .or_insert_with(|| normal(&clip(label, TITLE_BYTES))); self.sections[parent].add_sources([Source::Llms]); self.child(parent, child); } @@ -710,9 +767,15 @@ impl Build<'_> { let index = if let Some(i) = existing { i } else { - let Some(entry) = self.entry_for(first.as_url(), seg, Source::Sitemap) else { + let Some(entry) = self.entry_for( + first.as_url(), + &card::capitalized(&decode_fragment(seg)), + Source::Sitemap, + ) else { continue; }; + let mut entry = entry; + entry.path_name = true; self.section(entry) }; self.sections[index].add_sources([Source::Sitemap]); @@ -728,7 +791,11 @@ impl Build<'_> { .next() .unwrap_or_default() .replace('-', " "); - if let Some(child) = self.entry_for(key.as_url(), &label, Source::Sitemap) { + if let Some(child) = self.entry_for( + key.as_url(), + &card::capitalized(&decode_fragment(&label)), + Source::Sitemap, + ) { self.child(index, child); } } @@ -785,7 +852,8 @@ impl Place { let Some(entry) = self.sections.iter().find(|entry| &entry.id == id) else { return false; }; - !entry.off_site + !entry.menu_only + && !entry.off_site && SiteKey::from_url(entry.key.as_url()).as_ref() == Some(&self.site) && (self.key.tenant.is_none() || PlaceKey::from_url(entry.key.as_url()).as_ref() == Some(&self.key)) @@ -812,7 +880,8 @@ impl Place { landing: &'a Url, ) -> impl Iterator<Item = &'a Entry> { self.sections.iter().filter(move |entry| { - entry.key.page_match() != self.entry.page_match() + !entry.menu_only + && entry.key.page_match() != self.entry.page_match() && !crate::key::same_page(entry.key.as_url(), landing) && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) }) @@ -829,7 +898,8 @@ impl Place { self.sections .iter() .filter(|e| { - !e.off_site + !e.menu_only + && !e.off_site && e.tier != Tier::Action && e.key.as_url().origin() == landing.origin() && !crate::key::same_page(e.key.as_url(), landing) @@ -969,6 +1039,9 @@ impl Entry { fn leaf(&self, source: Source, label: &str) -> Entry { Entry { id: self.id.clone(), + menu_only: false, + menu_item: false, + path_name: false, read: None, tier: source.tier(), key: self.key.clone(), @@ -1011,13 +1084,24 @@ impl Entry { !exact(&self.label), ) } - fn child(&mut self, mut entry: Entry, requested: Option<&Focus>) { + fn child(&mut self, entry: Entry, requested: Option<&Focus>) { + self.insert_child(entry, requested, None); + } + fn insert_child( + &mut self, + mut entry: Entry, + requested: Option<&Focus>, + discovered: Option<EntryId>, + ) { if let Some(existing) = self .children .iter_mut() .find(|e| e.key.page_match() == entry.key.page_match() && e.locator == entry.locator) { existing.add_sources(entry.sources); + if let Some(id) = discovered { + existing.id = id; + } return; } if self.children.iter().any(|c| card::same_display(c, &entry)) { @@ -1037,7 +1121,8 @@ impl Entry { self.more += 1; } if self.children.len() < MAX_CHILDREN { - entry.id = EntryId::new(Some(&self.id), &entry.key, &entry.locator); + entry.id = discovered + .unwrap_or_else(|| EntryId::new(Some(&self.id), &entry.key, &entry.locator)); self.children.push(entry); } else { self.more += 1; @@ -1054,7 +1139,9 @@ impl Build<'_> { self.sections[index].children.append(&mut preferred); self.section_page(index, page); for child in others { - self.child(index, child); + let id = child.id.clone(); + let requested = self.requested; + self.sections[index].insert_child(child, requested, Some(id)); } } } @@ -1067,6 +1154,7 @@ pub(crate) fn enrich_held( ) -> (Place, PlaceStats) { let mut build = Build { names: Default::default(), + llms_headings: Default::default(), place, index: Default::default(), requested: None, @@ -1123,10 +1211,12 @@ pub(crate) fn with_results( ) -> Result<Place, KeyError> { let mut build = Build { names: Default::default(), + llms_headings: Default::default(), index: place .sections .iter() .enumerate() + .filter(|(_, e)| !e.menu_only) .map(|(i, e)| ((e.key.page_match(), e.locator.clone()), i)) .collect(), requested, @@ -1140,19 +1230,22 @@ pub(crate) fn with_results( .chain(hint.map(|link| (link, Source::EngineResult))) { if let Some(entry) = build.entry_for(&link.url, &link.title, source) { - if let Some(existing) = build + if let Some(existing) = build.sections.iter_mut().find(|e| e.id == entry.id) { + existing.add_sources(entry.sources); + } else if let Some(child) = build .sections .iter_mut() - .find(|existing| existing.id == entry.id) + .flat_map(|e| &mut e.children) + .find(|e| e.id == entry.id || (e.key == entry.key && e.locator == entry.locator)) { - existing.add_sources(entry.sources); + child.add_sources(entry.sources); } else { build.section(entry); } } } build.stats.sitelinks_truncated = links.len() > MAX_SITELINKS; - build.finish_sections(None); + build.finish_sections(None, None); build.notes.truncated |= build.stats.truncated(); build.check_ids()?; Ok(build.place) @@ -1183,6 +1276,7 @@ pub(crate) fn read_site_for( .unwrap_or_default(); let mut place = Build { names: Default::default(), + llms_headings: Default::default(), index: Default::default(), requested, stats: PlaceStats::default(), @@ -1286,7 +1380,8 @@ pub(crate) fn read_site_for( }) .count(); let eager = place.eager_reads(); - place.finish_sections(Some(doc.page())); + let menus = (!place.notes.wall).then(|| menus::Menus::read(&place, doc)); + place.finish_sections(Some(doc.page()), menus); place.check_ids()?; place.notes.truncated = place.stats.truncated() || place.sections.iter().any(|e| e.more > 0); Ok((place.place, place.stats, eager)) diff --git a/crates/zephium-map/src/site/card.rs b/crates/zephium-map/src/site/card.rs index 4f4499509..12bd9b218 100644 --- a/crates/zephium-map/src/site/card.rs +++ b/crates/zephium-map/src/site/card.rs @@ -5,7 +5,6 @@ pub const MAX_PRIMARY_LABEL_CHARS: usize = 48; pub const MAX_HOST_BYTES: usize = 253; pub const MAX_PATH_CHARS: usize = 128; const SENTENCE_WORDS: usize = 7; -const MIN_NAV_ROWS: usize = 3; const MIN_DIRECTORY_ITEMS: usize = 3; fn locale(segment: &str) -> bool { @@ -34,7 +33,7 @@ fn localized_key(key: &PageKey) -> PageMatch { PageKey::from_url(&url).map_or_else(|_| key.page_match(), |k| k.page_match()) } -fn placeholder(label: &str) -> bool { +pub(super) fn placeholder(label: &str) -> bool { matches!( normal(label).as_str(), "" | "other" @@ -65,6 +64,7 @@ fn version_badge(label: &str) -> bool { fn path_name(url: &Url) -> Option<String> { let slug = url.path_segments()?.rfind(|s| !s.is_empty())?; + let slug = super::decode_fragment(slug); let name = slug .trim_end_matches(".html") .trim_end_matches(".md") @@ -74,7 +74,16 @@ fn path_name(url: &Url) -> Option<String> { && !placeholder(&name) && name.chars().any(char::is_alphabetic) && name.chars().all(|c| c.is_alphanumeric() || c == ' ')) - .then_some(name) + .then(|| capitalized(&name)) + .filter(|s| !sentence(s)) +} + +pub(super) fn capitalized(name: &str) -> String { + let mut chars = name.chars(); + match chars.next() { + Some(c) => c.to_uppercase().chain(chars).collect(), + None => String::new(), + } } pub(super) fn action(entry: &Entry) -> bool { @@ -135,7 +144,7 @@ pub(super) fn action(entry: &Entry) -> bool { ) } -fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> bool { +pub(super) fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> bool { if entry.locator != Locator::default() { return false; } @@ -183,6 +192,7 @@ impl Build<'_> { && entry.role.is_some() { if let Some(name) = path_name(entry.key.as_url()) { + entry.path_name = true; entry.label = name; } } @@ -199,9 +209,6 @@ impl Build<'_> { pub(super) fn edit_card(&mut self, landing: Option<&Url>) { let mut candidates = Vec::new(); let entries = std::mem::take(&mut self.sections); - let saw_nav = entries - .iter() - .any(|e| e.sources.contains(&Source::PrimaryNav)); let locale_paths: BTreeSet<_> = entries .iter() .flat_map(|e| std::iter::once(e).chain(&e.children)) @@ -236,7 +243,7 @@ impl Build<'_> { for child in &mut entry.children { self.apply_link_name(child); } - let remove = home(&entry) || placeholder(&entry.label); + let remove = !entry.menu_only && (home(&entry) || placeholder(&entry.label)); let keep_members = !placeholder(&entry.label) || !entry.sources.contains(&Source::Llms); for mut child in entry .children @@ -259,7 +266,7 @@ impl Build<'_> { } } // Prefer the site's navigation over a second representation in a list or result. - candidates.sort_by_key(|e| e.tier); + candidates.sort_by_key(|e| (!e.navigation_row(), e.tier)); let roots: BTreeSet<_> = candidates .iter() .filter(|e| { @@ -283,12 +290,17 @@ impl Build<'_> { e.tier = Tier::Secondary; } else if e.tier == Tier::Primary && (sentence(&e.label) || version_badge(&e.label)) { if let Some(name) = path_name(e.key.as_url()) { + e.path_name = true; e.label = name; } else { e.tier = Tier::Secondary; } } - let destination = (localized_key(&e.key), e.locator.clone()); + let destination = ( + localized_key(&e.key), + e.locator.clone(), + e.menu_only.then(|| e.id.clone()), + ); let label = crate::flatten(&e.label).to_lowercase(); let edition = self .link_name(&e) @@ -319,7 +331,13 @@ impl Build<'_> { tier.min(e.tier) }; let children = std::mem::take(&mut e.children); - if destination != (localized_key(&kept.key), kept.locator.clone()) { + if destination + != ( + localized_key(&kept.key), + kept.locator.clone(), + kept.menu_only.then(|| kept.id.clone()), + ) + { kept.child(e, self.requested); } for child in children { @@ -341,11 +359,13 @@ impl Build<'_> { } } self.prefer_observed_directories(); + } + pub(super) fn fill_from_footer(&mut self, saw_nav: bool) { if saw_nav && self .sections .iter() - .filter(|e| e.tier == Tier::Primary && !e.utility()) + .filter(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) .count() < MIN_NAV_ROWS { @@ -414,6 +434,7 @@ impl Build<'_> { { if let Some(name) = path_name(parent.key.as_url()) { if parent.label.starts_with(char::is_numeric) || sentence(&parent.label) { + parent.path_name = true; parent.label = name; } parent.tier = Tier::Primary; @@ -430,7 +451,9 @@ impl Build<'_> { } pub(super) fn child_self(child: &Entry, parent: &Entry) -> bool { - child.locator == parent.locator && localized_key(&child.key) == localized_key(&parent.key) + !parent.menu_only + && child.locator == parent.locator + && localized_key(&child.key) == localized_key(&parent.key) } fn scheme_like(segment: &str) -> bool { @@ -488,3 +511,112 @@ pub fn display_hostname(url: &Url) -> Option<&str> { .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))) .then_some(host) } + +impl Entry { + pub fn navigation_row(&self) -> bool { + self.sources.iter().any(|s| { + matches!( + s, + Source::PrimaryNav | Source::MenuGroup | Source::LinkCluster + ) + }) + } +} + +impl Build<'_> { + pub(super) fn merge_supplements(&mut self) { + let sparse = self + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) + .count() + < MIN_NAV_ROWS; + let mut roles = BTreeMap::new(); + let mut names = BTreeMap::new(); + let mut docs = None; + let mut merged = BTreeMap::new(); + for (i, e) in self + .sections + .iter() + .enumerate() + .filter(|(_, e)| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) + { + let label = normal(&e.label); + if matches!(label.as_str(), "docs" | "documentation") { + if let Some(parent) = docs { + names.entry(label).or_insert(parent); + merged.insert(i, parent); + continue; + } else { + docs = Some(i); + } + } + names.entry(label).or_insert(i); + if let Some(role) = e.role { + roles.entry(role).or_insert(i); + } + } + let headings = &self.llms_headings; + for (i, e) in self.place.sections.iter_mut().enumerate() { + if e.navigation_row() + || e.tier == Tier::Action + || e.utility() + || !e + .sources + .iter() + .any(|s| matches!(s, Source::Llms | Source::Sitemap)) + { + continue; + } + let heading = headings.get(&e.id); + if let Some(parent) = heading.and_then(|name| names.get(name)) { + merged.insert(i, *parent); + continue; + } + let role = heading.map_or(e.role, |name| label_role(name)); + if let Some(role) = role { + if let Some(&parent) = roles.get(&role) { + merged.insert(i, parent); + } else if !sentence(&e.label) + && (e.tier == Tier::Primary + || e.sources.first() == Some(&Source::Sitemap) + && SECTION_WORDS + .iter() + .any(|(name, r)| *r == role && e.label.eq_ignore_ascii_case(name))) + { + e.tier = Tier::Primary; + roles.insert(role, i); + } + } else if !sparse { + e.tier = Tier::Secondary; + } + } + if merged.is_empty() { + return; + } + let mut rows: Vec<_> = std::mem::take(&mut self.sections) + .into_iter() + .map(Some) + .collect(); + for (index, owner) in merged { + let Some(mut entry) = rows[index].take() else { + continue; + }; + let Some(kept) = &mut rows[owner] else { + continue; + }; + let mut children = std::mem::take(&mut entry.children); + kept.add_sources(entry.sources.iter().copied()); + let prior = entry.id.clone(); + if let Some(i) = children.iter().position(|c| child_self(c, &entry)) { + kept.insert_child(children.remove(i), self.requested, Some(prior)); + } else if !entry.menu_only && !child_self(&entry, kept) { + kept.insert_child(entry, self.requested, Some(prior)); + } + for child in children { + kept.child(child, self.requested); + } + } + self.sections = rows.into_iter().flatten().collect(); + } +} diff --git a/crates/zephium-map/src/site/menus.rs b/crates/zephium-map/src/site/menus.rs new file mode 100644 index 000000000..b7e9ace09 --- /dev/null +++ b/crates/zephium-map/src/site/menus.rs @@ -0,0 +1,537 @@ +use super::*; +use crate::Node; + +const MIN_MENU_ITEMS: usize = 2; + +#[derive(Default)] +pub(super) struct Menus { + members: BTreeSet<EntryId>, + groups: BTreeMap<usize, Menu>, + order: BTreeMap<EntryId, usize>, +} + +#[derive(Clone, Copy, Default, PartialEq)] +enum Region { + #[default] + Other, + Navigation, + Footer, + Excluded, +} + +struct Menu { + label: String, + page: Option<Entry>, + items: Vec<Entry>, + trigger: Option<EntryId>, + source: Source, +} + +pub(super) fn link_label(n: &Node) -> &str { + let prefix = n.text.get(..n.link_prefix_bytes).filter(|s| { + !s.is_empty() + && n.text[s.len()..].starts_with(char::is_whitespace) + && s.chars().any(char::is_alphabetic) + && !matches!(normal(s).as_str(), "new" | "beta") + }); + [Some(n.name.trim()), Some(n.text.trim()), prefix] + .into_iter() + .flatten() + .filter(|s| !s.is_empty()) + .min_by_key(|s| s.chars().count()) + .unwrap_or_default() +} + +fn group_page(label: &str) -> Option<&str> { + ["see all ", "view all ", "browse all ", "explore all "] + .into_iter() + .find_map(|prefix| label.strip_prefix(prefix)) +} + +impl Menus { + pub(super) fn read(build: &Build<'_>, doc: &Doc) -> Self { + let nodes = doc.nodes(); + let mut menus = Self::default(); + let mut scopes = BTreeMap::new(); + let mut named = BTreeMap::new(); + let mut footer = BTreeMap::new(); + let mut direct = BTreeSet::new(); + let mut first_nav = None; + let clusters: BTreeSet<_> = build + .sections + .iter() + .filter(|e| e.sources.contains(&Source::LinkCluster)) + .map(|e| e.id.clone()) + .collect(); + let mut following = vec![None; nodes.len()]; + let mut sibling = vec![None; nodes.len()]; + for (i, n) in nodes.iter().enumerate().rev() { + if let Some(p) = n.parent_index() { + following[i] = sibling[p].replace(i); + } + } + let mut regions = Vec::with_capacity(nodes.len()); + for (i, n) in nodes.iter().enumerate() { + let inherited = n.parent_index().map(|p| regions[p]).unwrap_or_default(); + let region = match (inherited, n.role) { + (Region::Excluded, _) + | ( + _, + Role::Landmark { + landmark: Some(Landmark::Main | Landmark::Complementary), + }, + ) => Region::Excluded, + (Region::Footer, _) + | ( + _, + Role::Landmark { + landmark: Some(Landmark::Contentinfo), + }, + ) => Region::Footer, + ( + _, + Role::Landmark { + landmark: Some(Landmark::Banner), + }, + ) => Region::Navigation, + ( + _, + Role::Landmark { + landmark: Some(Landmark::Navigation), + }, + ) if visible(nodes, i) && *first_nav.get_or_insert(i) == i => Region::Navigation, + _ => inherited, + }; + regions.push(region); + if region == Region::Excluded + || region == Region::Other && (clusters.is_empty() || n.role != Role::Link) + || !visible(nodes, i) + { + continue; + } + let nav = region == Region::Navigation; + let parent = n.parent_index(); + let label = n.accessible_name().trim(); + if region == Region::Footer { + if matches!(n.role, Role::Text | Role::Heading { .. } | Role::Button) + && !n.text.trim().is_empty() + && !ancestors(nodes, i).any(|a| nodes[a].role == Role::Link) + { + if let Some(p) = parent { + footer.insert(p, normal(&n.text)); + } + } + continue; + } + let scope = match n.role { + Role::Group | Role::List if !label.is_empty() => Some(i), + Role::Button if doc.menu_links.contains_key(&i) => Some(i), + Role::Button | Role::Heading { .. } => parent + .filter(|&p| matches!(nodes[p].role, Role::Group | Role::ListItem)) + .or_else(|| { + following[i] + .filter(|&next| matches!(nodes[next].role, Role::Group | Role::List)) + }), + Role::Link => { + parent.filter(|&p| nodes[p].role == Role::ListItem && !scopes.contains_key(&p)) + } + _ => None, + }; + let Some(scope) = scope else { continue }; + if normal(label) + .split_whitespace() + .any(|w| w == "menu" || w == "navigation") + || card::placeholder(label) + || card::sentence(label) + || ancestors(nodes, i) + .skip(1) + .any(|a| nodes[a].role == Role::Link) + { + continue; + } + let key = normal(label); + let page = n + .destination + .as_ref() + .and_then(|u| build.entry_for(u, label, Source::PrimaryNav)) + .filter(|e| { + !card::self_link(e, &build.entry, Some(doc.page())) && !card::action(e) + }); + let trigger = page + .as_ref() + .filter(|e| e.key.page_match() == build.entry.page_match()) + .map(|e| e.id.clone()); + let page = page.filter(|_| trigger.is_none()); + let owner = if page.is_none() { + *named.entry(key).or_insert(i) + } else { + i + }; + menus.groups.entry(owner).or_insert_with(|| Menu { + label: clip(&crate::clean_text(label), TITLE_BYTES), + page, + trigger, + source: if nav { + Source::PrimaryNav + } else { + Source::LinkCluster + }, + items: Vec::new(), + }); + if let Some(links) = doc.menu_links.get(&i) { + if let Some(menu) = menus.groups.get_mut(&owner) { + for (url, label) in links { + if let Some(mut e) = + build.entry_for(url, label, Source::MenuGroup).filter(|e| { + !(card::action(e) + || card::placeholder(label) + || card::self_link(e, &build.entry, Some(doc.page())) + || e.off_site && site_profile(url).is_some()) + }) + { + e.menu_item = true; + menu.items.push(e); + } + } + } + } + scopes + .entry(scope) + .and_modify(|previous| { + if *previous != Some(owner) { + *previous = None; + } + }) + .or_insert(Some(owner)); + } + let mut footer_links = Vec::new(); + let mut seen = BTreeSet::new(); + for (i, n) in nodes.iter().enumerate() { + let region = regions[i]; + let nav = region == Region::Navigation; + let Some(url) = &n.destination else { continue }; + if region == Region::Excluded + || region == Region::Other && clusters.is_empty() + || !visible(nodes, i) + { + continue; + } + let label = link_label(n); + if SiteKey::from_url(url).as_ref() != Some(&build.site) && site_profile(url).is_some() { + continue; + } + let Some(mut entry) = build.entry_for(url, label, Source::MenuGroup) else { + continue; + }; + if n.marks.has(crate::doc::Marks::ACTION) + || card::action(&entry) + || card::self_link(&entry, &build.entry, Some(doc.page())) + || card::placeholder(label) + { + continue; + } + if region == Region::Footer { + let group = ancestors(nodes, i).find_map(|a| footer.get(&a)); + if let Some(owner) = group.and_then(|g| { + named.get(g).or_else(|| { + g.split_once(" and ") + .and_then(|(first, _)| named.get(first)) + }) + }) { + footer_links.push((*owner, entry)); + } + continue; + } + if !nav && !clusters.contains(&entry.id) { + continue; + } + menus.order.entry(entry.id.clone()).or_insert(i); + let label = normal(label); + let owner = ancestors(nodes, i) + .filter_map(|a| scopes.get(&a).copied().flatten()) + .last(); + let all = group_page(&label).and_then(|g| named.get(g)).copied(); + if let Some(owner) = all { + if let Some(menu) = menus.groups.get_mut(&owner) { + menu.page.get_or_insert(entry); + } + } else if let Some(owner) = owner.filter(|&o| o != i) { + if let Some(menu) = menus.groups.get_mut(&owner) { + let group = normal(&menu.label); + if label == group + || label == "overview" + && entry + .key + .as_url() + .path_segments() + .and_then(|mut p| p.next_back()) + .is_some_and(|s| normal(s) == group) + { + menu.page.get_or_insert(entry); + continue; + } + } + if seen.insert((owner, entry.id.clone())) { + entry.menu_item = true; + if let Some(menu) = menus.groups.get_mut(&owner) { + menu.items.push(entry); + } + } + } else { + direct.insert(entry.id); + } + } + let empty: BTreeSet<_> = menus + .groups + .iter() + .filter(|(_, m)| m.items.is_empty()) + .map(|(&i, _)| i) + .collect(); + for (owner, mut entry) in footer_links { + if !empty.contains(&owner) { + continue; + } + let Some(menu) = menus.groups.get_mut(&owner) else { + continue; + }; + if !direct.contains(&entry.id) && seen.insert((owner, entry.id.clone())) { + entry.menu_item = true; + entry.sources = vec![Source::Footer, Source::MenuGroup]; + menu.items.push(entry); + } + } + let mut unique = BTreeMap::new(); + let mut by_label = BTreeMap::new(); + let mut joined = BTreeMap::<usize, Menu>::new(); + for (i, menu) in menus.groups { + let identity = menu + .page + .as_ref() + .map(|p| p.id.clone()) + .unwrap_or_else(|| EntryId::menu(&build.entry, &menu.label)); + let key = normal(&menu.label); + let owner = *by_label + .entry(key) + .or_insert_with(|| *unique.entry(identity).or_insert(i)); + if let Some(kept) = joined.get_mut(&owner) { + if kept.page.is_none() { + kept.page = menu.page; + } + kept.items.extend(menu.items); + } else { + joined.insert(owner, menu); + } + } + menus.groups = joined; + for menu in menus.groups.values_mut() { + let mut distinct = BTreeSet::new(); + menu.items.retain(|e| { + distinct.insert(e.id.clone()) + && !direct.contains(&e.id) + && menu.page.as_ref().is_none_or(|p| p.id != e.id) + }); + if menu.items.len() >= MIN_MENU_ITEMS { + menus + .members + .extend(menu.items.iter().map(|e| e.id.clone())); + } + } + for e in build + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + { + if menus + .members + .contains(&EntryId::new(None, &e.key, &e.locator)) + { + menus.members.insert(e.id.clone()); + } + } + menus + } +} + +impl Menus { + pub(super) fn apply(mut self, build: &mut Build<'_>) { + let mut old: BTreeMap<_, _> = std::mem::take(&mut build.sections) + .into_iter() + .enumerate() + .map(|(position, e)| (e.id.clone(), (position, e))) + .collect(); + let routes: BTreeMap<_, _> = old + .iter() + .map(|(id, (_, e))| (EntryId::new(None, &e.key, &e.locator), id.clone())) + .collect(); + let prior_id = |id: &EntryId| routes.get(id).cloned().unwrap_or_else(|| id.clone()); + let mut rows = Vec::new(); + let mut taken: BTreeSet<_> = self + .groups + .values() + .filter(|m| !m.items.is_empty()) + .filter_map(|m| m.page.as_ref().map(|e| e.id.clone())) + .collect(); + for (position, menu) in self.groups { + if menu.items.is_empty() || menu.items.len() < MIN_MENU_ITEMS && menu.page.is_none() { + // A lone link underneath a toggle keeps its own name and destination. + if menu.page.is_none() { + if let Some(mut item) = menu.items.into_iter().next() { + if let Some((_, e)) = old.get_mut(&prior_id(&item.id)) { + e.label = item.label; + e.role = item.role; + } else { + item.menu_item = false; + item.add_sources([menu.source]); + rows.push((position, item)); + } + } + } + continue; + } + if let Some(id) = &menu.trigger { + old.remove(&prior_id(id)); + } + let Some(mut parent) = menu.page.or_else(|| { + let mut e = build.entry_for(build.entry.as_url(), &menu.label, menu.source)?; + e.id = EntryId::menu(&build.entry, &menu.label); + e.menu_only = true; + Some(e) + }) else { + continue; + }; + let mut extra = Vec::new(); + let mut prior_more = 0; + if let Some((_, existing)) = old.remove(&prior_id(&parent.id)) { + parent = existing; + extra = std::mem::take(&mut parent.children); + prior_more = std::mem::take(&mut parent.more); + } + parent.label = menu.label; + parent.tier = Tier::Primary; + parent.path_name = false; + parent.role = label_role(&parent.label); + parent.add_sources([menu.source]); + self.order.insert(parent.id.clone(), position); + let mut items = menu.items; + if items.len() > MAX_CHILDREN { + let mut ranked: Vec<_> = items.iter().collect(); + ranked.sort_by_key(|e| { + ( + build.requested.and_then(|r| r.rank(e)).is_none(), + e.role.is_none(), + ) + }); + let selected: BTreeSet<_> = ranked + .into_iter() + .take(MAX_CHILDREN) + .map(|e| e.id.clone()) + .collect(); + parent.more += (items.len() - MAX_CHILDREN) as u32; + items.retain(|e| { + if selected.contains(&e.id) { + true + } else { + old.remove(&prior_id(&e.id)); + false + } + }); + } + for mut item in items { + let original = item.id.clone(); + if let Some((_, e)) = old.remove(&prior_id(&original)) { + if build + .llms_headings + .get(&e.id) + .is_some_and(|h| *h == normal(&parent.label)) + { + extra.extend( + e.children + .into_iter() + .filter(|c| c.sources.contains(&Source::Llms)), + ); + } + item.key = e.key; + item.off_site = e.off_site; + item.locator = e.locator; + item.add_sources(e.sources); + } + let prior = extra + .iter() + .find(|c| c.key == item.key && c.locator == item.locator) + .map(|c| c.id.clone()); + let discovered = taken + .insert(original.clone()) + .then(|| prior.unwrap_or_else(|| prior_id(&original))); + parent.insert_child(item, build.requested, discovered); + } + for mut child in extra { + let route = EntryId::new(None, &child.key, &child.locator); + if self.members.contains(&route) { + continue; + } + let previous = prior_id(&route); + let secondary = child.sources.contains(&Source::Llms) + && old + .get(&previous) + .is_some_and(|(_, e)| e.tier == Tier::Secondary && !e.navigation_row()); + let discovered = if secondary { + old.remove(&previous).map(|(_, e)| { + child.add_sources(e.sources); + e.id + }) + } else { + None + }; + parent.insert_child(child, build.requested, discovered); + } + parent.more = parent.more.max(prior_more); + rows.push((position, parent)); + } + let labels: BTreeMap<_, _> = rows + .iter() + .enumerate() + .map(|(i, (_, e))| (normal(&e.label), i)) + .collect(); + let mut original: Vec<_> = old.into_values().collect(); + original.sort_by_key(|(pos, _)| *pos); + for (_, mut e) in original { + if let Some(&i) = labels + .get(&normal(&e.label)) + .filter(|_| e.tier != Tier::Action) + { + let group = &mut rows[i].1; + // The old discovery pass can use a menu label on its first linked item. + let children = std::mem::take(&mut e.children); + for child in children { + group.child(child, build.requested); + } + if group.menu_only + && !self.members.contains(&e.id) + && !e.menu_only + && e.navigation_row() + && normal(e.key.as_url().path().trim_matches('/')) == normal(&e.label) + { + group.key = e.key; + group.id = e.id; + group.locator = e.locator; + group.menu_only = false; + group.off_site = e.off_site; + } + continue; + } + // Menu destinations can also occur in result, footer or index sections. + e.children + .retain(|c| !taken.contains(&EntryId::new(None, &c.key, &c.locator))); + e.menu_item |= self.members.contains(&e.id); + let order = self + .order + .get(&e.id) + .or_else(|| self.order.get(&EntryId::new(None, &e.key, &e.locator))) + .copied() + .unwrap_or(usize::MAX); + rows.push((order, e)); + } + rows.sort_by_key(|(i, _)| *i); + build.sections = rows.into_iter().map(|(_, e)| e).collect(); + } +} diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index 48c0feecf..35d6e7358 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -80,18 +80,7 @@ impl Build<'_> { { continue; } - let prefix = n.text.get(..n.link_prefix_bytes).filter(|s| { - !s.is_empty() - && n.text[s.len()..].starts_with(char::is_whitespace) - && s.chars().any(char::is_alphabetic) - && !matches!(normal(s).as_str(), "new" | "beta") - }); - let label = [Some(n.name.trim()), Some(n.text.trim()), prefix] - .into_iter() - .flatten() - .filter(|s| !s.is_empty()) - .min_by_key(|s| s.chars().count()) - .unwrap_or_default(); + let label = menus::link_label(n); let marked_action = n.marks.has(crate::doc::Marks::ACTION); let parent = ancestors(nodes, i).skip(1).find_map(|a| { owners diff --git a/crates/zephium-map/tests/card.rs b/crates/zephium-map/tests/card.rs index 1d047da2e..09bda6cad 100644 --- a/crates/zephium-map/tests/card.rs +++ b/crates/zephium-map/tests/card.rs @@ -50,7 +50,7 @@ fn names_come_from_link_text_or_an_observed_path() { .filter(|e| e.tier == Tier::Primary) .map(|e| e.label.as_str()) .collect::<Vec<_>>(), - ["Hilfe", "research notes"] + ["Hilfe", "Research notes"] ); assert_eq!(p.sections.last().unwrap().tier, Tier::Secondary); for n in [MAX_PRIMARY_LABEL_CHARS, MAX_PRIMARY_LABEL_CHARS + 1] { @@ -107,14 +107,22 @@ proptest! { fn surviving_ids_ignore_label_noise_and_action_insertion(slugs in proptest::collection::btree_set("[a-z]{4,10}",1..10)) { let mut plain=String::from("<nav>"); let mut noisy=String::from("<nav><a href='/'>Home</a><a href='/login'>Enter</a>"); - for slug in slugs { + for slug in &slugs { plain.push_str(&format!("<a href='/pages/{slug}'>{slug}</a>")); noisy.push_str(&format!("<a href='/pages/{slug}'><span>{slug}</span><span>A longer explanation</span></a><a href='/de/pages/{slug}'>{slug}</a>")); } let a=card(&(plain+"</nav>")); let b=card(&(noisy+"</nav>")); let ids=|p:Place|p.sections.into_iter().filter(|e|e.tier==Tier::Primary).map(|e|(e.label,e.id)).collect::<Vec<_>>(); - prop_assert_eq!(ids(a),ids(b)); + let original = ids(a); + prop_assert_eq!(&original,&ids(b)); + let children = slugs.iter().map(|slug| format!("<a href='/pages/{slug}'>{slug}</a>")).collect::<String>(); + let grouped = card(&format!("<nav><div><button>Topics</button>{children}</div></nav>")); + if original.len()>1 { + prop_assert_eq!(grouped.sections.len(),1); + let placed:Vec<_>=grouped.sections[0].children.iter().map(|e|(e.label.clone(),e.id.clone())).collect(); + prop_assert_eq!(original,placed); + } else {prop_assert_eq!(original,ids(grouped));} } } @@ -176,7 +184,7 @@ fn repeated_locale_roots_are_not_sections_and_query_specific_routes_remain_disti fn the_word_boundary_refuses_a_teaser_and_keeps_a_short_title() { let p = card("<nav><a href='/one'>A B C D E F</a><a href='/two'>A B C D E F G</a></nav>"); assert_eq!(p.sections[0].label, "A B C D E F"); - assert_eq!(p.sections[1].label, "two"); + assert_eq!(p.sections[1].label, "Two"); } #[test] @@ -195,7 +203,7 @@ fn an_observed_directory_represents_three_or_more_deep_sibling_articles() { .unwrap(); assert_eq!(directory.tier, tier); if count == 3 { - assert_eq!(directory.label, "tools"); + assert_eq!(directory.label, "Tools"); } } } @@ -223,7 +231,7 @@ fn version_badges_release_items_and_breadcrumbs_do_not_displace_sections() { .filter(|e| e.tier == Tier::Primary) .map(|e| e.label.as_str()) .collect(); - assert_eq!(primary, ["versions", "Changelog", "Feeds", "Formats"]); + assert_eq!(primary, ["Versions", "Changelog", "Feeds", "Formats"]); assert!(p .sections .iter() @@ -242,3 +250,121 @@ fn platform_download_calls_and_markdown_sales_contacts_are_actions() { assert_eq!(actions, ["Download for Solaris", "Talk to us"]); assert_eq!(p.sections[0].label, "BSD"); } + +#[test] +fn a_group_uses_its_observed_index_and_flattens_nested_menus() { + let p=card("<nav><div><button>Tools</button><a href='/catalog'>See all tools</a><a href='/one'>First</a><div><button>Editors</button><a href='/two'>Second</a><a href='/three'>Third</a></div></div></nav>"); + assert_eq!(p.sections.len(), 1); + let tools = &p.sections[0]; + assert_eq!(tools.label, "Tools"); + assert_eq!(tools.key.as_url().path(), "/catalog"); + assert!(!tools.menu_only); + assert!(p.entry_openable(&tools.id, &Default::default())); + assert_eq!( + tools + .children + .iter() + .map(|c| c.label.as_str()) + .collect::<Vec<_>>(), + ["First", "Second", "Third"] + ); + assert!(tools.children.iter().all(|e| e.children.is_empty())); +} + +#[test] +fn a_collapsed_panel_needs_its_controls_reference_and_visible_members() { + for (id, expected) in [("panel", 1), ("other", 0)] { + let p=card(&format!("<nav><button aria-controls='panel'>Tools</button><div aria-hidden='true' id='{id}'><a href='/x'>First</a><a href='/y'>Second</a><div hidden><a href='/hidden'>Hidden</a></div></div></nav>")); + assert_eq!(p.sections.len(), expected); + if let Some(group) = p.sections.first() { + assert!(group.menu_only); + assert_eq!(group.children.len(), 2); + } + } +} + +#[test] +fn only_path_names_change_case_and_thin_counts_primary_rows() { + for (extra, thin) in [("", true), ("<a href='/third'>tHIRD</a>", false)] { + let p=card(&format!("<nav><a href='/ёж'>Here are the latest versions of this resource</a><a href='/foo'>lower case</a>{extra}<a href='/login'>Log in</a></nav>")); + assert_eq!(p.notes.thin, thin); + assert_eq!( + (&*p.sections[0].label, p.sections[0].path_name), + ("Ёж", true) + ); + assert_eq!( + (&*p.sections[1].label, p.sections[1].path_name), + ("lower case", false) + ); + if !thin { + assert_eq!(p.sections[2].label, "tHIRD"); + } + } +} + +#[test] +fn supplemental_roles_keep_the_navigation_id_and_fill_sparse_cards_roles_first() { + use zephium_map::site::SiteInputs; + let url = Url::parse("https://workshop.example/").unwrap(); + for (extra, sparse) in [("", true), ("<a href='/three'>Three</a>", false)] { + let html = format!("<nav><a href='/manual'>Docs</a><a href='/two'>Two</a>{extra}</nav>"); + let d = Doc::from_html(&url, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + let base = read_site(&d, &Default::default()).unwrap(); + let p=read_site(&d,&SiteInputs {llms:Some("## Documentation\n- [One](/help/one)\n- [Two guides](/help/two)\n## Assorted\n- [Start](/pricing)\n## Careers\n- [Open roles](/work)"),..Default::default()}).unwrap(); + let docs = &p.sections[0]; + assert_eq!(docs.id, base.sections[0].id); + assert_eq!(docs.label, "Docs"); + assert_eq!(docs.children.len(), 2); + assert!(!p.sections.iter().any(|e| e.label == "Documentation")); + let row = |name: &str| p.sections.iter().position(|e| e.label == name).unwrap(); + assert!(row("Careers") < row("Assorted")); + assert_eq!(p.sections[row("Careers")].tier, Tier::Primary); + assert_eq!(p.sections[row("Assorted")].tier == Tier::Primary, sparse); + } +} + +#[test] +fn an_index_heading_does_not_take_its_first_footer_links_role() { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc=Doc::from_html(&url,b"<nav><div><button>Resources</button><a href='/one'>One</a><a href='/two'>Two</a></div><a href='/three'>Three</a><a href='/four'>Four</a></nav><footer><a href='/help'>Support</a></footer>",None,DocLimits::SITE_PAGE).unwrap(); + let p = read_site( + &doc, + &zephium_map::site::SiteInputs { + llms: Some("## Resources\n- [Help center](/help)\n- [Reports](/reports)"), + ..Default::default() + }, + ) + .unwrap(); + assert!(p.sections.iter().all(|e| e.label != "Support")); + let row = p.sections.iter().find(|e| e.label == "Resources").unwrap(); + assert!(row.menu_only); + assert!(row + .children + .iter() + .any(|e| e.key.as_url().path() == "/help")); + assert!(row.children.iter().any(|e| e.label == "Reports")); +} + +#[test] +fn a_collapsed_menu_obeys_the_documents_text_budget() { + let url = Url::parse("https://workshop.example/").unwrap(); + let html="<nav><button aria-controls='menu'>Tools</button><div id='menu' aria-hidden='true'><a href='/first'>First</a><a href='/second'>Second</a></div></nav>"; + let room = ["/first", "/second"] + .iter() + .map(|path| url.join(path).unwrap().as_str().len()) + .sum::<usize>() + + "ToolsFirstSecond".len(); + for (limit, truncated) in [(room, false), (room - 1, true)] { + let d = Doc::from_html( + &url, + html.as_bytes(), + None, + DocLimits { + text_bytes: limit as u32, + ..DocLimits::SITE_PAGE + }, + ) + .unwrap(); + assert_eq!(d.body_truncated(), truncated); + } +} diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index 450ff8fa6..060a33e27 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -1548,7 +1548,7 @@ fn sitemap_samples_obey_read_byte_and_section_bounds() { .unwrap() .sections .iter() - .any(|e| e.label == "sampled")); + .any(|e| e.label == "Sampled")); } } } diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index de84733fc..653daa457 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -201,7 +201,7 @@ fn sitemap_sampling_and_index_bounds() { .unwrap(); assert_eq!( labels(&p.sections), - ["downloads", "docs", "examples", "news", "products"] + ["Downloads", "Docs", "Examples", "News", "Products"] ); assert_eq!(stats.sitemap_urls, 50_000); let count = p.sections.len(); @@ -214,7 +214,10 @@ fn sitemap_sampling_and_index_bounds() { assert_eq!(e.more, 10_000 - 1 - expected as u32); assert_eq!(e.children.len(), expected); assert_eq!(e.sources[0], Source::Sitemap); - assert_eq!(e.key.as_url().path(), format!("/{}/0", e.label)); + assert_eq!( + e.key.as_url().path(), + format!("/{}/0", e.label.to_lowercase()) + ); assert_eq!( labels(&e.children), (1..=expected).map(|n| n.to_string()).collect::<Vec<_>>() @@ -336,8 +339,9 @@ fn labelled_menus_and_deep_landings_use_observed_destinations() { let home=doc("/","<header><nav><div><button>Products</button><ul><li><a href='/editor'>Editor</a></li><li><a href='/reader'>Reader</a></li></ul></div><div><a href='/a'>Alpha</a><a href='/b'>Beta</a></div></nav></header>"); let place = read_site(&home, &Default::default()).unwrap(); assert_eq!(labels(&place.sections), ["Products", "Alpha", "Beta"]); - assert_eq!(place.sections[0].key.as_url().path(), "/editor"); - assert_eq!(labels(&place.sections[0].children), ["Reader"]); + assert!(place.sections[0].menu_only); + assert!(!place.entry_openable(&place.sections[0].id, &Default::default())); + assert_eq!(labels(&place.sections[0].children), ["Editor", "Reader"]); let deep = doc("/pricing", include_str!("fixtures/section-pricing.html")); let p = read_site(&deep, &Default::default()).unwrap(); assert_eq!(p.sections[0].key.as_url(), deep.page()); @@ -386,9 +390,9 @@ fn separate_sitemaps_merge_one_cluster_regardless_of_arrival() { }; let p = run([(key("/b.xml"), &b), (key("/a.xml"), &a)].into()); assert!(p == run([(key("/a.xml"), &a), (key("/b.xml"), &b)].into())); - assert_eq!(labels(&p.sections), ["docs"]); + assert_eq!(labels(&p.sections), ["Docs"]); assert_eq!(p.sections[0].key.as_url().path(), "/docs/read"); - assert_eq!(labels(&p.sections[0].children), ["print"]); + assert_eq!(labels(&p.sections[0].children), ["Print"]); } #[test] @@ -590,10 +594,14 @@ fn landmark_free_link_rows_require_short_labels_and_little_intervening_text() { assert_eq!( p.sections .iter() - .filter(|e| e.tier == Tier::Secondary) + .filter(|e| e.tier == Tier::Primary && e.sources == [Source::LinkCluster]) .count(), 8 ); + assert!(p + .sections + .iter() + .any(|e| e.label == "Manual" && e.tier == Tier::Secondary)); } #[test] diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 32faa2fa6..3436c22b0 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -584,9 +584,9 @@ This run used synthetic results pages. Group checks and first-layer latency were | full_ns | 1 | 10 | 10 | 10 | | memo_bytes | 1 | 256 | — | 256 | | peak_rss_delta_bytes | 0 | — | — | — | -| primary_sections_per_place | 1 | 3 | 3 | 3 | +| primary_sections_per_place | 1 | 5 | 5 | 5 | | requests | 2 | 0 | 0 | 0 | -| secondary_sections_per_place | 1 | 2 | 2 | 2 | +| secondary_sections_per_place | 1 | 0 | 0 | 0 | | sections_per_place | 1 | 5 | 5 | 5 | | wall_ns | 2 | 0 | 0 | 0 | | wire_bytes | 2 | 0 | 0 | 0 | @@ -609,8 +609,13 @@ Places with at least 3 sections — 1 of 1 place and compare sites. | off_host_root_children | 0 | 0 | | off_host_without_display | 0 | 0 | | order | 0 | 0 | +| path_names | 1 | 1 | +| same_role_pairs | 0 | 0 | | self | 0 | 0 | | sentence | 0 | 0 | +| supplemental_only | 2 | 1 | +| thin_cards | 0 | 0 | +| top_level_menu_items | 0 | 0 | | utility | 0 | 0 | | Session activity | Count | diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index 5011e8bd3..e93ce6ae5 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -698,6 +698,9 @@ fn flatten_place(outcome: &mut Outcome, index: usize, place: Place) { .iter() .filter(|source| **source != Source::Heading || depth == Depth::Two), ); + if entry.menu_only { + continue; + } let mut url = entry.key.as_url().clone(); if let Some(fragment) = entry .locator diff --git a/xtask/src/map_bench/session/quality.rs b/xtask/src/map_bench/session/quality.rs index fe312e68e..55a63a930 100644 --- a/xtask/src/map_bench/session/quality.rs +++ b/xtask/src/map_bench/session/quality.rs @@ -1,7 +1,7 @@ use std::collections::BTreeSet; use zephium_map::{site::MAX_PRIMARY_LABEL_CHARS, Place, SectionRole, Source, Tier}; -pub(in crate::map_bench) const CLASSES: [&str; 10] = [ +pub(in crate::map_bench) const CLASSES: [&str; 15] = [ "action", "sentence", "self", @@ -12,14 +12,41 @@ pub(in crate::map_bench) const CLASSES: [&str; 10] = [ "utility", "detail", "off_host_root_children", + "top_level_menu_items", + "supplemental_only", + "same_role_pairs", + "path_names", + "thin_cards", ]; pub(super) fn measure(place: &Place) -> [u64; CLASSES.len()] { let mut counts = [0; CLASSES.len()]; let mut labels = BTreeSet::new(); let mut destinations = BTreeSet::new(); + let mut roles = std::collections::BTreeMap::new(); + counts[14] = u64::from( + place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .count() + < zephium_map::site::MIN_NAV_ROWS, + ); let mut lower_priority = false; for entry in place.sections.iter().filter(|e| e.tier == Tier::Primary) { + counts[10] += u64::from(entry.menu_item); + counts[11] += u64::from( + entry + .sources + .iter() + .all(|s| matches!(s, Source::Llms | Source::Sitemap)), + ); + if let Some(role) = entry.role { + let previous = roles.entry(role).or_insert(0); + counts[12] += *previous; + *previous += 1; + } + counts[13] += u64::from(entry.path_name); let url = entry.key.as_url(); let label = entry.label.to_lowercase(); let path = url.path().trim_matches('/'); @@ -40,14 +67,19 @@ pub(super) fn measure(place: &Place) -> [u64; CLASSES.len()] { let sentence = entry.label.chars().count() > MAX_PRIMARY_LABEL_CHARS || label.contains(". ") || label.split_whitespace().count() >= 7; - let home = entry.key.page_match() == place.entry.page_match() + let home = !entry.menu_only + && entry.key.page_match() == place.entry.page_match() && entry.locator == Default::default(); let nameless = matches!( label.as_str(), "" | "more" | "other" | "optional" | "menu" | "learn more" ); let fresh_label = labels.insert(label.clone()); - let fresh_destination = destinations.insert((entry.card_page(), entry.locator.fragment())); + let fresh_destination = destinations.insert(( + entry.card_page(), + entry.locator.fragment(), + entry.menu_only.then_some(&entry.id), + )); let utility = entry.role == Some(SectionRole::Legal) || matches!( label.as_str(), @@ -59,8 +91,7 @@ pub(super) fn measure(place: &Place) -> [u64; CLASSES.len()] { && url.host_str() != place.entry.as_url().host_str() && path.contains('/'); let minor = action || home || nameless || utility || detail; - let direct = entry.sources.contains(&Source::PrimaryNav) - || entry.sources.contains(&Source::MenuGroup); + let direct = entry.navigation_row(); let order = !minor && direct && lower_priority; lower_priority |= minor || !direct; for (n, hit) in counts.iter_mut().zip([ @@ -121,3 +152,31 @@ mod tests { assert_eq!(scores["off_host_without_display"], 0); } } + +#[cfg(test)] +mod extended_tests { + use super::*; + use zephium_map::{site::read_site, Doc, DocLimits}; + #[test] + fn provenance_and_role_pairs_are_counted_per_primary_row() { + let url = url::Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>A</a><a href='/b'>B</a><a href='/c'>C</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + for e in &mut place.sections { + e.role = Some(SectionRole::Documentation); + } + place.sections[0].menu_item = true; + place.sections[0].path_name = true; + place.sections[0].sources = vec![Source::Sitemap, Source::Llms]; + place.sections[1].sources = vec![Source::Llms, Source::PrimaryNav]; + assert_eq!(measure(&place)[10..], [1, 1, 3, 1, 0]); + place.sections[0].tier = Tier::Secondary; + assert_eq!(measure(&place)[10..], [0, 0, 1, 0, 1]); + } +} diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs index 5c207355a..c38576efb 100644 --- a/xtask/src/map_try/printer.rs +++ b/xtask/src/map_try/printer.rs @@ -90,6 +90,7 @@ impl Printer { state.sections = place .sections .iter() + .filter(|e| !e.menu_only) .map(|entry| (entry.id.clone(), entry.label.clone())) .collect(); if *complete @@ -231,6 +232,12 @@ fn entry_line(entry: &Entry, focus: Option<&str>, indent: &str) -> String { } else { "" }; + if entry.menu_only { + return format!( + "{indent}{mark}{} ▸", + clip(&entry.label, COLUMNS - indent.len() - mark.len() - 2) + ); + } let off_site = if entry.off_site { " [off-site]" } else { "" }; let more = if entry.more { " [more]" } else { "" }; let available = COLUMNS - indent.len() - mark.len() - off_site.len() - more.len() - " ".len(); diff --git a/xtask/src/map_try/printer/tests.rs b/xtask/src/map_try/printer/tests.rs index 7ed698df4..888f2b4ce 100644 --- a/xtask/src/map_try/printer/tests.rs +++ b/xtask/src/map_try/printer/tests.rs @@ -3,6 +3,7 @@ use zephium_map_driver::wire::{Confidence, Network, Official}; fn entry(id: &str, label: &str, path: &str) -> Entry { Entry { + menu_only: false, id: id.into(), tier: Tier::Primary, label: label.into(), From a6590b31d2c76052cbb157671b384b2a0651bb61 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 05:24:51 +0100 Subject: [PATCH 38/40] fix(map): keep header links as rows and give a menu only its own page A menu's page comes from its control or a named index link, never from one of its items. A link that stands by itself in the header stays a primary row and is not also listed under a footer column; a footer column fills only a header menu with no members, and never with legal or policy links. Children are one per destination across locale paths. Skip links and language pickers are not rows. A place is titled with the site's name (site name metadata, application name, typed JSON-LD, then the title segment matching the host) instead of the page title. Memo version 6. --- crates/zephium-map/src/doc.rs | 12 +- crates/zephium-map/src/doc/html.rs | 49 +- crates/zephium-map/src/session/memo.rs | 2 +- crates/zephium-map/src/site.rs | 70 ++- crates/zephium-map/src/site/card.rs | 60 +- crates/zephium-map/src/site/menus.rs | 561 +++++++++++++++--- crates/zephium-map/src/site/menus/editions.rs | 59 ++ crates/zephium-map/src/site/menus/tests.rs | 31 + crates/zephium-map/src/site/navigation.rs | 1 + crates/zephium-map/src/site/title.rs | 54 ++ crates/zephium-map/tests/card.rs | 9 +- crates/zephium-map/tests/card_ownership.rs | 292 +++++++++ crates/zephium-map/tests/site.rs | 6 +- xtask/src/map_bench/run/tests/session.rs | 6 + xtask/src/map_bench/session.rs | 7 + xtask/src/map_bench/session/quality.rs | 64 +- 16 files changed, 1136 insertions(+), 147 deletions(-) create mode 100644 crates/zephium-map/src/site/menus/editions.rs create mode 100644 crates/zephium-map/src/site/menus/tests.rs create mode 100644 crates/zephium-map/src/site/title.rs create mode 100644 crates/zephium-map/tests/card_ownership.rs diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 72b7a8fa4..776870622 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -195,6 +195,7 @@ pub struct Node { pub hidden: bool, pub marks: Marks, pub language: Option<String>, + pub(crate) link_language: Option<String>, pub element_id: Option<String>, pub element_id_cleaned: bool, } @@ -231,6 +232,7 @@ impl Node { hidden: false, marks: Marks::default(), language: None, + link_language: None, element_id: None, element_id_cleaned: false, } @@ -243,6 +245,7 @@ pub struct Head { pub title: String, pub canonical: Option<Url>, pub site_name: String, + pub application_name: String, pub alternates: Vec<Alternate>, pub linked_data: Vec<String>, } @@ -255,11 +258,16 @@ pub struct Alternate { pub struct Doc { page: Url, - pub(crate) menu_links: std::collections::BTreeMap<usize, Vec<(Url, String)>>, + pub(crate) menu_links: std::collections::BTreeMap<usize, Vec<MenuLink>>, nodes: Vec<Node>, head: Head, truncated: bool, } +pub(crate) struct MenuLink { + pub url: Url, + pub label: String, + pub language: Option<String>, +} impl Doc { pub fn page(&self) -> &Url { &self.page @@ -347,6 +355,7 @@ impl DocBuilder { .len() .saturating_add(node.text.len()) .saturating_add(node.language.as_deref().map_or(0, str::len)) + .saturating_add(node.link_language.as_deref().map_or(0, str::len)) .saturating_add(node.element_id.as_deref().map_or(0, str::len)); if size > self.limits.node_text_bytes as usize || size > self.limits.text_bytes as usize - self.text_bytes @@ -372,6 +381,7 @@ impl DocBuilder { } self.doc.head.title.retain(crate::visible_char); self.doc.head.site_name.retain(crate::visible_char); + self.doc.head.application_name.retain(crate::visible_char); for a in &mut self.doc.head.alternates { a.title.retain(crate::visible_char); } diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index aaeb9cf69..c7c5cdcaa 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -139,11 +139,22 @@ impl DocBuilder { .attr("property") .is_some_and(|v| v.eq_ignore_ascii_case("og:site_name")) => { - if let Some(value) = node.attr("content") { + if let Some(value) = node.attr("content").filter(|_| !node.clipped("content")) { let text = self.words(value); self.doc.head.site_name = self.head_text(&text, limit); } } + "meta" + if self.doc.head.application_name.is_empty() + && node + .attr("name") + .is_some_and(|s| s.eq_ignore_ascii_case("application-name")) => + { + if let Some(value) = node.attr("content").filter(|_| !node.clipped("content")) { + let text = self.words(value); + self.doc.head.application_name = self.head_text(&text, limit); + } + } "link" => { let rel = node.attr("rel").unwrap_or_default(); let has = |word: &str| { @@ -198,6 +209,7 @@ impl DocBuilder { let node = &self.doc.nodes[at]; let room = self.limits.node_text_bytes as usize - node.language.as_deref().map_or(0, str::len) + - node.link_language.as_deref().map_or(0, str::len) - node.text.len() - node.name.len() - node.element_id.as_deref().map_or(0, str::len); @@ -417,10 +429,18 @@ impl DocBuilder { self.limits.node_text_bytes as usize, ); anchor = Some(links.len()); - links.push((url, label)); + let language = link_language(&n) + .filter(|s| s.len() <= self.limits.text_bytes as usize - self.text_bytes) + .map(str::to_ascii_lowercase); + self.text_bytes += language.as_deref().map_or(0, str::len); + links.push(MenuLink { + url, + label, + language, + }); } } else if let Some(i) = anchor { - let label = &mut links[i].1; + let label = &mut links[i].label; if label.is_empty() && n.is_text() && !n.text().trim().is_empty() { *label = self.head_text(n.text().trim(), self.limits.node_text_bytes as usize); } @@ -616,8 +636,17 @@ impl DocBuilder { - node.element_id.as_deref().map_or(0, str::len); node.language = language.filter(|s| s.len() <= room).map(str::to_owned); } + if role == Role::Link { + let room = (self.limits.node_text_bytes as usize) + .min(self.limits.text_bytes as usize - self.text_bytes) + - node.name.len() + - node.element_id.as_deref().map_or(0, str::len); + node.link_language = link_language(&n) + .filter(|s| s.len() <= room) + .map(str::to_ascii_lowercase); + } let index = self.push(node)? as usize; - if role == Role::Button { + if matches!(role, Role::Button | Role::Link) { self.disclosure_links(n, base, index); } (Some(index), level + 1) @@ -679,6 +708,17 @@ fn marks(n: &NodeRef) -> Marks { marks } +fn link_language<'a>(n: &NodeRef<'a>) -> Option<&'a str> { + ["hreflang", "lang"].into_iter().find_map(|attr| { + n.attr(attr).filter(|s| { + !n.clipped(attr) + && s.len() <= MAX_LANGUAGE_BYTES + && s.split('-') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric())) + }) + }) +} + fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { use super::Landmark as L; use Role::*; @@ -724,6 +764,7 @@ fn classify(n: &NodeRef, tag: &str, in_sink: bool) -> Option<Role> { }, "paragraph" => Paragraph, "link" => Link, + "button" if tag == "a" && n.has_attr("href") => Link, "button" => Button, "dialog" | "alertdialog" => Dialog, "list" | "feed" => List, diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index d39462f26..3a45dce9c 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -3,7 +3,7 @@ use crate::results::{MAX_SOCIAL, TITLE_BYTES}; use crate::site::{MAX_CHILDREN, MAX_SECTIONS}; use serde::{Deserialize, Serialize}; -pub const MEMO_VERSION: u16 = 5; +pub const MEMO_VERSION: u16 = 6; pub const MAX_MEMO_BYTES: usize = 256 * 1024; pub const MEMO_TTL: u64 = 24 * 60 * 60; #[derive(Clone, Serialize, Deserialize)] diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index cd10d37db..b9fe473c0 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -18,12 +18,15 @@ use url::Url; pub const MIN_NAV_ROWS: usize = 3; mod card; pub use card::{ - display_hostname, display_path, MAX_HOST_BYTES, MAX_PATH_CHARS, MAX_PRIMARY_LABEL_CHARS, + display_hostname, display_path, skip_label, MAX_HOST_BYTES, MAX_PATH_CHARS, + MAX_PRIMARY_LABEL_CHARS, }; mod menus; mod navigation; mod sitemap; +mod title; pub use sitemap::{Sitemap, XmlError, MAX_SITEMAP_URLS, MAX_XML_BYTES, MAX_XML_DEPTH}; +pub use title::{title_segments, MAX_SITE_NAME_BYTES}; pub const ENTRY_ID_BYTES: usize = 16; pub const MAX_PRIMARY_SECTIONS: usize = 12; @@ -150,6 +153,9 @@ pub struct PlaceNotes { } #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct PlaceStats { + pub missing_header_links: usize, + pub invalid_group_pages: usize, + pub language_groups: usize, pub robots_truncated: bool, pub entry_truncated: bool, pub sections_truncated: bool, @@ -477,7 +483,7 @@ impl Build<'_> { let globals: BTreeSet<_> = self .sections .iter() - .map(|e| (e.key.page_match(), e.locator.fragment())) + .map(Entry::card_route) .chain(std::iter::once((self.entry.page_match(), None))) .collect(); let demoted = Entry::utility; @@ -488,8 +494,7 @@ impl Build<'_> { let mut children = std::mem::take(&mut e.children); children.retain(|c| { !card::child_self(c, e) && { - c.sources.contains(&Source::Heading) - || !globals.contains(&(c.key.page_match(), c.locator.fragment())) + c.sources.contains(&Source::Heading) || !globals.contains(&c.card_route()) } }); let mut distinct = Vec::new(); @@ -1004,6 +1009,21 @@ pub(crate) fn quote(text: &str) -> Option<Locator> { }) } impl Entry { + fn footer_utility(&self) -> bool { + self.utility() + || normal(&self.label).split_whitespace().any(|w| { + matches!( + w, + "policy" + | "policies" + | "restricted" + | "prohibited" + | "licences" + | "licenses" + | "sitemap" + ) + }) + } fn utility(&self) -> bool { let label = self.label.to_lowercase(); self.role == Some(SectionRole::Legal) @@ -1022,7 +1042,14 @@ impl Entry { | "account" | "ask ai" | "search" + | "shopping bag" + | "shopping cart" ) + || label.strip_prefix("search ").is_some_and(|target| { + self.key.as_url().domain().is_some_and(|host| { + host.trim_start_matches("www.").eq_ignore_ascii_case(target) + }) + }) || self .key .as_url() @@ -1032,7 +1059,7 @@ impl Entry { .is_some_and(|s| { (s.starts_with("llms") && s.ends_with(".txt")) || s.ends_with(".xml") }) - || ["skip to", "language", "cookie", "select region"] + || ["skip to", "cookie", "select region"] .iter() .any(|s| label.contains(s)) } @@ -1096,10 +1123,12 @@ impl Entry { if let Some(existing) = self .children .iter_mut() - .find(|e| e.key.page_match() == entry.key.page_match() && e.locator == entry.locator) + .find(|e| e.card_page() == entry.card_page() && e.locator == entry.locator) { existing.add_sources(entry.sources); - if let Some(id) = discovered { + if let Some(id) = + discovered.filter(|_| existing.key.page_match() == entry.key.page_match()) + { existing.id = id; } return; @@ -1170,7 +1199,7 @@ pub(crate) fn enrich_held( let siblings: BTreeSet<_> = build .sections .iter() - .map(|entry| (entry.key.page_match(), entry.locator.fragment())) + .map(Entry::card_route) .chain(std::iter::once((build.entry.page_match(), None))) .collect(); let section = &mut build.sections[index]; @@ -1179,7 +1208,7 @@ pub(crate) fn enrich_held( !card::child_self(child, section) && { focus.as_ref() == Some(&child.id) || child.sources.contains(&Source::Heading) - || !siblings.contains(&(child.key.page_match(), child.locator.fragment())) + || !siblings.contains(&child.card_route()) } }); section.children = opened_children; @@ -1230,13 +1259,15 @@ pub(crate) fn with_results( .chain(hint.map(|link| (link, Source::EngineResult))) { if let Some(entry) = build.entry_for(&link.url, &link.title, source) { - if let Some(existing) = build.sections.iter_mut().find(|e| e.id == entry.id) { + if let Some(existing) = build.sections.iter_mut().find(|e| { + !e.menu_only && (e.id == entry.id || e.card_route() == entry.card_route()) + }) { existing.add_sources(entry.sources); } else if let Some(child) = build .sections .iter_mut() .flat_map(|e| &mut e.children) - .find(|e| e.id == entry.id || (e.key == entry.key && e.locator == entry.locator)) + .find(|e| e.id == entry.id || e.card_route() == entry.card_route()) { child.add_sources(entry.sources); } else { @@ -1266,14 +1297,7 @@ pub(crate) fn read_site_for( ) -> Result<(Place, PlaceStats, Vec<SectionRead>), KeyError> { let key = PlaceKey::from_url(doc.page()).ok_or(KeyError::Url)?; let site = SiteKey::from_url(doc.page()).ok_or(KeyError::Url)?; - let title = [ - doc.head().site_name.as_str(), - doc.head().title.as_str(), - site.as_str(), - ] - .into_iter() - .find(|s| !s.trim().is_empty()) - .unwrap_or_default(); + let title = title::site_title(doc.head(), &site); let mut place = Build { names: Default::default(), llms_headings: Default::default(), @@ -1281,7 +1305,7 @@ pub(crate) fn read_site_for( requested, stats: PlaceStats::default(), place: Place { - title: clip(title, TITLE_BYTES), + title, site, entry: key.root(doc.page())?, key, @@ -1380,8 +1404,12 @@ pub(crate) fn read_site_for( }) .count(); let eager = place.eager_reads(); - let menus = (!place.notes.wall).then(|| menus::Menus::read(&place, doc)); + let mut menus = (!place.notes.wall).then(|| menus::Menus::read(&place, doc)); + let evidence = menus.as_mut().map(menus::Menus::take_evidence); place.finish_sections(Some(doc.page()), menus); + if let Some(evidence) = evidence { + evidence.measure(&place.place, &mut place.stats); + } place.check_ids()?; place.notes.truncated = place.stats.truncated() || place.sections.iter().any(|e| e.more > 0); Ok((place.place, place.stats, eager)) diff --git a/crates/zephium-map/src/site/card.rs b/crates/zephium-map/src/site/card.rs index 12bd9b218..f00e0f9af 100644 --- a/crates/zephium-map/src/site/card.rs +++ b/crates/zephium-map/src/site/card.rs @@ -7,19 +7,48 @@ pub const MAX_PATH_CHARS: usize = 128; const SENTENCE_WORDS: usize = 7; const MIN_DIRECTORY_ITEMS: usize = 3; -fn locale(segment: &str) -> bool { - let (language, region) = segment - .split_once('-') - .map_or((segment, None), |(l, r)| (l, Some(r))); - language.len() == 2 - && language.bytes().all(|c| c.is_ascii_alphabetic()) - && region.is_none_or(|r| r.len() == 2 && r.bytes().all(|c| c.is_ascii_alphabetic())) +pub(super) fn locale(segment: &str) -> bool { + let mut parts = segment.split('-'); + let language = parts.next().unwrap_or_default(); + let alpha = |s: &str| s.bytes().all(|b| b.is_ascii_alphabetic()); + if !(language.len() == 2 || language.len() == 3 && segment.contains('-')) || !alpha(language) { + return false; + } + let mut region = parts.next(); + if region.is_some_and(|s| s.len() == 4 && alpha(s)) { + region = parts.next(); + } + parts.next().is_none() + && region.is_none_or(|s| { + s.len() == 2 && alpha(s) || s.len() == 3 && s.bytes().all(|b| b.is_ascii_digit()) + }) } impl Entry { pub fn card_page(&self) -> PageMatch { localized_key(&self.key) } + pub(super) fn card_route(&self) -> (PageMatch, Option<String>) { + (self.card_page(), self.locator.fragment()) + } +} + +pub(super) fn skip_link(url: &Url, label: &str, landing: &Url) -> bool { + url.fragment().is_some_and(|s| !s.is_empty()) + && crate::key::same_page(url, landing) + && skip_label(label) +} + +pub fn skip_label(label: &str) -> bool { + let label = normal(label); + label.starts_with("skip to ") + || matches!( + label.as_str(), + "skip navigation" + | "skip navigation links" + | "jump to content" + | "jump to main content" + ) } fn localized_key(key: &PageKey) -> PageMatch { @@ -176,6 +205,9 @@ pub(super) fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> } impl Build<'_> { + pub(super) fn link_is_edition(&self, entry: &Entry) -> bool { + self.link_name(entry).is_some_and(|n| n.language_host) + } fn link_name(&self, entry: &Entry) -> Option<&LinkName> { self.names.get(&entry.id).or_else(|| { self.names @@ -224,6 +256,10 @@ impl Build<'_> { .collect(); let home = |e: &Entry| { self_link(e, &self.entry, landing) + || e.locator.element.is_some() + && skip_label(&e.label) + && (e.key.page_match() == self.entry.page_match() + || landing.is_some_and(|u| crate::key::same_page(u, e.key.as_url()))) || (locale_paths.len() > 1 && e.locator == Locator::default() && e.key.as_url().query().is_none() @@ -533,7 +569,6 @@ impl Build<'_> { < MIN_NAV_ROWS; let mut roles = BTreeMap::new(); let mut names = BTreeMap::new(); - let mut docs = None; let mut merged = BTreeMap::new(); for (i, e) in self .sections @@ -542,15 +577,6 @@ impl Build<'_> { .filter(|(_, e)| e.tier == Tier::Primary && e.navigation_row() && !e.utility()) { let label = normal(&e.label); - if matches!(label.as_str(), "docs" | "documentation") { - if let Some(parent) = docs { - names.entry(label).or_insert(parent); - merged.insert(i, parent); - continue; - } else { - docs = Some(i); - } - } names.entry(label).or_insert(i); if let Some(role) = e.role { roles.entry(role).or_insert(i); diff --git a/crates/zephium-map/src/site/menus.rs b/crates/zephium-map/src/site/menus.rs index b7e9ace09..1c137d8d3 100644 --- a/crates/zephium-map/src/site/menus.rs +++ b/crates/zephium-map/src/site/menus.rs @@ -3,11 +3,68 @@ use crate::Node; const MIN_MENU_ITEMS: usize = 2; +mod editions; +use editions::{edition_path, Editions}; +#[cfg(test)] +mod tests; + #[derive(Default)] pub(super) struct Menus { members: BTreeSet<EntryId>, groups: BTreeMap<usize, Menu>, order: BTreeMap<EntryId, usize>, + direct: BTreeMap<(crate::PageMatch, Option<String>), (usize, Entry)>, + excluded: BTreeSet<EntryId>, + evidence: Evidence, +} + +#[derive(Default)] +pub(super) struct Evidence { + direct: BTreeMap<EntryId, (crate::PageMatch, Option<String>)>, + pages: BTreeMap<String, Option<EntryId>>, + languages: BTreeSet<String>, + editions: std::collections::HashSet<(crate::PageMatch, Locator)>, +} + +impl Evidence { + pub(super) fn measure(&self, place: &Place, stats: &mut PlaceStats) { + let primary: BTreeSet<_> = place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary) + .flat_map(|e| [e.id.clone(), EntryId::new(None, &e.key, &e.locator)]) + .collect(); + let primary_routes: BTreeSet<_> = place + .sections + .iter() + .filter(|e| e.tier == Tier::Primary && !e.menu_only) + .map(Entry::card_route) + .collect(); + stats.missing_header_links = self + .direct + .iter() + .filter(|(id, route)| !primary.contains(id) && !primary_routes.contains(route)) + .count(); + for e in &place.sections { + let label = normal(&e.label); + let language_group = self.languages.contains(&label) && !e.children.is_empty() + || e.children.len() >= MIN_MENU_ITEMS + && e.children + .iter() + .all(|c| self.editions.contains(&(c.card_page(), c.locator.clone()))); + stats.language_groups += usize::from(language_group); + if !e.menu_only + && (e.children.iter().any(|c| c.card_route() == e.card_route()) + || self.pages.get(&label).is_some_and(|page| { + page.as_ref().is_none_or(|id| { + *id != e.id && *id != EntryId::new(None, &e.key, &e.locator) + }) + })) + { + stats.invalid_group_pages += 1; + } + } + } } #[derive(Clone, Copy, Default, PartialEq)] @@ -22,9 +79,37 @@ enum Region { struct Menu { label: String, page: Option<Entry>, + index: Option<Entry>, items: Vec<Entry>, trigger: Option<EntryId>, source: Source, + editions: Editions, +} + +impl Menu { + fn add_item(&mut self, mut item: Entry) { + let label = normal(&item.label); + let group = normal(&self.label); + if label == group + || group_page(&label) == Some(group.as_str()) + || matches!( + label.as_str(), + "see all" | "view all" | "browse all" | "explore all" + ) + || label == "overview" + && item + .key + .as_url() + .path_segments() + .and_then(|mut s| s.next_back()) + .is_some_and(|s| normal(s) == group) + { + self.index.get_or_insert(item); + } else { + item.menu_item = true; + self.items.push(item); + } + } } pub(super) fn link_label(n: &Node) -> &str { @@ -55,8 +140,22 @@ impl Menus { let mut scopes = BTreeMap::new(); let mut named = BTreeMap::new(); let mut footer = BTreeMap::new(); - let mut direct = BTreeSet::new(); let mut first_nav = None; + let alternates: BTreeSet<_> = doc + .head() + .alternates + .iter() + .filter(|a| !a.language.is_empty()) + .filter_map(|a| PageKey::from_url(&a.url).ok().map(|k| k.page_match())) + .collect(); + let mut standalone = Vec::new(); + let actions: BTreeSet<_> = build + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter(|e| card::action(e)) + .map(Entry::card_route) + .collect(); let clusters: BTreeSet<_> = build .sections .iter() @@ -65,9 +164,11 @@ impl Menus { .collect(); let mut following = vec![None; nodes.len()]; let mut sibling = vec![None; nodes.len()]; + let mut peer_buttons = vec![0; nodes.len()]; for (i, n) in nodes.iter().enumerate().rev() { if let Some(p) = n.parent_index() { following[i] = sibling[p].replace(i); + peer_buttons[p] += usize::from(n.role == Role::Button && visible(nodes, i)); } } let mut regions = Vec::with_capacity(nodes.len()); @@ -75,6 +176,7 @@ impl Menus { let inherited = n.parent_index().map(|p| regions[p]).unwrap_or_default(); let region = match (inherited, n.role) { (Region::Excluded, _) + | (_, Role::Document) | ( _, Role::Landmark { @@ -111,7 +213,27 @@ impl Menus { } let nav = region == Region::Navigation; let parent = n.parent_index(); - let label = n.accessible_name().trim(); + let label = if n.role == Role::Text { + n.text.trim() + } else { + n.accessible_name().trim() + }; + if n.destination + .as_ref() + .is_some_and(|u| card::skip_link(u, link_label(n), doc.page())) + { + continue; + } + if n.role == Role::Link + && n.destination.as_ref().is_some_and(|u| { + u.fragment().is_none() + && build + .entry_for(u, label, Source::PrimaryNav) + .is_some_and(|e| card::self_link(&e, &build.entry, Some(doc.page()))) + }) + { + continue; + } if region == Region::Footer { if matches!(n.role, Role::Text | Role::Heading { .. } | Role::Button) && !n.text.trim().is_empty() @@ -123,18 +245,46 @@ impl Menus { } continue; } + let paired_panel = |control: usize| { + let p = nodes[control].parent_index()?; + let panel = following[control]?; + (matches!(nodes[p].role, Role::Group | Role::ListItem) + && sibling[p] == Some(control) + && following[panel].is_none() + && matches!( + nodes[panel].role, + Role::List + | Role::Group + | Role::Landmark { + landmark: Some(Landmark::Navigation) + } + )) + .then_some(panel) + }; let scope = match n.role { Role::Group | Role::List if !label.is_empty() => Some(i), - Role::Button if doc.menu_links.contains_key(&i) => Some(i), + Role::Button | Role::Link if doc.menu_links.contains_key(&i) => Some(i), Role::Button | Role::Heading { .. } => parent - .filter(|&p| matches!(nodes[p].role, Role::Group | Role::ListItem)) + .filter(|&p| { + matches!(nodes[p].role, Role::Group | Role::ListItem) + && (n.role != Role::Button || peer_buttons[p] == 1) + }) .or_else(|| { following[i] .filter(|&next| matches!(nodes[next].role, Role::Group | Role::List)) }), - Role::Link => { - parent.filter(|&p| nodes[p].role == Role::ListItem && !scopes.contains_key(&p)) - } + Role::Link => parent + .filter(|&p| nodes[p].role == Role::ListItem && !scopes.contains_key(&p)) + .or_else(|| paired_panel(i)), + Role::Text if nav => paired_panel(i).or_else(|| { + parent + .filter(|&p| { + nodes[p].role == Role::Group + && sibling[p] == Some(i) + && following[i].is_none() + }) + .and_then(paired_panel) + }), _ => None, }; let Some(scope) = scope else { continue }; @@ -170,6 +320,7 @@ impl Menus { menus.groups.entry(owner).or_insert_with(|| Menu { label: clip(&crate::clean_text(label), TITLE_BYTES), page, + index: None, trigger, source: if nav { Source::PrimaryNav @@ -177,11 +328,22 @@ impl Menus { Source::LinkCluster }, items: Vec::new(), + editions: Editions::default(), }); if let Some(links) = doc.menu_links.get(&i) { if let Some(menu) = menus.groups.get_mut(&owner) { - for (url, label) in links { - if let Some(mut e) = + for link in links { + let (url, label) = (&link.url, link.label.as_str()); + if card::skip_link(url, label, doc.page()) { + continue; + } + menu.editions.observe( + url, + link.language.as_deref(), + doc.page(), + &alternates, + ); + if let Some(e) = build.entry_for(url, label, Source::MenuGroup).filter(|e| { !(card::action(e) || card::placeholder(label) @@ -189,8 +351,7 @@ impl Menus { || e.off_site && site_profile(url).is_some()) }) { - e.menu_item = true; - menu.items.push(e); + menu.add_item(e); } } } @@ -206,9 +367,25 @@ impl Menus { } let mut footer_links = Vec::new(); let mut seen = BTreeSet::new(); + let mut flat_scopes = vec![None; nodes.len()]; + let mut flat_headings = BTreeMap::new(); for (i, n) in nodes.iter().enumerate() { let region = regions[i]; let nav = region == Region::Navigation; + if nav { + if let Some(p) = n.parent_index() { + if matches!(n.role, Role::Text | Role::ListItem) + && (sibling[p] == Some(i) || flat_headings.contains_key(&p)) + && !n.text.is_empty() + && visible(nodes, i) + { + if let Some(&owner) = named.get(&normal(&n.text)) { + flat_headings.insert(p, owner); + } + } + flat_scopes[i] = flat_headings.get(&p).copied().or(flat_scopes[p]); + } + } let Some(url) = &n.destination else { continue }; if region == Region::Excluded || region == Region::Other && clusters.is_empty() @@ -217,20 +394,40 @@ impl Menus { continue; } let label = link_label(n); + if card::skip_link(url, label, doc.page()) { + if let Some(entry) = build.entry_for(url, label, Source::MenuGroup) { + menus.excluded.insert(entry.id); + } + continue; + } + let owner = ancestors(nodes, i) + .filter_map(|a| scopes.get(&a).copied().flatten()) + .last(); + if let Some(menu) = owner + .filter(|&o| o != i) + .and_then(|o| menus.groups.get_mut(&o)) + { + menu.editions + .observe(url, n.link_language.as_deref(), doc.page(), &alternates); + } if SiteKey::from_url(url).as_ref() != Some(&build.site) && site_profile(url).is_some() { continue; } - let Some(mut entry) = build.entry_for(url, label, Source::MenuGroup) else { + let Some(entry) = build.entry_for(url, label, Source::MenuGroup) else { continue; }; if n.marks.has(crate::doc::Marks::ACTION) || card::action(&entry) + || actions.contains(&entry.card_route()) || card::self_link(&entry, &build.entry, Some(doc.page())) || card::placeholder(label) { continue; } if region == Region::Footer { + if entry.footer_utility() { + continue; + } let group = ancestors(nodes, i).find_map(|a| footer.get(&a)); if let Some(owner) = group.and_then(|g| { named.get(g).or_else(|| { @@ -238,7 +435,7 @@ impl Menus { .and_then(|(first, _)| named.get(first)) }) }) { - footer_links.push((*owner, entry)); + footer_links.push((*owner, entry, n.link_language.as_deref())); } continue; } @@ -247,95 +444,196 @@ impl Menus { } menus.order.entry(entry.id.clone()).or_insert(i); let label = normal(label); - let owner = ancestors(nodes, i) - .filter_map(|a| scopes.get(&a).copied().flatten()) - .last(); let all = group_page(&label).and_then(|g| named.get(g)).copied(); if let Some(owner) = all { if let Some(menu) = menus.groups.get_mut(&owner) { - menu.page.get_or_insert(entry); + menu.index.get_or_insert(entry); } } else if let Some(owner) = owner.filter(|&o| o != i) { - if let Some(menu) = menus.groups.get_mut(&owner) { - let group = normal(&menu.label); - if label == group - || label == "overview" - && entry - .key - .as_url() - .path_segments() - .and_then(|mut p| p.next_back()) - .is_some_and(|s| normal(s) == group) - { - menu.page.get_or_insert(entry); - continue; - } - } if seen.insert((owner, entry.id.clone())) { - entry.menu_item = true; if let Some(menu) = menus.groups.get_mut(&owner) { - menu.items.push(entry); + menu.add_item(entry); } } - } else { - direct.insert(entry.id); - } - } - let empty: BTreeSet<_> = menus - .groups - .iter() - .filter(|(_, m)| m.items.is_empty()) - .map(|(&i, _)| i) - .collect(); - for (owner, mut entry) in footer_links { - if !empty.contains(&owner) { - continue; - } - let Some(menu) = menus.groups.get_mut(&owner) else { - continue; - }; - if !direct.contains(&entry.id) && seen.insert((owner, entry.id.clone())) { - entry.menu_item = true; - entry.sources = vec![Source::Footer, Source::MenuGroup]; - menu.items.push(entry); + } else if nav { + standalone.push((i, entry)); } } - let mut unique = BTreeMap::new(); let mut by_label = BTreeMap::new(); let mut joined = BTreeMap::<usize, Menu>::new(); + let mut owners = BTreeMap::new(); for (i, menu) in menus.groups { - let identity = menu - .page - .as_ref() - .map(|p| p.id.clone()) - .unwrap_or_else(|| EntryId::menu(&build.entry, &menu.label)); let key = normal(&menu.label); - let owner = *by_label - .entry(key) - .or_insert_with(|| *unique.entry(identity).or_insert(i)); + let owner = *by_label.entry(key).or_insert(i); + owners.insert(i, owner); if let Some(kept) = joined.get_mut(&owner) { if kept.page.is_none() { kept.page = menu.page; } + if kept.index.is_none() { + kept.index = menu.index; + } kept.items.extend(menu.items); + kept.editions.merge(menu.editions); } else { joined.insert(owner, menu); } } menus.groups = joined; + let header_items: BTreeSet<_> = menus + .groups + .iter() + .flat_map(|(&i, menu)| menu.items.iter().map(move |e| (i, e.card_route()))) + .collect(); + let empty: BTreeSet<_> = menus + .groups + .iter() + .filter(|(_, m)| m.editions.targets.is_empty()) + .map(|(&i, _)| i) + .collect(); + for (owner, mut entry, language) in footer_links { + if let Some(menu) = owners + .get(&owner) + .filter(|o| empty.contains(o)) + .and_then(|o| menus.groups.get_mut(o)) + { + menu.editions + .observe(entry.key.as_url(), language, doc.page(), &alternates); + entry.sources = vec![Source::Footer, Source::MenuGroup]; + menu.add_item(entry); + } + } + for (i, entry) in standalone { + if flat_scopes[i] + .map(|owner| { + ancestors(nodes, owner) + .filter_map(|a| scopes.get(&a).copied().flatten()) + .last() + .unwrap_or(owner) + }) + .and_then(|owner| owners.get(&owner)) + .is_some_and(|owner| header_items.contains(&(*owner, entry.card_route()))) + { + continue; + } + let control = owners + .get(&i) + .and_then(|o| menus.groups.get(o)) + .is_some_and(|m| !m.items.is_empty() || m.editions.is_picker()); + if !control { + menus.direct.entry(entry.card_route()).or_insert((i, entry)); + } + } + let editions: BTreeSet<_> = menus + .groups + .values() + .filter(|m| m.editions.is_picker()) + .flat_map(|m| m.items.iter().map(|e| e.id.clone())) + .collect(); + menus.groups.retain(|_, m| { + if m.editions.is_picker() + || m.items.len() >= MIN_MENU_ITEMS + && m.items.iter().all(|e| editions.contains(&e.id)) + { + menus.evidence.languages.insert(normal(&m.label)); + menus + .evidence + .editions + .extend(m.items.iter().map(|e| (e.card_page(), e.locator.clone()))); + menus + .excluded + .extend(m.items.iter().chain(&m.page).map(|e| e.id.clone())); + false + } else { + true + } + }); + let landings: BTreeMap<_, _> = build + .sections + .iter() + .filter(|e| e.id != EntryId::new(None, &e.key, &e.locator)) + .map(|e| (&e.id, e.card_route())) + .collect(); + let route = |e: &Entry| { + landings + .get(&e.id) + .cloned() + .unwrap_or_else(|| e.card_route()) + }; + let mut claimed = BTreeMap::new(); + let mut ambiguous = BTreeSet::new(); + for (owner, menu) in menus.groups.iter().filter(|(_, m)| !m.items.is_empty()) { + for page in menu.page.iter().chain(&menu.index) { + let destination = route(page); + if claimed + .insert(destination.clone(), owner) + .is_some_and(|previous| previous != owner) + { + ambiguous.insert(destination); + } + } + } for menu in menus.groups.values_mut() { + let items: BTreeSet<_> = menu.items.iter().map(&route).collect(); + menu.page = menu + .page + .take() + .into_iter() + .chain(menu.index.take()) + .find(|p| { + let target = route(p); + !menus.direct.contains_key(&p.card_route()) + && !ambiguous.contains(&target) + && !items.contains(&target) + }); let mut distinct = BTreeSet::new(); menu.items.retain(|e| { - distinct.insert(e.id.clone()) - && !direct.contains(&e.id) - && menu.page.as_ref().is_none_or(|p| p.id != e.id) + distinct.insert(e.card_route()) && !menus.direct.contains_key(&e.card_route()) }); - if menu.items.len() >= MIN_MENU_ITEMS { + if menu.items.len() >= MIN_MENU_ITEMS || menu.page.is_some() && !menu.items.is_empty() { + menus.evidence.pages.insert( + normal(&menu.label), + menu.page.as_ref().map(|e| e.id.clone()), + ); menus .members .extend(menu.items.iter().map(|e| e.id.clone())); } } + let locale_roots: BTreeSet<_> = menus + .direct + .values() + .filter_map(|(_, e)| { + let url = e.key.as_url(); + let path = url.path().trim_matches('/'); + (card::locale(path) + && !path.eq_ignore_ascii_case(&e.label) + && url.query().is_none() + && edition_path(url) == edition_path(doc.page())) + .then_some(path.to_owned()) + }) + .collect(); + let triggers: BTreeSet<_> = menus + .groups + .values() + .filter(|m| !m.items.is_empty()) + .filter_map(|m| m.trigger.as_ref()) + .collect(); + menus.direct.retain(|_, (_, e)| { + !(e.utility() + || card::sentence(&e.label) + || build.link_is_edition(e) + || menus.excluded.contains(&e.id) + || triggers.contains(&e.id) + || locale_roots.len() >= MIN_MENU_ITEMS + && locale_roots.contains(e.key.as_url().path().trim_matches('/'))) + }); + menus.evidence.direct.extend( + menus + .direct + .values() + .map(|(_, e)| (e.id.clone(), e.card_route())), + ); for e in build .sections .iter() @@ -350,10 +648,71 @@ impl Menus { } menus } + + pub(super) fn take_evidence(&mut self) -> Evidence { + std::mem::take(&mut self.evidence) + } } impl Menus { pub(super) fn apply(mut self, build: &mut Build<'_>) { + let mut direct_routes = BTreeSet::new(); + let member_routes: BTreeSet<_> = self + .groups + .values() + .filter(|m| m.items.len() >= MIN_MENU_ITEMS || m.page.is_some()) + .flat_map(|m| m.items.iter().map(Entry::card_route)) + .collect(); + build.sections.retain(|e| { + !self + .excluded + .contains(&EntryId::new(None, &e.key, &e.locator)) + }); + for e in &mut build.sections { + e.children.retain(|c| { + !self + .excluded + .contains(&EntryId::new(None, &c.key, &c.locator)) + }); + } + let available: BTreeMap<_, _> = build + .sections + .iter() + .enumerate() + .map(|(i, e)| (e.card_route(), i)) + .collect(); + let discovered: BTreeMap<_, _> = build + .sections + .iter() + .enumerate() + .map(|(i, e)| (e.id.clone(), i)) + .collect(); + let mut named_rows: BTreeSet<_> = build.sections.iter().map(|e| normal(&e.label)).collect(); + for (route, (position, mut entry)) in self.direct { + if let Some(i) = discovered + .get(&entry.id) + .or_else(|| available.get(&route)) + .copied() + { + let e = &mut build.sections[i]; + if e.tier != Tier::Action { + e.add_sources([Source::PrimaryNav]); + if !e.path_name { + e.label = entry.label; + e.role = entry.role; + } + direct_routes.insert(route); + } + continue; + } + if named_rows.insert(normal(&entry.label)) { + entry.sources = vec![Source::PrimaryNav]; + entry.tier = Tier::Primary; + self.order.insert(entry.id.clone(), position); + direct_routes.insert(route); + build.sections.push(entry); + } + } let mut old: BTreeMap<_, _> = std::mem::take(&mut build.sections) .into_iter() .enumerate() @@ -364,6 +723,10 @@ impl Menus { .map(|(id, (_, e))| (EntryId::new(None, &e.key, &e.locator), id.clone())) .collect(); let prior_id = |id: &EntryId| routes.get(id).cloned().unwrap_or_else(|| id.clone()); + let localized: BTreeMap<_, _> = old + .values() + .map(|(_, e)| (e.card_route(), e.id.clone())) + .collect(); let mut rows = Vec::new(); let mut taken: BTreeSet<_> = self .groups @@ -438,7 +801,12 @@ impl Menus { } for mut item in items { let original = item.id.clone(); - if let Some((_, e)) = old.remove(&prior_id(&original)) { + let prior = routes + .get(&original) + .or_else(|| localized.get(&item.card_route())) + .cloned() + .unwrap_or_else(|| original.clone()); + if let Some((_, e)) = old.remove(&prior) { if build .llms_headings .get(&e.id) @@ -450,23 +818,28 @@ impl Menus { .filter(|c| c.sources.contains(&Source::Llms)), ); } - item.key = e.key; - item.off_site = e.off_site; - item.locator = e.locator; + if prior == original || routes.contains_key(&original) { + item.key = e.key; + item.off_site = e.off_site; + item.locator = e.locator; + } item.add_sources(e.sources); } - let prior = extra + let existing = extra .iter() - .find(|c| c.key == item.key && c.locator == item.locator) + .find(|c| c.card_route() == item.card_route()) .map(|c| c.id.clone()); let discovered = taken - .insert(original.clone()) - .then(|| prior.unwrap_or_else(|| prior_id(&original))); + .insert(prior.clone()) + .then(|| existing.unwrap_or(prior)); parent.insert_child(item, build.requested, discovered); } for mut child in extra { let route = EntryId::new(None, &child.key, &child.locator); - if self.members.contains(&route) { + if self.members.contains(&route) + || direct_routes.contains(&child.card_route()) + || child.sources.first() == Some(&Source::Footer) + { continue; } let previous = prior_id(&route); @@ -500,28 +873,28 @@ impl Menus { .filter(|_| e.tier != Tier::Action) { let group = &mut rows[i].1; - // The old discovery pass can use a menu label on its first linked item. - let children = std::mem::take(&mut e.children); - for child in children { - group.child(child, build.requested); - } - if group.menu_only - && !self.members.contains(&e.id) - && !e.menu_only - && e.navigation_row() - && normal(e.key.as_url().path().trim_matches('/')) == normal(&e.label) + if build + .llms_headings + .get(&e.id) + .is_some_and(|name| *name == normal(&group.label)) { - group.key = e.key; - group.id = e.id; - group.locator = e.locator; - group.menu_only = false; - group.off_site = e.off_site; + for child in e.children.into_iter().filter(|c| { + c.sources.contains(&Source::Llms) + && !direct_routes.contains(&c.card_route()) + }) { + group.child(child, build.requested); + } } continue; } + if member_routes.contains(&e.card_route()) { + continue; + } // Menu destinations can also occur in result, footer or index sections. - e.children - .retain(|c| !taken.contains(&EntryId::new(None, &c.key, &c.locator))); + e.children.retain(|c| { + !taken.contains(&EntryId::new(None, &c.key, &c.locator)) + && !direct_routes.contains(&c.card_route()) + }); e.menu_item |= self.members.contains(&e.id); let order = self .order diff --git a/crates/zephium-map/src/site/menus/editions.rs b/crates/zephium-map/src/site/menus/editions.rs new file mode 100644 index 000000000..7875dba2b --- /dev/null +++ b/crates/zephium-map/src/site/menus/editions.rs @@ -0,0 +1,59 @@ +use super::*; + +#[derive(Default)] +pub(super) struct Editions { + pub(super) targets: BTreeSet<crate::PageMatch>, + languages: BTreeSet<String>, + matched: bool, + unrelated: bool, +} + +pub(super) fn edition_path(url: &Url) -> (&str, &str) { + let host = url.domain().unwrap_or_default().trim_start_matches("www."); + let host = host + .split_once('.') + .filter(|(first, rest)| card::locale(first) && psl::domain_str(rest).is_some()) + .map_or(host, |(_, rest)| rest); + let path = url.path().trim_matches('/'); + let (first, rest) = path.split_once('/').unwrap_or((path, "")); + (host, if card::locale(first) { rest } else { path }) +} + +impl Editions { + pub(super) fn observe( + &mut self, + url: &Url, + language: Option<&str>, + current: &Url, + alternates: &BTreeSet<crate::PageMatch>, + ) { + let Ok(key) = PageKey::from_url(url) else { + return; + }; + let target = key.page_match(); + let edition = url.port_or_known_default() == current.port_or_known_default() + && url.query() == current.query() + && url.fragment().is_none() + && edition_path(url) == edition_path(current); + let alternate = alternates.contains(&target); + self.unrelated |= !edition && !alternate && language.is_none(); + self.matched |= (edition && !crate::key::same_page(url, current)) || alternate; + if let Some(lang) = language { + self.languages.insert(lang.to_owned()); + } + self.targets.insert(target); + } + + pub(super) fn merge(&mut self, other: Self) { + self.targets.extend(other.targets); + self.languages.extend(other.languages); + self.matched |= other.matched; + self.unrelated |= other.unrelated; + } + + pub(super) fn is_picker(&self) -> bool { + !self.unrelated + && self.targets.len() >= MIN_MENU_ITEMS + && (self.matched || self.languages.len() >= MIN_MENU_ITEMS) + } +} diff --git a/crates/zephium-map/src/site/menus/tests.rs b/crates/zephium-map/src/site/menus/tests.rs new file mode 100644 index 000000000..31b2bde3b --- /dev/null +++ b/crates/zephium-map/src/site/menus/tests.rs @@ -0,0 +1,31 @@ +use super::*; + +#[test] +fn structural_quality_compares_the_emitted_rows_to_observations() { + let url = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>One</a><a href='/b'>Two</a></nav>", + None, + crate::DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + let child = place.sections.pop().unwrap(); + let evidence = Evidence { + direct: [(child.id.clone(), child.card_route())].into(), + pages: [("topics".into(), None)].into(), + languages: ["editions".into()].into(), + editions: Default::default(), + }; + place.sections[0].label = "Topics".into(); + place.sections[0].children.push(child); + let mut stats = PlaceStats::default(); + evidence.measure(&place, &mut stats); + assert_eq!(stats.missing_header_links, 1); + assert_eq!(stats.invalid_group_pages, 1); + place.sections[0].label = "Editions".into(); + let mut stats = PlaceStats::default(); + evidence.measure(&place, &mut stats); + assert_eq!(stats.language_groups, 1); +} diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index 35d6e7358..d6933f775 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -188,6 +188,7 @@ impl Build<'_> { } if let Some(url) = &n.destination { if n.accessible_name().is_empty() + || card::skip_link(url, menus::link_label(n), doc.page()) || n.accessible_name().chars().count() > MAX_CLUSTER_LABEL_CHARS || SiteKey::from_url(url).as_ref() != Some(&self.site) { diff --git a/crates/zephium-map/src/site/title.rs b/crates/zephium-map/src/site/title.rs new file mode 100644 index 000000000..3262c334b --- /dev/null +++ b/crates/zephium-map/src/site/title.rs @@ -0,0 +1,54 @@ +use super::*; +use crate::doc::Head; + +pub const MAX_SITE_NAME_BYTES: usize = 128; + +pub fn title_segments(title: &str) -> impl Iterator<Item = &str> { + title + .split(['|', '–', '—', '·', '•', ':', '\\']) + .flat_map(|s| s.split(" - ")) + .map(str::trim) +} + +pub(super) fn site_title(head: &Head, site: &SiteKey) -> String { + fn name(value: &str) -> Option<String> { + let value = crate::flatten(&crate::clean_text(value)); + (!value.is_empty() && value.len() <= MAX_SITE_NAME_BYTES).then_some(value) + } + if let Some(value) = name(&head.site_name).or_else(|| name(&head.application_name)) { + return value; + } + let mut website = None; + let mut organization = None; + linked::objects(head, |obj| { + let slot = if linked::typed(obj, "WebSite") { + &mut website + } else if linked::typed(obj, "Organization") { + &mut organization + } else { + return; + }; + if slot.is_none() { + *slot = obj["name"].as_str().and_then(name); + } + }); + let label = site.as_str().split('.').next().unwrap_or_default(); + website + .or(organization) + .or_else(|| { + let brand = normal(label).replace(' ', ""); + title_segments(&head.title) + .find(|s| normal(s).replace(' ', "") == brand) + .and_then(name) + }) + .unwrap_or_else(|| { + clip( + if head.title.trim().is_empty() { + site.as_str() + } else { + head.title.trim() + }, + TITLE_BYTES, + ) + }) +} diff --git a/crates/zephium-map/tests/card.rs b/crates/zephium-map/tests/card.rs index 09bda6cad..fb17422de 100644 --- a/crates/zephium-map/tests/card.rs +++ b/crates/zephium-map/tests/card.rs @@ -223,7 +223,7 @@ fn a_shared_clipped_path_does_not_create_indistinguishable_children() { } #[test] -fn version_badges_release_items_and_breadcrumbs_do_not_displace_sections() { +fn direct_release_links_stay_primary_with_a_named_version_index_and_no_breadcrumbs() { let p = card("<nav><a href='/versions'>v3.4</a><a href='/changelog'>Changelog</a><a href='/changelog/cedar'>Cedar</a><a href='/changelog/feeds'>Feeds</a><a href='/topics#breadcrumbs'>Trail</a><a href='/topics#formats'>Formats</a></nav><footer><a href='/changelog/feeds'>Feeds</a></footer>"); let primary: Vec<_> = p .sections @@ -231,11 +231,14 @@ fn version_badges_release_items_and_breadcrumbs_do_not_displace_sections() { .filter(|e| e.tier == Tier::Primary) .map(|e| e.label.as_str()) .collect(); - assert_eq!(primary, ["Versions", "Changelog", "Feeds", "Formats"]); + assert_eq!( + primary, + ["Versions", "Changelog", "Cedar", "Feeds", "Formats"] + ); assert!(p .sections .iter() - .any(|e| e.label == "Cedar" && e.tier == Tier::Secondary)); + .any(|e| e.label == "Trail" && e.tier == Tier::Secondary)); } #[test] diff --git a/crates/zephium-map/tests/card_ownership.rs b/crates/zephium-map/tests/card_ownership.rs new file mode 100644 index 000000000..134fe0be8 --- /dev/null +++ b/crates/zephium-map/tests/card_ownership.rs @@ -0,0 +1,292 @@ +use url::Url; +use zephium_map::{ + site::{read_site_with_stats, PlaceStats, MAX_SITE_NAME_BYTES}, + Doc, DocLimits, Entry, Place, Tier, +}; + +fn read(html: &str) -> (Place, PlaceStats) { + let base = Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html(&base, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap(); + read_site_with_stats(&doc, &Default::default()).unwrap() +} + +fn row<'a>(p: &'a Place, label: &str) -> &'a Entry { + p.sections + .iter() + .find(|e| e.label == label && e.tier == Tier::Primary) + .unwrap() +} + +fn labels(e: &Entry) -> Vec<&str> { + e.children.iter().map(|c| c.label.as_str()).collect() +} + +#[test] +fn a_control_that_repeats_an_item_cannot_supply_the_group_page() { + for (href, index, expected) in [ + ("/one", "", None), + ("/topics", "", Some("/topics")), + ( + "/one", + "<li><a href='/index'>View all topics</a></li>", + Some("/index"), + ), + ] { + let (p, stats) = read(&format!( + "<nav><ul><li><a href='{href}'>Topics</a><ul> + <li><a href='/one'>One</a></li><li><a href='/two'>Two</a></li>{index} + </ul></li></ul></nav>" + )); + let group = row(&p, "Topics"); + assert_eq!(labels(group), ["One", "Two"]); + assert_eq!( + (!group.menu_only).then(|| group.key.as_url().path()), + expected + ); + assert_eq!( + p.entry_openable(&group.id, &Default::default()), + expected.is_some() + ); + assert_eq!(stats.invalid_group_pages, 0); + } +} + +#[test] +fn an_observed_redirect_to_a_member_cannot_become_the_menu_page() { + let base = Url::parse("https://workshop.example/").unwrap(); + let parse = |url: &Url, html: &str| { + Doc::from_html(url, html.as_bytes(), None, DocLimits::SITE_PAGE).unwrap() + }; + let home = parse( + &base, + "<nav><ul><li><a href='/topics'>Topics</a><ul> + <li><a href='/one'>One</a></li><li><a href='/two'>Two</a></li></ul></li></ul></nav>", + ); + let landing = parse(&base.join("/one").unwrap(), "<p>First topic</p>"); + let key = zephium_map::PageKey::from_url(&base.join("/topics").unwrap()).unwrap(); + let inputs = zephium_map::site::SiteInputs { + pages: [(key, &landing)].into(), + ..Default::default() + }; + let (place, _) = read_site_with_stats(&home, &inputs).unwrap(); + assert!(row(&place, "Topics").menu_only); + assert_eq!(labels(row(&place, "Topics")), ["One", "Two"]); +} + +#[test] +fn footer_lending_respects_both_header_membership_and_standalone_destinations() { + for (members, expected) in [ + ("", vec!["Studio", "Labs"]), + ( + "<a href='/studio'>Our studio</a><a href='/events'>Events</a>", + vec!["Our studio", "Events"], + ), + ] { + let (p, stats) = read(&format!("<header><nav><div><button>Product</button>{members}</div> + <a href='/pricing'>Pricing</a><a href='/enterprise'>Enterprise</a></nav></header> + <footer><div><h3>Product</h3><a href='/studio'>Studio</a><a href='/labs'>Labs</a> + <a href='/de/pricing'>Plans</a><a href='/enterprise'>For business</a> + <a href='/rules'>Privacy and terms</a><a href='/restrictions'>Prohibited and restricted businesses</a> + </div></footer>")); + assert_eq!(labels(row(&p, "Product")), expected); + for direct in ["Enterprise", "Pricing"] { + let target = row(&p, direct).card_page(); + assert!(p + .sections + .iter() + .flat_map(|e| &e.children) + .all(|c| c.card_page() != target)); + } + assert_eq!(stats.missing_header_links, 0); + } +} + +#[test] +fn repeated_mobile_control_cannot_lend_footer_items_to_a_populated_desktop_menu() { + let (p, _) = read( + "<nav><ul><li><a href='/tools'>Tools</a><ul><li><a href='/a'>First</a></li> + <li><a href='/b'>Second</a></li></ul></li></ul><div><button>Tools</button></div></nav> + <footer><div><h3>Tools</h3><a href='/c'>Third</a></div></footer>", + ); + assert_eq!(labels(row(&p, "Tools")), ["First", "Second"]); +} + +#[test] +fn localized_children_keep_the_observed_name_and_existing_identity_in_both_orders() { + for (first, other) in [("/review", "/de/review"), ("/de/review", "/review")] { + let nav = |extra: &str| { + format!( + "<nav><div><button>Tools</button><a href='{first}'>Review</a> + <a href='/cli'>CLI</a>{extra}</div></nav>" + ) + }; + let (baseline, _) = read(&nav("")); + let aliases = format!("<a href='{other}'>Code Review</a>"); + let (p, _) = read(&format!( + "{}<footer><div><h3>Tools</h3>{aliases}</div></footer>", + nav(&aliases) + )); + let tools = row(&p, "Tools"); + assert_eq!(labels(tools), ["Review", "CLI"]); + assert_eq!(tools.children[0].id, row(&baseline, "Tools").children[0].id); + assert_eq!(tools.children[0].key.as_url().path(), first); + } +} + +#[test] +fn skip_links_never_create_or_own_a_row() { + for following in ["", "<a href='/a'>First</a><a href='/b'>Second</a>"] { + let (p, _) = read(&format!( + "<header><div><a href='#main'>Skip to content</a>{following}</div></header>" + )); + assert!(p.sections.iter().all(|e| e.label != "Skip to content")); + if following.is_empty() { + assert!(p.sections.is_empty()); + } else { + for name in ["First", "Second"] { + assert!(row(&p, name).children.is_empty()); + } + } + } +} + +#[test] +fn a_disclosed_header_link_reuses_a_previously_discovered_footer_identity() { + for (header, footer) in [("/de/review", "/review"), ("/review", "/de/review")] { + let column = + format!("<footer><div><h3>Work</h3><a href='{footer}'>Code review</a></div></footer>"); + let (before, _) = read(&column); + let id = before + .sections + .iter() + .find(|e| e.label == "Code review") + .unwrap() + .id + .clone(); + let (after, _) = read(&format!( + "<nav><button aria-controls='panel'>Tools</button> + <div id='panel' aria-hidden='true'><a href='{header}'>Review</a><a href='/cli'>CLI</a> + <a href='/catalog'>See all tools</a></div></nav>{column}" + )); + let tools = row(&after, "Tools"); + assert_eq!(tools.key.as_url().path(), "/catalog"); + assert_eq!(labels(tools), ["Review", "CLI"]); + assert_eq!(tools.children[0].id, id); + assert_eq!(tools.children[0].key.as_url().path(), header); + } +} + +#[test] +fn separate_navigation_representations_agree_on_members_and_independent_links() { + let (p, _) = read("<header><nav><ul><li><span>Explore</span><ul><li><a href='/a'>One</a></li> + <li><a href='/b'>Two</a></li></ul></li><li><a href='/pricing'>Pricing</a></li></ul></nav> + <nav><ul><li>Explore</li><li><a href='/de/a'>First</a></li><li><a href='/b'>Second</a></li></ul> + <a href='/pricing'>Pricing</a></nav></header>"); + assert_eq!(labels(row(&p, "Explore")), ["One", "Two"]); + assert!(row(&p, "Pricing").children.is_empty()); +} + +#[test] +fn language_controls_need_evidence_from_their_destinations() { + let alternates = "<link rel='alternate' hreflang='de' href='/eins'><link rel='alternate' hreflang='fr' href='/deux'>"; + for (head, links, picker) in [ + ("", "<a hreflang='de' href='/eins'>First</a><a hreflang='fr' href='/deux'>Second</a>", true), + ("", "<a lang='de' href='/eins'>First</a><a lang='fr' href='/deux'>Second</a>", true), + (alternates, "<a href='/eins'>First</a><a href='/deux'>Second</a>", true), + ("", "<a href='/pt-BR/'>First</a><a href='/fr/'>Second</a>", true), + ("", "<a href='/zh-Hant-TW/'>First</a><a href='/es-419/'>Second</a>", true), + ("", "<a href='https://de.workshop.example/'>First</a><a href='https://fr.workshop.example/'>Second</a>", true), + ("", "<a lang='en' href='/docs/rust'>Rust</a><a lang='en' href='/docs/go'>Go</a>", false), + ] { + let (p, _) = read(&format!("<head>{head}</head><header><nav><div><button>Languages</button>{links}</div> + <a href='/about'>About</a></nav></header>")); + if picker { + assert_eq!(p.sections.len(), 1); + assert!(row(&p, "About").children.is_empty()); + } else { + assert_eq!(labels(row(&p, "Languages")), ["Rust", "Go"]); + } + } +} + +#[test] +fn a_standalone_page_and_a_differently_named_control_keep_separate_rows() { + let (p, _) = read("<nav><a href='/library'>Library</a><ul><li><a href='/library'>Resources</a> + <ul><li><a href='/news'>News</a></li><li><a href='/talks'>Talks</a></li></ul></li></ul></nav>"); + assert!(!row(&p, "Library").menu_only); + let resources = row(&p, "Resources"); + assert!(resources.menu_only); + assert_eq!(labels(resources), ["News", "Talks"]); +} + +#[test] +fn a_home_link_and_peer_utility_buttons_do_not_own_neighbouring_destinations() { + let (p, _) = read( + "<header><div><a href='/'>Workshop Home</a><div> + <a href='/pricing'>Pricing</a></div></div> + <div><button>Languages and currency</button><a href='/help'>Help</a> + <button>Choose a profile</button><a href='/events'>Events</a></div></header>", + ); + assert!(p.sections.iter().all(|e| !e.menu_only)); + for label in ["Pricing", "Help", "Events"] { + assert!(row(&p, label).children.is_empty()); + } +} + +#[test] +fn oversized_link_language_cannot_hide_an_ordinary_menu() { + let too_long = "a".repeat(zephium_map::doc::MAX_LANGUAGE_BYTES + 1); + let (p, _) = read(&format!( + "<nav><div><button>Topics</button><a lang='{too_long}' href='/a'>One</a> + <a lang='fr' href='/b'>Two</a></div></nav>" + )); + assert_eq!(labels(row(&p, "Topics")), ["One", "Two"]); +} + +#[test] +fn site_names_use_bounded_metadata_then_the_registrable_brand_then_the_title() { + let og = "<meta property='og:site_name' content='OG name'>"; + let application = "<meta name='application-name' content='App name'>"; + let website = + r#"<script type='application/ld+json'>{"@type":"WebSite","name":"Site name"}</script>"#; + let organization = + r#"<script type='application/ld+json'>{"@type":"Organization","name":"Org name"}</script>"#; + let title = "<title>Build something new | Work Shop</title>"; + let inputs = [og, application, website, organization, title]; + for (i, expected) in ["OG name", "App name", "Site name", "Org name", "Work Shop"] + .iter() + .enumerate() + { + assert_eq!( + read(&inputs[i..].iter().rev().copied().collect::<String>()) + .0 + .title, + *expected + ); + } + assert_eq!( + read("<title>Build something new | Catalog</title>").0.title, + "Build something new | Catalog" + ); + assert_eq!(read("").0.title, "workshop.example"); + for separator in [" • ", " \\ "] { + assert_eq!( + read(&format!( + "<title>Welcome to our site{separator}Workshop</title>" + )) + .0 + .title, + "Workshop" + ); + } + for (n, accepted) in [ + (MAX_SITE_NAME_BYTES, true), + (MAX_SITE_NAME_BYTES + 1, false), + ] { + let value = "a".repeat(n); + let (p, _) = read(&format!( + "<meta property='og:site_name' content='{value}'>{application}" + )); + assert_eq!(p.title, if accepted { &value } else { "App name" }); + } +} diff --git a/crates/zephium-map/tests/site.rs b/crates/zephium-map/tests/site.rs index 653daa457..23b97a8cf 100644 --- a/crates/zephium-map/tests/site.rs +++ b/crates/zephium-map/tests/site.rs @@ -697,7 +697,11 @@ fn footer_navigation_does_not_hide_primary_link_clusters() { fn nested_menu_links_keep_distinct_anchors_on_the_parent_page() { let home = doc("/", "<nav><ul><li><a href='/pricing'>Pricing</a><ul><li><a href='/pricing#students'>Students</a></li><li><a href='/pricing'>Same page</a></li></ul></li></ul></nav>"); let place = read_site(&home, &SiteInputs::default()).unwrap(); - assert_eq!(labels(&place.sections[0].children), ["Students"]); + assert!(place.sections[0].menu_only); + assert_eq!( + labels(&place.sections[0].children), + ["Students", "Same page"] + ); assert_eq!( place.sections[0].children[0].locator.fragment().as_deref(), Some("#students") diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 3436c22b0..148b54af6 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -605,6 +605,11 @@ Places with at least 3 sections — 1 of 1 place and compare sites. | action | 0 | 0 | | detail | 0 | 0 | | duplicate | 0 | 0 | +| duplicate_children | 0 | 0 | +| invalid_group_pages | 0 | 0 | +| language_groups | 0 | 0 | +| long_compound_titles | 0 | 0 | +| missing_header_links | 0 | 0 | | nameless | 0 | 0 | | off_host_root_children | 0 | 0 | | off_host_without_display | 0 | 0 | @@ -613,6 +618,7 @@ Places with at least 3 sections — 1 of 1 place and compare sites. | same_role_pairs | 0 | 0 | | self | 0 | 0 | | sentence | 0 | 0 | +| skip_links | 0 | 0 | | supplemental_only | 2 | 1 | | thin_cards | 0 | 0 | | top_level_menu_items | 0 | 0 | diff --git a/xtask/src/map_bench/session.rs b/xtask/src/map_bench/session.rs index e93ce6ae5..c07a1567e 100644 --- a/xtask/src/map_bench/session.rs +++ b/xtask/src/map_bench/session.rs @@ -579,6 +579,13 @@ fn flatten_stats(outcome: &mut Outcome, stats: Stats) { put("stale_memos", stats.stale_memos.into()); put("rejected_memos", stats.rejected_memos.into()); for (index, notes) in stats.places { + for (key, count) in [ + ("invalid_group_pages", notes.invalid_group_pages), + ("missing_header_links", notes.missing_header_links), + ("language_groups", notes.language_groups), + ] { + put(&format!("place.{index}.card.{key}"), count as u64); + } for (key, value) in [ ("probed_section", notes.probed_section), ("robots_truncated", notes.robots_truncated), diff --git a/xtask/src/map_bench/session/quality.rs b/xtask/src/map_bench/session/quality.rs index 55a63a930..09ef3160a 100644 --- a/xtask/src/map_bench/session/quality.rs +++ b/xtask/src/map_bench/session/quality.rs @@ -1,7 +1,9 @@ use std::collections::BTreeSet; use zephium_map::{site::MAX_PRIMARY_LABEL_CHARS, Place, SectionRole, Source, Tier}; -pub(in crate::map_bench) const CLASSES: [&str; 15] = [ +const SHORT_TITLE_WORDS: usize = 3; +const CARD_MEASURES: usize = 18; +pub(in crate::map_bench) const CLASSES: [&str; 21] = [ "action", "sentence", "self", @@ -17,10 +19,37 @@ pub(in crate::map_bench) const CLASSES: [&str; 15] = [ "same_role_pairs", "path_names", "thin_cards", + "duplicate_children", + "skip_links", + "long_compound_titles", + "invalid_group_pages", + "missing_header_links", + "language_groups", ]; -pub(super) fn measure(place: &Place) -> [u64; CLASSES.len()] { - let mut counts = [0; CLASSES.len()]; +pub(super) fn measure(place: &Place) -> [u64; CARD_MEASURES] { + let mut counts = [0; CARD_MEASURES]; + counts[17] = u64::from( + zephium_map::site::title_segments(&place.title).count() > 1 + && zephium_map::site::title_segments(&place.title) + .flat_map(str::split_whitespace) + .count() + > SHORT_TITLE_WORDS, + ); + for row in &place.sections { + let mut children = BTreeSet::new(); + for child in &row.children { + counts[15] += + u64::from(!children.insert((child.card_page(), child.locator.fragment()))); + } + for e in std::iter::once(row).chain(&row.children) { + counts[16] += u64::from( + e.locator.element.is_some() + && e.key.page_match() == place.entry.page_match() + && zephium_map::site::skip_label(&e.label), + ); + } + } let mut labels = BTreeSet::new(); let mut destinations = BTreeSet::new(); let mut roles = std::collections::BTreeMap::new(); @@ -158,6 +187,31 @@ mod extended_tests { use super::*; use zephium_map::{site::read_site, Doc, DocLimits}; #[test] + fn counts_locale_duplicates_skip_links_and_compound_titles_across_tiers() { + let url = url::Url::parse("https://workshop.example/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><a href='/a'>One</a><a href='/b'>Two</a></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let mut place = read_site(&doc, &Default::default()).unwrap(); + let first = place.sections.pop().unwrap(); + let mut alias = first.clone(); + alias.key = zephium_map::PageKey::from_url(&url.join("/de/b").unwrap()).unwrap(); + let row = &mut place.sections[0]; + row.tier = Tier::Secondary; + row.key = place.entry.clone(); + row.locator.element = Some(zephium_map::key::LocatorText::new("main").unwrap()); + row.label = "Skip to content".into(); + row.children = vec![first, alias]; + place.title = "Site | Three Words".into(); + assert_eq!(measure(&place)[15..], [1, 1, 0]); + place.title.push_str(" Four"); + assert_eq!(measure(&place)[15..], [1, 1, 1]); + } + #[test] fn provenance_and_role_pairs_are_counted_per_primary_row() { let url = url::Url::parse("https://workshop.example/").unwrap(); let doc = Doc::from_html( @@ -175,8 +229,8 @@ mod extended_tests { place.sections[0].path_name = true; place.sections[0].sources = vec![Source::Sitemap, Source::Llms]; place.sections[1].sources = vec![Source::Llms, Source::PrimaryNav]; - assert_eq!(measure(&place)[10..], [1, 1, 3, 1, 0]); + assert_eq!(measure(&place)[10..15], [1, 1, 3, 1, 0]); place.sections[0].tier = Tier::Secondary; - assert_eq!(measure(&place)[10..], [0, 0, 1, 0, 1]); + assert_eq!(measure(&place)[10..15], [0, 0, 1, 0, 1]); } } From e264fa9411f71a771764f1587e688c31f3fc7163 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 05:27:25 +0100 Subject: [PATCH 39/40] docs(architecture): name the search map driver --- docs/architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture.md b/docs/architecture.md index 5ad178041..0795f95d1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,7 +45,7 @@ These groups locate work; they do not define a dependency graph. | Provider and decision services | `zephium-agent-provider-transport`, `zephium-agent-model-catalog`, `zephium-decision` | | Account and credentials | `zephium-account`, `zephium-credentials` | | Sidebar assistance and voice | `zephium-page-assist`, `zephium-voice`, desktop adapters | -| Search map | `zephium-map` (pure logic, depends only on `zephium-core`), `zephium-public-fetch` (anonymous public reads and the public-address guard) | +| Search map | `zephium-map` (pure logic, depends only on `zephium-core`), `zephium-public-fetch` (anonymous public reads and the public-address guard), `zephium-map-driver` (runs one search session over a results source and the anonymous reader, and projects it for the interface) | | External protocol integration | `zephium-mcp` | | Development and qualification | `xtask`, `scripts/`, `zephium-terra-macos-probe` | From e833acd6973118fc2b95585ff33464bae5d8542e Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Mon, 23 Nov 2026 07:20:54 +0100 Subject: [PATCH 40/40] fix(map): hold a landing to its own robots policy and time the map from its results A read that redirects to another origin of the same site now waits for that origin's robots policy and is refused when the policy is missing or disallows it. The wait is charged to the read and byte budgets. Rows: a path prefix counts as a language edition only with evidence from the page, so /go/install and /js/install stay apart and a menu of short topical links is not taken for a language picker; a header link keeps its row beside a menu of the same name; children are told apart by destination, not by display text; a menu with one item keeps its shape; sign-in links in a collapsed panel become actions; a marked panel lends nothing. The site title reads only top-level entities that belong to the site. Session and driver: a memo from an asked search no longer completes an eager one (memo version 7); a budget skip no longer blocks a later open; an out-of-range slot is refused instead of indexing; an expired fetch is not dispatched; the map's clock starts when the first results page arrives, and the driver bounds that wait itself. Bench and try-out: one corrupt comparison journal no longer aborts a replay; left:: and right:: pick a comparison side; failed opens and an interrupt set the exit status. --- crates/zephium-map-driver/src/driver.rs | 51 ++- crates/zephium-map-driver/src/driver/tests.rs | 179 ++++++++++- crates/zephium-map/src/doc.rs | 7 + crates/zephium-map/src/doc/html.rs | 26 +- crates/zephium-map/src/doc/html/arena.rs | 11 - crates/zephium-map/src/session.rs | 47 ++- crates/zephium-map/src/session/memo.rs | 3 +- crates/zephium-map/src/session/scheduler.rs | 131 ++++++-- crates/zephium-map/src/site.rs | 80 +++-- crates/zephium-map/src/site/card.rs | 142 +++++---- crates/zephium-map/src/site/menus.rs | 116 +++---- crates/zephium-map/src/site/menus/editions.rs | 30 +- crates/zephium-map/src/site/navigation.rs | 1 + crates/zephium-map/src/site/title.rs | 30 +- crates/zephium-map/tests/card.rs | 38 ++- crates/zephium-map/tests/card_ownership.rs | 151 ++++++++- crates/zephium-map/tests/session.rs | 296 +++++++++++++++++- xtask/src/map_bench/run.rs | 9 +- xtask/src/map_bench/run/tests/session.rs | 37 +++ xtask/src/map_bench/session/quality.rs | 4 +- xtask/src/map_try.rs | 32 +- xtask/src/map_try/printer.rs | 22 +- xtask/src/map_try/printer/tests.rs | 21 ++ xtask/src/map_try/tests.rs | 118 +++++-- 24 files changed, 1279 insertions(+), 303 deletions(-) diff --git a/crates/zephium-map-driver/src/driver.rs b/crates/zephium-map-driver/src/driver.rs index dc9fb9a40..0473ae3af 100644 --- a/crates/zephium-map-driver/src/driver.rs +++ b/crates/zephium-map-driver/src/driver.rs @@ -30,6 +30,9 @@ use crate::{ pub const TICK: Duration = Duration::from_millis(250); pub const CHANGE_BUFFER: usize = 64; pub const MAX_WAITING_OPENS: usize = 4; +/// The longest a run waits for its first results page when its source sets +/// no bound of its own. +pub const RESULTS_WAIT: Duration = Duration::from_secs(60); const SLOTS: usize = 2; pub struct MapRequest { @@ -145,7 +148,7 @@ impl Driver { let (opens, open_requests) = mpsc::channel(MAX_WAITING_OPENS); let shared = Arc::new(Shared::default()); let run = Run { - started: io.clock.now(), + started: None, session: Some(session), io, profile: request.profile, @@ -276,7 +279,7 @@ struct Run { hosts: BTreeMap<Id, String>, immediate: VecDeque<Input>, seq: u32, - started: Duration, + started: Option<Duration>, cancelled: watch::Receiver<bool>, cancelling: bool, unsent: Option<Publication>, @@ -367,7 +370,7 @@ impl Run { { self.session = Some(session); self.opening = Some(request); - self.started = self.io.clock.now(); + self.started = Some(self.io.clock.now()); return Some(effects); } let (place, _) = wire::place(held.place(), Some(held.robots())); @@ -412,6 +415,9 @@ impl Run { Some(ReadState::Refused { failure }) => OpenResult::Refused { failure: failure.into(), }, + Some(ReadState::Skipped { .. }) => OpenResult::Refused { + failure: wire::Failure::Limit, + }, _ => OpenResult::Refused { failure: if entry.is_some() { wire::Failure::Blocked @@ -433,7 +439,7 @@ impl Run { } () = self.tx.closed() => return Next::Stop, Some(done) = self.reads.join_next_with_id() => done, - () = tokio::time::sleep(TICK) => return Next::Tick, + () = tokio::time::sleep(TICK), if self.started.is_some() => return Next::Tick, }; match self.completed(done) { Some(input) => { @@ -464,11 +470,16 @@ impl Run { } fn elapsed(&self) -> Duration { - self.io.clock.now().saturating_sub(self.started) + self.started.map_or(Duration::ZERO, |start| { + self.io.clock.now().saturating_sub(start) + }) } async fn handle(&mut self, input: Option<Input>) -> Option<Vec<Effect>> { let mut session = self.session.take()?; + if matches!(input, Some(Input::Results { .. })) { + self.started.get_or_insert_with(|| self.io.clock.now()); + } let time = self.elapsed(); let cancelling = self.cancelling; let shared = Arc::clone(&self.shared); @@ -659,7 +670,10 @@ impl Run { let source = Arc::clone(&self.io.results); let shared = Arc::clone(&self.shared); let read = self.reads.spawn(async move { - let result = match source.load(url).await { + let loaded = tokio::time::timeout(RESULTS_WAIT, source.load(url)) + .await + .unwrap_or(Err(Failure::Timeout)); + let result = match loaded { Ok(page) => { if page.truncated || page.html.len() > page::MAX_RESULTS_SOURCE_BYTES { bump(&shared.truncated_results); @@ -675,7 +689,14 @@ impl Run { self.tasks.insert(read.id(), (id, Kind::Results)); } - fn fetch(&mut self, id: Id, request: FetchRequest) { + fn fetch(&mut self, id: Id, mut request: FetchRequest) { + let Some(started) = self.started else { + self.immediate.push_back(Input::Fetch { + id, + result: Err(Failure::Unavailable), + }); + return; + }; let host = request.url.host_str().unwrap_or_default().to_owned(); if self.hosts.len() >= MAX_CONCURRENT || self.hosts.values().filter(|h| **h == host).count() >= MAX_HOST_CONCURRENT @@ -688,10 +709,20 @@ impl Run { return; } let fetcher = Arc::clone(&self.io.fetch); - let timeout = request.timeout; - bump(&self.shared.fetches); + let clock = Arc::clone(&self.io.clock); + let shared = Arc::clone(&self.shared); let read = self.reads.spawn(async move { - let result = tokio::time::timeout(timeout, fetcher.fetch(request)) + let elapsed = clock.now().saturating_sub(started); + let remaining = zephium_map::session::MAX_ELAPSED.saturating_sub(elapsed); + if elapsed >= zephium_map::session::LAST_START || remaining.is_zero() { + return Input::Fetch { + id, + result: Err(Failure::Timeout), + }; + } + request.timeout = request.timeout.min(remaining); + bump(&shared.fetches); + let result = tokio::time::timeout(request.timeout, fetcher.fetch(request)) .await .unwrap_or(Err(Failure::Timeout)); Input::Fetch { id, result } diff --git a/crates/zephium-map-driver/src/driver/tests.rs b/crates/zephium-map-driver/src/driver/tests.rs index f7a5883eb..7a63fec56 100644 --- a/crates/zephium-map-driver/src/driver/tests.rs +++ b/crates/zephium-map-driver/src/driver/tests.rs @@ -6,8 +6,9 @@ use crate::{ Reading, }; use std::sync::atomic::AtomicUsize; +use tokio::sync::oneshot; use zephium_map::{ - session::{FetchResult, FETCH_TIMEOUT, MAX_ELAPSED}, + session::{FetchResult, FETCH_TIMEOUT, LAST_START, MAX_ELAPSED}, PlaceKey, }; @@ -34,6 +35,7 @@ struct Seen { struct Fake { results: Plan, + results_wait: Option<mpsc::Sender<oneshot::Sender<()>>>, pages: BTreeMap<String, Plan>, delay: Duration, seen: Mutex<Seen>, @@ -47,6 +49,7 @@ impl Fake { fn new(results: Plan) -> Self { Self { results, + results_wait: None, pages: BTreeMap::new(), delay: Duration::from_millis(5), seen: Mutex::default(), @@ -101,7 +104,13 @@ impl ResultsSource for Fake { fn load(&self, url: Url) -> Reading<Result<ResultsPage, Failure>> { self.calls.fetch_add(1, Ordering::SeqCst); let plan = self.results.clone(); + let wait = self.results_wait.clone(); Box::pin(async move { + if let Some(wait) = wait { + let (deliver, delivery) = oneshot::channel(); + wait.send(deliver).await.unwrap(); + delivery.await.unwrap(); + } match plan { Plan::Page(_, html) => Ok(ResultsPage { html, @@ -441,7 +450,7 @@ async fn the_driver_refuses_reads_over_the_ceilings() { hosts: BTreeMap::new(), immediate: VecDeque::new(), seq: 0, - started: Duration::ZERO, + started: Some(Duration::ZERO), cancelled: watch::channel(false).1, cancelling: false, unsent: None, @@ -534,12 +543,31 @@ async fn cancel_ends_once_and_starts_nothing_after() { checked(&changes, 1); assert_eq!(changes.len(), 1); assert_eq!(outcome(&changes).0, Outcome::Cancelled); + assert!(tokio::time::timeout(FETCH_TIMEOUT, rx.recv()) + .await + .unwrap() + .is_none()); tokio::time::sleep(Duration::from_secs(30)).await; assert_eq!(active(&fake), 0); assert_eq!(fake.seen().fetches.len(), fetched); driver.cancel(); } +#[tokio::test(start_paused = true)] +async fn a_blocked_place_cannot_dispatch_a_fetch_after_the_deadline() { + for deadline in [zephium_map::session::LAST_START, MAX_ELAPSED] { + let fake = Arc::new(acme(Fake::new(html(RESULT)))); + let (driver, mut rx) = stalled(&fake); + while driver.counts().bytes < NAV.len() as u64 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + tokio::time::advance(deadline).await; + let changes = rest(&mut rx).await; + assert_eq!(outcome(&changes).0, Outcome::Done); + assert_eq!(driver.counts().fetches, 2); + } +} + fn stalled(fake: &Arc<Fake>) -> (Driver, mpsc::Receiver<Change>) { Driver::start_buffered(request("acme"), io(fake), &Handle::current(), 1).unwrap() } @@ -601,24 +629,112 @@ async fn dropping_the_driver_or_the_receiver_stops_reads_silently() { } } +async fn waiting_for_results( + plan: Plan, +) -> ( + Arc<Fake>, + Driver, + mpsc::Receiver<Change>, + oneshot::Sender<()>, +) { + let (wait, mut pending) = mpsc::channel(1); + let mut fake = acme(Fake::new(plan)); + fake.results_wait = Some(wait); + let fake = Arc::new(fake); + let (driver, rx) = stalled(&fake); + let deliver = pending.recv().await.unwrap(); + (fake, driver, rx, deliver) +} + #[tokio::test(start_paused = true)] -async fn a_hanging_results_page_is_ended_by_the_elapsed_budget() { - let fake = Arc::new(Fake::new(Plan::Hang)); - let (_driver, mut rx) = start(&fake, request("acme")); +async fn delayed_results_leave_the_site_read_budget_intact() { + for pause in [LAST_START - Duration::from_secs(1), LAST_START, MAX_ELAPSED] { + let (_fake, driver, mut rx, deliver) = waiting_for_results(html(RESULT)).await; + tokio::time::advance(Duration::from_secs(11)).await; + deliver.send(()).unwrap(); + // A full change buffer holds the first place before its follow-up reads. + tokio::time::timeout(FETCH_TIMEOUT, async { + while driver.counts().bytes < NAV.len() as u64 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the initial site reads should start after results delivery"); + assert_eq!(driver.counts().fetches, 2); + tokio::time::advance(pause).await; + let changes = rest(&mut rx).await; + checked(&changes, 0); + let (result, elapsed_ms) = outcome(&changes); + assert_eq!(result, Outcome::Done); + assert!((pause..pause + TICK).contains(&Duration::from_millis(elapsed_ms.into()))); + assert_eq!(driver.counts().fetches > 2, pause < LAST_START); + } +} + +#[tokio::test(start_paused = true)] +async fn a_late_results_failure_keeps_the_source_failure() { + let (fake, _driver, mut rx, deliver) = waiting_for_results(Plan::Fail(Failure::Consent)).await; + tokio::time::advance(MAX_ELAPSED * 2).await; + deliver.send(()).unwrap(); let changes = rest(&mut rx).await; checked(&changes, 0); - let (outcome, elapsed) = outcome(&changes); assert_eq!( - outcome, - Outcome::Failed { - failure: WireFailure::Timeout - } + outcome(&changes), + ( + Outcome::Failed { + failure: WireFailure::Consent + }, + 0 + ) + ); + assert!(fake.seen().fetches.is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_results_page_that_never_arrives_ends_as_a_timeout() { + let (fake, _driver, mut rx, mut deliver) = waiting_for_results(html(RESULT)).await; + assert!(tokio::time::timeout(RESULTS_WAIT - TICK, rx.recv()) + .await + .is_err()); + let changes = rest(&mut rx).await; + checked(&changes, 0); + assert_eq!( + outcome(&changes), + ( + Outcome::Failed { + failure: WireFailure::Timeout + }, + 0 + ) ); - let budget = MAX_ELAPSED.as_millis() as u32; - assert!((budget..=budget + TICK.as_millis() as u32).contains(&elapsed)); + tokio::time::timeout(TICK, deliver.closed()).await.unwrap(); assert!(fake.seen().fetches.is_empty()); } +#[tokio::test(start_paused = true)] +async fn cancel_or_drop_releases_a_pending_first_results_page() { + for cancel in [true, false] { + let (fake, driver, mut rx, mut deliver) = waiting_for_results(html(RESULT)).await; + assert!(tokio::time::timeout(MAX_ELAPSED * 2, rx.recv()) + .await + .is_err()); + if cancel { + driver.cancel(); + driver.cancel(); + let changes = rest(&mut rx).await; + assert_eq!(changes.len(), 1); + checked(&changes, 0); + assert_eq!(outcome(&changes), (Outcome::Cancelled, 0)); + } else { + drop(driver); + } + assert_eq!(rx.recv().await, None); + tokio::time::timeout(TICK, deliver.closed()).await.unwrap(); + assert!(fake.seen().fetches.is_empty()); + assert_eq!(fake.memo_calls.load(Ordering::SeqCst), 0); + } +} + #[tokio::test(start_paused = true)] async fn a_hanging_fetch_is_ended_by_its_own_timeout() { let fake = @@ -813,6 +929,45 @@ async fn opens_wait_for_search_end_and_the_queue_refuses_at_capacity() { ); } +#[tokio::test(start_paused = true)] +async fn an_open_after_a_long_idle_gets_its_full_fetch_timeout() { + let fake = + Arc::new(acme(Fake::new(html(RESULT))).site("acme.com", &[("/pricing", Plan::Hang)])); + let (driver, mut rx) = start(&fake, request("acme")); + let changes = rest(&mut rx).await; + let Some(Change::Place { place, .. }) = last_for(&changes, 0) else { + panic!("expected place"); + }; + let id = &place + .sections + .iter() + .find(|entry| entry.label == "Pricing") + .unwrap() + .id; + tokio::time::advance(MAX_ELAPSED * 2).await; + let opened = fake.clock.now(); + driver.open(0, id).unwrap(); + assert!(matches!( + rx.recv().await, + Some(Change::Place { complete: true, .. }) + )); + assert!(matches!( + rx.recv().await, + Some(Change::Opened { + result: OpenResult::Refused { + failure: WireFailure::Timeout + }, + .. + }) + )); + assert!(fake + .seen() + .fetches + .iter() + .any(|path| path == "acme.com/pricing")); + assert_eq!(fake.clock.now() - opened, FETCH_TIMEOUT); +} + #[tokio::test(start_paused = true)] async fn cancelling_or_dropping_during_an_open_aborts_it_silently() { for cancel in [true, false] { diff --git a/crates/zephium-map/src/doc.rs b/crates/zephium-map/src/doc.rs index 776870622..dce0f7378 100644 --- a/crates/zephium-map/src/doc.rs +++ b/crates/zephium-map/src/doc.rs @@ -371,6 +371,13 @@ impl DocBuilder { pub fn finish(mut self) -> Doc { for n in &mut self.doc.nodes { + n.link_prefix_bytes = n.text.get(..n.link_prefix_bytes).map_or(0, |prefix| { + prefix + .chars() + .filter(|&c| crate::visible_char(c)) + .map(char::len_utf8) + .sum() + }); n.text.retain(crate::visible_char); n.name.retain(crate::visible_char); if let Some(id) = &mut n.element_id { diff --git a/crates/zephium-map/src/doc/html.rs b/crates/zephium-map/src/doc/html.rs index c7c5cdcaa..9486b3efd 100644 --- a/crates/zephium-map/src/doc/html.rs +++ b/crates/zephium-map/src/doc/html.rs @@ -376,6 +376,8 @@ impl DocBuilder { if panel.attr("id") != Some(id) || panel.clipped("id") || panel.hidden_by_lift() + || excluded(marks(&panel)) + || excluded(panel.lifted_marks()) || panel.has_attr("hidden") || panel.attr("aria-hidden") != Some("true") || !super::super::ancestors(&self.doc.nodes, index).any(|a| { @@ -577,18 +579,6 @@ impl DocBuilder { node.marks.insert(Marks::ACTION); } node.destination = self.resolve(&n, "href", base); - if node - .destination - .as_ref() - .and_then(Url::domain) - .and_then(|h| h.split_once('.')) - .zip(n.link_language()) - .is_some_and(|((prefix, _), lang)| { - prefix.len() == 2 && prefix.eq_ignore_ascii_case(lang) - }) - { - node.marks.insert(Marks::LANGUAGE_HOST); - } } if role == Role::Image { node.image_source = self.resolve(&n, "src", base); @@ -644,6 +634,18 @@ impl DocBuilder { node.link_language = link_language(&n) .filter(|s| s.len() <= room) .map(str::to_ascii_lowercase); + if node + .destination + .as_ref() + .and_then(Url::domain) + .and_then(|h| h.split_once('.')) + .zip(node.link_language.as_deref()) + .is_some_and(|((prefix, _), lang)| { + prefix.len() == 2 && prefix.eq_ignore_ascii_case(lang) + }) + { + node.marks.insert(Marks::LANGUAGE_HOST); + } } let index = self.push(node)? as usize; if matches!(role, Role::Button | Role::Link) { diff --git a/crates/zephium-map/src/doc/html/arena.rs b/crates/zephium-map/src/doc/html/arena.rs index 19a94544c..7c4dcc808 100644 --- a/crates/zephium-map/src/doc/html/arena.rs +++ b/crates/zephium-map/src/doc/html/arena.rs @@ -164,17 +164,6 @@ impl<'a> NodeRef<'a> { (next != 0).then_some(self.arena.node(next)) }) } - pub(super) fn link_language(self) -> Option<&'a str> { - self.attr("hreflang").or_else(|| { - std::iter::successors(Some(self), |n| { - n.arena - .attached_parent(n.id) - .filter(|&p| p != 0) - .map(|p| n.arena.node(p)) - }) - .find_map(|n| n.attr("lang")) - }) - } fn attribute(self, key: &str) -> Option<&'a Attr> { if self.is_text() { return None; diff --git a/crates/zephium-map/src/session.rs b/crates/zephium-map/src/session.rs index 78ae215ec..ddec284f9 100644 --- a/crates/zephium-map/src/session.rs +++ b/crates/zephium-map/src/session.rs @@ -19,6 +19,8 @@ mod types; pub use memo::*; pub use types::*; +const SEARCH_SLOTS: usize = 2; + #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] enum Work { Robots, @@ -197,11 +199,12 @@ pub struct Session { queue: VecDeque<Job>, seen: BTreeSet<(Work, PageMatch)>, robots: BTreeMap<String, Robots>, + landings: BTreeMap<String, Vec<(Job, FetchResult)>>, hosts: BTreeMap<String, u32>, started: u32, sections: u32, - sites: [Option<SiteState>; 2], - unseeded: [Option<Unseeded>; 2], + sites: [Option<SiteState>; SEARCH_SLOTS], + unseeded: [Option<Unseeded>; SEARCH_SLOTS], articles: BTreeMap<usize, Doc>, first_passage: Option<Passage>, passages: Vec<Passage>, @@ -321,6 +324,9 @@ impl Session { confidence: Confidence, stale: bool, ) -> Result<(Self, Vec<Effect>), OpenRefusal> { + if usize::from(slot) >= SEARCH_SLOTS { + return Err(OpenRefusal::NotOpenable); + } let index = held.open_index(id)?; let url = held.place().sections[index].key.as_url().clone(); let key = held.place().sections[index].key.page_match(); @@ -375,10 +381,23 @@ impl Session { return None; }; let site = self.sites.get(*slot)?.as_ref()?; - let entry = site.place.as_ref()?.sections.iter().find(|entry| { - entry.read == Some(ReadState::Queued) && site.discovered.get(&entry.id) == Some(key) - })?; - Some((*slot as u8, &entry.id)) + let id = site + .place + .as_ref()? + .sections + .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .find(|entry| { + entry.read == Some(ReadState::Queued) && site.discovered.get(&entry.id) == Some(key) + }) + .map(|entry| &entry.id) + .or_else(|| { + site.discovered + .iter() + .find(|(_, discovered)| *discovered == key) + .map(|(id, _)| id) + })?; + Some((*slot as u8, id)) } fn place_robots(&self, place: &Place) -> BTreeMap<String, Robots> { @@ -409,6 +428,7 @@ impl Session { queue: VecDeque::new(), seen: BTreeSet::new(), robots: BTreeMap::new(), + landings: BTreeMap::new(), hosts: BTreeMap::new(), started: 0, sections: 0, @@ -662,6 +682,7 @@ impl Session { }; state.place = Some(place.clone()); let complete = !stale + && (self.cfg.sections == Sections::Asked || m.eager) && state.section_hint.is_none() && (state.requested.is_none() || place.focus.is_some()); state.complete = complete; @@ -820,11 +841,11 @@ impl Session { }; detail.probed_section = state.probed_section; self.stats.places.insert(i as u8, detail); - for entry in &mut place.sections { + let mut update_read = |entry: &mut site::Entry| { if entry.menu_only || self.cfg.sections == Sections::Asked && !candidates.contains(&entry.id) { - continue; + return; } let discovered = state .discovered @@ -838,8 +859,15 @@ impl Session { if let Some(key) = state.external.get(discovered) { entry.off_site = SiteKey::from_url(key.as_url()).as_ref() != Some(&place.site); entry.key = key.clone(); + entry.localized = false; entry.locator = Locator::default(); } + }; + for entry in &mut place.sections { + update_read(entry); + if self.cfg.sections == Sections::Asked { + entry.children.iter_mut().for_each(&mut update_read); + } } if !std::mem::take(&mut state.stale) && state.place.as_ref() == Some(&place) { return; @@ -871,6 +899,7 @@ impl Session { Sections::Asked => place .sections .iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) .filter(|e| e.read == Some(ReadState::Queued)) .map(|e| e.key.clone()) .collect(), @@ -1118,6 +1147,7 @@ impl Session { self.finished = true; self.pending.clear(); self.queue.clear(); + self.landings.clear(); self.emit( MapEvent::End { outcome: if self.stats.cancelled { @@ -1286,6 +1316,7 @@ impl Session { let site = s.seed.site.clone(); let memo = SiteMemo { version: MEMO_VERSION, + eager: self.cfg.sections == Sections::All, read_at: self.cfg.now, payload: SitePayload { place, robots }, }; diff --git a/crates/zephium-map/src/session/memo.rs b/crates/zephium-map/src/session/memo.rs index 3a45dce9c..deb5dca06 100644 --- a/crates/zephium-map/src/session/memo.rs +++ b/crates/zephium-map/src/session/memo.rs @@ -3,12 +3,13 @@ use crate::results::{MAX_SOCIAL, TITLE_BYTES}; use crate::site::{MAX_CHILDREN, MAX_SECTIONS}; use serde::{Deserialize, Serialize}; -pub const MEMO_VERSION: u16 = 6; +pub const MEMO_VERSION: u16 = 7; pub const MAX_MEMO_BYTES: usize = 256 * 1024; pub const MEMO_TTL: u64 = 24 * 60 * 60; #[derive(Clone, Serialize, Deserialize)] pub struct SiteMemo { pub version: u16, + pub eager: bool, pub read_at: u64, pub payload: SitePayload, } diff --git a/crates/zephium-map/src/session/scheduler.rs b/crates/zephium-map/src/session/scheduler.rs index d062ec82e..a54549755 100644 --- a/crates/zephium-map/src/session/scheduler.rs +++ b/crates/zephium-map/src/session/scheduler.rs @@ -5,7 +5,7 @@ impl Session { let Work::Section(i, key) = &job.work else { return None; }; - let state = self.sites[*i].as_ref()?; + let state = self.sites.get(*i)?.as_ref()?; if self.cfg.sections == Sections::All { return state .eager @@ -64,11 +64,7 @@ impl Session { .iter() .filter_map(|job| self.section_rank(job)) .min(); - let received = self - .stats - .phases - .values() - .fold(0u64, |bytes, phase| bytes.saturating_add(phase.bytes)); + let received = self.received_bytes(); let mut progressed = false; for _ in 0..self.queue.len() { let Some(job) = self.queue.pop_front() else { @@ -85,10 +81,20 @@ impl Session { let host = origin(&job.url); let hostname = job.url.host_str().unwrap_or_default(); let phase = job.work.phase(); + let landing_policy = job.work == Work::Robots; + if landing_policy && self.robots.contains_key(&host) { + self.resolve_landings(&host, out); + progressed = true; + continue; + } let blocked = if received >= self.cfg.total_bytes && matches!( job.work, - Work::Section(..) | Work::Sitemap(_) | Work::Llms(_) | Work::Passage(_) + Work::Robots + | Work::Section(..) + | Work::Sitemap(_) + | Work::Llms(_) + | Work::Passage(_) ) { Some(Budget::TotalBytes) } else if self.started >= self.cfg.fetches { @@ -128,6 +134,15 @@ impl Session { self.queue.push_back(job); continue; } + if landing_policy { + if active.iter().any(|(h, robots)| h == &host && *robots) { + self.queue.push_back(job); + continue; + } + self.start_job(job, out); + progressed = true; + break; + } if let Some(policy) = self.robots.get(&host) { if !policy.allows(&job.url[Position::BeforePath..Position::AfterQuery]) { self.set_read( @@ -200,6 +215,10 @@ impl Session { } } pub(super) fn set_read(&mut self, job: &Job, read: ReadState, out: &mut Vec<Effect>) { + if job.work == Work::Robots { + self.resolve_landings(&origin(&job.url), out); + return; + } if let Some(open) = &mut self.opening { if matches!(job.work, Work::Section(..)) { let failure = match read { @@ -210,7 +229,10 @@ impl Session { _ => Failure::Limit, }; let place = &mut open.held.payload.place; - place.sections[open.index].read = Some(ReadState::Refused { failure }); + place.sections[open.index].read = Some(match read { + ReadState::Skipped { budget } if budget != Budget::Elapsed => read, + _ => ReadState::Refused { failure }, + }); place.notes.robots_disallowed |= failure == Failure::Robots; place.notes.truncated |= failure == Failure::Limit; self.stats @@ -274,9 +296,15 @@ impl Session { } else { Effect::Fetch { id, - url, expect, - max_bytes: job.work.byte_cap(&self.cfg), + max_bytes: if job.work == Work::Robots && self.landings.contains_key(&origin(&url)) + { + let remaining = self.cfg.total_bytes.saturating_sub(self.received_bytes()); + u64::from(job.work.byte_cap(&self.cfg)).min(remaining) as u32 + } else { + job.work.byte_cap(&self.cfg) + }, + url, timeout: self .cfg .timeout @@ -332,6 +360,7 @@ impl Session { let mut updated = open.held.clone(); let entry = &mut updated.payload.place.sections[open.index]; entry.key = landing; + entry.localized = false; entry.locator = Locator::default(); if let Some(updated) = updated.bounded() { open.held = updated; @@ -355,13 +384,6 @@ impl Session { if job.work == Work::Robots && !r.final_url.path().ends_with("/robots.txt") { return Err(Failure::External); } - if job.work != Work::Robots - && self.robots.get(&origin(&r.final_url)).is_some_and(|p| { - !p.allows(&r.final_url[Position::BeforePath..Position::AfterQuery]) - }) - { - return Err(Failure::Robots); - } Ok(r) }); if job.work == Work::Robots { @@ -370,7 +392,18 @@ impl Session { (r.final_url.as_str().strip_prefix(landing.as_str()) == Some("/robots.txt")) .then_some(landing) }); + let host = origin(&job.url); + let received = self.received_bytes(); + let over_budget = self.landings.contains_key(&host) + && (received > self.cfg.total_bytes + || received == self.cfg.total_bytes + && result.as_ref().is_ok_and(|r| r.truncated)); let policy = match result { + Ok(_) if over_budget => { + self.budget(Budget::TotalBytes); + self.refused(phase, Failure::Limit); + Robots::limited() + } Ok(r) => Robots::from_sample(&r.bytes, r.truncated), Err(f) => { self.refused(phase, f); @@ -392,11 +425,68 @@ impl Session { .robots_truncated |= truncated; } if let Some(landing) = landing { - self.robots.insert(landing, policy.clone()); + self.robots + .entry(landing.clone()) + .or_insert_with(|| policy.clone()); + if landing != host { + self.resolve_landings(&landing, out); + } } - self.robots.insert(origin(&job.url), policy); + self.robots.insert(host.clone(), policy); + self.resolve_landings(&host, out); + return; + } + let Ok(r) = result else { + self.settle(job, result, out); + return; + }; + let host = origin(&r.final_url); + if self.robots.contains_key(&host) { + self.accept_landing(job, r, out); + return; + } + let Ok(url) = r.final_url.join("/robots.txt") else { + self.settle(job, Err(Failure::Robots), out); return; + }; + let in_flight = self.pending.values().any(|p| { + matches!(p, Pending::Job(j) if j.work == Work::Robots && j.url.origin() == url.origin()) + }); + let waiting = self.landings.entry(host).or_default(); + if waiting.is_empty() && !in_flight { + self.queue.push_front(Job { + work: Work::Robots, + url, + }); } + waiting.push((job, r)); + } + + fn received_bytes(&self) -> u64 { + self.stats + .phases + .values() + .fold(0, |sum, phase| sum.saturating_add(phase.bytes)) + } + + fn resolve_landings(&mut self, host: &str, out: &mut Vec<Effect>) { + for (job, result) in self.landings.remove(host).into_iter().flatten() { + self.accept_landing(job, result, out); + } + } + + fn accept_landing(&mut self, job: Job, r: FetchResult, out: &mut Vec<Effect>) { + let allowed = self + .robots + .get(&origin(&r.final_url)) + .is_some_and(|policy| { + policy.allows(&r.final_url[Position::BeforePath..Position::AfterQuery]) + }); + self.settle(job, if allowed { Ok(r) } else { Err(Failure::Robots) }, out); + } + + fn settle(&mut self, job: Job, result: Result<FetchResult, Failure>, out: &mut Vec<Effect>) { + let phase = job.work.phase(); let side = job.work.side(); let applied = result.and_then(|r| self.apply(job.clone(), r, out)); if let Err(f) = applied { @@ -442,7 +532,7 @@ impl Session { .place .sections .iter() - .position(|e| e.key.page_match() == key) + .position(|e| e.id == open.held.place().sections[open.index].id) { let occupied = memo .payload @@ -479,6 +569,7 @@ impl Session { ); } self.rebuild(i, out); + self.plan_sections(i); } Work::Passage(pos) => { let doc = html(&r, DocLimits::ARTICLE)?; diff --git a/crates/zephium-map/src/site.rs b/crates/zephium-map/src/site.rs index b9fe473c0..2ca52ffa4 100644 --- a/crates/zephium-map/src/site.rs +++ b/crates/zephium-map/src/site.rs @@ -137,6 +137,8 @@ pub struct Entry { pub menu_item: bool, #[serde(default)] pub path_name: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) localized: bool, pub off_site: bool, pub group: Option<String>, pub children: Vec<Entry>, @@ -352,6 +354,7 @@ struct LinkName { host_root: bool, } struct Build<'a> { + localized: BTreeSet<crate::PageMatch>, llms_headings: BTreeMap<EntryId, String>, names: std::collections::HashMap<EntryId, LinkName>, place: Place, @@ -416,6 +419,7 @@ impl Build<'_> { menu_only: false, menu_item: false, path_name: false, + localized: self.localized.contains(&key.page_match()), read: None, tier: source.tier(), key, @@ -497,13 +501,9 @@ impl Build<'_> { c.sources.contains(&Source::Heading) || !globals.contains(&c.card_route()) } }); - let mut distinct = Vec::new(); - for child in children { - if !distinct.iter().any(|c| card::same_display(c, &child)) { - distinct.push(child); - } - } - e.children = distinct; + let mut distinct = BTreeSet::new(); + children.retain(|c| distinct.insert(c.card_route())); + e.children = children; } self.sections .retain(|e| !e.menu_only || !e.children.is_empty()); @@ -884,12 +884,21 @@ impl Place { &'a self, landing: &'a Url, ) -> impl Iterator<Item = &'a Entry> { - self.sections.iter().filter(move |entry| { - !entry.menu_only - && entry.key.page_match() != self.entry.page_match() - && !crate::key::same_page(entry.key.as_url(), landing) - && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) - }) + self.sections + .iter() + .flat_map(|e| { + std::iter::once(e).chain( + e.children + .iter() + .filter(|c| c.sources.contains(&Source::EngineResult)), + ) + }) + .filter(move |entry| { + !entry.menu_only + && entry.key.page_match() != self.entry.page_match() + && !crate::key::same_page(entry.key.as_url(), landing) + && (self.focuses(entry) || entry.sources.contains(&Source::EngineResult)) + }) } pub(crate) fn likely_section(&self, request: &Focus, landing: &Url) -> Option<&Entry> { use SectionRole::*; @@ -1069,6 +1078,7 @@ impl Entry { menu_only: false, menu_item: false, path_name: false, + localized: self.localized, read: None, tier: source.tier(), key: self.key.clone(), @@ -1133,9 +1143,6 @@ impl Entry { } return; } - if self.children.iter().any(|c| card::same_display(c, &entry)) { - return; - } if self.children.len() == MAX_CHILDREN && requested.is_some_and(|request| { request.rank(&entry).is_some_and(|rank| { @@ -1182,6 +1189,7 @@ pub(crate) fn enrich_held( child_cap: usize, ) -> (Place, PlaceStats) { let mut build = Build { + localized: card::localized_pages(page), names: Default::default(), llms_headings: Default::default(), place, @@ -1239,6 +1247,7 @@ pub(crate) fn with_results( requested: Option<&Focus>, ) -> Result<Place, KeyError> { let mut build = Build { + localized: Default::default(), names: Default::default(), llms_headings: Default::default(), index: place @@ -1297,8 +1306,9 @@ pub(crate) fn read_site_for( ) -> Result<(Place, PlaceStats, Vec<SectionRead>), KeyError> { let key = PlaceKey::from_url(doc.page()).ok_or(KeyError::Url)?; let site = SiteKey::from_url(doc.page()).ok_or(KeyError::Url)?; - let title = title::site_title(doc.head(), &site); + let title = title::site_title(doc.head(), &site, doc.page()); let mut place = Build { + localized: card::localized_pages(doc), names: Default::default(), llms_headings: Default::default(), index: Default::default(), @@ -1381,7 +1391,9 @@ pub(crate) fn read_site_for( }) .collect(); for (i, page) in page_sections { + let home_paths = std::mem::replace(&mut place.localized, card::localized_pages(page)); place.enrich_section(i, page); + place.localized = home_paths; } place.stats.section_page_truncated |= inputs.pages.len() > MAX_SECTION_PAGES; if let Some(robots) = inputs.robots { @@ -1403,10 +1415,22 @@ pub(crate) fn read_site_for( }) }) .count(); - let eager = place.eager_reads(); + let mut eager = place.eager_reads(); let mut menus = (!place.notes.wall).then(|| menus::Menus::read(&place, doc)); - let evidence = menus.as_mut().map(menus::Menus::take_evidence); + let evidence = menus.as_mut().map(|menus| { + for action in menus.take_actions() { + place.section(action); + } + menus.take_evidence() + }); place.finish_sections(Some(doc.page()), menus); + let mut discovered: BTreeSet<_> = eager.iter().map(|r| r.id.clone()).collect(); + eager.extend( + place + .eager_reads() + .into_iter() + .filter(|r| discovered.insert(r.id.clone())), + ); if let Some(evidence) = evidence { evidence.measure(&place.place, &mut place.stats); } @@ -1503,6 +1527,24 @@ mod tests { mod review_tests { use super::*; + #[test] + fn the_final_card_admits_eager_rows_displaced_from_the_first_shortlist() { + let mut html = String::from("<nav>"); + for i in 0..MAX_PRIMARY_SECTIONS { + html.push_str(&format!("<a href='/docs/{i}'>Docs</a>")); + } + html.push_str("<a href='/pricing'>Pricing</a></nav>"); + let url = Url::parse("https://example.com/").unwrap(); + let doc = Doc::from_html(&url, html.as_bytes(), None, crate::DocLimits::SITE_PAGE).unwrap(); + let (place, _, eager) = read_site_for(&doc, &SiteInputs::default(), None).unwrap(); + let pricing = place + .sections + .iter() + .find(|e| e.label == "Pricing") + .unwrap(); + assert!(eager.iter().any(|r| r.id == pricing.id)); + } + #[test] fn result_sitelink_merges_with_the_discovered_id_after_a_redirect() { let base = Url::parse("https://example.com/").unwrap(); diff --git a/crates/zephium-map/src/site/card.rs b/crates/zephium-map/src/site/card.rs index f00e0f9af..547a5aea9 100644 --- a/crates/zephium-map/src/site/card.rs +++ b/crates/zephium-map/src/site/card.rs @@ -26,7 +26,16 @@ pub(super) fn locale(segment: &str) -> bool { impl Entry { pub fn card_page(&self) -> PageMatch { - localized_key(&self.key) + if self.localized { + if let Some((_, rest)) = locale_path(self.key.as_url()) { + let mut url = self.key.as_url().clone(); + url.set_path(&format!("/{rest}")); + if let Ok(key) = PageKey::from_url(&url) { + return key.page_match(); + } + } + } + self.key.page_match() } pub(super) fn card_route(&self) -> (PageMatch, Option<String>) { (self.card_page(), self.locator.fragment()) @@ -51,15 +60,73 @@ pub fn skip_label(label: &str) -> bool { ) } -fn localized_key(key: &PageKey) -> PageMatch { - let mut url = key.as_url().clone(); - if let Some((first, rest)) = url.path().trim_matches('/').split_once('/') { - if locale(first) { - let path = format!("/{rest}"); - url.set_path(&path); - } +fn locale_path(url: &Url) -> Option<(&str, &str)> { + let path = url.path().trim_matches('/'); + let (first, rest) = path.split_once('/').unwrap_or((path, "")); + locale(first).then_some((first, rest)) +} + +pub(super) fn localized_pages(doc: &Doc) -> BTreeSet<PageMatch> { + fn primary(tag: &str) -> &str { + tag.split_once('-').map_or(tag, |(language, _)| language) } - PageKey::from_url(&url).map_or_else(|_| key.page_match(), |k| k.page_match()) + let links = doc + .nodes() + .iter() + .enumerate() + .filter_map(|(i, n)| { + let url = n.destination.as_ref()?; + visible(doc.nodes(), i).then_some((url, n.link_language.as_deref())) + }) + .chain( + doc.menu_links + .iter() + .filter(|(i, _)| visible(doc.nodes(), **i)) + .flat_map(|(_, links)| links.iter()) + .map(|l| (&l.url, l.language.as_deref())), + ) + .map(|(url, language)| { + let tagged = language + .zip(locale_path(url)) + .is_some_and(|(tag, (prefix, _))| { + primary(tag).eq_ignore_ascii_case(primary(prefix)) + }); + (url, tagged) + }) + .chain( + doc.head() + .alternates + .iter() + .filter(|a| !a.language.is_empty()) + .map(|a| (&a.url, true)), + ); + let observed: BTreeSet<_> = links + .clone() + .map(|(u, _)| u) + .chain([doc.page()]) + .filter_map(|u| PageKey::from_url(u).ok().map(|k| k.page_match())) + .collect(); + let current = locale_path(doc.page()).map(|(lang, _)| lang); + links + .filter_map(|(url, tagged)| { + let (prefix, rest) = locale_path(url)?; + let key = PageKey::from_url(url).ok()?.page_match(); + if tagged || current.is_some_and(|c| c.eq_ignore_ascii_case(prefix)) { + return Some(key); + } + if rest.is_empty() && current.is_none() { + return None; + } + let mut counterpart = url.clone(); + counterpart.set_path(&match current { + Some(lang) => format!("/{lang}/{rest}"), + None => format!("/{rest}"), + }); + observed + .contains(&PageKey::from_url(&counterpart).ok()?.page_match()) + .then_some(key) + }) + .collect() } pub(super) fn placeholder(label: &str) -> bool { @@ -178,7 +245,7 @@ pub(super) fn self_link(entry: &Entry, root: &PageKey, landing: Option<&Url>) -> return false; } let url = entry.key.as_url(); - if localized_key(&entry.key) == root.page_match() + if entry.card_page() == root.page_match() || landing.is_some_and(|u| crate::key::same_page(u, url)) { return true; @@ -241,34 +308,12 @@ impl Build<'_> { pub(super) fn edit_card(&mut self, landing: Option<&Url>) { let mut candidates = Vec::new(); let entries = std::mem::take(&mut self.sections); - let locale_paths: BTreeSet<_> = entries - .iter() - .flat_map(|e| std::iter::once(e).chain(&e.children)) - .filter_map(|e| { - let u = e.key.as_url(); - let path = u.path().trim_matches('/'); - (locale(path) - && u.domain().map(|h| h.trim_start_matches("www.")) - == Some(self.key.host.as_str()) - && !e.label.eq_ignore_ascii_case(path)) - .then_some(path.to_owned()) - }) - .collect(); let home = |e: &Entry| { self_link(e, &self.entry, landing) || e.locator.element.is_some() && skip_label(&e.label) && (e.key.page_match() == self.entry.page_match() || landing.is_some_and(|u| crate::key::same_page(u, e.key.as_url()))) - || (locale_paths.len() > 1 - && e.locator == Locator::default() - && e.key.as_url().query().is_none() - && e.key - .as_url() - .domain() - .map(|h| h.trim_start_matches("www.")) - == Some(self.key.host.as_str()) - && locale_paths.contains(e.key.as_url().path().trim_matches('/'))) }; let originals: std::collections::HashMap<_, _> = entries .iter() @@ -333,7 +378,7 @@ impl Build<'_> { } } let destination = ( - localized_key(&e.key), + e.card_page(), e.locator.clone(), e.menu_only.then(|| e.id.clone()), ); @@ -355,7 +400,7 @@ impl Build<'_> { let existing = destinations .get(&destination) .or_else(|| edition.as_ref().and_then(|key| editions.get(key))) - .or_else(|| labels.get(&label)) + .or_else(|| labels.get(&(label.clone(), e.menu_only))) .copied(); if let Some(i) = existing { let kept: &mut Entry = &mut self.place.sections[i]; @@ -369,7 +414,7 @@ impl Build<'_> { let children = std::mem::take(&mut e.children); if destination != ( - localized_key(&kept.key), + kept.card_page(), kept.locator.clone(), kept.menu_only.then(|| kept.id.clone()), ) @@ -379,15 +424,15 @@ impl Build<'_> { for child in children { kept.child(child, self.requested); } + labels.insert((label, destination.2.is_some()), i); destinations.insert(destination, i); - labels.insert(label, i); if let Some(key) = edition { editions.insert(key, i); } } else { let index = self.sections.len(); destinations.insert(destination, index); - labels.insert(label, index); + labels.insert((label, e.menu_only), index); if let Some(key) = edition { editions.insert(key, index); } @@ -487,9 +532,7 @@ impl Build<'_> { } pub(super) fn child_self(child: &Entry, parent: &Entry) -> bool { - !parent.menu_only - && child.locator == parent.locator - && localized_key(&child.key) == localized_key(&parent.key) + !parent.menu_only && child.locator == parent.locator && child.card_page() == parent.card_page() } fn scheme_like(segment: &str) -> bool { @@ -519,25 +562,6 @@ pub fn display_path(url: &Url) -> String { } } -pub(super) fn same_display(left: &Entry, right: &Entry) -> bool { - if left.key.as_url().domain() != right.key.as_url().domain() { - return false; - } - let name = |e: &Entry| { - let label = crate::flatten(&e.label).to_lowercase(); - if label.contains("://") - || label - .split_whitespace() - .any(|w| w.starts_with("http:") || w.starts_with("https:") || w.starts_with("www.")) - { - display_path(e.key.as_url()).to_lowercase() - } else { - label - } - }; - name(left) == name(right) && display_path(left.key.as_url()) == display_path(right.key.as_url()) -} - pub fn display_hostname(url: &Url) -> Option<&str> { let host = url.domain()?.trim_end_matches('.'); (!host.is_empty() diff --git a/crates/zephium-map/src/site/menus.rs b/crates/zephium-map/src/site/menus.rs index 1c137d8d3..228a99de1 100644 --- a/crates/zephium-map/src/site/menus.rs +++ b/crates/zephium-map/src/site/menus.rs @@ -4,12 +4,13 @@ use crate::Node; const MIN_MENU_ITEMS: usize = 2; mod editions; -use editions::{edition_path, Editions}; +use editions::Editions; #[cfg(test)] mod tests; #[derive(Default)] pub(super) struct Menus { + actions: Vec<Entry>, members: BTreeSet<EntryId>, groups: BTreeMap<usize, Menu>, order: BTreeMap<EntryId, usize>, @@ -55,11 +56,12 @@ impl Evidence { stats.language_groups += usize::from(language_group); if !e.menu_only && (e.children.iter().any(|c| c.card_route() == e.card_route()) - || self.pages.get(&label).is_some_and(|page| { - page.as_ref().is_none_or(|id| { - *id != e.id && *id != EntryId::new(None, &e.key, &e.locator) - }) - })) + || !self.direct.contains_key(&e.id) + && self.pages.get(&label).is_some_and(|page| { + page.as_ref().is_none_or(|id| { + *id != e.id && *id != EntryId::new(None, &e.key, &e.locator) + }) + })) { stats.invalid_group_pages += 1; } @@ -146,7 +148,12 @@ impl Menus { .alternates .iter() .filter(|a| !a.language.is_empty()) - .filter_map(|a| PageKey::from_url(&a.url).ok().map(|k| k.page_match())) + .filter_map(|a| { + Some(( + PageKey::from_url(&a.url).ok()?.page_match(), + a.url.fragment().map(str::to_owned), + )) + }) .collect(); let mut standalone = Vec::new(); let actions: BTreeSet<_> = build @@ -303,10 +310,11 @@ impl Menus { let page = n .destination .as_ref() - .and_then(|u| build.entry_for(u, label, Source::PrimaryNav)) - .filter(|e| { - !card::self_link(e, &build.entry, Some(doc.page())) && !card::action(e) - }); + .and_then(|u| build.entry_for(u, label, Source::PrimaryNav)); + if page.as_ref().is_some_and(card::action) { + continue; + } + let page = page.filter(|e| !card::self_link(e, &build.entry, Some(doc.page()))); let trigger = page .as_ref() .filter(|e| e.key.page_match() == build.entry.page_match()) @@ -337,21 +345,21 @@ impl Menus { if card::skip_link(url, label, doc.page()) { continue; } - menu.editions.observe( - url, - link.language.as_deref(), - doc.page(), - &alternates, - ); - if let Some(e) = + menu.editions + .observe(url, &build.localized, doc.page(), &alternates); + if let Some(mut e) = build.entry_for(url, label, Source::MenuGroup).filter(|e| { - !(card::action(e) - || card::placeholder(label) + !(card::placeholder(label) || card::self_link(e, &build.entry, Some(doc.page())) || e.off_site && site_profile(url).is_some()) }) { - menu.add_item(e); + if card::action(&e) { + e.tier = Tier::Action; + menus.actions.push(e); + } else { + menu.add_item(e); + } } } } @@ -408,7 +416,7 @@ impl Menus { .and_then(|o| menus.groups.get_mut(&o)) { menu.editions - .observe(url, n.link_language.as_deref(), doc.page(), &alternates); + .observe(url, &build.localized, doc.page(), &alternates); } if SiteKey::from_url(url).as_ref() != Some(&build.site) && site_profile(url).is_some() { continue; @@ -435,7 +443,7 @@ impl Menus { .and_then(|(first, _)| named.get(first)) }) }) { - footer_links.push((*owner, entry, n.link_language.as_deref())); + footer_links.push((*owner, entry)); } continue; } @@ -491,14 +499,18 @@ impl Menus { .filter(|(_, m)| m.editions.targets.is_empty()) .map(|(&i, _)| i) .collect(); - for (owner, mut entry, language) in footer_links { + for (owner, mut entry) in footer_links { if let Some(menu) = owners .get(&owner) .filter(|o| empty.contains(o)) .and_then(|o| menus.groups.get_mut(o)) { - menu.editions - .observe(entry.key.as_url(), language, doc.page(), &alternates); + menu.editions.observe( + entry.key.as_url(), + &build.localized, + doc.page(), + &alternates, + ); entry.sources = vec![Source::Footer, Source::MenuGroup]; menu.add_item(entry); } @@ -524,17 +536,8 @@ impl Menus { menus.direct.entry(entry.card_route()).or_insert((i, entry)); } } - let editions: BTreeSet<_> = menus - .groups - .values() - .filter(|m| m.editions.is_picker()) - .flat_map(|m| m.items.iter().map(|e| e.id.clone())) - .collect(); menus.groups.retain(|_, m| { - if m.editions.is_picker() - || m.items.len() >= MIN_MENU_ITEMS - && m.items.iter().all(|e| editions.contains(&e.id)) - { + if m.editions.is_picker() { menus.evidence.languages.insert(normal(&m.label)); menus .evidence @@ -590,7 +593,7 @@ impl Menus { menu.items.retain(|e| { distinct.insert(e.card_route()) && !menus.direct.contains_key(&e.card_route()) }); - if menu.items.len() >= MIN_MENU_ITEMS || menu.page.is_some() && !menu.items.is_empty() { + if !menu.items.is_empty() { menus.evidence.pages.insert( normal(&menu.label), menu.page.as_ref().map(|e| e.id.clone()), @@ -600,19 +603,6 @@ impl Menus { .extend(menu.items.iter().map(|e| e.id.clone())); } } - let locale_roots: BTreeSet<_> = menus - .direct - .values() - .filter_map(|(_, e)| { - let url = e.key.as_url(); - let path = url.path().trim_matches('/'); - (card::locale(path) - && !path.eq_ignore_ascii_case(&e.label) - && url.query().is_none() - && edition_path(url) == edition_path(doc.page())) - .then_some(path.to_owned()) - }) - .collect(); let triggers: BTreeSet<_> = menus .groups .values() @@ -624,9 +614,7 @@ impl Menus { || card::sentence(&e.label) || build.link_is_edition(e) || menus.excluded.contains(&e.id) - || triggers.contains(&e.id) - || locale_roots.len() >= MIN_MENU_ITEMS - && locale_roots.contains(e.key.as_url().path().trim_matches('/'))) + || triggers.contains(&e.id)) }); menus.evidence.direct.extend( menus @@ -652,6 +640,9 @@ impl Menus { pub(super) fn take_evidence(&mut self) -> Evidence { std::mem::take(&mut self.evidence) } + pub(super) fn take_actions(&mut self) -> Vec<Entry> { + std::mem::take(&mut self.actions) + } } impl Menus { @@ -660,7 +651,6 @@ impl Menus { let member_routes: BTreeSet<_> = self .groups .values() - .filter(|m| m.items.len() >= MIN_MENU_ITEMS || m.page.is_some()) .flat_map(|m| m.items.iter().map(Entry::card_route)) .collect(); build.sections.retain(|e| { @@ -735,20 +725,7 @@ impl Menus { .filter_map(|m| m.page.as_ref().map(|e| e.id.clone())) .collect(); for (position, menu) in self.groups { - if menu.items.is_empty() || menu.items.len() < MIN_MENU_ITEMS && menu.page.is_none() { - // A lone link underneath a toggle keeps its own name and destination. - if menu.page.is_none() { - if let Some(mut item) = menu.items.into_iter().next() { - if let Some((_, e)) = old.get_mut(&prior_id(&item.id)) { - e.label = item.label; - e.role = item.role; - } else { - item.menu_item = false; - item.add_sources([menu.source]); - rows.push((position, item)); - } - } - } + if menu.items.is_empty() { continue; } if let Some(id) = &menu.trigger { @@ -820,6 +797,7 @@ impl Menus { } if prior == original || routes.contains_key(&original) { item.key = e.key; + item.localized = e.localized; item.off_site = e.off_site; item.locator = e.locator; } @@ -870,7 +848,7 @@ impl Menus { for (_, mut e) in original { if let Some(&i) = labels .get(&normal(&e.label)) - .filter(|_| e.tier != Tier::Action) + .filter(|_| e.tier != Tier::Action && !direct_routes.contains(&e.card_route())) { let group = &mut rows[i].1; if build diff --git a/crates/zephium-map/src/site/menus/editions.rs b/crates/zephium-map/src/site/menus/editions.rs index 7875dba2b..2782b7927 100644 --- a/crates/zephium-map/src/site/menus/editions.rs +++ b/crates/zephium-map/src/site/menus/editions.rs @@ -3,12 +3,11 @@ use super::*; #[derive(Default)] pub(super) struct Editions { pub(super) targets: BTreeSet<crate::PageMatch>, - languages: BTreeSet<String>, matched: bool, unrelated: bool, } -pub(super) fn edition_path(url: &Url) -> (&str, &str) { +fn edition_path(url: &Url, localized: bool) -> (&str, &str) { let host = url.domain().unwrap_or_default().trim_start_matches("www."); let host = host .split_once('.') @@ -16,16 +15,23 @@ pub(super) fn edition_path(url: &Url) -> (&str, &str) { .map_or(host, |(_, rest)| rest); let path = url.path().trim_matches('/'); let (first, rest) = path.split_once('/').unwrap_or((path, "")); - (host, if card::locale(first) { rest } else { path }) + ( + host, + if localized && card::locale(first) { + rest + } else { + path + }, + ) } impl Editions { pub(super) fn observe( &mut self, url: &Url, - language: Option<&str>, + localized: &BTreeSet<crate::PageMatch>, current: &Url, - alternates: &BTreeSet<crate::PageMatch>, + alternates: &BTreeSet<(crate::PageMatch, Option<String>)>, ) { let Ok(key) = PageKey::from_url(url) else { return; @@ -34,26 +40,20 @@ impl Editions { let edition = url.port_or_known_default() == current.port_or_known_default() && url.query() == current.query() && url.fragment().is_none() - && edition_path(url) == edition_path(current); - let alternate = alternates.contains(&target); - self.unrelated |= !edition && !alternate && language.is_none(); + && edition_path(url, localized.contains(&target)) == edition_path(current, true); + let alternate = alternates.contains(&(target.clone(), url.fragment().map(str::to_owned))); + self.unrelated |= !edition && !alternate; self.matched |= (edition && !crate::key::same_page(url, current)) || alternate; - if let Some(lang) = language { - self.languages.insert(lang.to_owned()); - } self.targets.insert(target); } pub(super) fn merge(&mut self, other: Self) { self.targets.extend(other.targets); - self.languages.extend(other.languages); self.matched |= other.matched; self.unrelated |= other.unrelated; } pub(super) fn is_picker(&self) -> bool { - !self.unrelated - && self.targets.len() >= MIN_MENU_ITEMS - && (self.matched || self.languages.len() >= MIN_MENU_ITEMS) + !self.unrelated && self.targets.len() >= MIN_MENU_ITEMS && self.matched } } diff --git a/crates/zephium-map/src/site/navigation.rs b/crates/zephium-map/src/site/navigation.rs index d6933f775..9253c21a1 100644 --- a/crates/zephium-map/src/site/navigation.rs +++ b/crates/zephium-map/src/site/navigation.rs @@ -293,6 +293,7 @@ impl Build<'_> { if !crate::key::same_page(doc.page(), self.sections[index].key.as_url()) || doc.page().fragment().is_some() { + self.sections[index].localized = self.localized.contains(&key.page_match()); self.sections[index].locator = element_locator(doc.page()).unwrap_or_default(); } self.sections[index].key = key.clone(); diff --git a/crates/zephium-map/src/site/title.rs b/crates/zephium-map/src/site/title.rs index 3262c334b..f234e41bf 100644 --- a/crates/zephium-map/src/site/title.rs +++ b/crates/zephium-map/src/site/title.rs @@ -10,7 +10,7 @@ pub fn title_segments(title: &str) -> impl Iterator<Item = &str> { .map(str::trim) } -pub(super) fn site_title(head: &Head, site: &SiteKey) -> String { +pub(super) fn site_title(head: &Head, site: &SiteKey, page: &Url) -> String { fn name(value: &str) -> Option<String> { let value = crate::flatten(&crate::clean_text(value)); (!value.is_empty() && value.len() <= MAX_SITE_NAME_BYTES).then_some(value) @@ -20,7 +20,16 @@ pub(super) fn site_title(head: &Head, site: &SiteKey) -> String { } let mut website = None; let mut organization = None; - linked::objects(head, |obj| { + let mut visit = |obj: &serde_json::Value| { + if obj.get("url").is_some_and(|v| { + v.as_str() + .and_then(|s| page.join(s).ok()) + .and_then(|u| SiteKey::from_url(&u)) + .as_ref() + != Some(site) + }) { + return; + } let slot = if linked::typed(obj, "WebSite") { &mut website } else if linked::typed(obj, "Organization") { @@ -31,7 +40,22 @@ pub(super) fn site_title(head: &Head, site: &SiteKey) -> String { if slot.is_none() { *slot = obj["name"].as_str().and_then(name); } - }); + }; + for raw in &head.linked_data { + let Ok(root) = serde_json::from_str::<serde_json::Value>(raw) else { + continue; + }; + for node in root + .as_array() + .map(Vec::as_slice) + .unwrap_or(std::slice::from_ref(&root)) + { + visit(node); + if let Some(graph) = node["@graph"].as_array() { + graph.iter().for_each(&mut visit); + } + } + } let label = site.as_str().split('.').next().unwrap_or_default(); website .or(organization) diff --git a/crates/zephium-map/tests/card.rs b/crates/zephium-map/tests/card.rs index fb17422de..12f85d289 100644 --- a/crates/zephium-map/tests/card.rs +++ b/crates/zephium-map/tests/card.rs @@ -88,16 +88,16 @@ fn destination_label_and_localized_duplicates_keep_the_first_representative() { } #[test] -fn sibling_identity_uses_display_host_and_path() { +fn sibling_identity_includes_query_and_host() { let p=card("<nav><ul><li><a href='/learn'>Learn</a><ul><li><a href='https://alpha.workshop.example/?mode=1'>Manual</a></li><li><a href='https://alpha.workshop.example/?mode=2'>Manual</a></li><li><a href='https://beta.workshop.example/'>Manual</a></li></ul></li></ul></nav>"); let children = &p.sections[0].children; - assert_eq!(children.len(), 2); + assert_eq!(children.len(), 3); assert_eq!( children[0].key.as_url().domain(), Some("alpha.workshop.example") ); assert_eq!( - children[1].key.as_url().domain(), + children[2].key.as_url().domain(), Some("beta.workshop.example") ); } @@ -116,19 +116,31 @@ proptest! { let ids=|p:Place|p.sections.into_iter().filter(|e|e.tier==Tier::Primary).map(|e|(e.label,e.id)).collect::<Vec<_>>(); let original = ids(a); prop_assert_eq!(&original,&ids(b)); - let children = slugs.iter().map(|slug| format!("<a href='/pages/{slug}'>{slug}</a>")).collect::<String>(); + let children = original.iter().map(|(slug, _)| format!("<a href='/pages/{slug}'>{slug}</a>")).collect::<String>(); let grouped = card(&format!("<nav><div><button>Topics</button>{children}</div></nav>")); - if original.len()>1 { - prop_assert_eq!(grouped.sections.len(),1); - let placed:Vec<_>=grouped.sections[0].children.iter().map(|e|(e.label.clone(),e.id.clone())).collect(); - prop_assert_eq!(original,placed); - } else {prop_assert_eq!(original,ids(grouped));} + let placed: std::collections::BTreeSet<_> = grouped.sections.iter() + .flat_map(|e| std::iter::once(e).chain(&e.children)) + .filter(|e| !e.menu_only && e.tier == Tier::Primary) + .map(|e| e.id.clone()).collect(); + prop_assert_eq!(original.into_iter().map(|(_, id)| id).collect::<std::collections::BTreeSet<_>>(), placed); } } +#[test] +fn the_generated_topics_destination_can_be_the_menu_index() { + let p = card( + "<nav><div><button>Topics</button><a href='/pages/aaaa'>aaaa</a> + <a href='/pages/topics'>topics</a></div></nav>", + ); + assert_eq!(p.sections.len(), 1); + assert_eq!(p.sections[0].key.as_url().path(), "/pages/topics"); + assert_eq!(p.sections[0].children.len(), 1); + assert_eq!(p.sections[0].children[0].key.as_url().path(), "/pages/aaaa"); +} + #[test] fn language_editions_need_a_matching_language_declaration() { - let p=card("<nav><div lang='ja'><a href='https://ja.workshop.example/'>日本語</a></div><a hreflang='de' href='https://de.workshop.example/'>Deutsch</a><a href='https://ai.workshop.example/'>Studio</a><a href='/go/'>Go</a></nav>"); + let p=card("<nav><a lang='ja' href='https://ja.workshop.example/'>日本語</a><a hreflang='de' href='https://de.workshop.example/'>Deutsch</a><a href='https://ai.workshop.example/'>Studio</a><a href='/go/'>Go</a></nav>"); assert_eq!( p.sections .iter() @@ -170,7 +182,7 @@ fn sparse_navigation_uses_a_named_footer_section_without_promoting_ancillary_lin #[test] fn repeated_locale_roots_are_not_sections_and_query_specific_routes_remain_distinct() { - let p=card("<nav><a href='/fr/'>Français</a><a href='/de'>Deutsch</a><a href='/products?t=one'>First</a><a href='/products?t=two'>Second</a></nav>"); + let p=card("<nav><a hreflang='fr' href='/fr/'>Français</a><a hreflang='de' href='/de'>Deutsch</a><a href='/products?t=one'>First</a><a href='/products?t=two'>Second</a></nav>"); assert_eq!( p.sections .iter() @@ -209,7 +221,7 @@ fn an_observed_directory_represents_three_or_more_deep_sibling_articles() { } #[test] -fn a_shared_clipped_path_does_not_create_indistinguishable_children() { +fn a_shared_clipped_display_path_preserves_distinct_destinations() { let common = "x".repeat(zephium_map::site::MAX_PATH_CHARS); let p=card(&format!("<nav><ul><li><a href='/guide'>Guide</a><ul><li><a href='/{common}1'>Index</a></li><li><a href='/{common}2'>Index</a></li><li><a href='/{common}3'>Index C#</a></li><li><a href='/{common}4'>Index C++</a></li></ul></li></ul></nav>")); assert_eq!( @@ -218,7 +230,7 @@ fn a_shared_clipped_path_does_not_create_indistinguishable_children() { .iter() .map(|e| e.label.as_str()) .collect::<Vec<_>>(), - ["Index", "Index C#", "Index C++"] + ["Index", "Index", "Index C#", "Index C++"] ); } diff --git a/crates/zephium-map/tests/card_ownership.rs b/crates/zephium-map/tests/card_ownership.rs index 134fe0be8..14bfb686c 100644 --- a/crates/zephium-map/tests/card_ownership.rs +++ b/crates/zephium-map/tests/card_ownership.rs @@ -21,6 +21,147 @@ fn labels(e: &Entry) -> Vec<&str> { e.children.iter().map(|c| c.label.as_str()).collect() } +#[test] +fn short_topical_paths_are_independent_destinations() { + let (p, _) = + read("<nav><a href='/go/install'>Install Go</a><a href='/js/install'>Install JS</a></nav>"); + assert_eq!(row(&p, "Install Go").key.as_url().path(), "/go/install"); + assert_eq!(row(&p, "Install JS").key.as_url().path(), "/js/install"); + let (p, _) = read("<nav><div><button>Install</button><a lang='en' href='/go/install'>Go</a><a lang='en' href='/js/install'>JS</a></div></nav>"); + assert_eq!(labels(row(&p, "Install")), ["Go", "JS"]); +} + +#[test] +fn topical_root_links_do_not_make_an_edition_picker() { + let (p, _) = read( + "<nav><div><button>Topics</button><a href='/ai'>AI</a><a href='/ml'>ML</a></div></nav>", + ); + assert_eq!(labels(row(&p, "Topics")), ["AI", "ML"]); +} + +#[test] +fn a_counterpart_under_the_entry_locale_confirms_only_its_own_remainder() { + let url = Url::parse("https://workshop.example/en/").unwrap(); + let doc = Doc::from_html( + &url, + b"<nav><div><button>Guides</button> + <a href='/en/install'>Setup</a><a href='/de/install'>Installation</a> + <a href='/go/guide'>Go</a><a href='/js/guide'>JS</a></div></nav>", + None, + DocLimits::SITE_PAGE, + ) + .unwrap(); + let (p, _) = read_site_with_stats(&doc, &Default::default()).unwrap(); + assert_eq!(labels(row(&p, "Guides")), ["Setup", "Go", "JS"]); +} + +#[test] +fn a_menu_and_a_direct_page_can_share_a_label() { + let (place, stats) = read( + "<nav><a href='/catalog'>Products</a><div><button>Products</button> + <a href='/one'>First</a><a href='/two'>Second</a></div></nav>", + ); + let rows: Vec<_> = place + .sections + .iter() + .filter(|e| e.label == "Products") + .collect(); + assert_eq!(rows.len(), 2); + assert!(rows + .iter() + .any(|e| e.menu_only && labels(e) == ["First", "Second"])); + assert!(rows + .iter() + .any(|e| !e.menu_only && e.key.as_url().path() == "/catalog")); + assert_eq!( + (stats.missing_header_links, stats.invalid_group_pages), + (0, 0) + ); +} + +#[test] +fn disclosure_actions_leave_the_named_single_item_menu_intact() { + let (place, _) = read("<nav><button aria-controls='items'>Resources</button> + <div aria-hidden='true' id='items'><a href='/signin'>Sign in</a><a href='/guides'>Guides</a></div></nav>"); + assert_eq!(labels(row(&place, "Resources")), ["Guides"]); + assert!(place + .sections + .iter() + .any(|e| e.label == "Sign in" && e.tier == Tier::Action)); +} + +#[test] +fn marked_disclosure_panels_supply_no_destinations() { + for mark in ["data-type='ad'", "aria-label='AI-generated overview'"] { + let (place, _) = read(&format!("<nav><button aria-controls='items'>Resources</button> + <div {mark} aria-hidden='true' id='items'><a href='/a'>First</a><a href='/b'>Second</a></div></nav>")); + assert!(place.sections.is_empty(), "{mark}"); + } +} + +#[test] +fn menu_members_with_the_same_label_keep_their_fragment_targets() { + let (p, _) = read( + "<nav><div><button>Resources</button><a href='/docs#api'>Overview</a> + <a href='/docs#cli'>Overview</a><a href='/docs#api'>Overview</a></div></nav>", + ); + assert_eq!(labels(row(&p, "Resources")), ["Overview", "Overview"]); +} + +#[test] +fn a_mixed_menu_keeps_its_unrelated_language_tagged_guide() { + for guide in ["/guide", "/fr#guide"] { + let (p, _) = read(&format!( + "<link rel='alternate' hreflang='fr' href='/fr'><nav><div><button>Resources</button> + <a href='/fr'>French</a><a href='{guide}' hreflang='de'>Guide</a></div></nav>" + )); + assert!(labels(row(&p, "Resources")).contains(&"Guide")); + } +} + +#[test] +fn the_document_language_does_not_declare_a_link_target_language() { + let (p, _) = read( + "<html lang='en'><nav><a href='https://en.workshop.example/docs'>Docs</a></nav></html>", + ); + assert_eq!(row(&p, "Docs").tier, Tier::Primary); +} + +#[test] +fn cleaned_link_prefix_keeps_its_byte_boundary() { + let (p, _) = read( + "<nav><a href='/guide'><span>Docs\u{200b}</span><span> API reference</span></a></nav>", + ); + assert_eq!(p.sections[0].label, "Docs"); +} + +#[test] +fn site_title_uses_only_owned_top_level_entities() { + for (json, expected) in [ + ( + r#"{"@type":"JobPosting","hiringOrganization":{"@type":"Organization","name":"Recruiter"}}"#, + "Workshop", + ), + ( + r#"{"@type":"WebSite","url":"https://other.example","name":"Other"}"#, + "Workshop", + ), + ( + r#"{"@graph":[{"@type":"WebSite","url":"https://www.workshop.example","name":"Workshop tools"}]}"#, + "Workshop tools", + ), + ] { + assert_eq!( + read(&format!( + "<title>Home | Workshop</title><script type='application/ld+json'>{json}</script>" + )) + .0 + .title, + expected + ); + } +} + #[test] fn a_control_that_repeats_an_item_cannot_supply_the_group_page() { for (href, index, expected) in [ @@ -190,11 +331,11 @@ fn separate_navigation_representations_agree_on_members_and_independent_links() fn language_controls_need_evidence_from_their_destinations() { let alternates = "<link rel='alternate' hreflang='de' href='/eins'><link rel='alternate' hreflang='fr' href='/deux'>"; for (head, links, picker) in [ - ("", "<a hreflang='de' href='/eins'>First</a><a hreflang='fr' href='/deux'>Second</a>", true), - ("", "<a lang='de' href='/eins'>First</a><a lang='fr' href='/deux'>Second</a>", true), + ("", "<a hreflang='de' href='/eins'>First</a><a hreflang='fr' href='/deux'>Second</a>", false), + ("", "<a lang='de' href='/de'>First</a><a lang='fr' href='/fr'>Second</a>", true), (alternates, "<a href='/eins'>First</a><a href='/deux'>Second</a>", true), - ("", "<a href='/pt-BR/'>First</a><a href='/fr/'>Second</a>", true), - ("", "<a href='/zh-Hant-TW/'>First</a><a href='/es-419/'>Second</a>", true), + ("", "<a hreflang='pt-BR' href='/pt-BR/'>First</a><a hreflang='fr' href='/fr/'>Second</a>", true), + ("", "<a lang='zh-Hant-TW' href='/zh-Hant-TW/'>First</a><a lang='es-419' href='/es-419/'>Second</a>", true), ("", "<a href='https://de.workshop.example/'>First</a><a href='https://fr.workshop.example/'>Second</a>", true), ("", "<a lang='en' href='/docs/rust'>Rust</a><a lang='en' href='/docs/go'>Go</a>", false), ] { @@ -204,7 +345,7 @@ fn language_controls_need_evidence_from_their_destinations() { assert_eq!(p.sections.len(), 1); assert!(row(&p, "About").children.is_empty()); } else { - assert_eq!(labels(row(&p, "Languages")), ["Rust", "Go"]); + assert_eq!(labels(row(&p, "Languages")).len(), 2); } } } diff --git a/crates/zephium-map/tests/session.rs b/crates/zephium-map/tests/session.rs index 060a33e27..0642ee40c 100644 --- a/crates/zephium-map/tests/session.rs +++ b/crates/zephium-map/tests/session.rs @@ -79,6 +79,7 @@ fn name(e: &Effect) -> String { } struct Run { trace: Vec<String>, + identified_sections: BTreeSet<String>, stats: Stats, places: Vec<Place>, conf: Vec<Confidence>, @@ -96,6 +97,7 @@ fn run( let mut queue: VecDeque<_> = effects.into(); let mut run = Run { trace: Vec::new(), + identified_sections: BTreeSet::new(), stats: Stats::default(), places: Vec::new(), conf: Vec::new(), @@ -108,6 +110,11 @@ fn run( let id = effect.id(); assert!(ids.insert(id)); run.trace.push(name(&effect)); + if let Effect::Fetch { id, url, .. } = &effect { + if session.section_fetch(*id).is_some() { + run.identified_sections.insert(url.path().to_owned()); + } + } let input = reply(&effect).or_else(|| { Some(match &effect { Effect::LoadResults { .. } => Input::Results { @@ -312,6 +319,27 @@ fn asked_reads_only_focus_and_the_results_section_link() { assert_eq!(both.stats.phases[&Phase::Section].started, 2); } +#[test] +fn eager_capture_identifies_a_read_displaced_from_the_card() { + let run = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/docs'>More</a><a href='/pricing'>Pricing</a></nav>", + )), + _ => None, + }); + assert!(run + .held + .unwrap() + .place() + .sections + .iter() + .all(|e| e.key.as_url().path() != "/docs")); + assert!(run.identified_sections.contains("/docs")); +} + #[test] fn open_from_a_fresh_memo_matches_the_eager_section_and_keeps_other_rows() { let eager = run(cfg(), "acme", RESULT, |_| None); @@ -565,10 +593,9 @@ fn open_respects_read_ceilings_media_and_truncation() { assert!(stats.budgets.contains(&budget)); assert_eq!( section(place.place(), "Pricing").read, - Some(ReadState::Refused { - failure: Failure::Limit - }) + Some(ReadState::Skipped { budget }) ); + open_fetch(&open(place, "Pricing", asked()).1, "/pricing"); } for (bytes, truncated, media, failure) in [ (9, false, "text/html", Failure::Limit), @@ -617,6 +644,269 @@ fn open_respects_read_ceilings_media_and_truncation() { }) ); } + +#[test] +fn open_refuses_an_out_of_range_slot() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let id = section(held.place(), "Pricing").id.clone(); + assert!(Session::open(cfg(), held, 2, id.as_str(), Confidence::High, false).is_err()); +} + +#[test] +fn a_fresh_asked_memo_is_provisional_for_an_eager_search() { + let prior = run(asked(), "acme", RESULT, |_| None).memo.unwrap(); + let replay = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::LookupSite { id, .. } => Some(Input::Cache { + id: *id, + memo: Some(prior.clone()), + }), + _ => None, + }); + assert_eq!(replay.stats.fresh_memos, 1); + assert_eq!(replay.stats.phases[&Phase::Section].started, 2); +} + +#[test] +fn landing_policy_precedes_section_acceptance_and_is_shared_by_origin() { + let landing = Url::parse("https://docs.acme.com/private").unwrap(); + for (policy, allowed) in [ + (Ok("User-agent: *\nAllow: /"), true), + (Ok("User-agent: *\nDisallow: /private"), false), + (Err(Failure::Unavailable), false), + ] { + let result = run(cfg(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if matches!(url.path(), "/news" | "/pricing") => Some( + response(*id, &landing, "text/html", "<h2 id='member'>Member</h2>"), + ), + Effect::Fetch { id, url, .. } if url.origin() == landing.origin() => { + Some(match policy { + Ok(text) => response(*id, url, "text/plain", text), + Err(failure) => Input::Fetch { + id: *id, + result: Err(failure), + }, + }) + } + _ => None, + }); + assert_eq!( + result + .trace + .iter() + .filter(|e| *e == "fetch docs.acme.com/robots.txt") + .count(), + 1 + ); + let reads = &result.stats.phases[&Phase::Section]; + assert_eq!(reads.completed, 2); + assert_eq!( + reads.refused.get(&Failure::Robots).copied().unwrap_or(0), + if allowed { 0 } else { 2 } + ); + if allowed { + let place = result.held.as_ref().unwrap().place(); + assert!(place + .sections + .iter() + .any(|e| e.read == Some(ReadState::Read) + && e.children.iter().any(|c| c.label == "Member"))); + } else { + assert!(result.memo.is_none()); + assert!(result + .places + .iter() + .flat_map(|p| &p.sections) + .all(|e| e.children.is_empty())); + } + } +} + +#[test] +fn an_open_charges_its_landing_policy_to_both_budgets() { + let held = run(asked(), "acme", RESULT, |_| None).held.unwrap(); + let landing = Url::parse("https://docs.acme.com/price").unwrap(); + let body = "<h2 id='tiers'>Tiers</h2>"; + for config in [ + Config { + fetches: 1, + ..asked() + }, + Config { + total_bytes: body.len() as u64, + ..asked() + }, + ] { + let (mut session, effects) = open(held.clone(), "Pricing", config); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!( + section(after.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert!(!remembered && !stats.budgets.is_empty()); + } + let rules = "User-agent: *\nAllow: /\n"; + for (room, truncated, accepted) in [(rules.len(), false, true), (rules.len(), true, false)] { + let (mut session, effects) = open( + held.clone(), + "Pricing", + Config { + total_bytes: (body.len() + room) as u64, + ..asked() + }, + ); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert!( + matches!(&effects[0], Effect::Fetch { max_bytes, .. } if *max_bytes as usize == room) + ); + let mut input = response(id, &url, "text/plain", rules); + if let Input::Fetch { + result: Ok(result), .. + } = &mut input + { + result.truncated = truncated; + } + let effects = session.handle(input); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!(remembered, accepted); + assert_eq!( + section(after.place(), "Pricing").read == Some(ReadState::Read), + accepted + ); + assert_eq!(stats.budgets.contains(&Budget::TotalBytes), !accepted); + } + let (mut session, effects) = open(held, "Pricing", asked()); + let (id, _) = open_fetch(&effects, "/pricing"); + let effects = session.handle(response(id, &landing, "text/html", body)); + let (id, url) = open_fetch(&effects, "/robots.txt"); + assert_eq!(url.origin(), landing.origin()); + let rules = "User-agent: *\nDisallow: /price"; + let policy_landing = Url::parse("https://rules.acme.com/robots.txt").unwrap(); + let effects = session.handle(response(id, &policy_landing, "text/plain", rules)); + let (after, remembered, stats) = open_complete(session, effects); + assert_eq!(stats.phases[&Phase::Robots].bytes, rules.len() as u64); + assert_eq!( + section(after.place(), "Pricing").read, + Some(ReadState::Refused { + failure: Failure::Robots + }) + ); + assert!(!remembered); +} + +#[test] +fn search_landing_policy_obeys_search_caps_and_coalesces_concurrent_redirects() { + let landing = Url::parse("https://docs.acme.com/private").unwrap(); + let body = "<h2 id='private'>Restricted</h2>"; + for (config, budget) in [ + ( + Config { + fetches: 3, + ..cfg() + }, + Some(Budget::Fetches), + ), + ( + Config { + total_bytes: (NAV.len() + body.len()) as u64, + ..cfg() + }, + Some(Budget::TotalBytes), + ), + ( + Config { + concurrent: 4, + host_concurrent: 2, + ..cfg() + }, + None, + ), + ] { + let run = + run(config, "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if matches!(url.path(), "/pricing" | "/news") => { + Some(response(*id, &landing, "text/html", body)) + } + Effect::Fetch { id, url, .. } if url.origin() == landing.origin() => Some( + response(*id, url, "text/plain", "User-agent: *\nDisallow: /"), + ), + _ => None, + }); + assert!(run.memo.is_none()); + let denials = run.stats.phases[&Phase::Section].refused[&Failure::Robots]; + if let Some(budget) = budget { + assert!(run.stats.budgets.contains(&budget)); + assert_eq!(run.stats.phases[&Phase::Robots].started, 1); + assert_eq!(denials, 1); + } else { + assert_eq!(run.stats.phases[&Phase::Robots].started, 2); + assert_eq!(denials, 2); + } + } +} + +#[test] +fn opening_a_fragment_enriches_the_same_memo_row() { + let initial = run(asked(), "acme", RESULT, |effect| match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response( + *id, + url, + "text/html", + "<nav><a href='/docs#setup'>Setup</a><a href='/docs#reference'>Reference</a></nav>", + )), + _ => None, + }); + let (mut session, effects) = open(initial.held.unwrap(), "Reference", asked()); + let (id, url) = open_fetch(&effects, "/docs"); + let effects = session.handle(response(id, &url, "text/html", "<h2 id='cli'>CLI</h2>")); + let memo = effects + .iter() + .find_map(|e| match e { + Effect::RememberSite { site, memo, .. } => Some(SiteMemo::decode(memo, site).unwrap()), + _ => None, + }) + .unwrap(); + assert!(section(&memo.payload.place, "Setup").children.is_empty()); + assert!(!section(&memo.payload.place, "Reference") + .children + .is_empty()); +} + +#[test] +fn asked_reads_the_result_child_under_a_menu_only_parent() { + let result = RESULT.replace( + "https://acme.com/'>Acme workshop", + "https://acme.com/guide'>Acme Docs", + ); + let run = run(asked(), "acme docs", &result, |effect| { + match effect { + Effect::Fetch { id, url, .. } if url.path() == "/" => Some(response(*id, url, "text/html", + "<nav><div><button>Resources</button><a href='/guide'>Docs</a><a href='/news'>News</a></div></nav>")), + Effect::Fetch { id, url, .. } if url.path() == "/guide" => Some(response(*id, url, "text/html", "<h2>Reference</h2>")), + _ => None, + } + }); + assert_eq!( + run.trace.iter().filter(|e| e.ends_with("/guide")).count(), + 1 + ); + let place = run.held.unwrap(); + let menu = section(place.place(), "Resources"); + assert!(menu.menu_only); + assert_eq!( + menu.children + .iter() + .find(|c| c.key.as_url().path() == "/guide") + .unwrap() + .read, + Some(ReadState::Read) + ); +} #[test] fn fresh_place_streams_complete_replacements() { let r = run(cfg(), "acme news", RESULT, |_| None); diff --git a/xtask/src/map_bench/run.rs b/xtask/src/map_bench/run.rs index f96b1fe9d..54ac5f8c9 100644 --- a/xtask/src/map_bench/run.rs +++ b/xtask/src/map_bench/run.rs @@ -1112,8 +1112,13 @@ pub(super) fn replay( super::corpus::Kind::Place | super::corpus::Kind::Compare ) { - let comparisons = compare_sections(root, query, recorded.clock(), index)?; - write_json(&path.join(SECTION_COMPARISON), &comparisons)?; + match compare_sections(root, query, recorded.clock(), index) { + Ok(comparisons) => write_json(&path.join(SECTION_COMPARISON), &comparisons)?, + Err(error) => { + write_json(&path.join("sections-error.json"), &error.class)?; + eprintln!("map bench: {}", error.for_query(&query.label.id)); + } + } } } let manifest = ReplayManifest { diff --git a/xtask/src/map_bench/run/tests/session.rs b/xtask/src/map_bench/run/tests/session.rs index 148b54af6..9c0916b27 100644 --- a/xtask/src/map_bench/run/tests/session.rs +++ b/xtask/src/map_bench/run/tests/session.rs @@ -728,6 +728,43 @@ fn replay_refuses_a_different_engine_before_writing_a_run() { assert!(!root.path().join("replay").exists()); } +#[test] +fn section_comparison_finishes_after_one_corrupt_journal() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("corpus.toml"); + let entries: String = ["first", "second"] + .iter() + .map(|id| format!("[[query]]\nid='{id}'\ntext='Acme docs'\n{ACME}\n")) + .collect(); + fs::write(&path, entries).unwrap(); + let corpus = Corpus::load(std::slice::from_ref(&path)).unwrap(); + init_engine(root.path(), &corpus, EngineKind::Session); + let mut source = ScriptedSource::new(site); + for query in &corpus.queries { + run_session(root.path(), query, &mut source); + } + fs::write( + root.path().join("queries/first/requests.jsonl"), + b"incomplete", + ) + .unwrap(); + crate::map_bench_section_flags::run(&[ + "replay".into(), + "--compare-sections".into(), + "--engine".into(), + "session".into(), + "--from".into(), + root.path().display().to_string(), + "--corpus".into(), + path.display().to_string(), + ]) + .unwrap(); + let (run, manifest) = latest_replay(root.path()).unwrap().unwrap(); + assert_eq!(manifest.queries.len(), 2); + assert!(run.join("queries/first/sections-error.json").is_file()); + assert!(run.join("queries/second/sections.json").is_file()); +} + fn save_row(root: &Path, path: &Path, request: &FetchRequest, result: FetchResult) { let mut journal = Journal::load(path).unwrap(); let start = Duration::from_secs(10); diff --git a/xtask/src/map_bench/session/quality.rs b/xtask/src/map_bench/session/quality.rs index 09ef3160a..6ef92f04e 100644 --- a/xtask/src/map_bench/session/quality.rs +++ b/xtask/src/map_bench/session/quality.rs @@ -191,7 +191,7 @@ mod extended_tests { let url = url::Url::parse("https://workshop.example/").unwrap(); let doc = Doc::from_html( &url, - b"<nav><a href='/a'>One</a><a href='/b'>Two</a></nav>", + b"<nav><a href='/a'>One</a><a hreflang='de' href='/de/b'>Two</a></nav>", None, DocLimits::SITE_PAGE, ) @@ -199,7 +199,7 @@ mod extended_tests { let mut place = read_site(&doc, &Default::default()).unwrap(); let first = place.sections.pop().unwrap(); let mut alias = first.clone(); - alias.key = zephium_map::PageKey::from_url(&url.join("/de/b").unwrap()).unwrap(); + alias.key = zephium_map::PageKey::from_url(&url.join("/b").unwrap()).unwrap(); let row = &mut place.sections[0]; row.tier = Tier::Secondary; row.key = place.entry.clone(); diff --git a/xtask/src/map_try.rs b/xtask/src/map_try.rs index 3fe60d752..f143447bf 100644 --- a/xtask/src/map_try.rs +++ b/xtask/src/map_try.rs @@ -50,6 +50,7 @@ enum Error { Runtime, Interrupt, Stream, + OpenFailed, Output, } @@ -73,7 +74,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::MissingQuery => { - "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private] [--open <label>]..." + "Usage: cargo xtask map <query> --site <host> [--site <host>] [--private] [--open <label|left::label|right::label>]..." } Self::MissingSite => "Usage error: specify a host with --site", Self::BadHost => "Usage error: --site needs a bare public hostname", @@ -89,6 +90,7 @@ impl fmt::Display for Error { Self::Runtime => "Could not start the map runtime.", Self::Interrupt => "Could not listen for Ctrl-C.", Self::Stream => "The map stopped without an outcome.", + Self::OpenFailed => "One or more requested sections could not be read.", Self::Output => "Could not write the map to the terminal.", }) } @@ -369,9 +371,10 @@ async fn stream( let mut watching = true; let mut interrupted_by = None; let mut opens = opens.into_iter(); + let mut open_failed = false; let mut open_started = None; loop { - let change = tokio::select! { + let mut change = tokio::select! { biased; signal = &mut interrupt, if !cancelling => { interrupted_by = signal.err().map(|_| Error::Interrupt); @@ -397,7 +400,11 @@ async fn stream( } change = changes.recv() => change.ok_or(Error::Stream)?, }; - if let Change::End { outcome, .. } = change { + if let Change::End { outcome, .. } = &mut change { + if cancelling { + *outcome = Outcome::Cancelled; + } + let outcome = *outcome; print_lines( output, printer.lines(&change, started.elapsed(), driver.counts()), @@ -405,9 +412,13 @@ async fn stream( if outcome != Outcome::Done || cancelling { return interrupted_by.map_or(Ok(outcome), Err); } - open_started = start_open(driver, &printer, &mut opens, output)?; + open_started = start_open(driver, &printer, &mut opens, &mut open_failed, output)?; if open_started.is_none() { - return Ok(outcome); + return if open_failed { + Err(Error::OpenFailed) + } else { + Ok(outcome) + }; } continue; } @@ -417,6 +428,7 @@ async fn stream( let status = match result { OpenResult::Read => "read".to_owned(), OpenResult::Refused { failure } => { + open_failed = true; format!("refused ({})", printer::failure_text(failure)) } }; @@ -430,9 +442,13 @@ async fn stream( )], )?; } - open_started = start_open(driver, &printer, &mut opens, output)?; + open_started = start_open(driver, &printer, &mut opens, &mut open_failed, output)?; if open_started.is_none() { - return Ok(Outcome::Done); + return if open_failed { + Err(Error::OpenFailed) + } else { + Ok(Outcome::Done) + }; } continue; } @@ -449,6 +465,7 @@ fn start_open<'a>( driver: &Driver, printer: &Printer, opens: &mut impl Iterator<Item = &'a str>, + failed: &mut bool, output: &mut impl Write, ) -> Result<Option<(Instant, Counts)>, Error> { for label in opens { @@ -461,6 +478,7 @@ fn start_open<'a>( }, Err(reason) => format!("Open refused ({reason})"), }; + *failed = true; print_lines(output, [message])?; } Ok(None) diff --git a/xtask/src/map_try/printer.rs b/xtask/src/map_try/printer.rs index c38576efb..adb650458 100644 --- a/xtask/src/map_try/printer.rs +++ b/xtask/src/map_try/printer.rs @@ -25,12 +25,22 @@ pub(super) struct Printer { impl Printer { pub(super) fn section(&self, label: &str) -> Result<(u8, &str), &'static str> { - let mut matches = self.slots.iter().enumerate().flat_map(|(index, slot)| { - slot.sections.iter().filter_map(move |(id, name)| { - name.eq_ignore_ascii_case(label.trim()) - .then_some((index as u8, id.as_str())) - }) - }); + let (side, label) = match label.trim().split_once("::") { + Some(("left", label)) => (Some(0), label.trim()), + Some(("right", label)) => (Some(1), label.trim()), + _ => (None, label.trim()), + }; + let mut matches = self + .slots + .iter() + .enumerate() + .filter(|(i, _)| side.is_none_or(|side| *i == side)) + .flat_map(|(index, slot)| { + slot.sections.iter().filter_map(move |(id, name)| { + name.eq_ignore_ascii_case(label) + .then_some((index as u8, id.as_str())) + }) + }); let section = matches.next().ok_or("unknown label")?; if matches.next().is_some() { return Err("ambiguous label"); diff --git a/xtask/src/map_try/printer/tests.rs b/xtask/src/map_try/printer/tests.rs index 888f2b4ce..1e8124785 100644 --- a/xtask/src/map_try/printer/tests.rs +++ b/xtask/src/map_try/printer/tests.rs @@ -42,6 +42,27 @@ fn changed(slot: u8, place: Place, complete: bool) -> Change { } } +#[test] +fn comparison_sides_disambiguate_an_open_label() { + let mut printer = Printer::default(); + for (slot, id) in [(0, "first"), (1, "second")] { + let mut rows = vec![entry(id, "Pricing", "/pricing")]; + if slot == 1 { + rows.push(entry("docs", "Docs", "/docs")); + } + printer.lines( + &changed(slot, place("Site", "example.com", rows), true), + Duration::ZERO, + Counts::default(), + ); + } + assert_eq!(printer.section("Pricing"), Err("ambiguous label")); + assert_eq!(printer.section("left::Pricing"), Ok((0, "first"))); + assert_eq!(printer.section("right::Pricing"), Ok((1, "second"))); + assert_eq!(printer.section("Docs"), Ok((1, "docs"))); + assert_eq!(printer.section("left::Docs"), Err("unknown label")); +} + #[test] fn place_stream_golden() { let first = Change::FirstLayer { diff --git a/xtask/src/map_try/tests.rs b/xtask/src/map_try/tests.rs index 3009cd394..c0d4e4180 100644 --- a/xtask/src/map_try/tests.rs +++ b/xtask/src/map_try/tests.rs @@ -266,32 +266,44 @@ async fn an_interrupt_cancels_the_driver_and_prints_its_end() { } } - let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); - let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); - let io = Io { - results: Arc::new(results), - fetch: Arc::new(NoFetch), - memo: Arc::new(MemoryMemo::new()), - clock: Arc::new(SystemClock::new()), - }; - let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); - let (_route, direct) = watch::channel(PublicRoute::Direct); - let mut output = Vec::new(); - let outcome = stream( - &driver, - changes, - direct, - std::future::ready(Ok(())), - &mut output, - Vec::new(), - ) - .await; - assert_eq!(outcome, Ok(Outcome::Cancelled)); - assert_eq!(driver.counts(), Counts::default()); - let printed = std::str::from_utf8(&output).unwrap(); - assert_eq!(printed.lines().count(), 1); - assert!(printed.starts_with("Cancelled ")); - assert!(printed.ends_with("ms reads 0 data 0.0 MB renders wanted 0\n")); + for buffered in [false, true] { + let arguments = args(&["Stripe Pricing", "--site", "stripe.com"]); + let (request, results) = Options::parse(&arguments).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(NoFetch), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, mut changes) = Driver::start(request, io, &Handle::current()).unwrap(); + if buffered { + let (tx, rx) = tokio::sync::mpsc::channel(1); + tx.try_send(Change::End { + seq: 0, + outcome: Outcome::Done, + elapsed_ms: 0, + }) + .unwrap(); + changes = rx; + } + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::ready(Ok(())), + &mut output, + vec!["Pricing"], + ) + .await; + assert_eq!(outcome, Ok(Outcome::Cancelled)); + assert_eq!(driver.counts(), Counts::default()); + let printed = std::str::from_utf8(&output).unwrap(); + assert_eq!(printed.lines().count(), 1); + assert!(printed.starts_with("Cancelled ")); + assert!(printed.ends_with("ms reads 0 data 0.0 MB renders wanted 0\n")); + } } #[tokio::test] @@ -396,3 +408,57 @@ async fn labelled_opens_after_end_reprint_the_card_and_each_read_cost() { assert_eq!(opens.len(), 2); assert!(opens.iter().all(|line| line.contains("reads 1 bytes "))); } + +#[tokio::test] +async fn failed_opens_affect_status_and_remaining_opens_still_run() { + struct Fixture; + impl Fetcher for Fixture { + fn fetch(&self, request: FetchRequest) -> Reading<Result<FetchResult, Failure>> { + Box::pin(async move { + let body = match request.url.path() { + "/" => "<nav><a href='/docs'>Docs</a><a href='/pricing'>Pricing</a></nav>", + "/pricing" => "<h2 id='annual'>Annual</h2>", + "/docs" => return Err(Failure::Timeout), + _ => return Err(Failure::Missing), + }; + Ok(FetchResult { + final_url: request.url, + bytes: body.as_bytes().into(), + content_type: "text/html".into(), + charset: None, + truncated: false, + }) + }) + } + } + for labels in [ + vec!["Unknown", "Pricing"], + vec!["Docs", "Pricing"], + vec!["Pricing", "Pricing"], + ] { + let args = args(&["Stripe", "--site", "stripe.com"]); + let (request, results) = Options::parse(&args).unwrap().prepare().unwrap(); + let io = Io { + results: Arc::new(results), + fetch: Arc::new(Fixture), + memo: Arc::new(MemoryMemo::new()), + clock: Arc::new(SystemClock::new()), + }; + let (driver, changes) = Driver::start(request, io, &Handle::current()).unwrap(); + let (_route, direct) = watch::channel(PublicRoute::Direct); + let mut output = Vec::new(); + let outcome = stream( + &driver, + changes, + direct, + std::future::pending(), + &mut output, + labels, + ) + .await; + assert!(matches!(outcome, Err(_) | Ok(Outcome::Failed { .. }))); + let printed = String::from_utf8(output).unwrap(); + assert!(printed.contains("Opened read")); + assert!(printed.contains("refused")); + } +}