Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clients/acceptance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ the rejection message can be asserted. The full three-suite contract is in

**`core`** — the VF 1.0 headline surface: Person agents, resource-specification booleans (#398/#407), offer/request proposals with `purpose` (#322) incl. immutability rejection, offers/requests index partition, transfer events, Claim settlement (`settles` → `settledBy`), `Process.intendedOutputs`, action-vocabulary parity (21 ids) and rejection guards (enum, action gate, temporal rule).

**`rea-flows`** — the REA engine in depth: an EconomicResource born from a `produce` event (with `conformsTo` inheritance), accounting arithmetic across produce/raise/lower/consume sequences, process `observedInputs`/`observedOutputs`, commitment→`fulfilledBy`, intent→`satisfiedBy`, agreement reverse fields, plan wiring (`plannedWithin`, `independentDemandOf`).
**`rea-flows`** — the REA engine in depth: an EconomicResource born from a `produce` event (with `conformsTo` inheritance), accounting arithmetic across produce/raise/lower/consume sequences, process `observedInputs`/`observedOutputs`, commitment→`fulfilledBy`, intent→`satisfiedBy`, agreement reverse fields, plan wiring (`plannedWithin`, `independentDemandOf`), and an `updateEconomicEvent` that changes the note and refuses a new `realizationOf` or `agreedIn` by name (#416).

**`crud`** — depth and edge cases: full Unit lifecycle (create/partial update/delete), people/organizations/agents partition, sparse partial updates across entities, delete visibility, cursor pagination without duplicates, SpatialThing WGS84 bounds, AgreementBundle membership, millisecond temporal round-trips, invalid actions on Commitment/Claim, and a **tripwire** documenting that agentRelationship mutations are schema-only (unimplemented in the DNA — the step starts failing the day someone implements them).

Expand Down
40 changes: 39 additions & 1 deletion clients/acceptance/src/scenarios/rea-flows.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { gql, type ApolloClient, type NormalizedCacheObject } from '@apollo/client/core'
import { type Runner } from '../steps.js'
import { expectRejection, type Runner } from '../steps.js'

type Client = ApolloClient<NormalizedCacheObject>

Expand Down Expand Up @@ -317,4 +317,42 @@ export async function runReaFlows(client: Client, r: Runner): Promise<void> {
say('Both sides of an observation can be corrected after the fact.')
return 'event and resource updates persist, revisions advance, omitted fields survive'
})

// #416: the zome used to keep `note` and discard every other update field.
// Only `note` may change on an observed event: every other field carries
// economic meaning, so the integrity zome refuses the change and names it.
await step('economicEvent update changes the note only and refuses realizationOf/agreedIn', async () => {
const createAgreement = gql`mutation ($a: AgreementCreateParams!) { res: createAgreement(agreement: $a) { agreement { id } } }`
const terms = (await client.mutate({ mutation: createAgreement, variables: { a: { name: 'Bakery terms' } } })).data?.res?.agreement?.id
const other = (await client.mutate({ mutation: createAgreement, variables: { a: { name: 'Other terms' } } })).data?.res?.agreement?.id
assert(terms && other, 'agreement id missing')
const event = (await client.mutate({
mutation: gql`mutation ($e: EconomicEventCreateParams!) { res: createEconomicEvent(event: $e) { economicEvent { id revisionId } } }`,
variables: { e: { action: 'produce', provider: alice, receiver: alice, resourceConformsTo: spec, resourceQuantity: { hasNumericalValue: 1 }, realizationOf: terms, agreedIn: 'https://example.org/terms', note: 'first pass' } },
})).data?.res?.economicEvent
assert(event?.id, 'event id missing')

const update = gql`mutation ($e: EconomicEventUpdateParams!) { res: updateEconomicEvent(event: $e) { economicEvent { id revisionId } } }`
await expectRejection(client, update, { e: { revisionId: event.revisionId, realizationOf: other } },
'EconomicEvent realizationOf cannot be changed after creation')
await expectRejection(client, update, { e: { revisionId: event.revisionId, agreedIn: 'https://example.org/other' } },
'EconomicEvent agreedIn cannot be changed after creation')
await client.mutate({ mutation: update, variables: { e: { revisionId: event.revisionId, note: 'second pass' } } })

const q = await client.query({
query: gql`query ($id: ID!, $a: ID!) {
economicEvent(id: $id) { note agreedIn realizationOf { id } }
agreement(id: $a) { economicEvents { id } }
}`,
variables: { id: event.id, a: terms },
})
const read = q.data?.economicEvent
assert(read?.note === 'second pass', `note did not update (got ${read?.note})`)
assert(read.realizationOf?.id === terms, `realizationOf moved (got ${read.realizationOf?.id})`)
assert(read.agreedIn === 'https://example.org/terms', `agreedIn moved (got ${read.agreedIn})`)
const listed = (q.data?.agreement?.economicEvents ?? []).map((e: any) => e.id)
assert(listed.includes(event.id), 'agreement.economicEvents lost the event after a note update')
say('A recorded event keeps its economic meaning; only its note can be edited.')
return 'note updates; realizationOf and agreedIn changes are refused by name; agreement index intact'
})
}
148 changes: 76 additions & 72 deletions dnas/hrea/zomes/coordinator/hrea/src/rea_economic_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,14 +416,30 @@ pub fn get_all_revisions_for_rea_economic_event(
Ok(records)
}

/// Sparse update payload for `update_rea_economic_event`: an absent (`None`)
/// field means "leave unchanged", a present one replaces the stored value. There
/// is no way to clear a field through an update, which is the same contract as
/// every other `*UpdateParams` merged with `merge_partial`.
///
/// Only `note` may change. An EconomicEvent is an observed fact, and every
/// other field carries economic meaning that a report computed earlier relies
/// on, so the integrity zome (`validate_economic_event_update`) rejects any
/// other change with `EconomicEvent <field> cannot be changed after creation`.
/// The other fields are declared here so that a change is refused rather than
/// silently dropped by serde, and so that a client echoing the whole event back
/// with only a new note still succeeds. A wrong event is fixed by recording a
/// new event that `corrects` it.
#[derive(Serialize, Deserialize, Debug)]
pub struct ReaEconomicEventUpdateParams {
pub note: Option<String>,
pub input_of: Option<ActionHash>,
pub output_of: Option<ActionHash>,
pub provider: Option<ActionHash>,
pub receiver: Option<ActionHash>,
pub agreed_in: Option<String>,
pub realization_of: Option<ActionHash>,
pub reciprocal_realization_of: Option<ActionHash>,
pub settles: Option<ActionHash>,
pub in_scope_of: Option<Vec<ActionHash>>,
pub triggered_by: Option<ActionHash>,
pub fulfills: Option<Vec<ActionHash>>,
Expand All @@ -437,16 +453,57 @@ pub struct UpdateReaEconomicEventInput {
pub entry: ReaEconomicEventUpdateParams,
}

/// Keep a single-valued relationship index in step with an update: drop the
/// link under the old base when the base changed, then point the link under the
/// current base at the new revision.
fn reindex_single(
old_base: &Option<ActionHash>,
new_base: &Option<ActionHash>,
link_type: LinkTypes,
revision: &ActionHash,
id: &ActionHash,
) -> ExternResult<()> {
if let Some(old) = old_base {
if new_base.as_ref() != Some(old) {
delete_links(old.clone().into(), id.clone().into(), link_type.clone())?;
}
}
if let Some(base) = new_base {
update_link(base.clone().into(), revision.clone(), link_type, id.clone().into())?;
}
Ok(())
}

/// The multi-valued counterpart of `reindex_single`, for `fulfills` and `satisfies`.
fn reindex_many(
old_bases: &Option<Vec<ActionHash>>,
new_bases: &Option<Vec<ActionHash>>,
link_type: LinkTypes,
revision: &ActionHash,
id: &ActionHash,
) -> ExternResult<()> {
let new_bases: &[ActionHash] = new_bases.as_deref().unwrap_or(&[]);
for old in old_bases.as_deref().unwrap_or(&[]) {
if !new_bases.contains(old) {
delete_links(old.clone().into(), id.clone().into(), link_type.clone())?;
}
}
for base in new_bases {
update_link(base.clone().into(), revision.clone(), link_type.clone(), id.clone().into())?;
}
Ok(())
}

#[hdk_extern]
pub fn update_rea_economic_event(input: UpdateReaEconomicEventInput) -> ExternResult<Record> {
let latest_record =
get(input.revision_id.clone(), GetOptions::default())?.ok_or(wasm_error!(
WasmErrorInner::Guest("Could not find the latest record".to_string())
))?;
let latest_record_decoded = ReaEconomicEvent::try_from(latest_record.clone())?;
let mut updated_rea_entry: ReaEconomicEvent = latest_record_decoded.clone();
// only update note field
updated_rea_entry.note = input.entry.note.clone();

let mut updated_rea_entry: ReaEconomicEvent =
merge_partial(input.entry, latest_record_decoded.clone())?;
updated_rea_entry.id = latest_record_decoded
.id
.clone()
Expand All @@ -463,75 +520,22 @@ pub fn update_rea_economic_event(input: UpdateReaEconomicEventInput) -> ExternRe
(),
)?;

if let Some(base) = updated_rea_entry.input_of.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ReaProcessToReaEconomicEventInputs,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.output_of.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ReaProcessToReaEconomicEventOutputs,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.provider.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ProviderToReaEconomicEvents,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.receiver.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ReceiverToReaEconomicEvents,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.realization_of.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ReaAgreementToReaEconomicEvents,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.triggered_by.clone() {
update_link(
AnyLinkableHash::from(base),
updated_rea_action_hash.clone(),
LinkTypes::ReaEconomicEventToReaEconomicEvents,
id.clone().into(),
)?;
}
if let Some(base) = updated_rea_entry.fulfills.clone() {
for b in base {
update_link(
AnyLinkableHash::from(b),
updated_rea_action_hash.clone(),
LinkTypes::CommitmentToFulfillingEconomicEvents,
id.clone().into(),
)?;
}
}
if let Some(base) = updated_rea_entry.satisfies.clone() {
for b in base {
update_link(
AnyLinkableHash::from(b),
updated_rea_action_hash.clone(),
// same pairing as create: events index under their own type
LinkTypes::IntentToSatisfyingEconomicEvents,
id.clone().into(),
)?;
}
}
// Point every relationship index at the new revision. The integrity rule
// keeps the bases fixed, so the old-base deletes in `reindex_*` only fire
// if that rule is ever relaxed.
let old = &latest_record_decoded;
let new = &updated_rea_entry;
let rev = &updated_rea_action_hash;
reindex_single(&old.input_of, &new.input_of, LinkTypes::ReaProcessToReaEconomicEventInputs, rev, &id)?;
reindex_single(&old.output_of, &new.output_of, LinkTypes::ReaProcessToReaEconomicEventOutputs, rev, &id)?;
reindex_single(&old.provider, &new.provider, LinkTypes::ProviderToReaEconomicEvents, rev, &id)?;
reindex_single(&old.receiver, &new.receiver, LinkTypes::ReceiverToReaEconomicEvents, rev, &id)?;
reindex_single(&old.realization_of, &new.realization_of, LinkTypes::ReaAgreementToReaEconomicEvents, rev, &id)?;
reindex_single(&old.triggered_by, &new.triggered_by, LinkTypes::ReaEconomicEventToReaEconomicEvents, rev, &id)?;
reindex_single(&old.settles, &new.settles, LinkTypes::ClaimToSettlingEvents, rev, &id)?;
reindex_many(&old.fulfills, &new.fulfills, LinkTypes::CommitmentToFulfillingEconomicEvents, rev, &id)?;
// same pairing as create: events index under their own type
reindex_many(&old.satisfies, &new.satisfies, LinkTypes::IntentToSatisfyingEconomicEvents, rev, &id)?;

let path = Path::from("all_economic_events");
update_link(
Expand Down
51 changes: 48 additions & 3 deletions dnas/hrea/zomes/integrity/hrea/src/rea_economic_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,13 +204,58 @@ fn validate_economic_event_fields(e: &ReaEconomicEvent) -> ValidateCallbackResul

/// On update, the core economic-event facts (who, what action) are immutable;
/// corrections are modelled as new events (vf:EconomicEvent.corrects), not edits.
/// An EconomicEvent records something that happened, and every field but `note`
/// carries economic meaning: who, what, how much, when, and which agreement,
/// commitment, intent, claim or scope it counts toward. Changing any of them
/// after the fact would make an accounting report computed earlier disagree
/// with one computed later, so only `note` may differ from the original (`id`
/// is bookkeeping, set on the first update). A wrong event is fixed by
/// recording a new event that `corrects` it.
fn validate_economic_event_update(
new: &ReaEconomicEvent,
old: &ReaEconomicEvent,
) -> ValidateCallbackResult {
crate::vf_check!(crate::vf_validate_unchanged(&old.provider, &new.provider, "provider", "EconomicEvent"));
crate::vf_check!(crate::vf_validate_unchanged(&old.receiver, &new.receiver, "receiver", "EconomicEvent"));
crate::vf_check!(crate::vf_validate_unchanged(&old.rea_action, &new.rea_action, "action", "EconomicEvent"));
// No `..`: a field added to the entry stops this compiling until it is
// either listed in `fixed!` below or deliberately left mutable here.
let ReaEconomicEvent {
id: _, note: _, rea_action: _, provider: _, receiver: _, input_of: _, output_of: _,
resource_inventoried_as: _, to_resource_inventoried_as: _, resource_classified_as: _,
resource_conforms_to: _, resource_quantity: _, effort_quantity: _, has_beginning: _,
has_end: _, has_point_in_time: _, at_location: _, agreed_in: _, realization_of: _,
reciprocal_realization_of: _, settles: _, in_scope_of: _, triggered_by: _, fulfills: _,
satisfies: _, corrects: _,
} = new;
macro_rules! fixed {
($($field:ident => $name:literal),+ $(,)?) => {
$(crate::vf_check!(crate::vf_validate_unchanged(&old.$field, &new.$field, $name, "EconomicEvent"));)+
};
}
fixed! {
rea_action => "action",
provider => "provider",
receiver => "receiver",
input_of => "inputOf",
output_of => "outputOf",
resource_inventoried_as => "resourceInventoriedAs",
to_resource_inventoried_as => "toResourceInventoriedAs",
resource_classified_as => "resourceClassifiedAs",
resource_conforms_to => "resourceConformsTo",
resource_quantity => "resourceQuantity",
effort_quantity => "effortQuantity",
has_beginning => "hasBeginning",
has_end => "hasEnd",
has_point_in_time => "hasPointInTime",
at_location => "atLocation",
agreed_in => "agreedIn",
realization_of => "realizationOf",
reciprocal_realization_of => "reciprocalRealizationOf",
settles => "settles",
in_scope_of => "inScopeOf",
triggered_by => "triggeredBy",
fulfills => "fulfills",
satisfies => "satisfies",
corrects => "corrects",
}
validate_economic_event_fields(new)
}

Expand Down
2 changes: 2 additions & 0 deletions docs/graphql-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ Where the CRUD set is incomplete, verified against `modules/vf-graphql-holochain
| `EconomicEvent` | no `deleteEconomicEvent` | events are an append-only record of what happened; correct one with a compensating event |
| `EconomicResource` | no `createEconomicResource`, no `deleteEconomicResource` | resources come into being through an event, via `newInventoriedResource` on `createEconomicEvent` |

`updateEconomicEvent` changes the `note` and nothing else. An EconomicEvent is an observed fact, and every other field carries economic meaning that a report computed earlier relies on: who and what, how much and when, and which agreement, commitment, intent, claim or scope it counts toward. The integrity zome therefore rejects an update that changes any field but `note`, with a message naming the field (`EconomicEvent realizationOf cannot be changed after creation`), and because the rule is in the integrity zome every peer enforces it, not only the coordinator. Sending a field's stored value back is accepted, so a client that echoes the whole event with a new note succeeds, and an absent `note` leaves the stored one unchanged. The base schema's `EconomicEventUpdateParams` still declares `agreedIn`, `triggeredBy` and `realizationOf`, and this adapter adds `reciprocalRealizationOf` and `settles`; sending a new value for any of them is refused. Set them when the event is created, and fix a wrong event by recording a new one that `corrects` it. Until #416 the zome kept only `note` and discarded the rest while still reporting success.

`offers` and `requests` are hREA extensions, not base ValueFlows: they partition proposals by `Proposal.purpose` through `get_proposals_by_purpose`. `purpose` itself is an hREA addition to the schema (`ProposalPurpose`, values `offer` and `request`), alongside `ResourceSpecification.mediumOfExchange`, `EconomicEvent.reciprocalRealizationOf`, `EconomicEvent.settles` and `Commitment.reciprocalClauseOf`. All of them are declared in `modules/vf-graphql-holochain/index.ts`.

Two things the zome stores that the schema does not yet expose: `ReaResourceSpecification.substitutable`, and `agentRelationship` with its role types, which the base schema declares but this adapter does not implement. `clients/acceptance/README.md` tracks the latter as a known gap.
Expand Down
Loading
Loading