gnomonlearn
Docs/Graph/RFC-0043

RFC-0043 · Graph Operations

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

A graph operation is the declarative form of a runtime-callable procedure: a typed (input, principal) → effect-pipeline → output contract. Operations are the request-handling unit of an Gnomon module — they are what API surfaces (RFC-0033) expose to external callers and what saga steps invoke internally.

The defining feature of an operation is the effect pipeline: rather than expressing behavior in imperative code, an operation declares an ordered sequence of typed effect steps (resource creates, statement upserts, template compositions, event emits, adapter calls). The runtime executes the pipeline within a single transaction, applying each step in order and rolling back on any failure.

This RFC codifies the legacy operation module object at /Volumes/Workspace/savvi-studio-full/packages/graph-module-model/model/objects/operation.ts. It specifies the operation declaration shape, the typed effect taxonomy, idempotency invariants for mutations, conflict policy, the optional workflow state machine, the authorization integration with predicate policies (RFC-0042), and the runtime execution model.

This RFC complements RFC-0008 §6 procedure declarations. The relationship is: language-level procedure declarations (RFC-0008) compile to graph operations defined here at the module-manifest level. Authors write procedure; the runtime sees operation.


2. Definitions

TermMeaning
OperationA declarative, typed runtime-callable unit. Has input schema, output schema, transport kind, authorization, and an effect pipeline.
TransportThe semantic kind of operation: query (read-only) or mutation (state-changing).
Effect stepOne typed action in the operation’s pipeline. Nine kinds defined in §5.
Effect pipelineThe ordered list of effect steps that the operation executes within a single transaction.
Idempotency keyA caller-supplied or server-derived key that uniquely identifies a mutation; replays of the same key return the original result without re-executing.
GuardA pre-flight policy expression that must evaluate true; if false, the operation is rejected with the configured error.
Conflict policyThe runtime’s behavior on concurrent-mutation conflicts. Currently only fail_fast is defined.
WorkflowAn optional state machine declaration that constrains operation invocations to declared transitions.

3. Operation Declaration

An operation object in a module manifest (RFC-0040 §9):

<name>:
  type: operation
  version:           <semver>
  transport:         query | mutation
  description:       <text>?
  inputSchemaRef:    <schema-ref>?         # entity/variant for input
  outputSchemaRef:   <schema-ref>?         # entity/variant for output
  timeoutMs:         number (default 10000)
  maxPayloadBytes:   number (default 262144)
  tenantBoundaryRef: <ref>                  # required: tenant scoping
  authorization:
    requiresAuth:        boolean (default true)
    requiresRoles:       [<role>, ...]?
    requiresPermissions: [<permission>, ...]?
    policy:              <policy-expression>?
  guards:
    - when:      <policy-expression>
      errorCode: <code>?
      message:   <text>?
  idempotency:
    requiredKey: boolean (default false)
    keyRef:      <ref>?
  conflictPolicy: fail_fast (default)
  effects:
    - kind:    <effect-kind>
      key:     <text>?
      with:    <map>?
      ...      # kind-specific fields
  workflow:                                # optional
    initialState:   <state>?
    states:         [<state>, ...]
    terminalStates: [<state>, ...]?
    transitions:
      - fromState:  <state>
        toState:    <state>
        trigger:    <trigger>
        guard:      <policy-expression>?
        effectKeys: [<effect-key>, ...]?
  errorCatalogRef:  <ref>?

3.1 Required fields

FieldRequired
versionYes (SemVer)
transportYes
tenantBoundaryRefYes (any operation MUST declare its tenant scoping)
effectsYes (1..20)

All other fields default as documented.

3.2 Transport semantics

TransportSemantics
queryRead-only. Effects MUST NOT mutate graph state. The runtime MAY parallelize concurrent invocations.
mutationState-changing. Effects MAY include any kind. Runs within a write transaction. Idempotency key is REQUIRED.

A mutation operation without idempotency.requiredKey: true MUST be rejected at compile time (M43010). A query operation containing any mutating effect (resource.create, resource.update, resource.delete, statement.upsert, statement.remove, template.compose, event.emit) MUST be rejected at compile time (M43011).

3.3 Tenant boundary

Every operation MUST declare tenantBoundaryRef, a reference to the workspace or tenant scope under which the operation runs. The runtime sets the backend tenant context (RFC-0037 §5.4) from this reference before invoking the effect pipeline.

tenantBoundaryRef MAY reference a session field (session.tenantId), an input field (input.organizationId), or a fixed module-scoped tenant. The runtime resolves the reference at request time.

Operations whose tenant boundary cannot be resolved at request time MUST be rejected with M43020 before any effects execute.


4. Authorization

Authorization combines four mechanisms:

authorization:
  requiresAuth:        true                   # principal must be authenticated
  requiresRoles:       [admin, manager]       # principal must have at least one role
  requiresPermissions: [edit.budget]          # principal must have all permissions
  policy:              { preset: app.write }  # predicate-policy preset

4.1 Conjunctive evaluation

All four checks apply conjunctively:

authorized ⇔
  (requiresAuth → principal is authenticated)
  ∧ (requiresRoles → principal has at least one of the listed roles)
  ∧ (requiresPermissions → principal has every listed permission)
  ∧ (policy → predicate-policy evaluation grants required level)

If any check fails, the operation is rejected before any effect executes. The error is Unauthorized (RFC-0035 core.errors.Unauthorized).

4.2 Predicate policy integration

The policy field references a predicate-policy preset (RFC-0042 §3.6). The runtime evaluates the preset against the operation’s (subject, resource) pair. The subject is typically the active principal; the resource is derived from the operation’s input or tenantBoundaryRef.

The integration with RFC-0042 is normative: ALL predicate-policy semantics (priority, matchMode, scoping, when expressions, cache invalidation) apply identically when invoked through an operation’s authorization.policy.

4.3 Roles and permissions

requiresRoles and requiresPermissions are simple attribute checks against the principal’s declared scopes (RFC-0048 §principal attributes). They are simpler than predicate-policy evaluation but cover the same authorization concerns for legacy compatibility.

Authors are encouraged to use policy (predicate-policy preset) for new operations; requiresRoles and requiresPermissions are retained for migration of legacy authorization decisions.


5. Effect Pipeline

5.1 Effect kinds

Nine effect kinds are defined. Each is a typed step with its own slot schema:

KindMutatingPurpose
resource.createYesCreate a Resource
resource.updateYesUpdate a Resource
resource.deleteYesSoft-delete a Resource
statement.upsertYesCreate or update a Statement
statement.removeYesInvalidate or remove a Statement
template.composeYesExecute a graph template
query.projectionNoRun a typed read-side projection
event.emitYes (semantic)Emit a domain event for downstream subscribers
adapter.callNo (per-adapter)Invoke an external adapter (RFC-0024 client)

Each step carries:

- kind:    <kind>
- key:     <text>?           # named handle for cross-step refs
- with:    <map>?            # parameters for the step
- ...      # kind-specific fields (e.g., template, event, adapter)

5.2 Step shapes

- kind: resource.create
  with: { kind: <ltree>, externalId?: <text>, data?: <map> }

- kind: resource.update
  with: { id: <ref>, data: <map>, merge?: bool }

- kind: resource.delete
  with: { id: <ref> }

- kind: statement.upsert
  with: { subject: <ref>, predicate: <ltree>, object: <ref>, data?: <map>,
          validFrom?: <ref>, validTo?: <ref> }

- kind: statement.remove
  with: { id: <ref> }

- kind: template.compose
  template: <qualified-template-name>
  with: <map>            # imports for the template

- kind: query.projection
  projection: <projection-name>?    # optional named projection

- kind: event.emit
  event: <event-name>
  payload: <expression>?

- kind: adapter.call
  adapter: <client-operation-ref>
  request: <expression>?

Each step MAY be assigned a key for cross-step referencing. Subsequent steps reference earlier results via {$ref: "<key>.<field>"} expressions.

5.3 Pipeline limits

  • effects MUST contain between 1 and 20 steps. Operations exceeding 20 steps MUST be decomposed (M43030).
  • The full pipeline executes in one transaction (RFC-0037 §4.8).
  • Step failures abort the transaction; no partial commits.

5.4 Step ordering and references

Steps execute in declaration order. A step’s with payload MAY reference the result of any earlier step via the {$ref: "<key>.<field>"} syntax (the same expression language as RFC-0039 §5).

Forward references (a step referencing a later step’s result) MUST be rejected at compile time (M43031).

5.5 Composing templates

The template.compose effect invokes a template (RFC-0039) within the operation’s transaction. The template’s exports become available to subsequent effect steps via the step’s key:

effects:
  - kind: template.compose
    key:  org-creation
    template: identity.create-organization
    with:
      orgName:  { $ref: input.name }
      ownerId:  { $ref: principal.id }

  - kind: statement.upsert
    with:
      subject:   { $ref: principal.id }
      predicate: org.member
      object:    { $ref: org-creation.root }

The template’s exports.root is accessible as <key>.root; other exports are accessible as <key>.<exportName>.


6. Idempotency

6.1 Mutation idempotency requirement

Every mutation operation MUST declare idempotency.requiredKey: true (§3.2). The runtime MUST refuse to execute a mutation without an idempotency key.

The key MAY be:

  • Caller-supplied — passed as a request header or body field (X-Idempotency-Key for HTTP, equivalent for other protocols).
  • Server-derived — declared via idempotency.keyRef, an expression that derives the key from input or principal context.

6.2 Replay semantics

When a mutation is invoked with a previously-seen idempotency key:

  • If the original execution succeeded: return the original result without re-executing.
  • If the original execution failed: re-execute (failures are not cached as terminal).
  • If the original is in-flight: block until the original completes; return its result.

The runtime MUST persist idempotency-key results for a duration governed by RFC-0046 (default 24 hours).

6.3 Key scope

Idempotency keys are scoped by (operation FQN, tenantId, principalId). The same key from a different principal or tenant is a fresh execution, not a replay.


7. Guards and Conflict Policy

7.1 Guards

Guards are pre-flight policy expressions evaluated AFTER authorization but BEFORE the first effect step:

guards:
  - when:      { $fn: "expr.greaterThan", args: [{ $ref: input.amount }, 0] }
    errorCode: invalid-amount
    message:   "amount must be positive"
  - when:      { $fn: "expr.notInBlackoutWindow" }
    errorCode: blackout-window

If any guard’s when evaluates to false, the operation aborts with a domain error (errorCode + message). The transaction is not opened; no effects execute.

Guards differ from authorization in that authorization checks identity and capability; guards check input validity, business rules, and runtime conditions.

7.2 Conflict policy

When two operations attempt to modify the same Resource concurrently, the conflict policy decides the resolution:

PolicyBehavior
fail_fast (default)The second-committing operation receives core.errors.Conflict; the first wins.

This RFC defines only fail_fast. Future revisions MAY add other policies (last_write_wins, merge, serialize); they MUST preserve the existing fail_fast semantics for backward compatibility.


8. Workflow State Machine

8.1 Optional declaration

Operations MAY declare a workflow state machine to constrain invocations:

workflow:
  initialState:   draft
  states:         [draft, pending, approved, rejected]
  terminalStates: [approved, rejected]
  transitions:
    - fromState:  draft
      toState:    pending
      trigger:    submit
      guard:      { $fn: "expr.complete", args: [{ $ref: input }] }
    - fromState:  pending
      toState:    approved
      trigger:    approve
      effectKeys: [notify-approver]
    - fromState:  pending
      toState:    rejected
      trigger:    reject

When a workflow is declared, the operation’s invocation requires a trigger parameter (in addition to the regular input). The runtime:

  1. Looks up the entity’s current state (from a designated state field on the operation’s subject Resource).
  2. Finds the transition with matching (fromState, trigger).
  3. Evaluates the transition’s guard expression (if present); rejects if false.
  4. Executes the effects identified by effectKeys (a subset of the operation’s full effect list); if no effectKeys, executes all effects.
  5. Updates the entity’s state to toState.

8.2 Terminal states

Transitions FROM a terminal state MUST be rejected at compile time (M43040). Once an entity reaches a terminal state, it cannot transition further via this operation.

8.3 Workflow scope

Workflows attach to operations, not to entity types. An entity can be the subject of multiple operations, each with its own workflow. The runtime serializes state-machine transitions on the same entity using row-level locks within the transaction.

8.4 Restrictions

  • query operations MUST NOT declare workflows (M43041).
  • The state field on the subject Resource MUST be a typed value matching the workflow’s states set; mismatches at runtime produce M43042.

9. Compile and Runtime Pipeline

9.1 Compile

At compile time, the operation declaration is:

  1. Validated against the schema in §3.
  2. Cross-checked: mutation requires idempotency key (§6.1); query forbids mutating effects (§3.2).
  3. Workflow validated: transitions reference declared states; no transitions FROM terminal states (§8.2).
  4. References resolved: tenantBoundaryRef, inputSchemaRef, outputSchemaRef, policy.preset, template references, adapter references.
  5. Registered in the operation registry by qualified name <module-namespace>.<operation-name>@<version>.

9.2 Runtime invocation

A request invoking the operation flows through:

1. Resolve operation by FQN
2. Set tenant context (from tenantBoundaryRef)
3. Authenticate (per authorization.requiresAuth + RFC-0048)
4. Evaluate authorization (roles, permissions, predicate policy preset)
5. Check idempotency cache (mutations only)
6. Open transaction
7. Evaluate guards
8. (If workflow) check current state; find matching transition; evaluate guard
9. Execute effect pipeline
10. (If workflow) update state to toState
11. Commit transaction
12. Persist idempotency result (mutations only)
13. Emit audit log entry (RFC-0047)
14. Return output

Every step that fails causes a transaction rollback (steps 6–11) or pre-transaction abort (steps 2–5, 7–8 if before transaction). The error type returned MUST match the failure cause:

FailureError
Steps 1, 2core.errors.NotFound (operation/tenant) or M43050
Step 3core.errors.Unauthorized
Step 4core.errors.Forbidden
Step 7 (guard)Domain error per guard’s errorCode
Step 8 (workflow guard)Domain error per transition’s guard
Step 9 (effect failure)Effect-kind-specific error (e.g., core.errors.Conflict for fail-fast collision)

10. Invariants

  1. Mutations MUST require idempotency keys (§3.2, M43010).
  2. Queries MUST NOT contain mutating effect kinds (§3.2, M43011).
  3. Every operation MUST declare tenantBoundaryRef (§3.3).
  4. The effect pipeline MUST contain 1..20 steps (§5.3).
  5. Forward references between effect steps MUST be rejected at compile time (§5.4, M43031).
  6. Workflow transitions FROM terminal states MUST be rejected at compile time (§8.2, M43040).
  7. Queries MUST NOT declare workflows (§8.4, M43041).
  8. Authorization is conjunctive across all four mechanisms (§4.1).
  9. Idempotency results are persisted per (operation FQN, tenantId, principalId) (§6.3).
  10. Every operation invocation produces an audit log entry (§9.2).

11. Compatibility and Migration

11.1 From legacy operation module object

This RFC is a faithful codification of the schema at /Volumes/Workspace/savvi-studio-full/packages/graph-module-model/model/objects/operation.ts:

Legacy fieldThis RFC
transport§3.2
inputSchemaRef, outputSchemaRef§3
timeoutMs, maxPayloadBytes§3
tenantBoundaryRef§3.3
authorization§4
guards§7.1
idempotency§6
conflictPolicy§7.2
effects (9 kinds)§5
workflow§8
errorCatalogRef(out of scope; future RFC)

The mapping is direct. Existing legacy operations install unchanged.

11.2 Relationship to RFC-0008 procedure

Authors write procedure declarations in .gnm source (RFC-0008 §6). The compiler lowers a procedure to one operation declaration in the module manifest. The lowering rules are:

  • Procedure input { } block → operation inputSchemaRef
  • Procedure returns → operation outputSchemaRef
  • Procedure execute { } block → operation effects[]
  • Procedure mustSatisfy → operation guards[]
  • Procedure declaration epistemic modifiers (stable, experimental, draft) → operation metadata

The full lowering algorithm is the responsibility of the compiler (RFC-0010 §4) and is normative there.

11.3 Behavior changes

  • tenantBoundaryRef is mandatory (§3.3). Legacy code permits operations without explicit tenant boundary; this RFC requires it.
  • Forward references between effect steps are rejected (§5.4). Legacy code does not enforce this.
  • maxPayloadBytes is normative (default 262144 bytes). Legacy code defaults the same value but does not enforce it; the runtime MUST reject inputs exceeding this size.

Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.