Computed attributes
A computed attribute is a customer attribute whose values no one writes: the
platform derives each guest’s value from that guest’s bookings, following the
definition’s rule. Every definition read carries it as computed, which is
null on an attribute whose values are entered.
From an idea to a value you can act on takes five steps, each covered below:
- Describe it, optionally.
POST /definitions/proposalsturns a plain description into a rule, or points at a built-in that already answers it (Proposals). - Create it with
POST /definitionsand acomputedrule, or switch a built-in on withPATCH /definitions/customer/{key}and{"enabled": true}. Either answers202, withcomputed.statereadingcomputing(Rules, Catalogue). - Wait for it to settle. Subscribe to
definition.computed(Webhook), or pollGET /definitions/customer/{key}untilcomputed.stateisready(Where computing stands). - Read the values on the guest, as any other attribute (Reading values).
- Use them in segments and in customer lists filtered and sorted by them,
both of which answer
409 segment-pendinguntil the attribute settles (Settling, Lists).
Authoring takes definitions:write, and reading definitions
definitions:read, as for every other definition.
A rule names which of a guest’s bookings count and the one operation that
turns them into a value. POST /definitions takes it as computed:
{ "entity": "customer", "key": "visits_12m_oslo", "label": "Visits in Oslo, last 12 months", "category": "visits", "computed": { "operation": "count", "bookings": { "status_class": "completed", "window": { "type": "last_days", "days": 365 }, "filters": [ { "field": "restaurant_id", "operator": "in", "value": ["0198a5b0-5e00-7a10-8b20-00000000000a"] } ] } }}The answer is 202 rather than 201: the definition exists, its Location
points at /definitions/customer/visits_12m_oslo, and its values are still
being computed (see Where computing stands).
bookings selects the bookings, every member AND-ed with the others:
status_class—completed,no_show,cancelledorupcoming, the outcome classes a segment’s booking conditions use, ornull(or absent) for bookings of every status.window— by booking start time:{"type": "all_time"}, orlast_days/next_dayswithdaysfrom 1 to 36500. Upcoming bookings take nolast_dayswindow.filters— narrowings: the tenant’s own restaurants ({"field": "restaurant_id", "operator": "in", "value": [...]}), the party size ({"field": "guest_count", ...}with a comparison orbetween), or a live booking attribute ({"attribute_key": ...}with anoperatorand avalue) under the operators itsdata_typetakes in a segment’s booking filter. TheComputedRulecomponent in the API reference states how many and the bounds of each.
operation turns the selected bookings into one value, and decides the
attribute’s data_type:
operation | The value | data_type |
|---|---|---|
count | how many bookings match | number |
distinct_restaurants | how many restaurants the matching bookings are at | number |
sum, avg, max, min | the aggregate of measure over the matching bookings | number |
first, latest | the start time of the earliest or the latest matching booking | datetime |
share | the percentage, 0 to 100, of the guest’s decided bookings that are in status_class | number |
measure is what sum, avg, max and min aggregate, and only they take
it: the party size ({"field": "guest_count"}) or a live number booking
attribute ({"attribute_key": "spend"}), whose display_hint the computed
attribute borrows. A share divides by the bookings that were decided —
completed, no-show or cancelled — inside the same window and filters, so its
status_class is one of those three, and its display_hint is percent.
typical_interval_days and lifecycle_stage appear on Nine Tables built-ins
only.
A guest whose bookings exist but none of which match holds 0 on a count;
on every other operation a guest holds no value until a booking matches, and
the attribute reads as unset for them, in segments as everywhere else.
What the rule decides, and what it refuses
Section titled “What the rule decides, and what it refuses”The rule decides data_type, display_hint and options, so a body with
computed leaves all three out. A computed attribute describes a guest, so
entity is customer, and its values are never written by anyone:
ui_writable and api_writable are false, a body setting either to true
is refused, and a value written to it answers not_api_writable with the
detail computed from bookings. Its values carry source: "computed",
where a built-in’s carry system.
A rule is checked twice. Its shape is the published schema, so an unknown
member, a misspelt one or a days out of range is schema_invalid. What
relates one member to another is the platform’s: a measure on an operation
that takes none, a share over upcoming, a restaurant that is not the
tenant’s or a booking attribute that is archived or unknown is
invalid_value keyed computed, its detail saying which. A tenant holds a
limited number of live computed attributes of its own (computed_cap), and a
key in the catalogue is reserved (see Catalogue). Every code is
in Field error codes.
Changing a rule
Section titled “Changing a rule”PATCH /definitions/customer/{key} with a new computed replaces the rule
and recomputes every guest, answering 202 with computed.state reading
computing. The rule it already holds, sent again in any spelling, changes
nothing and answers 200. The new rule must compute the same data_type, which is
immutable (computed_type_mismatch); for another type, create another
definition. display_hint and options follow the rule, so they are not sent
beside it. A rule cannot be given to an attribute whose values are entered, nor
changed on a built-in (system_locked). Every other member, label and the
display settings included, is edited as on any definition, and a computed
attribute is archived and restored as one too (see
Archive, never delete);
restoring it puts it back on a pass, answering 202.
An edit that moves guests across a segment’s rules does not announce them: segment webhook events resume from the membership the new rule produces (see Webhook).
Where computing stands
Section titled “Where computing stands”computed carries the rule beside the state of its values:
state—computingwhile the platform fills values in,readyonce every guest holds a current one,failedwhen computing kept failing. It is always the definition’scompute_state, andnullon a built-in that is off.progress—{processed, total}, the guests computed so far out of those the run set out to compute, present only whilestateiscomputing.computed_at— when the last computation finished andstatebecameready, ornullwhile none has.error— why computing last failed,nullonce a computation succeeds.
An attribute is computing after it is created, after its rule changes, after
a built-in is switched on and during a recompute. An attribute
put on the pass while another is computing joins the pass already running
over the tenant’s guests rather than starting one of its own, so several
created close together cost about one pass, not one each.
Once ready, values follow bookings without returning the attribute to
computing: a booking write queues its guest, the platform recomputes that
guest’s attributes shortly after, and windows that roll with the date are
moved forward by a daily sweep. computed_at does not move for either.
Settling
Section titled “Settling”While an attribute is computing or failed, its values are not an answer:
a guest’s value may be from before the change, or not there yet. So what reads
it says so instead of answering:
- each computed value read from a guest carries
statebesidevalue, and itsupdated_atis when the platform last computed it; - a dynamic segment whose rules read the attribute answers its count and its
member pages with
409 segment-pending(see Dynamic and fixed segments); - a customer list filtered or sorted by it answers the same (see Lists).
{ "type": "https://ninetables.io/problems/segment-pending", "title": "Segment Pending", "status": 409, "detail": "This request reads computed attributes whose values are not settled yet (visits_12m_oslo), so it is not answered until they are. Each one’s `compute_state` on GET /definitions says where it stands.", "code": "SEGMENT_PENDING", "pending_attributes": [ "visits_12m_oslo" ]}pending_attributes names the attributes the request waits on, and
Retry-After how many seconds to wait before asking again. A computing
attribute settles by itself; a failed one does not, so read its
computed.error and recompute it rather than retrying the read.
Rather than poll, wait for definition.computed and then read.
Catalogue
Section titled “Catalogue”The attributes Nine Tables defines (source: "system") are a catalogue, every
entry off until the tenant switches it on, so a built-in nobody uses costs
nothing. GET /definitions leaves the switched-off ones out unless
include_disabled=true, which lists them with enabled: false;
GET /definitions/{entity}/{key} reads one whether it is on or off, its rule
included, so computed shows exactly what a built-in counts.
PATCH /definitions/customer/{key} with {"enabled": true} switches one on:
it answers 202, computing, and its values arrive as any computed attribute’s
do. {"enabled": false} switches it off and its values go, refused with
409 conflict-definition-in-use while a dynamic segment reads it. enabled is
sent alone, and only a built-in takes it (not_catalogue on your own). A
built-in’s meaning, its rule included, belongs to Nine Tables, while where it
appears is yours while it is on: switching it off files it back in the system
category, where switching it on again leaves it, and a switched-off built-in
cannot be moved to another category (see
System attributes are computed).
Every catalogue key is reserved, whether the built-in is on or off. A
POST /definitions naming one answers 409 conflict-reserved-key, naming the
built-in to switch on instead:
{ "type": "https://ninetables.io/problems/conflict-reserved-key", "title": "Conflict", "status": 409, "detail": "'total_visits' is a Nine Tables attribute in the catalogue — turn it on with PATCH /definitions/customer/total_visits {\"enabled\": true} instead of creating it", "code": "CONFLICT_RESERVED_KEY"}Six built-ins read the loyalty club rather than bookings: loyalty_member,
loyalty_tier, loyalty_visits_period, loyalty_member_since,
loyalty_joined_via and loyalty_join_source. The catalogue holds them only
for a tenant with the loyalty club app, and switching one on without the app
answers 409 loyalty-not-installed. loyalty_tier is the tier’s name, or for
a tier with no name its threshold followed by + (3+ for a tier reached at
3 visits), the same in every language.
To count something close to a built-in but not the same, read the built-in’s
computed, change what differs, and create it under a key of your own.
Recompute
Section titled “Recompute”POST /definitions/customer/{key}/recompute computes one attribute again for
every guest and answers 202 with computed.state: "computing". Values keep
up with bookings and the passing days by themselves, so a recompute is for
when they did not: a failed attribute, once the cause in its
computed.error is fixed, or values you have reason to distrust. It works on
any computed attribute in use: your own, or a built-in that is switched on.
An entered attribute, an archived one or a built-in that is off answers
400 validation-failed.
A recompute puts the attribute back to computing, so its computed_at is
null and what reads it answers segment-pending until it is ready again
(see Settling), and its end sends definition.computed. A request
while the attribute is already computing joins that run and restarts nothing,
and the route takes an Idempotency-Key (see
Idempotency).
Recomputing needs a key that reaches every restaurant: a
key limited to restaurants
answers 403 tenant-wide-key-required, which no retry with that key changes.
Proposals
Section titled “Proposals”POST /definitions/proposals with {"description": "..."} turns a plain
description of something to know about guests into a proposal, and creates
nothing. Nine AI reads the description against the
tenant’s restaurants and booking attributes and answers one of three kinds,
with a one-sentence sentence saying what would be tracked, in the
description’s language:
computed— a rule the platform has validated, ascomputed.rule, with thedata_typeanddisplay_hintit produces, itscoverage(how many live guests the rule matches today, where acountof 0 is no match, out of how many live guests; the demo guests a trial tenant is seeded with are left out) and three example guests with their values: the matching guests holding the lowest, the median and the highest value, in that order, fewer when fewer guests match, so acountof 0 is never an example. Send the rule ascomputedonPOST /definitions, as it stands or adjusted.catalogue— a built-in already answers the description.cataloguenames it and says whether it isenabled; switch it on rather than create it.entered— the answer is not in the bookings, so it is an attribute your team or your integration fills in, with thedata_type(andoptionsordisplay_hint) to create it with.
An ambiguous description is given its most likely reading rather than a
question back; adjust the rule before creating it. Coverage and the examples
are measured on the tenant’s guests as they are now and stored nowhere; when
measuring takes too long, coverage is null and examples is [], and the
rule is still valid. An
example guest’s contact members appear only when the key holds
contacts:read. examples is listed only for a key that also holds
customers:read and attributes:read; otherwise it is []. A key limited to restaurants is shown, and proposed, only its
own restaurants.
Each call asks Nine AI afresh and is billed to the tenant’s AI credits only
when it answers 200. A tenant whose credits do not cover a proposal answers
402 insufficient-ai-credits before Nine AI is asked; an owner tops the
credits up in the Nine Tables app. 502 upstream-unavailable means Nine AI
was unreachable or answered twice with nothing usable: nothing was charged, and
the same request may be retried. A proposal costs more of your
rate limit than one token; the operation’s description
in the API reference states how many.
Webhook
Section titled “Webhook”definition.computed is the signal that values have settled. Add it to a
subscription’s events (it needs definitions:read beside
webhooks:manage), and every time a computation of a computed attribute
(after it is created, switched on, given a new rule or recomputed)
finishes, the subscription receives one delivery naming the
attribute by entity and key, its state (ready or failed), how many
guests hold a value as guest_count, and computed_at. The full body and
its members are in
Definition events.
Computed values raise no customer.updated and do not move the
updated_since change feed, so a first computation over every guest reads as
one event rather than one per guest. On ready, read the values back; on
failed, read the definition’s computed.error. Values that move afterwards,
as bookings change, send no further event.
Segment events stay the per-guest signal, and a computation never sends them guest by guest: a segment reading an attribute that has not settled is left out of the membership sample, and a rule edit moves its members without an event (see When segment events start).
GET /customers and GET /segments/{id}/customers can be filtered and
ordered by attribute values, computed or entered alike. Both parameters read
those values, since a filter tells you which guests hold one and a sorted
page’s next_cursor carries the last row’s, so either needs attributes:read
on top of the route’s own scope; without it the request answers
403 insufficient-scope naming attributes:read.
filter— repeatable, up to 5, AND-ed:<definition_key>:<operator>:<value>, one segment attribute condition written into a query parameter, under the same operators a segment rule takes for the attribute’sdata_type. A list operator (in,between, …) takes a comma list, so each value is percent-encoded inside the parameter (a comma as%2C, a%as%25) before the parameter itself is URL-encoded: a comma inside a value travels as%252C, whichURLSearchParams.append("filter", "loyalty_tier:in:gold,silver%2Cplus")produces for you. An operator that takes no value (is_set,is_true, …) is written without one:filter=visits_12m_oslo:gte:3&filter=loyalty_tier:in:gold,silver.sort— one attribute,<definition_key>ascending or-<definition_key>descending. Ties, and the guests with no value (who come last in either direction), are ordered by customer id. Amulti_selector acounter_listhas no order and is refused.
Pages are keyset-paged, so a page is stable while you walk them: pass
next_cursor back with the same filter and sort. Neither combines with
updated_since, which lists in change order, and a fixed segment’s member
pages, which serve a frozen list, refuse both; each answers
400 validation-failed naming the parameters sent. A filter or a sort on a
computed attribute that has not settled answers 409 segment-pending (see
Settling), because the attribute would read as unset and the page
would pass for a real answer.