Skip to main content

khive_runtime/operations/
entity_bulk.rs

1//! Prepared entity bulk construction.
2
3use super::entity_keys::{validate_entity_key, PendingEntityId};
4use super::*;
5use crate::secret_gate_finalizer::entity_admission::{
6    prepare_entity_admission_at, EntityAdmission, EntityEntryPoint,
7};
8use crate::EntityCandidateMutation;
9use khive_db::stores::entity::entity_key_claim_statement;
10
11impl KhiveRuntime {
12    /// Create a batch of entities atomically.
13    ///
14    /// All specs are validated before any write. If ANY spec fails validation
15    /// (unknown kind, empty name, secret-gate violation), the method returns
16    /// that error and no entities are written.
17    ///
18    /// Entity rows and their FTS documents are written in one SQLite transaction.
19    /// Any statement failure rolls back the entire batch across both surfaces.
20    /// Embedding is intentionally skipped: bulk structural ingest is the expected
21    /// use-case, and dense vectors are backfilled later via a `reindex` call.
22    pub async fn create_many(
23        &self,
24        token: &NamespaceToken,
25        specs: Vec<EntityCreateSpec>,
26    ) -> RuntimeResult<Vec<Entity>> {
27        if specs.is_empty() {
28            return Ok(vec![]);
29        }
30        let ns = token.namespace().as_str();
31
32        // Phase 1: validate ALL specs before any write.
33        // Includes entity-type validation via the pack-installed validator when available.
34        // Any validation failure here guarantees zero rows are written.
35        let mut admissions = Vec::with_capacity(specs.len());
36        for (index, spec) in specs.iter().enumerate() {
37            let (mut entity, aliases) = self.validate_bulk_entity(ns, spec)?;
38            let alias_statements = project_bulk_aliases(&mut entity, &aliases);
39            admissions.push((
40                prepare_entity_admission_at(
41                    token,
42                    EntityEntryPoint::Bulk,
43                    entity,
44                    &format!("entity[{index}]"),
45                )?,
46                alias_statements,
47            ));
48        }
49
50        #[cfg(any(test, feature = "fault-injection"))]
51        let fts_many_inject = consume_fault(&FTS_FAIL_MANY_NS, ns);
52        #[cfg(not(any(test, feature = "fault-injection")))]
53        let fts_many_inject = false;
54
55        #[cfg(any(test, feature = "fault-injection"))]
56        let fts_many_inject_partial = consume_fault(&FTS_FAIL_MANY_PARTIAL_NS, ns);
57        #[cfg(not(any(test, feature = "fault-injection")))]
58        let fts_many_inject_partial = false;
59
60        let injected_failure_index = if fts_many_inject {
61            Some(0)
62        } else if fts_many_inject_partial {
63            Some(usize::from(admissions.len() > 1))
64        } else {
65            None
66        };
67
68        let _ = self.entities(token)?;
69        let _ = self.text(token)?;
70
71        let mut entities = Vec::with_capacity(admissions.len());
72        let mut plans = Vec::with_capacity(admissions.len());
73        let mut has_finalizer = false;
74        for (index, (admission, alias_statements)) in admissions.into_iter().enumerate() {
75            has_finalizer |= matches!(&admission, EntityAdmission::Exempt(_));
76            let (entity, plan) = self
77                .finish_bulk_entity_plan(
78                    token,
79                    admission,
80                    injected_failure_index == Some(index),
81                    None,
82                    alias_statements,
83                )
84                .await?;
85            entities.push(entity);
86            plans.push(plan);
87        }
88
89        match run_atomic_unit(self.sql().as_ref(), plans).await {
90            Ok(AtomicRunOutcome::Committed { .. }) => Ok(entities),
91            Ok(AtomicRunOutcome::RolledBack {
92                failed_op_index,
93                failure,
94            }) => Err(RuntimeError::Internal(format!(
95                "create_many: atomic batch rolled back at entity index {failed_op_index}: \
96                 {failure:?}"
97            ))),
98            Err(e) if has_finalizer => Err(RuntimeError::Storage(e.0)),
99            Err(e) => Err(RuntimeError::Internal(format!(
100                "create_many: atomic batch failed: {}",
101                e.0
102            ))),
103        }
104    }
105
106    /// One bulk entity spec's pre-write checks and its row, shared by
107    /// `create_many` and [`Self::prepare_bulk_entity_plan`] so the two bulk
108    /// entity paths cannot drift apart: kind, entity_type, a nonempty name,
109    /// the reserved secret-gate property, the caller aliases and the secret
110    /// gate itself. The aliases are returned unapplied, so a caller that
111    /// names the row's id first writes them under that id.
112    fn validate_bulk_entity(
113        &self,
114        ns: &str,
115        spec: &EntityCreateSpec,
116    ) -> RuntimeResult<(Entity, EntityAliasChange)> {
117        self.validate_entity_kind(&spec.kind)?;
118        // Validate entity_type at the runtime layer via pack-installed callback.
119        // When no validator is installed (bare runtime, unit tests without packs),
120        // the type passes through unchanged, the same skip-when-absent pattern as
121        // validate_entity_kind. The handler layer remains the primary enforcement point.
122        let validated_type =
123            self.validate_entity_type_for_kind(&spec.kind, spec.entity_type.as_deref())?;
124        if spec.name.trim().is_empty() {
125            return Err(RuntimeError::InvalidInput("name must not be empty".into()));
126        }
127        crate::secret_gate::reject_reserved_secret_gate_property(spec.properties.as_ref())?;
128        let aliases = EntityAliasChange::replace(&spec.aliases)?;
129
130        let mut entity =
131            Entity::new(ns, &spec.kind, &spec.name).with_entity_type(validated_type.as_deref());
132        if let Some(d) = &spec.description {
133            entity = entity.with_description(d);
134        }
135        if let Some(p) = spec.properties.clone() {
136            entity = entity.with_properties(p);
137        }
138        if !spec.tags.is_empty() {
139            entity = entity.with_tags(spec.tags.clone());
140        }
141        Ok((entity, aliases))
142    }
143
144    /// Validate and prepare one entity item for a bulk `create(items=[...])`
145    /// write: the same admission and row/FTS plan as [`Self::create_many`],
146    /// with no scheduled reindex, so the vector is deferred to a later
147    /// `reindex` exactly as for `create_many`. The bulk create handler uses
148    /// this for every entity item so entity and note plans can join one
149    /// `run_atomic_unit` call.
150    pub async fn prepare_bulk_entity_plan(
151        &self,
152        token: &NamespaceToken,
153        spec: EntityCreateSpec,
154    ) -> RuntimeResult<(Entity, AtomicOpPlan)> {
155        let (mut entity, aliases) = self.validate_bulk_entity(token.namespace().as_str(), &spec)?;
156        let alias_statements = project_bulk_aliases(&mut entity, &aliases);
157        let admission =
158            prepare_entity_admission_at(token, EntityEntryPoint::Bulk, entity, "entity")?;
159        let _ = self.entities(token)?;
160        let _ = self.text(token)?;
161        self.finish_bulk_entity_plan(token, admission, false, None, alias_statements)
162            .await
163    }
164
165    /// [`Self::prepare_bulk_entity_plan`] for a bulk item under caller key
166    /// `key` (ADR-221 section 1). The row takes the id `id` names, and the
167    /// plan claims the key for it first under an exactly-one guard, so a key
168    /// another writer took after the caller read it rolls the whole unit
169    /// back. The key is validated and secret-gated before anything else.
170    pub async fn prepare_keyed_bulk_entity_plan(
171        &self,
172        token: &NamespaceToken,
173        spec: EntityCreateSpec,
174        key: &str,
175        id: PendingEntityId,
176    ) -> RuntimeResult<(Entity, AtomicOpPlan)> {
177        validate_entity_key(key)?;
178        let ns = token.namespace().as_str();
179        let (mut entity, aliases) = self.validate_bulk_entity(ns, &spec)?;
180        entity.id = id.0;
181        let alias_statements = project_bulk_aliases(&mut entity, &aliases);
182        let claim = PlanStatement {
183            statement: entity_key_claim_statement(
184                ns,
185                &entity.kind,
186                key,
187                entity.id,
188                entity.created_at,
189            ),
190            guard: Some(AffectedRowGuard::exactly(1)),
191        };
192        let admission =
193            prepare_entity_admission_at(token, EntityEntryPoint::Bulk, entity, "entity")?;
194        let _ = self.entities(token)?;
195        let _ = self.text(token)?;
196        self.finish_bulk_entity_plan(token, admission, false, Some(claim), alias_statements)
197            .await
198    }
199
200    /// [`Self::prepare_keyed_bulk_entity_plan`] again for the row `planned`
201    /// holds, with `spec` as its payload: a later item of the same request
202    /// replaced the payload under `on_key: "update"` (ADR-221 section 1).
203    /// The row keeps its id and the new plan replaces the old one, so one id
204    /// still names one new row. On a refusal `planned` is left as it was.
205    pub async fn replan_keyed_bulk_entity(
206        &self,
207        token: &NamespaceToken,
208        spec: EntityCreateSpec,
209        key: &str,
210        planned: &mut (Entity, AtomicOpPlan),
211    ) -> RuntimeResult<()> {
212        let id = PendingEntityId(planned.0.id);
213        *planned = self
214            .prepare_keyed_bulk_entity_plan(token, spec, key, id)
215            .await?;
216        Ok(())
217    }
218
219    async fn finish_bulk_entity_plan(
220        &self,
221        token: &NamespaceToken,
222        admission: EntityAdmission,
223        inject_fts_failure: bool,
224        key_claim: Option<PlanStatement>,
225        alias_statements: Vec<SqlStatement>,
226    ) -> RuntimeResult<(Entity, AtomicOpPlan)> {
227        match admission {
228            EntityAdmission::Legacy(entity) => {
229                let mut plan = bulk_entity_plan(&entity)?;
230                if inject_fts_failure {
231                    plan.statements.truncate(1);
232                    plan.statements.push(bulk_fts_failure());
233                }
234                if let Some(claim) = key_claim {
235                    plan.statements.insert(0, claim);
236                }
237                plan.statements
238                    .extend(super::entity_aliases::unguarded(alias_statements));
239                Ok((entity, AtomicOpPlan::AddEntity(plan)))
240            }
241            EntityAdmission::Exempt(prepared) => {
242                let entity = prepared.entity().clone();
243                let (mut required, _) = self
244                    .prepare_admitted_entity_indexes(token, &entity, &[], false)
245                    .await?;
246                if inject_fts_failure {
247                    required = vec![bulk_fts_failure()];
248                }
249                if let Some(claim) = key_claim {
250                    required.insert(0, claim);
251                }
252                required.extend(super::entity_aliases::unguarded(alias_statements));
253                let plan = prepared.into_plan(
254                    EntityCandidateMutation::CreateIfAbsent,
255                    required,
256                    PostCommitEffect::None,
257                )?;
258                Ok((entity, AtomicOpPlan::FinalizeEntity(Box::new(plan))))
259            }
260        }
261    }
262}
263
264/// Project `aliases` onto the bulk row `entity` and return the statements
265/// that write them, under the id and creation time the row carries now.
266fn project_bulk_aliases(entity: &mut Entity, aliases: &EntityAliasChange) -> Vec<SqlStatement> {
267    let created_at = entity.created_at;
268    super::entity_aliases::apply_entity_alias_change(entity, aliases, created_at, None).1
269}
270
271fn bulk_entity_plan(entity: &Entity) -> RuntimeResult<AddEntityPlan> {
272    crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
273    let mut statements = vec![PlanStatement {
274        statement: entity_upsert_statement(entity),
275        guard: Some(AffectedRowGuard::exactly(1)),
276    }];
277    // The FTS insert and rowid-map insert must remain adjacent on one connection.
278    statements.extend(
279        insert_document_statements("fts_entities", &entity_fts_document(entity))
280            .into_iter()
281            .map(|statement| PlanStatement {
282                statement,
283                guard: None,
284            }),
285    );
286    Ok(AddEntityPlan {
287        entity_id: entity.id,
288        statements,
289        post_commit: PostCommitEffect::None,
290    })
291}
292
293fn bulk_fts_failure() -> PlanStatement {
294    PlanStatement {
295        statement: SqlStatement {
296            sql: "INSERT INTO __khive_create_many_injected_failure__ DEFAULT VALUES".into(),
297            params: vec![],
298            label: Some("fts-insert-injected-failure".into()),
299        },
300        guard: None,
301    }
302}