Edits from functions

Most actions change objects with declarative rules: set this property from that parameter, create one object, link it to another. When the edits depend on logic that rules cannot express, an action hands the work to an edit function. The function reads what it needs, builds an edit set and returns it. It never writes. The action service validates that edit set, commits it in one transaction and logs it, exactly as it would for rules

3 operationsCreate, modify and delete
10,000Edits per action by default, raisable on request
1 transactionEvery edit commits together or none do
Per objectOptimistic concurrency on every object version touched

In the platform today

Built
  • An action type's rules can include a function rule, { name, args }, that calls a registered Python function from functions.py (or a TypeScript one from functions.ts)
  • The function reads through ctx as the person applying the action and returns a list of edits, each { op: modify | create | delete, type, key, set }; any other shape fails with FUNCTION_FAILED.INVALID_EDIT_SEQUENCE
  • Its edits join those of the other rules and commit with the action log entry
  • Edits are capped at 10,000 per action (ACTION_VALIDATION_FAILED.EDIT_LIMIT_EXCEEDED) and checked against value types and required properties (ACTION_VALIDATION_FAILED.REQUIRED_PROPERTY when a create leaves one unset or a modify clears one)
  • The function runs right before the commit, so its reads see every apply committed before it; when objects a parameter read keep changing, the action fails with CONCURRENCY_CONFLICT.OBJECT_CHANGED
  • A function that reads with ctx.sql reads as the person applying the action
  • :run with "options": {"dryRun": true} returns the edits without committing, and :runBatch runs each request as its own action and returns a result per item
On request
  • The edits() and @edits declarations with edits, link and unlink edits, staged and batched functions, version checks on every object the function loaded, and the test harness on this page
# An action type rule, as built
rules:
  - function:
      name: hold_batches_edits
      args:
        product: { parameter: product }
        batches: { parameter: batches }
        reason: { parameter: reason }
Requirements
  • Editor on the functions project to write and publish an edit function, and Editor or Owner on the ontology to bind it to an action type as a function rule
  • Every access label on the object types the function edits, for the author and for anyone who applies the action
  • The functions CLI @marklandstreet/ontology-cli and the generated client for your ontology
  • Deletes allowed from actions on any object type the function deletes from, and an egress allow-list entry set by an Administrator if the function calls outside hosts

When to use an edit function

Declarative rules are easier to review, render a readable summary in the action form and need no code release. Reach for an edit function when one of these is true

  • The set of objects to change is computed rather than chosen
  • The new values come from a calculation that spans several objects
  • The number of objects created depends on the data
  • The same logic has to be shared by several actions

Placing a hold on production batches is the canonical case. The person picks a product and its batches, but the action must also hold every lot still in the freezer or on a truck, count the units on hold against the product and open a quality issue linked to the product and every shop holding it

NeedDeclarative rulesEdit function
Change properties on the object the action was opened onYesYes, but unnecessary
Create a fixed number of objects from parametersYesYes
Change objects found by traversing linksOne hop, from an object parameterUp to 3 hops per query, any number of queries
Values computed from many objectsSimple expressions onlyAny TypeScript or Python logic
Create a data-dependent number of objectsNoYes
Call a model, a forecast or another functionNoYes
Summary shown in the action form before submitGenerated from rulesFrom the function's test run

An action can combine declarative rules and function rules: their edits join in rule order and commit together. Markham's clear-defect sets the defect's status with a modify rule and clears its active deferral with a function rule. When most of the edits are computed, put all of them in the function. That keeps the edit set in one place and avoids ordering questions between rules and code

Writing an edit function

Today a function rule calls a registered function that returns a list of modify, create and delete edits. Markham's clear-defect calls this one after its modify rule closes the defect

from mso.registry import function

@function(description='Edits that clear the active deferral on a defect being closed '
                      '(none if it has no deferral)',
          inputs={'defectId': 'string'}, output='array')
def clear_deferral_edits(ctx, defectId):
    d = ctx.get('defect', defectId)
    if not d or not d.get('deferralId'):
        return []
    m = ctx.get('deferral', d['deferralId'])
    if not m or m.get('status') != 'Active':
        return []
    return [{'op': 'modify', 'type': 'deferral', 'key': m['deferralId'],
             'set': {'status': 'Cleared', 'hoursRemaining': None, 'expiresSoon': False}}]

On request, edit functions declare the types they may touch and record edits through a builder

Edit operations

OperationEditRules
Create{ op: create, type, key, set }Fails if the key exists. Values are checked against value types and required properties
Modify{ op: modify, type, key, set }Only the listed properties change. Values are checked against value types, and clearing a required property fails
Delete{ op: delete, type, key }Removes the object

An edit of any other shape fails the function with FUNCTION_FAILED.INVALID_EDIT_SEQUENCE. On request, link and unlink edits

Reads inside an edit function

The function runs right before the commit, so its reads see every apply committed before it. On request, staged functions whose queries see their own pending edits

Reads see what the caller sees

An edit function reads with the permissions of the person applying the action. If a planner cannot see a shop in another region, a query for affected shops will not return it, and no edit for that shop will be produced. Where an action must reach every affected object regardless of who applies it, restrict who may apply it to people who can see all of them, and say so in the action's description

How an action applies the edit set

An edit function on its own changes nothing. Calling it from the API, an agent tool or a test returns the edit set as data, which is how the action form shows a preview. Only an action with a function rule commits it, through the same path every action takes

One transaction: check to commit Validatetypes, required,value types Criteriawho, when,object state Run functionsnapshot reads,edit set out Check versionsevery objectread or written Commitedits, log row,outbox rows Deliverwriteback andside effects version moved: rerun if deterministic
A test run stops after the version check and returns the edit set with before and after values. A real run commits, then the writeback service and side effects work from the outbox outside the transaction

Today, when objects a parameter read keep changing, the action fails with CONCURRENCY_CONFLICT.OBJECT_CHANGED. On request, the version check covers every object the function read, and a deterministic function is rerun on a fresh snapshot after a conflict. A function that made outbound calls is not rerun, because doing so could repeat an external effect

Conflicts are tracked per object, not per property. Two actions that update different properties of the same delivery still conflict. This is stricter than necessary, but it means an edit function never commits on top of an object state it did not see. Invariants that span several objects, such as "no more milk drawn from a silo than it holds", need both actions to write a shared object, for example the Raw milk silo itself, so that the version check catches the race

Batched execution

Today :runBatch runs each request as its own action and returns a result per item. On request, a batched edit function handles every item of a batch action in one call

Testing edit functions

Today :run with "options": {"dryRun": true} returns the edits without committing, so an edit set can be checked before anyone applies it. On request, a test harness runs an edit function against stubbed objects and checks the exact edit set. Failing tests block the release

Test the empty case and the limit case

Most production incidents with edit functions come from a batch with no lots, which produces an unexpected empty edit set, or a busy Saturday that returns far more objects than expected. Check both before the function goes to Stable

Limitations

  • An edit function never writes on its own. Called outside an action with a function rule, it only returns the edit set as data
  • Edits from declarative rules and function rules join in rule order and commit with one action log entry
  • Conflicts are detected per object, not per property, so two actions that edit different properties of one object still conflict
  • A function that made outbound calls or called an AI function is not rerun after a conflict, because a rerun could repeat an external effect
  • The function only produces edits for objects the person applying the action can see, so results can differ by who applies it
  • Properties a source owns with a "source wins" policy cannot be edited

Related