unityrs_export/ngui/seam.rs
1//! The engine seam (`docs/plans/batch.md` 2.6; review round 1's G1): the
2//! cutter is one phase of an attempt the engine owns. The engine registers
3//! the view ([`super::register`]), makes `M_X`, the key table and the sink,
4//! and hands them over in a [`Context`]; the cutter selects, plans and
5//! exports inside it, and returns what it recorded ([`super::Cut`]).
6//!
7//! The context's checks, each at the sites 2.6 names:
8//! - **the stop** ([`Hooks::stopped`]) between objects, sheet groups and
9//! outputs (step 11): a stopped attempt returns [`Failure::Stopped`] at
10//! once;
11//! - **evictions** after each Environment call (step 7): past
12//! `max_attempt_evictions` X fails, `limit(attempt_evictions, <value>)`,
13//! after the call's run-level class and before any other;
14//! - **export work** (step 10) at each pixel buffer's charge, before the
15//! decode that fills it ([`Hooks::export_work`]); the exception is a
16//! Sprite's render, whose intermediates are bounded by `M_X`'s charges
17//! and its decode work, and whose image is counted when the render
18//! returns it, after answer 11 and before its PNG; a file's increment is
19//! the sink's, at its claim;
20//! - **the refusal probe** (2.7) around each core call on its own: a
21//! `budget(...)` refusal during which the attempt budget's refusal count
22//! did not move was no budget's, so it is `host_memory`, a stop.
23//!
24//! Every output is handed to the sink as it is made, and the cutter keeps
25//! nothing of it, so each buffer is the sink's to drop before the next is
26//! made (2.8); a sheet's decode is dropped after its group (step 6).
27
28use std::sync::Arc;
29
30use unityrs_core::RawStr;
31use unityrs_core::env::Environment;
32use unityrs_core::files::BundleFile;
33use unityrs_core::limits::{Charge, Meter};
34
35use super::classify::{Class, Reason};
36use super::keys::{KeyTable, Template, TemplateKind};
37use super::{Failure, Output};
38
39/// What the engine's attempt answers for the cutter. Each method is called
40/// with no core lock held; an engine answers from its atomics.
41pub trait Hooks {
42 /// Whether the run has stopped (2.11).
43 fn stopped(&self) -> bool {
44 false
45 }
46
47 /// The attempt budget's refusal count (2.7), or none when the caller
48 /// counts none, which turns the probe off.
49 fn refusals(&self) -> Option<u64> {
50 None
51 }
52
53 /// Cumulative allocator observations for this attempt, separate from budget
54 /// refusals. Once nonzero, no further core call or publication is allowed,
55 /// even when optional work returned success after absorbing the failure.
56 fn allocator_refusals(&self) -> u64 {
57 0
58 }
59
60 /// Remaining engine export work before the next scoped collection.
61 fn export_work_remaining(&self) -> u64 {
62 u64::MAX
63 }
64
65 /// Counts `bytes` of export work (2.6 step 10): past
66 /// `max_export_work`, X's failure, `limit(export_work, <value>)`.
67 fn export_work(&self, bytes: u64) -> Result<(), Reason> {
68 let _ = bytes;
69 Ok(())
70 }
71
72 /// Test-only: the cut recorded a skip row, at export (`true`) or at
73 /// plan, as it recorded it (X13's reference model).
74 #[cfg(feature = "test-hooks")]
75 fn skipped(&self, _exporting: bool) {}
76
77 /// Test-only substitution, invoked inside texture panic containment.
78 #[cfg(feature = "test-hooks")]
79 fn decoder_fault(&self) {}
80
81 /// Test-only substitution of a registration Environment call's result,
82 /// after the real call has updated its eviction counters.
83 #[cfg(feature = "test-hooks")]
84 fn environment_fault(&self, _env: &Environment) -> Option<unityrs_core::Error> {
85 None
86 }
87
88 /// Meter sampled while the attempt holds a file, before its handle drops.
89 fn meter(&self, _meter: &Meter) {}
90
91 /// Environment figures after a call, including failed calls.
92 fn environment(&self, _env: &Environment) {}
93
94 /// A sprite group's export begins (4.4): told once for each of its
95 /// Sprites, in plan order, by the Sprite's file's name and its path id,
96 /// the group numbered `group` in export order. What the plan grouped,
97 /// for an observer (a test, B3's review round 3, T1); nothing is asked.
98 /// The name is the SerializedFile's, as an output's and a skip's are, so
99 /// two files of one CAB name (one nested) tell an observer the same
100 /// name: one that must tell such Sprites apart cannot from this alone
101 /// (review round 4, R8), as the records cannot.
102 fn sprite_group(&self, group: usize, file: &RawStr, path_id: i64) {
103 let _ = (group, file, path_id);
104 }
105}
106
107/// Hooks that never stop, count no refusal and bound no work: a tool's.
108#[derive(Clone, Copy, Debug, Default)]
109pub struct NoHooks;
110
111impl Hooks for NoHooks {}
112
113/// An archive's `members` entry (1.6, 4.7): its archive's index, its kind,
114/// and its path's template.
115#[derive(Clone, Debug)]
116pub struct MemberTemplate {
117 /// The archive's index in the spec.
118 pub archive: usize,
119 /// The kind of output it takes.
120 pub kind: TemplateKind,
121 /// Its path.
122 pub path: Template,
123}
124
125/// The view the engine registered ([`super::register`]): the private
126/// Environment, and X's own handle on `M_X`.
127pub struct Registered {
128 /// The private Environment, `view(X)` registered, X last.
129 pub env: Environment,
130 /// X's own open (2.6 step 2), on `M_X`: selection reads through it.
131 pub own: Arc<BundleFile>,
132 /// The charge of X's bytes to `M_X` when they were in hand
133 /// (`Data::Bytes`; a staged file's read carries its own).
134 pub(super) _held: Option<Charge>,
135}
136
137/// The engine's attempt, as the cutter sees it.
138pub struct Context<'a> {
139 /// The registered view.
140 pub registered: &'a Registered,
141 /// `M_X`.
142 pub meter: &'a Arc<Meter>,
143 /// X's spec id (`{input}`).
144 pub input: &'a str,
145 /// The stop flag, the refusal count and export work.
146 pub hooks: &'a dyn Hooks,
147 /// `max_attempt_evictions` (1.1).
148 pub max_evictions: u64,
149 /// The sink's key prefix (2.3), checked after the key.
150 pub prefix: &'a str,
151 /// Every archive's `members` entries.
152 pub members: &'a [MemberTemplate],
153 /// The attempt's one key table, for every kind's stage.
154 pub keys: &'a mut KeyTable,
155 /// Where each output goes as it is made (2.8's copy-out).
156 pub sink: &'a mut dyn FnMut(Output) -> Result<(), Failure>,
157}
158
159/// The context's shared part: what every site reads.
160#[derive(Clone, Copy)]
161pub(super) struct Seam<'a> {
162 pub registered: &'a Registered,
163 pub meter: &'a Arc<Meter>,
164 pub hooks: &'a dyn Hooks,
165 pub max_evictions: u64,
166 pub prefix: &'a str,
167 pub members: &'a [MemberTemplate],
168}
169
170impl<'a> Seam<'a> {
171 pub fn env(&self) -> &'a Environment {
172 &self.registered.env
173 }
174
175 /// The stop check: [`Failure::Stopped`] once the run stopped.
176 pub fn stop(&self) -> Result<(), Failure> {
177 allocator_check(self.hooks).map_err(Failure::from)?;
178 if self.hooks.stopped() {
179 Err(Failure::Stopped)
180 } else {
181 Ok(())
182 }
183 }
184
185 /// The eviction check, after an Environment call (2.6 step 7).
186 pub fn evictions(&self) -> Result<(), Class> {
187 evictions(self.env(), self.max_evictions)
188 }
189
190 /// `f`, one core call (or one charge), under the refusal probe (2.7).
191 pub fn probe<T>(&self, f: impl FnOnce() -> Result<T, Class>) -> Result<T, Class> {
192 probe(self.hooks, f)
193 }
194
195 /// An Environment call: the probe, then 2.6 step 7's order: a
196 /// run-level class first, then the evictions, then the rest.
197 pub fn env_call<T>(&self, f: impl FnOnce() -> Result<T, Class>) -> Result<T, Class> {
198 let out = self.probe(f);
199 self.hooks.environment(self.env());
200 if let Err(Class::Run(_)) = &out {
201 return out;
202 }
203 self.evictions()?;
204 out
205 }
206
207 /// Export work for a buffer of `bytes` pixel bytes, before it is made.
208 pub fn work(&self, bytes: u64) -> Result<(), Class> {
209 self.hooks.export_work(bytes).map_err(Class::Input)
210 }
211}
212
213/// [`Seam::evictions`] on `env`: registration's too.
214pub(super) fn evictions(env: &Environment, max: u64) -> Result<(), Class> {
215 if env.stats().dependencies_evicted > max {
216 let reason = format!("limit(attempt_evictions, {max})");
217 return Err(Class::Input(Reason::plain(reason)));
218 }
219 Ok(())
220}
221
222/// [`Seam::probe`] on `hooks`.
223pub(super) fn probe<T>(
224 hooks: &dyn Hooks,
225 f: impl FnOnce() -> Result<T, Class>,
226) -> Result<T, Class> {
227 allocator_check(hooks)?;
228 let before = hooks.refusals();
229 let out = f();
230 allocator_check(hooks)?;
231 out.map_err(|c| probed(hooks, before, c))
232}
233
234/// A sticky allocator audit also rejects successful calls that absorbed an
235/// optional failure. Check before running another call as well as afterwards.
236pub(super) fn allocator_check(hooks: &dyn Hooks) -> Result<(), Class> {
237 if hooks.allocator_refusals() != 0 {
238 Err(Class::Run(Reason::plain("host_memory")))
239 } else {
240 Ok(())
241 }
242}
243
244/// The probe's rule for one core call's class `c`, the refusal count
245/// having been `before` when the call began: a `budget(...)` refusal
246/// during which the count did not move is `host_memory`.
247pub(super) fn probed(hooks: &dyn Hooks, before: Option<u64>, c: Class) -> Class {
248 if let Err(c) = allocator_check(hooks) {
249 return c;
250 }
251 if let Some(before) = before
252 && is_refusal(&c)
253 && hooks.refusals() == Some(before)
254 {
255 return Class::Run(Reason::plain("host_memory"));
256 }
257 c
258}
259
260/// Whether `c` is a budget's refusal (`budget(input)`, `budget(dependency)`).
261fn is_refusal(c: &Class) -> bool {
262 let (Class::Skip(r) | Class::Input(r) | Class::Run(r)) = c;
263 r.reason.starts_with("budget(")
264}
265
266#[cfg(test)]
267mod allocator_tests {
268 use super::*;
269 use std::cell::Cell;
270 #[derive(Default)]
271 struct Audit {
272 allocator: Cell<u64>,
273 budget: Cell<u64>,
274 }
275 impl Hooks for Audit {
276 fn refusals(&self) -> Option<u64> {
277 Some(self.budget.get())
278 }
279 fn allocator_refusals(&self) -> u64 {
280 self.allocator.get()
281 }
282 }
283 #[test]
284 fn absorbed_allocator_refusal_wins_even_after_a_budget_refusal() {
285 let hooks = Audit::default();
286 let result = probe(&hooks, || {
287 hooks.budget.set(1);
288 hooks.allocator.set(1);
289 Ok(())
290 });
291 assert!(matches!(result, Err(Class::Run(r)) if r.reason == "host_memory"));
292 let mut called = false;
293 let _ = probe(&hooks, || {
294 called = true;
295 Ok(())
296 });
297 assert!(!called, "a poisoned attempt must make no further call");
298 }
299 #[test]
300 fn an_absorbed_budget_refusal_alone_can_still_succeed() {
301 let hooks = Audit::default();
302 assert!(
303 probe(&hooks, || {
304 hooks.budget.set(1);
305 Ok(())
306 })
307 .is_ok()
308 );
309 }
310}