use crate::domain::{
DomainError, EffectiveInterval, EffectiveUpdate, EntityInput, EntityRef,
NormalizedEffectiveInterval, ObjectInput, ObjectValue, PredicateRef, SpikeRank,
WithdrawalScope,
};
use crate::graph::{
acquire_fact_locks_in_txn, create_episode_in_txn, endpoint_json, ensure_property_in_txn,
fact_text, fetch_all_txn, fetch_one, fetch_one_txn, merge_literal_in_txn, merge_node_in_txn,
node_json, rel_json, safe_rel, Episode, MergedNode, NodeSpec,
};
use crate::iri::is_iri;
pub(super) use crate::layers::normalize_scope as normalize_layers;
use crate::merge::merge_suggestions;
use crate::mutation::{
best_effort_review, mutation_response, run_precommit, run_transaction, MutationBudget,
TransactionDisposition,
};
use crate::payload::finish_mutation;
use crate::vocabulary::{
is_system_relationship, structural_relationship_for, CONTRADICTS_PROPERTY_IRI,
SCHEMA_RELATIONSHIPS, SUPERSEDES_PROPERTY_IRI, SYSTEM_RELATIONSHIPS,
};
use crate::{
error::{Error, Result},
operation_error,
};
use neo4rs::{query, Graph, Node, Relation, Txn};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::time::{sleep, Duration};
use uuid::Uuid;
pub(super) const FACT_LOCK_SCOPE: &str = "@fact";
pub(super) const LAYERS_PROPERTY: &str = "mindreader:property/layers";
pub(super) const PREDICATE_USAGE_PROPERTY: &str = "mindreader:property/predicate-usage";
pub(super) const MAX_WRITE_FACTS: usize = 20;
pub(super) fn write_fact_lock_requests(
subject_iri: &str,
prop_iri: &str,
object_iri: &str,
contradicts: bool,
) -> Vec<(String, String, String)> {
let mut locks = vec![
(
prop_iri.to_string(),
PREDICATE_USAGE_PROPERTY.into(),
FACT_LOCK_SCOPE.into(),
),
(
subject_iri.to_string(),
prop_iri.to_string(),
FACT_LOCK_SCOPE.into(),
),
(
subject_iri.to_string(),
LAYERS_PROPERTY.into(),
FACT_LOCK_SCOPE.into(),
),
(
object_iri.to_string(),
LAYERS_PROPERTY.into(),
FACT_LOCK_SCOPE.into(),
),
];
if contradicts {
locks.push((
object_iri.to_string(),
CONTRADICTS_PROPERTY_IRI.into(),
FACT_LOCK_SCOPE.into(),
));
}
locks
}
pub(super) fn revision_fact_lock_requests(
subject_iri: &str,
prop_iri: &str,
old_iri: &str,
new_iri: &str,
contradicts: bool,
) -> Vec<(String, String, String)> {
let mut locks = write_fact_lock_requests(subject_iri, prop_iri, new_iri, contradicts);
locks.push((
old_iri.to_string(),
LAYERS_PROPERTY.into(),
FACT_LOCK_SCOPE.into(),
));
locks
}
pub(super) fn withdrawal_fact_lock_requests(
subject_iri: &str,
predicate: Option<&str>,
) -> Vec<(String, String, String)> {
let mut locks = vec![(
subject_iri.to_string(),
predicate.unwrap_or("*").to_string(),
FACT_LOCK_SCOPE.into(),
)];
if let Some(predicate) = predicate {
locks.push((
predicate.to_string(),
PREDICATE_USAGE_PROPERTY.into(),
FACT_LOCK_SCOPE.into(),
));
}
locks
}
pub(super) fn reject_system_owned_predicate(predicate: &str) -> Result<()> {
if is_system_relationship(predicate) {
return Err(DomainError::InvalidInput(format!(
"predicate {predicate:?} is system-owned and cannot be mutated directly"
))
.into());
}
Ok(())
}
pub(super) fn is_transient_neo4j_error(error: &Error) -> bool {
error.is_transient_neo4j()
}
pub(super) fn validate_target(target: &TargetArgs) -> Result<()> {
if !matches!(target.kind.as_str(), "node" | "fact") {
return Err(DomainError::InvalidInput("target.kind must be node or fact".into()).into());
}
let iri = target.iri.trim();
if !is_iri(iri) {
return Err(DomainError::InvalidInput(format!(
"target.iri must be a scheme-qualified IRI, not {:?}",
target.iri
))
.into());
}
let fact_suffix = iri.strip_prefix("mindreader:relationship/");
if fact_suffix == Some("") {
return Err(DomainError::InvalidInput(
"target.iri must include the complete relationship identity after mindreader:relationship/"
.into(),
)
.into());
}
let fact_iri = fact_suffix.is_some();
if (target.kind == "fact") != fact_iri {
return Err(DomainError::InvalidInput(format!(
"target kind {:?} does not match IRI {:?}; paste the complete returned {{kind, iri}} handle",
target.kind, target.iri
))
.into());
}
Ok(())
}
pub(super) fn serialized_scope(record: &Value) -> Result<Vec<String>> {
record
.get("scope")
.and_then(Value::as_array)
.ok_or_else(|| operation_error!("serialized scope is not an array"))?
.iter()
.map(|value| {
value
.as_str()
.map(str::to_string)
.ok_or_else(|| operation_error!("serialized scope contains a non-string value"))
})
.collect()
}
pub(super) fn validate_write_args(args: &WriteArgs) -> Result<()> {
if args.facts.is_empty() || args.facts.len() > MAX_WRITE_FACTS {
return Err(DomainError::InvalidInput(format!(
"write facts must contain between 1 and {MAX_WRITE_FACTS} items"
))
.into());
}
Ok(())
}
pub(super) fn validate_withdraw_args(args: &WithdrawArgs) -> Result<()> {
match (&args.target, &args.subject) {
(Some(_), Some(_)) => {
return Err(DomainError::InvalidInput(
"withdraw target and subject are mutually exclusive; send target only, or subject with optional p"
.into(),
)
.into())
}
(None, None) => {
return Err(DomainError::InvalidInput(
"withdraw requires target, or subject with optional p".into(),
)
.into())
}
_ => {}
}
if args.target.is_some() && args.p.is_some() {
return Err(DomainError::InvalidInput(
"withdraw p applies only with subject; omit p when target is supplied".into(),
)
.into());
}
if let Some(target) = &args.target {
validate_target(target)?;
if target.kind != "fact" {
return Err(
DomainError::InvalidInput("withdraw target.kind must be fact".into()).into(),
);
}
}
Ok(())
}
pub(super) fn prepare_write_fact(fact: WriteFact) -> Result<PreparedWriteFact> {
let predicate = PredicateRef::parse(&fact.p)?;
reject_system_owned_predicate(predicate.iri())?;
let spike = SpikeRank::parse(fact.spike)?.map(|rank| rank.as_str().to_string());
let subject_spec = node_spec(EntityRef::from_input(fact.s)?);
let subject_kind = "element".to_string();
let subject_iri = EntityRef {
iri: subject_spec.iri.clone(),
name: subject_spec.name.clone(),
labels: subject_spec.labels.clone(),
}
.resolved_iri(&subject_kind);
let object_value = ObjectValue::from_input(fact.o)?;
let object_iri = object_value.resolved_iri();
let prop_iri = predicate.iri().to_string();
let structural = structural_relationship_for(&prop_iri);
if structural.is_some() && fact.effective.is_some() {
return Err(DomainError::InvalidInput(
"write effective applies only to ordinary state facts, not structural relationships"
.into(),
)
.into());
}
let effective = fact
.effective
.map(|interval| interval.normalize("write facts[].effective"))
.transpose()?;
Ok(PreparedWriteFact {
subject_spec,
subject_kind,
subject_iri,
object_value,
object_iri,
prop_iri,
structural,
spike,
contradicts: fact.contradicts,
effective,
})
}
pub(super) fn merge_memberships(current: &[String], incoming: &[String]) -> Vec<String> {
if current.is_empty() || incoming.is_empty() {
return Vec::new();
}
let mut merged = current.to_vec();
merged.extend_from_slice(incoming);
merged.sort();
merged.dedup();
merged
}
pub(super) fn remove_memberships(current: &[String], selected: &[String]) -> Option<Vec<String>> {
if selected.is_empty() {
return current.is_empty().then(Vec::new);
}
if current.is_empty() {
return None;
}
let remaining = current
.iter()
.filter(|layer| !selected.contains(layer))
.cloned()
.collect::<Vec<_>>();
(remaining != current).then_some(remaining)
}
#[cfg(test)]
pub(super) fn effective_weight(subject: i64, relationship: i64, object: i64) -> i64 {
subject.saturating_add(relationship).saturating_add(object)
}
fn relationship_iri() -> String {
format!("mindreader:relationship/{}", Uuid::new_v4())
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WriteFact {
pub s: EntityInput,
pub p: String,
pub o: ObjectInput,
#[serde(default)]
pub spike: Option<String>,
#[serde(default)]
pub contradicts: bool,
#[serde(default)]
pub effective: Option<EffectiveInterval>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WriteArgs {
pub facts: Vec<WriteFact>,
pub scope: Vec<String>,
}
pub(super) struct PreparedWriteFact {
subject_spec: NodeSpec,
subject_kind: String,
pub(super) subject_iri: String,
object_value: ObjectValue,
pub(super) object_iri: String,
pub(super) prop_iri: String,
structural: Option<String>,
spike: Option<String>,
pub(super) contradicts: bool,
effective: Option<NormalizedEffectiveInterval>,
}
#[derive(Debug, Clone)]
struct RevisionPlan {
pub s: EntityInput,
pub p: String,
pub old: ObjectInput,
pub replacement: ObjectInput,
pub layers: Vec<String>,
pub spike: Option<String>,
pub contradicts: bool,
pub reason: Option<String>,
pub effective: EffectiveUpdate,
pub previous_effective: Option<NormalizedEffectiveInterval>,
}
struct RevisionResult {
noop: bool,
scope: Vec<String>,
episode: Option<Episode>,
current_target: TargetArgs,
previous_target: TargetArgs,
fact: Option<Value>,
alternatives: Vec<Value>,
unify: Vec<Value>,
}
#[derive(Debug, Clone)]
struct WithdrawalSelector {
pub kind: String,
pub s: EntityInput,
pub p: Option<String>,
pub o: Option<ObjectInput>,
}
#[derive(Debug, Clone)]
struct WithdrawalPlan {
pub target: WithdrawalSelector,
pub layers: Vec<String>,
pub reason: Option<String>,
}
struct WithdrawalResult {
scope: Vec<String>,
episode: Option<Episode>,
withdrawn_targets: Vec<TargetArgs>,
reason: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TargetArgs {
pub kind: String,
pub iri: String,
}
impl TargetArgs {
fn fact(iri: impl Into<String>) -> Self {
Self {
kind: "fact".into(),
iri: iri.into(),
}
}
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviseArgs {
pub scope: Vec<String>,
pub target: TargetArgs,
pub replacement: ObjectInput,
#[serde(default)]
pub spike: Option<String>,
#[serde(default)]
pub contradicts: bool,
#[serde(default)]
pub reason: Option<String>,
#[serde(default)]
pub effective: EffectiveUpdate,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WithdrawArgs {
pub scope: Vec<String>,
#[serde(default)]
pub target: Option<TargetArgs>,
#[serde(default)]
pub subject: Option<EntityInput>,
#[serde(default)]
pub p: Option<String>,
#[serde(default)]
pub reason: Option<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct JudgeRating {
pub target: TargetArgs,
pub mode: String,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct JudgeArgs {
pub scope: Vec<String>,
pub ratings: Vec<JudgeRating>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlaceEdit {
pub target: TargetArgs,
#[serde(default)]
pub add: Vec<String>,
#[serde(default)]
pub remove: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlaceArgs {
pub scope: Vec<String>,
pub edits: Vec<PlaceEdit>,
}
fn node_spec(entity: EntityRef) -> NodeSpec {
NodeSpec {
iri: entity.iri,
name: entity.name,
labels: entity.labels,
}
}
async fn merge_object_in_txn(txn: &mut Txn, value: ObjectValue) -> Result<(MergedNode, bool)> {
match value {
ObjectValue::Literal { value, datatype } => {
Ok((merge_literal_in_txn(txn, &value, &datatype).await?, true))
}
ObjectValue::Entity(entity) => Ok((
merge_node_in_txn(txn, &node_spec(entity), "element", &[]).await?,
false,
)),
}
}
async fn apply_node_memberships_txn(
txn: &mut Txn,
node: &MergedNode,
requested: &[String],
) -> Result<bool> {
let row = fetch_one_txn(
txn,
query(
r#"
MATCH (n:Entity {iri: $iri})
WITH n, n.layers AS before
SET n.layers = CASE
WHEN size($layers) = 0 THEN []
WHEN $created THEN $layers
WHEN size(before) = 0 THEN []
ELSE reduce(acc = before, layer IN $layers |
CASE WHEN layer IN acc THEN acc ELSE acc + layer END)
END
RETURN before, n.layers AS after
"#,
)
.param("iri", node.iri.clone())
.param("layers", requested.to_vec())
.param("created", node.created),
)
.await?
.ok_or_else(|| operation_error!("missing node while applying layers: {}", node.iri))?;
let before = row.get::<Vec<String>>("before")?;
let after = row.get::<Vec<String>>("after")?;
Ok(before != after)
}
#[derive(Debug, Clone)]
pub(super) struct CurrentFact {
pub(super) rel_id: i64,
pub(super) iri: String,
pub(super) layers: Vec<String>,
pub(super) spike: Option<String>,
pub(super) effective: Option<NormalizedEffectiveInterval>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct FactMembershipChange {
pub(super) rel_id: i64,
pub(super) remaining: Vec<String>,
}
pub(super) fn plan_fact_membership_changes(
currents: &[CurrentFact],
selected: &[String],
) -> Vec<FactMembershipChange> {
currents
.iter()
.filter_map(|current| {
remove_memberships(¤t.layers, selected).map(|remaining| FactMembershipChange {
rel_id: current.rel_id,
remaining,
})
})
.collect()
}
pub(super) fn select_revision_current(
currents: &[CurrentFact],
selected_layers: &[String],
expected_fact_iri: Option<&str>,
) -> Option<CurrentFact> {
currents
.iter()
.find(|current| expected_fact_iri.is_none_or(|iri| current.iri == iri))
.filter(|current| remove_memberships(¤t.layers, selected_layers).is_some())
.cloned()
}
async fn find_current_pairs_txn(
txn: &mut Txn,
s: &str,
prop_iri: &str,
structural: Option<&str>,
o: &str,
effective: Option<&NormalizedEffectiveInterval>,
) -> Result<Vec<CurrentFact>> {
let rows = if let Some(rel) = structural {
let rel = safe_rel(rel)?;
let cypher = format!(
"MATCH (s:Entity {{iri: $s}})-[r:{rel}]->(o:Entity {{iri: $o}}) \
WHERE r.validTo IS NULL RETURN id(r) AS rid, r.iri AS iri, \
r.layers AS layers, r.spike AS spike, \
false AS effectiveQualified, null AS effectiveFrom, null AS effectiveTo"
);
fetch_all_txn(
txn,
query(&cypher)
.param("s", s.to_string())
.param("o", o.to_string()),
)
.await?
} else {
fetch_all_txn(
txn,
query(
"MATCH (s:Entity {iri: $s})-[r:ASSERTS]->(o:Entity {iri: $o}) \
WHERE r.validTo IS NULL AND r.propertyIri = $p \
AND coalesce(r.effectiveQualified, false) = $effectiveQualified \
AND (($effectiveFrom IS NULL AND r.effectiveFrom IS NULL) \
OR ($effectiveFrom IS NOT NULL \
AND r.effectiveFrom = datetime($effectiveFrom))) \
AND (($effectiveTo IS NULL AND r.effectiveTo IS NULL) \
OR ($effectiveTo IS NOT NULL \
AND r.effectiveTo = datetime($effectiveTo))) \
RETURN id(r) AS rid, r.iri AS iri, r.layers AS layers, r.spike AS spike, \
coalesce(r.effectiveQualified, false) AS effectiveQualified, \
toString(r.effectiveFrom) AS effectiveFrom, \
toString(r.effectiveTo) AS effectiveTo",
)
.param("s", s.to_string())
.param("o", o.to_string())
.param("p", prop_iri.to_string())
.param("effectiveQualified", effective.is_some())
.param(
"effectiveFrom",
effective.and_then(|interval| interval.from.clone()),
)
.param(
"effectiveTo",
effective.and_then(|interval| interval.to.clone()),
),
)
.await?
};
rows.into_iter()
.map(|row| {
Ok(CurrentFact {
rel_id: row.get("rid")?,
iri: row.get("iri")?,
layers: row.get("layers")?,
spike: row.get::<String>("spike").ok(),
effective: row
.get::<bool>("effectiveQualified")
.unwrap_or(false)
.then(|| NormalizedEffectiveInterval {
from: row.get::<String>("effectiveFrom").ok(),
to: row.get::<String>("effectiveTo").ok(),
}),
})
})
.collect()
}
struct RelationWrite<'a> {
rel_type: &'a str,
s: &'a str,
o: &'a str,
prop_iri: &'a str,
layers: &'a [String],
episode: &'a Episode,
reason: Option<&'a str>,
fact_text: &'a str,
spike: Option<&'a str>,
effective: Option<&'a NormalizedEffectiveInterval>,
}
async fn ensure_relation_txn(
txn: &mut Txn,
write: &RelationWrite<'_>,
) -> Result<(String, bool, Option<String>)> {
let current = find_current_pairs_txn(
txn,
write.s,
write.prop_iri,
Some(write.rel_type).filter(|rel| *rel != "ASSERTS"),
write.o,
write.effective,
)
.await?;
if current.len() > 1 {
return Err(operation_error!(
"multiple current relationship identities for ({}, {}, {})",
write.s,
write.prop_iri,
write.o
));
}
if let Some(current) = current.first() {
let merged = merge_memberships(¤t.layers, write.layers);
let next_spike = write.spike.or(current.spike.as_deref());
if merged == current.layers && next_spike == current.spike.as_deref() {
return Ok((current.iri.clone(), false, current.spike.clone()));
}
fetch_one_txn(
txn,
query(
"MATCH ()-[r]->() WHERE id(r) = $rid AND r.validTo IS NULL \
SET r.layers = $layers, r.layersUpdatedAt = datetime(), \
r.layerEpisodeId = $episode, r.spike = $spike \
RETURN r.iri AS iri",
)
.param("rid", current.rel_id)
.param("layers", merged)
.param("episode", write.episode.iri.clone())
.param("spike", next_spike.map(str::to_string)),
)
.await?
.ok_or_else(|| operation_error!("relationship disappeared while merging layers"))?;
return Ok((current.iri.clone(), true, next_spike.map(str::to_string)));
}
let rel_type = safe_rel(write.rel_type)?;
let iri = relationship_iri();
let cypher = format!(
r#"
MATCH (s:Entity {{iri: $s}}), (o:Entity {{iri: $o}})
CREATE (s)-[r:{rel_type} {{
iri: $iri,
propertyIri: $p,
layers: $layers,
weight: 0,
validFrom: datetime(),
effectiveQualified: $effectiveQualified,
episodeId: $episode,
factText: $factText,
spike: $spike
}}]->(o)
SET r.reason = $reason,
r.effectiveFrom = CASE WHEN $effectiveFrom IS NULL
THEN null ELSE datetime($effectiveFrom) END,
r.effectiveTo = CASE WHEN $effectiveTo IS NULL
THEN null ELSE datetime($effectiveTo) END
RETURN r.iri AS iri
"#
);
fetch_one_txn(
txn,
query(&cypher)
.param("s", write.s.to_string())
.param("o", write.o.to_string())
.param("iri", iri.clone())
.param("p", write.prop_iri.to_string())
.param("layers", write.layers.to_vec())
.param("episode", write.episode.iri.clone())
.param("reason", write.reason.map(str::to_string))
.param("factText", write.fact_text.to_string())
.param("spike", write.spike.map(str::to_string))
.param("effectiveQualified", write.effective.is_some())
.param(
"effectiveFrom",
write.effective.and_then(|interval| interval.from.clone()),
)
.param(
"effectiveTo",
write.effective.and_then(|interval| interval.to.clone()),
),
)
.await?
.ok_or_else(|| operation_error!("failed to create relationship {iri}"))?;
Ok((iri, true, write.spike.map(str::to_string)))
}
async fn refreshed_node_json_txn(txn: &mut Txn, iri: &str) -> Result<Value> {
let row = fetch_one_txn(
txn,
query("MATCH (n:Entity {iri: $iri}) RETURN n").param("iri", iri.to_string()),
)
.await?
.ok_or_else(|| operation_error!("missing node {iri}"))?;
node_json(&row.get::<Node>("n")?)
}
async fn refreshed_relation_json_txn(
txn: &mut Txn,
iri: &str,
subject_iri: &str,
object_iri: &str,
) -> Result<Value> {
let row = fetch_one_txn(
txn,
query("MATCH ()-[r]->() WHERE r.iri = $iri RETURN r").param("iri", iri.to_string()),
)
.await?
.ok_or_else(|| operation_error!("missing relationship {iri}"))?;
rel_json(&row.get::<Relation>("r")?, subject_iri, object_iri)
}
async fn find_conflicts_txn(
txn: &mut Txn,
s: &str,
prop_iri: &str,
structural: Option<&str>,
o_iri: &str,
layers: &[String],
effective: Option<&NormalizedEffectiveInterval>,
) -> Result<Vec<Value>> {
let rel_type = structural.unwrap_or("ASSERTS");
let is_structural = structural.is_some();
fetch_all_txn(
txn,
query(
r#"
MATCH (s:Entity {iri: $s})-[r]->(o:Entity)
WHERE r.validTo IS NULL AND o.iri <> $o
AND (size(s.layers) = 0 OR any(layer IN s.layers WHERE layer IN $layers))
AND (size(r.layers) = 0 OR any(layer IN r.layers WHERE layer IN $layers))
AND (size(o.layers) = 0 OR any(layer IN o.layers WHERE layer IN $layers))
AND (($isStructural AND type(r) = $relType)
OR (NOT $isStructural AND type(r) = 'ASSERTS' AND r.propertyIri = $p))
AND ($isStructural
OR ($effectiveQualified = false
AND coalesce(r.effectiveQualified, false) = false)
OR ($effectiveQualified = true
AND coalesce(r.effectiveQualified, false) = true
AND ($effectiveTo IS NULL OR r.effectiveFrom IS NULL
OR r.effectiveFrom < datetime($effectiveTo))
AND (r.effectiveTo IS NULL OR $effectiveFrom IS NULL
OR datetime($effectiveFrom) < r.effectiveTo)))
RETURN r, o, r.propertyIri AS p
"#,
)
.param("s", s.to_string())
.param("o", o_iri.to_string())
.param("layers", layers.to_vec())
.param("p", prop_iri.to_string())
.param("relType", rel_type.to_string())
.param("isStructural", is_structural)
.param("effectiveQualified", effective.is_some())
.param(
"effectiveFrom",
effective.and_then(|interval| interval.from.clone()),
)
.param(
"effectiveTo",
effective.and_then(|interval| interval.to.clone()),
),
)
.await?
.into_iter()
.map(|row| {
let relationship: Relation = row.get("r")?;
let object: Node = row.get("o")?;
let property = row.get::<String>("p")?;
let object_iri = object.get::<String>("iri")?;
let relationship = rel_json(&relationship, s, &object_iri)?;
let object = endpoint_json(&object)?;
Ok(json!({
"relationship": relationship,
"o": object,
"p": property,
}))
})
.collect()
}
async fn ensure_contradictions_txn(
txn: &mut Txn,
new_o: &str,
conflicts: &[Value],
layers: &[String],
episode: &Episode,
) -> Result<bool> {
let mut changed = false;
let mut old_objects = conflicts
.iter()
.filter_map(|conflict| conflict.pointer("/o/iri").and_then(Value::as_str))
.map(str::to_string)
.collect::<Vec<_>>();
old_objects.sort();
old_objects.dedup();
for old_o in old_objects {
let text = format!("{new_o} CONTRADICTS {old_o}");
let (_, relation_changed, _) = ensure_relation_txn(
txn,
&RelationWrite {
rel_type: "CONTRADICTS",
s: new_o,
o: &old_o,
prop_iri: CONTRADICTS_PROPERTY_IRI,
layers,
episode,
reason: None,
fact_text: &text,
spike: None,
effective: None,
},
)
.await?;
changed |= relation_changed;
}
Ok(changed)
}
#[cfg(feature = "developer-tools")]
pub async fn memory_write(graph: &Graph, args: WriteArgs) -> Result<Value> {
memory_write_with_budget(graph, args, MutationBudget::unbounded()).await
}
pub(crate) async fn memory_write_with_budget(
graph: &Graph,
args: WriteArgs,
budget: MutationBudget,
) -> Result<Value> {
for attempt in 0..3_u64 {
match memory_write_once(graph, args.clone(), budget).await {
Err(error) if attempt < 2 && is_transient_neo4j_error(&error) => {
sleep(Duration::from_millis(25 * (attempt + 1))).await;
}
result => return result,
}
}
unreachable!("bounded retry loop always returns")
}
async fn memory_write_once(
graph: &Graph,
args: WriteArgs,
budget: MutationBudget,
) -> Result<Value> {
validate_write_args(&args)?;
let layers = normalize_layers(args.scope)?;
let prepared = args
.facts
.into_iter()
.map(prepare_write_fact)
.collect::<Result<Vec<_>>>()?;
let mut locks = Vec::new();
for fact in &prepared {
locks.extend(write_fact_lock_requests(
&fact.subject_iri,
&fact.prop_iri,
&fact.object_iri,
fact.contradicts,
));
}
let transaction_layers = layers.clone();
let (changed, episode, items, created_iris, alternatives) =
run_transaction(graph, "write", budget, move |txn| {
Box::pin(async move {
acquire_fact_locks_in_txn(txn, &locks).await?;
let episode = create_episode_in_txn(txn, "write", None).await?;
let mut any_changed = false;
let mut created_iris = Vec::new();
let mut items = Vec::with_capacity(prepared.len());
let mut alternatives = Vec::new();
for fact in prepared {
let item =
write_prepared_fact_txn(txn, fact, &transaction_layers, &episode).await?;
any_changed |= !item.noop;
created_iris.extend(item.created_iris);
if !item.alternatives.is_empty() {
alternatives.push(json!({
"target": item.target,
"conflicts": item.alternatives,
}));
}
items.push(item.fact);
}
created_iris.sort();
created_iris.dedup();
let value = (any_changed, episode, items, created_iris, alternatives);
Ok::<_, Error>(if any_changed {
TransactionDisposition::Commit(value)
} else {
TransactionDisposition::Rollback(value)
})
})
})
.await?;
let merge_suggestions = if changed {
best_effort_review(
budget,
merge_suggestions(graph, &created_iris, &layers),
Vec::new(),
)
.await
} else {
Vec::new()
};
mutation_response(
"write",
changed,
finish_mutation(
json!({
"ok": true,
"noop": !changed,
"scope": layers,
"episode": if changed {
json!({ "iri": episode.iri, "at": episode.at, "tool": episode.tool })
} else {
Value::Null
},
"review": review_payloads(&merge_suggestions, &alternatives),
"facts": items.clone(),
}),
&items,
&[],
None,
None,
),
)
}
fn review_payloads(merge_suggestions: &[Value], alternatives: &[Value]) -> Value {
json!({ "unify": merge_suggestions, "alternatives": alternatives })
}
struct PreparedFactResult {
noop: bool,
fact: Value,
target: TargetArgs,
created_iris: Vec<String>,
alternatives: Vec<Value>,
}
async fn write_prepared_fact_txn(
txn: &mut Txn,
fact: PreparedWriteFact,
layers: &[String],
episode: &Episode,
) -> Result<PreparedFactResult> {
let subject = merge_node_in_txn(txn, &fact.subject_spec, &fact.subject_kind, &[]).await?;
let (object, object_is_literal) = merge_object_in_txn(txn, fact.object_value).await?;
let (_, property_created, _) = ensure_property_in_txn(txn, &fact.prop_iri).await?;
let mut changed = property_created;
let subject_scope = schema_node_scope(&subject.labels, layers);
let object_scope = schema_node_scope(&object.labels, layers);
changed |= apply_node_memberships_txn(txn, &subject, subject_scope).await?;
changed |= apply_node_memberships_txn(txn, &object, object_scope).await?;
let fact_text_value = fact_text(&subject.name, &subject.iri, &fact.prop_iri, &object);
let relation_scope = schema_edge_scope(
fact.structural.as_deref(),
&subject.labels,
&object.labels,
layers,
);
let (relationship_iri, relationship_changed, _) = ensure_relation_txn(
txn,
&RelationWrite {
rel_type: fact.structural.as_deref().unwrap_or("ASSERTS"),
s: &subject.iri,
o: &object.iri,
prop_iri: &fact.prop_iri,
layers: relation_scope,
episode,
reason: None,
fact_text: &fact_text_value,
spike: fact.spike.as_deref(),
effective: fact.effective.as_ref(),
},
)
.await?;
changed |= relationship_changed;
let relationship_json =
refreshed_relation_json_txn(txn, &relationship_iri, &subject.iri, &object.iri).await?;
let relationship_scope = serialized_scope(&relationship_json)?;
let conflicts = find_conflicts_txn(
txn,
&subject.iri,
&fact.prop_iri,
fact.structural.as_deref(),
&object.iri,
layers,
fact.effective.as_ref(),
)
.await?;
if fact.contradicts {
changed |= ensure_contradictions_txn(txn, &object.iri, &conflicts, layers, episode).await?;
}
let subject_json = refreshed_node_json_txn(txn, &subject.iri).await?;
let object_json = refreshed_node_json_txn(txn, &object.iri).await?;
let mut created_iris = Vec::new();
if subject.created {
created_iris.push(subject.iri.clone());
}
if object.created && !object_is_literal {
created_iris.push(object.iri.clone());
}
if property_created {
created_iris.push(fact.prop_iri.clone());
}
let target = TargetArgs::fact(relationship_iri);
Ok(PreparedFactResult {
noop: !changed,
fact: {
let mut item = crate::graph::fact_envelope(
subject_json,
&fact.prop_iri,
object_json,
&relationship_json,
&relationship_scope,
)?;
item["noop"] = json!(!changed);
item["conflicts"] = if fact.contradicts {
json!(conflicts)
} else {
json!([])
};
item
},
target,
created_iris,
alternatives: conflicts,
})
}
async fn change_fact_memberships_txn(
txn: &mut Txn,
current: &CurrentFact,
selected: &[String],
episode: &Episode,
reason: Option<&str>,
) -> Result<bool> {
let Some(remaining) = remove_memberships(¤t.layers, selected) else {
return Ok(false);
};
if remaining.is_empty() {
txn.run(
query(
"MATCH ()-[r]->() WHERE id(r) = $rid AND r.validTo IS NULL \
SET r.validTo = datetime(), r.withdrawnBy = $episode, \
r.reason = coalesce($reason, r.reason)",
)
.param("rid", current.rel_id)
.param("episode", episode.iri.clone())
.param("reason", reason.map(str::to_string)),
)
.await?;
} else {
txn.run(
query(
"MATCH ()-[r]->() WHERE id(r) = $rid AND r.validTo IS NULL \
SET r.layers = $layers, r.layersUpdatedAt = datetime(), \
r.layerEpisodeId = $episode, r.reason = coalesce($reason, r.reason)",
)
.param("rid", current.rel_id)
.param("layers", remaining)
.param("episode", episode.iri.clone())
.param("reason", reason.map(str::to_string)),
)
.await?;
}
Ok(true)
}
async fn change_fact_memberships_batch_txn(
txn: &mut Txn,
changes: &[FactMembershipChange],
episode: &Episode,
reason: Option<&str>,
) -> Result<()> {
if changes.is_empty() {
return Ok(());
}
let expected = i64::try_from(changes.len())
.map_err(|_| operation_error!("too many fact membership changes to batch"))?;
let ids = changes
.iter()
.map(|change| change.rel_id)
.collect::<Vec<_>>();
let remaining = changes
.iter()
.map(|change| change.remaining.clone())
.collect::<Vec<_>>();
let row = fetch_one_txn(
txn,
query(
r#"
UNWIND range(0, size($ids) - 1) AS i
WITH $ids[i] AS rid, $remaining[i] AS remaining
MATCH ()-[r]->()
WHERE id(r) = rid AND r.validTo IS NULL
FOREACH (_ IN CASE WHEN size(remaining) = 0 THEN [1] ELSE [] END |
SET r.validTo = datetime(), r.withdrawnBy = $episode,
r.reason = coalesce($reason, r.reason)
)
FOREACH (_ IN CASE WHEN size(remaining) > 0 THEN [1] ELSE [] END |
SET r.layers = remaining, r.layersUpdatedAt = datetime(),
r.layerEpisodeId = $episode,
r.reason = coalesce($reason, r.reason)
)
RETURN count(r) AS updated
"#,
)
.param("ids", ids)
.param("remaining", remaining)
.param("episode", episode.iri.clone())
.param("reason", reason.map(str::to_string)),
)
.await?
.ok_or_else(|| operation_error!("fact membership batch returned no result"))?;
let updated = row.get::<i64>("updated")?;
if updated != expected {
return Err(operation_error!(
"fact membership batch updated {updated} relationships, expected {expected}"
));
}
Ok(())
}
async fn apply_revision(
graph: &Graph,
args: RevisionPlan,
expected_fact_iri: Option<&str>,
budget: MutationBudget,
) -> Result<RevisionResult> {
for attempt in 0..3_u64 {
match apply_revision_once(graph, args.clone(), expected_fact_iri, budget).await {
Err(error) if attempt < 2 && is_transient_neo4j_error(&error) => {
sleep(Duration::from_millis(25 * (attempt + 1))).await;
}
result => return result,
}
}
unreachable!("bounded retry loop always returns")
}
async fn apply_revision_once(
graph: &Graph,
args: RevisionPlan,
expected_fact_iri: Option<&str>,
budget: MutationBudget,
) -> Result<RevisionResult> {
let layers = normalize_layers(args.layers)?;
let predicate = PredicateRef::parse(&args.p)?;
reject_system_owned_predicate(predicate.iri())?;
let spike = SpikeRank::parse(args.spike)?.map(|rank| rank.as_str().to_string());
let subject_spec = node_spec(EntityRef::from_input(args.s)?);
let subject_kind = "element".to_string();
let subject_iri = EntityRef {
iri: subject_spec.iri.clone(),
name: subject_spec.name.clone(),
labels: subject_spec.labels.clone(),
}
.resolved_iri(&subject_kind);
let old_value = ObjectValue::from_input(args.old)?;
let old_iri = old_value.resolved_iri();
let replacement_value = ObjectValue::from_input(args.replacement)?;
let replacement_iri = replacement_value.resolved_iri();
let prop_iri = predicate.iri().to_string();
let structural = structural_relationship_for(&prop_iri);
if structural.is_some() && !matches!(&args.effective, EffectiveUpdate::Inherit) {
return Err(DomainError::InvalidInput(
"revise effective applies only to ordinary state facts, not structural relationships"
.into(),
)
.into());
}
let replacement_effective = match args.effective.clone() {
EffectiveUpdate::Inherit => args.previous_effective.clone(),
EffectiveUpdate::Clear => None,
EffectiveUpdate::Set(interval) => Some(interval.normalize("revise effective")?),
};
let locks = revision_fact_lock_requests(
&subject_iri,
&prop_iri,
&old_iri,
&replacement_iri,
args.contradicts,
);
let transaction_layers = layers.clone();
let expected_fact_iri = expected_fact_iri.map(str::to_string);
let (mut result, created_iris) = run_transaction(graph, "revise", budget, move |txn| {
Box::pin(async move {
acquire_fact_locks_in_txn(txn, &locks).await?;
let old_currents = find_current_pairs_txn(
txn,
&subject_iri,
&prop_iri,
structural.as_deref(),
&old_iri,
args.previous_effective.as_ref(),
)
.await?;
let old_current = select_revision_current(
&old_currents,
&transaction_layers,
expected_fact_iri.as_deref(),
)
.ok_or_else(|| {
let selected = expected_fact_iri
.as_deref()
.map(|iri| format!("fact handle {iri}"))
.unwrap_or_else(|| format!("fact ({subject_iri}, {prop_iri}, {old_iri})"));
if old_currents.iter().any(|current| {
expected_fact_iri
.as_deref()
.is_none_or(|iri| current.iri == iri)
&& current.layers.is_empty()
}) && !transaction_layers.is_empty()
{
DomainError::Precondition(format!("{selected} is global; retry with scope: []"))
} else {
DomainError::Precondition(format!(
"cannot revise the selected memberships of non-current {selected}"
))
}
})?;
if old_iri == replacement_iri && old_current.effective == replacement_effective {
let target_iri = expected_fact_iri.as_deref().unwrap_or(&old_current.iri);
let target = TargetArgs::fact(target_iri);
return Ok(TransactionDisposition::Rollback((
RevisionResult {
noop: true,
scope: transaction_layers,
episode: None,
current_target: target.clone(),
previous_target: target,
fact: None,
alternatives: Vec::new(),
unify: Vec::new(),
},
Vec::new(),
)));
}
let effective_spike = spike.clone().or_else(|| old_current.spike.clone());
let subject = merge_node_in_txn(txn, &subject_spec, &subject_kind, &[]).await?;
let (replacement_object, replacement_is_literal) =
merge_object_in_txn(txn, replacement_value).await?;
let (_, property_created, _) = ensure_property_in_txn(txn, &prop_iri).await?;
let episode = create_episode_in_txn(txn, "revise", args.reason.as_deref()).await?;
apply_node_memberships_txn(txn, &subject, &transaction_layers).await?;
apply_node_memberships_txn(txn, &replacement_object, &transaction_layers).await?;
change_fact_memberships_txn(
txn,
&old_current,
&transaction_layers,
&episode,
args.reason.as_deref(),
)
.await?;
let replacement_text =
fact_text(&subject.name, &subject.iri, &prop_iri, &replacement_object);
let (replacement_relationship_iri, _, _) = ensure_relation_txn(
txn,
&RelationWrite {
rel_type: structural.as_deref().unwrap_or("ASSERTS"),
s: &subject.iri,
o: &replacement_object.iri,
prop_iri: &prop_iri,
layers: &transaction_layers,
episode: &episode,
reason: args.reason.as_deref(),
fact_text: &replacement_text,
spike: effective_spike.as_deref(),
effective: replacement_effective.as_ref(),
},
)
.await?;
let supersedes_text = format!("{} SUPERSEDES {old_iri}", replacement_object.iri);
let (supersedes_iri, _, _) = ensure_relation_txn(
txn,
&RelationWrite {
rel_type: "SUPERSEDES",
s: &replacement_object.iri,
o: &old_iri,
prop_iri: SUPERSEDES_PROPERTY_IRI,
layers: &transaction_layers,
episode: &episode,
reason: args.reason.as_deref(),
fact_text: &supersedes_text,
spike: None,
effective: None,
},
)
.await?;
txn.run(
query(
"MATCH (e:Entity:Episode {iri: $episode}) \
SET e.previousFactIri = $previousFactIri, \
e.replacementFactIri = $replacementFactIri, \
e.supersedesIri = $supersedesIri, \
e.selectedScope = $selectedScope",
)
.param("episode", episode.iri.clone())
.param("previousFactIri", old_current.iri.clone())
.param("replacementFactIri", replacement_relationship_iri.clone())
.param("supersedesIri", supersedes_iri)
.param("selectedScope", transaction_layers.clone()),
)
.await?;
let conflicts = find_conflicts_txn(
txn,
&subject.iri,
&prop_iri,
structural.as_deref(),
&replacement_object.iri,
&transaction_layers,
replacement_effective.as_ref(),
)
.await?;
if args.contradicts {
ensure_contradictions_txn(
txn,
&replacement_object.iri,
&conflicts,
&transaction_layers,
&episode,
)
.await?;
}
let subject_json = refreshed_node_json_txn(txn, &subject.iri).await?;
let replacement_json = refreshed_node_json_txn(txn, &replacement_object.iri).await?;
let relationship_json = refreshed_relation_json_txn(
txn,
&replacement_relationship_iri,
&subject.iri,
&replacement_object.iri,
)
.await?;
let mut created_iris = Vec::new();
if subject.created {
created_iris.push(subject.iri.clone());
}
if replacement_object.created && !replacement_is_literal {
created_iris.push(replacement_object.iri.clone());
}
if property_created {
created_iris.push(prop_iri.clone());
}
created_iris.sort();
created_iris.dedup();
let current_target = TargetArgs::fact(replacement_relationship_iri);
let previous_target =
TargetArgs::fact(expected_fact_iri.as_deref().unwrap_or(&old_current.iri));
let conflict_values = if args.contradicts {
Value::Array(conflicts.clone())
} else {
json!([])
};
let mut fact = crate::graph::fact_envelope(
subject_json,
&prop_iri,
replacement_json,
&relationship_json,
&transaction_layers,
)?;
fact["conflicts"] = conflict_values;
Ok::<_, Error>(TransactionDisposition::Commit((
RevisionResult {
noop: false,
scope: transaction_layers,
episode: Some(episode),
current_target,
previous_target,
fact: Some(fact),
alternatives: conflicts,
unify: Vec::new(),
},
created_iris,
)))
})
})
.await?;
if !result.noop {
result.unify = best_effort_review(
budget,
merge_suggestions(graph, &created_iris, &layers),
Vec::new(),
)
.await;
}
Ok(result)
}
async fn apply_withdrawal(
graph: &Graph,
args: WithdrawalPlan,
expected_fact_iri: Option<&str>,
budget: MutationBudget,
) -> Result<WithdrawalResult> {
for attempt in 0..3_u64 {
match apply_withdrawal_once(graph, args.clone(), expected_fact_iri, budget).await {
Err(error) if attempt < 2 && is_transient_neo4j_error(&error) => {
sleep(Duration::from_millis(25 * (attempt + 1))).await;
}
result => return result,
}
}
unreachable!("bounded retry loop always returns")
}
async fn apply_withdrawal_once(
graph: &Graph,
args: WithdrawalPlan,
expected_fact_iri: Option<&str>,
budget: MutationBudget,
) -> Result<WithdrawalResult> {
let layers = normalize_layers(args.layers)?;
let scope = WithdrawalScope::parse(&args.target.kind)?;
let subject = EntityRef::from_input(args.target.s)?;
let subject_iri = subject.resolved_iri("element");
let predicate = args
.target
.p
.map(PredicateRef::parse)
.transpose()?
.map(|predicate| predicate.iri().to_string());
if let Some(predicate) = &predicate {
reject_system_owned_predicate(predicate)?;
}
let object_iri = args
.target
.o
.map(ObjectValue::from_input)
.transpose()?
.map(|object| object.resolved_iri());
match scope {
WithdrawalScope::Fact if predicate.is_none() || object_iri.is_none() => {
return Err(DomainError::InvalidInput(
"fact withdrawal requires target.p and target.o".into(),
)
.into())
}
WithdrawalScope::Predicate if predicate.is_none() || object_iri.is_some() => {
return Err(DomainError::InvalidInput(
"predicate withdrawal requires target.p and forbids target.o".into(),
)
.into())
}
WithdrawalScope::Subject if predicate.is_some() || object_iri.is_some() => {
return Err(DomainError::InvalidInput(
"subject withdrawal forbids target.p and target.o".into(),
)
.into())
}
_ => {}
}
let protected = SCHEMA_RELATIONSHIPS
.iter()
.chain(SYSTEM_RELATIONSHIPS)
.map(|value| (*value).to_string())
.collect::<Vec<_>>();
let locks = withdrawal_fact_lock_requests(&subject_iri, predicate.as_deref());
let expected_fact_iri = expected_fact_iri.map(str::to_string);
run_transaction(graph, "withdraw", budget, move |txn| {
Box::pin(async move {
acquire_fact_locks_in_txn(txn, &locks).await?;
let rows = match scope {
WithdrawalScope::Subject => {
fetch_all_txn(
txn,
query(
r#"
MATCH (s:Entity {iri: $s})-[r]->(o:Entity)
WHERE r.validTo IS NULL
AND NOT type(r) IN $protected
AND NOT s:Class AND NOT s:Property
AND NOT o:Class AND NOT o:Property
AND (size(s.layers) = 0
OR any(layer IN s.layers WHERE layer IN $layers))
AND (size(r.layers) = 0
OR any(layer IN r.layers WHERE layer IN $layers))
AND (size(o.layers) = 0
OR any(layer IN o.layers WHERE layer IN $layers))
RETURN id(r) AS rid, r.iri AS iri, r.layers AS layers
"#,
)
.param("s", subject_iri.clone())
.param("protected", protected)
.param("layers", layers.clone()),
)
.await?
}
WithdrawalScope::Fact | WithdrawalScope::Predicate => {
let predicate = predicate.as_deref().expect("validated predicate");
let structural = structural_relationship_for(predicate);
let rel_clause = structural
.as_deref()
.map(safe_rel)
.transpose()?
.map(|rel| format!(":{rel}"));
let object_clause = object_iri
.as_ref()
.map(|_| "AND o.iri = $o")
.unwrap_or_default();
let target_clause = expected_fact_iri
.as_deref()
.map(|_| "AND r.iri = $targetIri")
.unwrap_or_default();
let cypher = if let Some(rel) = rel_clause {
format!(
"MATCH (s:Entity {{iri: $s}})-[r{rel}]->(o:Entity) \
WHERE r.validTo IS NULL {object_clause} {target_clause} \
AND (size(s.layers) = 0 OR any(layer IN s.layers WHERE layer IN $layers)) \
AND (size(r.layers) = 0 OR any(layer IN r.layers WHERE layer IN $layers)) \
AND (size(o.layers) = 0 OR any(layer IN o.layers WHERE layer IN $layers)) \
RETURN id(r) AS rid, r.iri AS iri, r.layers AS layers"
)
} else {
format!(
"MATCH (s:Entity {{iri: $s}})-[r:ASSERTS]->(o:Entity) \
WHERE r.validTo IS NULL AND r.propertyIri = $p {object_clause} {target_clause} \
AND (size(s.layers) = 0 OR any(layer IN s.layers WHERE layer IN $layers)) \
AND (size(r.layers) = 0 OR any(layer IN r.layers WHERE layer IN $layers)) \
AND (size(o.layers) = 0 OR any(layer IN o.layers WHERE layer IN $layers)) \
RETURN id(r) AS rid, r.iri AS iri, r.layers AS layers"
)
};
let mut q = query(&cypher)
.param("s", subject_iri.clone())
.param("p", predicate.to_string())
.param("layers", layers.clone());
if let Some(object) = &object_iri {
q = q.param("o", object.clone());
}
if let Some(target_iri) = &expected_fact_iri {
q = q.param("targetIri", target_iri.clone());
}
fetch_all_txn(txn, q).await?
}
};
let currents = rows
.into_iter()
.map(|row| {
Ok(CurrentFact {
rel_id: row.get("rid")?,
iri: row.get("iri")?,
layers: row.get("layers")?,
spike: None,
effective: None,
})
})
.collect::<Result<Vec<_>>>()?;
let changes = plan_fact_membership_changes(¤ts, &layers);
let withdrawn_targets = changes
.iter()
.filter_map(|change| {
currents
.iter()
.find(|current| current.rel_id == change.rel_id)
.map(|current| TargetArgs::fact(current.iri.clone()))
})
.collect::<Vec<_>>();
if changes.is_empty() {
if !currents.is_empty()
&& currents.iter().all(|current| current.layers.is_empty())
&& !layers.is_empty()
{
return Err(DomainError::Precondition(
"fact target is global; retry with scope: []".into(),
)
.into());
}
return Ok(TransactionDisposition::Rollback(WithdrawalResult {
scope: layers,
episode: None,
withdrawn_targets: Vec::new(),
reason: args.reason,
}));
}
let episode = create_episode_in_txn(txn, "withdraw", args.reason.as_deref()).await?;
change_fact_memberships_batch_txn(txn, &changes, &episode, args.reason.as_deref())
.await?;
Ok(TransactionDisposition::Commit(WithdrawalResult {
scope: layers,
episode: Some(episode),
withdrawn_targets,
reason: args.reason,
}))
})
})
.await
}
async fn load_current_fact(
graph: &Graph,
iri: &str,
layers: &[String],
) -> Result<(
EntityInput,
String,
ObjectInput,
Option<NormalizedEffectiveInterval>,
)> {
let row = fetch_one(
graph,
query(
r#"
MATCH (s:Entity)-[r]->(o:Entity)
WHERE r.iri = $iri AND r.validTo IS NULL
AND (size(s.layers) = 0
OR any(layer IN s.layers WHERE layer IN $layers))
AND (size(r.layers) = 0
OR any(layer IN r.layers WHERE layer IN $layers))
AND (size(o.layers) = 0
OR any(layer IN o.layers WHERE layer IN $layers))
RETURN s, r, o, r.propertyIri AS p,
coalesce(r.effectiveQualified, false) AS effectiveQualified,
toString(r.effectiveFrom) AS effectiveFrom,
toString(r.effectiveTo) AS effectiveTo
"#,
)
.param("iri", iri.to_string())
.param("layers", layers.to_vec()),
)
.await?;
let row = match row {
Some(row) => row,
None => {
let existing = fetch_one(
graph,
query(
"MATCH ()-[r]->() WHERE r.iri = $iri AND r.validTo IS NULL \
RETURN r.layers AS layers",
)
.param("iri", iri.to_string()),
)
.await?;
return Err(if let Some(existing) = existing {
let stored = existing.get::<Vec<String>>("layers")?;
if stored.is_empty() && !layers.is_empty() {
DomainError::Precondition(format!(
"fact target {iri} is global; retry with scope: []"
))
} else {
DomainError::Precondition(
"fact target is missing, hidden, or historical".into(),
)
}
} else {
DomainError::Precondition("fact target is missing, hidden, or historical".into())
}
.into());
}
};
let subject: Node = row.get("s")?;
let object: Node = row.get("o")?;
let property: String = row.get("p")?;
let effective = row
.get::<bool>("effectiveQualified")
.unwrap_or(false)
.then(|| NormalizedEffectiveInterval {
from: row.get::<String>("effectiveFrom").ok(),
to: row.get::<String>("effectiveTo").ok(),
});
Ok((
entity_input_from_node(&subject)?,
crate::graph::local_predicate_name(&property),
object_input_from_node(&object)?,
effective,
))
}
fn entity_input_from_node(node: &Node) -> Result<EntityInput> {
Ok(EntityInput {
kind: "node".into(),
iri: Some(node.get::<String>("iri")?),
name: node.get::<String>("name").ok(),
labels: Vec::new(),
})
}
fn object_input_from_node(node: &Node) -> Result<ObjectInput> {
let labels: Vec<String> = node
.labels()
.into_iter()
.filter(|label| *label != "Entity")
.map(str::to_string)
.collect();
if labels.iter().any(|label| label == "Literal") {
return Ok(ObjectInput {
kind: "literal".into(),
iri: None,
name: None,
labels: Vec::new(),
value: Some(node.get::<String>("value")?),
datatype: Some(node.get::<String>("datatype")?),
});
}
Ok(ObjectInput {
kind: "node".into(),
iri: Some(node.get::<String>("iri")?),
name: None,
labels: Vec::new(),
value: None,
datatype: None,
})
}
#[cfg(feature = "developer-tools")]
pub async fn memory_revise(graph: &Graph, args: ReviseArgs) -> Result<Value> {
memory_revise_with_budget(graph, args, MutationBudget::unbounded()).await
}
pub(crate) async fn memory_revise_with_budget(
graph: &Graph,
args: ReviseArgs,
budget: MutationBudget,
) -> Result<Value> {
validate_target(&args.target)?;
if args.target.kind != "fact" {
return Err(DomainError::InvalidInput("revise target.kind must be fact".into()).into());
}
let layers = normalize_layers(args.scope)?;
let (s, p, old, previous_effective) = run_precommit(
"revise",
budget,
load_current_fact(graph, &args.target.iri, &layers),
)
.await?;
let result = apply_revision(
graph,
RevisionPlan {
s,
p,
old,
replacement: args.replacement,
layers,
spike: args.spike,
contradicts: args.contradicts,
reason: args.reason,
effective: args.effective,
previous_effective,
},
Some(&args.target.iri),
budget,
)
.await?;
let current_target = result.current_target;
let previous_target = result.previous_target;
let current_target_value = json!(current_target);
let previous_target_value = json!(previous_target);
let facts = result.fact.clone().into_iter().collect::<Vec<_>>();
let fact = result.fact.unwrap_or(Value::Null);
let alternatives = if result.alternatives.is_empty() {
Vec::new()
} else {
vec![json!({
"target": current_target_value.clone(),
"conflicts": result.alternatives,
})]
};
let episode = result.episode.map_or(
Value::Null,
|episode| json!({ "iri": episode.iri, "at": episode.at, "tool": episode.tool }),
);
mutation_response(
"revise",
!result.noop,
finish_mutation(
json!({
"ok": true,
"scope": result.scope,
"noop": result.noop,
"episode": episode,
"target": current_target_value.clone(),
"previousTarget": previous_target_value.clone(),
"fact": fact,
"review": {
"unify": result.unify,
"alternatives": alternatives,
},
}),
&facts,
&[],
Some(current_target_value),
Some(previous_target_value),
),
)
}
#[cfg(feature = "developer-tools")]
pub async fn memory_withdraw(graph: &Graph, args: WithdrawArgs) -> Result<Value> {
memory_withdraw_with_budget(graph, args, MutationBudget::unbounded()).await
}
pub(crate) async fn memory_withdraw_with_budget(
graph: &Graph,
args: WithdrawArgs,
budget: MutationBudget,
) -> Result<Value> {
validate_withdraw_args(&args)?;
let layers = normalize_layers(args.scope.clone())?;
let expected_fact_iri = args.target.as_ref().map(|target| target.iri.clone());
let withdrawal = if let Some(ref target) = args.target {
let (s, p, o, _) = run_precommit(
"withdraw",
budget,
load_current_fact(graph, &target.iri, &layers),
)
.await?;
WithdrawalPlan {
target: WithdrawalSelector {
kind: "fact".into(),
s,
p: Some(p),
o: Some(o),
},
layers,
reason: args.reason,
}
} else {
let subject = args.subject.expect("validated subject");
WithdrawalPlan {
target: WithdrawalSelector {
kind: if args.p.is_some() {
"predicate".into()
} else {
"subject".into()
},
s: subject,
p: args.p,
o: None,
},
layers,
reason: args.reason,
}
};
let result = apply_withdrawal(graph, withdrawal, expected_fact_iri.as_deref(), budget).await?;
let withdrawn = result.withdrawn_targets.len();
let withdrawn_facts = result
.withdrawn_targets
.iter()
.map(|target| json!({ "target": target }))
.collect::<Vec<_>>();
let episode = result.episode.map_or(
Value::Null,
|episode| json!({ "iri": episode.iri, "at": episode.at, "tool": episode.tool }),
);
mutation_response(
"withdraw",
withdrawn > 0,
finish_mutation(
json!({
"ok": true,
"scope": result.scope,
"noop": withdrawn == 0,
"episode": episode,
"withdrawn": withdrawn,
"withdrawnTargets": result.withdrawn_targets,
"reason": result.reason,
}),
&withdrawn_facts,
&[],
None,
None,
),
)
}
fn schema_node_labels(labels: &[String]) -> bool {
labels
.iter()
.any(|label| label == "Class" || label == "Property")
}
fn schema_node_scope<'a>(labels: &[String], scope: &'a [String]) -> &'a [String] {
if schema_node_labels(labels) {
&[]
} else {
scope
}
}
fn schema_edge_scope<'a>(
structural: Option<&str>,
subject_labels: &[String],
object_labels: &[String],
scope: &'a [String],
) -> &'a [String] {
match structural {
Some("INSTANCE_OF") if schema_node_labels(object_labels) => &[],
Some("SUBCLASS_OF" | "SUBPROPERTY_OF") => &[],
Some("DOMAIN" | "RANGE") if schema_node_labels(subject_labels) => &[],
_ => scope,
}
}
#[cfg(test)]
mod review_tests {
use super::review_payloads;
use serde_json::json;
#[test]
fn review_payloads_keeps_alternatives_when_conflicts_are_empty() {
let alternatives = vec![json!({
"target": {"kind":"fact","iri":"mindreader:relationship/a"},
"conflicts": [{"p":"observed"}]
})];
let review = review_payloads(&[], &alternatives);
assert_eq!(review["alternatives"].as_array().unwrap().len(), 1);
assert!(review["unify"].as_array().unwrap().is_empty());
}
}