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        // What the roster reconcile and the reloads report (a mem
74        // attached since, a sibling's commit, a commit this load
75        // completed) rides the receipt like on a single verb.
76        let (_write_lock, drift_warnings) = {
77            let items = &creates;
78            // Each item's own mem, and the mems it refers to.
79            let mut locked = touched_mems.clone();
80            for (a, _) in items {
81                locked.extend(crate::engine::write_lock::referred_mems(
82                    &a.mem,
83                    a.relations.iter().map(|r| &r.target),
84                    a.sections
85                        .values()
86                        .map(String::as_str)
87                        .chain(a.relations.iter().filter_map(|r| r.description.as_deref())),
88                ));
89            }
90            self.lock_for_verb(!dry_run, &locked, &touched_mems, |engine| {
91                items.iter().any(|(a, _)| {
92                    engine.write_needs_full_load(
93                        &a.mem,
94                        a.relations
95                            .iter()
96                            .map(|r| crate::engine::mutation::EdgeWrite {
97                                rel_type: &r.rel_type,
98                                target_mem: r.target.mem(),
99                                remove: false,
100                            }),
101                        a.sections.values().map(String::as_str),
102                    )
103                })
104            })?
105        };
106        // Same acyclic-guard rule as the single-item path: declared
107        // relations on an ACYCLIC rel-type (or one in an
108        // `acyclic_sets` set) walk the whole subgraph, so the walk
109        // must see every mem — deferred ones included (see the
110        // batch_relate comment). Declared signals on any involved
111        // schema need the full load too (see the single-item path).
112        if creates.iter().any(|(a, _)| {
113            self.write_needs_full_load(
114                &a.mem,
115                a.relations
116                    .iter()
117                    .map(|r| crate::engine::mutation::EdgeWrite {
118                        rel_type: &r.rel_type,
119                        target_mem: r.target.mem(),
120                        remove: false,
121                    }),
122                a.sections.values().map(String::as_str),
123            )
124        }) {
125            self.ensure_mems_loaded(None);
126        }
127
128        let store_snapshot = self.store.clone();
129
130        // --- Identity pass: derive every entry's id, refusing
131        // duplicates against the pre-batch store AND within the batch.
132        // Collect EVERY failure (report-all), never just the first.
133        struct IdentityRow {
134            id: Option<EntityId>,
135            error: Option<EngineError>,
136        }
137        let mut rows: Vec<IdentityRow> = Vec::with_capacity(creates.len());
138        // id → title of the batch entry that claimed it, so a
139        // within-batch duplicate can name the occupying title.
140        let mut batch_ids: HashMap<EntityId, String> = HashMap::new();
141        for (args, _) in &creates {
142            let identity = (|| -> Result<EntityId, EngineError> {
143                let title = args.title.trim();
144                // Divergence warnings ride the per-entry prepare pass
145                // below, which re-derives; this pass only needs the id.
146                let slug = validate_and_derive_slug(title)?.slug;
147                let id = EntityId::new(&args.mem, &slug);
148                crate::entity::id::enforce_id_length(id.as_ref())?;
149                if let Some(existing) = self.store.get(&id)
150                    && !existing.stub
151                {
152                    return Err(EngineError::AlreadyExists {
153                        id: id.to_string(),
154                        existing_title: existing.title.clone(),
155                        existing_is_stub: false,
156                    });
157                }
158                if let Some(prior_title) = batch_ids.get(&id) {
159                    // Duplicate WITHIN the batch — same typed code as
160                    // the store collision; the index in the report
161                    // localises it.
162                    return Err(EngineError::AlreadyExists {
163                        id: id.to_string(),
164                        existing_title: prior_title.clone(),
165                        existing_is_stub: false,
166                    });
167                }
168                Ok(id)
169            })();
170            match identity {
171                Ok(id) => {
172                    batch_ids.insert(id.clone(), args.title.trim().to_string());
173                    rows.push(IdentityRow {
174                        id: Some(id),
175                        error: None,
176                    });
177                }
178                Err(e) => rows.push(IdentityRow {
179                    id: None,
180                    error: Some(e),
181                }),
182            }
183        }
184
185        // --- Skeleton staging: make every batch id a REAL, typed store
186        // entry so sibling references validate against present targets.
187        // A pre-existing stub at a batch id is replaced (its incoming
188        // edges survive the upsert — the same adoption the single-item
189        // create performs).
190        for ((args, _), row) in creates.iter().zip(rows.iter()) {
191            if let Some(id) = &row.id {
192                let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
193                skeleton.stub = false;
194                skeleton.stub_kind = None;
195                skeleton.entity_type = args.entity_type.clone();
196                skeleton.title = args.title.trim().to_string();
197                self.store.upsert(id.clone(), skeleton);
198            }
199        }
200
201        // --- Full prepare pass, report-all. Skeletons make intra-batch
202        // targets real; each entry's own skeleton is exempted from the
203        // duplicate check via `batch_skeleton_ids`.
204        let mut prepared: Vec<PreparedCreate> = Vec::new();
205        let mut notes: Vec<Option<String>> = Vec::new();
206        let mut errors: Vec<(usize, EngineError)> = Vec::new();
207        let mut ids_in_order: Vec<EntityId> = Vec::new();
208        let skeleton_ids: HashSet<EntityId> = batch_ids.keys().cloned().collect();
209        for (i, ((args, note), row)) in creates.into_iter().zip(rows).enumerate() {
210            let fallback_id = row
211                .id
212                .clone()
213                .unwrap_or_else(|| EntityId::new(&args.mem, "invalid-entry"));
214            ids_in_order.push(fallback_id);
215            if let Some(e) = row.error {
216                errors.push((i, e));
217                continue;
218            }
219            // Rehearsal is batch-level (the `dry_run` parameter) —
220            // per-entry dry-run stays forced off so the prepare pass
221            // below never short-circuits into a per-entry preview.
222            let mut args = args;
223            args.dry_run = false;
224            match self.prepare_create(args, Some(&skeleton_ids), Vec::new()) {
225                Ok(CreatePrepareOutcome::Prepared(p)) => {
226                    // Stage this item's declared edges onto its skeleton
227                    // so later items validate against the batch's own
228                    // graph state — an intra-batch cycle on an acyclic
229                    // rel-type refuses exactly like a stored one
230                    // (`validate_edge_acyclicity` walks the store). The
231                    // snapshot rollback discards these on refusal; the
232                    // apply pass replaces them with the parsed truth.
233                    for r in &p.relations_declared {
234                        self.store.add_edge(
235                            p.id.clone(),
236                            crate::store::Edge {
237                                rel_type: r.rel_type.clone(),
238                                target: r.target.clone(),
239                                source: crate::store::EdgeSource::Explicit,
240                            },
241                        );
242                    }
243                    ids_in_order[i] = p.id.clone();
244                    prepared.push(p);
245                    notes.push(note);
246                }
247                Ok(CreatePrepareOutcome::Done(_)) => unreachable!("dry_run forced off"),
248                Err(e) => errors.push((i, e)),
249            }
250        }
251
252        // The checks form over the store as the whole batch leaves it: a
253        // new criterion created beside the plan it closes counts, as it
254        // does when the two creates run one after the other.
255        if errors.is_empty() {
256            let mut post = store_snapshot.clone();
257            let mut writes = Vec::new();
258            for p in &prepared {
259                match crate::entity::parser::parse_markdown(
260                    &p.markdown,
261                    &p.file_path,
262                    p.type_def.as_ref(),
263                    &p.mem,
264                ) {
265                    Ok(parsed) => {
266                        post.upsert(parsed.entity.id.clone(), parsed.entity.clone());
267                        writes.push((parsed.entity, p.type_def.clone()));
268                    }
269                    Err(e) => {
270                        self.store = store_snapshot;
271                        self.discard_all_pending();
272                        return Err(EngineError::ParseAfterWrite(e.to_string()));
273                    }
274                }
275            }
276            for (entity, blocked) in self.checks_form_after(&post, &store_snapshot, &writes) {
277                let i = ids_in_order
278                    .iter()
279                    .position(|id| *id == entity.id)
280                    .unwrap_or(0);
281                errors.push((
282                    i,
283                    EngineError::ConstraintUnsatisfied {
284                        entity_type: entity.entity_type.clone(),
285                        entity_id: entity.id.to_string(),
286                        violations: blocked,
287                    },
288                ));
289            }
290        }
291
292        if !errors.is_empty() {
293            // Refuse the whole batch; nothing was committed and the
294            // store snapshot rolls back the skeletons.
295            self.store = store_snapshot;
296            self.discard_all_pending();
297            return Ok(batch_refusal(ids_in_order, errors));
298        }
299
300        // Rehearsal: every entry validated against the batch's own
301        // graph state (skeletons made intra-batch targets real) and
302        // nothing failed — stop before any write. Roll back the
303        // skeleton staging and return the would-be receipt with the
304        // marker form's empty `write_id`.
305        if dry_run {
306            self.store = store_snapshot;
307            self.discard_all_pending();
308            return Ok(batch_receipt(
309                created_actions(prepared),
310                Vec::new(),
311                Vec::new(),
312                String::new(),
313            ));
314        }
315
316        // --- Stage every write + anchors, then commit once per mem.
317        for p in &prepared {
318            if let Err(e) = self.stage_prepared_create(p) {
319                self.store = store_snapshot;
320                self.discard_all_pending();
321                return Err(e);
322            }
323        }
324        let mut distinct_mounts: Vec<usize> = Vec::new();
325        for p in &prepared {
326            if !distinct_mounts.contains(&p.mount_idx) {
327                distinct_mounts.push(p.mount_idx);
328            }
329        }
330        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
331        let mut batch_warnings: Vec<WarningHint> = drift_warnings;
332        for &m in &distinct_mounts {
333            let entity_ids: Vec<String> = prepared
334                .iter()
335                .filter(|p| p.mount_idx == m)
336                .map(|p| p.id.to_string())
337                .collect();
338            let count = entity_ids.len();
339            let subject = format!("memstead: batch-create ({count} entities)");
340            // Per-entry notes ride the ONE batch commit's note record as
341            // `<id>: <note>` lines:
342            // `append_provenance` below is a documented no-op on the
343            // git-branch backend, so without this the notes survived
344            // nowhere exactly where most writes happen. A batch with no
345            // notes carries no note record at all.
346            let note_lines: Vec<String> = prepared
347                .iter()
348                .zip(notes.iter())
349                .filter(|(p, _)| p.mount_idx == m)
350                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.id)))
351                .collect();
352            let mut ctx = self.commit_context(
353                Some("batch_create"),
354                actor,
355                client.cloned(),
356                if note_lines.is_empty() {
357                    None
358                } else {
359                    Some(note_lines.join("\n"))
360                },
361            );
362            ctx.entity_ids = Some(entity_ids);
363            // One provenance record per item, landing with the mem's
364            // commit.
365            let records: Vec<Provenance> = prepared
366                .iter()
367                .zip(notes.iter())
368                .filter(|(p, _)| p.mount_idx == m)
369                .map(|(p, note)| {
370                    self.provenance_record(
371                        ProvenanceKind::Create,
372                        &p.id,
373                        actor,
374                        client,
375                        note.as_deref(),
376                    )
377                })
378                .collect();
379            match self.commit_or_complete(m, self.commit_staged(m, &subject, &ctx, &records)) {
380                Ok(landed) => {
381                    batch_warnings.extend(landed.warnings);
382                    mount_commits.push((m, landed.write_id));
383                }
384                Err(e) => {
385                    // Mems already committed in this loop stay
386                    // committed, so the view of each is reloaded from
387                    // storage after the store rollback.
388                    self.store = store_snapshot;
389                    self.discard_all_pending();
390                    let items: Vec<(usize, EntityId)> = prepared
391                        .iter()
392                        .map(|p| (p.mount_idx, p.id.clone()))
393                        .collect();
394                    return Err(self.batch_commit_failed(
395                        &distinct_mounts,
396                        &items,
397                        mount_commits,
398                        m,
399                        e,
400                    ));
401                }
402            }
403        }
404
405        // Store application (parse the generated bytes so the store
406        // mirrors disk, replacing the skeletons).
407        for (m, write_id) in &mount_commits {
408            self.record_self_write(*m, write_id);
409            batch_warnings.extend(self.stamp_mutation_versions(*m));
410        }
411        let committed_mounts: Vec<usize> = mount_commits.iter().map(|(m, _)| *m).collect();
412        self.after_commits(
413            &committed_mounts,
414            "store_update",
415            &mut batch_warnings,
416            |engine| {
417                let fallback = engine_fallback_type();
418                for p in &prepared {
419                    let parse_result =
420                        parse_markdown(&p.markdown, &p.file_path, p.type_def.as_ref(), &p.mem)
421                            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
422                    push_entities_into_store(
423                        &mut engine.store,
424                        vec![parse_result],
425                        fallback.as_ref(),
426                        None,
427                    );
428                }
429                crate::entity::store_builder::remap_alias_target_edge_sources(
430                    &mut engine.store,
431                    &engine.schemas,
432                );
433                // Forward-reference stubs for OUT-OF-BATCH targets only —
434                // in-batch targets are real entities now.
435                let mut out_of_batch_stubs: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
436                for p in &prepared {
437                    for target in &p.relation_targets {
438                        if !engine.store.contains(target) {
439                            let kind = super::super::deferred_verified_stub_kind(engine, target)?;
440                            out_of_batch_stubs.push((target.clone(), kind));
441                        }
442                    }
443                }
444                for (target, kind) in out_of_batch_stubs {
445                    engine
446                        .store
447                        .upsert(target.clone(), make_stub(&target, kind));
448                }
449                Ok(())
450            },
451        );
452        self.invalidate_communities();
453        self.invalidate_search_indexes();
454
455        let write_id = mount_commits
456            .last()
457            .map(|(_, s)| s.clone())
458            .unwrap_or_default();
459        Ok(batch_receipt(
460            created_actions(prepared),
461            batch_warnings,
462            Vec::new(),
463            write_id,
464        ))
465    }
466}
467
468/// The create verb's one action word: every prepared item was `created`.
469fn created_actions(prepared: Vec<PreparedCreate>) -> Vec<(EntityId, String)> {
470    prepared
471        .into_iter()
472        .map(|p| (p.id, "created".to_string()))
473        .collect()
474}