Skip to content

M2-S3 — The data model and its contracts

Section titled “M2-S3 — The data model and its contracts”
ModuleM2 — The platform’s architecture and contracts
After this session you canRead a definition and a record as the platform stores them, map a builder change onto them, and say which values are a wire contract that must never be renumbered.
TimeFacilitated: 60 min · On your own: 60 min
Before you startM2-S2: you have read a record-updated event. Larkspur Lab with the API and record-store windows (workbench).
Go deeperReference: core entities · Reference: enums · Field configuration reference

◆ Orientation (1 min) — What a builder’s click becomes

Section titled “◆ Orientation (1 min) — What a builder’s click becomes”

When Omar Haddad adds a field to Work Orders, he fills a dialog. When a technician saves a work order, she fills a form. Both end as documents in MongoDB, and every engine you open from here on reads those documents: the query engine compiles filters against the definition’s fields, the workflow engine stores its state inside the record, the reaction engine receives the record in its events, the package contract carries the definitions between environments. Knowing their shape is what lets you predict what a change will do before a builder makes it. That is the master’s job in the change control you wrote in M1-S2: Class B changes are changes to these shapes.

▤ Concept (12 min) — Definitions, records, and the values that must not move

Section titled “▤ Concept (12 min) — Definitions, records, and the values that must not move”

The platform keeps two kinds of document, and the whole model turns on keeping them apart.

  • The definition layer describes what was built: modules, entities and their fields, relations, queries, views, pages, reactions, and the entry-based resources (reports, buttons, counters, Functions, statistic queries). Each is a document in a fixed meta-model collection, named after its class: DataModule, DataEntity, DataRelation, DataQuery and so on.
  • The record layer holds what people entered. Every record of every entity, built-in or custom, is stored in one universal envelope, the DataEntry. Its dataEntity field says which entity it belongs to, and its value holds the fields.

There is no fixed “work orders” table in the code. When Omar created Work Orders, the platform created a definition and, from then on, stored its records in a collection named after the entity’s normalized name, work_orders. The data service builds a repository for that collection at run time (M2-S1’s factory). That is how a no-code platform gives a new entity storage the moment it is saved, with no deployment. It is also why many things that look like features are records: a space, a holiday, a language, a notification, a dashboard, a user, each a DataEntry whose value is shaped by a definition the platform ships.

flowchart LR
  subgraph DEF["Definition layer (meta-model collections)"]
    M["DataModule<br/>asset_maintenance"]
    E["DataEntity<br/>work_orders<br/>fields, workflows, indexes"]
    R["DataRelation<br/>work_orders.asset to assets"]
  end
  subgraph REC["Record layer (one collection per entity)"]
    W1["DataEntry in work_orders<br/>dataEntity, value, state"]
    A1["DataEntry in assets"]
  end
  E -->|"module"| M
  W1 -->|"dataEntity"| E
  W1 -->|"value.asset = {dataEntity, dataEntry}"| A1
  R --- E

What to notice: the record does not copy its definition; it points at it. A change to the definition therefore changes how every existing record is read, which is why some changes are breaking.

A few small shapes recur everywhere, and once you know them you can read any document.

BlockShapeWhat it means
Reference{ dataEntity, dataEntry }A pointer to one record of an entity. Every link is one: a reference field, a workflow step’s owner, who did something, which store a record belongs to.
Audit stamp{ doneAt, doneBy, delegatee? }When and by whom; doneBy is itself a reference to a user record. Used for creationInfo, updateInfo, archiveInfo. The platform’s own actor has the all-zero id.
Localized value{ en, ar }Any name or text kept per language
Normalized namework_orders, planned_dateThe stable, machine name of a definition or field. Labels change; normalized names should not.
Two version numbersspecificationVersion, versionspecificationVersion is the version of the document’s shape (today 1); an entity’s version is a counter of breaking changes the tenant made to it.
Change tokenupdateIdentifierM2-S1’s optimistic-concurrency token

A stored record looks like this (shortened; the work order you will read in the lab):

{
"id": "3f9c…",
"dataEntity": "a71e…",
"entityVersion": 3,
"specificationVersion": 1,
"state": 1,
"value": {
"title": "Replace mechanical seal on P-101",
"asset": { "dataEntity": "c02b…", "dataEntry": "88d1…" },
"asset_title": "Feed pump P-101",
"priority": { "id": "opt-high" },
"estimated_hours": "4",
"_metaCurrentSteps": [ … ],
"_metaWorkflowHistory": [ … ]
},
"lifeCycleStatus": 0,
"store": { "dataEntity": "…", "dataEntry": "…" },
"searchIndex": { … },
"isInvalid": false,
"creationInfo": { "doneAt": "…", "doneBy": { "dataEntity": "USER", "dataEntry": "…" } },
"updateInfo": { "doneAt": "…", "doneBy": { … } },
"updateIdentifier": "…"
}
  • dataEntity says which entity this is; entityVersion says which version of that entity’s structure the record was written against.
  • value holds the fields by normalized name, each in its stored form (next section).
  • state is the record’s lifecycle state: 0 draft, 1 active, 2 archived, with a stateHistory of transitions. lifeCycleStatus is separate: it tracks a record in a workflow (0 active, 1 completed, -1 failed) and is absent when there is no workflow.
  • The workflow’s runtime state lives inside value, under reserved keys: the current steps (_metaCurrentSteps), the history of every step taken (_metaWorkflowHistory), ad-hoc steps and relations. Anything that rewrites value wholesale must keep them, a rule you meet again in migrations (M2-S4) and in the workflow engine (M4-S3).
  • store names the store the record belongs to (M2-S4); searchIndex is a denormalised copy for full-text search (M3-S4).
  • isInvalid with invalidReason marks a record that fails the current definition without deleting it: reason 0 (Obsolete) after a breaking change, 1 (Invalid) otherwise.

Fields: what a builder chose, and what is stored

Section titled “Fields: what a builder chose, and what is stored”

A field definition in the entity’s fields list has a storage type (dataType) and an edit component (renderOptions), and the two together make the field kind a builder picked. The storage types are few: text, number, date, time, date-time, boolean, files (blob), entity reference, icon, block, localized text, map (GeoJSON), JSON. Many kinds share one: Text, Long text, Password and Phone are all stored as text and differ only in their component. On save, each value is converted towards its storage type by a caster registered for that type (M2-S1’s booters again); a type with no caster passes its value through.

Field kind (designer)Stored asIn value
Reference, Userentity reference{ dataEntity, dataEntry }
CategoryJSON{ id } of the chosen option, or an array of them when Multiple is on
Mapped Fieldthe source field’s typea copy of the source value, refreshed by its update mode
Blockblockan object (or array, when repeatable) of the block’s own fields
Number, Sequence Fieldnumbera number

Two kinds need a closer look because they are seams in disguise.

  • A relation is recorded twice: the reference field’s value in each record, and a DataRelation definition naming the source entity, the target entity and the field that carries it. The definition is what lets lists, queries and search follow the link (M3).
  • A mapped field copies a value from a referenced record, such as the asset’s name onto each work order as Asset Title. It is a real copy, stored in the record, kept current by the data service when the source changes (one of the consumers of record events you met in M2-S2). Its update mode decides how: Local Update (copied, then editable here), Never (copied once), From Parent Only (follows the source, locked here) or 2 way (written in both directions). A category’s options are records of an internal collection kept per entity; the record stores the option’s id, never its label.

Changing a definition: versions and obsolete records

Section titled “Changing a definition: versions and obsolete records”

Most changes to an entity are safe for existing records: adding an optional field, changing a label, deleting a field. A breaking change is one that existing records may not satisfy: changing a field’s type, making a field required or unique, turning Repeatable or Multiple on or off, changing the workflow’s steps, turning encryption on or off. When one is saved on an entity that has records, the platform:

  1. increments the entity’s version and records which fields broke and why;
  2. publishes an entity-updated event (and a version-changed one), so every consumer refreshes;
  3. leaves every existing record as it was, now behind: its entityVersion is lower than the entity’s version, and it is marked Obsolete (isInvalid: true, reason 0);
  4. waits for someone to upgrade the records, which rewrites each one to the current version, choosing per field a fixed value, an expression, the default, nothing, or Auto Repair, which runs the new type’s caster over the old value.

Builders met this as the Confirm Structure Changes dialog and the Obsolete entries filter in ACD. What the master adds is the prediction: which records will become obsolete, which old values the caster can convert and which it cannot, and which automation will stall because an obsolete record cannot move on in its workflow until it is upgraded.

Look again at the record: state: 1, lifeCycleStatus: 0, dataType: 2. Most of the platform’s enumerations are numeric enums in TypeScript: the code reads a name (Active, Date), but the number is what is stored in MongoDB and sent over the wire. The same enumerations are mirrored in the web application and the mobile app, which must agree on every number. That makes each number a contract between the database, the services and both front ends, and gives you the master’s rules:

  • Never renumber. Changing Date from 2 to 3 silently turns every stored date field into a time field. Existing data is not migrated by renaming an enum member; it is reinterpreted.
  • Append, with an explicit number. A new member goes at the end, or into a range kept for its family, with = n written out. Members without explicit numbers are counted from the previous one, so inserting one in the middle shifts every number after it.
  • Gaps are deliberate. Several enums reserve ranges (the reaction action types group entity, record, workflow, user and integration actions in separate ranges). Filling a gap casually takes a number that a family was meant to grow into.
  • Read the type. A few enums are not plain integers: the access levels use fractions so that Restricted and Developer sit between whole levels (-1, -0.5, 0, 0.5, 1, 2), and some link enums store the strings '0' to '4', so comparing them with a number never matches.
  • A change is three changes. Back end, web and mobile must ship the same number together. On mobile, Dart’s exhaustive switches (M0-S1) turn a missing case into a build error, which is the safety net; on the web, a missing value is simply not drawn.

The same idea applies one level up, to what builders create. A category option is stored by its id; delete Urgent and create a new Urgent, and every old work order points at an option that no longer exists, while every report grouped by priority splits in two. A normalized name is bound by queries, reactions, proxies and packages (M1-S1). In both cases the label is free to change and the identifier is not.

▶ Guided demo (8 min) — One definition, one record

Section titled “▶ Guided demo (8 min) — One definition, one record”

In Larkspur Lab, with the API and record-store windows open.

  1. Read the Work Orders definition through the API, keeping only what matters:

    Terminal window
    curl -s -H "x-app-token: $TOKEN" "$BASE/api/v1/entities/work_orders" | jq '.result |
    {normalizedName, version, type, fields: [.fields[] | {normalizedName, dataType,
    component: .renderOptions.editComponent.component, title: .options.showAsTitle}],
    workflows: [.workflows[]?.name.en]}'

    You see the fields with their storage types and components, version, and one workflow.

  2. Find the same definition in the record store: db.DataEntity.findOne({normalizedName: "work_orders"}, {normalizedName:1, version:1, "fields.normalizedName":1}). It is the same document the API returned, before the send step wrapped it.

  3. Read one record: db.work_orders.findOne({"value.title": /P-101/}). Point at dataEntity (the definition’s id), entityVersion (equal to the entity’s version), state, the reference in value.asset, the copied value.asset_title, the category {id} in value.priority, and the workflow keys under value.

  4. Follow the reference by hand: take value.asset.dataEntry and read db.assets.findOne({id: "<that id>"}, {"value.asset_name":1}). The name matches Asset Title.

  5. Open the same work order in the portal and compare: every label on the screen is a normalized name in value, translated by the definition.

    Screenshot pending A work order open in the portal beside its stored document in mongosh, with Asset Title and Priority highlighted in both What to notice: the screen shows “High”; the record stores an option id. The label lives in the definition, so renaming it changes no record.

PracticeChoose one answer.

You open a stored work order and find "entityVersion": 2, while the Work Orders definition says "version": 3. What do you expect to see on that record?

  1. Explanation for A

    ✓ Correct

    Correct: a breaking change raised the entity’s version, and records written against the older one stay obsolete until upgraded. See Changing a definition.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a breaking change leaves existing records as they are; an upgrade rewrites them. See Changing a definition.

  3. Explanation for C

    ✗ Incorrect

    Not this one: lagging records stay active and are marked, not archived. See The record envelope.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

A supplier is renamed in Supplier Management. Spare parts show the supplier’s name through a mapped field set to From Parent Only. What happens to the stored spare-part records?

  1. Explanation for A

    ✗ Incorrect

    Not this one: a mapped field is a real copy kept in each record. See Fields.

  2. Explanation for B

    ✓ Correct

    Correct: From Parent Only follows the source, and the copy is refreshed from the record event. See Fields.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a value changing in a source record is not a change of structure. See Changing a definition.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A builder deletes the category option Urgent from Priority and creates a new one with the same label and colour. What happens to the work orders that were Urgent?

  1. Explanation for A

    ✗ Incorrect

    Not this one: records store the option’s id, and the new option has a new id. See Values that are a wire contract.

  2. Explanation for B

    ✗ Incorrect

    Not this one: deleting an option is not a breaking change and nothing re-points the old ids. See Changing a definition.

  3. Explanation for C

    ✓ Correct

    Correct: the identifier is the contract; the label is presentation. See Values that are a wire contract.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

⛏ Lab (25 min) — Audit Work Orders and predict a type change

Section titled “⛏ Lab (25 min) — Audit Work Orders and predict a type change”

Goal. An audit of the Work Orders definition and three of its records, read-only, followed by a prediction of what changing Estimated Hours from text to number will do, and its proof.

Before you start. Larkspur Lab; the API and record-store windows; Rami Aziz in the portal. A file m2-s3-audit.md. Part C changes the lab suite; the seed’s --reset restores it.

Part A: the definition

  1. Save the Work Orders definition (demo step 1, without the jq filter) as work_orders.json.
  2. List every field with its normalized name, storage type number, component and, for references, the target entity. Mark the field shown as the title.
  3. Find the relation definitions for Work Orders: db.DataRelation.find({targetField: {$in: ["asset", "raised_by_plan"]}}, {normalizedName:1, targetField:1, relationType:1}).
  4. Find the mapped field Asset Title and write down its source and its update mode.

Part B: three records

  1. Read three records from work_orders: Replace mechanical seal on P-101, Inspect bearing noise on C-201 and Lubricate bearings on P-102.
  2. For each, record: state, lifeCycleStatus, entityVersion, the current step from value._metaCurrentSteps, the stored form of Priority and Estimated Hours, and who last updated it.
  3. Compare Asset Title in each record with the name of the asset its reference points at.

Part C: predict, then prove, a type change

  1. Write your prediction for this change: Estimated Hours changes from Text to Number. Say: is it breaking; what happens to the entity’s version; which records become obsolete; what Auto Repair will make of the stored values "4", "2.5" and "half a day".

  2. In the portal, open Asset Maintenance › Work Orders, edit the entity, change Estimated Hours to Number and select Save. Read the Confirm Structure Changes dialog, then select Save.

    Screenshot pending The Confirm Structure Changes dialog for Work Orders, listing Estimated Hours with the reason Field type changed What to notice: the dialog names the field and the breaking reason; saving creates a new version of the entity and makes every existing work order obsolete.

  3. Read the entity’s version again, and one record’s entityVersion, isInvalid and invalidReason.

  4. On the entity’s Entries tab, filter to Obsolete entries, select all, and select Upgrade (Entries N). Choose Auto Repair for Estimated Hours and select Upgrade.

Screenshot pending The upgrade dialog for obsolete work orders, with Estimated Hours under Required changes and Auto Repair selected What to notice: Auto Repair keeps each record’s value and converts it to the new type; a value the conversion cannot handle is where the upgrade reports a problem.

  1. Read the three records’ Estimated Hours in the record store, and note any record that failed to upgrade.
  2. Compare with your prediction, and write one line on what you would have told Omar before he made this change in production.

Check.

  • Part A lists every field with storage type and component, the relation definitions, and the mapped field’s source and mode.
  • Part B gives the six facts for each of the three records.
  • Your prediction was written before step 9.
  • Step 10 shows the entity’s version raised by one and the records marked obsolete.
  • Step 12 shows each record’s new stored value, or its failure.
  • Your closing line names the records whose value could not be converted.

Pass condition. All six checks hold.

If something goes wrong

What you seeWhat to do
GET /api/v1/entities/work_orders answers 404Use the entity’s id instead: find it with db.DataEntity.findOne({normalizedName:"work_orders"},{id:1}).
db.work_orders.findOne returns nullCheck the database (lk-data) and the title; list a few with db.work_orders.find({}, {"value.title":1}).limit(5).
No Confirm Structure Changes dialog appearsThe field was already a number in your lab, or the entity has no records. Run the seed’s --reset and start Part C again.
Upgrade is not offeredFilter the list to Obsolete entries first; only obsolete records can be upgraded.
A record fails with Workflow reset requiredYou changed more than the field type. Reset the seed and repeat Part C with only the type change.
Model answer

Part A. Fields (storage type in brackets): title (0, text, shown as title), asset (7, reference to assets), asset_title (mapped field from the asset’s asset_name, mode From Parent Only, locked), priority (12, JSON, category component), description (0, text, long-text component), planned_date (2, date), estimated_hours (0, text), raised_by_plan (7, reference to maintenance_plans), technician (7, user). Two relation definitions, outgoing, on asset and raised_by_plan. One workflow: Raised, Planned, In Progress, Completed.

Part B. All three: state: 1, lifeCycleStatus: 0 (in their workflow), entityVersion equal to the entity’s version. Current steps: Planned, Raised, Planned (if you moved P-102 in M2-S2). Priority stored as { "id": "…" }; Estimated Hours as the strings "4", "2.5" and "half a day". Last updated by Rami Aziz for the two you changed in M2-S1 and M2-S2, by the seed’s operator account otherwise. Asset Title equals the referenced asset’s name in each.

Part C, the prediction and the result. A type change is breaking: the entity’s version rises by one, and every existing record becomes obsolete (isInvalid: true, invalidReason: 0), with its entityVersion one behind. Auto Repair runs the number caster over each old value: "4" becomes 4, "2.5" becomes 2.5, and "half a day" cannot be converted, so that record either fails to upgrade or upgrades with the field empty, depending on the field’s validation.

Until they are upgraded, the obsolete work orders cannot move on in their workflow, so the nightly plan’s new work orders flow but existing ones stall. What to tell Omar: “Change the type, but first fix the text values a number cannot hold, and plan the upgrade in the same window; otherwise open work orders stop moving.”

◇ Worked scenario (3 min) — The tidy enum

Section titled “◇ Worked scenario (3 min) — The tidy enum”

A partner team building a mobile companion app for Larkspur’s technicians sends you a pull request against their copy of the platform’s shared enumerations, “to tidy things up”. It does three things. Decide on each before you read on.

Change 1: the access levels become whole numbers. They replace -1, -0.5, 0, 0.5, 1, 2 with 0 to 5, because “fractions look like a mistake”. Decide. Refuse. The numbers are stored on every grant, and the engine compares levels numerically to find the highest grant a person holds (M5-S2). Renumbered, every stored grant means something else: a stored 0 (View) would read as None. The fractions are not a mistake; they are how Restricted and Developer were slotted between existing levels without moving them.

Change 2: a new field type, Meter reading, inserted after Number. Decide. Refuse the position, not the idea. Inserted after Number = 1, it takes 2, and every member after it moves up by one: every stored date field would read as the new type. If the platform ever gains such a type, it is appended at the end with an explicit number, and the same number ships in the back end, the web and the mobile app in one release. (You will see exactly this as a source-strand recipe in M8-S2.)

Change 3: the link-type comparison becomes if (link.type === 1). Decide. Refuse, with a different reason: those enums store strings, '1', so the comparison is never true, and the app would silently treat every link as the default kind. Compare with the enum’s own member.

The outcome. None of the three is a bug today, and all three would have shipped as silent data corruption. Your review comment fits in one sentence per change, each naming the stored value it would reinterpret. That is what “a wire contract” means in practice.

✓ Practice (6 min) — Predict the change

Section titled “✓ Practice (6 min) — Predict the change”
PracticeChoose one answer.

Which of these changes to Work Orders, which holds 900 records, creates a new version of the entity?

  1. Explanation for A

    ✓ Correct

    Correct: existing records may lack a value, so they no longer satisfy the structure and become obsolete. See Changing a definition.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a label change leaves every stored value valid, so no version is created. See Changing a definition.

  3. Explanation for C

    ✗ Incorrect

    Not this one: old records simply have it empty, which the new structure allows. See Changing a definition.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

A teammate looks for the code class that stores Larkspur’s Assets, to add a database index. What do you tell them?

  1. Explanation for A

    ✗ Incorrect

    Not this one: there is no repository per entity; a factory builds one at run time. See Two layers.

  2. Explanation for B

    ✓ Correct

    Correct: records of every entity share one envelope, stored in a collection named after the entity, and the definition carries its indexes. See Two layers.

  3. Explanation for C

    ✗ Incorrect

    Not this one: no code is generated for an entity, at deployment or at any other time. See Two layers.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A work order’s stored document shows "state": 2 and "lifeCycleStatus": 0. What is it?

  1. Explanation for A

    ✗ Incorrect

    Not this one: a draft is state 0, and a failed workflow is life-cycle status -1. See The record envelope.

  2. Explanation for B

    ✗ Incorrect

    Not this one: active is state 1, and a completed workflow is life-cycle status 1. See The record envelope.

  3. Explanation for C

    ✓ Correct

    Correct: state 2 is archived, and life-cycle status 0 means its workflow was still active. See The record envelope.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A list of work orders can be filtered by the asset’s site, through the reference. What makes that filter possible?

  1. Explanation for A

    ✓ Correct

    Correct: the relation is recorded as a definition as well as in each record’s value. See Fields.

  2. Explanation for B

    ✗ Incorrect

    Not this one: nothing is copied for a filter; the engine follows the link (M3-S2). See Fields.

  3. Explanation for C

    ✗ Incorrect

    Not this one: to the database it is just an object; the platform’s definitions carry the meaning. See Fields.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

Two fields, Notes and Technician Phone, look different in the portal but share one storage type. How does the platform tell them apart?

  1. Explanation for A

    ✗ Incorrect

    Not this one: normalized names are chosen by the builder and carry no kind. See Fields.

  2. Explanation for B

    ✓ Correct

    Correct: the field kind is the storage type plus the component, and many kinds share text. See Fields.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the kind is part of the definition, not guessed from data. See Fields.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

↺ Recap (1 min) — The shapes every engine reads

Section titled “↺ Recap (1 min) — The shapes every engine reads”

You can now read a definition and a record as stored, explain how references, mapped fields and categories are kept, predict what a breaking change does to existing records and their workflows, and refuse a change that would renumber a stored value.

Next. M2-S4 follows these documents down to where they physically live: the databases, the stores that decide which space sees which records, the files beside them, and the migrations that change all of it when the platform is upgraded.