Author SHA1 Message Date
gloamxun 8903ae6c7a Record A4 final-state reuse, SVG equivalence and visible timings 2026-12-02 04:43:38 +08:00
gloamxun 841198615a Reuse exact final fingerprints of distinct published states 2026-12-02 04:41:41 +08:00
gloamxun af8f38bb78 Reuse logical namespace keys during native file checks 2026-12-02 04:41:41 +08:00
gloamxun 4586d961e9 Share exact repeated native glyph outlines in SVG previews 2026-12-02 04:41:41 +08:00
gloamxun 9f556d6a5f Measure native editor worker CPU at preview phase boundaries 2026-12-02 04:25:44 +08:00
gloamxun 10e497e6e0 Record direct SVG delivery and A4 visible latency evidence 2026-12-02 04:22:41 +08:00
gloamxun a72768bdb3 Deliver direct SVG drafts before native PDF export 2026-12-02 04:19:06 +08:00
gloamxun 37a42c82c8 Copy native command bindings through smaller persistent shards 2026-12-02 04:19:06 +08:00
gloamxun a7c2a571c1 Record exact fingerprint savings and native editor transport comparison 2026-12-02 04:02:49 +08:00
gloamxun 6adadd7237 Revert "Decode binary native preview replies without SVG text conversion"
This reverts commit 4df8983ff5.
2026-12-02 04:01:42 +08:00
gloamxun 4df8983ff5 Decode binary native preview replies without SVG text conversion 2026-12-02 03:58:07 +08:00
gloamxun 3c09d6486d Resume exact state fingerprints from ordered command checkpoints 2026-12-02 03:55:50 +08:00
gloamxun dc86f941b6 Record protected-path preparation and real browser retest 2026-12-02 03:40:42 +08:00
gloamxun b7e1c9078d Check overlapping generated path ownership once during preparation 2026-12-02 03:33:35 +08:00
gloamxun 143775b427 Reuse bound command keys and keep identical shared bindings 2026-12-02 03:33:33 +08:00
gloamxun ac93967cb2 Record accounting CPU reductions and browser latency tails 2026-12-02 03:22:37 +08:00
gloamxun d74933348d Share common macro accounting and reduce command checkpoint copies 2026-12-02 03:14:10 +08:00
gloamxun f558bf43ea Record native preview channel correctness and editor paint timing 2026-12-02 02:59:40 +08:00
gloamxun 44e5774b3a Deliver idle native editor previews over a persistent socket 2026-12-02 02:55:20 +08:00
gloamxun 3504a43bde Compare command shard entries directly when their order matches 2026-12-02 02:55:20 +08:00
gloamxun f1b95bd749 Record real A4 browser comparison of persistent preview delivery 2026-12-02 02:43:39 +08:00
gloamxun 65bf302f5f Maintain command source bounds across checkpoint revisions 2026-12-02 02:38:43 +08:00
gloamxun c8f7a0cbe6 Expose optional checkpoint clone and suffix proof timings 2026-12-02 02:38:43 +08:00
gloamxun 67396827a9 Record project Web paint timing and exact Opt3 accounting comparison 2026-12-02 02:20:39 +08:00
gloamxun ccb278fceb Count shared command shards once during suffix verification 2026-12-02 02:11:10 +08:00
gloamxun 7981493caf Record closed-child release latency and loopback controls 2026-12-02 02:05:31 +08:00
gloamxun e4d6e049f8 Reuse settled suffixes after verified closed child edits 2026-12-02 01:53:20 +08:00
gloamxun 55c497dccd Record default-release A4 presentation latency 2026-12-02 01:47:52 +08:00
gloamxun ed105bdd39 Reuse exact hash input for shared macro meanings 2026-12-02 01:35:49 +08:00
gloamxun c4003c8dad Reduce allocation and traversal in settled suffix checks 2026-12-02 01:23:14 +08:00
gloamxun 1ff049737f Prove suffix reuse across unequal retained histories 2026-12-02 01:06:03 +08:00
29 changed files with 4252 additions and 592 deletions

No files matched your search

Generated
+165 -6
View File
@@ -123,6 +123,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "boxworks"
version = "0.1.0"
@@ -210,6 +219,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cc"
version = "1.8.0"
@@ -226,6 +241,17 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core",
]
[[package]]
name = "chrono"
version = "0.4.45"
@@ -268,6 +294,12 @@ dependencies = [
"serde",
]
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "const_fn"
version = "0.4.12"
@@ -298,6 +330,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -317,6 +358,21 @@ dependencies = [
"typenum",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "deflate"
version = "0.8.6"
@@ -344,8 +400,19 @@ version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"block-buffer 0.10.4",
"crypto-common 0.1.7",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer 0.12.1",
"const-oid",
"crypto-common 0.2.2",
]
[[package]]
@@ -531,6 +598,18 @@ dependencies = [
"rusttype",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
name = "gif"
version = "0.11.4"
@@ -557,6 +636,9 @@ name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
]
[[package]]
name = "hayro-ccitt"
@@ -663,12 +745,37 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa 1.0.18",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "hyphenate"
version = "0.1.0"
@@ -1099,6 +1206,29 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"chacha20",
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "read-fonts"
version = "0.46.0"
@@ -1269,6 +1399,17 @@ dependencies = [
"sha1_smol",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"digest 0.11.3",
]
[[package]]
name = "sha1_smol"
version = "1.0.1"
@@ -1282,8 +1423,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
@@ -1432,7 +1573,7 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
"sha1",
"sha1 0.6.1",
"syn 1.0.109",
]
@@ -1571,6 +1712,7 @@ dependencies = [
"hayro-svg",
"hyphenate",
"image 0.23.14",
"libc",
"lopdf",
"printpdf",
"rmp-serde",
@@ -1586,6 +1728,7 @@ dependencies = [
"texrra-tex-core",
"tiny_http",
"ttf-parser",
"tungstenite",
]
[[package]]
@@ -1593,8 +1736,8 @@ name = "texrra-tex-core"
version = "0.1.0"
dependencies = [
"flate2",
"hashbrown",
"harfbuzz_rs",
"hashbrown",
"hyphenate",
"image 0.23.14",
"libc",
@@ -1711,6 +1854,22 @@ dependencies = [
"core_maths",
]
[[package]]
name = "tungstenite"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand",
"sha1 0.11.0",
"thiserror",
]
[[package]]
name = "typenum"
version = "1.20.1"
+4
View File
@@ -48,4 +48,8 @@ texlang = { path = "vendor/texlang" }
texlang-stdlib = { path = "vendor/texlang-stdlib" }
[dev-dependencies]
tungstenite = "0.30"
serde_json = "1"
[target.'cfg(target_os = "linux")'.dev-dependencies]
libc = "0.2"
+1 -1
View File
@@ -7,7 +7,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
[dependencies]
flate2 = "1.1"
hashbrown = { version = "0.17.2", default-features = false, features = ["raw-entry"] }
hashbrown = { version = "0.17.2", default-features = false, features = ["default-hasher", "raw-entry"] }
harfbuzz_rs = "=3.0.1"
image = { version = "0.23.12", default-features = false, features = ["bmp"] }
lopdf = "0.26"
@@ -1,20 +1,85 @@
//! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency;
use std::collections::{BTreeSet, HashSet};
use std::{
collections::{BTreeSet, HashMap},
sync::Arc,
};
#[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct DependencyReads {
byte_catcodes: [u64; 4],
other: HashSet<Dependency>,
const INITIAL_EPOCH: u32 = 1;
const DISABLED_EPOCH: u32 = u32::MAX;
/// Last observation of each dependency, in the completed read set's order.
/// The clock records capture boundaries and has no public execution semantics.
#[derive(Clone, Debug, Default)]
pub(super) struct DependencyEvidence(Option<Arc<[u32]>>);
impl DependencyEvidence {
pub(super) fn new(epochs: Vec<u32>) -> Self {
Self(Some(epochs.into()))
}
pub(super) fn epochs(&self) -> Option<&[u32]> {
self.0.as_deref()
}
}
// The same execution can be captured at different boundaries.
impl PartialEq for DependencyEvidence {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for DependencyEvidence {}
#[derive(Clone)]
pub(super) struct DependencyReads {
pub(super) current_epoch: u32,
byte_catcodes: [u32; 256],
other: HashMap<Dependency, u32>,
}
impl Default for DependencyReads {
fn default() -> Self {
Self {
current_epoch: INITIAL_EPOCH,
byte_catcodes: [0; 256],
other: HashMap::new(),
}
}
}
impl PartialEq for DependencyReads {
fn eq(&self, other: &Self) -> bool {
self.other.len() == other.other.len()
&& self
.byte_catcodes
.iter()
.zip(&other.byte_catcodes)
.all(|(&left, &right)| (left == 0) == (right == 0))
&& self.other.keys().all(|key| other.other.contains_key(key))
}
}
impl Eq for DependencyReads {}
impl DependencyReads {
pub(super) fn epoch(&self) -> Option<u32> {
(self.current_epoch != DISABLED_EPOCH).then_some(self.current_epoch)
}
pub(super) fn advance_epoch(&mut self) {
self.current_epoch = self.current_epoch.saturating_add(1);
}
pub(super) fn disable_epochs(&mut self) {
self.current_epoch = DISABLED_EPOCH;
}
pub(super) fn catcode(&mut self, character: char) {
let index = character as usize;
if let Some(bits) = self.byte_catcodes.get_mut(index / 64) {
*bits |= 1 << (index % 64);
if let Some(epoch) = self.byte_catcodes.get_mut(character as usize) {
*epoch = self.current_epoch;
} else {
self.other.insert(Dependency::CatCode(character));
self.other
.insert(Dependency::CatCode(character), self.current_epoch);
}
}
@@ -22,50 +87,93 @@ impl DependencyReads {
if let Dependency::CatCode(character) = dependency {
self.catcode(character);
} else {
self.other.insert(dependency);
self.other.insert(dependency, self.current_epoch);
}
}
pub(super) fn observed_statistics(&self) -> bool {
self.other.contains(&Dependency::ResourceStatistics)
self.other.contains_key(&Dependency::ResourceStatistics)
}
pub(super) fn is_subset(&self, other: &Self) -> bool {
self.byte_catcodes
.iter()
.zip(other.byte_catcodes)
.all(|(&bits, permitted)| bits & !permitted == 0)
&& self.other.is_subset(&other.other)
self.other.len() <= other.other.len()
&& self
.byte_catcodes
.iter()
.zip(&other.byte_catcodes)
.all(|(&seen, &permitted)| seen == 0 || permitted != 0)
&& self.other.keys().all(|key| other.other.contains_key(key))
}
/// Extend a completed execution with observations made only in the new prefix.
/// The caller has already checked that the prefix keeps all old observations.
pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet<Dependency>) {
if self.byte_catcodes != prior.byte_catcodes {
into.extend(byte_catcode_dependencies(std::array::from_fn(|index| {
self.byte_catcodes[index] & !prior.byte_catcodes[index]
})));
for (index, (&seen, &old)) in self
.byte_catcodes
.iter()
.zip(&prior.byte_catcodes)
.enumerate()
{
if seen != 0 && old == 0 {
into.insert(Dependency::CatCode(char::from(index as u8)));
}
}
if self.other.len() != prior.other.len() {
into.extend(self.other.difference(&prior.other).cloned());
into.extend(
self.other
.keys()
.filter(|key| !prior.other.contains_key(*key))
.cloned(),
);
}
}
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
pub(super) fn observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
self.other
.iter()
.map(|(key, &epoch)| (key.clone(), epoch))
.chain(byte_catcode_observations(
self.byte_catcodes.iter().copied(),
))
}
pub(super) fn into_evidence(
self,
meanings: impl Iterator<Item = (Dependency, u32)>,
) -> (BTreeSet<Dependency>, DependencyEvidence) {
let has_captures = self.epoch().is_some_and(|epoch| epoch > INITIAL_EPOCH);
let observations = self
.other
.into_iter()
.chain(byte_catcode_dependencies(self.byte_catcodes))
.collect()
.chain(byte_catcode_observations(self.byte_catcodes.into_iter()))
.chain(meanings);
if !has_captures {
return (
observations.map(|(read, _)| read).collect(),
DependencyEvidence::default(),
);
}
let mut ordered: Vec<_> = observations.collect();
ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae)));
// A diagnostic can record a meaning also present in the lookup cache.
ordered.dedup_by(|a, b| a.0 == b.0);
let (reads, epochs) = ordered.into_iter().unzip();
(reads, DependencyEvidence::new(epochs))
}
#[cfg(test)]
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
self.into_evidence(std::iter::empty()).0
}
}
fn byte_catcode_dependencies(bits: [u64; 4]) -> impl Iterator<Item = Dependency> {
(0..=u8::MAX)
.filter(move |&index| {
let index = usize::from(index);
bits[index / 64] & (1 << (index % 64)) != 0
})
.map(|index| Dependency::CatCode(char::from(index)))
fn byte_catcode_observations(
epochs: impl Iterator<Item = u32>,
) -> impl Iterator<Item = (Dependency, u32)> {
epochs.enumerate().filter_map(|(index, epoch)| {
(epoch != 0).then(|| (Dependency::CatCode(char::from(index as u8)), epoch))
})
}
impl Extend<Dependency> for DependencyReads {
@@ -102,6 +210,40 @@ mod tests {
assert_eq!(reads, expected);
}
#[test]
fn evidence_keeps_the_last_read_across_capture_boundaries() {
let mut reads = DependencyReads::default();
reads.extend([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
Dependency::EscapeChar,
]);
let original = reads.clone();
let boundary_epoch = reads.epoch().unwrap();
reads.advance_epoch();
reads.extend([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
]);
assert!(reads == original);
let (ordered, evidence) = reads.into_evidence(std::iter::empty());
let repeated: BTreeSet<_> = ordered
.into_iter()
.zip(evidence.epochs().unwrap())
.filter_map(|(read, &epoch)| (epoch > boundary_epoch).then_some(read))
.collect();
assert_eq!(
repeated,
BTreeSet::from([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
])
);
}
#[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default();
+91 -22
View File
@@ -1,9 +1,12 @@
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::hash::{BuildHasher, RandomState};
use std::sync::Arc;
use std::time::{Duration, Instant};
use hashbrown::{HashMap, hash_map::RawEntryMut};
use super::dependency_reads::DependencyEvidence;
use super::job::InputStream;
use super::mouth::Mouth;
use super::state::{GroupKind, Key, Replacement, command_hasher};
@@ -43,7 +46,10 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings};
pub use continuation::{
ClosedSourceChange, RelocatedShipoutSuffix, RetainedStateFingerprint, SuffixKernelTimings,
SuffixStateProofTimings,
};
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -238,9 +244,10 @@ pub struct Executor {
stream_sources: BTreeSet<usize>,
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
reads: DependencyReads,
// Cache the resolved meaning alongside the already required read evidence.
// A shard's revision is only valid on this executor's state history.
meaning_reads: HashMap<CommandName, (u64, Meaning), RandomState>,
// Cache the resolved meaning alongside the last read epoch. A shard's
// revision is only valid on this executor's state history.
// Keep the read epoch on each executor, while snapshots share cache keys.
meaning_reads: HashMap<Arc<CommandName>, (u64, Meaning, u32), RandomState>,
reads_tracing_macros: bool,
conditionals: Vec<Conditional>,
in_csname: bool,
@@ -336,6 +343,14 @@ pub enum CheckpointDecision {
ReplayFailed(String),
}
/// Time spent cloning live kernel state while resuming or capturing checkpoints.
#[derive(Clone, Copy, Debug, Default)]
pub struct CheckpointCloneTimings {
pub restore: Duration,
pub capture: Duration,
pub captures: usize,
}
/// A live, in-memory kernel continuation at an entry-file command boundary.
/// The host must validate dependencies and replay all prefix effects before
/// resumption. The checkpoint itself validates the entry bytes already loaded.
@@ -436,7 +451,7 @@ impl EntryCheckpoint {
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(source, None, files, cancellation, None, None,
self.resume_observed(source, None, files, cancellation, None, None, None,
|_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix")
}
@@ -459,7 +474,8 @@ impl EntryCheckpoint {
cancellation,
Some(line_break_cache),
previous,
Executor::entry_observer(self.incoming_state, select, |slot, entry, files| {
None,
Executor::entry_observer(self.incoming_state, None, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
@@ -475,11 +491,19 @@ impl EntryCheckpoint {
cancellation: Cancellation,
line_break_cache: Arc<super::LineBreakCache>,
previous: Option<&Execution>,
timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
self.resume_observed(source, nested, files, cancellation, Some(line_break_cache), previous,
Executor::entry_observer(self.incoming_state, select, capture))
let measured = timings.is_some().then(Cell::default);
let result = self.resume_observed(
source, nested, files, cancellation, Some(line_break_cache), previous, measured.as_ref(),
Executor::entry_observer(self.incoming_state, measured.as_ref(), select, capture),
);
if let Some((timings, measured)) = timings.zip(measured) {
*timings = measured.into_inner();
}
result
}
fn resume_observed<F: SourceProvider>(
@@ -490,6 +514,7 @@ impl EntryCheckpoint {
cancellation: Cancellation,
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
timings: Option<&Cell<CheckpointCloneTimings>>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
if !self.accepts_entry(&source)
@@ -500,7 +525,15 @@ impl EntryCheckpoint {
{
return Ok(None);
}
let mut executor = self.executor.clone().with_cancellation(cancellation);
let started = timings.is_some().then(Instant::now);
let executor = self.executor.clone();
if let Some((timings, started)) = timings.zip(started) {
let mut measured = timings.get();
measured.restore += started.elapsed();
timings.set(measured);
}
let mut executor = executor.with_cancellation(cancellation);
executor.reads.advance_epoch();
executor.line_break_cache = line_break_cache;
let previous_len = self.executor.sources[self.entry].data.len();
let current_len = source.data.len();
@@ -821,10 +854,14 @@ impl Executor {
}
}
}
fn take_dependency_reads(&mut self) -> BTreeSet<Dependency> {
let mut reads = std::mem::take(&mut self.reads).into_ordered();
reads.extend(self.meaning_reads.drain().map(|(name, _)| Dependency::Meaning(name)));
reads
fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
self.reads.observations().chain(self.meaning_reads.iter()
.map(|(name, (_, _, epoch))| (Dependency::Meaning(name.as_ref().clone()), *epoch)))
}
fn take_dependency_reads(&mut self) -> (BTreeSet<Dependency>, DependencyEvidence) {
std::mem::take(&mut self.reads).into_evidence(self.meaning_reads.drain()
.map(|(name, (_, _, epoch))| (Dependency::Meaning(Arc::unwrap_or_clone(name)), epoch)))
}
fn meaning(&mut self, token: &Token) -> Meaning {
@@ -836,9 +873,11 @@ impl Executor {
fn lookup_meaning(&mut self, name: &CommandName) -> Meaning {
let hash = self.meaning_reads.hasher().hash_one(name);
let revision = self.state.command_revision(hash);
let epoch = self.reads.current_epoch;
match self.meaning_reads.raw_entry_mut().from_key_hashed_nocheck(hash, name) {
RawEntryMut::Occupied(mut entry) => {
let (cached_revision, meaning) = entry.get_mut();
let (cached_revision, meaning, last_read) = entry.get_mut();
*last_read = epoch;
if *cached_revision != revision {
*meaning = self.state.meaning_hashed(name, hash);
*cached_revision = revision;
@@ -846,8 +885,8 @@ impl Executor {
meaning.clone()
}
RawEntryMut::Vacant(entry) => {
let meaning = self.state.meaning_hashed(name, hash);
entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone()));
let (key, meaning) = self.state.cache_meaning_hashed(name, hash);
entry.insert_hashed_nocheck(hash, key, (revision, meaning.clone(), epoch));
meaning
}
}
@@ -3567,7 +3606,7 @@ impl Executor {
for node in nodes {
self.output_node(node, files)?;
}
let reads = self.take_dependency_reads();
let (reads, dependency_evidence) = self.take_dependency_reads();
let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution {
format_dumped: self.format_dumped,
@@ -3591,6 +3630,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads,
dependency_evidence,
line_observations: Some(self.line_observations),
events: self.events.into_vec(),
steps: self.steps,
@@ -3953,7 +3993,7 @@ impl Executor {
let result = self.run_observed(
file,
files,
Self::entry_observer(incoming_state, select, |slot, entry, files| {
Self::entry_observer(incoming_state, None, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
@@ -3963,6 +4003,7 @@ impl Executor {
fn entry_observer<F: SourceProvider, S>(
incoming_state: u64,
timings: Option<&Cell<CheckpointCloneTimings>>,
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision {
@@ -4007,7 +4048,17 @@ impl Executor {
return CheckpointDecision::Continue;
}
engine.events.seal_prefix();
let started = timings.is_some().then(Instant::now);
let mut executor = engine.clone();
if let Some((timings, started)) = timings.zip(started) {
let mut measured = timings.get();
measured.capture += started.elapsed();
measured.captures += 1;
timings.set(measured);
}
// Any subsequent read belongs to the suffix, even if it
// happens before the next logical TeX execution step.
engine.reads.advance_epoch();
executor.cancellation = None;
executor.line_break_cache = None;
let checkpoint = EntryCheckpoint {
@@ -4028,7 +4079,7 @@ impl Executor {
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
let reads = self.take_dependency_reads();
let (reads, dependency_evidence) = self.take_dependency_reads();
let result = result.and_then(|()| {
if self.shipped_pages > 0 && !self.format_dumped
&& let Some(objects) = self.state.pdf_objects.as_deref_mut()
@@ -4076,9 +4127,10 @@ impl Executor {
}
// An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments.
let outgoing_state = previous
.filter(|last| last.state == self.state)
.map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state);
let outgoing_state = match previous {
Some(last) if last.state == self.state => last.outgoing_state,
last => self.state.fingerprint_with_prior(last.map(|last| &last.state)),
};
let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution {
format_dumped: self.format_dumped,
@@ -4098,6 +4150,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads,
dependency_evidence,
line_observations: Some(self.line_observations),
incoming_state,
steps: self.steps,
@@ -5275,3 +5328,19 @@ impl Executor {
})
}
}
#[test]
fn cached_meaning_reads_are_observed_again_after_a_capture() {
let name = CommandName::Control("relax".into());
let read = Dependency::Meaning(name.clone());
let mut executor = Executor::new(State::default(), Limits::default());
executor.reads.insert(read.clone());
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
let boundary_epoch = executor.reads.epoch().unwrap();
executor.reads.advance_epoch();
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
let (reads, evidence) = executor.take_dependency_reads();
assert_eq!(reads, BTreeSet::from([read]));
assert_eq!(evidence.epochs().unwrap(), [boundary_epoch + 1]);
}
@@ -1,6 +1,7 @@
use super::super::{
dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::BoxNodeOffset,
statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize},
};
use super::*;
use std::time::{Duration, Instant};
@@ -96,8 +97,57 @@ impl InputFrame {
#[derive(Clone, Copy, Debug, Default)]
pub struct SuffixKernelTimings {
pub state_comparison: Duration,
/// The caller can enable the more detailed checks without changing this path.
pub state_proof: Option<SuffixStateProofTimings>,
pub retained_accounting: Duration,
pub suffix_assembly: Duration,
/// Exact matches with an earlier distinct completed state.
pub reused_final_fingerprints: usize,
}
/// Work within state comparison, which also checks the surrounding executor.
#[derive(Clone, Copy, Debug, Default)]
pub struct SuffixStateProofTimings {
pub attempts: usize,
pub matches: usize,
pub relocated_attempts: usize,
pub state_clone: Duration,
pub state_relocation: Duration,
pub exact_equality: Duration,
}
impl std::ops::AddAssign for SuffixKernelTimings {
fn add_assign(&mut self, attempt: Self) {
self.state_comparison += attempt.state_comparison;
self.retained_accounting += attempt.retained_accounting;
self.suffix_assembly += attempt.suffix_assembly;
self.reused_final_fingerprints += attempt.reused_final_fingerprints;
if let Some(attempt) = attempt.state_proof {
let total = self.state_proof.get_or_insert_with(SuffixStateProofTimings::default);
total.attempts += attempt.attempts;
total.matches += attempt.matches;
total.relocated_attempts += attempt.relocated_attempts;
total.state_clone += attempt.state_clone;
total.state_relocation += attempt.state_relocation;
total.exact_equality += attempt.exact_equality;
}
}
}
/// The final state and exact fingerprint of a completed execution.
pub struct RetainedStateFingerprint {
state: State,
fingerprint: u64,
}
impl Execution {
/// Retain just the state needed to compare a future splice.
pub fn retain_final_state_fingerprint(&self) -> RetainedStateFingerprint {
RetainedStateFingerprint {
state: self.state.clone(),
fingerprint: self.outgoing_state,
}
}
}
/// Source coordinates for the shipouts copied from a moved execution suffix.
@@ -122,7 +172,71 @@ impl RelocatedShipoutSuffix {
}
}
/// One changed physical child whose scanner has already left the input stack.
pub struct ClosedSourceChange<'a> {
pub source_id: usize,
pub name: &'a str,
pub previous_bytes: usize,
pub current_bytes: usize,
}
impl EntryCheckpoint {
/// Identify a closed byte-framed child before the host verifies its path,
/// distinct file roles, read counts, and absence of later observations.
pub fn closed_source_change<'a>(
&'a self,
prior: &Self,
completed: &Execution,
) -> Option<ClosedSourceChange<'a>> {
let current = &self.executor;
let old = &prior.executor;
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
|| current.sources.len() != old.sources.len()
|| !matches!(current.state.input_profile(), InputProfile::TeX8Bit | InputProfile::UnicodeScalar)
|| current.state.input_profile() != old.state.input_profile()
{
return None;
}
let mut differences = current.sources.iter().zip(&old.sources).enumerate()
.filter(|(_, (new, old))| new != old);
let (source_id, (new, old_source)) = differences.next()?;
if differences.next().is_some()
|| source_id == self.entry
|| new.name != old_source.name
|| completed.sources.get(source_id)? != old_source
{
return None;
}
let uniquely_named = |sources: &[Arc<SourceFile>]| {
sources.iter().filter(|source| source.name == new.name).take(2).count() == 1
};
let is_closed = |executor: &Executor| {
!executor.stream_sources.contains(&source_id)
&& !executor.generated_inputs.contains_key(&source_id)
&& !executor.inputs.iter().any(|frame| matches!(
frame, InputFrame::Source { source, .. } if *source == source_id
))
};
if !uniquely_named(&old.sources)
|| !uniquely_named(&current.sources)
|| !uniquely_named(&completed.sources)
|| !is_closed(old)
|| !is_closed(current)
|| completed.stream_sources.contains(&source_id)
|| completed.generated_inputs.contains_key(&source_id)
{
return None;
}
Some(ClosedSourceChange {
source_id,
name: &new.name,
previous_bytes: old_source.data.len(),
current_bytes: new.data.len(),
})
}
/// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
@@ -145,6 +259,56 @@ impl EntryCheckpoint {
&self,
prior: &Self,
completed: &Execution,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_suffix_with_fingerprint(prior, completed, None, None, timings)
}
/// Reuse a suffix after the caller has verified the actual host reads
/// of the changed child, including probes that only consumed its size.
/// The caller must reject later uses of this file and replay all effects.
pub fn splice_settled_closed_source_suffix_observed(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_suffix_with_fingerprint(
prior, completed, Some((source_id, prefix_resource_reads)), None, timings,
)
}
/// Verify a settled suffix with an optional prior state used only for
/// its final fingerprint. The usual kernel and host proofs still apply.
pub fn splice_settled_suffix_with_fingerprint(
&self,
prior: &Self,
completed: &Execution,
closed_source: Option<(usize, usize)>,
retained: Option<&RetainedStateFingerprint>,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
let (source_id, prefix_resource_reads) = match closed_source {
Some((source_id, reads)) => {
if reads == 0 || self.closed_source_change(prior, completed)?.source_id != source_id {
return None;
}
(source_id, reads)
}
None => (self.entry, 1),
};
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, retained, timings)
}
fn splice_settled_sources(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
retained: Option<&RetainedStateFingerprint>,
mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
@@ -169,7 +333,7 @@ impl EntryCheckpoint {
.zip(&old.sources)
.enumerate()
.any(|(id, (new, old))| {
if id == self.entry {
if id == source_id {
new.name != old.name
} else {
new != old
@@ -185,26 +349,28 @@ impl EntryCheckpoint {
None if box_offset.is_identity() => None,
None => return None,
};
if current.material_charge != old.material_charge {
// A capacity recount can lower the running charge and change
// which storage TeX counts. Bound every future charge on both
// histories so neither can enter that path.
let donor = completed.box_nodes_created?;
if donor == usize::MAX {
return None;
}
let remaining = donor.checked_sub(old.box_nodes_created)?;
let largest = current.material_charge.max(old.material_charge);
if largest.checked_add(remaining)? > current.limits.tokens {
return None;
}
// A capacity recount can lower the running charge and observe
// the retained event history. Bound all future visits on both
// runs before translating any unequal charge or history.
let no_suffix_recount = completed.box_nodes_created.is_some_and(|nodes| {
nodes != usize::MAX
&& nodes.checked_sub(old.box_nodes_created)
.and_then(|remaining| current.material_charge.max(old.material_charge)
.checked_add(remaining))
.is_some_and(|charge| charge <= current.limits.tokens)
});
if current.material_charge != old.material_charge && !no_suffix_recount {
return None;
}
let previous_bytes = &old.sources[self.entry].data;
let current_bytes = &current.sources[self.entry].data;
let entry_sizes = (previous_bytes.len() != current_bytes.len())
.then_some((previous_bytes.len(), current_bytes.len()));
let relocation = match entry_sizes {
Some(_) => {
let previous_bytes = &old.sources[source_id].data;
let current_bytes = &current.sources[source_id].data;
let resize = (previous_bytes.len() != current_bytes.len()).then_some(SuffixSourceResize {
sizes: (previous_bytes.len(), current_bytes.len()),
active_at_anchor: source_id == self.entry,
prefix_resource_reads,
});
let relocation = match resize {
Some(resize) if resize.active_at_anchor => {
let map = self.source_mouth(self.entry)
.relocation_from(prior.source_mouth(prior.entry))?;
if map.relocate_offset(prior.frontier) != Some(self.frontier) {
@@ -212,13 +378,16 @@ impl EntryCheckpoint {
}
Some(map)
}
Some(_) if self.frontier == prior.frontier => {
Some(SourceRelocation::new(source_id, previous_bytes, current_bytes)?)
}
None if self.frontier == prior.frontier => None,
None => return None,
_ => return None,
};
let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| {
observations.get(&self.entry) != old.line_observations.get(&self.entry)
let observes_changed_line = completed.line_observations.as_ref().is_none_or(|observations| {
observations.get(&source_id) != old.line_observations.get(&source_id)
});
if observes_entry_line
if observes_changed_line
&& relocation.as_ref().map_or_else(
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1,
@@ -239,9 +408,24 @@ impl EntryCheckpoint {
// Comparison and publication visit some of the same original
// allocations. Keep the checked relocations for this donor only.
let mut moved = relocation.as_ref().map(EventRelocation::new);
if !measure(timings.as_deref_mut().map(|timings| &mut timings.state_comparison), || {
same_kernel_continuation(current, old, moved.as_mut())
}) {
let states_match = if let Some(timings) = timings.as_deref_mut() {
let started = Instant::now();
if let Some(proof) = &mut timings.state_proof {
proof.attempts += 1;
proof.relocated_attempts += usize::from(moved.is_some());
}
let matched = same_kernel_continuation(
current, old, moved.as_mut(), timings.state_proof.as_mut(),
);
if let Some(proof) = &mut timings.state_proof {
proof.matches += usize::from(matched);
}
timings.state_comparison += started.elapsed();
matched
} else {
same_kernel_continuation(current, old, moved.as_mut(), None)
};
if !states_match {
return None;
}
let offset = StepOffset::new(old.steps, current.steps);
@@ -252,30 +436,39 @@ impl EntryCheckpoint {
return None;
}
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
sources[source_id] = current.sources[source_id].clone();
let tail = completed.events.get(old.events.len()..)?;
if completed.accounts_event_history
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
})
{
return None;
}
let retained_history = if completed.accounts_event_history {
measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
if current.events.len() == old.events.len()
&& current.equivalent_accounting_history_with_source_resize(old, resize)
{
return Some(None);
}
// Shipout reports also contribute to later diagnostic
// counters. Only translate the final report here.
let has_final_report = matches!(tail.last(),
Some(Event::Statistics(report)) if matches!(report.phase, StatisticsPhase::End { .. })
);
if !no_suffix_recount || !has_final_report
|| tail[..tail.len() - 1].iter().any(|event| matches!(event, Event::Statistics(_)))
{
return None;
}
let history = current.retained_history_offset(old, resize)?;
Some((!history.is_identity()).then_some(history))
})?
} else {
None
};
let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history };
// The joined events are published results. Resumption always starts
// from a live checkpoint, whose original shared allocations stay intact.
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
let mut events = Vec::with_capacity(completed.events.len());
let mut reused_final_fingerprint = false;
let execution = measure(timings.as_deref_mut().map(|timings| &mut timings.suffix_assembly), || {
let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?);
events.extend(current.events.iter().cloned());
let mut reads = completed.reads.clone();
current.reads.extend_ordered_delta(&old.reads, &mut reads);
if current.meaning_reads.len() != old.meaning_reads.len() {
reads.extend(
current.meaning_reads.keys()
.filter(|name| !old.meaning_reads.contains_key(*name))
.cloned()
.map(Dependency::Meaning),
);
}
let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?;
let mut execution = Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
@@ -293,6 +486,7 @@ impl EntryCheckpoint {
stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(),
reads,
dependency_evidence,
line_observations,
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
@@ -301,20 +495,27 @@ impl EntryCheckpoint {
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
};
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
if let Some((moved, resize)) = moved.as_mut().zip(resize) {
relocate::append_suffix(
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(),
&mut execution, tail, &statistics, moved, resize, old.sources.len(),
)?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
execution.outgoing_state = if let Some(retained) = retained
&& execution.state == retained.state
{
reused_final_fingerprint = true;
retained.fingerprint
} else {
execution.state.fingerprint_with_prior(Some(&completed.state))
};
}
} else if offset.is_identity() && box_offset.is_identity() {
} else if statistics.is_identity() {
execution.events.extend_from_slice(tail);
} else {
for event in tail {
execution.events.push(match event {
Event::Statistics(report) => Event::Statistics(Box::new(
report.with_execution_offsets(offset, box_offset)?,
statistics.translate(report, None)?,
)),
_ => event.clone(),
});
@@ -322,6 +523,9 @@ impl EntryCheckpoint {
}
Some(execution)
})?;
if let Some(timings) = timings {
timings.reused_final_fingerprints += usize::from(reused_final_fingerprint);
}
let layout = relocation.map(|map| RelocatedShipoutSuffix {
// The executor records one top-level shipout event whenever
// this count advances. Form canvases do not enter this sequence.
@@ -346,21 +550,29 @@ impl EntryCheckpoint {
}
let current = &self.executor;
let old = &prior.executor;
// Rebased checkpoints retain the donor's closed-source bytes.
if current.sources.len() != old.sources.len()
|| current.sources.iter().zip(&old.sources).enumerate()
.any(|(id, (new, old))| id != self.entry && new != old)
{
return None;
}
// Later snapshots retain the donor's meaning cache and read history.
// A successful splice proved key inclusion, so equal lengths prove
// that no new meaning lookup would be lost by carrying the snapshot.
if current.reads != old.reads
// Keeping them requires the same keys, even when the finished splice
// could publish a different set using exact suffix evidence.
if current.events.len() != old.events.len()
|| current.reads != old.reads
|| current.meaning_reads.len() != old.meaning_reads.len()
|| !old.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|| current.box_nodes_created != old.box_nodes_created
|| current.material_charge != old.material_charge
{
return None;
}
// A restored checkpoint may later be asked to account for its
// history, even if the job that furnished the suffix did not.
if !completed.accounts_event_history
&& !self.executor.equivalent_accounting_history(&prior.executor)
{
// A carried executor needs the exact alias history before taking
// donor allocations from equal-valued events. Translating a final
// report proves only the published counts.
if completed.reads_event_history || !current.equivalent_accounting_history(old) {
return None;
}
// Keep the old allocations of unchanged material, including inside
@@ -418,6 +630,9 @@ impl EntryCheckpoint {
}
let mut executor = next.clone();
// These carried snapshots still have the right cumulative keys.
// The donor's private timestamps alone cannot date the new prefix.
executor.reads.disable_epochs();
executor.line_observations = splice_line_observations(
&current.line_observations, &old.line_observations, &next.line_observations,
)?;
@@ -468,6 +683,48 @@ impl EntryCheckpoint {
}
}
fn splice_dependencies(
current: &Executor,
prior: &Executor,
completed: &Execution,
) -> Option<(BTreeSet<Dependency>, DependencyEvidence)> {
if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = (
current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(),
) {
if donor.len() != completed.reads.len() {
return None;
}
let mut observed: BTreeMap<Dependency, u32> = BTreeMap::new();
for (key, epoch) in current.dependency_observations() {
observed.entry(key).and_modify(|last| *last = (*last).max(epoch)).or_insert(epoch);
}
for (key, &epoch) in completed.reads.iter().zip(donor) {
if epoch > donor_epoch {
let translated = current_epoch.checked_add(epoch - donor_epoch)?;
observed.insert(key.clone(), translated);
}
}
let (reads, epochs) = observed.into_iter().unzip();
return Some((reads, DependencyEvidence::new(epochs)));
}
// Restored records without epoch evidence can only preserve every
// previous prefix key. Removing one could erase a repeated suffix read.
if !prior.reads.is_subset(&current.reads)
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
{
return None;
}
let mut reads = completed.reads.clone();
current.reads.extend_ordered_delta(&prior.reads, &mut reads);
if current.meaning_reads.len() != prior.meaning_reads.len() {
reads.extend(current.meaning_reads.keys()
.filter(|name| !prior.meaning_reads.contains_key(*name))
.map(|name| Dependency::Meaning(name.as_ref().clone())));
}
Some((reads, DependencyEvidence::default()))
}
fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
let started = elapsed.is_some().then(Instant::now);
let value = action();
@@ -497,6 +754,28 @@ fn splice_line_observations(
Some(combined)
}
struct SuffixStatistics {
steps: StepOffset,
boxes: BoxNodeOffset,
retained_history: Option<RetainedHistoryOffset>,
}
impl SuffixStatistics {
fn is_identity(&self) -> bool {
self.steps.is_identity() && self.boxes.is_identity() && self.retained_history.is_none()
}
fn translate(
&self,
report: &StatisticsReport,
resize: Option<SuffixSourceResize>,
) -> Option<StatisticsReport> {
report.with_source_resize(
self.steps, self.boxes, resize, self.retained_history.as_ref(),
)
}
}
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
match event {
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
@@ -522,6 +801,7 @@ fn same_kernel_continuation(
current: &Executor,
prior: &Executor,
relocation: Option<&mut EventRelocation<'_>>,
timings: Option<&mut SuffixStateProofTimings>,
) -> bool {
// Every field belongs to one of these checks. Adding kernel state requires
// an explicit decision here before a later execution may be skipped.
@@ -626,13 +906,9 @@ fn same_kernel_continuation(
if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
return false;
}
if current.events.len() != prior.events.len()
|| current.inputs.len() != prior.inputs.len()
if current.inputs.len() != prior.inputs.len()
// Statistics membership also constrains source rebinding.
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|| !prior.reads.is_subset(&current.reads)
|| prior.meaning_reads.len() > current.meaning_reads.len()
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
{
return false;
}
@@ -643,9 +919,9 @@ fn same_kernel_continuation(
return false;
}
if let Some(relocation) = relocation {
return relocate::same_kernel_provenance(current, prior, relocation).unwrap_or(false);
return relocate::same_kernel_provenance(current, prior, relocation, timings).unwrap_or(false);
}
current.state == prior.state
measure(timings.map(|timings| &mut timings.exact_equality), || current.state == prior.state)
&& current.generated_inputs == prior.generated_inputs
&& current.conditionals == prior.conditionals
&& current.current == prior.current
@@ -1,10 +1,11 @@
use super::*;
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset};
use crate::execution::source_relocation_events::EventRelocation;
pub(super) fn same_kernel_provenance(
current: &Executor,
prior: &Executor,
relocation: &mut EventRelocation<'_>,
mut timings: Option<&mut SuffixStateProofTimings>,
) -> Option<bool> {
let map = relocation.map();
if current.current != map.relocate_span(prior.current)?
@@ -98,24 +99,31 @@ pub(super) fn same_kernel_provenance(
return Some(false);
}
let mut state = prior.state.clone();
state.relocate_source(relocation)?;
Some(current.state == state)
let mut state = measure(
timings.as_deref_mut().map(|timings| &mut timings.state_clone),
|| prior.state.clone(),
);
measure(
timings.as_deref_mut().map(|timings| &mut timings.state_relocation),
|| state.relocate_source(relocation),
)?;
Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state))
}
pub(super) fn append_suffix(
execution: &mut Execution,
tail: &[Event],
offset: StepOffset,
boxes: BoxNodeOffset,
statistics: &SuffixStatistics,
relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize),
resize: SuffixSourceResize,
source_count: usize,
) -> Option<()> {
let map = relocation.map();
for event in tail {
if let Event::Statistics(report) = event {
if let StatisticsPhase::Shipout { before, after } = &report.phase {
if resize.active_at_anchor
&& let StatisticsPhase::Shipout { before, after } = &report.phase
{
// The active entry was the only source frame at convergence.
// If a report follows any later input open, its mouth payload
// alone cannot prove whether that frame is still present.
@@ -123,9 +131,7 @@ pub(super) fn append_suffix(
return None;
}
}
let mut report = report
.with_execution_offsets(offset, boxes)?
.with_suffix_entry_resize(previous_bytes, current_bytes)?;
let mut report = statistics.translate(report, Some(resize))?;
report.span = map.relocate_span(report.span)?;
execution.events.push(Event::Statistics(Box::new(report)));
} else {
@@ -1,6 +1,7 @@
use super::super::statistics::{
Collector,
Ownership::{Active, Retained},
RetainedHistoryOffset, SuffixSourceResize,
};
use super::*;
impl Executor {
@@ -49,8 +50,9 @@ impl Executor {
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
c: Collector,
mut c: Collector,
) -> ResourceUsage {
self.state.collect_statistics(&mut c);
let mut c = self.collect_live_usage(shipping, host, c);
Self::collect_event_usage(self.events.iter(), &mut c);
c.usage
@@ -62,7 +64,6 @@ impl Executor {
host: Option<HostResourceUsage>,
mut c: Collector,
) -> Collector {
self.state.collect_statistics(&mut c);
c.usage.steps = self.steps;
c.usage.source_files = self.sources.len();
c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum();
@@ -231,14 +232,39 @@ impl Executor {
}
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
self.equivalent_accounting_history_with_entry_sizes(old, None)
self.equivalent_accounting_history_with_source_resize(old, None)
}
pub(super) fn equivalent_accounting_history_with_entry_sizes(
pub(super) fn equivalent_accounting_history_with_source_resize(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
resize: Option<SuffixSourceResize>,
) -> bool {
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
self.collect_compared_accounting(old, resize, collector).is_some_and(
|(live, old_live, history, old_history)| {
live.has_equivalent_history(&old_live, &history, &old_history)
},
)
})
}
pub(super) fn retained_history_offset(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
) -> Option<RetainedHistoryOffset> {
let (live, old_live, history, old_history) =
self.collect_compared_accounting(old, resize, Collector::default)?;
live.retained_history_offset(&old_live, &history, &old_history)
}
fn collect_compared_accounting(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
collector: fn() -> Collector,
) -> Option<(Collector, Collector, Collector, Collector)> {
// These containers may reintroduce previously retained allocations
// that are outside the accounting walk at this boundary.
let fully_visited = |engine: &Self| {
@@ -246,26 +272,27 @@ impl Executor {
&& engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty())
};
if !fully_visited(self) || !fully_visited(old) {
return false;
return None;
}
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some((previous, current)) = entry_sizes {
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
let Some(source) = restore(live.usage.source_payload_bytes) else { return false; };
let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; };
live.usage.source_payload_bytes = source;
live.usage.mouth_payload_bytes = mouth;
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let (live, old_live) = self.state.collect_compared_statistics(
&old.state, collector().tracking_aliases(),
)?;
let mut live = self.collect_live_usage(None, None, live);
let old_live = old.collect_live_usage(None, None, old_live);
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some(resize) = resize {
let (previous, current) = resize.sizes;
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
if resize.active_at_anchor {
live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
}
live.has_equivalent_history(&old_live, &history, &old_history)
})
}
Some((live, old_live, history, old_history))
}
pub(super) fn statistics_before_shipout(
@@ -341,6 +368,57 @@ impl Executor {
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::statistics::BoxNodeOffset;
#[test]
fn equal_mark_events_with_different_aliases_cannot_carry_a_checkpoint() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let shared: Arc<[Token]> = Arc::from([token.clone()]);
let independent: Arc<[Token]> = Arc::from([token]);
let mark = |tokens| {
Event::VerticalMaterial(vec![NativeVerticalNode::Mark(NativeMark {
class: 0,
tokens,
span: Span::default(),
})])
};
let mut old = Executor::default();
old.state.page_marks.insert(0, PageMarks {
top: Some(shared.clone()),
..PageMarks::default()
});
let mut current = old.clone();
old.events.push(mark(shared.clone()));
old.events.push(mark(shared.clone()));
current.events.push(mark(shared));
current.events.push(mark(independent));
// Rebase's value comparison alone would retain the old Arc sharing.
assert!(current.events.iter().eq(old.events.iter()));
assert!(!current.equivalent_accounting_history(&old));
let offset = current.retained_history_offset(&old, None).unwrap();
assert!(!offset.is_identity());
let end_report = |engine: &Executor| {
StatisticsReport::new(
StatisticsPhase::End {
success: true,
usage: engine.collect_usage(None, None, Collector::default()),
},
WriteDestination::Log,
Span::default(),
)
};
assert_eq!(
end_report(&old).with_suffix_adjustments(
StepOffset::new(0, 0),
BoxNodeOffset::new(0, 0),
None,
Some(&offset),
),
Some(end_report(&current))
);
}
#[test]
fn shared_event_prefix_keeps_tail_deduplication_and_membership() {
+8 -4
View File
@@ -72,8 +72,9 @@ pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
SuffixKernelTimings,
CheckpointCloneTimings, CheckpointDecision, CheckpointSource, ClosedSourceChange,
EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, RetainedStateFingerprint, SuffixKernelTimings,
SuffixStateProofTimings,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
@@ -678,9 +679,12 @@ pub struct Execution {
pub stream_sources: BTreeSet<usize>,
#[serde(default)]
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
/// Reads made during this execution, not a license to reuse output after
/// state changes. Incremental execution/cache reuse is a later milestone.
/// Dependencies observed over the execution. Suffix reuse additionally
/// validates the state and the reads that follow its checkpoint.
pub reads: BTreeSet<Dependency>,
/// Internal epochs relate active checkpoint cuts to repeated reads.
#[serde(skip)]
dependency_evidence: dependency_reads::DependencyEvidence,
/// Per-source observations distinguish suffix reads from identical prefix reads.
#[serde(default, skip_serializing_if = "Option::is_none")]
line_observations: Option<BTreeMap<usize, usize>>,
@@ -3,7 +3,8 @@ use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex};
use super::{
Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, LineBreakCache,
Cancellation, CheckpointCloneTimings, EntryCheckpoint, Error, Execution, ExecutionFailure,
Executor, LineBreakCache,
SourceFile, SourceProvider,
};
@@ -305,11 +306,28 @@ impl RevisionJob {
line_break_cache: Arc<LineBreakCache>,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
self.resume_deciding_suffix_observed(
checkpoint, source, nested, files, line_break_cache, None, select, capture,
)
}
/// Resume with optional timing for the executor clones used by checkpoints.
pub fn resume_deciding_suffix_observed<F: SourceProvider, S>(
&self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
line_break_cache: Arc<LineBreakCache>,
timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix(
source, nested, files, self.cancellation.clone(), line_break_cache,
previous.as_deref().map(|item| &item.execution), select, capture,
previous.as_deref().map(|item| &item.execution), timings, select, capture,
)?;
Ok(executed.map(|result| self.finish_execution(result, files, previous.as_deref())))
}
@@ -220,6 +220,12 @@ impl SourceRelocation {
}
}
/// A shard whose ranges end strictly before the edit can retain every
/// span, including zero-width points at those earlier positions.
pub(super) fn preserves_prefix_through(&self, end: usize) -> bool {
end < self.unchanged_prefix
}
pub(super) fn relocate_span(&self, span: Span) -> Option<Span> {
if span.source != self.source {
return Some(span);
+717 -103
View File
@@ -1,9 +1,12 @@
mod fingerprint;
pub(super) mod source_relocation;
use hashbrown::HashMap;
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::{HashMap, hash_map::RawEntryMut};
use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
use std::sync::{Arc, OnceLock};
use std::sync::{Arc, Mutex, OnceLock};
use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -799,10 +802,110 @@ enum PdftexRevision {
R24,
}
const COMMAND_SHARDS: usize = 32;
type CommandShard = HashMap<Arc<CommandName>, Meaning, RandomState>;
// The first write after a checkpoint copies one directory group and one
// small shard. The group's local revisions remain cheap to read and copy.
const COMMAND_SHARD_GROUPS: usize = 32;
const COMMAND_SHARDS_PER_GROUP: usize = 16;
const COMMAND_SHARDS: usize = COMMAND_SHARD_GROUPS * COMMAND_SHARDS_PER_GROUP;
type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)]
struct CommandShard {
entries: CommandEntries,
// Keep conservative bounds as each meaning is installed. Checkpoints
// share the bounds along with the entries, so proving a source move does
// not have to discover them from every macro body in each donor.
// Replacing or removing an entry may retain its bound.
source_bounds: BTreeMap<usize, Option<usize>>,
}
impl CommandShard {
fn new(hasher: RandomState) -> Self {
Self {
entries: CommandEntries::with_hasher(hasher),
source_bounds: BTreeMap::new(),
}
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) -> Option<Meaning> {
let hash = self.entries.hasher().hash_one(name.as_ref());
self.insert_hashed(name, meaning, hash)
}
fn insert_hashed(
&mut self,
name: Arc<CommandName>,
meaning: Meaning,
hash: u64,
) -> Option<Meaning> {
source_relocation::include_meaning_bounds(&mut self.source_bounds, &meaning);
match self.entries.raw_entry_mut().from_key_hashed_nocheck(hash, name.as_ref()) {
RawEntryMut::Occupied(mut entry) => Some(std::mem::replace(entry.get_mut(), meaning)),
RawEntryMut::Vacant(entry) => {
entry.insert_hashed_nocheck(hash, name, meaning);
None
}
}
}
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning, hash: u64) -> bool {
let RawEntryMut::Vacant(entry) =
self.entries.raw_entry_mut().from_key_hashed_nocheck(hash, name.as_ref())
else {
return false;
};
source_relocation::include_meaning_bounds(&mut self.source_bounds, &meaning);
entry.insert_hashed_nocheck(hash, name, meaning);
true
}
}
impl PartialEq for CommandShard {
fn eq(&self, other: &Self) -> bool {
if self.entries.len() != other.entries.len() {
return false;
}
// Copy-on-write shards with only value changes can keep their bucket
// order. Verify each key before comparing its meaning.
for ((name, meaning), (other_name, other_meaning)) in self.entries.iter().zip(&other.entries) {
if name != other_name {
return self.entries == other.entries;
}
if meaning != other_meaning {
return false;
}
}
true
}
}
impl Eq for CommandShard {}
#[derive(Clone, Debug)]
struct CommandShardGroup {
shards: [Arc<CommandShard>; COMMAND_SHARDS_PER_GROUP],
revisions: [u64; COMMAND_SHARDS_PER_GROUP],
}
impl PartialEq for CommandShardGroup {
fn eq(&self, other: &Self) -> bool {
self.shards == other.shards
}
}
impl Eq for CommandShardGroup {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
const COMMAND_HASH_CHECKPOINT_STRIDE: usize = 128;
#[derive(Debug)]
struct CommandHashCheckpoints {
blocks: Vec<DefaultHasher>,
end: DefaultHasher,
}
pub(super) fn command_hasher() -> &'static RandomState {
// Identical hashes feed the binding table and the executor's read cache.
// The seed and partition are private to this process.
@@ -812,26 +915,31 @@ pub(super) fn command_hasher() -> &'static RandomState {
#[derive(Clone, Debug)]
struct CommandBindings {
shards: [Arc<CommandShard>; COMMAND_SHARDS],
revisions: [u64; COMMAND_SHARDS],
shard_groups: [Arc<CommandShardGroup>; COMMAND_SHARD_GROUPS],
// Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
hash_checkpoints: OnceLock<Arc<CommandHashCheckpoints>>,
}
impl Default for CommandBindings {
fn default() -> Self {
let hasher = command_hasher();
Self {
shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))),
revisions: [0; COMMAND_SHARDS],
shard_groups: std::array::from_fn(|_| Arc::new(CommandShardGroup {
shards: std::array::from_fn(|_| Arc::new(CommandShard::new(hasher.clone()))),
revisions: [0; COMMAND_SHARDS_PER_GROUP],
})),
ordered_names: Arc::default(),
fingerprint_inputs: Arc::default(),
hash_checkpoints: OnceLock::new(),
}
}
}
impl PartialEq for CommandBindings {
fn eq(&self, other: &Self) -> bool {
self.shards == other.shards
self.shard_groups == other.shard_groups
}
}
@@ -843,40 +951,85 @@ impl CommandBindings {
((hash >> 32) as usize) % COMMAND_SHARDS
}
fn shard(&self, index: usize) -> &Arc<CommandShard> {
&self.shard_groups[index / COMMAND_SHARDS_PER_GROUP].shards[index % COMMAND_SHARDS_PER_GROUP]
}
fn shards(&self) -> impl Iterator<Item = &Arc<CommandShard>> {
self.shard_groups.iter().flat_map(|group| &group.shards)
}
fn get(&self, name: &CommandName) -> Option<&Meaning> {
self.get_hashed(name, command_hasher().hash_one(name))
}
fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> {
self.shards[Self::shard_index(hash)]
.raw_entry()
.from_key_hashed_nocheck(hash, name)
.map(|(_, meaning)| meaning)
self.get_hashed_entry(name, hash).map(|(_, meaning)| meaning)
}
fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard {
let index = Self::shard_index(command_hasher().hash_one(name));
self.revisions[index] += 1;
Arc::make_mut(&mut self.shards[index])
fn get_hashed_entry(
&self,
name: &CommandName,
hash: u64,
) -> Option<(&Arc<CommandName>, &Meaning)> {
self.shard(Self::shard_index(hash))
.entries
.raw_entry()
.from_key_hashed_nocheck(hash, name)
}
fn shard_group_mut(&mut self, index: usize) -> &mut CommandShardGroup {
self.hash_checkpoints.take();
Arc::make_mut(&mut self.shard_groups[index / COMMAND_SHARDS_PER_GROUP])
}
fn shard_mut(&mut self, index: usize) -> &mut CommandShard {
let group = self.shard_group_mut(index);
Arc::make_mut(&mut group.shards[index % COMMAND_SHARDS_PER_GROUP])
}
fn revise_shard(&mut self, hash: u64) -> &mut CommandShard {
let index = Self::shard_index(hash);
let group = self.shard_group_mut(index);
let slot = index % COMMAND_SHARDS_PER_GROUP;
group.revisions[slot] += 1;
Arc::make_mut(&mut group.shards[slot])
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) {
if self.shard_mut(&name).insert(name, meaning).is_none() {
let hash = command_hasher().hash_one(name.as_ref());
let index = Self::shard_index(hash);
let group = &self.shard_groups[index / COMMAND_SHARDS_PER_GROUP];
let shard = &group.shards[index % COMMAND_SHARDS_PER_GROUP];
// The caller already saved or cleared the TeX group entry. Either
// level of sharing can make an identical installation avoid a copy.
if (Arc::strong_count(group) > 1 || Arc::strong_count(shard) > 1)
&& shard.entries.raw_entry().from_key_hashed_nocheck(hash, name.as_ref())
.is_some_and(|(_, previous)| match (previous, &meaning) {
(Meaning::Macro(previous), Meaning::Macro(body)) => Arc::ptr_eq(previous, body),
(previous, meaning) => previous == meaning,
})
{
return;
}
if self.revise_shard(hash).insert_hashed(name, meaning, hash).is_none() {
self.invalidate_order();
}
}
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
if let hashbrown::hash_map::Entry::Vacant(entry) =
self.shard_mut(&name).entry(name.into())
{
entry.insert(meaning);
let hash = command_hasher().hash_one(&name);
if self.revise_shard(hash).insert_if_absent(name.into(), meaning, hash) {
self.invalidate_order();
}
}
fn remove(&mut self, name: &CommandName) {
if self.shard_mut(name).remove(name).is_some() {
let hash = command_hasher().hash_one(name);
if let RawEntryMut::Occupied(entry) =
self.revise_shard(hash).entries.raw_entry_mut().from_key_hashed_nocheck(hash, name)
{
entry.remove();
self.invalidate_order();
}
}
@@ -890,11 +1043,11 @@ impl CommandBindings {
}
fn len(&self) -> usize {
self.shards.iter().map(|shard| shard.len()).sum()
self.shards().map(|shard| shard.entries.len()).sum()
}
fn iter(&self) -> impl Iterator<Item = (&Arc<CommandName>, &Meaning)> {
self.shards.iter().flat_map(|shard| shard.iter())
self.shards().flat_map(|shard| shard.entries.iter())
}
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
@@ -919,9 +1072,97 @@ impl CommandBindings {
}
}
impl CommandBindings {
fn first_changed_binding(&self, prior: &Self) -> Option<usize> {
// Value overwrites can retain the order object. Insertion and
// removal replace it before a different ordered key set is used.
if !Arc::ptr_eq(&self.ordered_names, &prior.ordered_names) {
return None;
}
let names = prior.ordered_names.get()?;
let mut first = None;
let changed_groups = self.shard_groups.iter().zip(&prior.shard_groups)
.filter(|(current, old)| !Arc::ptr_eq(current, old));
for (current, old) in changed_groups.flat_map(|(current, old)| current.shards.iter().zip(&old.shards)) {
if Arc::ptr_eq(current, old) {
continue;
}
for (name, meaning) in &current.entries {
if first.is_some_and(|first| name >= first) {
continue;
}
let unchanged = match (meaning, old.entries.get(name)?) {
(Meaning::Macro(current), Meaning::Macro(old)) => Arc::ptr_eq(current, old),
(current, old) => current == old,
};
if !unchanged {
first = Some(name);
}
}
}
match first {
Some(name) => names.binary_search_by(|(key, _)| key.cmp(name)).ok(),
None => Some(names.len()),
}
}
fn hash_fingerprint(&self, hasher: &mut FingerprintHasher, prior: Option<&Self>) {
if let Some(checkpoints) = self.hash_checkpoints.get() {
hasher.restore(&checkpoints.end);
return;
}
let entries = self.ordered();
let count = entries.len();
let donor = prior.and_then(|prior| {
let checkpoints = prior.hash_checkpoints.get()?;
Some((self.first_changed_binding(prior)?, checkpoints))
});
if let Some((first, donor)) = donor
&& first == count
{
hasher.restore(&donor.end);
let _ = self.hash_checkpoints.set(donor.clone());
return;
}
let mut blocks = Vec::with_capacity(count / COMMAND_HASH_CHECKPOINT_STRIDE + 1);
let offset = if let Some((first, donor)) = donor {
let index = first / COMMAND_HASH_CHECKPOINT_STRIDE;
blocks.extend_from_slice(&donor.blocks[..=index]);
hasher.restore(&donor.blocks[index]);
index * COMMAND_HASH_CHECKPOINT_STRIDE
} else {
count.hash(hasher);
blocks.push(hasher.checkpoint());
0
};
let mut inputs = self.fingerprint_inputs.try_lock().ok();
if let Some(inputs) = &mut inputs {
inputs.prune_if_full();
}
for (index, (name, meaning)) in entries.enumerate().skip(offset) {
name.hash(hasher);
if let Some(inputs) = &mut inputs {
inputs.hash_meaning(meaning, hasher);
} else {
meaning.hash(hasher);
}
if (index + 1) % COMMAND_HASH_CHECKPOINT_STRIDE == 0 {
blocks.push(hasher.checkpoint());
}
}
let end = hasher.checkpoint();
let _ = self.hash_checkpoints.set(Arc::new(CommandHashCheckpoints { blocks, end }));
}
}
impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.ordered().collect::<Vec<_>>().hash(hasher);
let entries = self.ordered();
entries.len().hash(hasher);
for entry in entries {
entry.hash(hasher);
}
}
}
@@ -944,11 +1185,33 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard.
// Formats and fingerprints use key order.
commands: Arc<CommandBindings>,
// Derive the ordinary hash and emit the specialized fingerprint in the
// same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state {
($( $(#[$metadata:meta])* $access:vis $field:ident: $ty:ty, )*) => {
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard.
commands: Arc<CommandBindings>,
$( $(#[$metadata])* $access $field: $ty, )*
}
impl State {
pub fn fingerprint(&self) -> u64 {
self.fingerprint_with_prior(None)
}
pub(super) fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 {
let mut hash = FingerprintHasher::default();
self.commands.hash_fingerprint(&mut hash, prior.map(|prior| prior.commands.as_ref()));
$(self.$field.hash(&mut hash);)*
hash.finish()
}
}
};
}
define_state! {
catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>,
toks: BTreeMap<u16, Vec<Token>>,
@@ -1031,46 +1294,6 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl Hasher for FingerprintHasher {
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
#[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex();
@@ -1096,6 +1319,304 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
check(&state);
}
#[test]
fn state_fingerprint_resumes_before_the_first_changed_binding() {
let direct = |state: &State| {
let mut hasher = DefaultHasher::new();
state.hash(&mut hasher);
hasher.finish()
};
let mut original = State { commands: Arc::default(), ..State::default() };
let stride = COMMAND_HASH_CHECKPOINT_STRIDE;
let name = |index| CommandName::Control(format!("binding-{index:04}"));
for index in 0..stride * 3 {
original.define(name(index), Meaning::Count(0), true);
}
let original_hash = original.fingerprint();
let mut registers_only = original.clone();
registers_only.counts.insert(101, 7);
assert_eq!(registers_only.fingerprint(), direct(&registers_only));
assert_ne!(registers_only.fingerprint(), original_hash);
let mut revised = original.clone();
let edited = stride * 2 + 3;
revised.define(name(edited), Meaning::Count(1), true);
assert!(revised.commands.hash_checkpoints.get().is_none());
assert_eq!(revised.commands.first_changed_binding(&original.commands), Some(edited));
let revised_hash = revised.fingerprint_with_prior(Some(&original));
assert_eq!(revised_hash, direct(&revised));
assert_ne!(revised_hash, original_hash);
assert_eq!(revised.fingerprint(), revised_hash);
assert_eq!(original.fingerprint(), original_hash);
// A mutation in place must clear the computed checkpoints as well.
revised.define(name(0), Meaning::Count(2), true);
assert!(revised.commands.hash_checkpoints.get().is_none());
assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised));
revised.command_bindings_mut().remove(&name(0));
assert!(revised.commands.first_changed_binding(&original.commands).is_none());
assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised));
}
#[test]
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
use super::Span;
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
let fingerprint = state.fingerprint();
assert_eq!(fingerprint, direct.finish());
fingerprint
};
let first = CommandName::Control("测试命令".into());
let alias = CommandName::Control("命令别名".into());
let mut token = Token::new(
TokenKind::Command(CommandName::Control("αβγ".into())),
Span { source: 2, start: 40, end: 44 },
);
token.invocation = Some(Span { source: 3, start: 99, end: 101 });
let mut body = Arc::new(Macro {
prefix: vec![TokenKind::Character('木', CatCode::Letter)],
parameters: vec![vec![TokenKind::Character('λ', CatCode::Other)]],
parameter_chars: vec!['#'],
replacement: vec![Replacement::Token(token.clone()); 80],
long: true,
outer: false,
protected: true,
});
let mut state = State::default();
state.define(first.clone(), Meaning::Macro(body.clone()), true);
state.define(alias, Meaning::Macro(body.clone()), true);
let original = check(&state);
assert_eq!(Arc::weak_count(&body), 1);
assert_eq!(check(&state), original);
let donor = state.clone();
token.invocation = Some(Span { source: 3, start: 111, end: 113 });
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token.clone());
state.define(first.clone(), Meaning::Macro(body.clone()), true);
assert_ne!(check(&state), original);
assert_eq!(check(&donor), original);
assert_eq!(Arc::weak_count(&body), 1);
token.kind = TokenKind::Command(CommandName::Control("λ".repeat(40_000)));
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
state.define(first, Meaning::Macro(body), true);
let uncached = check(&state);
state.command_bindings_mut().hash_checkpoints.take();
let _held = state.commands.fingerprint_inputs.lock().unwrap();
assert_eq!(state.fingerprint(), uncached);
}
#[test]
fn paired_statistics_keep_aliases_from_changed_to_shared_command_shards() {
use super::statistics::Collector;
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let independent = Arc::new(body.as_ref().clone());
let first = CommandName::Control("common-definition".into());
let second = CommandName::Control("other-common-definition".into());
let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name));
let shared_shards = [shard(&first), shard(&second)];
let edited = (0..COMMAND_SHARDS)
.map(|index| CommandName::Control(format!("edited-alias-{index}")))
.find(|name| !shared_shards.contains(&shard(name)))
.unwrap();
let mut prior = State::default();
prior.define(first, Meaning::Macro(body.clone()), true);
prior.define(second, Meaning::Macro(independent.clone()), true);
prior.define(edited.clone(), Meaning::Macro(body), true);
let mut current = prior.clone();
current.define(edited, Meaning::Macro(independent), true);
assert_eq!(current, prior);
let history = Collector::default();
let (new_counts, old_counts) = current
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert_eq!(new_counts.usage, old_counts.usage);
assert!(!new_counts.has_equivalent_history(&old_counts, &history, &history));
let (same, old_counts) = prior
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert!(same.has_equivalent_history(&old_counts, &history, &history));
}
#[test]
fn paired_statistics_keep_aliases_within_changed_command_shards() {
use super::statistics::Collector;
let first_body = Arc::new(Macro {
prefix: vec![TokenKind::Character('P', CatCode::Letter)],
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let second_body = Arc::new(first_body.as_ref().clone());
let mut names_by_shard: [Vec<CommandName>; COMMAND_SHARDS] = std::array::from_fn(|_| Vec::new());
// At least one shard gets nine names, regardless of the process hash seed.
for index in 0..=8 * COMMAND_SHARDS {
let name = CommandName::Control(format!("paired-binding-{index}"));
let shard = CommandBindings::shard_index(command_hasher().hash_one(&name));
names_by_shard[shard].push(name);
}
let (index, names) = names_by_shard
.into_iter()
.enumerate()
.find(|(_, names)| names.len() >= 9)
.unwrap();
let mut prior = State::default();
let [first, second, edited, rest @ ..] = names.as_slice() else {
unreachable!();
};
prior.define(first.clone(), Meaning::Macro(first_body.clone()), true);
prior.define(second.clone(), Meaning::Macro(second_body.clone()), true);
prior.define(edited.clone(), Meaning::Macro(first_body), true);
for name in rest {
prior.define(name.clone(), Meaning::Count(0), true);
}
let original = prior.commands.shard(index);
let mut matching = prior.clone();
let matching_shard = matching.command_bindings_mut().shard_mut(index);
assert!(original.entries.keys().eq(matching_shard.entries.keys()));
let mut reordered = matching.clone();
let changed = reordered.command_bindings_mut().shard_mut(index);
for capacity in [32, 64, 128, 256, 512, 1024] {
changed.entries.reserve(capacity);
if !original.entries.keys().eq(changed.entries.keys()) {
break;
}
}
assert!(!original.entries.keys().eq(changed.entries.keys()));
let history = Collector::default();
let counts = |state: &State| {
let (live, old_live) = state
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
let mut expected = Collector::default();
state.collect_statistics(&mut expected);
assert_eq!(live.usage, expected.usage);
assert_eq!(live.usage, old_live.usage);
live.has_equivalent_history(&old_live, &history, &history)
};
for (mut current, expect_same_order) in [(matching, true), (reordered, false)] {
assert!(!Arc::ptr_eq(original, current.commands.shard(index)));
assert_eq!(current, prior);
assert!(counts(&current));
let changed = current.command_bindings_mut().shard_mut(index);
*changed.entries.get_mut(edited).unwrap() = Meaning::Macro(second_body.clone());
assert_eq!(original.entries.keys().eq(changed.entries.keys()), expect_same_order);
assert_eq!(current, prior);
assert!(!counts(&current));
}
}
#[test]
fn command_shard_equality_checks_values_in_matching_bucket_order() {
let mut before = CommandShard::new(command_hasher().clone());
let name = Arc::new(CommandName::Control("first".into()));
before.insert(name.clone(), Meaning::Count(3));
before.insert(Arc::new(CommandName::Control("second".into())), Meaning::Count(7));
let mut after = before.clone();
assert_eq!(before, after);
*after.entries.get_mut(&name).unwrap() = Meaning::Count(7);
assert!(before.entries.keys().eq(after.entries.keys()));
assert_ne!(before, after);
}
#[test]
fn command_shard_equality_matches_keys_when_bucket_order_differs() {
let mut before = CommandShard::new(command_hasher().clone());
for index in 0..32 {
before.insert(
Arc::new(CommandName::Control(format!("binding-{index}"))),
Meaning::Count(index),
);
}
// Find a genuinely different iteration order for these same bindings
// without depending on a particular hashbrown bucket layout.
let mut after = (0..16)
.find_map(|_| {
let mut candidate = CommandShard::new(RandomState::new());
for (name, meaning) in &before.entries {
candidate.insert(name.clone(), meaning.clone());
}
(!before.entries.keys().eq(candidate.entries.keys())).then_some(candidate)
})
.expect("different hash seeds should give different bucket orders");
assert_eq!(before, after);
let (name, _) = before.entries.keys().zip(after.entries.keys())
.find(|(name, other_name)| name != other_name)
.unwrap();
*after.entries.get_mut(name).unwrap() = Meaning::Count(100);
assert_ne!(before, after);
}
#[test]
fn reinstalling_a_shared_binding_preserves_its_allocation_and_epoch() {
let name = CommandName::Control("sharedbinding".into());
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let mut state = State::default();
state.define(name.clone(), Meaning::Macro(body.clone()), true);
let prior = state.clone();
let hash = command_hasher().hash_one(&name);
let index = CommandBindings::shard_index(hash);
let key = state.commands.get_hashed_entry(&name, hash).unwrap().0.clone();
assert!(Arc::ptr_eq(&key, &state.cache_meaning_hashed(&name, hash).0));
state.define(name.clone(), Meaning::Macro(body.clone()), true);
assert!(Arc::ptr_eq(state.commands.shard(index), prior.commands.shard(index)));
assert_eq!(state.command_revision(hash), prior.command_revision(hash));
let independent = Arc::new(body.as_ref().clone());
state.define(name.clone(), Meaning::Macro(independent.clone()), true);
assert!(!Arc::ptr_eq(state.commands.shard(index), prior.commands.shard(index)));
assert_eq!(state.command_revision(hash), prior.command_revision(hash) + 1);
let Meaning::Macro(installed) = state.meaning(&name) else { panic!("expected macro") };
assert!(Arc::ptr_eq(&installed, &independent));
assert_eq!(state, prior);
state.begin_group(GroupKind::Simple, None);
state.define(name.clone(), Meaning::Count(5), false);
let local = state.clone();
let saved = Key::Command(name.clone());
assert!(state.groups.last().unwrap().saved.contains_key(&saved));
state.define(name, Meaning::Count(5), true);
assert!(Arc::ptr_eq(state.commands.shard(index), local.commands.shard(index)));
assert!(!state.groups.last().unwrap().saved.contains_key(&saved));
}
#[test]
fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let mut state = State::initex().with_etex();
@@ -1106,9 +1627,14 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
state.define(name.clone(), Meaning::Count(7), true);
assert_eq!(snapshot.meaning(&name), Meaning::Count(3));
assert_eq!(state.meaning(&name), Meaning::Count(7));
let shared = state.commands.shards.iter().zip(&snapshot.commands.shards)
let shared = state.commands.shards().zip(snapshot.commands.shards())
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
assert_eq!(shared, COMMAND_SHARDS - 1);
let shared_groups = state.commands.shard_groups.iter().zip(&snapshot.commands.shard_groups)
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
assert_eq!(shared_groups, COMMAND_SHARD_GROUPS - 1);
let hash = command_hasher().hash_one(&name);
assert_eq!(state.command_revision(hash), snapshot.command_revision(hash) + 1);
assert!(Arc::ptr_eq(
&state.commands.ordered_names,
&snapshot.commands.ordered_names,
@@ -1610,6 +2136,94 @@ impl Default for State {
impl State {
pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) {
if !c.material_only() {
c.usage.state.command_entries = self.commands.len();
for (name, meaning) in self.commands.iter() {
Self::collect_command_statistics(c, name, meaning);
}
}
self.collect_state_storage(c);
}
pub(super) fn collect_compared_statistics(
&self,
old: &Self,
mut current_usage: super::statistics::Collector,
) -> Option<(super::statistics::Collector, super::statistics::Collector)> {
let mut old_usage = if current_usage.material_only() {
current_usage.clone()
} else {
current_usage.usage.state.command_entries = old.commands.len();
let mut changed_macros = Vec::new();
for (current, prior) in self.commands.shards().zip(old.commands.shards()) {
if current.entries.len() != prior.entries.len() {
return None;
}
if Arc::ptr_eq(current, prior) {
for (name, meaning) in &prior.entries {
Self::collect_command_statistics(&mut current_usage, name, meaning);
}
continue;
}
let mut ordered = Some(current.entries.iter());
for (name, old_meaning) in &prior.entries {
let meaning = match ordered.as_mut().and_then(Iterator::next) {
Some((current_name, meaning)) if name == current_name => meaning,
_ => {
ordered = None;
current.entries.get(name)?
}
};
if let CommandName::Control(name) = name.as_ref() {
current_usage.usage.state.control_name_bytes += name.len();
}
match (meaning, old_meaning) {
(Meaning::Macro(body), Meaning::Macro(old_body)) => {
current_usage.usage.state.macro_bindings += 1;
if Arc::ptr_eq(body, old_body) {
current_usage.macro_body(body);
} else {
changed_macros.push((body, old_body));
}
}
// Settled suffixes already require equal live meanings.
(Meaning::Macro(_), _) | (_, Meaning::Macro(_)) => return None,
_ => {}
}
}
}
// The same permutation on both sides leaves the alias proof
// intact. Record common allocations first so a later reference
// to any of them still has the original ordinal on both sides.
let mut old_usage = current_usage.clone();
for (body, old_body) in changed_macros {
current_usage.macro_body(body);
old_usage.macro_body(old_body);
}
old_usage
};
self.collect_state_storage(&mut current_usage);
old.collect_state_storage(&mut old_usage);
Some((current_usage, old_usage))
}
fn collect_command_statistics(
c: &mut super::statistics::Collector,
name: &CommandName,
meaning: &Meaning,
) {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
}
fn collect_state_storage(&self, c: &mut super::statistics::Collector) {
use super::statistics::Ownership::Active;
for b in self.boxes.values() {
c.native_box(b, Active);
@@ -1622,26 +2236,6 @@ impl State {
}
return;
}
c.usage.state.command_entries = self.commands.len();
let track_aliases = c.tracks_aliases();
let mut visit_command = |name: &CommandName, meaning: &Meaning| {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
};
if track_aliases {
for (name, meaning) in self.commands.ordered() {
visit_command(name, meaning);
}
} else {
for (name, meaning) in self.commands.iter() {
visit_command(name, meaning);
}
}
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
c.usage.state.parameter_entries =
self.parameters.len() + self.token_parameters.len() + self.job_parameters.len();
@@ -2483,9 +3077,10 @@ impl State {
let state = Self::initex().with_input_profile(self.input_profile);
let state = if extended { state.with_etex() } else { state };
Arc::unwrap_or_clone(state.commands)
.shards
.shard_groups
.into_iter()
.flat_map(Arc::unwrap_or_clone)
.flat_map(|group| Arc::unwrap_or_clone(group).shards)
.flat_map(|shard| Arc::unwrap_or_clone(shard).entries)
.filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) {
CommandName::Control(name) => Some((name, meaning)),
_ => None,
@@ -2501,7 +3096,8 @@ impl State {
}
pub(super) fn command_revision(&self, hash: u64) -> u64 {
self.commands.revisions[CommandBindings::shard_index(hash)]
let index = CommandBindings::shard_index(hash);
self.commands.shard_groups[index / COMMAND_SHARDS_PER_GROUP].revisions[index % COMMAND_SHARDS_PER_GROUP]
}
pub fn meaning(&self, name: &CommandName) -> Meaning {
@@ -2509,14 +3105,37 @@ impl State {
}
pub(super) fn meaning_hashed(&self, name: &CommandName, hash: u64) -> Meaning {
match name {
self.resolve_meaning_hashed(name, hash).1
}
pub(super) fn cache_meaning_hashed(
&self,
name: &CommandName,
hash: u64,
) -> (Arc<CommandName>, Meaning) {
let (key, meaning) = self.resolve_meaning_hashed(name, hash);
(key.cloned().unwrap_or_else(|| Arc::new(name.clone())), meaning)
}
fn resolve_meaning_hashed(
&self,
name: &CommandName,
hash: u64,
) -> (Option<&Arc<CommandName>>, Meaning) {
let meaning = match name {
CommandName::FrozenRelax => Meaning::Primitive(Primitive::Relax),
CommandName::FrozenPrimitivePrefix => Meaning::Primitive(Primitive::DeferredPrimitive),
CommandName::FrozenPrimitive(_) => self.original_primitive(name)
.map(|(_, meaning)| meaning.clone()).unwrap_or(Meaning::Undefined),
CommandName::Font(font) => Meaning::Font(*font),
_ => self.commands.get_hashed(name, hash).cloned().unwrap_or(Meaning::Undefined),
}
_ => {
if let Some((key, meaning)) = self.commands.get_hashed_entry(name, hash) {
return (Some(key), meaning.clone());
}
Meaning::Undefined
}
};
(None, meaning)
}
/// Classic projection for byte-table consumers. A code outside the
/// representable classic range has TeX's recovery value of zero.
@@ -2712,11 +3331,6 @@ impl State {
}
}
pub fn fingerprint(&self) -> u64 {
let mut hash = FingerprintHasher::default();
self.hash(&mut hash);
hash.finish()
}
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
self.groups.push(Group {
kind,
@@ -0,0 +1,210 @@
use super::{Macro, Meaning};
use std::{
collections::HashMap,
fmt,
hash::{DefaultHasher, Hash, Hasher},
sync::{Arc, Weak},
};
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
pub(super) struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl FingerprintHasher {
// The checkpoint represents exactly the bytes already written, including
// the partial buffer. It is always resumed at a complete binding boundary.
pub(super) fn checkpoint(&mut self) -> DefaultHasher {
if self.used > 0 {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
self.hasher.clone()
}
pub(super) fn restore(&mut self, checkpoint: &DefaultHasher) {
self.hasher = checkpoint.clone();
self.used = 0;
}
#[inline]
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
if N > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
let end = self.used + N;
self.buffer[self.used..end].copy_from_slice(&bytes);
self.used = end;
}
}
impl Hasher for FingerprintHasher {
#[inline]
fn write_u8(&mut self, value: u8) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u16(&mut self, value: u16) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u32(&mut self, value: u32) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u64(&mut self, value: u64) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_usize(&mut self, value: usize) {
self.write_fixed(value.to_ne_bytes());
}
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
const MAX_CACHED_BYTES: usize = 16 * 1024 * 1024;
const MAX_CACHED_MACROS: usize = 8192;
const MAX_RECORDED_BYTES: usize = 64 * 1024;
const MIN_REPLACEMENT_TOKENS: usize = 8;
struct MacroInput {
// Keep the allocation address reserved while its bytes are cached,
// without keeping the definition or its token storage alive.
body: Weak<Macro>,
bytes: Option<Box<[u8]>>,
}
#[derive(Default)]
pub(super) struct MacroFingerprintInputs {
inputs: HashMap<usize, MacroInput>,
bytes: usize,
}
impl fmt::Debug for MacroFingerprintInputs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MacroFingerprintInputs")
.field("entries", &self.inputs.len())
.field("bytes", &self.bytes)
.finish()
}
}
impl MacroFingerprintInputs {
fn full(&self) -> bool {
self.bytes >= MAX_CACHED_BYTES || self.inputs.len() >= MAX_CACHED_MACROS
}
pub(super) fn prune_if_full(&mut self) {
if self.full() {
self.inputs.retain(|_, input| {
let live = input.body.strong_count() > 0;
if !live {
self.bytes -= input.bytes.as_deref().map_or(0, <[u8]>::len);
}
live
});
}
}
pub(super) fn hash_meaning(&mut self, meaning: &Meaning, hasher: &mut FingerprintHasher) {
let Meaning::Macro(body) = meaning else {
meaning.hash(hasher);
return;
};
if body.replacement.len() < MIN_REPLACEMENT_TOKENS {
meaning.hash(hasher);
return;
}
let key = Arc::as_ptr(body) as usize;
if let Some(input) = self.inputs.get(&key) {
if let Some(bytes) = &input.bytes {
hasher.write(bytes);
} else {
meaning.hash(hasher);
}
return;
}
if self.full() {
meaning.hash(hasher);
return;
}
// Record the complete Meaning hash, including its enum tag. Replay
// only to FingerprintHasher, whose integer, length, and string writes
// consume the same ordered bytes as the recorder's default methods.
let mut record = HashInput::default();
meaning.hash(&mut record);
let mut bytes = None;
if record.overflow {
meaning.hash(hasher);
} else {
hasher.write(&record.bytes);
if record.bytes.len() <= MAX_CACHED_BYTES - self.bytes {
self.bytes += record.bytes.len();
bytes = Some(record.bytes.into_boxed_slice());
} else {
return;
}
}
self.inputs.insert(key, MacroInput { body: Arc::downgrade(body), bytes });
}
}
#[derive(Default)]
struct HashInput {
bytes: Vec<u8>,
overflow: bool,
}
impl Hasher for HashInput {
fn write(&mut self, bytes: &[u8]) {
if !self.overflow {
if bytes.len() > MAX_RECORDED_BYTES - self.bytes.len() {
self.overflow = true;
} else {
self.bytes.extend_from_slice(bytes);
}
}
}
fn finish(&self) -> u64 {
unreachable!("recording a macro writes hash input without finishing a digest")
}
}
@@ -1,5 +1,7 @@
use super::*;
use crate::execution::source_relocation_events::EventRelocation;
use crate::execution::{
Span, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
};
use crate::pdf_device::forms::FormContents;
impl State {
@@ -12,13 +14,16 @@ impl State {
let commands = self.commands.clone();
// Copy only shards with a relocated macro. Ordinary format macros
// and macros from the byte-identical prefix keep their allocations.
for (index, shard) in commands.shards.iter().enumerate() {
for (name, meaning) in shard.iter() {
for (index, shard) in commands.shards().enumerate() {
if shard.preserves_source_spans(relocation.map()) {
continue;
}
for (name, meaning) in &shard.entries {
if let Meaning::Macro(body) = meaning {
let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) {
let shard = &mut Arc::make_mut(&mut self.commands).shards[index];
Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated));
self.command_bindings_mut().shard_mut(index)
.insert(name.clone(), Meaning::Macro(relocated));
}
}
}
@@ -97,9 +102,85 @@ impl State {
}
}
impl CommandShard {
fn preserves_source_spans(&self, relocation: &SourceRelocation) -> bool {
self.source_bounds.get(&relocation.source()).is_none_or(|end| {
end.is_some_and(|end| relocation.preserves_prefix_through(end))
})
}
}
pub(super) fn include_meaning_bounds(
bounds: &mut BTreeMap<usize, Option<usize>>,
meaning: &Meaning,
) {
let Meaning::Macro(body) = meaning else {
return;
};
let mut include = |span: Span| {
let end = bounds.entry(span.source).or_insert(Some(0));
*end = end.filter(|_| span.start <= span.end).map(|end| end.max(span.end));
};
for part in &body.replacement {
if let Replacement::Token(token) = part {
include(token.span);
if let Some(invocation) = token.invocation {
include(invocation);
}
}
}
}
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
for token in tokens {
relocation.relocate_token(token)?;
}
Some(())
}
#[test]
fn command_bounds_track_redefinitions_and_invocation_origins() {
use crate::execution::CatCode;
let map = SourceRelocation::new(0, b"First\nx\nKeep\n", b"First\nlonger\nKeep\n").unwrap();
let name = CommandName::Control("boundtest".into());
let meaning = |invocation| {
let mut token = Token::new(
TokenKind::Character('x', CatCode::Letter),
Span { source: 0, start: 0, end: 1 },
);
token.invocation = invocation;
Meaning::Macro(Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token)],
long: false,
outer: false,
protected: false,
}))
};
let mut state = State::default();
state.define(name.clone(), meaning(None), true);
let shard = CommandBindings::shard_index(command_hasher().hash_one(&name));
assert_eq!(state.commands.shard(shard).source_bounds[&0], Some(1));
let before = state.clone();
let token_span = Span { source: 0, start: 8, end: 9 };
state.define(name.clone(), meaning(Some(token_span)), true);
assert_eq!(state.commands.shard(shard).source_bounds[&0], Some(9));
let prior_hash = state.fingerprint();
let donor = state.clone();
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();
assert!(state.commands.hash_checkpoints.get().is_none());
assert_ne!(state.fingerprint_with_prior(Some(&donor)), prior_hash);
assert_eq!(donor.fingerprint(), prior_hash);
let mapped = map.relocate_span(token_span).unwrap();
assert_ne!(mapped, token_span);
assert_eq!(state.meaning(&name), meaning(Some(mapped)));
assert_eq!(before.meaning(&name), meaning(None));
state.define(name, meaning(Some(Span { source: 0, start: 2, end: 1 })), true);
assert!(state.relocate_source(&mut EventRelocation::new(&map)).is_none());
}
@@ -1,9 +1,7 @@
//! Measured native storage and execution resources, not invented TeX arena words.
use super::*;
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
sync::Arc,
};
use hashbrown::{HashMap, HashSet, hash_map::Entry};
use std::{collections::BTreeSet, sync::Arc};
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MaterialUsage {
@@ -197,6 +195,98 @@ impl BoxNodeOffset {
}
}
#[derive(Clone, Default, PartialEq, Eq)]
struct RetainedHistoryUsage {
material: MaterialUsage,
events: usize,
shipouts: usize,
token_list_cells: usize,
}
impl RetainedHistoryUsage {
fn take_from(usage: &mut ResourceUsage) -> Self {
Self {
material: std::mem::take(&mut usage.retained_material),
events: std::mem::take(&mut usage.retained_events),
shipouts: std::mem::take(&mut usage.retained_shipouts),
token_list_cells: std::mem::take(&mut usage.token_list_cells),
}
}
}
/// The contribution of the replaced prefix to the final resource report.
#[derive(Clone, Default)]
pub(super) struct RetainedHistoryOffset {
previous: RetainedHistoryUsage,
current: RetainedHistoryUsage,
}
impl RetainedHistoryOffset {
pub(super) fn is_identity(&self) -> bool {
self.previous == self.current
}
fn replace_prefix(&self, usage: &mut ResourceUsage) -> Option<()> {
fn replace(total: usize, previous: usize, current: usize) -> Option<usize> {
total.checked_sub(previous)?.checked_add(current)
}
let previous = &self.previous;
let current = &self.current;
let material = &usage.retained_material;
let old = &previous.material;
let new = &current.material;
let material = MaterialUsage {
boxes: replace(material.boxes, old.boxes, new.boxes)?,
horizontal_nodes: replace(material.horizontal_nodes, old.horizontal_nodes, new.horizontal_nodes)?,
vertical_nodes: replace(material.vertical_nodes, old.vertical_nodes, new.vertical_nodes)?,
math_nodes: replace(material.math_nodes, old.math_nodes, new.math_nodes)?,
geometry_items: replace(material.geometry_items, old.geometry_items, new.geometry_items)?,
diagnostic_nodes: replace(material.diagnostic_nodes, old.diagnostic_nodes, new.diagnostic_nodes)?,
ligature_work_items: replace(material.ligature_work_items, old.ligature_work_items, new.ligature_work_items)?,
};
// The final report formats the aggregate with MaterialUsage::records.
[
material.boxes,
material.horizontal_nodes,
material.vertical_nodes,
material.math_nodes,
material.geometry_items,
material.diagnostic_nodes,
material.ligature_work_items,
]
.into_iter()
.try_fold(0usize, usize::checked_add)?;
let events = replace(usage.retained_events, previous.events, current.events)?;
let shipouts = replace(usage.retained_shipouts, previous.shipouts, current.shipouts)?;
let tokens = replace(
usage.token_list_cells, previous.token_list_cells, current.token_list_cells,
)?;
usage.retained_material = material;
usage.retained_events = events;
usage.retained_shipouts = shipouts;
usage.token_list_cells = tokens;
Some(())
}
}
/// Byte counts affected by the sole changed physical source at convergence.
#[derive(Clone, Copy)]
pub(super) struct SuffixSourceResize {
pub(super) sizes: (usize, usize),
pub(super) active_at_anchor: bool,
pub(super) prefix_resource_reads: usize,
}
impl SuffixSourceResize {
pub(super) fn entry(sizes: (usize, usize)) -> Self {
Self {
sizes,
active_at_anchor: true,
prefix_resource_reads: 1,
}
}
}
impl StatisticsReport {
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
let text = phase.text();
@@ -218,7 +308,7 @@ impl StatisticsReport {
if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() {
return None;
}
usage.resize_entry_payload(previous, current, true)?;
usage.resize_source_payload(SuffixSourceResize::entry((previous, current)), true)?;
}
debug_assert_eq!(self.text, self.phase.text());
Some(())
@@ -227,26 +317,9 @@ impl StatisticsReport {
/// Recompute a report for a verified suffix after the initial entry read
/// changed size. The caller authenticates the entry scanner's lifetime.
pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option<Self> {
let mut phase = self.phase.clone();
match &mut phase {
StatisticsPhase::Shipout { before, after } => {
for usage in [before, after] {
let active = usage.mouth_payload_bytes == previous;
if !active && usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, active)?;
}
}
StatisticsPhase::End { usage, .. } => {
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, false)?;
}
}
let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report)
self.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some((previous, current)), None,
)
}
pub fn with_step_offset(&self, offset: StepOffset) -> Option<Self> {
@@ -257,6 +330,26 @@ impl StatisticsReport {
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
) -> Option<Self> {
self.with_suffix_adjustments(steps, boxes, None, None)
}
pub(super) fn with_suffix_adjustments(
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
entry_sizes: Option<(usize, usize)>,
history: Option<&RetainedHistoryOffset>,
) -> Option<Self> {
self.with_source_resize(steps, boxes, entry_sizes.map(SuffixSourceResize::entry), history)
}
pub(super) fn with_source_resize(
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
resize: Option<SuffixSourceResize>,
history: Option<&RetainedHistoryOffset>,
) -> Option<Self> {
let translate = |usage: &mut ResourceUsage| {
usage.steps = steps.apply(usage.steps)?;
@@ -266,10 +359,34 @@ impl StatisticsReport {
let mut phase = self.phase.clone();
match &mut phase {
StatisticsPhase::Shipout { before, after } => {
translate(before)?;
translate(after)?;
if history.is_some_and(|offset| !offset.is_identity()) {
return None;
}
for usage in [before, after] {
translate(usage)?;
if let Some(resize) = resize {
let active = resize.active_at_anchor && usage.mouth_payload_bytes == resize.sizes.0;
if resize.active_at_anchor && !active && usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_source_payload(resize, active)?;
}
}
}
StatisticsPhase::End { usage, .. } => {
translate(usage)?;
if let Some(resize) = resize {
if resize.active_at_anchor
&& (usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0)
{
return None;
}
usage.resize_source_payload(resize, false)?;
}
if let Some(offset) = history {
offset.replace_prefix(usage)?;
}
}
StatisticsPhase::End { usage, .. } => translate(usage)?,
}
let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report)
@@ -287,18 +404,17 @@ impl StatisticsReport {
}
impl ResourceUsage {
fn resize_entry_payload(
&mut self,
previous: usize,
current: usize,
active: bool,
) -> Option<()> {
fn resize_source_payload(&mut self, resize: SuffixSourceResize, active: bool) -> Option<()> {
let (previous, current) = resize.sizes;
self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?;
if active {
self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?;
}
if let Some(host) = &mut self.host {
host.rebind_entry_bytes(u64::try_from(previous).ok()?, u64::try_from(current).ok()?)?;
let reads = u64::try_from(resize.prefix_resource_reads).ok()?;
let previous = u64::try_from(previous).ok()?.checked_mul(reads)?;
let current = u64::try_from(current).ok()?.checked_mul(reads)?;
host.rebind_entry_bytes(previous, current)?;
}
Some(())
}
@@ -367,7 +483,7 @@ pub(super) enum Ownership {
Active,
Retained,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Allocation {
Macro(usize),
Tokens(usize, usize),
@@ -376,22 +492,27 @@ enum Allocation {
#[derive(Clone, Default)]
struct AliasVisits {
ordinals: BTreeMap<Allocation, usize>,
ordinals: HashMap<Allocation, usize>,
visits: Vec<(Allocation, usize)>,
}
impl AliasVisits {
fn record(&mut self, allocation: Allocation) {
fn record(&mut self, allocation: Allocation) -> bool {
let next = self.ordinals.len();
let ordinal = *self.ordinals.entry(allocation).or_insert(next);
let (ordinal, first) = match self.ordinals.entry(allocation) {
Entry::Occupied(entry) => (*entry.get(), false),
Entry::Vacant(entry) => (*entry.insert(next), true),
};
self.visits.push((allocation, ordinal));
first
}
}
#[derive(Clone, Default)]
pub(super) struct Collector {
pub usage: ResourceUsage,
// Alias visits keep traversal order separately from this membership index.
// A tracked visit uses its ordinal index for deduplication. The
// membership sets cover normal collection and any visits before tracking.
macros: HashSet<usize>,
token_lists: BTreeSet<(usize, usize)>,
shared_lists: Option<BTreeSet<usize>>,
@@ -406,21 +527,14 @@ impl Collector {
}
pub(super) fn tracking_aliases(mut self) -> Self {
self.aliases = Some(AliasVisits::default());
self.aliases.get_or_insert_with(AliasVisits::default);
self
}
pub(super) fn tracks_aliases(&self) -> bool {
self.aliases.is_some()
}
fn tracks_allocation(&mut self, allocation: Allocation) {
if let Some(aliases) = &mut self.aliases {
aliases.record(allocation);
}
}
fn contains(&self, allocation: Allocation) -> bool {
if self.aliases.as_ref().is_some_and(|aliases| aliases.ordinals.contains_key(&allocation)) {
return true;
}
match allocation {
Allocation::Macro(address) => self.macros.contains(&address),
Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)),
@@ -431,19 +545,47 @@ impl Collector {
}
}
/// Check the live allocation correspondence and each allocation's
/// membership in the retained history. Counting a later event can
/// encounter older storage only through these surviving references.
pub(super) fn has_equivalent_history(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> bool {
history.usage == old_history.usage && self.same_live_history(other, history, old_history)
}
/// Compare separately collected live state and retained events. The
/// caller must prove that the suffix cannot recount capacity.
pub(super) fn retained_history_offset(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> Option<RetainedHistoryOffset> {
if self.material_only() || other.material_only()
|| history.material_only() || old_history.material_only()
|| !self.same_live_history(other, history, old_history)
{
return None;
}
let mut usage = history.usage.clone();
let mut old_usage = old_history.usage.clone();
let current = RetainedHistoryUsage::take_from(&mut usage);
let previous = RetainedHistoryUsage::take_from(&mut old_usage);
(usage == old_usage).then_some(RetainedHistoryOffset { previous, current })
}
/// Later events can reach old storage only through allocations that
/// survive in live state. Keep both their alias order and history membership.
fn same_live_history(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> bool {
let a = &self.aliases.as_ref().expect("live alias traversal").visits;
let b = &other.aliases.as_ref().expect("live alias traversal").visits;
self.usage == other.usage
&& history.usage == old_history.usage
&& a.len() == b.len()
&& a.iter().zip(b).all(|(&(new, ni), &(old, oi))| {
ni == oi
@@ -458,8 +600,13 @@ impl Collector {
pub fn macro_body(&mut self, m: &Arc<Macro>) {
let address = Arc::as_ptr(m) as usize;
self.tracks_allocation(Allocation::Macro(address));
if self.macros.insert(address) {
let first = if let Some(aliases) = &mut self.aliases {
aliases.record(Allocation::Macro(address))
&& (self.macros.is_empty() || !self.macros.contains(&address))
} else {
self.macros.insert(address)
};
if first {
self.usage.unique_macro_bodies += 1;
self.usage.macro_token_cells += m.prefix.len()
+ m.parameters.iter().map(Vec::len).sum::<usize>()
@@ -468,11 +615,15 @@ impl Collector {
}
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
let address = t.as_ptr() as usize;
if !t.is_empty() {
self.tracks_allocation(Allocation::Tokens(address, t.len()));
}
if self.token_lists.insert((address, t.len())) {
self.usage.token_list_cells += t.len();
let len = t.len();
let first = if let Some(aliases) = &mut self.aliases && len != 0 {
aliases.record(Allocation::Tokens(address, len))
&& !self.token_lists.contains(&(address, len))
} else {
self.token_lists.insert((address, len))
};
if first {
self.usage.token_list_cells += len;
}
}
fn material(&mut self, o: Ownership) -> &mut MaterialUsage {
@@ -608,13 +759,15 @@ impl Collector {
self.usage.active_material.ligature_work_items += b.ligature_work_items();
}
fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool {
let Some(seen) = &mut self.shared_lists else {
return true;
};
let address = Arc::as_ptr(list).cast::<()>() as usize;
if self.shared_lists.is_some() {
self.tracks_allocation(Allocation::Material(address));
if let Some(aliases) = &mut self.aliases {
aliases.record(Allocation::Material(address)) && !seen.contains(&address)
} else {
seen.insert(address)
}
self.shared_lists
.as_mut()
.is_none_or(|seen| seen.insert(address))
}
pub fn shared_diagnostics(
@@ -692,6 +845,185 @@ mod tests {
);
}
#[test]
fn suffix_adjustments_check_only_the_final_diagnostic_budget() {
let report = |usage| {
StatisticsReport::new(
StatisticsPhase::End { success: true, usage },
WriteDestination::Log,
Span::default(),
)
};
let mut usage = ResourceUsage {
steps: 9,
source_payload_bytes: 10,
..ResourceUsage::default()
};
usage.token_limit = report(usage.clone()).text.len();
let original = report(usage.clone());
let steps = StepOffset::new(0, 1);
assert!(original.with_step_offset(steps).is_none());
usage.steps = 10;
usage.source_payload_bytes = 9;
assert_eq!(
original.with_suffix_adjustments(
steps, BoxNodeOffset::new(0, 0), Some((10, 9)), None,
),
Some(report(usage))
);
}
#[test]
fn retained_history_offsets_require_shared_token_membership() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let retained: Arc<[Token]> = Arc::from([token.clone()]);
let old_retained: Arc<[Token]> = Arc::from([token.clone()]);
let extra: Arc<[Token]> = Arc::from([token.clone(), token]);
let mut live = Collector::default().tracking_aliases();
live.shared_tokens(&retained);
let mut old_live = Collector::default().tracking_aliases();
old_live.shared_tokens(&old_retained);
let mut history = Collector::default();
history.shared_tokens(&retained);
history.shared_tokens(&extra);
history.usage.retained_events = 3;
history.usage.retained_material.horizontal_nodes = 5;
let mut old_history = Collector::default();
old_history.shared_tokens(&old_retained);
old_history.usage.retained_events = 2;
old_history.usage.retained_material.horizontal_nodes = 1;
assert!(!live.has_equivalent_history(&old_live, &history, &old_history));
let offset = live.retained_history_offset(&old_live, &history, &old_history).unwrap();
assert!(!offset.is_identity());
assert!(
old_live.retained_history_offset(&old_live, &history, &old_history).is_none()
);
let mut usage = ResourceUsage {
token_list_cells: 8,
retained_events: 4,
retained_material: MaterialUsage { horizontal_nodes: 3, ..MaterialUsage::default() },
token_limit: 4096,
..ResourceUsage::default()
};
let report = StatisticsReport::new(
StatisticsPhase::End { success: true, usage: usage.clone() },
WriteDestination::Log,
Span::default(),
);
usage.token_list_cells = 10;
usage.retained_events = 5;
usage.retained_material.horizontal_nodes = 7;
assert_eq!(
report.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
).unwrap(),
StatisticsReport::new(
StatisticsPhase::End { success: true, usage },
WriteDestination::Log,
Span::default(),
)
);
let overflow = StatisticsReport::new(
StatisticsPhase::End {
success: true,
usage: ResourceUsage {
retained_material: MaterialUsage {
boxes: usize::MAX - 1,
horizontal_nodes: 1,
..MaterialUsage::default()
},
token_limit: 4096,
..old_history.usage
},
},
WriteDestination::Log,
Span::default(),
);
assert!(overflow.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
).is_none());
}
#[test]
fn closed_source_resize_counts_each_host_read_and_leaves_other_mouths() {
let usage = ResourceUsage {
source_payload_bytes: 50,
mouth_payload_bytes: 30,
host: Some(HostResourceUsage {
resource_reads: 5,
resource_bytes_read: 100,
..HostResourceUsage::default()
}),
token_limit: 4096,
..ResourceUsage::default()
};
let resize = SuffixSourceResize {
sizes: (8, 11),
active_at_anchor: false,
prefix_resource_reads: 3,
};
let report = StatisticsReport::new(
StatisticsPhase::Shipout { before: usage.clone(), after: usage },
WriteDestination::Log,
Span::default(),
);
let adjusted = report.with_source_resize(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some(resize), None,
).unwrap();
assert_eq!(adjusted.text, report.text);
let StatisticsPhase::Shipout { before, after } = adjusted.phase else {
unreachable!();
};
for usage in [before, after] {
assert_eq!(usage.source_payload_bytes, 53);
assert_eq!(usage.mouth_payload_bytes, 30);
let host = usage.host.unwrap();
assert_eq!(host.resource_reads, 5);
assert_eq!(host.resource_bytes_read, 109);
}
}
#[test]
fn tracked_macro_counts_share_the_ordinal_index_without_losing_visits() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token.clone())],
long: false,
outer: false,
protected: false,
});
let independent = Arc::new((*body).clone());
let tokens: Arc<[Token]> = Arc::from([token]);
let mut history = Collector::default();
let mut live = Collector::default().tracking_aliases();
for collector in [&mut history, &mut live] {
collector.macro_body(&body);
collector.shared_tokens(&tokens);
collector.macro_body(&body);
collector.macro_body(&independent);
}
assert_eq!(live.usage, history.usage);
assert_eq!(live.usage.unique_macro_bodies, 2);
assert!(live.macros.is_empty());
assert!(live.token_lists.is_empty());
let visits = &live.aliases.as_ref().unwrap().visits;
assert_eq!(visits.iter().map(|(_, ordinal)| *ordinal).collect::<Vec<_>>(), [0, 1, 0, 2]);
assert!(visits.iter().all(|(allocation, _)| {
history.contains(*allocation) && live.contains(*allocation)
}));
let mut previously_counted = history.clone().tracking_aliases();
previously_counted.macro_body(&body);
assert_eq!(previously_counted.usage, history.usage);
}
#[test]
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
+96 -5
View File
@@ -176,6 +176,49 @@ struct NativeSvgGlyph<'a> {
scalable: bool,
}
#[derive(Default)]
struct NativeSvgOutlines<'a> {
ids: std::collections::HashMap<&'a str, Option<usize>>,
definitions: Vec<&'a str>,
}
impl<'a> NativeSvgOutlines<'a> {
fn observe(&mut self, path: &'a str) {
// Even two instances of a long outline pay for the definition and
// references. Keep short and one-off paths inline.
if path.len() < 128 {
return;
}
use std::collections::hash_map::Entry;
match self.ids.entry(path) {
Entry::Vacant(entry) => {
entry.insert(None);
}
Entry::Occupied(mut entry) if entry.get().is_none() => {
entry.insert(Some(self.definitions.len()));
self.definitions.push(path);
}
Entry::Occupied(_) => {}
}
}
fn id(&self, path: &str) -> Option<usize> {
self.ids.get(path).copied().flatten()
}
fn write_definitions(&self, out: &mut String) {
if self.definitions.is_empty() {
return;
}
use std::fmt::Write as _;
out.push_str("<defs>\n");
for (id, path) in self.definitions.iter().enumerate() {
writeln!(out, "<path id=\"native-outline-{id}\" d=\"{path}\"/>").unwrap();
}
out.push_str("</defs>\n");
}
}
impl DisplayItem {
fn native_svg_glyph(&self) -> Option<Result<NativeSvgGlyph<'_>, String>> {
let Self::NativeGlyph {
@@ -573,12 +616,23 @@ impl DisplayList {
.expect("SVG display list cannot be rendered")
}
pub fn try_to_svg(&self) -> Result<String, String> {
self.render_svg(false)
}
/// Render a page preview with shared definitions for repeated native outlines.
#[doc(hidden)]
pub fn try_to_preview_svg(&self) -> Result<String, String> {
self.render_svg(true)
}
fn render_svg(&self, share_native_outlines: bool) -> Result<String, String> {
if !(1..=32768).contains(&self.magnification) {
return Err("invalid display-list magnification".into());
}
if self.has_embedded_pdf() {
return Err("this page requires a PDF renderer".into());
}
let mut outlines = share_native_outlines.then(NativeSvgOutlines::default);
for item in &self.items {
if let DisplayItem::PdfColor { program, .. } = item
&& program
@@ -589,12 +643,16 @@ impl DisplayList {
return Err("unresolved PDF graphics state in SVG page".into());
}
if let Some(glyph) = item.native_svg_glyph() {
glyph?;
let glyph = glyph?;
if let Some(outlines) = &mut outlines {
outlines.observe(glyph.path);
}
}
}
self.svg_with_resolved_fonts()
self.svg_with_resolved_fonts(outlines.as_ref())
}
fn svg_with_resolved_fonts(&self) -> Result<String, String> {
fn svg_with_resolved_fonts(&self, outlines: Option<&NativeSvgOutlines<'_>>) -> Result<String, String> {
let width = self.width as f64 / 65_536.0;
let height = self.height as f64 / 65_536.0;
let mag = f64::from(self.magnification) / 1000.0
@@ -641,6 +699,9 @@ impl DisplayList {
}
out.push_str("</defs>\n");
}
if let Some(outlines) = outlines {
outlines.write_definitions(&mut out);
}
let mut opentype_paths = std::collections::BTreeMap::new();
let mut opentype_faces = std::collections::BTreeMap::new();
let mut fill = [0u8, 0, 0];
@@ -697,9 +758,14 @@ impl DisplayList {
use std::fmt::Write as _;
write!(
out,
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"",
escape_attribute(font), escape_attribute(glyph), escape_attribute(&label), path,
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\">",
escape_attribute(font), escape_attribute(glyph), escape_attribute(&label),
).unwrap();
if let Some(id) = outlines.and_then(|outlines| outlines.id(path)) {
write!(out, "<use href=\"#native-outline-{id}\" transform=\"").unwrap();
} else {
write!(out, "<path d=\"{path}\" transform=\"").unwrap();
}
if let Some([vx2, vy]) = vertical_origin {
let vx = f64::from(vx2) / 2.0;
let vy = f64::from(vy);
@@ -2580,6 +2646,31 @@ impl Page {
mod tests {
use super::*;
#[test]
fn preview_outline_definitions_share_only_long_repeated_path_text() {
let first = "M0 0L1 1Z".repeat(16);
let second = "M0 0L2 2Z".repeat(16);
let single = "M0 0L3 3Z".repeat(16);
let same_second = second.clone();
let short = "M0 0L4 4Z";
let mut outlines = NativeSvgOutlines::default();
for path in [&first, &single, &second, &same_second, &first, &first] {
outlines.observe(path);
}
outlines.observe(short);
outlines.observe(short);
assert_eq!(outlines.id(&first), Some(1));
assert_eq!(outlines.id(&second), Some(0));
assert_eq!(outlines.id(&single), None);
assert_eq!(outlines.id(short), None);
let mut definitions = String::new();
outlines.write_definitions(&mut definitions);
assert_eq!(definitions, format!(
"<defs>\n<path id=\"native-outline-0\" d=\"{second}\"/>\n<path id=\"native-outline-1\" d=\"{first}\"/>\n</defs>\n"
));
}
#[test]
fn relocates_raw_shipout_origins_without_changing_paint_or_virtual_packets() {
use crate::math_engine_tex::{MathItem, PositionedItem};
+27 -10
View File
@@ -636,6 +636,8 @@ pub struct FileWorld {
staged_generated: BTreeMap<PathBuf, PathBuf>,
/// Actual host resource promotions, never inferred from serialized cache.
protected_paths: BTreeSet<PathBuf>,
// Logical path keys shared by namespace operations within a job.
project_path_keys: OnceLock<BTreeSet<PathBuf>>,
replay_gaps: Vec<String>,
project: Option<Arc<ProjectSnapshot>>,
system_fonts: Option<Result<Vec<named_fonts::NamedFace>, String>>,
@@ -777,6 +779,7 @@ impl FileWorld {
live_paths: BTreeSet::new(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
project_path_keys: OnceLock::new(),
replay_gaps: Vec::new(),
project: None,
system_fonts: None,
@@ -828,6 +831,7 @@ impl FileWorld {
live_paths,
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
project_path_keys: OnceLock::new(),
replay_gaps: Vec::new(),
project: Some(project),
system_fonts: None,
@@ -857,7 +861,7 @@ impl FileWorld {
pub fn check_generated_output(&self, logical: &Path, physical: &Path) -> Result<(), String> {
if let Some(project) = &self.project {
self.check_artifact_output(physical)?;
project.check_generated_output(logical, physical, &self.project_paths())?;
project.check_generated_output(logical, physical, self.project_paths())?;
}
Ok(())
}
@@ -866,8 +870,8 @@ impl FileWorld {
pub fn generated_output_path(&self, logical: &Path) -> Result<PathBuf, String> {
if let Some(project) = &self.project {
let known = self.project_paths();
let target = project.locate(logical, &known)?.path;
project.check_generated_output(logical, &target, &known)?;
let target = project.locate(logical, known)?.path;
project.check_generated_output(logical, &target, known)?;
self.check_artifact_output(&target)?;
Ok(target)
} else {
@@ -919,6 +923,7 @@ impl FileWorld {
.unwrap_or_default(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
project_path_keys: OnceLock::new(),
replay_gaps: Vec::new(),
project: snapshot.project.clone(),
system_fonts: snapshot.system_fonts.clone(),
@@ -961,6 +966,7 @@ impl FileWorld {
));
}
if self.live_paths.insert(path.to_owned()) && self.project.is_some() {
self.project_path_keys.take();
self.current_project_indexes.clear();
}
}
@@ -986,6 +992,9 @@ impl FileWorld {
if self.pinned {
if was_live || self.project.is_some() {
let newly_protected = self.protected_paths.insert(resource.version.path.clone());
if was_live || newly_protected {
self.project_path_keys.take();
}
if self.project.as_ref().is_some_and(|project| {
was_live || (newly_protected && project.file(&resource.version.path).is_none())
}) {
@@ -1063,11 +1072,19 @@ impl FileWorld {
pub fn generated_storage<'a>(&'a self, path: &'a Path) -> &'a Path {
self.staged_generated.get(path).map_or(path, PathBuf::as_path)
}
fn project_paths(&self) -> BTreeSet<PathBuf> {
self.live_paths
.union(&self.protected_paths)
.cloned()
.collect()
fn project_paths(&self) -> &BTreeSet<PathBuf> {
if self.protected_paths.is_empty() {
&self.live_paths
} else if self.live_paths.is_empty() {
&self.protected_paths
} else {
self.project_path_keys.get_or_init(|| {
self.live_paths
.union(&self.protected_paths)
.cloned()
.collect()
})
}
}
fn probe(&mut self, path: &Path) -> Result<Option<PathBuf>, String> {
// PathBuf equality drops `/.` and trailing separators. Such spellings
@@ -1085,7 +1102,7 @@ impl FileWorld {
return Self::existing(path);
}
if let Some(project) = &self.project {
let location = project.locate(path, &self.project_paths())?;
let location = project.locate(path, self.project_paths())?;
let result = if location.kind == Some(project::NodeKind::File) {
if self.live_paths.contains(&location.path) {
if let Some(storage) = self.staged_generated.get(&location.path) {
@@ -1454,7 +1471,7 @@ impl FileWorld {
|| (recursive && !self.indexes[root].recursive)
{
let index =
project.index(root, &self.project_paths(), self.config.max_index_entries, recursive)?;
project.index(root, self.project_paths(), self.config.max_index_entries, recursive)?;
self.indexes.insert(root.into(), Arc::new(index));
self.current_project_indexes.insert(root.into());
}
@@ -447,6 +447,8 @@ fn protected_generated_resources_keep_alias_and_recursive_visibility_without_cac
vec![SearchPath::directory(p.join("gen"), true)],
);
d.generated.insert(p.join("gen/nested/initial.tfm"));
// Retain a live key while the earlier resource is promoted and the next one is added.
d.generated.insert(p.join("gen/nested/kept-live.tfm"));
d.aliases
.insert(p.join("again.tfm"), "gen/nested/initial.tfm".into());
d.aliases
+670
View File
@@ -87,6 +87,676 @@ p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。
原始样本、构建清单、机器状态和逐次输出对照在
`target/p4-a4-browser-recheck/`。
## 2026-12-02 不等长事件历史的后缀复用
发页后即使两版的保留事件数量不同,内核也可以继续核对状态、实际
宿主效果和来源坐标。若后缀可能重算盒容量,或途中还会输出发页统计,
继续要求完全相同的记账历史。只有确认后缀不会重算容量、统计只在
收尾发生,而且跨接缝的分配共享关系一致时,才调整收尾报告中的保留
事件、材料和令牌计数。可继续执行的检查点仍需精确的记账等价证明。
检查点记录依赖最后一次被访问的区间,包含命中缓存的命令查询。
拼接结果保留新版前缀和实际跳过的后缀观测。只在旧前缀出现的观测
可以删除。旧记录缺少区间时继续采用保守规则。
十五项定向管线回归和五项内核单测通过。冻结 A4 的六次主文件改写与各自独立全量的
执行、PDF、SVG、来源、资源和生成文件均一致。五次各跳过 20,618
步后缀,实际执行 32,994 或 32,997 步,较同一组旧样本少约 38.5%。
首个改写仍执行完后缀。该批使用 opt-level 0,成功拼接的核对和
组装仍有额外耗时。原始样本在 `target/p4-a4-suffix-proof/run-tc4ag9tt/`。
### 候选分支的 Edge 复测
同一台机器和同一冻结 A4,主文件与子文件各 30 次实际页面更新。
主文件有 29 次各跳过 20,618 步后缀,子文件的 30 次仍执行后缀。
全部 60 次的 PDF、SVG 和来源映射与主线基线逐项相同。
| A4 热编辑 | 主线可见 p50 / p95 | 候选可见 p50 / p95 |
| --- | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 325.5 / 512.1 ms |
| 子文件正文 | 184.1 / 241.5 ms | 185.4 / 266.7 ms |
候选的主文件实际执行步数 p50 为 35,138,主线为 55,755。
主文件执行阶段 p50 升至 225.6 ms。用同一优化构建单次拆分,
状态比较 31.9 ms、保留记账 66.9 ms、结果组装 68.5 ms。
候选保存在 `perf/retained-history-suffix`。100 ms 门槛仍开放。
浏览器原始记录在 `target/p4-a4-retained-history/`,单次阶段
数据在 `target/p4-a4-suffix-proof/run-qcghpnrj/`。
## 2026-12-02 降低后缀会合的遍历成本
沿候选分支保留不等长事件历史的复用。旧优化版 A4 的带采样诊断
显示,一次成功接缝的记账有约 88 ms 花在两遍实时状态统计,组装
中重算最终指纹约 56 ms,比较中的状态来源换算约 26 ms。原始
作用域数据在 `target/p4-a4-suffix-proof/release-profile/`。
命令表分片保留宏替换文本和调用位置的来源范围。范围严格早于
修改位置时,沿用共享分片。涉及修改区或有异常范围时,继续逐个
换算来源。写入新定义同步扩展范围。匹配两版记账时,字段和命令
键保持逐项对应,用同一遍历顺序核对别名。首次访问和分配去重
共用同一份索引。状态指纹仍按原有命令顺序和字节序列计算。
8 项内核单测和 15 项管线回归通过。冻结 A4 原生对照在两个同配置
优化构建上各跑 3 次,全部与各自独立全量一致,且两版 PDF 指纹相同。
两次成功接缝都跳过 20,618 步。保留记账分别从 64.38 降至 18.65 ms、
从 38.73 降至 18.30 ms。状态比较仍约 30–32 ms,组装仍约 58–64 ms。
阶段原始数据在 `target/p4-a4-shard-relocation/a4-main-only/`。
同机 Edge 实测主文件、子文件各 30 次。主文件 29 次各跳过
20,618 步,子文件仍执行后缀。全部 60 次的 PDF、SVG 和来源映射
指纹与主线基线逐项一致。进程峰值 RSS 为 603,116 KiB。
| A4 热编辑 | 主线可见 p50 / p95 | 上一候选 p50 / p95 | 本轮候选 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 325.5 / 512.1 ms | 285.4 / 497.4 ms |
| 子文件正文 | 184.1 / 241.5 ms | 185.4 / 266.7 ms | 188.4 / 337.5 ms |
本轮候选继续保存在 `perf/retained-history-suffix`。浏览器 100 ms
门槛仍开放。性能记录、构建指纹和逐次结果在
`target/p4-a4-shard-relocation/`。下一轮继续压缩仍占主要时间的
状态指纹,并认证子文件耗尽后的前后缀资源读证据。
## 2026-12-02 复用宏的指纹输入
状态指纹保持现有字段顺序、命令顺序与哈希输入。状态声明与专用
指纹遍历使用同一份字段清单,通用 `Hash` 继续由原有字段派生。
命令表的共享快照可复用完整宏含义写入的字节。缓存使用弱引用保留
分配身份,宏变更时按新分配计算。每个共享命令表的缓存受字节量与
条目数限制。锁占用及超限场景走原计算路径。格式镜像和对外执行
记录仍使用原来的字段。每套共享命令表最多保留 16 MiB 哈希字节
和 8,192 个宏条目。
7 项内核单测和 15 项管线回归通过。两版优化构建的三次冻结 A4
编辑全部与独立全量一致,六个输入和输出指纹逐项相同。两次成功
接缝仍各跳过 20,618 步,组装从 68.34、55.52 ms 降到 46.33、
37.34 ms。三次原生端到端时间有升有降。精确指纹与阶段数据在
`target/p4-a4-fingerprint-proof/direct-comparison.md`。
同机 Edge 对主文件和子文件各采样 30 次。全部 60 次的 PDF、SVG
和来源映射与上一候选逐项一致。主文件 29 次各跳过 20,618 步,
子文件仍执行后缀。服务峰值 RSS 为 619,944 KiB,上一候选为
603,116 KiB。
| A4 热编辑 | 主线可见 p50 / p95 | 上一候选 p50 / p95 | 本轮候选 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 285.4 / 497.4 ms | 264.8 / 493.9 ms |
| 子文件正文 | 184.1 / 241.5 ms | 188.4 / 337.5 ms | 196.8 / 329.7 ms |
100 ms 门槛仍开放。候选保存在 `perf/retained-history-suffix`。
此处两版均为 opt-level 1。实际样本和构建清单在
`target/p4-a4-fingerprint-proof/`。
## 2026-12-02 默认发布优化与页面呈现
用提交 `ed105bd` 构建 opt-level 3,内核和引擎均核对了实际编译
参数。15 项定向管线回归通过。与同一提交的 opt-level 1 做冻结
A4 三次原生对照。各次均与独立全量的执行、资源、PDF、SVG、
来源映射和生成文件相同,两种构建的实际状态指纹与执行步数也
逐项一致。两次成功复用各跳过 20,618 步。内核接缝耗时从
94.42 和 82.39 ms 降至 93.83 和 81.57 ms,原生端到端有升有降。
原始对照在 `target/p4-a4-release-opt3/a4-main-only/`。
Edge 同机、同格式和资源,主文件与子文件各 30 次。原有绘制确认
计时与上一批一致,60 次的 PDF、SVG、来源映射、变更页逐项相同。
主文件 29 次各跳过 20,618 步,子文件继续执行后缀。
进程峰值 RSS 为 618,988 KiB。
| A4 热编辑 | Opt1 可见 p50 / p95 | Opt3 可见 p50 / p95 | Opt3 呈现诊断 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 264.8 / 493.9 ms | 249.8 / 287.1 ms | 248.5 / 294.7 ms |
| 子文件正文 | 196.8 / 329.7 ms | 180.9 / 214.1 ms | 184.1 / 223.8 ms |
呈现诊断从浏览器读取带当前修订标识的实际替换页时间。两组 30 次
都有有效时间。浏览器报告呈现的中位时间比两帧确认晚 5.7 和
3.4 ms,两种记录均高于 100 ms。正式门槛仍开放。原生内核收益
小于浏览器 p95 差额,不能把整段差额归于编译级别。构建、环境与
逐次记录在 `target/p4-a4-release-opt3/`。
[Element Timing 规范草案](https://w3c.github.io/element-timing/)
## 2026-12-02 已关闭子文件的后缀复用
已完成读取的一个按字节分行子文件可在入口不变时参与后缀复用。
内核核对唯一源编号、其他来源与活动扫描器,并按实际文件变化
迁移来源坐标。宿主验证同一个规范路径与两版内容版本,核对
一次正文读取及已执行的大小查询,检查后缀没有新的子文件访问,
并重放真实效果。源码总字节按一次变动更新,宿主读取总量按
实际读取次数更新。已关闭的子文件不进入活动扫描器字节数。
新用例包含两次实际大小查询、一次正文读取和后缀引用子文件内
定义。连同入口长度变化和 XeTeX 整行编辑在内的五项管线测试
与两项记账单测均通过。变化后的 PDF、SVG、页面、日志、来源映射及宿主资源轨迹
均与独立全量一致。
冻结 A4 只改子文件的三次实测也与各自独立全量逐项相同,每次
都读取该子文件五次,流式读取为零。第一次执行 78,475 步,后两次
各跳过 20,618 步后缀,实际执行 57,863 和 57,857 步。
子文件 185 → 188 → 185 字节,最终源码字节相应 ±3,宿主读量
±15,最终扫描器字节为零,宿主读取次数保持 93。当前样本使用
诊断构建。原始核对在 `target/p4-child-source-splice/a4-child-only/`。
浏览器 100 ms 条件仍待在发布构建上实测。
## 2026-12-02 子文件发布实测与响应残差
提交 `e4d6e04` 的 opt-level 3 发布构建通过五项定向管线测试。
原样 A4 三次只改子文件均与独立全量一致,且与诊断构建的实际
指纹、来源、输出和步数相同。后两次各跳过 20,618 步。
成功接缝的内核检查和组装共 62.06、59.49 ms。原生逐次证据在
`target/p4-a4-child-release/a4-child-only/`。
Edge 仍保留原有确认计时,同时记录实际替换页呈现时间,主、子文件
各 30 次。全部 60 次的 PDF、SVG、来源映射与上一 opt-level 3 基线
逐项一致。主文件 29 次、子文件 30 次各跳过 20,618 步。
子文件实际执行中位数从 78,489 降到 57,871,执行耗时中位数从
84.2 ms 升至 103.2 ms,复用的证明成本仍需降低。
| A4 热编辑 | 上一版可见 p50 / p95 | 子文件复用版可见 p50 / p95 | 本轮呈现诊断 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 249.8 / 287.1 ms | 212.4 / 246.0 ms | 214.5 / 248.1 ms |
| 子文件正文 | 180.9 / 214.1 ms | 195.9 / 222.3 ms | 204.9 / 233.9 ms |
同一隔离服务、同一套真实子文件编辑,Linux 与 Windows 的 curl
各测六次复用连接的热响应。对应 SVG 字节相同。扣除处理与队列
耗时后,从发送请求至响应头的中位残差分别为 2.46 和 1.81 ms。
同批 Edge 子文件中位残差为 35.15 ms。直连试验的两端残差均低于 3 ms,
Edge 的余量需继续按浏览器请求和响应调度分解。
峰值 RSS 为 618,732 KiB。100 ms 门槛仍开放。
原始浏览器、构建和直连对照在 `target/p4-a4-child-release/`。
## 2026-12-02 共享命令分片的记账
事件历史与执行状态的跨接缝证明仍核对分配别名。两版共享同一
命令分片时只走一次已共享绑定,再从该遍历的别名序号出发分别
统计两版独立分片和活动状态。单测证明两版宏值及计数完全相等时,
跨分片别名指向另一个同值宏仍会拒绝复用。五项内核单测及五项管线
回归通过,覆盖重复子文件读取、盒计数、不同长度的事件历史、
连续检查点和 XeTeX UTF-16 整行编辑。验证原始记录在
`target/p4-shared-shard-accounting/`。
`ccb278f` 的 opt-level 3 发布构建完成。与 `e4d6e04` 同配置的冻结
A4 子文件编辑各三次,全部通过独立全量核验。两版的状态指纹、PDF、
SVG、aux 和实际读取轨迹一致,后两次均各跳过 20,618 步。
两次记账分别由 21.30 降到 15.25 ms、由 21.03 降到 20.40 ms。
前一批较空闲的基线分别为 19.17、19.44 ms。收益集中在其中一次。
原生对照在 `target/p4-a4-shared-accounting-release/a4-child-only/`。
本轮启动项目 Web `e14b7aa` 的文件树和编辑页,使用 Windows
Edge 无头浏览器输入真实编辑。以前的 60 次样本来自内核自带简版
编辑页,可比较同一输入的输出。新版 60 次 PDF、SVG、来源映射
和变更页与其逐项一致。主文件 29 次、子文件 30 次各跳过
20,618 步。
| A4 项目 Web 热编辑 | 样本 | 可见确认 p50 / p95 | 替换页首帧 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 30 | 205.3 / 511.8 ms | 204.4 / 512.1 ms |
| 子文件正文 | 30 | 196.5 / 345.2 ms | 203.4 / 351.4 ms |
Edge 的网络记录匹配全部 60 次请求,全部复用连接。发完请求
至收到响应头(扣除服务处理和排队)的中位残差为主文件 36.97 ms、
子文件 36.74 ms。发送和解析响应头各不足 0.2 ms(中位数),
响应体完成约 1 ms。一次主文件编辑收到响应后约 300.5 ms 才
确认呈现。运行前后 WSL 的整机 I/O 压力 10 秒均值分别为
6.09% 和 11.24%。内核服务峰值 RSS 为 619,024 KiB。100 ms
条件仍开放。完整输入、输出与时序在
`target/p4-a4-shared-accounting-release/edge-a4-6tx6u3sb/`。
## 2026-12-02 A4 状态核对与浏览器等待的拆分
`ccb278f` 的同一 Opt3 原生执行器在三次 A4 子文件编辑中
通过独立全量核验,后两次各跳过 20,618 步。硬件计数器测得成功
接缝的状态核对 CPU 时间分别为 26.40、25.31 ms,保留记账为
20.94、19.77 ms。状态核对的 16 条采样栈中有 10 条首次遍历
宏替换文本以建立分片的来源范围,另外 6 条在精确比较中查找命令名。
组装也观察到首次建立范围。采样表与调用栈位于
`target/p4-a4-shared-accounting-release/a4-child-only/cpu-profile/`。
项目 Web 用同一二进制诊断主、子文件各六次。12 次的 PDF、SVG、
变更页和来源映射与上一轮同输入一致。响应完成到 JSON 可用的中位数
为 3.85 / 3.35 ms,SVG 解码为 17.30 / 14.60 ms,替换 DOM 后到
首帧为 14.90 / 14.20 ms。本轮未再观察到上一轮约 300 ms 的响应
后等待。分段样本保存在 `target/p4-browser-presentation-attribution/`。
隔离 HTTP 对照在同一个 Windows Edge 轮流请求 Windows 和 WSL
本地端点,已在两种路径上复现浏览器响应头残差。Windows 本地边界
对照用 24 次连接复用请求,测试 GET 和 JSON POST,每种各有六次
开启 CDP 网络事件、六次关闭。JSON POST 的中位残差分别为
39.64 和 34.96 ms,服务器收到请求头到取得正文耗时 8.08 和
8.87 ms,回复就绪到浏览器记录响应头为 31.43 和 23.42 ms。
两组 GET 发送相同长度的回复正文,残差为 18.22 和 21.89 ms。
这些时间没有经过原生编译,直接定位浏览器请求等待,不参与
100 ms 的页面验收。原始脚本和样本在
`target/p4-browser-timing-attribution/`。
将命令分片的保守来源范围随绑定安装维护。格式反序列化、重定义、
分组恢复和换算后的宏都经过相同路径。移除的绑定可以保留旧上界,
因此无法证明不移动时仍会检查实际内容。排序、格式、指纹及宏
分配别名保持按原逻辑核对。
同配置 Opt3 前后各三次子文件编辑与独立全量一致,前后指纹、
读轨迹、PDF、SVG 和 aux 逐项相同,两次成功接缝各跳过 20,618 步。
成功接缝的状态核对从 27.76 / 27.01 ms 降至 11.44 / 10.10 ms,
总内核核验从 74.01 / 61.19 ms 降至 38.79 / 38.62 ms。新增的
可选诊断显示两次实际来源换算分别为 0.07、0.03 ms,剩下的精确
状态比较为 11.01、9.91 ms。恢复时执行器克隆约 1 ms,每次热
编辑的六次捕获克隆合计 5.21–7.68 ms。全程 I/O 等待偏高,
每版一次的最初编译为 3.25 与 3.83 s,这组数据不能判定完整
冷启动影响。另用同一格式在各三个新进程单独测解码,扣除输入
读取后,线程 CPU 中位数由 1,097.83 升至 1,115.83 ms,
墙钟中位数由 1,104.56 升至 1,118.32 ms。三项核心测试和四项
管线测试通过,覆盖宏来源、别名、重读子文件、拒绝草稿后的恢复
和 XeTeX UTF-16 整行编辑。配对证据在
`target/p4-a4-checkpoint-attribution/`。
Windows 全部本地的另一轮对照使用同样的 682 字节请求及
145,000 字节回复,分别以 HTTP POST 和一条已建立的 WebSocket
交替收取完整回复。每种等待配置各四对。扣除实际服务耗时,
无等待组的中位残差从 34.25 降到 5.89 ms,80 ms 等待组从
50.55 降到 18.71 ms。该结果用于选择传输试验,项目 Web 的页面
呈现门槛仍开放。回执为
`target/p4-browser-timing-attribution/websocket-vs-post-report.json`。
## 2026-12-02 项目 Web 的持久预览通道试验
项目 Web 使用 `65bf302` 的同一原生发布版、隔离的 Windows 本地
代理及同一 A4 会话。浏览器在 12 次实际编辑中交替走 HTTP POST
和预热的 WebSocket,每种通道各有三次主文件和三次子文件编辑。
两组收到相同结构的原生预览回复,继续走项目编辑页的图片解码、
修订核对和发布流程。12 次的 PDF、SVG、来源映射及变更页
与此前相同编辑逐次一致,全部热样本复用连接。
| 阶段中位数 | HTTP POST | WebSocket |
| --- | ---: | ---: |
| 请求至完整回复 | 164.30 ms | 142.80 ms |
| 扣除公共代理和原生处理后的余量 | 42.82 ms | 22.86 ms |
| 原生预览就绪 | 111.31 ms | 111.70 ms |
| 输入至替换页实际首帧 | 205.85 ms | 182.75 ms |
样本用于评估传输路径,100 ms 的正式条件仍开放。试验通过
串行编辑定位到页面首帧的改善。接入项目自身的预览通道时需覆盖
连续输入、旧修订取消和重新连接后的发布一致性。原始回执、隔离
代理和核验记录在 `target/p4-browser-timing-attribution/project-transport-ab-4iu_kdz1/`
及其上级目录。
## 2026-12-02 原生预览通道与命令分片精确核对
`3504a43` 在命令分片的遍历顺序相同时逐项核对键和完整含义。
顺序有差异时使用原精确查找。宏分配的独立别名证明继续执行。
同配置 A4 的三次子文件编辑均与独立全量一致,后两次各跳过
20,618 步。成功接缝中,精确状态比较由 11.09 / 7.96 ms 降至
0.93 / 0.44 ms。同期整次接缝耗时分别为 39.77 / 25.86 ms,
基线为 33.68 / 29.80 ms。原生样本与阶段记录在
`target/p4-native-preview-channel/a4-child-only/`。四项内核单测和三项
管线回归通过,包含已关闭子文件、拒绝草稿后的恢复和 XeTeX UTF-16
整行编辑。
`44e5774` 将持久 WebSocket 接入原生项目预览。连接空闲时通过
该连接提交,并沿既有队列执行。连接忙或正在建立时继续使用 HTTP,
让新编辑及时取消旧作业。当前请求断线时使用相同编辑和新序号
重试,过期响应由浏览器忽略。项目切换后,旧连接保留的弱会话引用
不能提交到新项目。握手限制为同源的本地编辑器。
真实 Edge 的取消验证先通过项目接口观察到旧编辑已到达服务,
再由更新的 HTTP 编辑取消。旧作业返回 409 且未绘制。浏览器在
另一次发送后关闭连接,用更高序号重试通过,之后的新连接也成功
发布。最终 PDF、实际 DOM SVG 和规范化来源映射与独立全量逐项
一致。不同来源和无效握手分别返回 403、400。该组使用浏览器关闭
握手。证据在 `target/p4-preview-socket-correctness/run-blaoglh2/`。
同一发布构建在项目库的 `/p/a4/` 路径进行原样 A4 的固定序列
热编辑,Windows Edge 无头模式下主、子文件各 30 次。60 次均走
原生 WebSocket,逐次的 PDF、SVG、来源映射和变更页与此前 HTTP
样本一致。主文件 29 次、子文件 30 次各复用 20,618 步。
| A4 项目库热编辑 | 实际首帧 p50 / p95 | 内核就绪 p50 / p95 | 完整回复至首帧 p50 |
| --- | ---: | ---: | ---: |
| 主文件 | 158.1 / 185.1 ms | 110.03 / 130.64 ms | 35.0 ms |
| 子文件 | 150.8 / 181.2 ms | 98.01 / 131.70 ms | 37.1 ms |
WebSocket 发送至完整回复扣除服务处理和排队后的中位余量为
10.38 / 9.80 ms。内核进程峰值 RSS 为 619,452 KiB,测量前后
I/O 压力 10 秒整机等待均值分别为 0.72% 和 10.55%。正式 100 ms
门槛仍开放。完整样本和回执在
`target/p4-native-preview-channel/edge-a4-ade22dgz/`。内核就绪
p95 已高于门槛,继续追查保留记账和仍执行的原生热编辑路径。
## 2026-12-02 热编辑的命令复制和宏别名记账
发布版 `44e5774` 使用同一 A4 子文件编辑序列做 CPU 采样。两次
成功复用后缀的保留记账分别使用 19.75、28.16 ms CPU,均执行约
4,048 万条机器指令。15 条记账调用栈有 11 条经过宏分配别名计数。
在其余恢复执行的 67 条调用栈中,有 21 条对应普通赋值或分组还原
触发的命令分片复制。状态复制、来源换算及精确比较合计只占
0.80、1.66 ms CPU。原始计数器和栈位于
`target/p4-native-preview-channel/a4-child-only/cpu-profile/`。
将命令表的写时复制粒度细分为 128 个分片。命令含义查询缓存的键
随检查点共享,读取轮次仍各自更新。后缀记账首先收集两版共同的
宏分配,包括发生写入的分片中的共同绑定,再独立收集不同分配。
命令迭代顺序一致时直接配对,遇到差异时继续核对实际键。
宏别名序列仍逐项检查,地址集合使用既有哈希表依赖。格式与状态
指纹继续按原有键顺序生成。
候选 `d749333` 通过八项内核单测和四项管线回归。同配置原生三次
A4 子文件编辑均与独立全量一致,资源读写、状态指纹、PDF、SVG、
aux 和原执行步数亦与基线一致,后两次各跳过 20,618 步。
两次后缀记账 CPU 从 19.75 / 28.16 ms 降至 7.47 / 7.42 ms,
指令数由约 4,048 万降至约 745 万。两次恢复执行的全部指令数
各减少约 25%,其中后缀核验之外的恢复工作指令数约减 8%。
基线与候选的主机负载有差异,指令计数和调用栈是这次配对的主要
定位依据。原始配对在
`target/p4-native-accounting-refresh/a4-child-only/cpu-profile/`。
同版项目库的 A4 主、子文件各 30 次热编辑全部走原生 WebSocket。
60 次的 PDF、SVG、来源映射和变更页与上一发布版逐项一致。
| 编辑范围 | 上版首帧 p50 / p95 | 候选首帧 p50 / p95 | 候选内核就绪 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件 | 158.1 / 185.1 ms | 141.1 / 233.2 ms | 93.09 / 172.64 ms |
| 子文件 | 150.8 / 181.2 ms | 132.6 / 190.5 ms | 80.77 / 124.39 ms |
首帧中位数下降,尾部等待升高。候选两个最慢主文件样本仍分别
只执行 35,140 和 35,137 步,原生执行耗时却为 140.67 和
149.02 ms。候选整机 I/O 压力的 10 秒均值在测量前后为
2.68% 和 12.21%,无法由这一时间窗判断具体慢样本的原因。
峰值 RSS 为 619,608 KiB。100 ms 条件仍开放。
可复验样本在 `target/p4-native-accounting-refresh/edge-a4-bbs5lgx6/`,
尾部拆分在 `target/p4-native-accounting-refresh/tail-diagnostics.json`。
为复查长尾,两版用同机独立会话,按编辑序号交错交付。每组
主、子文件各六次。全部 24 次的 PDF、SVG 和来源映射与归档逐次
一致。候选首帧中位数为主文件 155.20 ms、子文件 146.45 ms,
对照为 181.30 ms、157.25 ms。个别主文件候选样本更慢,对照的
一个子文件样本达 382.2 ms。整段 CPU、I/O 和系统压力保留在
诊断记录中。正式 p95 使用上表每类 30 次样本。
对照回执在 `target/p4-native-accounting-refresh/paired-edge-diagnostic/run-yzzmu1gd/`。
另用相同 `44e5774` 在 Edge 比较默认 GPU 与禁用 GPU,各 12 次,
24 次 PDF、SVG 和来源映射与已归档编辑一致。Edge 确认默认组
启用 GPU 合成和光栅化。在该组运行顺序下,完整回复到实际首帧
的配对中位数多 4.55 ms(主文件)和 4.25 ms(子文件)。两组
内核耗时也有漂移,这次对照未观察到首帧收益。样本在
`target/p4-browser-presentation-attribution/gpu-control-verified-comparison.json`。
## 2026-12-02 复查首帧长尾和准备阶段
将原来的交错浏览器诊断延长到每版前 32 次,保留两组各自完整的
修订历史。64 次编辑的 PDF、SVG、来源映射与归档一致。
首帧的每对差值中位数为主文件 −22.50 ms、子文件 −12.95 ms。
原长测的第 21、31 次主文件编辑在这次比较中执行步数相同。
| 编辑序号 | 上版 / 候选执行 | 上版 / 候选首帧 |
| --- | ---: | ---: |
| 21 | 103.17 / 91.11 ms | 184.7 / 181.2 ms |
| 31 | 88.16 / 83.60 ms | 157.1 / 168.2 ms |
原来的两次执行尖峰未复现。第 31 次候选的回复等待和绘制增加,
抵消了执行收益。候选也有不同序号的慢子文件样本,100 ms 条件继续
开放。采样保存了相同编辑序号的原始读数和整段 CPU、I/O 以及
整机压力,压力读数覆盖编译、发布和验证窗口。
证据在 `target/p4-native-accounting-refresh/paired-edge-diagnostic/run-gcerfxzr/`。
在准备生成文件时,项目显式声明与已有账本重叠的同一路径统一使用
声明处的实时别名检查,继续观察文件版本、锁内初态和发布前一致性。
命令表将已计算的键散列用于写入,共享分片上的相同绑定延续原分配
和缓存版本。全局赋值前后的分组记录仍由原逻辑处理。缓存未命中时
复用已有命令键,未绑定和虚拟命令按原路径取得含义。宏值相同且
分配独立时继续按新的绑定安装。
内核源码提交 `143775b`,宿主准备提交 `b7e1c90`。七项内核、
三项宿主和四项管线定向检查通过,覆盖宏分配、全局赋值与分组、
真实硬链接保护、已关闭子文件和 XeTeX 整行复用。宿主单测以当前
宿主源码连接归档内核,组合发布构建另通过管线回归与独立全量对照。
同配置发布版各三次 A4 子文件编辑都与独立全量一致,状态指纹、
PDF、SVG、aux 与实际读取记录跨版本逐项相同。两次复用仍各
跳过 20,618 步。每次准备的别名比较从 652 降至 563,其中目标
生成文件从 178 降至 89,文件元数据探测从 521 降至 430。准备
时间为原 9.34 / 7.81 / 13.41 ms,候选 9.79 / 10.71 / 7.69 ms。
单独的线程 CPU 记录受系统计时粒度影响。这三次能确认减少重复
探测,准备阶段时延仍有波动。证据在
`target/p4-native-host-refresh/a4-child-only/`。
### 项目 Web 的首帧
同机 Windows 无界面 Edge 打开项目库 `/p/a4/`,主、子文件各做
30 次热编辑。全部使用原生 WebSocket,以 Element Timing 记录
输入到新页面首帧。60 次的 PDF、SVG、来源映射和变更页逐项与
`d749333` 归档一致。主文件 29 次、子文件 30 次各跳过 20,618
步后缀。服务进程峰值 RSS 为 619,732 KiB。
| A4 热编辑 | 上版首帧 p50 / p95 | 本版首帧 p50 / p95 | 本版内核就绪 p50 / p95 | 本版完整响应到首帧 p50 / p95 |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 141.1 / 233.2 ms | 146.3 / 203.5 ms | 94.80 / 152.43 ms | 36.3 / 47.6 ms |
| 子文件正文 | 132.6 / 190.5 ms | 129.7 / 201.4 ms | 79.32 / 118.30 ms | 39.9 / 55.0 ms |
本批主文件 p95 下降、子文件 p95 上升,两组首帧均超过 100 ms。
原生执行耗时 p50 / p95 分别为 72.35 / 111.19 和 58.44 /
96.23 ms。浏览器的原始样本与逐次核验在
`target/p4-native-host-refresh/edge-a4-te4md_mw/`。
### 主文件的后缀重建
同一发布产物做三次独立的主文件热编辑。每次的执行、PDF、SVG、
来源、生成文件和读取记录均与各自全量一致,后两次各跳过 20,618
步。带诊断的两次成功会合,精确状态比较分别为 1.50 / 1.54 ms,
统计为 7.27 / 6.69 ms,后缀结果组装为 39.71 / 41.17 ms。
同版子文件探针的对应组装为 5.7–5.8 ms。带诊断的分段耗时单独
记录,浏览器表使用无探针的首帧。两次有针对性的主文件 CPU 采样
仍与独立全量一致。其中成功复用的第 2 次,后缀组装为 36.14 ms
线程 CPU,最终状态指纹为 25.56 ms,追加及重定位为 2.14 ms。
另一轮未会合的样本在正常收尾计算指纹用了 54.14 ms 线程 CPU。
主文件原始分段和 CPU 采样在
`target/p4-native-host-refresh/a4-main-only/`。
### 从旧状态复用命令哈希前缀
原生命令表在全局排序的第 128、256 等绑定之后保存哈希器状态。
旧版与新版共享同一键顺序时,只比较发生改变的命令分片。新版可从
首个变化绑定之前的最近检查点继续输入剩余命令和所有其他状态。
命令赋值、删除和来源位置换算都使对应缓存失效。数值指纹和格式
序列化沿用原有规则。实现 `3c09d64`,通过 10 项内核和 3 项
管线定向检查,其中包括 XeTeX UTF-16 整行复用。
冻结 A4 三次主文件热编辑全部与独立全量一致,也与上一发布版的
进出指纹、执行步数、PDF、SVG、aux 和来源逐项一致。首次编辑未能
复用前缀,在 23,957 个命令绑定中从 0 开始。后两次首个变化索引
均为 4,891,实际从旧哈希器的第 4,864 个绑定之后继续,各跳过
20,618 步执行后缀。
第 2 次编辑的配对探针记录指纹线程 CPU 由 25.56 降至 21.65 ms,
指令数由 101.74 百万降至 84.30 百万,后缀组装线程 CPU 由
36.14 降至 28.96 ms。首次编辑的指纹指令数由 131.97 百万增至
132.49 百万,两个样本的 CPU 差异不能归于前缀复用。证据在
`target/p4-command-hash-checkpoint/a4-main-only/fingerprint-profile/`。
### 二进制 WebSocket 预览对照
候选 `4df8983` 在同一条 WebSocket 消息中发送精简元数据和
原始 SVG 字节。客户端仍经图片解码、编辑序号与基准修订校验
后替换页面。未协商二进制的请求、编译错误和 HTTP 回退继续使用
文本。Windows Edge 实测旧请求返回 409、断线后自动使用较高
序号发 HTTP 请求再恢复 WebSocket、旧客户端返回文本预览。
实际 TeX 错误返回 422,保留上版页面及 PDF。最后二进制帧的页面
字节与安装到 DOM 的 SVG 相同,且与零复用的独立全量 PDF、SVG
和来源映射一致。回执在
`target/p4-binary-preview-wire/correctness/run-rd9re33v/`。
在同机项目库 `/p/a4/` 主、子文件各 30 次实际热编辑。60 次
均收到二进制回复,输出、变更页、来源映射与 `b7e1c90` 全部
一致,每次实际执行步数及前后缀复用也一致。服务峰值 RSS
619,172 KiB。
| A4 热编辑 | 文本首帧 p50 / p95 | 合并候选首帧 p50 / p95 | 合并候选内核就绪 p50 / p95 | 合并候选完整响应到首帧 p50 / p95 |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 146.3 / 203.5 ms | 131.1 / 287.6 ms | 85.39 / 200.37 ms | 35.9 / 57.3 ms |
| 子文件正文 | 129.7 / 201.4 ms | 124.6 / 219.9 ms | 77.83 / 153.96 ms | 37.3 / 56.8 ms |
这两批分别使用不同内核和传输版本。候选首帧 p50 较低,p95
较高,60 次均超过 100 ms。主文件最慢两次的实际执行分别为
177.1 和 149.4 ms,仍各跳过 20,618 步。子文件最慢一次实际
执行为 143.7 ms。以上耗时在回复前观测到。原始样本和逐次
输出核验在 `target/p4-binary-preview-wire/edge-a4-hstj7f9y/`。
同一发布二进制再做文本与二进制各 12 次交错,24 次启用预期
帧类型,输出与归档逐项一致。二进制相对文本,完整响应到实际
首帧的配对差值中位数为主文件 +3.65 ms、子文件 −1.35 ms。
扣掉内核和排队后,发请求到完整回复的配对差值两组都不到
1 ms。该对照未显示稳定收益,`6adadd7` 恢复文本预览协议。
交错数据在 `target/p4-binary-preview-wire/paired/run-0_p1i5wc/`。
### 保留版本的项目 Web 复测
保留命令哈希前缀复用,使用原生文本 WebSocket,在同机 Windows
Edge 项目库 `/p/a4/` 复测主、子文件各 30 次。60 次均用
WebSocket,PDF、SVG、来源和变更页与 `b7e1c90` 逐项一致。
主文件 29 次、子文件 30 次各跳过 20,618 步,服务峰值 RSS
619,460 KiB。
| A4 热编辑 | 上版首帧 p50 / p95 | 保留版本首帧 p50 / p95 | 内核就绪 p50 / p95 | 完整响应到首帧 p50 / p95 |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 146.3 / 203.5 ms | 129.7 / 204.8 ms | 82.56 / 126.64 ms | 36.0 / 54.7 ms |
| 子文件正文 | 129.7 / 201.4 ms | 126.0 / 172.8 ms | 74.99 / 92.11 ms | 36.1 / 47.3 ms |
两组中位数下降,主文件 p95 接近上版,子文件 p95 降低 28.6 ms。
本批 WSL 整体 I/O 压力在测试窗口有变化。所有样本仍超过 100 ms,
浏览器条件继续开放。实际首帧及逐次比对在
`target/p4-command-hash-checkpoint/edge-a4-v6_papg9/`。
## 2026-12-02 页面交付与检查点准备的定向定位
同一文本 WebSocket 发布版各做 12 次配对浏览器编辑。更换为等待
SVG 图片加载事件后,实际绘制的页面、PDF 和来源映射全部一致。
相对原先等待解码,完整回复至新页实际首帧的配对中位差为主文件
+0.20 ms、子文件 −1.45 ms。该候选未进入发布分支。
原始记录在 `target/p4-svg-load-paint/paired/run-mn5_68go/`。
冻结 A4 两次主文件编辑的原始计数表明,实际发页到现有输出组
结束后的收敛点都只差 471 步。输出组结束和现有观察点处于同一步。
这两次与独立全量编译和归档指纹一致。继续以完整输出组结束作为
收敛边界。证据在
`target/p4-command-hash-checkpoint/a4-main-only/physical-gap/case-qee7w1oc/`。
同一 Opt3 发布版的两次 A4 主文件编辑用于定位准备阶段。检查点
准备线程 CPU 为 11.47、12.55 ms。其中较大的开销在选择与宿主
重放环节,为 5.51、6.19 ms,合计约占 55% 指令。实时准备文件
为 3.77、4.03 ms,校验固定格式为 1.42、1.49 ms。此次断点
测量的墙钟值包含探针开销。两次仍与独立全量一致,证据在
`target/p4-next-host-prep/case-o61fl8mx/`。
### 分层命令表与直接 SVG 草稿
`37a42c8` 将命令表细分为 32 个目录组,每组 16 个分片。一次绑定
变动只复制受影响的共享目录组和分片,其余 31 组及 511 个分片可
共享旧检查点。查找、分组恢复和命令缓存使用同一语义。通过原
有序状态哈希与序列化对照,以及来源重定位和宏别名回归。
`a72768b` 在已解析的发页列表可自行生成 SVG 时,让编辑器在 PDF
导出前发送可撤销的预览。依赖 PDF 字节的页面在导出后生成预览。
编译完成后再安装 PDF、aux 和日志并解除对应修订的下载标记。
取消及发布失败恢复上一版。准备成功时也省去将资源追踪和输入
快照复制到失败报告的工作,失败路径继续采集实际观测。
10 项内核和 5 项管线定向检查通过。检查包括早期预览和发布页面
一致、早期及晚期取消后旧文件保留、两种草稿边界的输出硬链接冲突、
准备失败证据及 XeTeX UTF-16 整行复用。记录在
`target/p4-early-native-draft/`。
两版各三次冻结 A4 主文件编辑,每次均与自己的独立全量一致。
两版进出状态指纹、实际执行步数和 PDF、SVG、aux、来源均逐项
相同。后两次各跳过 20,618 步。三次执行阶段线程 CPU 从
79.99 / 64.01 / 64.02 ms 变为 79.97 / 55.98 / 88.03 ms。
重定位分段的墙钟值从 0.80 / 0.99 变为 0.30 / 0.62 ms。
三次对照的执行耗时有升有降,命令表分片的整体时延收益尚待确认。
对照在 `target/p4-early-native-draft/paired-native-shards/`。
### 真实项目 Web 的草稿与发布
Edge 实测最终编辑的实际文本 WebSocket 回复明确处于 PDF 导出前。
对应页面由浏览器实际绘制,已发布的 PDF 之后才可下载。过时编辑
被取消,断线重试并恢复连接。实际 TeX 422 错误保留上一张页面
和字节相同的 PDF,下一轮正常恢复。最终 PDF、SVG 和来源映射与
零复用全量一致。回执在
`target/p4-early-native-draft/correctness/run-sce9oov1/`。
原样 A4 项目库 `/p/a4/` 主、子文件各 30 次。60 次全部走
提前草稿和独立文件发布,31 次在绘制后仍观测到发布等待。60 次
PDF、SVG、来源、变更页、总步数和实际复用步骤与 `3c09d64`
逐项一致。服务峰值 RSS 为 618,976 KiB。
| A4 热编辑 | 上版首帧 p50 / p95 | 本版首帧 p50 / p95 | 本版预览就绪 p50 / p95 | 本版完整回复到首帧 p50 / p95 |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 129.7 / 204.8 ms | 126.6 / 229.2 ms | 77.67 / 125.21 ms | 39.0 / 66.7 ms |
| 子文件正文 | 126.0 / 172.8 ms | 119.8 / 170.1 ms | 68.30 / 102.51 ms | 40.5 / 51.4 ms |
主文件 p95 上升了 24.4 ms,子文件下降了 2.7 ms。两类第 4 次
编辑分别用 35.6 和 38.1 ms 准备、208.8 和 126.9 ms 执行,
实际执行步数与同一编辑的上版相同。主文件第 3 次的完整回复
到实际首帧用了 87.5 ms。60 个首帧均超过 100 ms,性能条件继续
开放。实测及校验在 `target/p4-early-native-draft/edge-a4-f7p1nfq1/`。
同目录上一级保存逐次对照 `baseline-parity.json` 和证据清单。
## 2026-12-02 热编辑线程时间与 SVG 内容
`9f556d6` 为本地编辑器增加可选的工作线程采样。设置
`TEXRRA_EDITOR_THREAD_USAGE=1` 时,预览回执会记录准备、执行、
布局及预览就绪时的 CPU、上下文切换与块 I/O 计数。浏览器继续以
Element Timing 记录实际页面首帧。
同机同一早期预览版在项目库中主、子文件各 30 次。60 次输出、
来源、步数与 `a72768b` 逐项一致。上次第 4 次编辑中的尖峰在本批
未复现。预览就绪的工作线程墙钟减 CPU 的逐样本差值 p50/p95 为主
2.02/3.66 ms、子 2.26/3.86 ms。实际执行 CPU p50/p95 为主
56.01/68.01 ms、子 47.99/59.98 ms,完整回复到首帧的 p50 约
35 ms。Linux 线程记账有量化和舍入,个别分段差值略小于零。
基线样本在 `target/p4-live-thread-cost/baseline/edge-a4-sr81i4lh/`。
再用真实交替编辑历史独立全量核对最终状态。只保留最近两次编译
结果时,六次探针未观察到更早状态的新命中。扩展为 12 次,在完整
状态逐项相等的前提下,保留上一个不同的完成状态可覆盖第 5、7、
9、11 次的 4 次主文件编辑。6 次子文件编辑均命中最近状态。
所有实际执行和输出均与独立全量一致。证据在
`target/p4-a4-distinct-state-proof/after/run-8jo9g_2k/`。
### 精确指纹与 SVG 轮廓复用
`8411986` 保留一个与最近成功发布结果不同的最终状态及数值指纹。
只有后缀的现有证明通过且最终状态逐项相等时,才复用该指纹。否则
继续按原字段顺序计算。宿主文件重放和发布仍根据本次实际结果验证。
发布新结果前,重复的完成状态不会替换保留的不同状态。
`4586d96` 对独立 SVG 草稿的重复长字形轮廓按原路径文本去重。每次
出现时保留位置、缩放、颜色、透明度和标签。PDF 及其页面渲染使用
现有路径。`af8f38b` 在同次作业为文件查找共用逻辑路径集合,路径
角色变化时重建。真实文件身份、版本和流仍实际检查。11 项内核、
2 项命名空间、5 项管线定向检查通过。
冻结 A4 实际项目库 60 次,主、子文件各 30 次。候选与带诊断的
基线的 PDF、变更页、来源、执行和复用步数逐项一致。60 个压缩
SVG 逐个展开,字节均与上版一致。四次选定编辑在 Edge 中将实际
预览和展开版本以同一显示尺寸重绘,RGBA 字节逐项一致。
| A4 热编辑 | 基线首帧 p50 / p95 | 候选首帧 p50 / p95 | 候选就绪 p50 / p95 | SVG 字节中位数 |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 120.9 / 145.3 ms | 101.1 / 136.0 ms | 53.91 / 72.92 ms | 157,234 → 76,582 |
| 子文件正文 | 108.7 / 137.4 ms | 109.1 / 139.1 ms | 63.81 / 86.91 ms | 156,913 → 76,423 |
26 次主文件编辑命中保留状态。命中样本的执行 CPU 配对差值中位
数为 −20.02 ms,实际首帧为 −21.2 ms。四次未命中的执行 CPU
配对差值中位数为 −2.06 ms。子文件没有额外状态命中。完整回复
至实际首帧的配对差值中位数为主 +0.10 ms、子 −0.25 ms。SVG
体积约减半,尚未观察到绘制等待一致下降。候选服务峰值 RSS 为
620,056 KiB。主、子分别有 13/30、2/30 个首帧不高于 100 ms,
两组 p95 均未达到 100 ms。候选和 CPU 配对数据在
`target/p4-live-thread-cost/candidate/edge-a4-61_vmidl/` 和
`target/p4-live-thread-cost/worker-cohort-parity.json`。
另对两版各做两次冻结 A4 主文件的定向准备 CPU 探针。宿主准备
和运行检查次数、I/O 调用、实际重放以及执行步骤一致,各自与独立
完整编译的执行、日志、资源及流记录、PDF 和 SVG 一致。两版 SVG
展开后逐字节相同。准备阶段指令数由 25.171 / 25.211 百万降至
24.905 / 24.950 百万,约减少 1%。准备线程 CPU 分别从
11.67 / 15.54 ms 改为 11.43 / 17.59 ms,本组未证实时间收益。
报告在 `target/p4-next-host-prep/namespace-cache/paired-native/`。
## 2026-12-02 XeTeX 整行编辑复用
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他
+104 -12
View File
@@ -15,6 +15,7 @@ const fileTree = document.querySelector("#file-tree");
const edits = new Map();
const fileViews = new Map();
const EDIT_IDLE_MS = 70;
const PREVIEW_SOCKET_RETRY_MS = 1000;
let files;
let activeFile;
let sequence = 0;
@@ -24,6 +25,10 @@ let composing = false;
let compileTimer;
let lastTypingAt = -Infinity;
let promptCompilePending = false;
let previewSocketUrl;
let previewSocket;
let previewSocketRetryAt = 0;
let pendingSocketPreview;
const projectPrefix = location.pathname.startsWith("/p/") ? location.pathname.slice(0, -1) : "";
const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published";
@@ -161,22 +166,107 @@ async function publicationStatus(edit, revision) {
return null;
}
function completeSocketPreview(reply) {
const pending = pendingSocketPreview;
pendingSocketPreview = undefined;
pending?.resolve(reply);
}
function retirePreviewSocket(socket) {
if (previewSocket !== socket) return;
previewSocket = undefined;
previewSocketRetryAt = performance.now() + PREVIEW_SOCKET_RETRY_MS;
completeSocketPreview(null);
socket.close();
}
function connectPreviewSocket() {
if (!previewSocketUrl || previewSocket || performance.now() < previewSocketRetryAt) return;
let socket;
try {
socket = new WebSocket(previewSocketUrl);
} catch {
previewSocketRetryAt = performance.now() + PREVIEW_SOCKET_RETRY_MS;
return;
}
previewSocket = socket;
socket.addEventListener("close", () => retirePreviewSocket(socket));
socket.addEventListener("error", () => retirePreviewSocket(socket));
socket.addEventListener("message", ({ data }) => {
if (previewSocket !== socket || !pendingSocketPreview) return;
try {
const reply = JSON.parse(data);
if (reply.sequence !== pendingSocketPreview.sequence
|| !Number.isInteger(reply.status) || reply.status < 200 || reply.status > 599
|| !reply.body || typeof reply.body !== "object") {
retirePreviewSocket(socket);
return;
}
completeSocketPreview(reply);
} catch {
retirePreviewSocket(socket);
}
});
}
function advertisePreviewSocket(path) {
if (typeof WebSocket !== "function" || path !== projectPrefix + "/preview-socket") return;
const url = new URL(path, location.href);
url.protocol = location.protocol === "https:" ? "wss:" : "ws:";
previewSocketUrl = url.href;
connectPreviewSocket();
}
function requestSocketPreview(payload) {
connectPreviewSocket();
const socket = previewSocket;
// The native socket handles one request at a time. An edit that supersedes
// this request goes straight to HTTP so it can cancel the existing work.
if (!socket || socket.readyState !== WebSocket.OPEN || pendingSocketPreview) return null;
return new Promise((resolve) => {
pendingSocketPreview = { sequence: payload.sequence, resolve };
try {
socket.send(JSON.stringify(payload));
} catch {
retirePreviewSocket(socket);
}
});
}
async function requestHttpPreview(payload) {
const response = await fetch(projectPrefix + "/preview", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
return { status: response.status, body: await response.json() };
}
async function compile(edit, submitted, changes) {
const replacements = [];
try {
const response = await fetch(projectPrefix + "/preview", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sequence: edit,
visible_revision: publishedRevision,
files: changes,
preview_draft: previewDraft,
}),
});
const result = await response.json();
const payload = {
sequence: edit,
visible_revision: publishedRevision,
files: changes,
preview_draft: previewDraft,
};
const socketReply = requestSocketPreview(payload);
let response;
if (socketReply) {
response = await socketReply;
if (edit !== sequence) return;
if (!response) {
// The native server may have accepted the edit before the disconnect.
// Retry the same local changes with a fresh sequence to supersede it.
edit = ++sequence;
payload.sequence = edit;
}
}
response ??= await requestHttpPreview(payload);
if (edit !== sequence) return;
if (!response.ok) throw new Error(result.error);
const result = response.body;
if (response.status < 200 || response.status >= 300) throw new Error(result.error);
const update = result.update;
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== publishedRevision)) {
throw new Error("预览版本与当前页面不一致");
@@ -208,6 +298,7 @@ async function compile(edit, submitted, changes) {
engineMs: result.ready_ms,
admissionAndQueueMs: result.admission_and_queue_ms,
phases: result.phases,
workerUsage: result.worker_usage,
visibleMs: performance.now() - submitted,
steps: result.steps,
reusedSteps: result.reused_steps,
@@ -382,6 +473,7 @@ async function openProject() {
source.setAttribute("autocomplete", "off");
addFormulaButtons();
sequence = project.sequence;
advertisePreviewSocket(project.preview_socket);
save.disabled = false;
save.addEventListener("click", saveSources);
document.addEventListener("keydown", (event) => {
+201 -135
View File
@@ -7,13 +7,14 @@ use std::{
io::Read,
path::{Component, Path, PathBuf},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
Arc, Condvar, Mutex, mpsc,
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
},
time::Instant,
};
use texrra_engine::native::{
CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, DraftPreview, Entry,
CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
DraftPreview, Entry,
EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot,
job_time,
};
@@ -21,14 +22,17 @@ use texrra_tex_core::{
execution::InputProfile,
resources::{InputPolicy, ResourceKind, SearchPath, WorldConfig},
};
use thread_usage::ThreadUsage;
use tiny_http::{Header, Method, Request, Response, Server};
mod library;
mod preview_socket;
#[path = "../../src/projects.rs"]
#[allow(dead_code)]
mod projects;
mod resource_capture;
mod saved_project;
mod thread_usage;
const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024;
const PAGE: &str = include_str!("index.html");
@@ -51,8 +55,33 @@ struct Save {
files: BTreeMap<String, String>,
}
enum PreviewReply {
Http(Request),
Socket(mpsc::Sender<(u16, Value)>),
}
impl PreviewReply {
fn send(self, status: u16, payload: Value) {
match self {
Self::Http(request) => reply(request, status, payload),
Self::Socket(sender) => {
let _ = sender.send((status, payload));
}
}
}
fn send_draft(self, payload: Value) {
match self {
Self::Http(request) => {
std::thread::spawn(move || reply(request, 200, payload));
}
socket => socket.send(200, payload),
}
}
}
struct Work {
request: Request,
respond_to: PreviewReply,
job: CompileJob,
compile: CompileRequest,
sequence: u64,
@@ -61,11 +90,19 @@ struct Work {
preview_draft: bool,
}
#[derive(Clone, Copy, Default)]
struct StageTiming {
wall_ms: f64,
worker: Option<ThreadUsage>,
}
struct EditorObserver {
started: Instant,
ended: Mutex<[f64; 5]>,
initial_worker_usage: Option<ThreadUsage>,
reused_final_fingerprints: AtomicUsize,
ended: Mutex<[StageTiming; 5]>,
queue: Arc<Queue>,
request: Mutex<Option<Request>>,
respond_to: Mutex<Option<PreviewReply>>,
sequence: u64,
visible_revision: Option<u64>,
received: Instant,
@@ -81,10 +118,23 @@ impl CompileObserver for EditorObserver {
CompileStage::Exported => 3,
CompileStage::ReadyToPublish => 4,
};
self.ended.lock().unwrap()[index] = self.elapsed_ms();
self.ended.lock().unwrap()[index] = self.measure_stage();
Ok(())
}
fn checkpoint_timings(&self, _: u64, timings: CheckpointTimings) {
if self.initial_worker_usage.is_some() {
self.reused_final_fingerprints.store(
timings.suffix_kernel.reused_final_fingerprints,
Ordering::Relaxed,
);
}
}
fn preview_before_export(&self) -> bool {
self.preview_draft
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
if !self.preview_draft || !self.is_current() {
return Ok(());
@@ -105,8 +155,8 @@ impl CompileObserver for EditorObserver {
draft.entry_checkpoint_work(),
None,
);
let request = self
.request
let respond_to = self
.respond_to
.lock()
.unwrap()
.take()
@@ -117,7 +167,7 @@ impl CompileObserver for EditorObserver {
result: None,
};
*self.queue.publication.lock().unwrap() = Some(publication);
std::thread::spawn(move || reply(request, 200, reply_body));
respond_to.send_draft(reply_body);
Ok(())
}
}
@@ -127,6 +177,14 @@ impl EditorObserver {
self.started.elapsed().as_secs_f64() * 1000.0
}
fn measure_stage(&self) -> StageTiming {
let wall_ms = self.elapsed_ms();
StageTiming {
wall_ms,
worker: self.initial_worker_usage.and_then(|_| ThreadUsage::current()),
}
}
fn is_current(&self) -> bool {
self.sequence == self.queue.current.load(Ordering::Acquire)
}
@@ -138,17 +196,28 @@ impl EditorObserver {
work: &EntryCheckpointWork,
compiled: Option<f64>,
) -> Value {
let ready = self.elapsed_ms();
let ready = self.measure_stage();
let pending = compiled.is_none();
let compiled = compiled.unwrap_or_else(|| self.ended.lock().unwrap()[4]);
json!({
let [prepared, executed, fonts, exported, publish_ready] = *self.ended.lock().unwrap();
let exported_ms = (exported.wall_ms > 0.0).then_some(exported.wall_ms);
let publish_ready_ms = (publish_ready.wall_ms > 0.0).then_some(publish_ready.wall_ms);
let compiled = compiled.or(publish_ready_ms);
let mut payload = json!({
"sequence": self.sequence,
"update": update,
"pending_publication": pending,
"compile_ms": compiled,
"ready_ms": ready,
"ready_ms": ready.wall_ms,
"admission_and_queue_ms": self.started.duration_since(self.received).as_secs_f64() * 1000.0,
"phases": self.phases(compiled, ready),
"phases": {
"prepare_ms": prepared.wall_ms,
"execute_ms": executed.wall_ms - prepared.wall_ms,
"layout_and_fonts_ms": fonts.wall_ms - executed.wall_ms,
"pdf_ms": exported_ms.map(|end| end - fonts.wall_ms),
"draft_ms": publish_ready_ms.zip(exported_ms).map(|(end, start)| end - start),
"seal_and_publish_ms": compiled.zip(publish_ready_ms).map(|(end, start)| end - start),
"svg_ms": ready.wall_ms - compiled.unwrap_or(fonts.wall_ms),
},
"steps": steps,
"reused_steps": work.reused_steps,
"reused_suffix_steps": work.reused_suffix_steps,
@@ -157,20 +226,18 @@ impl EditorObserver {
.saturating_add(work.discarded_suffix_attempt_steps),
"reused_frontier": work.reused_frontier,
"replayed_calls": work.replayed_calls,
})
}
fn phases(&self, compiled: f64, rendered: f64) -> Value {
let [prepared, executed, fonts, exported, ready] = *self.ended.lock().unwrap();
json!({
"prepare_ms": prepared,
"execute_ms": executed - prepared,
"layout_and_fonts_ms": fonts - executed,
"pdf_ms": exported - fonts,
"draft_ms": ready - exported,
"seal_and_publish_ms": compiled - ready,
"svg_ms": rendered - compiled,
})
});
if let Some(initial) = self.initial_worker_usage {
payload["worker_usage"] = json!({
"prepare": ThreadUsage::between(Some(initial), prepared.worker),
"execute": ThreadUsage::between(prepared.worker, executed.worker),
"layout_and_fonts": ThreadUsage::between(executed.worker, fonts.worker),
"export": ThreadUsage::between(fonts.worker, exported.worker),
"ready": ThreadUsage::between(Some(initial), ready.worker),
"reused_final_fingerprints": self.reused_final_fingerprints.load(Ordering::Relaxed),
});
}
payload
}
}
@@ -235,7 +302,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
if library.is_some() && web.is_none() {
return Err("The project library requires --web-dir".into());
}
let (port, mut session) = if library.is_some() {
let (port, session) = if library.is_some() {
(read_port(args.next())?, None)
} else {
let source = args.next().ok_or(usage)?.canonicalize()?;
@@ -264,6 +331,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
})?),
)
};
let mut session = session.map(|session| Arc::new(Mutex::new(session)));
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
println!("Native editor http://{}", server.server_addr());
for request in server.incoming_requests() {
@@ -323,10 +391,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
reply(request, 404, json!({"error": "Not found"}));
continue;
};
let project_open = session
.as_ref()
.is_some_and(|session| session.lock().unwrap().id.as_deref() == Some(id));
if rest.is_empty() && request.method() == &Method::Get {
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
if !project_open {
match library.open(id) {
Ok(next) => session = Some(next),
Ok(next) => session = Some(Arc::new(Mutex::new(next))),
Err(error) => {
reply(request, 422, json!({"error": error.to_string()}));
continue;
@@ -341,7 +412,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
continue;
}
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
if !project_open {
reply(
request,
409,
@@ -351,24 +422,41 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
session_path = &path[path.len() - rest.len() - 1..];
}
let Some(session) = &mut session else {
let Some(session) = &session else {
reply(request, 404, json!({"error": "Not found"}));
continue;
};
if session_path == "/preview-socket" && request.method() == &Method::Get {
preview_socket::open(request, Arc::downgrade(session));
continue;
}
if session_path == "/preview" && request.method() == &Method::Post {
let received = Instant::now();
let mut request = request;
match read_json(&mut request) {
Ok(edit) => session
.lock()
.unwrap()
.submit_edit(edit, received, PreviewReply::Http(request)),
Err(error) => reply(request, 400, json!({ "error": error })),
}
continue;
}
let mut session = session.lock().unwrap();
let EditorSession {
id,
run,
compiler,
queue,
save_number,
editor,
..
} = session;
} = &mut *session;
let EditorProject {
project,
entry,
editable,
declared,
options,
..
} = editor;
match (request.method(), session_path) {
(&Method::Get, "/") => respond(
@@ -393,78 +481,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"source": std::str::from_utf8(&file.data)?,
"files": files,
"sequence": queue.current.load(Ordering::Acquire),
"preview_socket": id.as_deref().map_or_else(
|| "/preview-socket".to_owned(), |id| format!("/p/{id}/preview-socket"),
),
}),
);
}
(&Method::Post, "/preview") => {
let received = Instant::now();
let mut request = request;
let edit: Edit = match read_json(&mut request) {
Ok(edit) => edit,
Err(error) => {
reply(request, 400, json!({ "error": error }));
continue;
}
};
if edit.sequence <= queue.current.load(Ordering::Acquire) {
reply(
request,
409,
json!({ "error": "A newer edit is already queued" }),
);
continue;
}
let updates = edit
.files
.into_iter()
.map(|(name, value)| {
let path = editable
.get(&name)
.ok_or_else(|| format!("File is not editable: {name}"))?;
if path == entry && value.is_none() {
return Err("The entry file cannot be removed".into());
}
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
})
.collect::<Result<BTreeMap<_, _>, String>>();
let next = updates.and_then(|mut updates| {
if let Some(source) = edit.source
&& updates
.insert(entry.clone(), Some(Arc::from(source.into_bytes())))
.is_some()
{
return Err("The entry file was edited twice".into());
}
project.with_file_changes(edit.sequence, updates)
});
*project = match next {
Ok(project) => project,
Err(error) => {
reply(request, 422, json!({ "error": error }));
continue;
}
};
let compile = options.clone().with_project(project.clone());
let job = compiler.start();
queue.current.store(edit.sequence, Ordering::Release);
let replaced = queue.next.lock().unwrap().replace(Work {
request,
job,
compile,
sequence: edit.sequence,
visible_revision: edit.visible_revision,
received,
preview_draft: edit.preview_draft,
});
queue.available.notify_one();
if let Some(old) = replaced {
reply(
old.request,
409,
json!({ "error": "A newer edit is already queued" }),
);
}
}
(&Method::Post, "/save") => {
let mut request = request;
if !request.headers().iter().any(|header| {
@@ -637,6 +659,64 @@ impl EditorSession {
editor,
})
}
fn submit_edit(&mut self, edit: Edit, received: Instant, respond_to: PreviewReply) {
let EditorProject {
project,
entry,
editable,
options,
..
} = &mut self.editor;
if edit.sequence <= self.queue.current.load(Ordering::Acquire) {
respond_to.send(409, json!({ "error": "A newer edit is already queued" }));
return;
}
let updates = edit
.files
.into_iter()
.map(|(name, value)| {
let path = editable
.get(&name)
.ok_or_else(|| format!("File is not editable: {name}"))?;
if path == entry && value.is_none() {
return Err("The entry file cannot be removed".into());
}
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
})
.collect::<Result<BTreeMap<_, _>, String>>();
let next = updates.and_then(|mut updates| {
if let Some(source) = edit.source
&& updates.insert(entry.clone(), Some(Arc::from(source.into_bytes()))).is_some()
{
return Err("The entry file was edited twice".into());
}
project.with_file_changes(edit.sequence, updates)
});
*project = match next {
Ok(project) => project,
Err(error) => {
respond_to.send(422, json!({ "error": error }));
return;
}
};
let compile = options.clone().with_project(project.clone());
let job = self.compiler.start();
self.queue.current.store(edit.sequence, Ordering::Release);
let replaced = self.queue.next.lock().unwrap().replace(Work {
respond_to,
job,
compile,
sequence: edit.sequence,
visible_revision: edit.visible_revision,
received,
preview_draft: edit.preview_draft,
});
self.queue.available.notify_one();
if let Some(old) = replaced {
old.respond_to.send(409, json!({ "error": "A newer edit is already queued" }));
}
}
}
impl Drop for EditorSession {
@@ -646,7 +726,7 @@ impl Drop for EditorSession {
// A fresh revision cancels any work still running on the old session.
self.compiler.start();
if let Some(old) = pending.take() {
reply(old.request, 409, json!({"error": "The project has closed"}));
old.respond_to.send(409, json!({"error": "The project has closed"}));
}
self.queue.available.notify_one();
}
@@ -851,6 +931,7 @@ fn prepare(
}
fn worker(queue: &Arc<Queue>) {
let measure_worker = std::env::var_os("TEXRRA_EDITOR_THREAD_USAGE").is_some_and(|value| value == "1");
let mut resources = resource_capture::ResourceCapture::default();
loop {
let work = queue
@@ -861,7 +942,7 @@ fn worker(queue: &Arc<Queue>) {
.unwrap()
.take();
let Some(Work {
request,
respond_to,
job,
mut compile,
sequence,
@@ -874,9 +955,11 @@ fn worker(queue: &Arc<Queue>) {
};
let observer = Arc::new(EditorObserver {
started: Instant::now(),
ended: Mutex::new([0.0; 5]),
initial_worker_usage: measure_worker.then(ThreadUsage::current).flatten(),
reused_final_fingerprints: AtomicUsize::new(0),
ended: Mutex::new([StageTiming::default(); 5]),
queue: queue.clone(),
request: Mutex::new(Some(request)),
respond_to: Mutex::new(Some(respond_to)),
sequence,
visible_revision,
received,
@@ -893,7 +976,7 @@ fn worker(queue: &Arc<Queue>) {
.expect("captured resources retain their original roots");
let result = job
.compile_expanding_project(compile.with_project(project.clone()), |failure| {
if observer.request.lock().unwrap().is_none() || !observer.is_current() {
if observer.respond_to.lock().unwrap().is_none() || !observer.is_current() {
return None;
}
project = resources.expand(&project, failure)?;
@@ -901,8 +984,8 @@ fn worker(queue: &Arc<Queue>) {
})
.map_err(|failure| failure.error);
let compile_ms = observer.elapsed_ms();
let request = observer.request.lock().unwrap().take();
let Some(request) = request else {
let respond_to = observer.respond_to.lock().unwrap().take();
let Some(respond_to) = respond_to else {
let mut current = queue.publication.lock().unwrap();
let publication = current
.as_mut()
@@ -922,34 +1005,21 @@ fn worker(queue: &Arc<Queue>) {
let document = match result {
Ok(document) => document,
Err(CompileError::Cancelled) => {
reply(
request,
409,
json!({ "error": "Compilation was superseded" }),
);
respond_to.send(409, json!({ "error": "Compilation was superseded" }));
continue;
}
Err(error) => {
reply(
request,
422,
json!({ "error": error.to_string(), "sequence": sequence }),
);
respond_to.send(422, json!({ "error": error.to_string(), "sequence": sequence }));
continue;
}
};
let preview = document.preview_since(visible_revision);
if !observer.is_current() {
reply(
request,
409,
json!({ "error": "The rendered preview was superseded" }),
);
respond_to.send(409, json!({ "error": "The rendered preview was superseded" }));
continue;
}
match preview {
Ok(update) => reply(
request,
Ok(update) => respond_to.send(
200,
observer.preview_payload(
update,
@@ -958,11 +1028,7 @@ fn worker(queue: &Arc<Queue>) {
Some(compile_ms),
),
),
Err(error) => reply(
request,
422,
json!({ "error": error, "sequence": sequence }),
),
Err(error) => respond_to.send(422, json!({ "error": error, "sequence": sequence })),
}
}
}
+131
View File
@@ -0,0 +1,131 @@
use super::{Edit, EditorSession, MAX_EDIT_BODY, PreviewReply, reply};
use serde_json::json;
use std::{
sync::{Mutex, Weak, mpsc},
time::Instant,
};
use tiny_http::{Header, Request, Response};
use tungstenite::{
Message, WebSocket,
handshake::server::{Request as HandshakeRequest, create_response},
protocol::{Role, WebSocketConfig},
};
pub(super) fn open(request: Request, session: Weak<Mutex<EditorSession>>) {
let host = header(&request, "Host");
let origin = header(&request, "Origin");
if !host.zip(origin).is_some_and(|(host, origin)| {
origin.strip_prefix("http://") == Some(host)
&& host
.parse::<tungstenite::http::uri::Authority>()
.is_ok_and(|authority| matches!(authority.host(), "127.0.0.1" | "localhost"))
}) {
reply(
request,
403,
json!({ "error": "Preview socket requires the editor origin" }),
);
return;
}
let Some(accept) = websocket_accept(&request) else {
reply(
request,
400,
json!({ "error": "Invalid preview socket handshake" }),
);
return;
};
std::thread::spawn(move || {
let response = Response::empty(101).with_header(accept);
let stream = request.upgrade("websocket", response);
let config = WebSocketConfig::default()
.max_message_size(Some(MAX_EDIT_BODY as usize))
.max_frame_size(Some(MAX_EDIT_BODY as usize));
let mut socket = WebSocket::from_raw_socket(stream, Role::Server, Some(config));
while let Ok(message) = socket.read() {
let received = Instant::now();
let result = match message {
Message::Text(text) => serde_json::from_slice::<Edit>(text.as_bytes()),
Message::Binary(bytes) => serde_json::from_slice::<Edit>(&bytes),
Message::Ping(_) => {
// Tungstenite queues the pong when reading a ping.
if socket.flush().is_err() {
break;
}
continue;
}
Message::Pong(_) => continue,
Message::Close(_) => {
let _ = socket.flush();
break;
}
Message::Frame(_) => break,
};
let Ok(edit) = result else {
// Invalid JSON cannot be attributed to a pending sequence.
let _ = socket.close(None);
break;
};
let sequence = edit.sequence;
let (status, body) = if let Some(session) = session.upgrade() {
let (sender, receiver) = mpsc::channel();
session
.lock()
.unwrap()
.submit_edit(edit, received, PreviewReply::Socket(sender));
drop(session);
let Ok(response) = receiver.recv() else {
break;
};
response
} else {
(
409,
json!({ "error": "The project is no longer open. Reload to reopen it." }),
)
};
if socket
.send(Message::text(
json!({ "sequence": sequence, "status": status, "body": body }).to_string(),
))
.is_err()
{
break;
}
}
});
}
fn header<'a>(request: &'a Request, name: &'static str) -> Option<&'a str> {
let mut matches = request
.headers()
.iter()
.filter(|header| header.field.equiv(name));
let value = matches.next()?.value.as_str();
matches.next().is_none().then_some(value)
}
fn websocket_accept(request: &Request) -> Option<Header> {
let mut handshake = HandshakeRequest::builder()
.method("GET")
.version(tungstenite::http::Version::HTTP_11);
if request.http_version() != &tiny_http::HTTPVersion(1, 1)
|| request.body_length().is_some_and(|length| length != 0)
{
return None;
}
for name in [
"Connection",
"Upgrade",
"Sec-WebSocket-Version",
"Sec-WebSocket-Key",
] {
handshake = handshake.header(name, header(request, name)?);
}
let response = create_response(&handshake.body(()).ok()?).ok()?;
Header::from_bytes(
"Sec-WebSocket-Accept",
response.headers().get("Sec-WebSocket-Accept")?.as_bytes(),
)
.ok()
}
+48
View File
@@ -0,0 +1,48 @@
//! Per-compilation worker counters, sampled only when requested.
use serde::Serialize;
#[derive(Clone, Copy, Serialize)]
pub(super) struct ThreadUsage {
cpu_ms: f64,
voluntary_switches: u64,
involuntary_switches: u64,
block_inputs: u64,
block_outputs: u64,
}
impl ThreadUsage {
#[cfg(target_os = "linux")]
pub(super) fn current() -> Option<Self> {
let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
// A successful RUSAGE_THREAD call initializes the provided struct.
if unsafe { libc::getrusage(libc::RUSAGE_THREAD, usage.as_mut_ptr()) } != 0 {
return None;
}
let usage = unsafe { usage.assume_init() };
let millis = |time: libc::timeval| time.tv_sec as f64 * 1000.0 + time.tv_usec as f64 / 1000.0;
Some(Self {
cpu_ms: millis(usage.ru_utime) + millis(usage.ru_stime),
voluntary_switches: usage.ru_nvcsw as u64,
involuntary_switches: usage.ru_nivcsw as u64,
block_inputs: usage.ru_inblock as u64,
block_outputs: usage.ru_oublock as u64,
})
}
#[cfg(not(target_os = "linux"))]
pub(super) fn current() -> Option<Self> {
None
}
pub(super) fn between(start: Option<Self>, end: Option<Self>) -> Option<Self> {
let start = start?;
let end = end?;
Some(Self {
cpu_ms: end.cpu_ms - start.cpu_ms,
voluntary_switches: end.voluntary_switches.checked_sub(start.voluntary_switches)?,
involuntary_switches: end.involuntary_switches.checked_sub(start.involuntary_switches)?,
block_inputs: end.block_inputs.checked_sub(start.block_inputs)?,
block_outputs: end.block_outputs.checked_sub(start.block_outputs)?,
})
}
}
+103 -36
View File
@@ -33,7 +33,8 @@ pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, Project
pub use texrra_tex_core::resources::{WorldFailure, WorldObservation};
use texrra_tex_core::{
execution::{
Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits,
Cancellation, CheckpointCloneTimings, ExecutionFailure, Executor, FormatImage, InputProfile,
JobTime, Limits,
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
SourceProvider, State, SuffixKernelTimings, WriteDestination,
},
@@ -102,6 +103,8 @@ pub struct CheckpointTimings {
/// Restoring the executor, running new commands, observing checkpoints,
/// and finishing the revision's kernel result.
pub resume: Duration,
/// Executor clone times within resume, including captures rejected by the host.
pub clones: CheckpointCloneTimings,
pub capture: Duration,
pub suffix_host_validation: Duration,
pub suffix_kernel_validation: Duration,
@@ -121,9 +124,31 @@ pub trait CompileObserver: Send + Sync {
/// Observe the work of a resumed native revision before layout begins.
fn checkpoint_timings(&self, _revision: u64, _timings: CheckpointTimings) {}
/// Called for a completed native draft before its staged files are synced
/// and installed. The caller can display these pages provisionally. The
/// compile result determines whether this revision actually published.
/// Opt in to executor clone timings and individual suffix candidate observations.
fn wants_checkpoint_details(&self) -> bool {
false
}
/// Observe one candidate that reached the kernel. Donors are numbered in
/// the order considered, starting at zero. Acceptance here precedes replay.
fn suffix_candidate_timing(
&self,
_revision: u64,
_page: usize,
_donor_index: usize,
_accepted: bool,
_timings: SuffixKernelTimings,
) {}
/// Allow an SVG-only draft before export when the resolved pages do
/// not need the exported PDF to render.
fn preview_before_export(&self) -> bool {
false
}
/// Called once per compile attempt for a draft before publication. Observers
/// can receive SVG-only drafts before PDF export. The compile result
/// determines whether this revision actually published.
fn draft_ready(&self, _draft: DraftPreview<'_>) -> Result<(), String> {
Ok(())
}
@@ -131,27 +156,32 @@ pub trait CompileObserver: Send + Sync {
/// The same revision's native preview, available before artifact publication.
pub struct DraftPreview<'a> {
document: &'a CompiledDocument,
revision: u64,
pages: &'a [DisplayList],
preview: &'a PreviewState,
pdf: Option<&'a Arc<[u8]>>,
steps: usize,
work: &'a EntryCheckpointWork,
cancellation: &'a Cancellation,
}
impl DraftPreview<'_> {
pub fn preview_since(&self, visible_revision: Option<u64>) -> Result<PreviewUpdate, String> {
self.document.preview.render(
self.document.revision(),
&self.document.pages,
self.document.pdf.as_ref(),
self.preview.render(
self.revision,
self.pages,
self.pdf,
visible_revision,
|| check(self.cancellation).map_err(|error| error.to_string()),
)
}
pub fn execution_steps(&self) -> usize {
self.document.execution.execution.steps
self.steps
}
pub fn entry_checkpoint_work(&self) -> &EntryCheckpointWork {
&self.document.entry_checkpoint_work
self.work
}
}
fn notify(
@@ -290,6 +320,10 @@ pub enum FormatPreparation {
Reused,
}
impl CompiledDocument {
fn preview_base(&self) -> (u64, &[DisplayList], &PreviewState) {
(self.revision(), &self.pages, &self.preview)
}
pub fn revision(&self) -> u64 {
self.execution.revision
}
@@ -954,8 +988,8 @@ fn prepare_checked(
check(cancellation)?;
Ok((path, source, executor, output, format_preparation))
})();
evidence.world(&world);
let (path, source, executor, output, format_preparation) = prepared?;
let (path, source, executor, output, format_preparation) =
prepared.inspect_err(|_| evidence.world(&world))?;
let files = Files::new_with_terminal(
&path,
&output,
@@ -1272,7 +1306,7 @@ impl CompileJob {
files.write_layout_manifest(path, e, &pages, &source_map)?;
}
evidence.phase = AttemptPhase::Fonts;
let preview_fonts = if draft_mode {
let mut preview_fonts = if draft_mode {
PreviewFonts::default()
} else {
let mut forms = pages.first_mut().map(|first| std::mem::take(&mut first.forms))
@@ -1334,6 +1368,37 @@ impl CompileJob {
} else {
None
};
// Direct SVG uses the resolved, final page lists. PDF-dependent
// pages need the exported bytes and use the later draft boundary.
let draft_observer = checkpoints.and(request.observer.as_ref());
let early_preview = if let Some(observer) = draft_observer.filter(|observer| {
observer.preview_before_export() && request.target == Target::Shipouts
&& !dvi_mode && !draft_mode && !pages.is_empty()
&& !pages.iter().any(DisplayList::has_embedded_pdf)
}) {
let previous = self.compiler.latest();
let preview = PreviewState::new(
&pages,
previous.as_deref().map(CompiledDocument::preview_base),
false,
std::mem::take(&mut preview_fonts),
);
check(&cancellation)?;
let observed = observer.draft_ready(DraftPreview {
revision,
pages: &pages,
preview: &preview,
pdf: None,
steps: e.steps,
work: &entry_checkpoint_work,
cancellation: &cancellation,
});
check(&cancellation)?;
observed?;
Some(preview)
} else {
None
};
let mut dvi = None;
let (pdf, export_diagnostics) = if pages.is_empty() {
(None, Vec::new())
@@ -1396,25 +1461,22 @@ impl CompileJob {
})
.transpose()?;
let receipt = prepared.as_ref().map(|p| p.version(&output)).transpose()?;
let previous = self.compiler.latest();
// Identical PDF output allows direct reuse. When it differs,
// PDF previews validate the new page and its reachable objects.
let pdf_unchanged = pdf.is_some() && pages.iter().any(DisplayList::has_embedded_pdf)
&& previous
.as_deref()
.is_some_and(|document| document.pdf.as_deref() == pdf.as_deref());
let preview = PreviewState::new(
&pages,
previous.as_deref().map(|document| {
(
document.revision(),
document.pages.as_slice(),
&document.preview,
)
}),
pdf_unchanged,
preview_fonts,
);
let preview_sent_before_export = early_preview.is_some();
let preview = early_preview.unwrap_or_else(|| {
let previous = self.compiler.latest();
// Identical PDF output allows direct reuse. When it differs,
// PDF previews validate the new page and its reachable objects.
let pdf_unchanged = pdf.is_some() && pages.iter().any(DisplayList::has_embedded_pdf)
&& previous
.as_deref()
.is_some_and(|document| document.pdf.as_deref() == pdf.as_deref());
PreviewState::new(
&pages,
previous.as_deref().map(CompiledDocument::preview_base),
pdf_unchanged,
preview_fonts,
)
});
let result = Arc::new(CompiledDocument {
format_preparation,
entry_checkpoint_work,
@@ -1442,11 +1504,16 @@ impl CompileJob {
CompileStage::ReadyToPublish,
&cancellation,
)?;
if checkpoints.is_some()
&& let Some(observer) = &request.observer
if !preview_sent_before_export
&& let Some(observer) = draft_observer
{
let observed = observer.draft_ready(DraftPreview {
document: &result,
revision,
pages: &result.pages,
preview: &result.preview,
pdf: result.pdf.as_ref(),
steps: result.execution.execution.steps,
work: &result.entry_checkpoint_work,
cancellation: &cancellation,
});
check(&cancellation)?;
+155 -27
View File
@@ -1,5 +1,5 @@
//! Reuse a recorded entry prefix only after validating the current job host.
use super::checkpoint_probe::{Call, RecordingHost};
use super::checkpoint_probe::{Call, ClosedSourceUsageOffset, RecordingHost, closed_source_reads};
use super::*;
#[cfg(test)]
use std::fs;
@@ -10,7 +10,7 @@ use std::{
time::Instant,
};
use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport},
execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, RetainedStateFingerprint, StatisticsPhase, StatisticsReport},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -45,6 +45,7 @@ pub(super) struct PublishedCheckpoints {
current: Arc<CheckpointSet>,
previous_body: Option<Arc<CheckpointSet>>,
previous_completion: Option<Arc<CompletedExecution>>,
previous_fingerprint: Option<Arc<RetainedStateFingerprint>>,
}
struct CachedCheckpoint {
@@ -59,9 +60,17 @@ struct CompletedExecution {
result: Arc<RevisionExecution>,
guard: PrefixInputGuard,
calls: Arc<[Call]>,
trace: ResourceTrace,
settled: BTreeMap<usize, SettledCheckpoint>,
}
struct ClosedSourceSuffix {
source_id: usize,
prefix_resource_reads: usize,
version: ResourceVersion,
usage: ClosedSourceUsageOffset,
}
struct SettledCheckpoint {
entry: Arc<EntryCheckpoint>,
host: crate::native_job::ReplayBoundary,
@@ -82,6 +91,7 @@ pub(super) struct CheckpointSet {
pub(super) struct SelectedCheckpoint {
set: Arc<CheckpointSet>,
candidate: ExecutionCandidate,
previous_fingerprint: Option<Arc<RetainedStateFingerprint>>,
}
pub(super) struct ReusedShipoutLayouts {
@@ -417,6 +427,7 @@ impl<'a> CapturedEntries<'a> {
prior: &SettledCheckpoint,
completed: &CompletedExecution,
end_statistics: Option<&StatisticsReport>,
closed_source: Option<&ClosedSourceSuffix>,
host: &mut RecordingHost,
cancellation: &Cancellation,
) -> Result<(), String> {
@@ -426,9 +437,10 @@ impl<'a> CapturedEntries<'a> {
let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len();
let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1);
let mut later = [const { None }; SOURCE_INTERVALS];
// Untranslated live continuations and their source intervals still
// refer to the old entry when its length changed.
if previous_bytes == bytes
// Carried checkpoints still carry the donor's scanner and source
// allocations. An exhausted child edit also changes that history.
if closed_source.is_none()
&& previous_bytes == bytes
&& let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution)
{
// Keep the deepest compatible settled continuation per source interval.
@@ -451,7 +463,7 @@ impl<'a> CapturedEntries<'a> {
let Some(calls) = completed.calls.get(replayed..anchor.call_count) else {
continue;
};
host.replay_suffix(calls, end_statistics, cancellation)?;
host.replay_suffix(calls, end_statistics, None, cancellation)?;
replayed = anchor.call_count;
if anchor.host == host.files().replay_boundary() {
let regular = CaptureSlots {
@@ -464,7 +476,16 @@ impl<'a> CapturedEntries<'a> {
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
}
}
host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?;
host.replay_suffix(
&completed.calls[replayed..], end_statistics, closed_source.map(|child| child.usage),
cancellation,
)?;
if let Some(child) = closed_source {
let (trace, calls) = host.prefix().ok_or("child suffix host observations are unavailable")?;
if closed_source_reads(&child.version, trace, calls) != Some(child.prefix_resource_reads) {
return Err("completed suffix observed the changed child again".into());
}
}
completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string())
}
@@ -521,17 +542,18 @@ impl<'a> CapturedEntries<'a> {
recording.generated_outputs(),
self.initial?,
).ok()?;
Some(guard)
Some((guard, trace.clone()))
}).flatten();
let mut calls = recording.into_calls()?;
if completion.is_none() {
calls.truncate(replay_count);
}
let calls = Arc::<[Call]>::from(calls);
let completion = completion.map(|guard| Arc::new(CompletedExecution {
let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution {
result: result.clone(),
guard,
calls: calls.clone(),
trace,
settled: self.settled,
}));
Some(Arc::new(CheckpointSet {
@@ -607,10 +629,23 @@ impl CheckpointCache {
let previous_completion = published.as_ref().and_then(|published| {
published.current.completion.clone().or_else(|| published.previous_completion.clone())
});
let previous_fingerprint = published.as_ref().and_then(|published| {
if let Some((before, after)) = published.current.completion.as_ref().zip(next.completion.as_ref()) {
let before = &before.result.execution;
let after = &after.result.execution;
// Equal results should not evict the other distinct state.
// A hash mismatch proves distinctness, but a match does not prove equality.
if before.outgoing_state != after.outgoing_state || before.state != after.state {
return Some(Arc::new(before.retain_final_state_fingerprint()));
}
}
published.previous_fingerprint.clone()
});
*published = Some(Arc::new(PublishedCheckpoints {
current: next,
previous_body,
previous_completion,
previous_fingerprint,
}));
}
@@ -672,6 +707,7 @@ impl PublishedCheckpoints {
SelectedCheckpoint {
set: self.current.clone(),
candidate: ExecutionCandidate::Completed(result.clone()),
previous_fingerprint: None,
}
}))
.collect();
@@ -741,7 +777,7 @@ impl PublishedCheckpoints {
EffectMode::Draft,
KernelPreparation::Resume,
)?;
let selected = selected.expect("resume preparation chose a verified checkpoint");
let mut selected = selected.expect("resume preparation chose a verified checkpoint");
let guard = selected.guard();
let partial_source = guard.nested_source.as_ref()
.and_then(|source| project.file(&source.path)).map(|file| &file.version);
@@ -763,6 +799,7 @@ impl PublishedCheckpoints {
continue;
}
*evidence = attempt;
selected.previous_fingerprint = self.previous_fingerprint.clone();
return Ok((selected, prepared));
}
}
@@ -805,6 +842,7 @@ impl CheckpointSet {
.map(|index| SelectedCheckpoint {
set: Arc::clone(self),
candidate: ExecutionCandidate::Boundary(index),
previous_fingerprint: None,
})
}
}
@@ -962,15 +1000,19 @@ impl SelectedCheckpoint {
let mut suffix_base = None;
let mut reused_layouts = None;
let mut timings = CheckpointTimings::default();
let timed = request.observer.is_some();
let observer = request.observer.as_deref();
let timed = observer.is_some();
let detailed_observer = observer.filter(|observer| observer.wants_checkpoint_details());
let mut clones = CheckpointCloneTimings::default();
let resume_started = timed.then(Instant::now);
let result = job
.resume_deciding_suffix(
.resume_deciding_suffix_observed(
&checkpoint.entry,
source,
nested_source,
&mut recording,
line_break_cache,
detailed_observer.is_some().then_some(&mut clones),
|source, pages| {
if source.is_entry {
// The loaded entry line can be shared by several shipouts.
@@ -996,23 +1038,43 @@ impl SelectedCheckpoint {
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
return CheckpointDecision::Continue;
};
let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| {
let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().enumerate().find_map(|(donor_index, completed)| {
let old = completed.settled.get(&page)?;
let host_matches = measure(&mut timings.suffix_host_validation, timed, || {
old.call_count == new.call_count
&& new.host.matches_for_suffix(&old.host)
let closed_source = measure(&mut timings.suffix_host_validation, timed, || {
if old.call_count != new.call_count {
return None;
}
if new.host.matches_for_suffix(&old.host)
&& can_replay_completed_suffix(completed, request, host.files())
});
if !host_matches {
return None;
}
let kernel_timings = timed.then_some(&mut timings.suffix_kernel);
let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || {
entry.splice_settled_suffix_observed(
&old.entry, &completed.result.execution, kernel_timings,
)
{
return Some(None);
}
let change = entry.closed_source_change(&old.entry, &completed.result.execution)?;
prove_closed_source_suffix(change, old, new, completed, request, host)
.map(Some)
})?;
Some((completed, old, execution, layout))
let mut attempt = detailed_observer.map(|_| SuffixKernelTimings {
state_proof: Some(Default::default()),
..SuffixKernelTimings::default()
});
let result = measure(&mut timings.suffix_kernel_validation, timed, || {
let kernel_timings = attempt.as_mut().or(timed.then_some(&mut timings.suffix_kernel));
entry.splice_settled_suffix_with_fingerprint(
&old.entry,
&completed.result.execution,
closed_source.as_ref().map(|child| (child.source_id, child.prefix_resource_reads)),
self.previous_fingerprint.as_deref(),
kernel_timings,
)
});
if let Some((observer, attempt)) = detailed_observer.zip(attempt) {
timings.suffix_kernel += attempt;
observer.suffix_candidate_timing(
job.revision(), page, donor_index, result.is_some(), attempt,
);
}
let (execution, layout) = result?;
Some((completed, old, execution, layout, closed_source))
}) else {
return CheckpointDecision::Continue;
};
@@ -1024,7 +1086,8 @@ impl SelectedCheckpoint {
});
let replayed = measure(&mut timings.suffix_host_replay, timed, || {
captures.replay_settled_suffix(
page, &entry, old, completed, end_statistics, host, &cancellation,
page, &entry, old, completed, end_statistics,
closed_source.as_ref(), host, &cancellation,
)
});
if let Err(error) = replayed {
@@ -1053,6 +1116,7 @@ impl SelectedCheckpoint {
.ok_or_else(changed_prefix)?;
if let Some(started) = resume_started {
timings.resume = started.elapsed();
timings.clones = clones;
}
let next = measure(&mut timings.retain, timed, || {
result.as_ref().ok().and_then(|result| captures.finish(recording, true, result, suffix_base))
@@ -1090,6 +1154,61 @@ fn can_replay_completed_suffix(
completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok()
}
fn prove_closed_source_suffix(
change: ClosedSourceChange<'_>,
old: &SettledCheckpoint,
current: &SettledCheckpoint,
completed: &CompletedExecution,
request: &CompileRequest,
host: &RecordingHost<'_>,
) -> Option<ClosedSourceSuffix> {
let path = Path::new(change.name);
let guard = &completed.guard;
let next_project = request.project.as_deref()?;
if path == guard.entry || !guard.immutable.contains(path) || guard.generated.contains(path)
|| !guard.project.immutable_paths().eq(next_project.immutable_paths())
{
return None;
}
// The child route cannot simultaneously relocate or replace the entry.
if guard.project.file(&guard.entry)?.version != next_project.file(&guard.entry)?.version {
return None;
}
let previous = &guard.project.file(path)?.version;
let current_version = &next_project.file(path)?.version;
if previous == current_version || previous.path != path || current_version.path != path
|| previous.bytes != u64::try_from(change.previous_bytes).ok()?
|| current_version.bytes != u64::try_from(change.current_bytes).ok()?
{
return None;
}
let (trace, calls) = host.prefix()?;
if calls.len() != current.call_count || trace.project_version.as_ref() != Some(next_project.version()) {
return None;
}
let prefix_resource_reads = closed_source_reads(
previous, old.host.trace_for_suffix(), completed.calls.get(..old.call_count)?,
)?;
// In the donor's whole job, the only observations of the child must
// be the reads already present at the splice. The live prefix has
// actually made the same count of allowed observations of its new version.
if closed_source_reads(previous, &completed.trace, &completed.calls)? != prefix_resource_reads
|| closed_source_reads(current_version, trace, calls)? != prefix_resource_reads
|| !current.host.matches_for_closed_source_suffix(&old.host, previous, current_version)
{
return None;
}
let files = host.files();
let project = guard.verify_project_with_closed_source(request, Some(path)).ok()?;
guard.verify_host(project, files.replay_world(), files.preparation()).ok()?;
Some(ClosedSourceSuffix {
source_id: change.source_id,
prefix_resource_reads,
version: current_version.clone(),
usage: ClosedSourceUsageOffset::new(previous.bytes, current_version.bytes, prefix_resource_reads)?,
})
}
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
if previous == current {
return None;
@@ -1317,6 +1436,14 @@ impl PrefixInputGuard {
fn verify_project<'a>(
&self,
request: &'a CompileRequest,
) -> Result<&'a ProjectSnapshot, String> {
self.verify_project_with_closed_source(request, None)
}
fn verify_project_with_closed_source<'a>(
&self,
request: &'a CompileRequest,
closed_source: Option<&Path>,
) -> Result<&'a ProjectSnapshot, String> {
let old = &self.original;
if old.input != request.input
@@ -1354,6 +1481,7 @@ impl PrefixInputGuard {
let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and(
|(old, new)| {
old.version == new.version
|| closed_source == Some(path.as_path())
|| self.nested_source.as_ref().is_some_and(|source| &source.path == path)
|| self.immutable_sizes.get(path) == Some(&new.version.bytes)
|| self.immutable_stream_prefixes.get(path).is_some_and(|&end| {
+82
View File
@@ -42,6 +42,75 @@ pub(super) struct RebindableSourceObservations {
pub(super) size: Option<u64>,
}
#[derive(Clone, Copy)]
pub(super) struct ClosedSourceUsageOffset {
previous: u64,
current: u64,
}
impl ClosedSourceUsageOffset {
pub(super) fn new(previous: u64, current: u64, reads: usize) -> Option<Self> {
let reads = u64::try_from(reads).ok()?;
Some(Self {
previous: previous.checked_mul(reads)?,
current: current.checked_mul(reads)?,
})
}
}
/// Return the entire byte-read count of a closed immutable child, including
/// typed size queries. Every other observation of the child rules out reuse.
pub(super) fn closed_source_reads(
version: &ResourceVersion,
trace: &ResourceTrace,
calls: &[Call],
) -> Option<usize> {
let path = &version.path;
if trace.stream_reads.iter().any(|read| &read.path == path)
|| trace.file_modifications.iter().any(|item| &item.path == path)
|| trace.generated_lookups.iter().any(|lookup| &lookup.target == path)
|| trace.format_input_bindings.iter().any(|(old, current)| old == path || current == path)
|| trace.read_errors.iter().any(|(read, _)| read == path)
|| !trace.namespace_capture_failures.is_empty()
{
return None;
}
let mut sources = 0usize;
let mut sizes = 0usize;
for call in calls {
match call {
Call::ReadSource(source) => {
if let Ok(read) = &source.expected
&& &read.path == path
{
if read != version {
return None;
}
sources += 1;
}
}
Call::FileSize(size) if size.read.as_ref().is_some_and(|read| &read.path == path) => {
// A size query can have been replayed from an equal-sized
// earlier source. Its exact path and numeric result are
// evidence, while the actual trace authenticates the bytes.
if call.observed_file_size() != Some((path.as_path(), version.bytes)) {
return None;
}
sizes += 1;
}
_ => {}
}
}
let count = sources.checked_add(sizes)?;
let mut actual = trace.reads.iter().filter(|read| &read.path == path);
if sources != 1 || actual.clone().count() != count || !actual.all(|read| read == version) {
return None;
}
let mut lookups = trace.lookups.iter().filter(|lookup| lookup.resolved.as_ref() == Some(path));
(lookups.clone().count() == count && lookups.all(|item| item.kind == ResourceKind::Tex))
.then_some(count)
}
impl Call {
pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> {
let Self::FileSize(read) = self else { return None };
@@ -178,6 +247,7 @@ impl<'a> RecordingHost<'a> {
&mut self,
calls: &[Call],
end_statistics: Option<&StatisticsReport>,
closed_source: Option<ClosedSourceUsageOffset>,
cancellation: &Cancellation,
) -> Result<(), String> {
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
@@ -196,6 +266,18 @@ impl<'a> RecordingHost<'a> {
Call::EndStatistics(Arc::new(translated.clone()))
}
}
Call::ResourceUsage(read) if closed_source.is_some_and(|bytes| bytes.previous != bytes.current) => {
let bytes = closed_source.expect("checked closed source adjustment");
let mut observed = read.observed.clone();
if let Some(usage) = &mut observed {
usage.rebind_entry_bytes(bytes.previous, bytes.current)
.ok_or("invalid replayed child resource usage")?;
}
Call::ResourceUsage(Arc::new(ResourceUsageRead {
observed,
entry_bytes: read.entry_bytes,
}))
}
call => call.clone(),
};
call.replay(self.files, None)?;
+126 -7
View File
@@ -169,6 +169,42 @@ impl ReplayBoundary {
pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool {
self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state
}
pub(super) fn trace_for_suffix(&self) -> &texrra_tex_core::resources::ResourceTrace {
&self.state.trace
}
/// The caller proves that all reads of this canonical path are the
/// closed source or its typed size queries, and that none are in the tail.
pub(super) fn matches_for_closed_source_suffix(
&self,
prior: &Self,
previous: &ResourceVersion,
current: &ResourceVersion,
) -> bool {
if self.entry_bytes.is_none() || self.entry_bytes != prior.entry_bytes {
return false;
}
let ReplayState {
inputs, outputs, next_handle, columns, terminal_enabled, generated_reads,
generated_before, generated_written, trace, stream_events,
} = &self.state;
let old = &prior.state;
if inputs != &old.inputs || outputs != &old.outputs || next_handle != &old.next_handle
|| columns != &old.columns || terminal_enabled != &old.terminal_enabled
|| generated_reads != &old.generated_reads || generated_before != &old.generated_before
|| generated_written != &old.generated_written || stream_events != &old.stream_events
{
return false;
}
let mut old_trace = old.trace.clone();
for read in &mut old_trace.reads {
if read == previous {
*read = current.clone();
}
}
*trace == old_trace
}
}
#[derive(PartialEq, Eq)]
@@ -446,8 +482,15 @@ impl Files {
ArtifactLedger::new(cwd.clone())
};
preparation.phase = HostPreparationPhase::Protection;
let declared: BTreeSet<_> = world
.project()
.map(|project| project.generated().collect())
.unwrap_or_default();
// The explicit role validates this path immediately before
// observing its actual version. Prune only the other claims here.
let immutable_claims: Vec<_> = ledger
.paths()
.filter(|path| !declared.contains(path))
.filter(|path| {
preparation.aliases_any(
path,
@@ -462,13 +505,9 @@ impl Files {
for path in immutable_claims {
ledger.forget(&path);
}
let declared: Vec<_> = world
.project()
.map(|p| p.generated().map(Path::to_path_buf).collect())
.unwrap_or_default();
for path in declared {
if preparation.aliases_any(
&path,
path,
protected
.iter()
.chain(std::iter::once(&log_path))
@@ -476,11 +515,11 @@ impl Files {
) {
return Err("atomic generated role aliases a protected input or output".into());
}
let observed = file_version(&path);
let observed = file_version(path);
preparation
.observations
.push(crate::native_host::HostObservation::VersionCheck {
path: path.clone(),
path: path.to_owned(),
expected: crate::native_host::VersionExpectation::Any,
observed: observed.clone(),
});
@@ -3003,6 +3042,86 @@ mod generated_file_tests {
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn preparation_checks_overlapping_generated_roles_once_before_reading_the_version() {
use crate::native_host::HostObservation;
use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot};
let root = root().canonicalize().unwrap();
let source = root.join("main.tex");
let generated = root.join("actual.aux");
let ledger = {
let mut seed = files(&root, "main.tex").unwrap();
write(&mut seed, "actual.aux", "prior version");
seed.finish().unwrap();
seed.ledger_path.clone()
};
let original_ledger = fs::read(&ledger).unwrap();
let original_log = fs::read(root.join("job.log")).unwrap();
fs::write(&generated, b"new version before preparation").unwrap();
let expected = file_version(&generated).unwrap();
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: WorldConfig::new(&root),
revision: 1,
roots: BTreeSet::from([root.clone()]),
files: BTreeMap::from([(source.clone(), Arc::from(br"\end".as_slice()))]),
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([root.clone()]),
generated: BTreeSet::from([generated.clone()]),
})
.unwrap();
let prepare = |preparation: &mut HostPreparation| {
let mut world = FileWorld::from_project(project.clone()).unwrap();
world.read(ResourceKind::Tex, "main.tex", &root).unwrap();
Files::prepare_observed(
&source,
&root.join("job.pdf"),
world,
Ok(root.join("policy")),
false,
&GeneratedInputPolicy::Observe,
preparation,
None,
EffectMode::Draft,
)
};
let mut preparation = HostPreparation::default();
let mut host = prepare(&mut preparation).unwrap_or_else(|error| panic!("{}", error.error));
let aliases = preparation.observations.iter().filter(|observation| {
matches!(observation, HostObservation::Alias { left, right, same: false }
if left == &source && right == &generated)
});
assert_eq!(aliases.count(), 1);
assert_eq!(
preparation.generated_initial.as_ref().unwrap().files().get(&generated),
Some(&expected)
);
assert_eq!(
host.read("actual.aux", "").unwrap().data,
b"new version before preparation"
);
assert_eq!(host.generated_reads.get(&generated), expected.as_ref());
drop(host);
fs::remove_file(&generated).unwrap();
fs::hard_link(&source, &generated).unwrap();
let mut preparation = HostPreparation::default();
let failure = prepare(&mut preparation).err().expect("hardlink aliases a source");
assert!(failure.error.contains("atomic generated role aliases"));
assert_eq!(preparation.phase, HostPreparationPhase::Protection);
assert!(preparation.observations.iter().any(|observation| {
matches!(observation, HostObservation::Alias { left, right, same: true }
if left == &source && right == &generated)
}));
assert_eq!(fs::read(&source).unwrap(), br"\end");
assert_eq!(fs::read(&generated).unwrap(), br"\end");
assert_eq!(fs::read(root.join("job.log")).unwrap(), original_log);
assert_eq!(fs::read(&ledger).unwrap(), original_ledger);
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn preparation_alias_rejection_records_actual_hardlink_identity() {
+1 -1
View File
@@ -248,7 +248,7 @@ impl PreviewState {
});
pdf.render_page(index, page.pdf_user_unit(), prior)
} else {
page.try_to_svg().map(|svg| CachedPage {
page.try_to_preview_svg().map(|svg| CachedPage {
svg: Arc::from(svg),
pdf_page: None,
same_as_previous: false,
+164 -16
View File
@@ -1763,29 +1763,29 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() {
}
#[test]
fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() {
fn settled_suffix_distinguishes_removed_prefix_reads_from_repeated_suffix_reads() {
use texrra_tex_core::execution::Dependency;
let cwd = directory("settled-prefix-dependencies");
let entry = cwd.join("main.tex");
let body = |ignored| format!(r"
let body = |ignored, repeat| format!(r"
\catcode64=9 \catcode63=9
?\relax
\shipout\hbox{{Cover}}\relax
{ignored}\relax
\shipout\hbox{{Checkpoint}}\relax
\shipout\hbox{{Suffix}}\relax
{repeat}\relax\shipout\hbox{{Suffix}}\relax
\endinput\shipout\hbox{{Final}}\relax\end
");
for (before, after, reuse) in [('?', '@', true), ('@', '?', false)] {
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap();
for (before, after, repeat) in [('?', '@', '?'), ('@', '?', '?'), ('@', '?', '@')] {
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before, repeat))).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
let new_read = Dependency::CatCode('@');
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@');
let source = format!("{HEADER}{}", body(after));
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@' || repeat == '@');
let source = format!("{HEADER}{}", body(after, repeat));
let project = project.with_file_edits(
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
).unwrap();
@@ -1793,8 +1793,8 @@ fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() {
let updated = session.compile(input.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
assert!(!work.reused_completion, "{work:?}");
assert_eq!(work.reused_suffix_steps > 0, reuse, "{work:?}");
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@');
assert!(work.reused_suffix_steps > 0, "{work:?}");
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@' || repeat == '@');
let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(input).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
@@ -1862,6 +1862,134 @@ fn settled_suffix_translates_cumulative_box_charges_in_both_directions() {
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn settled_suffix_translates_final_retained_statistics_for_unequal_histories() {
use texrra_tex_core::execution::{Event, StatisticsPhase};
let cwd = directory("settled-retained-history");
let entry = cwd.join("main.tex");
let body = |stats, text| format!(r"
\tracingstats={stats}
\shipout\hbox{{Cover with x}}\relax
\shipout\hbox{{{text}}}\relax
\shipout\hbox{{Suffix}}\relax
\endinput\shipout\hbox{{Final}}\relax\end
");
let retained = |document: &CompiledDocument| {
let Some(Event::Statistics(report)) = document.execution.execution.events.last() else {
panic!("missing final resource report");
};
let StatisticsPhase::End { usage, .. } = &report.phase else {
panic!("expected final resource report");
};
(usage.retained_events, usage.retained_material.horizontal_nodes)
};
for (stats, before, after, reuse) in [
(1, "x", "xxxxxxx", true),
(1, "xxxxxxx", "x", true),
(2, "x", "xxxxxxx", false),
] {
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(stats, before))).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
let source = format!("{HEADER}{}", body(stats, after));
let project = project.with_file_edits(
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
).unwrap();
let input = request.with_project(project);
let updated = session.compile(input.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
assert!(!work.reused_completion, "{work:?}");
if reuse {
assert!(work.reused_suffix_steps > 0, "{work:?}");
}
assert_ne!(retained(&updated), retained(&donor));
let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(input).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
assert_eq!(updated.resources.trace, full.resources.trace);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
}
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn settled_suffix_reuses_an_exhausted_child_and_adjusts_repeated_resource_reads() {
use texrra_tex_core::execution::{Event, ResourceUsage, StatisticsPhase};
let cwd = directory("closed-child-suffix");
let child = cwd.join("chapter.tex");
let body = r"
\tracingstats=1
\shipout\hbox{Cover}\relax
\begingroup
\count0=\pdffilesize{chapter.tex}\relax
\count0=\pdffilesize{chapter.tex}\relax
\endgroup
\input chapter.tex
\shipout\hbox{Page with \childtext}\relax
\shipout\hbox{Suffix with \childtext}\relax
\endinput\shipout\hbox{Final}\relax\end
";
let child_source = |comment| format!("% {comment}\n\\def\\childtext{{Body}}\n").into_bytes();
let previous_bytes = child_source("old");
let current_bytes = child_source("the expanded frozen comment");
let extra = current_bytes.len() - previous_bytes.len();
let end_usage = |result: &CompiledDocument| -> ResourceUsage {
let Some(Event::Statistics(report)) = result.execution.execution.events.last() else {
panic!("missing final resource report");
};
let StatisticsPhase::End { usage, .. } = &report.phase else {
panic!("expected final resource report");
};
usage.clone()
};
let mut definition = atomic_definition(&cwd, 1, body);
definition.files.insert(child.clone(), Arc::from(previous_bytes));
let project = ProjectSnapshot::new(definition).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let original = session.compile(request.clone().with_project(project.clone())).unwrap();
let project = project.with_file_edits(
2, [(child.clone(), Arc::from(current_bytes))].into(),
).unwrap();
let input = request.with_project(project);
let updated = session.compile(input.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
assert!(!work.reused_completion && work.reused_suffix_steps > 0, "{work:?}");
let actual_child_reads = updated.resources.trace.reads.iter().filter(|read| read.path == child).count();
assert_eq!(actual_child_reads, 3);
let before = end_usage(&original);
let after = end_usage(&updated);
assert_eq!(after.source_payload_bytes, before.source_payload_bytes + extra);
assert_eq!(after.mouth_payload_bytes, before.mouth_payload_bytes);
assert_eq!(
after.host.unwrap().resource_bytes_read,
before.host.unwrap().resource_bytes_read + (actual_child_reads * extra) as u64,
);
assert_ne!(updated.source_map.pages, original.source_map.pages);
let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(input).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
assert_eq!(updated.resources.trace, full.resources.trace);
assert_eq!(updated.resources.stream_io, full.resources.stream_io);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.pages, full.pages);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages);
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn resized_entry_prefix_reuses_verified_statistics() {
let cwd = directory("resized-entry-statistics");
@@ -2708,13 +2836,24 @@ fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts(
artifacts: [Vec<u8>; 3],
update: Mutex<Option<PreviewUpdate>>,
action: Action,
early: bool,
exported: Mutex<bool>,
}
impl CompileObserver for WatchDraft {
fn stage(&self, _: u64, _: CompileStage) -> Result<(), String> {
fn stage(&self, _: u64, stage: CompileStage) -> Result<(), String> {
if stage == CompileStage::Exported {
*self.exported.lock().unwrap() = true;
}
Ok(())
}
fn preview_before_export(&self) -> bool {
self.early
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
assert_eq!(*self.exported.lock().unwrap(), !self.early);
assert!(self.update.lock().unwrap().is_none());
assert!(Arc::ptr_eq(
&self.previous,
&self.compiler.latest().unwrap()
@@ -2776,12 +2915,15 @@ fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts(
)
.unwrap();
let mut request = request.with_project(changed);
let mut cancelled = None;
for action in [
Action::Supersede,
let mut cancelled: Option<PreviewUpdate> = None;
for (action, early) in [
(Action::Supersede, false),
(Action::Supersede, true),
#[cfg(unix)]
Action::Conflict,
Action::Publish,
(Action::Conflict, false),
#[cfg(unix)]
(Action::Conflict, true),
(Action::Publish, true),
] {
let observer = Arc::new(WatchDraft {
compiler: compiler.clone(),
@@ -2790,6 +2932,8 @@ fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts(
artifacts: artifacts.clone(),
update: Mutex::new(None),
action,
early,
exported: Mutex::new(false),
});
request.observer = Some(observer.clone());
let result = compiler.compile_detailed(request.clone());
@@ -2798,7 +2942,8 @@ fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts(
let failure = result.err().unwrap();
if matches!(action, Action::Supersede) {
assert!(matches!(failure.error, CompileError::Cancelled));
assert_eq!(failure.phase, AttemptPhase::ReadyToPublish);
let phase = if early { AttemptPhase::Export } else { AttemptPhase::ReadyToPublish };
assert_eq!(failure.phase, phase);
} else {
assert!(failure.error.to_string().contains("aliases"), "{failure:?}");
assert_eq!(failure.phase, AttemptPhase::Publishing);
@@ -2809,6 +2954,9 @@ fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts(
["job.pdf", "job.log", "state.dat"].map(|name| fs::read(p.join(name)).unwrap()),
artifacts,
);
if let Some(previous_draft) = &cancelled {
assert_eq!(update.pages, previous_draft.pages);
}
cancelled = Some(update);
} else {
let document = result.unwrap();