1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Validate phase of an update: the payload gates, in the order the
//! wire contract fixes them — the empty-mutation guard, the anchors
//! payload, the schema and the type, section-mode conflicts, the
//! required-section and updatable-section gates, section keys and
//! content, metadata key gates, the set/unset overlap, and the
//! repair-power gate. Refusals leave nothing behind.
use std::collections::HashSet;
use std::sync::Arc;
use memstead_schema::{Schema, TypeDefinition};
use crate::entity::{Entity, EntityId};
use crate::runtime_validator::{
validate_section_content, validate_section_keys, validate_unsettable_metadata_key,
validate_updatable_section, validate_writable_metadata_key,
};
use super::super::unknown_type_error;
use super::resolve::ResolvedUpdate;
use super::{Engine, EngineError, UpdateEntityArgs};
/// An update past every payload gate: the schema and the type the
/// compose phase renders against, and the validated anchors payload.
pub(super) struct ValidatedUpdate {
pub(super) args: UpdateEntityArgs,
pub(super) mount_idx: usize,
pub(super) mem: String,
pub(super) entity: Entity,
pub(super) prev_body_targets: HashSet<EntityId>,
pub(super) schema: Arc<Schema>,
pub(super) type_def: Arc<TypeDefinition>,
pub(super) anchors: Vec<crate::anchor::Anchor>,
pub(super) anchor_unsets: Vec<crate::anchor::AnchorUnset>,
}
impl Engine {
/// Run the payload gates over a resolved update.
pub(super) fn validate_update(
&self,
resolved: ResolvedUpdate,
) -> Result<ValidatedUpdate, EngineError> {
let ResolvedUpdate {
args,
mount_idx,
mem,
entity,
prev_body_targets,
} = resolved;
let id = &args.id;
// Empty-mutation guard. After existence/stub/hash
// gates so the more-specific errors fire first. A payload
// with no recognised mutation content refuses BEFORE any
// mutation work runs so a misspelled or omitted mutation
// key (which deserialised to empty defaults under the
// lenient pre-fix posture) doesn't silently land as
// `succeeded: N, action: "updated", write_id: ""`.
// Distinct from `UPDATE_NOOP` (a warning that fires when
// mutation content was provided but matched the current
// entity state) — the two are different states and ship
// different envelopes.
if args.sections.is_empty()
&& args.append_sections.is_empty()
&& args.patch_sections.is_empty()
&& args.sections_unset.is_empty()
&& args.metadata.is_empty()
&& args.metadata_unset.is_empty()
&& args.declare_relations.is_empty()
&& args.relations_unset.is_empty()
&& args.anchors.is_empty()
&& args.anchors_unset.is_empty()
{
return Err(EngineError::EmptyUpdate { id: id.to_string() });
}
// Validate any `anchors[]` / `anchors_unset[]` payload up front —
// a malformed element refuses the whole update with a typed
// `INVALID_ANCHOR` envelope before any disk write, on every path
// (real / dry-run / no-op). Empty payloads → empty vecs (no
// sidecar write; byte-identical to a pre-anchor update).
let validated_anchors = self.validate_anchor_inputs(&mem, &args.anchors)?;
let validated_anchor_unsets = Self::validate_anchor_unsets(&args.anchors_unset)?;
let schema = self
.schemas
.get(&mem)
.expect("schema present for every registered mount")
.clone();
let type_def = schema
.get_type(&entity.entity_type)
.ok_or_else(|| unknown_type_error(schema.as_ref(), &entity.entity_type))?;
// Mode-conflict: the same section key may not appear in
// more than one of `sections`, `append_sections`,
// `patch_sections`. Mirrors full's
// `EngineError::ConflictingSectionModes`. Three-way check:
// build the conflict list per key and reject when ≥2 modes
// claim it.
for key in args.sections.keys() {
let mut modes = vec!["sections".to_string()];
if args.append_sections.contains_key(key) {
modes.push("append_sections".to_string());
}
if args.patch_sections.contains_key(key) {
modes.push("patch_sections".to_string());
}
if modes.len() > 1 {
return Err(EngineError::ConflictingSectionModes {
section: key.clone(),
modes,
});
}
}
for key in args.append_sections.keys() {
if args.patch_sections.contains_key(key) {
return Err(EngineError::ConflictingSectionModes {
section: key.clone(),
modes: vec!["append_sections".to_string(), "patch_sections".to_string()],
});
}
}
// `sections_unset` is a fourth mode: a key both written and
// removed in one call is a contradiction, not a sequence.
for key in &args.sections_unset {
let mut modes = vec!["sections_unset".to_string()];
if args.sections.contains_key(key) {
modes.push("sections".to_string());
}
if args.append_sections.contains_key(key) {
modes.push("append_sections".to_string());
}
if args.patch_sections.contains_key(key) {
modes.push("patch_sections".to_string());
}
if modes.len() > 1 {
return Err(EngineError::ConflictingSectionModes {
section: key.clone(),
modes,
});
}
}
// Removing a REQUIRED section refuses with the conformance
// vocabulary: the right repair for a required-but-empty heading
// is filling it, never removing it. One refusal names every
// offending key.
let unset_required: Vec<crate::runtime_validator::MissingRequiredSection> = type_def
.required_sections()
.filter(|sec| args.sections_unset.contains(&sec.key))
.map(|sec| crate::runtime_validator::MissingRequiredSection {
entity_type: type_def.name.clone(),
key: sec.key.clone(),
heading: sec.heading.clone(),
write_rules: sec.write_rules.clone(),
})
.collect();
if !unset_required.is_empty() {
let mut type_guidance: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
type_guidance.insert(type_def.name.clone(), type_def.write_rules.clone());
return Err(EngineError::MissingRequiredSection {
entity_type: type_def.name.clone(),
missing_count: unset_required.len(),
sections: unset_required,
type_guidance,
pre_announced_missing_fields: Vec::new(),
});
}
// An absent key is a silent no-op (symmetric with
// `metadata_unset`), so the updatable-section gate applies only
// to keys the entity actually carries — otherwise unsetting a
// key the schema never declared would refuse instead of
// no-opping.
for key in &args.sections_unset {
if entity.sections.contains_key(key) || key == "relationships" {
validate_updatable_section(key.as_str(), type_def.as_ref())?;
}
}
validate_section_keys(
args.sections
.keys()
.chain(args.append_sections.keys())
.chain(args.patch_sections.keys())
.map(String::as_str),
type_def.as_ref(),
)?;
let mut heading_buf: Vec<&str> = Vec::new();
#[allow(unused_assignments)]
let mut catch_all = None;
// Refuse embedded `^## ` in section content on every update path
// that writes section bodies: `sections` (replace) and
// `append_sections` (append). `patch_sections` replaces a
// substring — its `new` text feeds into the eventual section
// body so it gets the same gate.
validate_section_content(
args.sections
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.chain(
args.append_sections
.iter()
.map(|(k, v)| (k.as_str(), v.as_str())),
)
.chain(
args.patch_sections
.iter()
.flat_map(|(k, ps)| ps.iter().map(move |p| (k.as_str(), p.new.as_str()))),
),
{
let t: &memstead_schema::TypeDefinition = type_def.as_ref();
catch_all = crate::runtime_validator::catch_all_context(t, &mut heading_buf);
catch_all
},
)?;
for key in args.sections.keys() {
validate_updatable_section(key.as_str(), type_def.as_ref())?;
}
for key in args.append_sections.keys() {
validate_updatable_section(key.as_str(), type_def.as_ref())?;
}
for key in args.patch_sections.keys() {
validate_updatable_section(key.as_str(), type_def.as_ref())?;
}
for key in args.metadata.keys() {
validate_writable_metadata_key(key.as_str(), type_def.as_ref())?;
}
// Unset has its own gate: the reserved `mem`/`id`/`type` triple
// is unset-ALLOWED (the sanctioned repair for entities that
// acquired a smuggled reserved key before the write gates
// closed) while engine-stamped timestamp fields stay refused —
// see `validate_unsettable_metadata_key`.
for key in &args.metadata_unset {
validate_unsettable_metadata_key(key.as_str(), type_def.as_ref())?;
}
// Reject the same key appearing in `metadata` (set) and
// `metadata_unset` — the wire contract is that the conflict is
// a hard error. Caught before any required-field /
// parse-metadata check so the resolution ("pick one map") is
// unambiguous regardless of whether the overlapping key is
// required.
let mut overlap: Vec<String> = args
.metadata
.keys()
.filter(|k| args.metadata_unset.iter().any(|u| u == k.as_str()))
.cloned()
.collect();
if !overlap.is_empty() {
overlap.sort();
overlap.dedup();
return Err(EngineError::SetAndUnsetConflict { keys: overlap });
}
// Repair-power gate:
// repair-shaped input is accepted only when the entity
// currently fails the conformance check against the effective
// schema. Conformance is per-entity-local and cheap, so the
// gate runs in pre-validation; no agent-settable flag exists —
// the entity's own state is the evidence. A pure-consistency
// break does not open the gate (those have ungated repair
// paths: `memstead_relate(remove)` and the additive params).
if !args.relations_unset.is_empty() {
let findings = crate::ops::integrity::entity_conformance_findings(
&self.store,
&entity,
schema.as_ref(),
&self.schemas,
);
if findings.is_empty() {
return Err(EngineError::RepairNotNeeded {
id: id.to_string(),
recovery: "use memstead_relate(remove=true) to detach an edge from a conformant entity, or the additive memstead_update params to evolve it"
.to_string(),
});
}
}
Ok(ValidatedUpdate {
args,
mount_idx,
mem,
entity,
prev_body_targets,
schema,
type_def,
anchors: validated_anchors,
anchor_unsets: validated_anchor_unsets,
})
}
}