M2-S3 — The data model and its contracts
Section titled “M2-S3 — The data model and its contracts”| Module | M2 — The platform’s architecture and contracts |
| After this session you can | Read 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. |
| Time | Facilitated: 60 min · On your own: 60 min |
| Before you start | M2-S2: you have read a record-updated event. Larkspur Lab with the API and record-store windows (workbench). |
| Go deeper | Reference: 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”Two layers
Section titled “Two layers”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,DataQueryand 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. ItsdataEntityfield says which entity it belongs to, and itsvalueholds 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.
The building blocks every document shares
Section titled “The building blocks every document shares”A few small shapes recur everywhere, and once you know them you can read any document.
| Block | Shape | What 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 name | work_orders, planned_date | The stable, machine name of a definition or field. Labels change; normalized names should not. |
| Two version numbers | specificationVersion, version | specificationVersion 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 token | updateIdentifier | M2-S1’s optimistic-concurrency token |
The record envelope
Section titled “The record envelope”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": "…"}dataEntitysays which entity this is;entityVersionsays which version of that entity’s structure the record was written against.valueholds the fields by normalized name, each in its stored form (next section).stateis the record’s lifecycle state:0draft,1active,2archived, with astateHistoryof transitions.lifeCycleStatusis separate: it tracks a record in a workflow (0active,1completed,-1failed) 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 rewritesvaluewholesale must keep them, a rule you meet again in migrations (M2-S4) and in the workflow engine (M4-S3). storenames the store the record belongs to (M2-S4);searchIndexis a denormalised copy for full-text search (M3-S4).isInvalidwithinvalidReasonmarks a record that fails the current definition without deleting it: reason0(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 as | In value |
|---|---|---|
| Reference, User | entity reference | { dataEntity, dataEntry } |
| Category | JSON | { id } of the chosen option, or an array of them when Multiple is on |
| Mapped Field | the source field’s type | a copy of the source value, refreshed by its update mode |
| Block | block | an object (or array, when repeatable) of the block’s own fields |
| Number, Sequence Field | number | a 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
DataRelationdefinition 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:
- increments the entity’s
versionand records which fields broke and why; - publishes an entity-updated event (and a version-changed one), so every consumer refreshes;
- leaves every existing record as it was, now behind: its
entityVersionis lower than the entity’sversion, and it is marked Obsolete (isInvalid: true, reason0); - 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.
Values that are a wire contract
Section titled “Values that are a wire contract”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
Datefrom2to3silently 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
= nwritten 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.
-
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. -
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. -
Read one record:
db.work_orders.findOne({"value.title": /P-101/}). Point atdataEntity(the definition’s id),entityVersion(equal to the entity’sversion),state, the reference invalue.asset, the copiedvalue.asset_title, the category{id}invalue.priority, and the workflow keys undervalue. -
Follow the reference by hand: take
value.asset.dataEntryand readdb.assets.findOne({id: "<that id>"}, {"value.asset_name":1}). The name matches Asset Title. -
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.
✓ Practice (4 min) — Read the shapes
Section titled “✓ Practice (4 min) — Read the shapes”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?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
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?
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
- Save the Work Orders definition (demo step 1, without the
jqfilter) aswork_orders.json. - List every field with its normalized name, storage type number, component and, for references, the target entity. Mark the field shown as the title.
- Find the relation definitions for Work Orders:
db.DataRelation.find({targetField: {$in: ["asset", "raised_by_plan"]}}, {normalizedName:1, targetField:1, relationType:1}). - Find the mapped field Asset Title and write down its source and its update mode.
Part B: three records
- Read three records from
work_orders: Replace mechanical seal on P-101, Inspect bearing noise on C-201 and Lubricate bearings on P-102. - For each, record:
state,lifeCycleStatus,entityVersion, the current step fromvalue._metaCurrentSteps, the stored form of Priority and Estimated Hours, and who last updated it. - Compare Asset Title in each record with the name of the asset its reference points at.
Part C: predict, then prove, a type change
-
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". -
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.
-
Read the entity’s
versionagain, and one record’sentityVersion,isInvalidandinvalidReason. -
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.
- Read the three records’ Estimated Hours in the record store, and note any record that failed to upgrade.
- 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 see | What to do |
|---|---|
GET /api/v1/entities/work_orders answers 404 | Use the entity’s id instead: find it with db.DataEntity.findOne({normalizedName:"work_orders"},{id:1}). |
db.work_orders.findOne returns null | Check 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 appears | The 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 offered | Filter the list to Obsolete entries first; only obsolete records can be upgraded. |
| A record fails with Workflow reset required | You 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”Which of these changes to Work Orders, which holds 900 records, creates a new version of the entity?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A teammate looks for the code class that stores Larkspur’s Assets, to add a database index. What do you tell them?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A work order’s stored document shows "state": 2 and "lifeCycleStatus": 0. What is it?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A list of work orders can be filtered by the asset’s site, through the reference. What makes that filter possible?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
Two fields, Notes and Technician Phone, look different in the portal but share one storage type. How does the platform tell them apart?
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.