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