Functions overview

Functions are versioned TypeScript or Python that read the Ontology and return typed results. You write one in TypeScript or Python against a client generated from your own object types, publish it under an ID, and call it from actions, derived properties, applications, agents, automations and the REST API. Every call runs with the caller's permissions

2 languagesTypeScript and Python, with V8 isolates and gVisor sandboxes on request
5 sDefault time per TypeScript call, up to 30 s
128 MBDefault heap per TypeScript call, up to 1 GB
SemverEvery published version is immutable and pinnable

In the platform today

Built
  • Functions in TypeScript and Python run in the platform service with tests
  • Python functions live in an ontology's functions.py, registered with @function(description=…, inputs={…}, output=…), and read through ctx as the caller: get, query, linked, aggregate, call, member, user and now()
  • ctx.sql(text, params) is one SELECT, read as the caller reads the lake in the SQL workspace: only the schemas sql.grants gives them, objects.<type> filtered to their view, and a backing dataset under its type's row policy with hidden and sealed columns removed. It is refused as the workspace refuses (PERMISSION_DENIED.TABLE_GRANT_REQUIRED, NOT_FOUND.TABLE_NOT_FOUND)
  • ctx.predict(model, rows, alias=…) returns a trained model's predictions, with rows checked against its input columns and every prediction logged
  • ctx.file(id) and ctx.file_info(id) return an attachment's bytes and metadata, for a file the caller may read
  • ctx.service_sql(text, params) is a service read for lookups, such as the next free document number, shown in the trace
  • TypeScript functions live in functions.ts, declared with query({ description, inputs, output, timeoutMs, memoryMB }, async (ctx, args) => …) from @marklandstreet/functions, and each call runs with the caller's permissions in a restricted process
  • Their limits are 5 s per call by default and 30 s at most, 128 MB of heap by default and 1 GB at most, 500 reads per call and calls nested 8 deep, set per implementation
  • Both kinds are called the same way by actions, agents, automations, evaluations, the Assistant and POST /api/v2/functions/{name}:invoke, which takes {"arguments": {…}} and returns {"function", "result", "ms"}; GET /api/v2/functions/typescript lists the TypeScript functions and their runtime
  • functions.ts is type-checked with a pinned TypeScript compiler against types generated from the ontology and the ctx API, when the ontology loads or reloads and on POST /api/v2/functions/typescript:check; errors carry the line and column, and by default the last version that passed keeps running
  • A thrown FunctionError returns its message as FUNCTION_FAILED.USER_FACING_ERROR (422)
  • Each accepted content of functions.ts is a version, set with export const version = "1.4.0" or numbered automatically, and callers can pin name@1.2.0, @^1, @~1.2 or @>=1.1
  • Inputs can be interface-typed, { type: "object", interface: "cold-asset" } in TypeScript or {'type': 'object', 'interface': 'cold-asset'} in Python, and receive the object with interface property names plus _type, _key and _title; ctx.member(interface, ref) reads one in either language
On request
  • Signatures read from types, the result cache, the egress allowlist, gVisor sandboxes for Python and higher limits

What a function is

Operations logic tends to end up in three places: spreadsheet formulas nobody can review, stored procedures in a system of record, and application code that each screen reimplements. Functions move that logic into one place that sits next to the model it reasons about. A function that computes how many hours of strawberry a shop has left is written once, tested once and released once. The operations view, the planning agent, the Saturday automation and a partner's integration all call the same version and get the same answer

A function has a signature (named, typed inputs and one typed output), a body, a version and an owner. The signature is extracted from your source code at publish time, stored in the Ontology registry as an immutable revision, and used to generate typed call sites in the Client SDK. Callers never pass untyped JSON blobs to a function. If a caller sends a Production batch where a Scoop shop is expected, the call fails before your code runs

There are four kinds of function. They share a runtime, a type system and a release process, and differ in what they are allowed to do

Kind and exampleWhat it may doTypical use
Query function
weekend_cover(shopId)
Read objects, links, time series and other functions. Never writesDerived properties, screen widgets, agent tools, API endpoints
Edit function
product_hold_edits(batch, hold)
Read, then return an edit set. Edits apply only when an action runs the functionActions whose edits depend on logic too rich for declarative rules
AI function
classify-supplier-email(subject, body)
Call a language model through the model gateway with a typed prompt and a schema for the outputClassifying, extracting, drafting text, ranking options
Model function
weekend-demand(shopId, sku)
Wrap a registered statistical or machine learning model with a typed signatureForecasts, anomaly scores, equipment health

Edit functions are covered in Edits from functions and AI functions in AI functions. The rest of this page applies to all four kinds

A function in TypeScript

TypeScript functions live in an ontology's functions.ts. Any exported constant created with query() becomes a function, with its signature in the definition, type-checked against the types generated from the ontology

import { query, FunctionError, type Shop } from "@marklandstreet/functions";

export const flavourStock = query({
  description: "Tubs on hand by flavour for one shop",
  inputs: { shop: { type: "string", objectType: "shop", required: true } },
  output: "struct",
}, async (ctx, { shop }: { shop: Shop }) => {
  if (shop.status === "Closed")
    throw new FunctionError(`${shop.name} is closed for this period`);
  const stops = await ctx.linked("shop", shop.shopId, "delivery-stop-shop");
  return { onHand: shop.tubsOnHand, strawberry: shop.stkStr, inboundRuns: stops.length };
});

On request, functions live in a repository with their own dependencies, and the compiler reads the signature from the TypeScript types

A function in Python

Python functions live in an ontology's functions.py, registered with @function and its description, inputs and output, and read through ctx as the caller. The function below is the Python form of the TypeScript one above

from mso.registry import function

@function(description='Tubs on hand and inbound delivery stops for one shop',
          inputs={'shop': 'string'}, output='struct')
def flavour_stock(ctx, shop):
    s = ctx.get('shop', shop)
    if not s:
        raise ValueError(f'shop {shop} not found')
    stops = ctx.linked('shop', s['shopId'], 'delivery-stop-shop')
    return {'onHand': s.get('tubsOnHand'),
            'strawberry': s.get('stkStr'),
            'inboundRuns': len(stops)}

On request, Python functions take their signature from type annotations and dataclasses, with dependencies locked at publish time

Pick the language by the work, not the team

TypeScript functions start in milliseconds and suit anything on a screen or in an agent's inner loop. Python functions start slower but bring NumPy, pandas, Polars, SciPy and your own models. A common split is TypeScript for derived properties and action logic, Python for forecasts, optimization and heavy aggregation

Types and the Ontology client

Every type in a signature maps to an Ontology type, so a function published from TypeScript can be called from Python and the reverse. Value types such as Temperature °C carry their constraints across the boundary: a function that declares a TemperatureC input rejects a value outside the value type's range before your code sees it

Ontology typeTypeScriptPython
String, Booleanstring, booleanstr, bool
Integer, Longnumber (checked integer), bigintint
Double, Decimalnumber, Decimalfloat, decimal.Decimal
Date, TimestampLocalDate, Timestamp (UTC instant)datetime.date, timezone-aware datetime
Value typeBranded type, e.g. TemperatureCNewType, e.g. TemperatureC
Structinterface or type alias@dataclass or TypedDict
List, optionalT[], T | undefinedlist[T], T | None
ObjectGenerated class, e.g. ShopGenerated class, e.g. Shop
Object setObjectSet<Shop>ObjectSet[Shop]
Geopoint, time series, attachmentGeoPoint, TimeSeries, AttachmentGeoPoint, TimeSeries, Attachment
Edits (edit functions only)EditsEdits

Reads are consistent and permissioned

The client inside a function is the same client the SDK generates, with two differences. First, every read in one call is pinned to a single snapshot of the object store taken when the call starts, so a function that reads a shop's stock and then its deliveries never sees one at 14:00:01 and the other at 14:00:03. Second, the client always reads as the caller. When a store manager calls weekend_cover for a shop outside their region, the row access policy on Scoop shop applies inside the function exactly as it would on the screen, and properties hidden from them by field access come back as unavailable rather than as values

That second rule means a function is never a way around access controls. In the platform service, ctx.sql reads with the caller's SQL grants, row policies and hidden properties too. ctx.service_sql is a service read for lookups, such as the next free number, shown in the call's trace. Publishing a function does not grant anyone access to the data it reads. To call a function, a person needs the Viewer role on the function's project; what the function can then see is limited by what that person can see

Prefer object sets to arrays

An object set is a description of objects, not the objects. Filtering, link traversal and aggregation on an object set are pushed down to the object query service and run against the index and the object store. Loading objects into an array and filtering in your code moves the data to the function instead, which is slower, costs memory and counts against the reads a call may make. Use arrays when you need to run logic that the query service cannot express, and only after narrowing the set as far as filters allow

The runtime

Today each TypeScript call runs in a restricted process with the caller's permissions. On request, TypeScript runs in V8 isolates and Python in gVisor sandboxes, with outbound calls limited to allowed hosts

Caching

On request, query functions cache results by version, arguments and the caller's access, cleared when an object they read changes

Where functions are called from

CallerHow it callsIdentity used
ActionsA function rule runs an edit function and applies its edit setThe person applying the action
Derived propertiesThe object query service evaluates a query function per object, in batches of up to 1,000The person reading the objects
ApplicationsGenerated SDK call or a widget bound to a functionThe signed-in person
AgentsA function exposed as a toolThe person the agent acts on behalf of
AutomationsAn effect that runs a function on matching objectsThe automation's owner
REST APIPOST /functions/{function}:invokeThe OAuth client or user token
POST /api/v2/functions/weekend_cover:invoke
POST /api/v2/functions/weekend_cover:invoke HTTP/1.1
Host: creamery.ontology.marklandstreet.com
Authorization: Bearer eyJhbGciOi…
Content-Type: application/json

{ "arguments": { "shopId": "SHP-BSL" } }

HTTP/1.1 200 OK
{ "function": "weekend_cover",
  "result": { "shopId": "SHP-BSL", "level": "At risk",
    "need": 34, "stock": 29, "arriving": 36, "short": 4,
    "flavours": [
      { "key": "stkStr", "need": 5.4, "forecast": 3.0, "stock": 5, "short": 0, "…": "…" },
      "…" ],
    "…": "…" },
  "ms": 83.8 }

A TypeScript function's version is pinned in the path, as flavourStock@^1.4:invoke. On request: version, cached and traceId in the response

Object inputs are passed by primary key over the API and loaded by the runtime at the caller's permissions. If the caller cannot see SHP-BSL, the response is a 404 with the same body as for a shop that does not exist, so a function cannot be used to probe for objects

Limits and errors

TypeScript limitDefaultHighest
Time per call5 s30 s
V8 heap per call128 MB1 GB
Reads through ctx per call500Set per implementation
Nested function call depth88

A definition can ask for more time or heap with timeoutMs and memoryMB, up to the highest values. All of these limits are set per implementation

A call that exceeds a limit fails with a typed error such as FUNCTION_TIMEOUT, MEMORY_LIMIT_EXCEEDED or FUNCTION_READ_LIMIT, and the trace shows how far it got. Exceptions you throw are reported to administrators with the stack trace and to end users as a generic failure. To show a specific message in a form or a screen, throw FunctionError (TypeScript) or, on request, raise FunctionError (Python). Its text is shown verbatim, so write it for the person reading it: "B-0841 has no QA results yet", not "qa_status was null"

Do not catch limit errors to return partial results

A function that catches its own timeout and returns what it has will look correct to every caller and be silently wrong. Narrow the object set, raise the limit, or move the work to a pipeline that precomputes it as a property

Limitations

  • Only edit functions produce edits, and only an action applies them. Query, AI and model functions never write
  • A function always reads as its caller and cannot see more than that person or client can. Publishing a function grants no access to data
  • Every read in a call is pinned to the snapshot taken when the call starts, so a function never sees changes committed while it runs
  • TypeScript functions have no file or child process access. On request, functions have no network access until an Administrator allow-lists hosts for the project
  • Do not rely on state between calls; anything to keep belongs in an object. On request, Python sandboxes are reset after each call
  • A function that makes outbound calls is treated as non-deterministic, so its action is not retried automatically on a write conflict
  • Only query functions can use the result cache. Edit functions are never cached

Related