Skip to content

M2-S4 — Persistence: stores, migrations and files

Section titled “M2-S4 — Persistence: stores, migrations and files”
ModuleM2 — The platform’s architecture and contracts
After this session you canPredict what an upgrade’s data migrations do to a customised tenant, say where an entity’s records and files physically live, and read the migration ledger.
TimeFacilitated: 48 min · On your own: 48 min
Before you startM2-S3: definitions and records. Larkspur Lab with the record-store and logs windows (workbench).
Go deeperReference: schema and migrations · File storage internals · Data stores: model, routing and API

◆ Orientation (1 min) — The ground under the records

Section titled “◆ Orientation (1 min) — The ground under the records”

ACDE taught you to back up and restore the databases and to recover a failed upgrade as an operator. M1-S2 made upgrades part of the program’s release train. Neither told you what an upgrade actually does to Larkspur’s records, or why a rollback of the chart does not roll the data back. That is this session: where the documents of M2-S3 physically live, how a store decides which space sees which record, where files go, and how the platform changes all of it, one migration at a time, when you upgrade. In M9-S2 you turn it into the upgrade plan for a platform that carries your extensions.

▤ Concept (11 min) — Where things live, and how they change

Section titled “▤ Concept (11 min) — Where things live, and how they change”

You configured the databases in ACDE: the combined pods build each application’s MongoDB address from one template, replacing {db} with the application’s database name, and standalone services take their own address (ACDE M1-S1). In Larkspur Lab, with the prefix lk-, that gives the picture below. Read it as “which application owns which data”.

DatabaseHoldsOwned by
lk-dataEvery definition (the meta-model collections) and every record (one collection per entity); also the dependency graph, packages and reactions’ shared dataThe data service, with the dependency, packaging and reaction applications pointing at it by design
lk-reactionThe reaction application’s own working dataReactions
lk-cell-opsOperations state shared by the cell, such as reaction-run state (BusWorkflowState) and job-run talliesReactions and the scheduler’s job tallies
lk-workflow, lk-timeline, lk-logging, lk-integrations, lk-notification-apiEach application’s own dataThat application
lk-identityAccounts, sign-in clients, tokensThe identity server (M5-S1)
lk-storageFile metadata and the file-reference ledgerThe storage service
lk-schedulerScheduled jobsThe scheduler (M4-S1)

Two consequences. The data service’s database is the platform: a backup that misses it misses everything a builder made and everything people entered. And applications never read each other’s databases; they ask over HTTP or listen on the bus (M2-S1). A report that needs workflow history asks the workflow service, it does not open lk-workflow.

ACE taught you stores as a design choice: by default an entity’s records are visible from every space (the public store) or only from the space that created them (private), and a shared store spans two or more chosen spaces; the weight decides where new records go (ACE M1-S2). Here is how the engine does it.

Every record carries a store reference (M2-S3). The entity’s definition carries store rules: by default two, Public with weight 100 and Private with weight 50, plus one per shared store you add. Public and private stores are not documents at all: they are fixed identifiers, PUBLIC and PRIVATE_<space id>. Only shared stores are stored, as documents in the DataStore collection listing their spaces.

  • On a write, the engine drops every shared rule whose store does not include the current space, takes the rule with the highest weight, and stamps the record with that store. So with the defaults, a new record goes to the public store (100 beats 50).
  • On a read, the engine computes the stores visible from the current space (the public store, that space’s private store, and every shared store that lists the space) and returns only records whose store is among them. A record in a store the space cannot see is simply not found there, which is how stores scope visibility without any permission being involved.

Two practical facts. Every list read starts by matching on store (then state), so the entity’s indexes lead with it; the 1.10 line added store indexes with the right collation for exactly that reason. And because the store is stamped when a record is written, changing an entity’s store weights later does not move existing records: it only changes where new ones go.

A file, image or document field never holds bytes. The file is uploaded to the storage service, which writes the bytes to its configured provider (a disk volume in your lab; Azure, S3-compatible or Google storage in production) and its metadata (name, type, size, owner, the provider’s coordinates) to its own database. The record’s field stores the file’s id.

Uploads arrive as temporary files, kept for a day in a separate collection and a temporary location. When a save references a temporary file, the 1.10 line promotes it to permanent storage and records the reference in a file-reference ledger: which owner (a record, a draft, an entity, a view, a page, a reaction, a report) refers to which file. When the last reference goes, the file is marked orphaned, and after a waiting period (seven days by default) a sweeper deletes it, but only after every former owner confirms it no longer lists the file. Anything uncertain keeps the file. A save that references a temporary file that has already expired is refused with FILE_EXPIRED, and the user uploads again.

ACDE taught you to take a consistent MongoDB backup and restore it with the writers stopped (ACDE M4-S3). Knowing where things live adds one rule: a tenant’s state is spread over several stores, and a backup is only useful if its parts agree. Records hold file ids, so restoring the data database without the storage provider’s files leaves records pointing at nothing; restoring the files without the storage database’s metadata and ledger leaves files that nothing can find, which the sweeper will later judge. Identity’s database holds the accounts that every doneBy reference points at. And the migration ledger lives inside the data database, so restoring that database also restores the record of which scripts ran: after a restore, the next upgrade re-applies exactly what the restored data had not yet received, which is what you want.

So the upgrade plan’s backup is taken of every database and the file provider, at the same moment, with the platform’s writers stopped, and the restore test restores all of them together. A backup of lk-data alone is a backup of most of Larkspur, which is not the same thing as a backup of Larkspur.

Migrations: how an upgrade changes stored data

Section titled “Migrations: how an upgrade changes stored data”

A new platform release sometimes needs the stored data to change: a new core entity, a new field on a built-in definition, an index, a backfilled value. That work is done by migrations: small scripts, shipped in the data service, each with an up() that makes one change. They run in the migration Job that ACDE taught you to watch: a Helm hook after every install and upgrade (ACDE M2-S2). Here is what happens inside it on the 1.10 line.

  1. Selection by identity. Each script has a version in the release’s train (such as 1.10.0-a38) and a scriptName. The runner reads every row of the migration ledger, the Migration collection in the data database, and runs every script whose scriptName is not already recorded, in version order, up to the running application’s version. There is no single “database version” any more: a set of applied scripts is compared with the set the release ships. The older rule (“run everything above the last recorded version”) let a script whose version collided with another’s be skipped for ever, which is why it was replaced.
  2. One row per script, after it succeeds. A script that throws is not recorded, so the next run retries it from the top. Everything recorded before it is not run again.
  3. Failure fails the release. A run that stops half-way exits with an error, so the Job fails, the Helm hook fails and helm upgrade reports failure. (Before 1.10 it reported success over a half-migrated database.) The recovery is the one ACDE taught: read the Job’s log, fix the cause, upgrade again.
  4. Forward only. Almost every script’s down() is empty, and the runner never calls down() on a downgrade: if the database is ahead of the application, it logs a warning and changes nothing. Rolling the chart back restores the old workloads over data that has already been migrated forward. The only true way back for the data is a restore from a backup taken before the upgrade.
flowchart TD
  U["helm upgrade"] --> J["migration Job (post-upgrade hook)"]
  J --> L["read the ledger:<br/>which scriptNames are applied?"]
  L --> P["pending = shipped minus applied,<br/>up to the app version, in order"]
  P --> S["run one script's up()"]
  S -->|"succeeds"| R["record its row in the ledger"]
  R --> P
  S -->|"throws"| F["Job fails, helm upgrade fails;<br/>the script stays pending"]

What to notice: the ledger is the only memory. That is why ACDE’s rule “never delete a migration record” matters: deleting a row makes the runner apply that script again on the next upgrade.

Most scripts either edit definitions directly and then publish an entity-updated event, or send commands through the same handlers as everyday writes, so that indexing, the dependency graph and reactions see the change like any other. Three habits of the 1.10 line are worth knowing when you read an upgrade’s log: index migrations publish an entity-updated event for every eligible entity on every run, so a large tenant sees a burst of indexing work after an upgrade; a few scripts catch their own failure and only log it, so the Job can succeed while that one change is missing, which is why you read the migration log after every upgrade, not just its exit code; and each script logs how long it took (Applied migration … in N ms), which is how you size the next upgrade’s window from the last one.

In a multi-tenant cell the same chain runs against every tenant’s data database, a few tenants at a time; a tenant that fails is listed as a casualty while the others complete, and a re-run resumes it at its failed script. Larkspur’s single-tenant release is the same chain run once.

Why migrations matter more on a customised tenant

Section titled “Why migrations matter more on a customised tenant”

The platform’s own entities change in predictable ways. Your tenant’s do not, and migrations meet them. A migration that adds an index scans every collection it applies to, so Larkspur’s 300,000 work orders cost minutes where a fresh tenant costs nothing. A migration that adds an implicit field to a core definition can refuse to run if a builder already created a field with the same normalized name. A migration that rewrites a value stored in every record of entities with a repeatable block reads all of them. And a migration may change a built-in definition your extensions read. The release notes and the migration list tell you which scripts a release ships; the master’s job is to map each one onto what Larkspur has, before production does it for you.

◇ Worked scenario (4 min) — Larkspur’s production upgrade to the 1.10 line

Section titled “◇ Worked scenario (4 min) — Larkspur’s production upgrade to the 1.10 line”

Larkspur’s production tenant still runs the 1.8 line; your lab already runs 1.10. Leila Amari asks how long production will be unavailable, and what could go wrong with “our own data”. You take the 1.10 line’s migration list and map four of its scripts onto Larkspur. Decide at each before reading on.

The collated store indexes. Several scripts add indexes to every entity so that list reads, which always start by matching the store, use an index instead of sorting in memory. Decide: what does this cost Larkspur? Work Orders holds 300,000 records and Purchase Orders 80,000. Each index build scans the whole collection, and each script then publishes an entity-updated event per entity, which the indexing service processes afterwards. You read the lab’s per-script timing lines (a few seconds on 2,000 work orders) and scale them: plan minutes, not seconds, and expect search to lag for a while after the Job ends.

Stable ids for repeatable-block rows. One script gives every row of every top-level repeatable block a stable id, streaming every record of every entity that has one. Decide: does Larkspur have any? Maintenance Plans has a repeatable Checklist block. 1,200 plans is small: seconds. But you note it, because a builder who adds a repeatable block to Work Orders before the upgrade would turn it into a 300,000-record pass.

The application user’s expiry date. One script changes the type of the application user’s expiry date from date-time to date. Decide: who is affected? Every application user: Larkspur Workbench, Legacy ERP Sync, and any your integrations use. Their expiry dates survive (a date is kept), but this script is one of the few that log a failure and continue. After the upgrade you read the migration log for its line, and open each application user to check its expiry date.

Rolling back. Decide: if the upgrade misbehaves the next morning, what does helm rollback give you? The 1.8 workloads, over data that the 1.10 scripts have changed, with no down() run. So the plan’s real way back is the backup taken immediately before the upgrade, restored as ACDE taught, with everything entered since lost. That is a business decision, and Leila must know it before the window, not after.

The answer to Leila. “About an hour of downtime, most of it index building on work orders and purchase orders; search will be slower for a while after. Nothing in our own data is rewritten except new stable ids inside maintenance-plan checklists. If we have to go back, we go back to last night’s backup and re-enter that morning’s work.” You write it as a decision record (M1-S2), and M9-S2 turns it into the full upgrade plan.

⛏ Lab (23 min) — Read the ledger and map an upgrade onto Larkspur

Section titled “⛏ Lab (23 min) — Read the ledger and map an upgrade onto Larkspur”

Goal. Evidence from Larkspur Lab of where an entity’s records, store and files live, a reading of the migration ledger and the migration Job’s log, and the scenario’s four predictions checked against the lab’s own data.

Before you start. Larkspur Lab; the record-store and logs windows. A file m2-s4-persistence.md.

Where things live

  1. List the release’s databases: in mongosh, show dbs. Match each lk- database to the table in the Concept, and note any you did not expect.
  2. Read the store rules of Work Orders: db.DataEntity.findOne({normalizedName: "work_orders"}, {storeRules: 1}). Then read the store of one work order: db.work_orders.findOne({}, {store: 1}). Explain why that store was chosen.
  3. Find a file. The seeded inspection Casting porosity, batch OC-2231 has a photo. Read its id from the record: db.inspections.findOne({"value.title": /OC-2231/}, {"value.photo": 1}).
  4. Open the storage database (use lk-storage) and read the file’s metadata and its references: db.metadata.findOne({_id: "<the id>"}) and db.file_references.find({fileId: "<the id>"}). Note the provider type, the owner and whether the file is tracked.

The migration ledger

  1. Back in lk-data, read the last ten applied scripts: db.Migration.find({}, {scriptName: 1, version: 1, appliedAt: 1, changeNumber: 1}).sort({changeNumber: -1}).limit(10).

  2. Count the applied scripts of the 1.10 line: db.Migration.countDocuments({version: /^1\.10\./}).

  3. Read the migration Job’s log for its summary and timings:

    Terminal window
    kubectl -n larkspur logs job/lk-osos-migration-1 | grep -E "Applied migration|already applied|Cannot migrate" | tail -20

    Find the three slowest scripts and their durations.

Map the scenario onto the lab

  1. Collated indexes: list Work Orders’ index names, db.DataEntity.findOne({normalizedName: "work_orders"}).indexes.map(i => i.name). Find the collated (_ci) ones.
  2. Repeatable-block row ids: read one maintenance plan’s checklist, db.maintenance_plans.findOne({}, {"value.checklist": 1}), and look for each row’s stable id.
  3. Application users’ expiry dates: in the portal, open Administration › Organization › Users and open Legacy ERP Sync. Note its expiry date and its type on screen.
  4. Write the rollback paragraph for Larkspur: what helm rollback restores, what it does not, and what must exist before production’s upgrade starts.
  5. Write two lines for the upgrade plan: the expected duration you derive from step 7’s timings scaled to production’s record counts (Work Orders 300,000), and the log lines to check afterwards.

Check.

  • Every lk- database is matched to its owning application, with surprises noted.
  • You explained the work order’s store from the store rules and the write rule.
  • You traced one file from the record’s field to its metadata and its reference rows.
  • You quoted the latest applied script, the 1.10 count and the three slowest scripts with their durations.
  • Steps 8 to 12 are answered, and the rollback paragraph names the backup as the only way back for the data.

Pass condition. All five checks hold.

If something goes wrong

What you seeWhat to do
job/lk-osos-migration-1 not foundThe Job is kept for a day after it finishes (ttlSecondsAfterFinished). List what exists with kubectl -n larkspur get jobs; if it is gone, run helm upgrade with the same values to get a fresh one (nothing new is applied, and the log says so).
db.Migration is emptyYou are in the wrong database: the ledger lives in lk-data.
inspections.findOne returns no photoThe seed’s file upload may have failed; any record with a file field works. Find one with db.inspections.find({"value.photo": {$exists: true}}).limit(1).
metadata.findOne returns nullFile ids are the _id of the metadata document, as a string; check you pasted the id without quotes around the braces.
No _ci index on Work OrdersIndexes are built by the indexing service after the migration; look at the entity’s indexStatus for building or failed.
Model answer

Where things live. lk-data (definitions, records, dependency graph, packages), lk-reaction, lk-workflow, lk-timeline, lk-logging, lk-integrations, lk-notification-api, lk-identity, lk-storage, lk-scheduler, lk-translation; possibly a cell-level database the release uses for shared bookkeeping, such as the reactions’ saga state (M4-S2). Work Orders’ store rules are Public weight 100 and Private weight 50, no shared store, so the work order’s store is { dataEntity: "DataStore", dataEntry: "PUBLIC" }: the public rule has the highest weight. The photo’s metadata shows the disk provider, owner type DataEntity (or the record as owner) and tracked: true, with one live row in file_references for the inspection record.

The ledger. The latest rows are the highest 1.10.0-aNN scripts your release ships; the count is the number of 1.10-line scripts in that release; the log ends with Applied N migration script(s) in N ms (or All N migration scripts are already applied on a later run). The slowest scripts on a fresh lab are usually the initial set-up and index scripts, at seconds.

The mapping. Work Orders has the collated store indexes (…_ci). Each checklist row carries a stable __id. Legacy ERP Sync shows a date (not a date and time) as its expiry.

Rollback paragraph. helm rollback restores the previous chart’s workloads and configuration. It does not undo any migration: no down() runs, and the data stays migrated forward, under an older application. The only way back for the data is to restore the backup taken immediately before the upgrade, losing what was entered since. So the backup, tested, is a precondition of the upgrade window.

Duration. Scale the slowest index scripts by production’s record counts (for example 4 s on 2,000 work orders becomes roughly ten minutes on 300,000), add the indexing lag after the Job, and check the log for Cannot migrate, for each script’s applied line, and for the scripts that only log a failure.

✓ Practice (8 min) — Predict persistence

Section titled “✓ Practice (8 min) — Predict persistence”
PracticeChoose one answer.

After a failed upgrade, a colleague proposes deleting the last three rows of the migration ledger “so the database is back at the old version”. What actually happens on the next run?

  1. Explanation for A

    ✗ Incorrect

    Not this one: rows are a record of what ran; removing them changes no data and runs no down(). See Migrations.

  2. Explanation for B

    ✗ Incorrect

    Not this one: that was the old watermark rule; 1.10 compares the full applied set. See Migrations.

  3. Explanation for C

    ✓ Correct

    Correct: selection is by which scriptNames are recorded, so a deleted row means “run it again”. See Migrations.

Check your answer

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

PracticeChoose one answer.

Larkspur adds a shared store for Spare Parts spanning its two plants’ spaces, with weight 120. What happens to the 6,000 spare parts already stored?

  1. Explanation for A

    ✓ Correct

    Correct: existing records keep their store; the write rule applies to new writes. See Stores.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the store is stamped when a record is written; weights choose where new records go. See Stores.

  3. Explanation for C

    ✗ Incorrect

    Not this one: adding a store is not a breaking change, and existing records stay readable where they were. See Stores.

Check your answer

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

PracticeChoose one answer.

A record exists, but a user in another space gets 404 when opening it, and nobody has removed any permission. What explains it?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the gateway resolves the space; which records it may see is decided by the data service’s store rules. See Stores.

  2. Explanation for B

    ✓ Correct

    Correct: stores scope visibility by space before permissions are considered. See Stores.

  3. Explanation for C

    ✗ Incorrect

    Not this one: obsolete is a property of the record, not of the space reading it. See M2-S3: 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 removes a photo from an inspection and saves. When is the photo’s file deleted?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the ledger only marks the file orphaned; it never deletes on its own. See Files.

  2. Explanation for B

    ✗ Incorrect

    Not this one: tracked files that nothing references are swept after a waiting period. See Files.

  3. Explanation for C

    ✓ Correct

    Correct: an orphaned tracked file is deleted only after the waiting period and the owners’ confirmation; anything uncertain keeps it. See Files.

Check your answer

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

PracticeChoose one answer.

The upgrade Job completed and helm upgrade reported success. Why do you still read the migration log?

  1. Explanation for A

    ✓ Correct

    Correct: those scripts catch and log; only the log shows that their change did not happen. See Migrations.

  2. Explanation for B

    ✗ Incorrect

    Not this one: on 1.10 an unresolvable application version now fails the run instead of skipping everything. See Migrations.

  3. Explanation for C

    ✗ Incorrect

    Not this one: no down() runs on the 1.10 line, on upgrade or downgrade. See Migrations.

Check your answer

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

PracticeChoose one answer.

To save time, an upgrade plan backs up only lk-data, because “that is where everything is”. What would a restore from it leave broken?

  1. Explanation for A

    ✗ Incorrect

    Not this one: they are, but files, accounts and other applications’ data live elsewhere. See Backups that agree with each other.

  2. Explanation for B

    ✓ Correct

    Correct: a tenant’s state spans several databases and the file provider, so their backups must be taken together. See Backups that agree with each other.

  3. Explanation for C

    ✗ Incorrect

    Not this one: search can be rebuilt, but files and accounts cannot be rebuilt from the data database. See Backups that agree with each other.

Check your answer

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

↺ Recap (1 min) — After Module 2 you can

Section titled “↺ Recap (1 min) — After Module 2 you can”

After this module you can trace any request or message through the services, read definitions and records as they are stored, say where records and files physically live and which space sees them, and predict what an upgrade does to a customised tenant’s data, including what rolling back cannot undo.

Next. In M3 you open the read side: the engines that compute, filter, aggregate, search and draw these stored records, starting with the expression engine that evaluates every calculated field.