Interfaces and shared properties

An interface is a shape that several object types share. Write an app, a function, an automation or an agent tool against the interface and it works for every type that implements it, including types added later. Shared properties are the same idea at a smaller scale: one property definition reused across many types. This page covers both, how to implement and query them, and how to change them without breaking anything

No dataInterfaces are contracts; objects belong to implementing types
Many per typeA type can implement up to 20 interfaces by default, 100 on request
ExtensionInterfaces can extend other interfaces
1,000Implementing types per interface, by default

In the platform today

Built
  • Interfaces, shared properties and value types run in the platform service, defined in ontology.yaml as below
  • An interface has properties, inline or from a shared property, each optionally required, and links to an object type; it can extend others up to 5 levels, and cycles are refused
  • An object type lists the interfaces it implements, with explicit mappings, or automatic ones by the same shared property and then the same ID, and an optional where that limits which of its objects are members
  • The registry refuses a file where a required member is missing or a mapping has an incompatible type: the same value type, the same base type, or integer for double
  • An interface can start an object set in POST /api/v2/query and /query/aggregate, with filters, ordering, paging, derived values, grouping by _type and following an interface link, and each implementing type keeps its own access labels, row policies, and hidden and sealed properties
  • The routes are GET /api/v2/interfaces, /interfaces/{id}, /interfaces/{id}/objects, POST /interfaces/{id}/objects/search and GET /api/v2/shared-properties; the Python client has mso.interface(id) and generated classes, and model changes have operations such as addInterface and implementInterface, with checks for breaking uses
  • Action parameters can be interface-typed, { interface: id } (with type: objects for a list): they take an object of any implementing type as { objectType, key }, { _type, _key } or "type:key", read through the interface as the caller, and refuse others with PARAMETER_INVALID and an objectReason of NOT_AN_IMPLEMENTER, NOT_A_MEMBER, OBJECT_NOT_FOUND or PROPERTY_NOT_MAPPED
  • Conditions and templates read interface properties, a modify rule sets interface properties on the property each type maps them to, an action's objectType may name an interface, and GET /api/v2/interfaces/{id} lists the actions that take its objects
  • Python, TypeScript and AI function inputs take interface too, and functions in either language read one with ctx.member(interface, ref)
On request
  • Required actions, which resolve one interface action to each type's own action type, links to another interface, link cardinality, narrowing with .as(), and status, owners and deprecation

In the platform service, interfaces and shared properties are defined in ontology.yaml

valueTypes:
  temperature-c: { name: Temperature °C, type: double, unit: °C, min: -60, max: 100 }
sharedProperties:
  temperatureC:
    name: Temperature
    valueType: temperature-c
    description: Measured temperature, probe nearest the product
  setpointC:
    name: Setpoint
    valueType: temperature-c
    description: The temperature the unit is set to hold
interfaces:
  temperature-controlled:
    name: Temperature-controlled
    properties:
      temperature: { sharedProperty: temperatureC, required: true }
      setpoint: { sharedProperty: setpointC }
  cold-storage-asset:
    name: Cold storage asset
    # inherits properties and links; up to 5 levels, no cycles
    extends: [temperature-controlled]
    properties:
      assetName: { type: string, required: true }
      fill: { type: double, unit: "%" }
      lastReadingAt: { type: timestamp }
    links:
      waste: { to: waste, name: Waste }
objectTypes:
  silo:
    implements:
      - interface: cold-storage-asset
        properties: { assetName: name, fill: fillPct }
        links: { waste: waste-silo }
  equipment:
    implements:
      - interface: cold-storage-asset
        # only these objects are members
        where: { kind: { $in: [Cold room, Blast freezer, Hardening tunnel, Cheese cave] } }
        # temperature and setpoint map automatically: the same shared properties
        properties: { assetName: name, fill: fillPct }

Why interfaces

The illustrative ice cream maker keeps milk and product cold in four kinds of place: raw milk silos at the creamery, the plant's cold rooms, freezers and hardening tunnel, the backroom freezer in each scoop shop and refrigerated trucks on the road. Each is its own object type, with its own grain, keys and properties, because each is owned by a different team and changes for different reasons. Yet a quality lead asks one question across all of them: what is out of range right now, and for how long

Without interfaces there are two bad answers. One is four copies of every screen, function and alert, one per type, which drift apart. The other is a single Cold thing type with a kind column and every property of every kind, most of them empty. An interface avoids both: the four types stay separate, and each declares that it is also Temperature-controlled, with a temperature and a setpoint, and the three that store product are also a Cold storage asset with a name, a fill and a time of last reading

Temperature-controlled (interface) temperature · setpoint extended by Cold storage asset implements Raw milk siloname → assetNametemp → temperatureSIL-2 Equipmentsetpoint → setpointtemp → temperatureEQ-HTN Scoop shopfreezerSetpoint → setpointfreezerTemp → temperatureSHP-HFX Reefer deliverysetpoint → setpointtemp → temperatureDLV-5521
Each type keeps its own property names and maps them to the interface. An excursion monitor reads temperature and setpoint without knowing which type it is looking at

Anatomy of an interface

An interface declares members that each implementer supplies. Interface properties are built; on request, an interface also has required links and actions, and metadata like any resource, such as a display name, status and owners

MemberDeclaresImplementer supplies
Interface propertyA name, base type or value type, and whether it is requiredOne of its own properties with a compatible type
Required linkA side name, a target (an object type or another interface), a cardinality and whether it is requiredOne of its own link types whose other end satisfies the target
Required actionAn action name and its parameters, with no logicOne of its own action types, with a mapping of parameters

Interfaces hold no data and cannot be instantiated. There is no "Cold storage asset" object with a key of its own; every object you get back through the interface is a silo, a cold room or freezer, or a scoop shop, and keeps its own type, key and security

An action can take any cold storage asset, whatever its type

actionTypes:
  log-temperature:
    name: Log temperature reading
    # an interface: the log records each object's own type and key
    objectType: cold-storage-asset
    requiresApproval: false
    parameters:
      # any implementing type; type: objects for a list
      asset: { interface: cold-storage-asset, required: true }
      reading: { valueType: temperature-c, required: true }
    rules:
      # interface property names
      - modify: { object: { parameter: asset }, set: { temperature: { parameter: reading } } }
    notify:
      - group: operations
        # templates read interface properties
        message: "{{asset.assetName}}: {{reading}} °C, setpoint {{asset.setpoint}} °C"

Implementing an interface

An object type implements an interface by mapping every required member, and any optional members it wants to offer. The mapping is part of the object type's definition and changes through a proposal like any other part of it

# In ontology/object-types/shop.yaml
implements:
  - interface: cold-storage-asset
    properties:
      assetName: freezerName
      temperature: freezerTemp
      setpoint: freezerSetpoint
    links:
      lots: lot-shop                       # Shipped lot → Scoop shop, many to one
    actions:
      logExcursion:
        action: log-excursion
        parameters: { asset: shop, reading: reading, note: note }

Saving is blocked while a required member is unmapped or a mapping is incompatible. The rules for property mappings are

Interface expectsCan be mapped fromNot from
A value typeA property with the same value type, or a newer non-breaking version of itA bare base type, even if values happen to fit
A base typeThe same base type, or a widening: integer to long or to doubleA narrowing, or string to anything else
A single valueA scalar property, a struct field, or an array with a display rollupAn array without a display rollup
A structA struct whose fields include every interface field with compatible typesA struct missing a field
Any propertyA derived property, read-only through the interfaceNothing, if a required action of the interface writes it

When an interface property is backed by a shared property and the implementing type already uses the same shared property, the mapping is made automatically. A type keeps all of its own properties, links and actions beyond the interface, and can implement as many interfaces as it needs: a Raw milk silo is a Cold storage asset and, through it, Temperature-controlled

Querying through an interface

An interface works as a starting point for an object set. The result contains objects of every implementing type the reader can see, exposed through the interface's properties. Filters, ordering, aggregation and link traversal on interface members are pushed to each implementing type and merged. With the TypeScript client, name the interface's ID where you would name a type

import { Client } from "@marklandstreet/ontology-client";
const mso = new Client("https://creamery.ontology.marklandstreet.com", { getToken });

// Everything with a setpoint, furthest above it first
const warm = await mso.objects("temperature-controlled")
  .where({ setpoint: { $missing: false } })
  .derive({ overBy: "temperature - setpoint" })
  .page({ pageSize: 50, orderBy: "-overBy", select: ["temperature", "setpoint", "overBy"] });

// prints "equipment" "EQ-HTN" -33.2 first
for (const a of warm.data) console.log(a._type, a._key, a.temperature);

// Counts by implementing type
const byType = await mso.objects("temperature-controlled")
  .aggregate({ group: ["_type"], measure: { n: "count" } });

A where after derive filters on the derived value, such as .where({ overBy: { $gt: 3 } }). Typed interface descriptors, and narrowing to the concrete type with .as(), are delivered on request

Over REST, an interface object set is loaded with the same endpoint as any other object set. "from": "cold-storage-asset" works too, since interface IDs can't be object type IDs

POST /api/v2/query
{
  "query": {
    "from": {"interface": "cold-storage-asset"},
    "where": {"temperature": {"$gt": -30}}
  },
  "select": ["setpoint", "temperature", "lastReadingAt"],
  "pageSize": 100
}

On request, applying an action through an interface resolves the required action to the concrete action type of each object, so a "log excursion" button on a mixed list of cold storage assets runs log-excursion with a shop in its shop parameter and a silo in its silo parameter, each type with its own criteria and side effects

Functions, automations and agent tools

Functions take interface-typed parameters the same way they take object types, which is where interfaces pay off most. The excursion function below is written once and called for every cold storage asset by an automation, by the Assistant when someone asks "what's warm right now", and by the cold chain agent as a tool. When the plant adds a cold room next year, the equipment type's where makes it a Cold storage asset, and all three pick it up with no code change

import { query, type Context } from "@marklandstreet/functions";
import { ColdStorageAsset } from "@marklandstreet/functions";

/** Degrees above its setpoint, or 0 if the asset is within the margin of it now */
export const cold_chain_check = query("cold_chain_check",
  async (ctx: Context, asset: ColdStorageAsset): Promise<number> => {
    const margin = 1;
    if (asset.temperature == null || asset.setpoint == null) return 0;
    const ref = { objectType: asset._type, key: asset._key };
    const now = await ctx.member("cold-storage-asset", ref);
    const over = now.temperature - now.setpoint;
    return over > margin ? Math.round(over * 10) / 10 : 0;
  });

Agents see interfaces in their tool descriptions with the interface's description and members, which helps a model choose correctly between a question about one freezer and a question about the whole cold chain. Keep interface descriptions as carefully written as object type descriptions for that reason

LimitDefaultNotes
Implementing types per interface1,000100 when the interface is set for full-text search, since search fans out to every type
Interfaces per object type20Raisable to 100 on request
Properties per interface200Including inherited ones
Extension depth5 levelsCycles are rejected

Extending interfaces

An interface can extend any number of other interfaces and inherits all of their properties, required links and required actions. An implementer of the child must satisfy the whole inherited shape, and its objects appear in queries against both the child and every parent. Extension is how a small, stable base grows specific variants without copying

Two styles of interface are common, and both are useful

  • Capability interfaces describe something a type can do or have: Temperature-controlled, a temperature someone watches against a setpoint, which silos, cold equipment, shop freezers and reefer runs all have. They are small and many types implement several
  • Category interfaces describe what a type is: Cold storage asset, implemented by the raw milk silos, the plant's cold rooms and freezers, and the scoop shops for their backroom freezers. They often extend capability interfaces, as Cold storage asset extends Temperature-controlled
interface:
  id: cold-storage-asset
  extends: [temperature-controlled]
  properties:
    assetName: { baseType: string, required: true }
    fill:      { baseType: double, required: false }    # percent

Prefer several small interfaces composed together over one deep hierarchy. A type that needs half of a big interface ends up mapping placeholder values to satisfy the other half, which makes every consumer of the interface less trustworthy

Shared properties

A shared property is one property definition used by many object types. It holds the name, description, base type or value type, formatting, index and display options, and display priority, and every type that attaches it inherits them. Each local property keeps its own ID and backing column, so attaching or detaching a shared property never breaks a client

sharedProperty:
  id: storageLocation
  displayName: Location
  description: Site, area and bay of a cold asset, as JSON: {site, area, bay}
  baseType: struct
  indexing: [fullText]

# Attached on three types, each with its own column
# silo.storageLocation       ← storageLocation
# equipment.storageLocation  ← storageLocation
# shop.storageLocation       ← storageLocation

While attached, inherited metadata is locked on the local property; change it on the shared property and the change reaches every user in the same proposal. Index and display options merge, with the shared property's taking precedence. The shared property's page lists every type and interface that uses it, which is also the fastest way to answer "where in the ontology do we store cold asset locations"

Use a shared property when the same fact is recorded on several types and must mean the same thing everywhere: temperatures, setpoints, storage locations, site codes. Use an interface when you also want to query those types together or write tools that work across them. Interface properties can themselves be shared properties, in which case types that already use the shared property map to the interface automatically

Evolving interfaces safely

Every implementer and every consumer depends on an interface's shape, so some changes are breaking. Proposal checks classify each change and list the types, functions, apps and agent tools affected

ChangeEffectHow to make it
Add an optional property, link or actionNon-breakingDirectly in a proposal
Change a description or display nameNon-breakingDirectly
Add a required memberBreaking for implementersMap it on every implementer in the same proposal, or add it as optional first
Change a member's typeBreaking for implementers and consumersAdd a new member, migrate, then deprecate the old one
Remove a memberBreaking for consumersDeprecate it, wait for the deadline, then remove
Remove an implementation from a typeBreaking for consumers that expect that type's objectsProposal with owner approval from the interface and the type

When a change is too large to make in place, create a new interface that extends the old one with the new members, move implementers to it one at a time, then deprecate the old one. Generated SDKs mark deprecated interface members, and calls through them return a deprecation header until they are removed

Limitations

  • Interfaces hold no data and cannot be instantiated. There is no interface primary key, and every object returned keeps its own type, key and security
  • Extension chains are limited to 5 levels and cycles are rejected
  • A derived property mapped to an interface property is read-only through the interface, so it cannot satisfy a property that a required action of the interface writes
  • An array can satisfy a single-value interface property only through a display rollup, and rolled-up values cannot be filtered on through the interface
  • Queries through an interface fan out to every implementing type. An interface set for full-text search allows at most 100 implementing types, and the slowest implementing type sets the query's latency
  • Adding a required member, changing a member's type or removing a member is breaking and cannot be done in place without migrating every implementer or consumer

Related