Skip to main content

ifc_model/
authored_dump.rs

1//! Coverage audit: record which entity types are actually constructed.
2//!
3//! Off unless the `authored-dump` feature is on *and* `AUTHORED_DUMP`
4//! names a directory, so an `--all-features` build pays one relaxed
5//! atomic load per entity and nothing else.
6//!
7//! # Why this exists
8//!
9//! Static scanning of writer call sites cannot answer "is this entity
10//! authorable". A type name reaches [`crate::Entity::new`] through a
11//! const, a catalogue row, or a match arm returning it into a tuple, so
12//! a scan both misses real writers and counts names that are only
13//! mentioned. Recording what is built during a test run answers it
14//! directly.
15//!
16//! # Origins
17//!
18//! Three call sites, because "an entity of this type exists" and "a
19//! writer can produce one" are different claims:
20//!
21//! - `create`: [`crate::Transaction::create`], the authoring path. The
22//!   only origin that proves a writer exists.
23//! - `insert`: [`crate::Model::insert`], where every entity actually
24//!   lands -- committed transactions, [`crate::Model::push`], and codec
25//!   loads all funnel through it. The chokepoint, so nothing enters a
26//!   model unseen.
27//! - `retype`: `Model::retype`, which changes a type name in place and
28//!   can therefore produce a type no writer ever constructed.
29//!
30//! An earlier version hooked `create` and `push` only. That missed
31//! `Transaction::stage(Edit::Create { .. })`, which builds an entity
32//! without going through `create`, and missed `retype` entirely.
33//!
34//! # Usage
35//!
36//! ```text
37//! AUTHORED_DUMP=/tmp/dump \
38//!   cargo test --workspace --all-features --features ifc-model/authored-dump
39//! python3 scripts/authored-coverage.py /tmp/dump
40//! ```
41
42use std::collections::BTreeSet;
43use std::sync::atomic::{AtomicU8, Ordering};
44use std::sync::{Mutex, OnceLock};
45
46/// Where records accumulate until the process exits.
47fn seen() -> &'static Mutex<BTreeSet<(&'static str, String)>> {
48    static SEEN: OnceLock<Mutex<BTreeSet<(&'static str, String)>>> = OnceLock::new();
49    SEEN.get_or_init(|| Mutex::new(BTreeSet::new()))
50}
51
52/// Tri-state cache of the `AUTHORED_DUMP` lookup: 0 unknown, 1 off, 2 on.
53///
54/// The variable is read once. Without this every constructed entity pays
55/// an environment lookup and a `String` allocation, which is a real cost
56/// on a full `--all-features` run where the feature is on but the
57/// variable is unset.
58static STATE: AtomicU8 = AtomicU8::new(0);
59
60/// The directory named by `AUTHORED_DUMP`, resolved once.
61fn directory() -> Option<&'static str> {
62    static DIR: OnceLock<Option<String>> = OnceLock::new();
63    DIR.get_or_init(|| std::env::var("AUTHORED_DUMP").ok())
64        .as_deref()
65}
66
67/// Whether recording is on, reading the environment at most once.
68///
69/// Public so a test can assert the hook stays inert when the feature
70/// is compiled in but `AUTHORED_DUMP` is unset -- the configuration
71/// every `--all-features` build runs in. Asserting on an absent output
72/// directory would pass even if this returned `true`, since the writer
73/// has no directory to write to either way.
74pub fn recording() -> bool {
75    match STATE.load(Ordering::Relaxed) {
76        1 => false,
77        2 => true,
78        _ => {
79            let on = directory().is_some();
80            STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed);
81            on
82        }
83    }
84}
85
86/// Record one type name against the path that produced it.
87///
88/// `origin` is `"create"`, `"insert"` or `"retype"`; see the module
89/// docs for what each proves. Names are upper-cased because the crates
90/// disagree on the casing they store and the audit compares against the
91/// schema.
92pub fn record(type_name: &str, origin: &'static str) {
93    if !recording() {
94        return;
95    }
96    let Ok(mut set) = seen().lock() else {
97        return;
98    };
99    if !set.insert((origin, type_name.to_ascii_uppercase())) {
100        return;
101    }
102    // Flushed on growth, not on every call: a test binary has no exit
103    // hook to write from, and the set grows at most once per distinct
104    // (origin, type) pair -- hundreds of writes across a run, not one
105    // per constructed entity.
106    flush(&set);
107}
108
109/// Write the accumulated set to a per-process file.
110///
111/// Per-process because cargo runs test binaries in parallel and a single
112/// shared path would have them overwrite each other. The reader unions
113/// every file in the directory.
114///
115/// Failures are ignored: this is an audit aid, and a full disk or a
116/// missing directory must not fail the run it is observing.
117fn flush(set: &BTreeSet<(&'static str, String)>) {
118    let Some(dir) = directory() else {
119        return;
120    };
121    let body = set
122        .iter()
123        .map(|(origin, name)| format!("{origin}\t{name}"))
124        .collect::<Vec<_>>()
125        .join("\n");
126    let path = std::path::Path::new(dir).join(format!("{}.txt", std::process::id()));
127    let _ = std::fs::create_dir_all(dir);
128    let _ = std::fs::write(path, body);
129}