Plans
¶
Define a plan and its exports.
Define a plan¶
- lamindb_setup.evolve.create_plan(func)¶
Turn a declaration function into a
Plan.The function takes a
PlanContextand anexportsargument annotated with aPlanExportssubclass, orNoneif it has no exports. Its body runs when the plan is finalized, not at decoration time. Creating declarations in that body registers them with the plan.Example:
@create_plan def measurements(ctx: PlanContext, exports: None) -> None: Feature("measurement", dtype=LaminDType(float))
Use
lamin evolve initto create a plan file with the imports and stable transform UID required by the CLI. See the Manage schemas guide.- Return type:
Plan[Any]
- class lamindb_setup.evolve.Plan(name)¶
Collect metadata declarations for validation, preview, and apply.
Usually created with
create_plan(). Callingfinalize()runs the plan and collects its declarations and dependencies in memory; it does not save them to an instance.- property defining_module: str | None¶
Return the name of the module that defines this plan, if known.
Used to tell plans declared in a file apart from plans merely imported into it. By default this is the module of the plan’s class. For a decorated plan, it is the module that defines the function.
- property ctx: PlanContext¶
Return the
PlanContextproduced while running the plan.
- property exports: E¶
Return the
PlanExportspopulated while running the plan.
- property dependencies: DependencyDAG¶
Return the collected dependencies ordered for creation.
- property own_dependencies: DependencyDAG¶
Return only the dependencies this plan declares itself.
Unlike
dependencies, the objects inherited from the plans independs_onare excluded.destroyuses this so tearing down a plan only deletes the objects it concretely creates, leaving the objects managed by upstream plans untouched.
- property inherited_dependencies: DependencyDAG¶
Return only the dependencies inherited from
depends_on.The complement of
own_dependencieswithindependencies: the objects a prerequisite plan declares and this plan merely references. They still have to be resolved – a schema cannot link a borrowed feature without it – but they are the prerequisite plan’s to manage, soapplyadopts them without recording them in this plan’s lock.
- property inherited_moves: tuple[Moved, ...]¶
Return the address changes declared by the plans in
depends_on.A prerequisite plan renaming one of its objects changes that object’s natural key, and this plan records the borrowed object by that key wherever it references it (a schema’s member list, a sheet’s schema). Surfacing the upstream declarations lets
applyrebase those references instead of reading the rename as “the plan dropped a member”. Collected transitively, since a prerequisite may itself depend on a plan that declares a move.
- classmethod active()¶
Return the active plan while it is running, or
Noneotherwise.- Return type:
Plan[Any] |None
- abstract run(ctx, exports, /)¶
Define the plan by creating schema objects.
Subclasses implement this to declare the objects to materialize. Use
ctxto configure plan-wide settings such as the default space, and assign reusable outputs toexports.- Return type:
None
- add_dependency(obj, /)¶
Record a dependency as a to-be-materialized object.
- Return type:
None
- add_plan_dependency(plan, /)¶
Record another plan that must be finalized before this one runs.
- Return type:
None
- reset()¶
Discard finalized state so the next
finalize()re-runs the plan.Applying the same plan against several instances in one process reconnects LaminDB between them;
lamindb_setuptears Django down and rebuilds the model classes on that switch (reset_django), so alamindbclass captured while the plan was finalized against the previous instance (e.g. aLaminDTypeholdingln.ULabel) is stale for the next one and failsisinstance/issubclasschecks. Reset clears the cached objects so the plan is finalized afresh against each instance’s live classes; it cascades to the prerequisite plans independs_onsince their objects go stale for the same reason.- Return type:
None
- class lamindb_setup.evolve.PlanContext¶
Mutable context passed to
Plan.run()for plan-wide settings.- migrate(obj, migration, /)¶
Attach a narrowing data migration to
objfor the next apply.Unblocks a validation-affecting change on
objthat the live data would otherwise refuse (a narrowing the data does not already prove safe). The shapes, by the kind ofobj: :rtype:Nonea Feature whose dtype narrows: on apply the engine flips the dtype and then runs
migrationinside the same transaction to rewrite the stored values so they validate against it. The callable receives aMigrationContext.a Feature whose
nullablethe plan turns off:migrationbackfills the sheet rows that omit it, once per schema declaring it (seefill_nulls()), or vouches for the datasets validated with it (seeaccept_non_null()). A backfill receives aMemberMigrationContext.a Schema that makes an optional member required: the engine narrows the optional set and then runs
migrationto annotate the rows that omitted the member. The callable receives aMemberMigrationContext, whosemissing()enumerates exactly those rows. A row still omitting it afterwards fails the apply, so a partial backfill rolls back.a Schema that drops a member whose values are stored: the engine unlinks it and then runs
migrationto say what becomes of them (seedrop_member_values()andkeep_member_values()). The callable receives aMemberRemovalContext.a Schema whose change invalidates an exported sheet snapshot: the engine hands
migrationthe stale exports so it can write a new version of each (seereexport_sheets()andkeep_stale_exports()). The callable receives aSheetExportContext, and – alone among these – runs after the apply transaction committed, onto a branch merged into the instance only on success: an exported CSV is a file in storage, which no transaction can roll back.a Schema whose
indexthe plan adds, changes or removes while it has already validated data: the engine switches the index and then runsmigration, which states that the data conforms (seeaccept_index_change()). The callable receives aIndexChangeContext.a Schema whose
flexiblethe plan turns off: the engine switches the flag and then runsmigration, which either keeps what the flexible match annotated – and, on amaximal_setschema, vouches that the data still validates (seeaccept_flexible_change()) – or removes it (seedrop_nonmember_annotations()). The callable receives aFlexibleChangeContext.a Sheet the plan points at another schema while it has rows:
revalidate_rows()has the apply check them against the new schema, andreexport_sheets()orkeep_stale_exports()say what becomes of the exports written against the old one, as for a schema.a natural key string naming a feature the plan no longer declares, e.g.
"FeatureType:ft/Feature:retired": the removal pass runsmigrationbefore the feature is trashed (seedrop_values()andkeep_values()). The callable receives aFeatureRemovalContext. A string is the only way to address it: the plan deleting the feature is precisely the plan with no object left to point at. A record type or sheet the plan deletes is addressed the same way, to say what becomes of its records (drop_rows(), receiving aRecordTypeRemovalContext), and so is a deleted schema, to vouch for the datasets it validated (keep_validated(), receiving aSchemaRemovalContext). Instead of letting the trash take them, the records can be kept (keep_rows()) or moved to another record type or sheet (move_rows()), the datasets pointed at another schema (revalidate_against()), and the sub-types, features and schemas typed under a deleted type re-parented (adopt_children()) – each performed by the apply itself, before the deletion.a seeded Record, which ignores the plan’s edits once it exists:
update_record()writes the plan’s feature values and description over the instance’s, receiving aRecordUpdateContext. A record the plan stops declaring stays on the instance;drop_record(), declared by its natural key, trashes it – relocating the annotations that hold it as their value first – receiving aRecordRemovalContext.
Like
moved(), the declaration is idempotent: once the instance matches the plan the change – and hence the migration – is skipped, so it is safe to leave in place until every instance has been migrated and then remove it in a follow-up commit.A migration never creates the objects it maps into: they must be declared in the plan (or already exist in the instance). Declaration order does not matter – the apply runs every migration in its own phase, after it has materialized every object the plan declares.
Finalizing the plan checks every declaration, so
validatecatches a misdeclared one offline with aPlanDeclarationError: a helper attached to a kind of target it does not answer for (the shapes above, seetargets; a natural key may stand in for an object, as for a schema no plan manages), a string that is not a natural key, and a removal declared for the key of an object this plan or a prerequisite still declares. A hand-written migration naming no narrowing answers whatever it is declared for, so only its target is checked to be a plan object or a natural key.
- moved(obj, from_, /)¶
Declare that
objwas previously stored under a different address.Records a rename or a move to another parent so the next apply keeps the existing object’s identity – its
uidand everything validated against it – instead of deleting the old address and creating a new one.from_is either the object’s previous name (a leaf rename under the same type chain) or a full previous natural key such as"FeatureType:old/Feature:x"for a move that also changes the type chain. A record type’s parent decides whichcat[Record[<type>]]features admit its records, so moving one out from under a type is applied only when no such feature holds a value below it.The declaration is idempotent: once applied (the new address is recorded in the lock) it is a no-op, so it is safe to leave in place until every instance has been migrated and then remove it in a follow-up commit. Finalizing the plan refuses a
from_naming the object’s current name or natural key, and afrom_holding a:or/that is not a natural key.Seed-only objects have no lock entry to re-address and so cannot be moved: renaming one on the instance is invisible to the plan and needs no declaration here.
- Return type:
None
- class lamindb_setup.evolve.PlanExports¶
Base class for declaring the reusable outputs of a
Plan.Subclasses declare named, typed fields for the objects a plan produces so they can be exported and reused by other plans:
class MyExports(PlanExports): feature_0: Feature schema_0: Schema
Only the schema types used as plan building blocks may be declared as fields; any other annotation raises
TypeErrorwhen the subclass is defined.
- exception lamindb_setup.evolve.PlanDeclarationError¶
A plan declares something that can never do what it says.
Raised while the plan is finalized, so
validatereports it offline as a one-lineError:. AValueErrortoo, which is what the checks it replaces raised.
Plan result types¶
- class lamindb_setup.evolve.SpaceUID(value: str, *, registry: str | None = None)¶
UID subclass for Space registry, enforcing 12-character length.
-
registry_name:
str|None= 'lamindb.models.sqlrecord.Space'¶
-
registry_name:
- class lamindb_setup.evolve.core._uids.FeatureUID(value: str, *, registry: str | None = None)¶
UID subclass for Feature registry, enforcing 12-character length.
-
registry_name:
str|None= 'lamindb.models.feature.Feature'¶
-
registry_name:
- class lamindb_setup.evolve.core._uids.RecordUID(value: str, *, registry: str | None = None)¶
UID subclass for Record registry, enforcing 16-character length.
-
registry_name:
str|None= 'lamindb.models.record.Record'¶
-
registry_name:
- class lamindb_setup.evolve.core._uids.SchemaUID(value: str, *, registry: str | None = None)¶
UID subclass for Schema registry, enforcing 16-character length.
-
registry_name:
str|None= 'lamindb.models.schema.Schema'¶
-
registry_name:
- class lamindb_setup.evolve.core._graph.Promise(arg, func, *, label=None)¶
A deferred call.
-
label:
str|None¶
- resolve(ctx)¶
Resolve to the concrete uid, materializing the underlying object.
ctxsupplies the cache and lock state shared by the apply run. Callers outside a run supply their own context.- Return type:
TypeVar(R)
- get_arg()¶
Get the underlying argument that will be materialized.
- Return type:
TypeVar(T)
-
label:
- class lamindb_setup.evolve.core._graph.Dependency(obj, *, requires=None)¶
Represents a dependency on another object that needs to be materialized first.
- class lamindb_setup.evolve.core._graph.DependencyDAG(dependencies)¶
Dependencies ordered so that required objects are created first.
- ordered()¶
Return the dependencies in a valid creation order (requirements first).
- Return type:
list[Dependency]
- class lamindb_setup.evolve.authoring._plan.Moved(obj, from_)¶
A declared address change:
objwas previously known asfrom_.objis the object at its new address;from_is its previous name (a bare leaf name) or a full previous natural key. Seemoved().
- class lamindb_setup.evolve.authoring._migrations.Migrated(obj, migration)¶
A migration declared for
objviamigrate().objis a plan object, or the natural key of one the plan no longer contains – the only way to address a feature the plan is deleting, which by definition has no object left to point at.
- class lamindb_setup.evolve.authoring._migrations.WriteStrategy(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
How a relocation wrote the replacement annotations.
A
str -> cat[...]relocation writes the link rows itself when the target store supports batched link writes. Otherwise it uses lamindb’sadd_values, which re-resolves the feature and runs a curator per annotated object. The choice is invisible in the resulting data – both end with the same link rows – so the migration records which one it took.- BATCHED_LINKS = 'batched link rows'¶
- ADD_VALUES = 'add_values'¶