Plans .md

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 PlanContext and an exports argument annotated with a PlanExports subclass, or None if 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 init to 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(). Calling finalize() 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 PlanContext produced while running the plan.

property exports: E

Return the PlanExports populated 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 in depends_on are excluded. destroy uses 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_dependencies within dependencies: 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, so apply adopts 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 apply rebase 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.

property depends_on: tuple[Plan[Any], ...]

Return directly declared prerequisite plans.

classmethod active()

Return the active plan while it is running, or None otherwise.

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 ctx to configure plan-wide settings such as the default space, and assign reusable outputs to exports.

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

finalize()

Run run() once, collecting the planned objects.

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_setup tears Django down and rebuilds the model classes on that switch (reset_django), so a lamindb class captured while the plan was finalized against the previous instance (e.g. a LaminDType holding ln.ULabel) is stale for the next one and fails isinstance/issubclass checks. Reset clears the cached objects so the plan is finalized afresh against each instance’s live classes; it cascades to the prerequisite plans in depends_on since 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.

property migrations: tuple[Migrated, ...]

Return the data migrations declared via migrate().

property moves: tuple[Moved, ...]

Return the address changes declared via moved().

migrate(obj, migration, /)

Attach a narrowing data migration to obj for the next apply.

Unblocks a validation-affecting change on obj that the live data would otherwise refuse (a narrowing the data does not already prove safe). The shapes, by the kind of obj: :rtype: None

  • a Feature whose dtype narrows: on apply the engine flips the dtype and then runs migration inside the same transaction to rewrite the stored values so they validate against it. The callable receives a MigrationContext.

  • a Feature whose nullable the plan turns off: migration backfills the sheet rows that omit it, once per schema declaring it (see fill_nulls()), or vouches for the datasets validated with it (see accept_non_null()). A backfill receives a MemberMigrationContext.

  • a Schema that makes an optional member required: the engine narrows the optional set and then runs migration to annotate the rows that omitted the member. The callable receives a MemberMigrationContext, whose missing() 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 migration to say what becomes of them (see drop_member_values() and keep_member_values()). The callable receives a MemberRemovalContext.

  • a Schema whose change invalidates an exported sheet snapshot: the engine hands migration the stale exports so it can write a new version of each (see reexport_sheets() and keep_stale_exports()). The callable receives a SheetExportContext, 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 index the plan adds, changes or removes while it has already validated data: the engine switches the index and then runs migration, which states that the data conforms (see accept_index_change()). The callable receives a IndexChangeContext.

  • a Schema whose flexible the plan turns off: the engine switches the flag and then runs migration, which either keeps what the flexible match annotated – and, on a maximal_set schema, vouches that the data still validates (see accept_flexible_change()) – or removes it (see drop_nonmember_annotations()). The callable receives a FlexibleChangeContext.

  • a Sheet the plan points at another schema while it has rows: revalidate_rows() has the apply check them against the new schema, and reexport_sheets() or keep_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 runs migration before the feature is trashed (see drop_values() and keep_values()). The callable receives a FeatureRemovalContext. 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 a RecordTypeRemovalContext), and so is a deleted schema, to vouch for the datasets it validated (keep_validated(), receiving a SchemaRemovalContext). 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 a RecordUpdateContext. 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 a RecordRemovalContext.

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 validate catches a misdeclared one offline with a PlanDeclarationError: a helper attached to a kind of target it does not answer for (the shapes above, see targets; 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 obj was 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 uid and 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 which cat[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 a from_ 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 TypeError when 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 validate reports it offline as a one-line Error:. A ValueError too, 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'
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'
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'
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'
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.

ctx supplies 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)

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: obj was previously known as from_.

obj is the object at its new address; from_ is its previous name (a bare leaf name) or a full previous natural key. See moved().

class lamindb_setup.evolve.authoring._migrations.Migrated(obj, migration)

A migration declared for obj via migrate().

obj is 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’s add_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.

ADD_VALUES = 'add_values'