Skip to main content

latexml_post/
object_db.rs

1//! Object database for cross-document data sharing.
2//!
3//! Port of `LaTeXML::Util::ObjectDB` + `ObjectDB::Entry`.
4//! A key-value store used by Scan, CrossRef, MakeIndex, and MakeBibliography
5//! to share structural information across documents and processing phases.
6//!
7//! Keys follow conventions:
8//! - `ID:<xml:id>` — element data (type, parent, children, labels, location, etc.)
9//! - `LABEL:<label>` — label → ID mapping
10//! - `DOCUMENT:<path>` — document location → root ID mapping
11//! - `SITE_ROOT` — root document of the site
12//! - `BIBLABEL:<list>:<key>` — bibliography key → item ID
13//! - `GLOSSARY:<list>:<key>` — glossary entries
14//! - `INDEX:<phrase1>:<phrase2>:...` — index entries (`INDEX@<list>:…` outside the default `idx` list)
15//! - `DECLARATION:(global|local):<name>` — declared symbols
16//! - `NOTATION:<name>` — notation entries
17
18use libxml::tree::Node;
19use rustc_hash::{FxHashMap as HashMap, FxHashSet};
20
21/// A single entry in the ObjectDB.
22///
23/// Port of `LaTeXML::Util::ObjectDB::Entry`.
24#[derive(Debug, Clone)]
25pub struct Entry {
26  /// The key this entry is stored under.
27  pub key:       String,
28  /// Attribute-value pairs.
29  values:        HashMap<String, Value>,
30  /// Per list attribute, the `Display` strings of its items as `push_new` left them: Perl's
31  /// `grep { $_ eq $value } @$list` as a set lookup instead of a scan that formats every item
32  /// (1702.06564: one parent with thousands of children spent 247 of 323 s in that scan). An
33  /// attribute's set is dropped whenever another method writes that attribute, and rebuilt from
34  /// the list on the next `push_new`.
35  push_new_seen: HashMap<String, FxHashSet<String>>,
36}
37
38/// A value stored in an Entry.
39///
40/// Values can be scalars, lists, nested hashes, or XML node references.
41#[derive(Debug, Clone)]
42pub enum Value {
43  /// A simple string value.
44  String(String),
45  /// An integer value.
46  Int(i64),
47  /// A boolean value.
48  Bool(bool),
49  /// A list of values.
50  List(Vec<Value>),
51  /// A nested hash (for associations like referrers).
52  Hash(HashMap<String, Value>),
53  /// An XML node (cloned from the document).
54  Xml(Node),
55  /// Null/undefined.
56  Null,
57}
58
59impl Value {
60  /// Get as string, if possible.
61  pub fn as_str(&self) -> Option<&str> {
62    match self {
63      Value::String(s) => Some(s),
64      _ => None,
65    }
66  }
67
68  /// Get as string, converting if needed.
69  pub fn as_string(&self) -> String {
70    match self {
71      Value::String(s) => s.clone(),
72      Value::Int(n) => n.to_string(),
73      Value::Bool(b) => b.to_string(),
74      Value::Xml(node) => node.get_content(),
75      Value::Null => String::new(),
76      _ => String::new(),
77    }
78  }
79
80  /// Check if the value is truthy (non-null, non-empty).
81  pub fn is_truthy(&self) -> bool {
82    match self {
83      Value::Null => false,
84      Value::String(s) => !s.is_empty(),
85      Value::Bool(b) => *b,
86      Value::List(v) => !v.is_empty(),
87      Value::Hash(h) => !h.is_empty(),
88      _ => true,
89    }
90  }
91}
92
93impl From<&str> for Value {
94  fn from(s: &str) -> Self { Value::String(s.to_string()) }
95}
96
97impl From<String> for Value {
98  fn from(s: String) -> Self { Value::String(s) }
99}
100
101impl std::fmt::Display for Value {
102  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103    match self {
104      Value::String(s) => write!(f, "{}", s),
105      Value::Int(n) => write!(f, "{}", n),
106      Value::Bool(b) => write!(f, "{}", b),
107      Value::Null => Ok(()),
108      Value::Xml(node) => write!(f, "{}", node.get_content()),
109      Value::List(_) | Value::Hash(_) => Ok(()),
110    }
111  }
112}
113
114// NOTE deliberately NO `impl From<Node> for Value`: a bare node handle points
115// into whichever document it came from, and storing one couples the DB's
116// validity to that document's lifetime (fatal under streaming, where page DOMs
117// are freed as soon as they are processed). Nodes enter the DB only through
118// `ObjectDB::adopt_xml`, which copies them into DB-owned storage.
119
120impl From<bool> for Value {
121  fn from(b: bool) -> Self { Value::Bool(b) }
122}
123
124impl From<Vec<String>> for Value {
125  fn from(v: Vec<String>) -> Self { Value::List(v.into_iter().map(Value::String).collect()) }
126}
127
128impl Entry {
129  /// Create a new entry with the given key.
130  pub fn new(key: &str) -> Self {
131    Entry {
132      key:           key.to_string(),
133      values:        HashMap::default(),
134      push_new_seen: HashMap::default(),
135    }
136  }
137
138  /// Get the entry's key.
139  pub fn get_key(&self) -> &str { &self.key }
140
141  /// Check if the entry has a value for the given attribute.
142  pub fn has_value(&self, attr: &str) -> bool { self.values.contains_key(attr) }
143
144  /// The entry's attribute names, in no particular order.
145  pub fn attributes(&self) -> impl Iterator<Item = &str> { self.values.keys().map(String::as_str) }
146
147  /// Get a value by attribute name.
148  pub fn get_value(&self, attr: &str) -> Option<&Value> { self.values.get(attr) }
149
150  /// Get a string value by attribute name.
151  pub fn get_string(&self, attr: &str) -> Option<&str> {
152    self.values.get(attr).and_then(|v| v.as_str())
153  }
154
155  /// Get an XML node value by attribute name.
156  pub fn get_xml(&self, attr: &str) -> Option<&Node> {
157    match self.values.get(attr) {
158      Some(Value::Xml(n)) => Some(n),
159      _ => None,
160    }
161  }
162
163  /// Get a children list (as string IDs).
164  pub fn get_children(&self) -> Vec<String> {
165    match self.values.get("children") {
166      Some(Value::List(items)) => items
167        .iter()
168        .filter_map(|v| v.as_str().map(String::from))
169        .collect(),
170      _ => vec![],
171    }
172  }
173
174  /// Set multiple attribute-value pairs.
175  ///
176  /// Port of `Entry::setValues`.
177  pub fn set_values(&mut self, pairs: Vec<(&str, Value)>) {
178    for (key, value) in pairs {
179      self.push_new_seen.remove(key);
180      match value {
181        Value::Null => {
182          self.values.remove(key);
183        },
184        _ => {
185          self.values.insert(key.to_string(), value);
186        },
187      }
188    }
189  }
190
191  /// Set a single value.
192  pub fn set_value(&mut self, attr: &str, value: Value) {
193    self.push_new_seen.remove(attr);
194    match value {
195      Value::Null => {
196        self.values.remove(attr);
197      },
198      _ => {
199        self.values.insert(attr.to_string(), value);
200      },
201    }
202  }
203
204  /// Push values onto a list attribute.
205  ///
206  /// Port of `Entry::pushValues`.
207  pub fn push_values(&mut self, attr: &str, values: Vec<Value>) {
208    self.push_new_seen.remove(attr);
209    let list = self
210      .values
211      .entry(attr.to_string())
212      .or_insert_with(|| Value::List(Vec::new()));
213    if let Value::List(items) = list {
214      for v in values {
215        items.push(v);
216      }
217    }
218  }
219
220  /// Push values onto a list attribute, skipping duplicates.
221  ///
222  /// Port of `Entry::pushNew`.
223  pub fn push_new(&mut self, attr: &str, values: Vec<Value>) {
224    let list = self
225      .values
226      .entry(attr.to_string())
227      .or_insert_with(|| Value::List(Vec::new()));
228    if let Value::List(items) = list {
229      let seen = self
230        .push_new_seen
231        .entry(attr.to_string())
232        .or_insert_with(|| items.iter().map(Value::to_string).collect());
233      for v in values {
234        if seen.insert(v.to_string()) {
235          items.push(v);
236        }
237      }
238    }
239  }
240
241  /// Create nested hash association.
242  ///
243  /// Port of `Entry::noteAssociation`.
244  /// `noteAssociation("referrers", "parent_id")` creates `{referrers => {parent_id => 1}}`
245  pub fn note_association(&mut self, keys: &[&str]) {
246    if keys.is_empty() {
247      return;
248    }
249    self.push_new_seen.remove(keys[0]);
250    if keys.len() == 1 {
251      self.values.insert(keys[0].to_string(), Value::Bool(true));
252      return;
253    }
254
255    // Navigate/create nested hash structure
256    let first = keys[0];
257    let rest = &keys[1..];
258
259    let hash = self
260      .values
261      .entry(first.to_string())
262      .or_insert_with(|| Value::Hash(HashMap::default()));
263
264    if let Value::Hash(h) = hash {
265      let mut current = h;
266      for (i, &key) in rest.iter().enumerate() {
267        if i == rest.len() - 1 {
268          // Last key: set to true
269          current.insert(key.to_string(), Value::Bool(true));
270        } else {
271          // Intermediate: navigate/create hash
272          let entry = current
273            .entry(key.to_string())
274            .or_insert_with(|| Value::Hash(HashMap::default()));
275          if let Value::Hash(inner) = entry {
276            current = inner;
277          } else {
278            break;
279          }
280        }
281      }
282    }
283  }
284}
285
286/// The Object Database.
287///
288/// Port of `LaTeXML::Util::ObjectDB`.
289/// In-memory key-value store. For now, no external DB persistence
290/// (the Perl version uses Berkeley DB via DB_File).
291pub struct ObjectDB {
292  /// In-memory entry storage.
293  objects:    HashMap<String, Entry>,
294  /// The ONE document owning every [`Value::Xml`] node the DB stores. A
295  /// stored node used to be a handle into the scanned page's own DOM, which
296  /// made the DB's lifetime silently depend on every page document staying
297  /// resident — a use-after-free the moment a streaming pipeline frees a
298  /// processed page. [`ObjectDB::adopt_xml`] deep-copies into this document
299  /// instead, so stored XML lives exactly as long as the DB, whatever happens
300  /// to the source.
301  ///
302  /// **One document, not one per value.** The first cut retained a whole fresh
303  /// `xmlDoc` per adopted node, and Scan adopts a `title` and `toctitle` for
304  /// every object it registers: on a 614 MB core XML (200,403 objects) that is
305  /// tens of thousands of documents — each with its own dictionary and
306  /// structure — to hold a few MB of title markup. Measured, that regressed
307  /// the split post-processing of that input from ~21 GB peak (completing over
308  /// 40,201 pages) to **67 GB and a memory-ceiling kill with zero pages
309  /// written**. Titles really are small; `xmlDoc`s are not.
310  xml_holder: Option<libxml::tree::Document>,
311  /// The attached external store, when this DB was opened via
312  /// [`ObjectDB::attach`] (Perl `--dbfile`); `None` for purely in-memory use.
313  external:   Option<ExternalDb>,
314}
315
316impl ObjectDB {
317  /// Create a new empty ObjectDB.
318  pub fn new() -> Self {
319    ObjectDB {
320      objects:    HashMap::default(),
321      xml_holder: None,
322      external:   None,
323    }
324  }
325
326  /// The DB's holding document, created on first adoption (so a DB that
327  /// stores no XML allocates none), with a root element to parent the copies
328  /// under — an unparented node would not be reached by the holder's own
329  /// `xmlFreeDoc` either.
330  fn xml_holder_mut(&mut self) -> Option<&mut libxml::tree::Document> {
331    if self.xml_holder.is_none() {
332      let mut doc = libxml::tree::Document::new().ok()?;
333      let root = Node::new("_objectdb_", None, &doc).ok()?;
334      doc.set_root_element(&root);
335      self.xml_holder = Some(doc);
336    }
337    self.xml_holder.as_mut()
338  }
339
340  /// Adopt an XML node for storage: deep-copy it into a document the DB owns
341  /// and return the [`Value::Xml`] wrapping the copy. This is the ONLY way a
342  /// node enters the DB (`From<Node> for Value` was removed on purpose), so
343  /// no stored value can dangle into a page document that was freed.
344  ///
345  /// Two hops, because the fork's copy primitives pull in opposite
346  /// directions: `dup_node_into_new_doc` copies from a LINKED source but only
347  /// into a fresh document, while `import_node` copies into an EXISTING
348  /// document but rejects a linked source. So: copy out to a scratch
349  /// document, detach, copy into the holder, and free the scratch copy —
350  /// an unlinked doc-owned node is freed by nobody (the rust-libxml `Linkage`
351  /// rule behind `Node::free_subtree`), so dropping the scratch document
352  /// alone would leak it. A one-hop version wants a fork method that copies
353  /// from a linked source into an existing document; that is a publish + dep
354  /// bump, and this is a regression fix.
355  ///
356  /// Returns `None` when the copy fails; callers should degrade to a string
357  /// form rather than store nothing, and never crash.
358  pub fn adopt_xml(&mut self, node: &Node) -> Option<Value> {
359    let scratch = libxml::tree::Document::dup_node_into_new_doc(node).ok()?;
360    let mut extracted = scratch.get_root_element()?;
361    extracted.unlink_node();
362    let holder = self.xml_holder_mut()?;
363    let mut adopted = holder.import_node(&mut extracted).ok()?;
364    let mut root = holder.get_root_element()?;
365    root.add_child(&mut adopted).ok()?;
366    extracted.free_subtree();
367    Some(Value::Xml(adopted))
368  }
369
370  /// Look up an entry by key.
371  ///
372  /// Port of `ObjectDB::lookup`.
373  pub fn lookup(&self, key: &str) -> Option<&Entry> { self.objects.get(key) }
374
375  /// Look up an entry by key (mutable).
376  pub fn lookup_mut(&mut self, key: &str) -> Option<&mut Entry> { self.objects.get_mut(key) }
377
378  /// Register an entry: create if new, or return existing.
379  /// Sets the given properties on the entry.
380  ///
381  /// Port of `ObjectDB::register`.
382  pub fn register(&mut self, key: &str, props: Vec<(&str, Value)>) -> &mut Entry {
383    let entry = self
384      .objects
385      .entry(key.to_string())
386      .or_insert_with(|| Entry::new(key));
387    if !props.is_empty() {
388      entry.set_values(props);
389    }
390    self.objects.get_mut(key).unwrap()
391  }
392
393  /// Remove an entry.
394  ///
395  /// Port of `ObjectDB::unregister`.
396  pub fn unregister(&mut self, key: &str) {
397    self.objects.remove(key);
398    // Perl ObjectDB.pm:183: "Must remove external entry (if any) as well,
399    // else it'll get pulled back in!" — without this the key resurrects on
400    // the next attach (review 2026-08-03 finding #1).
401    if let Some(external) = &mut self.external {
402      external.baseline.remove(key);
403      if !external.readonly {
404        let _ = external
405          .conn
406          .execute("DELETE FROM entries WHERE key = ?1", rusqlite::params![key]);
407      }
408    }
409  }
410
411  /// Get all keys, sorted.
412  ///
413  /// Port of `ObjectDB::getKeys`.
414  pub fn get_keys(&self) -> Vec<&String> {
415    let mut keys: Vec<_> = self.objects.keys().collect();
416    keys.sort();
417    keys
418  }
419
420  /// Number of registered entries. O(1); avoids `get_keys().len()`'s
421  /// sort + allocation when only the count is needed.
422  pub fn len(&self) -> usize { self.objects.len() }
423
424  /// True when no entries are registered.
425  pub fn is_empty(&self) -> bool { self.objects.is_empty() }
426
427  /// Iterate keys in arbitrary order without allocating/sorting. Use when
428  /// the traversal order does not matter (e.g. per-node fill-ins).
429  pub fn keys_iter(&self) -> impl Iterator<Item = &String> { self.objects.keys() }
430
431  /// Return a status string.
432  ///
433  /// Port of `ObjectDB::status`.
434  pub fn status(&self) -> String { format!("{} objects", self.objects.len()) }
435}
436
437impl Default for ObjectDB {
438  fn default() -> Self { Self::new() }
439}
440
441// ======================================================================
442// Perl `--dbfile` parity: SQLite persistence (design 2026-08-02, docs/
443// archive/STREAMING_POST_DESIGN_2026-07-06.md §6). Faithful to the
444// OBSERVABLE contract of `LaTeXML::Util::ObjectDB` (ObjectDB.pm):
445// `new(dbfile)` attaches a keyed store (creating it unless readonly),
446// `lookup`/`getKeys` see the union of stored + registered entries, and
447// `finish` writes back ONLY entries that differ from what is stored
448// (ObjectDB.pm `sub finish`: `next if compare_hash($row, thaw($stored))`),
449// then detaches. One deliberate internal divergence: Perl thaws entries
450// lazily per `lookup` because Berkeley DB reads are cheap point-lookups;
451// we load eagerly at attach — SQLite reads the whole table in one scan,
452// every consumer (CrossRef's nav/TOC walks) touches most keys anyway, and
453// eager load keeps `lookup(&self)` free of interior mutability.
454//
455// Storage: `entries(key TEXT PRIMARY KEY, props TEXT)` with the property
456// map JSON-encoded (Perl uses Storable `nfreeze`; JSON keeps the artifact
457// `sqlite3`-CLI-inspectable, which Storable never was), plus a `meta`
458// table and `PRAGMA user_version` for staleness: a format-version mismatch
459// refuses the file rather than limping (caller decides to rebuild).
460// `Value::Xml` round-trips as serialized XML, re-adopted into the reader's
461// own holder document via the same `adopt_xml` copy discipline Scan uses.
462
463/// Bump when the on-disk encoding changes shape. Mismatched files are
464/// refused at `attach` — never silently reinterpreted.
465pub const DBFILE_FORMAT_VERSION: i64 = 1;
466
467/// The attached external store: connection plus the as-stored JSON of every
468/// loaded entry, so `finish` can implement Perl's changed-only write-back
469/// by string comparison instead of re-reading the table.
470struct ExternalDb {
471  conn:     rusqlite::Connection,
472  readonly: bool,
473  baseline: HashMap<String, String>,
474}
475
476/// Options for [`ObjectDB::attach`], mirroring Perl `ObjectDB::new`'s
477/// `dbfile`/`clean`/`readonly` knobs.
478#[derive(Default)]
479pub struct DbAttachOptions {
480  /// Delete any existing file first (Perl `clean => 1`).
481  pub clean:    bool,
482  /// Open for reading only; `finish` will not write (Perl `readonly`).
483  pub readonly: bool,
484}
485
486impl ObjectDB {
487  /// Attach (and load) an external SQLite object store — Perl
488  /// `ObjectDB->new(dbfile => …)`.
489  pub fn attach(dbfile: &std::path::Path, options: DbAttachOptions) -> Result<Self, String> {
490    if options.clean && options.readonly {
491      return Err("dbfile: clean requires write access (Perl always opens O_RDWR)".to_string());
492    }
493    if options.clean && dbfile.exists() {
494      latexml_core::common::error::emit_warn(
495        "expected",
496        "dbfile",
497        &format!("Removing Object database file {}!", dbfile.display()),
498      );
499      std::fs::remove_file(dbfile)
500        .map_err(|e| format!("cannot remove {}: {e}", dbfile.display()))?;
501    }
502    let conn = if options.readonly {
503      rusqlite::Connection::open_with_flags(dbfile, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
504    } else {
505      rusqlite::Connection::open(dbfile)
506    }
507    .map_err(|e| format!("cannot attach DB {}: {e}", dbfile.display()))?;
508    // Concurrent workers are this layer's purpose: WAL lets N readers overlap
509    // one writer, and a busy timeout rides out a writer's commit instead of
510    // failing mid-transaction with SQLITE_BUSY.
511    if !options.readonly {
512      let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()));
513    }
514    conn
515      .busy_timeout(std::time::Duration::from_secs(10))
516      .map_err(|e| format!("cannot set busy_timeout: {e}"))?;
517
518    let version: i64 = conn
519      .query_row("PRAGMA user_version", [], |r| r.get(0))
520      .map_err(|e| format!("cannot read user_version: {e}"))?;
521    let entries_table: bool = conn
522      .query_row(
523        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='entries'",
524        [],
525        |r| r.get::<_, i64>(0),
526      )
527      .map(|n| n > 0)
528      .unwrap_or(false);
529    let any_table: bool = conn
530      .query_row(
531        "SELECT COUNT(*) FROM sqlite_master WHERE type='table'",
532        [],
533        |r| r.get::<_, i64>(0),
534      )
535      .map(|n| n > 0)
536      .unwrap_or(false);
537    if version == 0 && any_table && !entries_table {
538      return Err(format!(
539        "{} is a SQLite file but not an ObjectDB (no entries table) — refusing to adopt it",
540        dbfile.display()
541      ));
542    }
543    if version == 0 && !options.readonly {
544      conn
545        .execute_batch(&format!(
546          "PRAGMA user_version = {DBFILE_FORMAT_VERSION};
547           CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
548           CREATE TABLE IF NOT EXISTS entries(key TEXT PRIMARY KEY, props TEXT NOT NULL);"
549        ))
550        .map_err(|e| format!("cannot initialize {}: {e}", dbfile.display()))?;
551    } else if version != 0 && version != DBFILE_FORMAT_VERSION {
552      return Err(format!(
553        "object database {} has format version {version}, this binary reads {DBFILE_FORMAT_VERSION} — rebuild it (--dbfile with a clean run)",
554        dbfile.display()
555      ));
556    }
557
558    let mut db = ObjectDB::new();
559    let mut baseline = HashMap::default();
560    // A fresh readonly file has no tables; treat as empty rather than erroring.
561    let table_exists: bool = conn
562      .query_row(
563        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='entries'",
564        [],
565        |r| r.get::<_, i64>(0),
566      )
567      .map(|n| n > 0)
568      .unwrap_or(false);
569    if table_exists {
570      let mut stmt = conn
571        .prepare("SELECT key, props FROM entries")
572        .map_err(|e| format!("cannot read entries: {e}"))?;
573      let rows = stmt
574        .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
575        .map_err(|e| format!("cannot scan entries: {e}"))?;
576      for row in rows {
577        let (key, props) = row.map_err(|e| format!("bad row: {e}"))?;
578        // One bad row must not poison the whole file (review finding #4):
579        // warn with the key and skip; the on-disk row stays as it was.
580        match db.decode_entry(&key, &props) {
581          // A readonly attach never writes back, so it keeps no as-stored copy: a render worker's db
582          // would otherwise hold its JSON twice (Nasser k2400, 45 MB db).
583          Ok(entry) if options.readonly => {
584            db.objects.insert(key, entry);
585          },
586          Ok(entry) => {
587            db.objects.insert(key.clone(), entry);
588            baseline.insert(key, props);
589          },
590          Err(e) => latexml_core::common::error::emit_warn("malformed", "dbfile_entry", &e),
591        }
592      }
593      drop(stmt);
594    }
595    db.external = Some(ExternalDb {
596      conn,
597      readonly: options.readonly,
598      baseline,
599    });
600    Ok(db)
601  }
602
603  /// Persist this IN-MEMORY db as a fresh dbfile (the parallel-render
604  /// handoff: the parent scans/sweeps in memory, saves once, and each worker
605  /// attaches the file readonly). Unlike [`ObjectDB::finish`] this does not
606  /// consume the attachment state — the db stays usable in memory, and any
607  /// existing file at `path` is replaced.
608  pub fn save_as(&self, path: &std::path::Path) -> Result<usize, String> {
609    if path.exists() {
610      std::fs::remove_file(path).map_err(|e| format!("cannot replace {}: {e}", path.display()))?;
611    }
612    let mut conn = rusqlite::Connection::open(path)
613      .map_err(|e| format!("cannot create dbfile {}: {e}", path.display()))?;
614    let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()));
615    conn
616      .execute_batch(&format!(
617        "PRAGMA user_version = {DBFILE_FORMAT_VERSION};
618         CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
619         CREATE TABLE entries(key TEXT PRIMARY KEY, props TEXT NOT NULL);"
620      ))
621      .map_err(|e| format!("cannot initialize {}: {e}", path.display()))?;
622    let tx = conn
623      .transaction()
624      .map_err(|e| format!("cannot begin save_as transaction: {e}"))?;
625    let mut stored = 0usize;
626    {
627      let mut stmt = tx
628        .prepare("INSERT INTO entries(key, props) VALUES (?1, ?2)")
629        .map_err(|e| format!("cannot prepare save_as insert: {e}"))?;
630      let mut buf = Vec::with_capacity(512);
631      for (key, entry) in &self.objects {
632        buf.clear();
633        write_entry_json(&mut buf, self.xml_holder.as_ref(), entry)
634          .map_err(|e| format!("cannot encode entry {key}: {e}"))?;
635        let props =
636          std::str::from_utf8(&buf).map_err(|e| format!("encoded entry {key} not utf-8: {e}"))?;
637        stmt
638          .execute(rusqlite::params![key, props])
639          .map_err(|e| format!("cannot store entry {key}: {e}"))?;
640        stored += 1;
641      }
642    }
643    tx.execute(
644      "INSERT INTO meta(key, value) VALUES ('latexml_version', ?1)",
645      rusqlite::params![env!("CARGO_PKG_VERSION")],
646    )
647    .map_err(|e| format!("cannot store meta: {e}"))?;
648    tx.commit()
649      .map_err(|e| format!("cannot commit save_as: {e}"))?;
650    Ok(stored)
651  }
652
653  /// Write back changed entries and detach — Perl `ObjectDB::finish`.
654  /// Returns how many entries were stored. Idempotent: a second call (or a
655  /// call on a never-attached DB) stores nothing.
656  pub fn finish(&mut self) -> Result<usize, String> {
657    let Some(external) = self.external.take() else {
658      return Ok(0);
659    };
660    if external.readonly {
661      return Ok(0);
662    }
663    // Stream: encode → compare → insert per entry inside one transaction, so
664    // peak memory is ONE encoded entry, not the whole changed set (review
665    // finding #5 — the baseline copy itself is dropped with `external` at
666    // the end of this function).
667    let mut stored = 0usize;
668    let mut conn = external.conn;
669    let tx = conn
670      .transaction()
671      .map_err(|e| format!("cannot begin dbfile transaction: {e}"))?;
672    {
673      let mut stmt = tx
674        .prepare(
675          "INSERT INTO entries(key, props) VALUES (?1, ?2)
676           ON CONFLICT(key) DO UPDATE SET props = excluded.props",
677        )
678        .map_err(|e| format!("cannot prepare dbfile upsert: {e}"))?;
679      for (key, entry) in &self.objects {
680        let props = {
681          let map: serde_json::Map<String, serde_json::Value> = entry
682            .values
683            .iter()
684            .map(|(k, v)| (k.clone(), value_to_json_with(self.xml_holder.as_ref(), v)))
685            .collect();
686          serde_json::Value::Object(map).to_string()
687        };
688        if external.baseline.get(key) == Some(&props) {
689          continue;
690        }
691        stmt
692          .execute(rusqlite::params![key, props])
693          .map_err(|e| format!("cannot store entry {key}: {e}"))?;
694        stored += 1;
695      }
696    }
697    tx.execute(
698      "INSERT INTO meta(key, value) VALUES ('latexml_version', ?1)
699       ON CONFLICT(key) DO UPDATE SET value = excluded.value",
700      rusqlite::params![env!("CARGO_PKG_VERSION")],
701    )
702    .map_err(|e| format!("cannot store meta: {e}"))?;
703    tx.commit()
704      .map_err(|e| format!("cannot commit dbfile: {e}"))?;
705    Ok(stored)
706  }
707
708  /// Tagged, self-describing encoding — one-key objects so `Hash` values
709  /// can never be confused with the wrapper: `{"s":…}` string, `{"i":…}`
710  /// int, `{"b":…}` bool, `{"l":[…]}` list, `{"h":{…}}` hash, `{"x":"<…>"}`
711  /// serialized XML, JSON `null` for `Null`.
712  fn value_to_json(&self, value: &Value) -> serde_json::Value {
713    value_to_json_with(self.xml_holder.as_ref(), value)
714  }
715
716  fn decode_entry(&mut self, key: &str, props: &str) -> Result<Entry, String> {
717    let parsed: serde_json::Value =
718      serde_json::from_str(props).map_err(|e| format!("entry {key} is not valid JSON: {e}"))?;
719    let serde_json::Value::Object(map) = parsed else {
720      return Err(format!("entry {key} is not a JSON object"));
721    };
722    let mut entry = Entry::new(key);
723    for (attr, jv) in map {
724      let value = self.json_to_value(&jv, key)?;
725      entry.set_value(&attr, value);
726    }
727    Ok(entry)
728  }
729
730  fn json_to_value(&mut self, jv: &serde_json::Value, key: &str) -> Result<Value, String> {
731    use serde_json::Value as J;
732    let J::Object(o) = jv else {
733      return match jv {
734        J::Null => Ok(Value::Null),
735        other => Err(format!("entry {key}: unexpected bare JSON value {other}")),
736      };
737    };
738    if let Some((tag, inner)) = o.iter().next()
739      && o.len() == 1
740    {
741      return match (tag.as_str(), inner) {
742        ("s", J::String(s)) => Ok(Value::String(s.clone())),
743        ("i", J::Number(n)) => n
744          .as_i64()
745          .map(Value::Int)
746          .ok_or_else(|| format!("entry {key}: non-integer numeric value {n}")),
747        ("b", J::Bool(b)) => Ok(Value::Bool(*b)),
748        ("l", J::Array(items)) => Ok(Value::List(
749          items
750            .iter()
751            .map(|v| self.json_to_value(v, key))
752            .collect::<Result<Vec<_>, _>>()?,
753        )),
754        ("h", J::Object(map)) => {
755          let mut out = HashMap::default();
756          for (k, v) in map {
757            out.insert(k.clone(), self.json_to_value(v, key)?);
758          }
759          Ok(Value::Hash(out))
760        },
761        ("x", J::String(xml)) => {
762          let parsed = libxml::parser::Parser::default()
763            .parse_string(xml)
764            .map_err(|e| format!("entry {key}: stored XML does not parse: {e}"))?;
765          let root = parsed
766            .get_root_element()
767            .ok_or_else(|| format!("entry {key}: stored XML is empty"))?;
768          self
769            .adopt_xml(&root)
770            .ok_or_else(|| format!("entry {key}: could not adopt stored XML"))
771        },
772        (tag, _) => Err(format!("entry {key}: unknown value tag '{tag}'")),
773      };
774    }
775    Err(format!("entry {key}: malformed value object"))
776  }
777}
778
779/// Stream an [`Entry`] directly as the tagged JSON encoding used by
780/// [`value_to_json_with`] into a caller-reused byte buffer, avoiding per-entry
781/// `serde_json::Map` and `serde_json::Value` allocations during `save_as`.
782fn write_entry_json(
783  out: &mut Vec<u8>,
784  holder: Option<&libxml::tree::Document>,
785  entry: &Entry,
786) -> serde_json::Result<()> {
787  write_map_json(out, holder, &entry.values)
788}
789
790fn write_map_json(
791  out: &mut Vec<u8>,
792  holder: Option<&libxml::tree::Document>,
793  map: &HashMap<String, Value>,
794) -> serde_json::Result<()> {
795  // Sort keys so the serialized JSON matches `serde_json::Map` (`BTreeMap`)
796  // byte-for-byte, keeping `finish()`'s `baseline` equality sound even if a
797  // `save_as` DB is ever reopened read-write.
798  let mut keys: Vec<&String> = map.keys().collect();
799  keys.sort_unstable();
800  out.push(b'{');
801  for (idx, k) in keys.into_iter().enumerate() {
802    if idx > 0 {
803      out.push(b',');
804    }
805    serde_json::to_writer(&mut *out, k)?;
806    out.push(b':');
807    write_value_json(out, holder, &map[k])?;
808  }
809  out.push(b'}');
810  Ok(())
811}
812
813fn write_value_json(
814  out: &mut Vec<u8>,
815  holder: Option<&libxml::tree::Document>,
816  value: &Value,
817) -> serde_json::Result<()> {
818  match value {
819    Value::Null => out.extend_from_slice(b"null"),
820    Value::String(s) => {
821      out.extend_from_slice(b"{\"s\":");
822      serde_json::to_writer(&mut *out, s)?;
823      out.push(b'}');
824    },
825    Value::Int(i) => {
826      out.extend_from_slice(b"{\"i\":");
827      serde_json::to_writer(&mut *out, i)?;
828      out.push(b'}');
829    },
830    Value::Bool(b) => {
831      out.extend_from_slice(if *b {
832        b"{\"b\":true}"
833      } else {
834        b"{\"b\":false}"
835      });
836    },
837    Value::List(items) => {
838      out.extend_from_slice(b"{\"l\":[");
839      for (idx, item) in items.iter().enumerate() {
840        if idx > 0 {
841          out.push(b',');
842        }
843        write_value_json(out, holder, item)?;
844      }
845      out.extend_from_slice(b"]}");
846    },
847    Value::Hash(map) => {
848      out.extend_from_slice(b"{\"h\":");
849      write_map_json(out, holder, map)?;
850      out.push(b'}');
851    },
852    Value::Xml(node) => {
853      let xml = holder
854        .map(|doc| doc.node_to_string(node))
855        .unwrap_or_default();
856      out.extend_from_slice(b"{\"x\":");
857      serde_json::to_writer(&mut *out, &xml)?;
858      out.push(b'}');
859    },
860  }
861  Ok(())
862}
863
864/// Tagged, self-describing encoding (see [`ObjectDB::value_to_json`]); a free
865/// function so `finish` can encode while iterating `self.objects`.
866fn value_to_json_with(holder: Option<&libxml::tree::Document>, value: &Value) -> serde_json::Value {
867  use serde_json::{Value as J, json};
868  match value {
869    Value::String(s) => json!({ "s": s }),
870    Value::Int(i) => json!({ "i": i }),
871    Value::Bool(b) => json!({ "b": b }),
872    Value::Null => J::Null,
873    Value::List(items) => {
874      json!({ "l": items.iter().map(|v| value_to_json_with(holder, v)).collect::<Vec<_>>() })
875    },
876    Value::Hash(map) => {
877      json!({ "h": map.iter().map(|(k, v)| (k.clone(), value_to_json_with(holder, v))).collect::<serde_json::Map<_, _>>() })
878    },
879    Value::Xml(node) => {
880      let xml = holder
881        .map(|doc| doc.node_to_string(node))
882        .unwrap_or_default();
883      json!({ "x": xml })
884    },
885  }
886}
887
888#[cfg(test)]
889mod tests {
890  use super::*;
891
892  #[test]
893  fn test_entry_basic() {
894    let mut entry = Entry::new("test:key");
895    assert_eq!(entry.get_key(), "test:key");
896    assert!(!entry.has_value("name"));
897
898    entry.set_value("name", Value::from("Alice"));
899    assert!(entry.has_value("name"));
900    assert_eq!(entry.get_string("name"), Some("Alice"));
901  }
902
903  #[test]
904  fn test_entry_push_new() {
905    let mut entry = Entry::new("test");
906    entry.push_new("children", vec![Value::from("a"), Value::from("b")]);
907    entry.push_new("children", vec![Value::from("b"), Value::from("c")]);
908    // "b" should not be duplicated
909    let children = entry.get_children();
910    assert_eq!(children, vec!["a", "b", "c"]);
911    // Writes through the other methods are seen by the next push_new.
912    entry.push_values("children", vec![Value::from("d")]);
913    entry.push_new("children", vec![
914      Value::from("d"),
915      Value::from("a"),
916      Value::from("e"),
917    ]);
918    assert_eq!(entry.get_children(), vec!["a", "b", "c", "d", "e"]);
919    entry.set_value("children", Value::List(vec![Value::from("x")]));
920    entry.push_new("children", vec![Value::from("a"), Value::from("x")]);
921    assert_eq!(entry.get_children(), vec!["x", "a"]);
922    entry.set_value("children", Value::Null);
923    entry.push_new("children", vec![Value::from("x"), Value::from("x")]);
924    assert_eq!(entry.get_children(), vec!["x"]);
925  }
926
927  #[test]
928  fn test_entry_note_association() {
929    let mut entry = Entry::new("test");
930    entry.note_association(&["referrers", "doc1"]);
931    entry.note_association(&["referrers", "doc2"]);
932
933    assert!(entry.has_value("referrers"));
934    if let Some(Value::Hash(refs)) = entry.get_value("referrers") {
935      assert!(refs.contains_key("doc1"));
936      assert!(refs.contains_key("doc2"));
937    } else {
938      panic!("Expected Hash value for referrers");
939    }
940  }
941
942  #[test]
943  fn test_db_register_lookup() {
944    let mut db = ObjectDB::new();
945
946    db.register("ID:doc1", vec![
947      ("type", Value::from("ltx:document")),
948      ("title", Value::from("Test Document")),
949    ]);
950
951    let entry = db.lookup("ID:doc1");
952    assert!(entry.is_some());
953    assert_eq!(entry.unwrap().get_string("type"), Some("ltx:document"));
954    assert_eq!(entry.unwrap().get_string("title"), Some("Test Document"));
955
956    // Lookup non-existent
957    assert!(db.lookup("ID:missing").is_none());
958  }
959
960  #[test]
961  fn test_db_register_updates() {
962    let mut db = ObjectDB::new();
963    db.register("ID:x", vec![("a", Value::from("1"))]);
964    db.register("ID:x", vec![("b", Value::from("2"))]);
965
966    let entry = db.lookup("ID:x").unwrap();
967    assert_eq!(entry.get_string("a"), Some("1"));
968    assert_eq!(entry.get_string("b"), Some("2"));
969  }
970
971  #[test]
972  fn test_db_get_keys() {
973    let mut db = ObjectDB::new();
974    db.register("B", vec![]);
975    db.register("A", vec![]);
976    db.register("C", vec![]);
977
978    let keys = db.get_keys();
979    assert_eq!(keys, vec![
980      &"A".to_string(),
981      &"B".to_string(),
982      &"C".to_string()
983    ]);
984  }
985
986  #[test]
987  fn test_db_status() {
988    let mut db = ObjectDB::new();
989    assert_eq!(db.status(), "0 objects");
990    db.register("x", vec![]);
991    assert_eq!(db.status(), "1 objects");
992  }
993
994  #[test]
995  fn many_adoptions_share_one_holding_document() {
996    // The regression this guards: one `xmlDoc` per adopted value. Scan adopts
997    // a title (and toctitle) per registered object, so a book-scale document
998    // adopted tens of thousands of times — measured, that took split
999    // post-processing of a 614 MB core XML from ~21 GB to 67 GB and a
1000    // memory-ceiling kill. Every copy must live in ONE document, and all of
1001    // them must still be readable after the sources are gone.
1002    let parser = libxml::parser::Parser::default();
1003    let mut db = ObjectDB::new();
1004    let mut sources = Vec::new();
1005    for i in 0..64 {
1006      let doc = parser
1007        .parse_string(format!("<title>Section <em>{i}</em></title>").as_bytes())
1008        .expect("parse source");
1009      let root = doc.get_root_element().expect("root");
1010      let adopted = db.adopt_xml(&root).expect("adopt");
1011      db.register(&format!("ID:S{i}"), vec![("title", adopted)]);
1012      sources.push(doc);
1013    }
1014    drop(sources); // every page DOM goes away
1015    for i in 0..64 {
1016      let entry = db.lookup(&format!("ID:S{i}")).expect("entry");
1017      let node = entry.get_xml("title").expect("stored node");
1018      assert_eq!(node.get_content(), format!("Section {i}"));
1019    }
1020    // All 64 copies are children of the single holder root, which is what
1021    // keeps the retained cost constant instead of linear in objects.
1022    let holder = db
1023      .xml_holder
1024      .as_ref()
1025      .expect("holder exists after adoption");
1026    let root = holder.get_root_element().expect("holder root");
1027    assert_eq!(root.get_child_elements().len(), 64);
1028  }
1029
1030  #[test]
1031  fn adopted_xml_survives_source_document_drop() {
1032    // The streaming contract: a stored XML value must stay valid after the
1033    // page document it was scanned from is freed. Under the old
1034    // `Value::Xml(source_node)` representation this was a use-after-free.
1035    let parser = libxml::parser::Parser::default();
1036    let source = parser
1037      .parse_string(
1038        "<title xmlns:m=\"http://www.w3.org/1998/Math/MathML\">\
1039         The <m:mi>\u{03b1}</m:mi> section</title>",
1040      )
1041      .expect("parse source");
1042    let title = source.get_root_element().expect("root");
1043
1044    let mut db = ObjectDB::new();
1045    let adopted = db.adopt_xml(&title).expect("adopt");
1046    db.register("ID:S1", vec![("title", adopted)]);
1047    drop(source); // the page DOM goes away, as it will under streaming
1048
1049    let entry = db.lookup("ID:S1").expect("entry");
1050    let node = entry.get_xml("title").expect("stored node");
1051    assert_eq!(node.get_name(), "title");
1052    assert_eq!(node.get_content(), "The \u{03b1} section");
1053    // Markup survives adoption, not just flattened text: the MathML child is
1054    // still an element in its namespace.
1055    let mi = node
1056      .get_child_nodes()
1057      .into_iter()
1058      .find(|c| c.get_name() == "mi")
1059      .expect("m:mi child survives");
1060    assert_eq!(
1061      mi.get_namespace().map(|ns| ns.get_href()),
1062      Some(String::from("http://www.w3.org/1998/Math/MathML"))
1063    );
1064  }
1065
1066  #[test]
1067  fn test_value_truthy() {
1068    assert!(!Value::Null.is_truthy());
1069    assert!(!Value::String(String::new()).is_truthy());
1070    assert!(Value::String("hello".to_string()).is_truthy());
1071    assert!(Value::Bool(true).is_truthy());
1072    assert!(!Value::Bool(false).is_truthy());
1073    assert!(Value::Int(42).is_truthy());
1074    assert!(!Value::List(vec![]).is_truthy());
1075    assert!(Value::List(vec![Value::Int(1)]).is_truthy());
1076  }
1077
1078  /// Perl `--dbfile` parity: a DB round-trips through its SQLite file —
1079  /// scalars, lists, nested hashes, and adopted XML (re-adopted into the
1080  /// READER's holder document, never a dangling node).
1081  #[test]
1082  fn dbfile_round_trips_all_value_shapes() {
1083    let dir = tempfile::tempdir().expect("tempdir");
1084    let dbfile = dir.path().join("site.db");
1085
1086    let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach fresh");
1087    let title_doc = libxml::parser::Parser::default()
1088      .parse_string("<ltx:text xmlns:ltx=\"http://dlmf.nist.gov/LaTeXML\">A <ltx:emph>title</ltx:emph></ltx:text>")
1089      .expect("title parses");
1090    let title = db
1091      .adopt_xml(&title_doc.get_root_element().expect("root"))
1092      .expect("adopted");
1093    db.register("doc1#s1", vec![
1094      ("type", Value::String("ltx:section".into())),
1095      ("pageid", Value::Int(3)),
1096      ("fresh", Value::Bool(true)),
1097      (
1098        "children",
1099        Value::List(vec![
1100          Value::String("doc1#s1.p1".into()),
1101          Value::String("doc1#s1.p2".into()),
1102        ]),
1103      ),
1104      (
1105        "referrers",
1106        Value::Hash({
1107          let mut h = HashMap::default();
1108          h.insert("doc2".to_string(), Value::String("ref".into()));
1109          h
1110        }),
1111      ),
1112      ("title", title),
1113      ("missing", Value::Null),
1114    ]);
1115    let stored = db.finish().expect("finish writes");
1116    assert_eq!(stored, 1, "one changed entry stored");
1117
1118    let mut reloaded = ObjectDB::attach(&dbfile, DbAttachOptions {
1119      readonly: true,
1120      ..Default::default()
1121    })
1122    .expect("attach readonly");
1123    assert!(
1124      reloaded
1125        .external
1126        .as_ref()
1127        .is_some_and(|e| e.baseline.is_empty()),
1128      "a readonly attach keeps no as-stored copy"
1129    );
1130    let entry = reloaded.lookup("doc1#s1").expect("entry survives");
1131    assert_eq!(entry.get_string("type"), Some("ltx:section"));
1132    assert!(matches!(entry.get_value("pageid"), Some(Value::Int(3))));
1133    assert!(matches!(entry.get_value("fresh"), Some(Value::Bool(true))));
1134    assert_eq!(entry.get_children(), vec!["doc1#s1.p1", "doc1#s1.p2"]);
1135    assert!(matches!(entry.get_value("referrers"), Some(Value::Hash(_))));
1136    let title = entry.get_xml("title").expect("XML value survives");
1137    assert!(
1138      title.get_content().contains("A title"),
1139      "adopted XML content round-trips"
1140    );
1141    assert_eq!(reloaded.finish().expect("readonly finish"), 0);
1142
1143    // XML idempotence (review finding #3): re-attach READ-WRITE and finish —
1144    // if serialize→adopt→serialize is not byte-stable, the XML entry rewrites
1145    // on every finish and the changed-only contract silently degrades to
1146    // rewrite-everything.
1147    let mut again = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach rw");
1148    assert_eq!(
1149      again.finish().expect("idempotent finish"),
1150      0,
1151      "an untouched XML-bearing entry must not re-store"
1152    );
1153
1154    // unregister must delete the STORED row too (Perl ObjectDB.pm:183:
1155    // "else it'll get pulled back in!").
1156    let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach 3");
1157    db.unregister("doc1#s1");
1158    db.finish().expect("finish after unregister");
1159    let db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach 4");
1160    assert!(
1161      db.lookup("doc1#s1").is_none(),
1162      "an unregistered key must not resurrect on re-attach"
1163    );
1164  }
1165
1166  /// Perl `finish` stores only entries that DIFFER from what the file holds
1167  /// (ObjectDB.pm: `next if compare_hash(...)`) — re-finishing an unchanged
1168  /// DB writes nothing; touching one entry writes exactly one.
1169  #[test]
1170  fn dbfile_finish_writes_only_changes() {
1171    let dir = tempfile::tempdir().expect("tempdir");
1172    let dbfile = dir.path().join("site.db");
1173    let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach");
1174    db.register("a", vec![("v", Value::Int(1))]);
1175    db.register("b", vec![("v", Value::Int(2))]);
1176    assert_eq!(db.finish().expect("first finish"), 2);
1177
1178    let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach");
1179    assert_eq!(
1180      db.finish().expect("no-op finish"),
1181      0,
1182      "unchanged DB stores nothing"
1183    );
1184
1185    let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach 2");
1186    db.register("b", vec![("v", Value::Int(99))]);
1187    db.register("c", vec![("v", Value::Int(3))]);
1188    assert_eq!(
1189      db.finish().expect("delta finish"),
1190      2,
1191      "one changed + one new"
1192    );
1193    let db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach 3");
1194    assert!(matches!(
1195      db.lookup("b").and_then(|e| e.get_value("v")),
1196      Some(Value::Int(99))
1197    ));
1198    assert_eq!(db.len(), 3);
1199  }
1200
1201  /// The concurrency contract the layer exists for (parallel page-render
1202  /// workers): N readers attach the SAME file while a writer commits — WAL
1203  /// keeps readers unblocked on their snapshot — and a second writer rides
1204  /// out the first's transaction via busy_timeout instead of failing with
1205  /// SQLITE_BUSY. ObjectDB itself is !Send (libxml values), so each thread
1206  /// builds its OWN handle inside the thread — exactly the worker model.
1207  #[test]
1208  fn dbfile_concurrent_readers_and_writer_contention() {
1209    let dir = tempfile::tempdir().expect("tempdir");
1210    let dbfile = dir.path().join("site.db");
1211    {
1212      let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("seed");
1213      for i in 0..500 {
1214        db.register(&format!("k{i}"), vec![("v", Value::Int(i))]);
1215      }
1216      assert_eq!(db.finish().expect("seed finish"), 500);
1217    }
1218
1219    // Writer-vs-writer: hold an IMMEDIATE transaction on a raw connection,
1220    // then finish() a second writer — busy_timeout must ride it out.
1221    let blocker = rusqlite::Connection::open(&dbfile).expect("blocker open");
1222    blocker
1223      .execute_batch("BEGIN IMMEDIATE; UPDATE entries SET props = props WHERE key = 'k0';")
1224      .expect("blocker tx");
1225    let release = std::thread::spawn(move || {
1226      std::thread::sleep(std::time::Duration::from_millis(300));
1227      blocker.execute_batch("COMMIT;").expect("blocker commit");
1228    });
1229    let mut writer = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("writer");
1230    writer.register("k0", vec![("v", Value::Int(-1))]);
1231    let t0 = std::time::Instant::now();
1232    assert_eq!(
1233      writer.finish().expect("contended finish succeeds"),
1234      1,
1235      "the second writer stores its one change after the blocker commits"
1236    );
1237    assert!(
1238      t0.elapsed() < std::time::Duration::from_secs(9),
1239      "finish waited out the blocker, not the full timeout"
1240    );
1241    release.join().expect("blocker thread");
1242
1243    // N concurrent readers, each with its own attach, racing a live writer.
1244    std::thread::scope(|scope| {
1245      let dbfile = &dbfile;
1246      let mut handles = Vec::new();
1247      for _ in 0..4 {
1248        handles.push(scope.spawn(move || {
1249          for _ in 0..10 {
1250            let db = ObjectDB::attach(dbfile, DbAttachOptions {
1251              readonly: true,
1252              ..Default::default()
1253            })
1254            .expect("reader attaches during writes");
1255            assert_eq!(db.len(), 500, "readers always see a full snapshot");
1256            assert!(db.lookup("k42").is_some());
1257          }
1258        }));
1259      }
1260      scope.spawn(move || {
1261        for round in 0..10 {
1262          let mut db =
1263            ObjectDB::attach(dbfile, DbAttachOptions::default()).expect("writer attaches");
1264          db.register("k1", vec![("v", Value::Int(1000 + round))]);
1265          db.finish().expect("interleaved writer finish");
1266        }
1267      });
1268      for h in handles {
1269        h.join().expect("reader thread");
1270      }
1271    });
1272  }
1273
1274  /// Staleness contract: a format-version mismatch REFUSES the file with a
1275  /// named error — never a silent reinterpretation.
1276  #[test]
1277  fn dbfile_version_mismatch_is_refused() {
1278    let dir = tempfile::tempdir().expect("tempdir");
1279    let dbfile = dir.path().join("site.db");
1280    {
1281      let conn = rusqlite::Connection::open(&dbfile).expect("open");
1282      conn
1283        .execute_batch("PRAGMA user_version = 999;")
1284        .expect("stamp");
1285    }
1286    let err = ObjectDB::attach(&dbfile, DbAttachOptions::default())
1287      .err()
1288      .expect("mismatched version must refuse");
1289    assert!(
1290      err.contains("format version 999"),
1291      "names the found version: {err}"
1292    );
1293    // `clean` is the sanctioned rebuild path (Perl `clean => 1`).
1294    let db = ObjectDB::attach(&dbfile, DbAttachOptions {
1295      clean: true,
1296      ..Default::default()
1297    })
1298    .expect("clean rebuild attaches");
1299    assert!(db.is_empty());
1300  }
1301
1302  /// Verify that `write_entry_json` (used by `save_as`) emits byte-identical
1303  /// JSON to `serde_json::to_string(&value_to_json_with(...))` across all 7
1304  /// `Value` variants, including deterministic sorted keys and escaped chars,
1305  /// and round-trips cleanly through `save_as` -> `attach`.
1306  #[test]
1307  fn save_as_streaming_json_matches_value_to_json_for_all_variants() {
1308    use crate::document::{PostDocument, PostDocumentOptions};
1309
1310    let dir = tempfile::tempdir().expect("tempdir");
1311    let dbfile = dir.path().join("snapshot.db");
1312
1313    let mut db = ObjectDB::new();
1314    let doc = PostDocument::new_from_string(
1315      r#"<ltx:document xmlns:ltx="http://dlmf.nist.gov/LaTeXML"><ltx:title>Hi &amp; "Bye"</ltx:title></ltx:document>"#,
1316      PostDocumentOptions::default(),
1317    )
1318    .expect("parse xml");
1319    let title = doc
1320      .findnodes("//ltx:title")
1321      .into_iter()
1322      .next()
1323      .expect("title node");
1324    let adopted = db.adopt_xml(&title).expect("adopt xml");
1325
1326    let mut nested = HashMap::default();
1327    nested.insert("z_key".to_string(), Value::Int(-42));
1328    nested.insert("a_key".to_string(), Value::Bool(false));
1329
1330    db.register("ID:all7", vec![
1331      ("k_null", Value::Null),
1332      ("k_str", Value::from("line1\n\"quoted\"\\slash")),
1333      ("k_int", Value::Int(123_456)),
1334      ("k_bool_t", Value::Bool(true)),
1335      ("k_bool_f", Value::Bool(false)),
1336      (
1337        "k_list",
1338        Value::List(vec![Value::from("x"), Value::Int(7), Value::Null]),
1339      ),
1340      ("k_hash", Value::Hash(nested)),
1341      ("k_xml", adopted),
1342    ]);
1343
1344    let entry = db.lookup("ID:all7").expect("registered entry");
1345    let holder = db.xml_holder.as_ref();
1346    let mut streamed = Vec::new();
1347    write_entry_json(&mut streamed, holder, entry).expect("stream json");
1348    let streamed_str = String::from_utf8(streamed).expect("utf8");
1349
1350    let mut serde_map = serde_json::Map::new();
1351    for (k, v) in &entry.values {
1352      serde_map.insert(k.clone(), value_to_json_with(holder, v));
1353    }
1354    let expected_str = serde_json::to_string(&serde_json::Value::Object(serde_map)).expect("serde");
1355    assert_eq!(streamed_str, expected_str);
1356
1357    assert_eq!(db.save_as(&dbfile).expect("save_as"), 1);
1358    let reloaded = ObjectDB::attach(&dbfile, DbAttachOptions {
1359      readonly: true,
1360      ..Default::default()
1361    })
1362    .expect("reattach");
1363    let r = reloaded.lookup("ID:all7").expect("reloaded entry");
1364    // Top-level `Value::Null` deletes the key on `set_value`; `Value::Null` inside `k_list` survives.
1365    assert!(r.get_value("k_null").is_none());
1366    assert_eq!(r.get_string("k_str"), Some("line1\n\"quoted\"\\slash"));
1367    assert!(matches!(r.get_value("k_int"), Some(Value::Int(123_456))));
1368    assert!(matches!(r.get_value("k_bool_t"), Some(Value::Bool(true))));
1369    assert!(matches!(r.get_value("k_bool_f"), Some(Value::Bool(false))));
1370    assert!(matches!(
1371      r.get_value("k_list"),
1372      Some(Value::List(l)) if l.len() == 3 && matches!(l[2], Value::Null)
1373    ));
1374    assert!(matches!(r.get_value("k_hash"), Some(Value::Hash(h)) if h.len() == 2));
1375    assert!(matches!(r.get_value("k_xml"), Some(Value::Xml(_))));
1376  }
1377}