Skip to main content

memstead_base/engine/mutation/create/
batch.rs

1//! `Engine::batch_create`: the same phases as a single create, driven
2//! over every entry before anything is written — an identity pass
3//! that refuses duplicates against the store and within the batch,
4//! skeleton staging so intra-batch references validate as real
5//! targets, the per-entry prepare (resolve, validate, compose), then
6//! stage everything and commit once per mem. A refused or rehearsed
7//! batch rolls the store snapshot back and discards every pending
8//! buffer.
9
10use std::collections::HashMap;
11
12use crate::engine_fallback_type;
13use crate::entity::EntityId;
14use crate::entity::id::validate_and_derive_slug;
15use crate::entity::parser::parse_markdown;
16use crate::entity::store_builder::push_entities_into_store;
17use crate::ops::WarningHint;
18use crate::provenance::{Provenance, ProvenanceKind};
19
20use super::super::{batch_empty, batch_receipt, batch_refusal, make_stub};
21use super::{
22    Actor, ClientId, CreateEntityArgs, CreatePrepareOutcome, Engine, EngineError, PreparedCreate,
23};
24
25impl Engine {
26    /// Atomic batch create — the create-side sibling of
27    /// [`Self::batch_update`], with one upgrade and one addition:
28    ///
29    /// - **Report-all refusal.** Every failing entry is identified with
30    ///   its index and typed `{code, message, details}` envelope (the
31    ///   family's upgraded contract) — bounded at
32    ///   [`Self::BATCH_ERROR_REPORT_CAP`] detailed envelopes, with
33    ///   `errors_suppressed` counting the rest. A refused batch writes
34    ///   NOTHING: no entity, no edge, no head movement.
35    /// - **Intra-batch references resolve as REAL targets.** Every
36    ///   entity in the batch is staged (a skeleton store entry carrying
37    ///   its declared type) before per-entry validation runs, so an
38    ///   edge to a sibling created in the same batch gets full
39    ///   target-type shape validation, no transient stub, and no stub
40    ///   warning — the batch validates as one graph state, cycles
41    ///   included where the schema permits them. Duplicates within the
42    ///   batch are refused in the identity pass.
43    ///
44    /// One workspace load (the caller's), one commit per touched mem
45    /// (subject `memstead: batch-create (N entities)`), per-entry
46    /// provenance notes exactly like `batch_update`.
47    ///
48    /// **Rehearsal** (`dry_run: true`): the FULL validation pass runs —
49    /// identity, skeleton staging (so intra-batch references resolve as
50    /// real targets, cycles included), per-entry prepare, report-all
51    /// refusals — then the batch stops before any write. A legal batch
52    /// returns the would-be receipt (`applied: true`, per-entry
53    /// `"created"` with the prospective ids) with the marker form's
54    /// empty `write_id`; an illegal one returns the same refusal a
55    /// real call would. Nothing is written, committed, or stubbed.
56    pub fn batch_create(
57        &mut self,
58        creates: Vec<(CreateEntityArgs, Option<String>)>,
59        actor: Actor,
60        client: Option<&ClientId>,
61        dry_run: bool,
62    ) -> Result<crate::ops::BatchResult, EngineError> {
63        use std::collections::HashSet;
64
65        if creates.is_empty() {
66            return Ok(batch_empty());
67        }
68
69        // Reload every touched mem once, up front.
70        let mut touched_mems: Vec<String> = creates.iter().map(|(a, _)| a.mem.clone()).collect();
71        touched_mems.sort();
72        touched_mems.dedup();
73        let _write_lock = self.lock_mems_for_write_if(!dry_run, &touched_mems)?;
74        for m in &touched_mems {
75            self.reload_if_stale(Some(m));
76        }
77        // Same acyclic-guard rule as the single-item path: declared
78        // relations on an ACYCLIC rel-type (or one in an
79        // `acyclic_sets` set) walk the whole subgraph, so the walk
80        // must see every mem — deferred ones included (see the
81        // batch_relate comment). Declared signals on any involved
82        // schema need the full load too (see the single-item path).
83        if creates.iter().any(|(a, _)| {
84            a.relations.iter().any(|r| {
85                self.schemas.get(&a.mem).is_some_and(|s| {
86                    s.relationship_acyclic(&r.rel_type)
87                        || s.acyclic_set_containing(&r.rel_type).is_some()
88                }) || self
89                    .schemas
90                    .get(r.target.mem())
91                    .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
92            }) || self
93                .schemas
94                .get(&a.mem)
95                .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
96        }) {
97            self.ensure_mems_loaded(None);
98        }
99
100        let store_snapshot = self.store.clone();
101
102        // --- Identity pass: derive every entry's id, refusing
103        // duplicates against the pre-batch store AND within the batch.
104        // Collect EVERY failure (report-all), never just the first.
105        struct IdentityRow {
106            id: Option<EntityId>,
107            error: Option<EngineError>,
108        }
109        let mut rows: Vec<IdentityRow> = Vec::with_capacity(creates.len());
110        // id → title of the batch entry that claimed it, so a
111        // within-batch duplicate can name the occupying title.
112        let mut batch_ids: HashMap<EntityId, String> = HashMap::new();
113        for (args, _) in &creates {
114            let identity = (|| -> Result<EntityId, EngineError> {
115                let title = args.title.trim();
116                // Divergence warnings ride the per-entry prepare pass
117                // below, which re-derives; this pass only needs the id.
118                let slug = validate_and_derive_slug(title)?.slug;
119                let id = EntityId::new(&args.mem, &slug);
120                crate::entity::id::enforce_id_length(id.as_ref())?;
121                if let Some(existing) = self.store.get(&id)
122                    && !existing.stub
123                {
124                    return Err(EngineError::AlreadyExists {
125                        id: id.to_string(),
126                        existing_title: existing.title.clone(),
127                        existing_is_stub: false,
128                    });
129                }
130                if let Some(prior_title) = batch_ids.get(&id) {
131                    // Duplicate WITHIN the batch — same typed code as
132                    // the store collision; the index in the report
133                    // localises it.
134                    return Err(EngineError::AlreadyExists {
135                        id: id.to_string(),
136                        existing_title: prior_title.clone(),
137                        existing_is_stub: false,
138                    });
139                }
140                Ok(id)
141            })();
142            match identity {
143                Ok(id) => {
144                    batch_ids.insert(id.clone(), args.title.trim().to_string());
145                    rows.push(IdentityRow {
146                        id: Some(id),
147                        error: None,
148                    });
149                }
150                Err(e) => rows.push(IdentityRow {
151                    id: None,
152                    error: Some(e),
153                }),
154            }
155        }
156
157        // --- Skeleton staging: make every batch id a REAL, typed store
158        // entry so sibling references validate against present targets.
159        // A pre-existing stub at a batch id is replaced (its incoming
160        // edges survive the upsert — the same adoption the single-item
161        // create performs).
162        for ((args, _), row) in creates.iter().zip(rows.iter()) {
163            if let Some(id) = &row.id {
164                let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
165                skeleton.stub = false;
166                skeleton.stub_kind = None;
167                skeleton.entity_type = args.entity_type.clone();
168                skeleton.title = args.title.trim().to_string();
169                self.store.upsert(id.clone(), skeleton);
170            }
171        }
172
173        // --- Full prepare pass, report-all. Skeletons make intra-batch
174        // targets real; each entry's own skeleton is exempted from the
175        // duplicate check via `batch_skeleton_ids`.
176        let mut prepared: Vec<PreparedCreate> = Vec::new();
177        let mut notes: Vec<Option<String>> = Vec::new();
178        let mut errors: Vec<(usize, EngineError)> = Vec::new();
179        let mut ids_in_order: Vec<EntityId> = Vec::new();
180        let skeleton_ids: HashSet<EntityId> = batch_ids.keys().cloned().collect();
181        for (i, ((args, note), row)) in creates.into_iter().zip(rows).enumerate() {
182            let fallback_id = row
183                .id
184                .clone()
185                .unwrap_or_else(|| EntityId::new(&args.mem, "invalid-entry"));
186            ids_in_order.push(fallback_id);
187            if let Some(e) = row.error {
188                errors.push((i, e));
189                continue;
190            }
191            // Rehearsal is batch-level (the `dry_run` parameter) —
192            // per-entry dry-run stays forced off so the prepare pass
193            // below never short-circuits into a per-entry preview.
194            let mut args = args;
195            args.dry_run = false;
196            match self.prepare_create(args, Some(&skeleton_ids), Vec::new()) {
197                Ok(CreatePrepareOutcome::Prepared(p)) => {
198                    // Stage this item's declared edges onto its skeleton
199                    // so later items validate against the batch's own
200                    // graph state — an intra-batch cycle on an acyclic
201                    // rel-type refuses exactly like a stored one
202                    // (`validate_edge_acyclicity` walks the store). The
203                    // snapshot rollback discards these on refusal; the
204                    // apply pass replaces them with the parsed truth.
205                    for r in &p.relations_declared {
206                        self.store.add_edge(
207                            p.id.clone(),
208                            crate::store::Edge {
209                                rel_type: r.rel_type.clone(),
210                                target: r.target.clone(),
211                                source: crate::store::EdgeSource::Explicit,
212                            },
213                        );
214                    }
215                    ids_in_order[i] = p.id.clone();
216                    prepared.push(p);
217                    notes.push(note);
218                }
219                Ok(CreatePrepareOutcome::Done(_)) => unreachable!("dry_run forced off"),
220                Err(e) => errors.push((i, e)),
221            }
222        }
223
224        if !errors.is_empty() {
225            // Refuse the whole batch; nothing was committed and the
226            // store snapshot rolls back the skeletons.
227            self.store = store_snapshot;
228            self.discard_all_pending();
229            return Ok(batch_refusal(ids_in_order, errors));
230        }
231
232        // Rehearsal: every entry validated against the batch's own
233        // graph state (skeletons made intra-batch targets real) and
234        // nothing failed — stop before any write. Roll back the
235        // skeleton staging and return the would-be receipt with the
236        // marker form's empty `write_id`.
237        if dry_run {
238            self.store = store_snapshot;
239            self.discard_all_pending();
240            return Ok(batch_receipt(
241                created_actions(prepared),
242                Vec::new(),
243                Vec::new(),
244                String::new(),
245            ));
246        }
247
248        // --- Stage every write + anchors, then commit once per mem.
249        for p in &prepared {
250            if let Err(e) = self.stage_prepared_create(p) {
251                self.store = store_snapshot;
252                self.discard_all_pending();
253                return Err(e);
254            }
255        }
256        let mut distinct_mounts: Vec<usize> = Vec::new();
257        for p in &prepared {
258            if !distinct_mounts.contains(&p.mount_idx) {
259                distinct_mounts.push(p.mount_idx);
260            }
261        }
262        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
263        for &m in &distinct_mounts {
264            let entity_ids: Vec<String> = prepared
265                .iter()
266                .filter(|p| p.mount_idx == m)
267                .map(|p| p.id.to_string())
268                .collect();
269            let count = entity_ids.len();
270            let subject = format!("memstead: batch-create ({count} entities)");
271            // Per-entry notes ride the ONE batch commit's note record as
272            // `<id>: <note>` lines (decision 3, an earlier plan):
273            // `append_provenance` below is a documented no-op on the
274            // git-branch backend, so without this the notes survived
275            // nowhere exactly where most writes happen. A batch with no
276            // notes carries no note record at all.
277            let note_lines: Vec<String> = prepared
278                .iter()
279                .zip(notes.iter())
280                .filter(|(p, _)| p.mount_idx == m)
281                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.id)))
282                .collect();
283            let mut ctx = self.commit_context(
284                Some("batch_create"),
285                actor,
286                client.cloned(),
287                if note_lines.is_empty() {
288                    None
289                } else {
290                    Some(note_lines.join("\n"))
291                },
292            );
293            ctx.entity_ids = Some(entity_ids);
294            match self.mounts[m].backend.commit(&subject, &ctx) {
295                Ok(sha) => mount_commits.push((m, sha)),
296                Err(e) => {
297                    self.store = store_snapshot;
298                    self.discard_all_pending();
299                    return Err(e.into());
300                }
301            }
302        }
303
304        // Provenance + store application (parse the generated bytes so
305        // the store mirrors disk, replacing the skeletons).
306        let fallback = engine_fallback_type();
307        let mut batch_warnings: Vec<WarningHint> = Vec::new();
308        for (p, note) in prepared.iter().zip(notes.iter()) {
309            let write_id = mount_commits
310                .iter()
311                .find(|(m, _)| *m == p.mount_idx)
312                .map(|(_, s)| s.clone())
313                .unwrap_or_default();
314            self.mounts[p.mount_idx].backend.append_provenance(
315                &Provenance::new(
316                    std::time::SystemTime::now(),
317                    ProvenanceKind::Create,
318                    Some(p.id.to_string()),
319                    actor,
320                    client.cloned(),
321                    note.clone(),
322                )
323                .with_role(self.current_role)
324                .with_identity(self.current_identity.clone()),
325            )?;
326            self.record_self_write(p.mount_idx, &write_id);
327            batch_warnings.extend(self.stamp_mutation_versions(p.mount_idx));
328            let parse_result =
329                parse_markdown(&p.markdown, &p.file_path, p.type_def.as_ref(), &p.mem)
330                    .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
331            push_entities_into_store(&mut self.store, vec![parse_result], fallback.as_ref(), None);
332        }
333        crate::entity::store_builder::remap_alias_target_edge_sources(
334            &mut self.store,
335            &self.schemas,
336        );
337        // Forward-reference stubs for OUT-OF-BATCH targets only —
338        // in-batch targets are real entities now.
339        let mut out_of_batch_stubs: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
340        for p in &prepared {
341            for target in &p.relation_targets {
342                if !self.store.contains(target) {
343                    let kind = super::super::deferred_verified_stub_kind(self, target)?;
344                    out_of_batch_stubs.push((target.clone(), kind));
345                }
346            }
347        }
348        for (target, kind) in out_of_batch_stubs {
349            self.store.upsert(target.clone(), make_stub(&target, kind));
350        }
351        self.invalidate_communities();
352        self.invalidate_search_indexes();
353
354        let write_id = mount_commits
355            .last()
356            .map(|(_, s)| s.clone())
357            .unwrap_or_default();
358        Ok(batch_receipt(
359            created_actions(prepared),
360            batch_warnings,
361            Vec::new(),
362            write_id,
363        ))
364    }
365}
366
367/// The create verb's one action word: every prepared item was `created`.
368fn created_actions(prepared: Vec<PreparedCreate>) -> Vec<(EntityId, String)> {
369    prepared
370        .into_iter()
371        .map(|p| (p.id, "created".to_string()))
372        .collect()
373}