## Data migrations

Fill, map, move, or drop existing values when applying a plan.

Attach a migration to its target with "PlanContext.migrate()". Preview
it with "lamin evolve plan --preview-migrations" before applying it.

# Migration types

class lamindb_setup.evolve.DataMigration(*, name, migrate, reason='', keeps_values=False, narrowing='', index_name_conflict=None, merges=None, detaches=(), updates=(), relocates_to=None, relocation='', narrower=False, targets=None)

 A narrowing data migration attached to a plan object.

 Declared with "migrate()", it unblocks a validation-affecting
 change the live data would otherwise refuse. "migrate" receives a
 context shaped by what it unblocks -- a "MigrationContext" for a
 feature's dtype narrowing (the live feature, already flipped to the
 new dtype), a "MemberMigrationContext" for a schema making an
 optional member required -- and must fix the data up so nothing is
 left invalid; it runs inside the apply "transaction.atomic()".

 "name" identifies the migration in previews and the change audit;
 "reason" is a short human-readable explanation of what it does
 (defaulting to "name").

 "keeps_values" marks a migration that deliberately leaves the data
 where it is, which a member removal, a stale sheet export and a
 schema turning "flexible" off all have a meaning for: the values
 stay on the rows as undeclared extra data, the exported snapshot
 stays as it is, respectively the annotations the flexible match
 wrote stay on the artifacts.  It exempts the migration from the
 post-check that would otherwise require them to be gone. For a
 member removal it is refused on a "maximal_set" schema, which is
 precisely the kind that does not tolerate an undeclared member.

 "narrowing" identifies the change this migration handles. Examples
 include "member_required", "member_added", "member_removal",
 "stale_exports", "index_change", "flexible_change", "rows_removal",
 "validated_removal", and "nullability". A custom migration with an
 empty "narrowing" handles the change it is attached to.

 For an index change, "index_name_conflict" chooses which value to
 keep when a row's name and its new index value differ
 (""keep_name"" or ""keep_feature""). Applying the plan stops on a
 conflict without a choice.

 "merges" identifies the live schema to merge by UID or natural key.
 "detaches" lists the schemas from which to remove a deleted
 feature. "updates" selects which aspects of a seeded record to
 update (values, description, or reference). An empty selection
 updates all three.

 For a removal, "relocation" identifies what to move (rows,
 datasets, or children). "relocates_to" identifies their destination
 by plan object, natural key, or UID. Use "None" for an untyped
 destination. Set "narrower" to allow a more restrictive replacement
 schema when revalidating datasets.

 targets

 The "DeclarationTarget" entries allowed by this migration.
 Defaults to the targets for the selected narrowing. Plan
 validation checks them before apply. A custom migration with no
 narrowing or explicit targets skips this check.

 A migration never *creates* the objects it maps into, so they must
 already exist when it runs.  The engine guarantees that by running
 every declared migration in its own phase, after the whole plan has
 been materialized -- so a target declared anywhere in the plan is
 there, whatever order the plan file lists it in.

 The "migrate" callable must not capture LaminDB class objects from
 an outer scope: a plan is re-finalized against each instance's
 freshly rebuilt classes, so import "lamindb" (and any registry)
 *inside* the callable.

 run(context)

 Execute the migration against "context".

 Which context it gets is decided by the object the migration is
 attached to, not by the migration itself -- hence the
 deliberately loose annotation on "migrate": a single class
 serves both narrowings, and the pairing is an invariant of
 "migrate()" rather than something the signature can express.

 Return type:
 "None"

class lamindb_setup.evolve.MigrationReport(kept=0, matched=0, mapped=0, transformed=0, nulled=0, dropped=0, updated=0, relocated=0, notes=<factory>, write_strategy=None)

 Per-value outcome counters a migration reports back to the caller.

 The engine threads one of these onto every "MigrationContext" and
 renders "summary()" into the change details, so a "plan" dry-run
 shows *what the migration did to the data* ("12 matched, 3 mapped,
 2 dropped") rather than only whether it left values stranded.  A
 hand-written migration may leave it empty. The built-in migration
 helpers populate it.

 "kept" counts values left as they were because the new dtype
 already admits them, "matched" those that resolved against an
 existing target directly, "mapped" those redirected by an explicit
 mapping, "transformed" those rescued by a transform callable,
 "nulled" those written as the feature's null (see "NULL"), and
 "dropped" those resolved to "None" and therefore de-annotated.
 "updated" counts the values and attributes a seeded record took
 over from the plan, and "relocated" the annotations moved off a
 record the plan drops.  "notes" carries free-form lines appended
 with "note()".  "write_strategy" records which write path a
 relocation took (see "WriteStrategy").

 kept: "int" = 0

 matched: "int" = 0

 mapped: "int" = 0

 transformed: "int" = 0

 nulled: "int" = 0

 dropped: "int" = 0

 updated: "int" = 0

 relocated: "int" = 0

| write_strategy: "WriteStrategy" | "None" = None |

 note(message)

 Append a free-form line to the report.

 Return type:
 "None"

 summary()

 A one-line human summary, or "None" when nothing was recorded.

 Zero-valued counters are omitted so the line stays short; the
 notes are appended after the counters.

 Return type:
| "str" | "None" |

exception lamindb_setup.evolve.MigrationError

 Raised when a data migration fails to relocate every value.

 Applying the plan rolls back if values remain in the old store or
 point to labels outside the new dtype's registries or filters.

# Fill and map values

lamindb_setup.evolve.fill_nulls(value=DEFAULT, *, name='fill_nulls', reason='')

 A migration giving a value to every row that is null for a feature
 made non-nullable.

 Hand it to "ctx.migrate" on the *feature* whose "nullable" the plan
 turns off:

 ctx.migrate(organism, fill_nulls("unknown"))

 A row that omits the feature is null for it: lamindb stores no
 null, and the row reads as one in every tabular view of its sheet,
 an export included.  So every row of a sheet whose schema declares
 the feature is backfilled where it omits it, like "fill_missing()"
 does for a member made required, and the apply fails if one is
 left.  "value" works as there -- a value, a "(feature, row) ->
 value" callable, or "DEFAULT" for the feature's "default_value" --
 except that a null is refused: it is what the change forbids.

 Datasets validated against such a schema cannot be backfilled; see
 "accept_non_null()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.fill_missing(value=DEFAULT, *, feature=None, name='', reason='')

 A migration giving every row that omits a newly-required member a
 value.

 The declarative form of "backfill_members()", to hand to
 "ctx.migrate" on the *schema* whose optional set the plan narrows.
 Pass "feature" to scope it to one member and declare one per
 member:

 ctx.migrate(Experiment.schema, fill_missing("bla", feature="ngs_instrument"))
 ctx.migrate(Experiment.schema, fill_missing(-1, feature="replicate"))

 Omitting "value" fills every member with its own "default_value",
 and "NULL" fills it with null -- which works for a record dtype as
 much as for a scalar one, since a null annotation is an absent one
 either way:

 ctx.migrate(Experiment.schema, fill_missing())  # each member's default
 ctx.migrate(Experiment.schema, fill_missing(NULL, feature="cell_line"))

 Return type:
 "DataMigration"

lamindb_setup.evolve.map_values(*, mapping=None, transform=None, element_wise=False, name='map_values', reason='')

 A migration rewriting scalar values for a narrowed scalar dtype.

 The declarative form of "rewrite_values()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.map_to_records(*, mapping=None, transform=None, standardize=False, field=None, element_wise=False, name='map_to_records', reason='')

 A migration relocating scalar values onto existing records.

 The declarative form of "relocate_to_records()", ready to hand to
 "migrate()".  The records it maps onto must be declared in the plan
 (or already exist); the apply runs every migration after it has
 materialized the whole plan, so where in the plan file they are
 declared does not matter.

 Return type:
 "DataMigration"

lamindb_setup.evolve.map_to_str(*, mapping=None, transform=None, field=None, name='map_to_str', reason='')

 A migration rendering categorical values back to strings.

 The declarative form of "relocate_to_str()".

 Return type:
 "DataMigration"

# Remove and revalidate data

lamindb_setup.evolve.drop_values(*, name='drop_values', reason='')

 A migration deleting every value stored for the feature.

 The declarative form of "clear_values()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.drop_rows(*, name='drop_rows', reason='')

 A migration trashing the records of a record type the plan deletes.

 Declared by natural key on a "RecordType" or "Sheet" the plan no
 longer declares, whose deletion is refused while it still has
 records:

 ctx.migrate("Sheet:Experiments", drop_rows())

 It moves every record typed by it to the trash -- what deleting the
 record type does to them anyway, now stated.  Sub-types are not
 rows: one the plan does not delete in the same apply still refuses
 the deletion.

 Return type:
 "DataMigration"

lamindb_setup.evolve.revalidate_against(*, schema, reason='', narrower=False, name='revalidate_against')

 A declaration pointing the datasets a deleted schema validated at
 another.

 Declared by natural key on a "Schema" the plan no longer declares,
 whose deletion is refused while artifacts or collections were
 validated against it:

 ctx.migrate("Schema:Legacy", revalidate_against(schema=v2))

 Each artifact and collection -- and every artifact slot link --
 naming it is pointed at "schema", a plan object, a natural key or a
 uid, instead of being left on a trashed one.  Nothing is re-curated
 in place, so "schema" has to admit everything the deleted one did:
 the same members (in their order under "ordered_set") plus optional
 ones, no set flag turned on, "flexible" not turned off under
 "maximal_set", the same index, otype, itype and dtype -- and for a
 composite the same slots, each judged alike. "narrower=True" points
 them at one that admits less, which "reason" has to vouch for.  A
 sheet export stays with the deleted schema: the CSV was written
 against it.

 Return type:
 "DataMigration"

lamindb_setup.evolve.revalidate_rows(*, reason='', name='revalidate_rows')

 A declaration asking the apply to check a sheet's rows against its
 new schema.

 Hand it to "ctx.migrate" on a sheet the plan points at another
 schema -- or on a record type it promotes to a sheet -- that
 already has rows:

 ctx.migrate(samples, revalidate_rows())

 The apply curates every row against the new schema with lamindb's
 "DataFrameCurator", checks that each carries a value for every
 member the new schema requires, and goes ahead only when all of
 them validate, naming what does not otherwise.  It rewrites
 nothing: rows that do not fit have to be fixed first.  "--allow-
 data-validated-changes" does the same for every sheet at once.  The
 sheet's exports are a separate question, answered by
 "reexport_sheets()" or "keep_stale_exports()" on the same sheet.

 Return type:
 "DataMigration"

lamindb_setup.evolve.reexport_sheets(*, sheet=None, name='', reason='')

 A migration re-exporting the sheet snapshots a schema change
 invalidated.

 Hand it to "ctx.migrate" on the *schema* whose change invalidates
 them:

 ctx.migrate(BioSampleSheetSchema.schema, reexport_sheets())

 or on a *sheet* the plan points at another schema, whose exports
 were written against the old one; the new version is written
 against the new.

 Each stale export gains a new version written from the sheet's rows
 *after* the rest of the apply -- including every other declared
 migration -- has run and committed, so the new file reflects the
 migrated data.  "sheet" narrows the declaration to one sheet by
 name, for a schema several sheets use.

 Nothing is created for an export whose data did not actually
 change: lamindb deduplicates by content hash, so the re-export
 resolves to the version already stored.  If it instead resolves to
 a *superseded* version -- the rows render exactly what an older
 export holds, which a schema change and its revert produce -- the
 family is re-pointed at that version rather than growing a
 duplicate, since "(hash, key, storage)" is a database unique
 constraint.  Either way the head ends up describing the schema as
 the plan declares it.

 Unlike the other migrations, this one runs *outside* the apply
 transaction (a file write cannot be rolled back with it) and onto a
 dedicated branch that is merged into the instance only once every
 declared migration succeeded.

 Return type:
 "DataMigration"

# Accept schema changes

lamindb_setup.evolve.accept_non_null(*, reason='', name='accept_non_null')

 A declaration vouching that datasets validated with a feature hold
 no nulls for it.

 Hand it to "ctx.migrate" on the *feature* whose "nullable" the plan
 turns off:

 ctx.migrate(organism, accept_non_null(reason="every obs frame is complete"))

 A dataset validated against a schema declaring the feature may have
 held nulls for it while it was nullable, and its cells cannot be
 re-checked in place, so the change is refused while such datasets
 exist.  This declaration is the plan author vouching for them: it
 writes nothing and shows up in the diff with its "reason".  Rows of
 a sheet are backfilled instead (see "fill_nulls()").

 Return type:
 "DataMigration"

lamindb_setup.evolve.accept_index_change(*, reason='', index_name_conflict=None, name='')

 A migration accepting a change to a schema's "index" despite
 validated data.

 Hand it to "ctx.migrate" on the *schema* whose "index=" the plan
 adds, changes or removes:

 ctx.migrate(
 visium_hd_obs,
 accept_index_change(reason="every table already uses the barcode as obs index"),
 )

 Changing the index changes how every dataset the schema already
 validated would be curated now, and that cannot be re-checked in
 place, so the change is refused while such data exists.  This
 declaration is the plan author vouching that the data conforms: it
 writes nothing beyond the index itself, and shows up in the "plan"
 / "apply" output with its "reason".  A schema that has validated
 nothing needs no declaration -- "--allow-data-validated-changes"
 covers it.

 "index_name_conflict" settles the one case lamindb cannot decide
 alone.  A sheet using the schema stores its index value on
 "Record.name", so when a row already has a "Record.name" *and* a
 different value for the new index feature, one of them has to win:
 ""keep_name"" keeps the name, ""keep_feature"" takes the feature's
 value.  The other one is discarded. Without a choice the apply
 refuses and names the rows -- it never prompts.

 Return type:
 "DataMigration"

lamindb_setup.evolve.accept_flexible_change(*, reason='', name='')

 A migration accepting that a schema's "flexible" goes off despite
 validated data.

 Hand it to "ctx.migrate" on the *schema* whose "flexible=True" the
 plan turns off:

 ctx.migrate(
 var_schema,
 accept_flexible_change(reason="every var frame only carries member columns"),
 )

 Only a "maximal_set=True" schema needs it.  There, turning
 "flexible" off shrinks the admitted columns to the members, so a
 dataset that carried a column the flexible match accepted would no
 longer validate -- and that cannot be re-checked in place, so the
 change is refused while such datasets may exist.  This declaration
 is the plan author vouching for them.  Under "maximal_set=False"
 the change is applied without one, and a schema that has validated
 no dataset needs none either: "--allow-data-validated-changes"
 covers it.

 It writes nothing: what the flexible match annotated stays on the
 artifacts. Declare "drop_nonmember_annotations()" instead to remove
 it.

 Return type:
 "DataMigration"

# Handle existing metadata

lamindb_setup.evolve.drop_member_values(*, feature=None, name='', reason='')

 A migration deleting the values a removed schema member still
 holds.

 The declarative form of "clear_member_values()", to hand to
 "ctx.migrate" on the *schema* the plan removes the member from:

 ctx.migrate(Experiment.schema, drop_member_values(feature="ngs_instrument"))

 This is destructive and irreversible: the value rows have no trash
 state.  Use "keep_member_values()" to retire a member without
 touching the data.

 Return type:
 "DataMigration"

lamindb_setup.evolve.keep_member_values(*, feature=None, name='', reason='')

 A migration that retires a schema member and *keeps* its values.

 The non-destructive counterpart of "drop_member_values()": the
 schema stops declaring the member, and the values already stored
 for it stay on the rows as undeclared extra data.  Nothing is
 written and nothing is deleted -- the declaration exists to state
 that the leftover values are intended, which is what unblocks the
 removal:

 ctx.migrate(Experiment.schema, keep_member_values(feature="replicate"))

 Refused for a "maximal_set" schema: that is exactly the kind that
 does not tolerate a member it does not declare, so keeping the
 values there would invalidate the very rows carrying them.  Use
 "drop_member_values()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.drop_nonmember_annotations(*, name='', reason='')

 A migration removing what the flexible match annotated, as
 "flexible" goes off.

 The declarative form of "clear_nonmember_annotations()", to hand to
 "ctx.migrate" on the *schema* whose "flexible=True" the plan turns
 off:

 ctx.migrate(obs_schema, drop_nonmember_annotations())

 Without it the annotations stay, and the diff names the artifacts
 carrying them.  This is destructive: label links have no trash
 state.  On a "maximal_set" schema it is also the plan author's word
 that a dataset still carrying such a column may stop validating,
 which lifts the block there just as "accept_flexible_change()"
 does.

 Return type:
 "DataMigration"

lamindb_setup.evolve.keep_stale_exports(*, sheet=None, name='', reason='')

 A migration that leaves an invalidated sheet export as it is.

 The non-destructive counterpart of "reexport_sheets()": the schema
 changes and the exported snapshot keeps describing it as it was.
 Nothing is written -- the declaration exists to state that the
 stale export is intended, which is what unblocks the change:

 ctx.migrate(BioSampleSheetSchema.schema, keep_stale_exports())

 Declared on a sheet the plan points at another schema, it keeps the
 exports written against the old one.

 Reach for it when the export is a deliberate historical record
 rather than a live view of the sheet.  Note that the artifact keeps
 pointing at the changed schema through its "schema" foreign key, so
 it will read as validated against a schema it no longer satisfies.

 Return type:
 "DataMigration"

lamindb_setup.evolve.keep_values(*, name='', reason='')

 A migration that deletes a feature and *keeps* its stored values.

 The non-destructive resolution for a feature the plan no longer
 declares, to hand to "ctx.migrate" by natural key:

 ctx.migrate("FeatureType:ft/Feature:retired", keep_values())

 Nothing is written and nothing is deleted; the declaration states
 that the values outliving the feature is intended, which is what
 unblocks the deletion.  Be aware of what that leaves: the values
 stay keyed to a trashed record, so they are readable only by name
 and a later feature of the same name will not see them.

 The acceptance is recorded on the feature itself so it survives the
 deletion, which is how "repair stranded-values" knows not to report
 it.

 Return type:
 "DataMigration"

lamindb_setup.evolve.keep_validated(*, reason='', name='keep_validated')

 A declaration vouching for the datasets a schema the plan deletes
 validated.

 Declared by natural key on a "Schema" the plan no longer declares,
 whose deletion is refused while artifacts or collections were
 validated against it:

 ctx.migrate("Schema:Legacy", keep_validated(reason="superseded by v2"))

 It writes nothing: the datasets keep pointing at the schema in the
 trash, as they did before the deletion was vetted, and the diff
 shows the "reason".

 Return type:
 "DataMigration"

lamindb_setup.evolve.keep_rows(*, type=None, reason='', name='keep_rows')

 A declaration keeping the records of a record type the plan
 deletes.

 Declared by natural key on a "RecordType" or "Sheet" the plan no
 longer declares, whose deletion is refused while it still has
 records:

 ctx.migrate("Sheet:Old", keep_rows(reason="still referenced"))
 ctx.migrate("RecordType:Vocab", keep_rows(type=archive))

 Instead of going to the trash with it, every record is re-typed
 onto "type" -- a "RecordType" as a plan object, a natural key or a
 uid -- or left untyped when it is "None".  Their feature values and
 names stay as they are.  A "Sheet" is refused as "type": rows
 landing in a sheet must validate against its schema, which
 "move_rows()" checks.  So is a name already taken under "type", and
 a feature filtering on the deleted type that holds these records as
 values, since they would no longer satisfy it.

 Return type:
 "DataMigration"

# Migrate records

lamindb_setup.evolve.move_rows(*, to, reason='', index_name_conflict=None, name='move_rows')

 A declaration moving the records of a record type the plan deletes.

 Declared by natural key on a "RecordType" or "Sheet" the plan no
 longer declares:

 ctx.migrate("Sheet:Old", move_rows(to=new_sheet, reason="merged"))

 Every record is re-typed onto "to" -- a "Sheet" or "RecordType" as
 a plan object, a natural key or a uid -- instead of going to the
 trash.  Rows moving into a sheet are checked against its schema
 first, exactly as a sheet pointed at another schema is: curated,
 and each must carry every member the schema requires.  They keep
 their names, which a target sheet keyed by another index than the
 source's would have to re-key, so that is refused, and so is a name
 already taken there.  A row whose name differs from its value for
 the shared index is settled by "index_name_conflict" (""keep_name""
 or ""keep_feature""), as for an index change.  A target sheet's
 exports go stale, so it also needs "reexport_sheets()" or
 "keep_stale_exports()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.adopt_children(*, to=None, reason='', name='adopt_children')

 A declaration re-parenting the children of a type the plan deletes.

 Declared by natural key on a "FeatureType", "SchemaType",
 "RecordType" or "Sheet" the plan no longer declares, whose deletion
 is refused while sub-types, features or schemas the plan does not
 delete are typed under it:

 ctx.migrate("FeatureType:legacy", adopt_children(to=current))

 Each is moved under "to" -- a type of the same kind, as a plan
 object, a natural key or a uid -- or to the root when it is "None",
 with its uid and its own children.  A name already taken there is
 refused, and so is a child another plan manages.  A record type's
 records are rows, not children: they take "drop_rows()",
 "keep_rows()" or "move_rows()".

 Return type:
 "DataMigration"

lamindb_setup.evolve.update_record(*, values=True, description=True, reference=True, name='update_record', reason='')

 A declaration opting a seeded record into the plan's edits.

 A plan seeds its records: it creates one the instance lacks and
 otherwise leaves it alone, so a corrected annotation or description
 never reaches an instance that already has the record.  Declared on
 the record, it writes the plan's version over the instance's:

 hepatocyte = Record("hepatocyte", type=cell_types, features={"germ_layer": "endoderm"})
 ctx.migrate(hepatocyte, update_record())

 "values" writes each feature value the plan declares that differs
 from the stored one, straight into its link table or "RecordJson"
 so the row is not re-curated against a schema mid-apply;
 "description" and "reference" (with "reference_type") set those
 attributes.  Only what the plan declares is written: a feature it
 leaves out, or a "None", keeps its stored value.  Once the instance
 matches the plan the declaration is a no-op, so it can stay in
 place.

 Return type:
 "DataMigration"

lamindb_setup.evolve.drop_record(*, relocate_to=None, name='drop_record', reason='')

 A declaration trashing a seeded record the plan no longer declares.

 A plan never deletes a record it stops declaring: a vocabulary
 value's lifecycle is the instance's.  Declared by the record's
 natural key, it moves the record to the trash:

 ctx.migrate("RecordType:CellTypes/Record:hepatocite", drop_record())

 The removal is refused while other objects still hold the record as
 a categorical value -- a record's, an artifact's or a run's
 annotation. "relocate_to" -- a plan "Record", a natural key or a
 uid -- moves each of them onto that record first, which every
 annotating feature's dtype has to admit and the plan must not drop
 as well.  It is refused, too, while records still name it as their
 parent: "relocate_to" moves annotations, not children.  Once the
 record is gone the declaration is a no-op.

 Return type:
 "DataMigration"

# Fill values

lamindb_setup.evolve.NULL = NULL

 Sentinel for "this value is null".

 Distinct from "None", which every helper already reads as "do
 nothing with this row": a backfill that skipped a row leaves it
 invalid, whereas one that filled it with null answered for it.
 Nothing is stored either way -- lamindb has no null annotation, so
 an un-annotated row *is* one, for every dtype alike -- but the two
 are reported apart and only the latter settles the row.

 Refused for a feature that is not nullable, which is what makes the
 distinction more than bookkeeping.

lamindb_setup.evolve.DEFAULT = DEFAULT

 Sentinel for "write the feature's "default_value"".

 Resolved per *feature*, not per migration, so one declaration
 covers members of different dtypes.  Falls back to "NULL" for a
 nullable feature that declares no default, which is what lamindb's
 own "DataFrameCurator.standardize()" fills a missing column with.