Merge pull request #3991 from dotCooCoo/fix/metadata-xmp-work-counts

metadata: the XMP scan tests count work instead of timing
This commit is contained in:
BFlat authored and GitHub committed 2026-11-30 01:08:38 +07:00
commit ddb3ab5872
4 files changed
+133 -36

No files matched your search

+42 -1
View File
@@ -419,6 +419,7 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut from = 0;
while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) {
searched(k + key.len() - from);
from = k + key.len();
// An attribute or an opening tag of exactly this name (not `</key>`, not `xkey`).
if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) {
@@ -443,13 +444,34 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> {
// attribute re-ran this full-suffix `find(close)` for every occurrence, which is
// quadratic in the packet size. A missing close means the value is unterminated, so
// no later value can parse either; stop scanning in that case.
let Some(len) = value.find(close) else { break };
let Some(len) = value.find(close) else {
// the search read the rest of the packet, and no key search follows
searched(value.len());
from = xmp.len();
break;
};
searched(len + close.len_utf8());
out.push((start, start + len));
from = start + len + close.len_utf8();
}
searched(xmp.len().saturating_sub(from));
out
}
// The bytes of the packet `xmp_values` searches for a key or a closing quote, on this thread.
#[cfg(test)]
std::thread_local! {
static SEARCHED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn searched(count: usize) {
#[cfg(test)]
SEARCHED.with(|searched| searched.set(searched.get().saturating_add(count)));
#[cfg(not(test))]
let _ = count;
}
/// An XMP rational (`300/1`) or plain number.
fn xmp_number(s: &str) -> Option<f64> {
let s = s.trim();
@@ -780,3 +802,22 @@ pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)>
#[cfg(test)]
mod complexity_tests;
#[cfg(test)]
mod xmp_scan_tests {
use super::*;
/// Property-like text repeated through a packet is searched once: each property's values are
/// found in one pass, not a search of the rest of the packet from every occurrence.
#[test]
fn repeated_property_text_is_searched_once_for_each_property() {
let decoys = " tiff:ResolutionUnit>".repeat(50_000);
for key in [XMP_X, XMP_Y, XMP_UNIT] {
SEARCHED.with(|searched| searched.set(0));
let _ = xmp_values(&decoys, key);
let read = SEARCHED.with(std::cell::Cell::get);
assert!(read <= decoys.len(), "{key}: {read} bytes searched in {}", decoys.len());
}
assert_eq!(xmp_resolution(&decoys), None);
}
}
+38 -14
View File
@@ -567,7 +567,7 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<
*truncated = true;
continue;
}
let key = format!("{prefix}{k}");
let key = build_path(format!("{prefix}{k}"));
if take_key_bytes(&key, budget, truncated) {
props.entry(key).or_default().push(v.clone());
}
@@ -577,6 +577,20 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<
}
}
// The bytes of every property path `collect_description` and `collect_property` build, on this
// thread.
#[cfg(test)]
std::thread_local! {
static PATH_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn build_path(path: String) -> String {
#[cfg(test)]
PATH_BYTES.with(|bytes| bytes.set(bytes.get().saturating_add(path.len())));
path
}
/// Charge one flattened key's length to the key budget; `false` when the budget is spent (the
/// property is then left out, like other elements a limit has cut) and the map is marked partial.
fn take_key_bytes(key: &str, budget: &mut usize, dropped: &mut bool) -> bool {
@@ -596,8 +610,11 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
*truncated = true;
return;
}
let key = format!("{prefix}{}", p.name);
// Every path built below is charged to the budget, a struct's prefix with its key: a path
// built and then refused would be copied again for each sibling while the budget stays put.
let path = || build_path(format!("{prefix}{}", p.name));
if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) {
let key = path();
let mut items: Vec<(bool, String)> = arr
.children
.iter()
@@ -614,32 +631,39 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
}
return;
}
let struct_prefix = format!("{key}/");
// a struct's path is charged like a key before its fields copy it: that work too is bounded
// by the budget, kept fields or not
let is_struct = p.attr("rdf:parseType") == Some("Resource") || p.children.iter().any(|c| c.name == "rdf:Description");
if is_struct && !take_key_bytes(&key, budget, truncated) {
return;
}
if p.attr("rdf:parseType") == Some("Resource") {
// a Resource struct carries fields as attributes as well as child elements, like a nested Description
collect_description(p, &struct_prefix, props, budget, truncated);
return;
}
if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
collect_description(d, &struct_prefix, props, budget, truncated);
if is_struct {
let key = path();
if !take_key_bytes(&key, budget, truncated) {
return;
}
let struct_prefix = build_path(format!("{key}/"));
if p.attr("rdf:parseType") == Some("Resource") {
// a Resource struct carries fields as attributes as well as child elements, like a nested Description
collect_description(p, &struct_prefix, props, budget, truncated);
} else if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
collect_description(d, &struct_prefix, props, budget, truncated);
}
return;
}
let field_attrs: Vec<&(String, String)> = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect();
if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() {
for (k, v) in field_attrs {
let full = format!("{struct_prefix}{k}");
// the budget is checked before the path is built, as for a description's attributes
if *budget < prefix.len().saturating_add(p.name.len()).saturating_add(1).saturating_add(k.len()) {
*truncated = true;
continue;
}
let full = build_path(format!("{prefix}{}/{k}", p.name));
if take_key_bytes(&full, budget, truncated) {
props.entry(full).or_default().push(v.clone());
}
}
return;
}
let key = path();
let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string());
if take_key_bytes(&key, budget, truncated) {
props.entry(key).or_default().push(v);
+32 -2
View File
@@ -886,9 +886,39 @@ fn paths_are_not_built_past_the_key_budget() {
doc.push_str(&format!("</lc:{level}>"));
}
doc.push_str("</rdf:Description></rdf:RDF></x:xmpmeta>");
let t = std::time::Instant::now();
PATH_BYTES.with(|bytes| bytes.set(0));
let _ = parse_xmp(&doc);
assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed());
// Each path built is charged to the budget, or is a charged struct path and its "/".
let built = PATH_BYTES.with(std::cell::Cell::get);
let structs = 100_004;
assert!(built <= 2 * MAX_KEY_BYTES + structs, "{built} bytes of paths built");
}
/// A field attribute whose path no longer fits the budget, while its element's own path still
/// does, left the budget as it was: each of its siblings then copied the long ancestor path again.
#[test]
fn field_paths_past_the_key_budget_are_not_built_for_each_sibling() {
// One struct of n letters, then a field that spends the budget down to n + 10 bytes: room for
// the path of `lc:e` under the struct (n + 8 bytes) but not for that of its field `lc:f`
// (n + 13).
let n = 200_000;
let level = "n".repeat(n);
let drain = "a".repeat(MAX_KEY_BYTES - 3 * n - 25);
let mut doc = format!(
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:lc=\"{}\"><rdf:RDF><rdf:Description><lc:{level} rdf:parseType=\"Resource\"><lc:d lc:{drain}=\"1\"/>",
LC.uri
);
for _ in 0..20_000 {
doc.push_str("<lc:e lc:f=\"1\"/>");
}
doc.push_str(&format!("</lc:{level}></rdf:Description></rdf:RDF></x:xmpmeta>"));
PATH_BYTES.with(|bytes| bytes.set(0));
let data = parse_xmp(&doc).unwrap_or_else(|e| panic!("{e}"));
assert!(data.properties_truncated);
assert!(data.properties.contains_key(&format!("lc:{level}/lc:d/lc:{drain}")));
assert!(!data.properties.contains_key(&format!("lc:{level}/lc:e/lc:f")));
let built = PATH_BYTES.with(std::cell::Cell::get);
assert!(built <= 2 * MAX_KEY_BYTES, "{built} bytes of paths built");
}
/// The caller's namespace is declared where the read-only `crs` sits in the table, is known to the
+21 -19
View File
@@ -97,6 +97,12 @@ fn pos(r: &quick_xml::Reader<&[u8]>) -> usize {
usize::try_from(r.buffer_position()).unwrap_or(usize::MAX)
}
// Each attribute name `scan` looks up in its set of the tag's names, on this thread.
#[cfg(test)]
std::thread_local! {
static NAME_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Locate the descriptions, their top-level properties and `</rdf:RDF>` in a packet.
fn scan(s: &str, extra: &[XmpNamespace]) -> Result<Scan, XmpError> {
let mut reader = quick_xml::Reader::from_reader(s.as_bytes());
@@ -124,6 +130,8 @@ fn scan(s: &str, extra: &[XmpNamespace]) -> Result<Scan, XmpError> {
for a in e.attributes().with_checks(false) {
let a = a.map_err(|e| XmpError::Xml(e.to_string()))?;
let k = String::from_utf8_lossy(a.key.as_ref()).into_owned();
#[cfg(test)]
NAME_CHECKS.with(|checks| checks.set(checks.get().saturating_add(1)));
if !seen.insert(k.clone()) {
return Err(XmpError::Xml(format!("repeated attribute {k}")));
}
@@ -490,11 +498,10 @@ mod tests {
#[test]
fn many_attributes_scan_in_linear_time() {
// quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on
// one description took over 20 s to scan, about 30 ms with the set. Four times the attributes must take
// about four times as long, not sixteen. A ratio of the fastest runs holds on a loaded machine, where
// a fixed bound does not.
let packet = |n: usize| {
// A duplicate-name check that compares each attribute with all earlier ones took over 20 s for
// 200 000 attributes on one description. The scan looks each name up once in a set of the tag's
// names, and leaves quick-xml's own check off.
let packet = |n: usize, repeat: &str| {
let mut s = String::from(
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:foo=\"http://example.com/foo/\"",
@@ -502,25 +509,20 @@ mod tests {
for i in 0..n {
s.push_str(&format!(" foo:a{i}=\"{i}\""));
}
s.push_str(repeat);
s.push_str("/></rdf:RDF></x:xmpmeta>");
s
};
let run = |s: &str, n: usize| {
let t = std::time::Instant::now();
let found = scan(s, &[]).unwrap();
let took = t.elapsed();
for n in [20_000, 80_000] {
NAME_CHECKS.with(|checks| checks.set(0));
let found = scan(&packet(n, ""), &[]).unwrap();
assert_eq!(found.descs[0].attrs.len(), n + 2, "every attribute is read");
took
};
let (n, small_packet, large_packet) = (20_000, packet(20_000), packet(80_000));
// interleaved, so a burst of load slows both sizes rather than one; the fastest run of each counts
let (mut small, mut large) = (std::time::Duration::MAX, std::time::Duration::MAX);
for _ in 0..3 {
small = small.min(run(&small_packet, n));
large = large.min(run(&large_packet, 4 * n));
// one lookup for each attribute of the three tags: xmlns:x, xmlns:rdf, rdf:about, xmlns:foo and the n
assert_eq!(NAME_CHECKS.with(std::cell::Cell::get), n + 4);
// the set, not quick-xml, finds a name given twice
let repeated = scan(&packet(n, " foo:a0=\"again\""), &[]).map(|_| ()).unwrap_err();
assert_eq!(repeated, XmpError::Xml("repeated attribute foo:a0".into()));
}
let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-6);
assert!(ratio < 10.0, "4x the attributes took {ratio:.1}x as long ({small:?}, then {large:?})");
}
#[test]