## Custom migrations

Write a migration for a change that needs custom logic.

The change being applied determines which context the migration
receives.

# Migration contexts

class lamindb_setup.evolve.MigrationContext(feature, desired_dtype, live_dtype, target_registry=None, cat_filters=None, report=<factory>)

 What a "DataMigration" callable receives when it runs.

 "feature" is the *live* LaminDB "Feature" record, already flipped
 to "desired_dtype" by the engine (the dtype write must precede any
 categorical value write; the stale scalar rows survive the flip and
 remain readable).  The callable relocates / rewrites the feature's
 stored values so they validate against "desired_dtype", then
 returns; it runs inside the apply transaction, so raising rolls the
 whole apply back.

 "target_registry" and "cat_filters" are the *plan's* resolved
 target: the live registry class the new dtype points at (e.g.
 "ln.Record", "bt.CellType") and the filters narrowing it (e.g.
 "{"type__uid": ...}"). The engine resolves both from the plan
 feature's declared "LaminDType", which is the only place they
 survive intact -- "desired_dtype" is a *string*, and no registry-
 name to class resolver exists.  Both are "None" for a scalar
 target.

 "report" collects per-value outcomes for the plan preview (see
 "MigrationReport").

 target_registry: "Any" = None

| cat_filters: "dict"["str", "Any"] | "None" = None |

class lamindb_setup.evolve.DeclarationTarget(kind, answers, by_key=False)

 One kind of target a "DataMigration" can be declared for.

 A plan object of "kind" -- ""Feature"", ""Schema"", ""Sheet"" or
 ""Record"" -- or, with "by_key", the natural key of one whose leaf
 is of that kind: the only way to address an object the plan no
 longer declares. A natural key may stand in for an object target
 too, since the engine looks every declaration up by key -- that is
 how a schema no plan manages, one a deleted feature is detached
 from, is answered for.  "answers" says what a declaration attached
 there answers for, which is what an error naming a misplaced
 declaration explains.

 by_key: "bool" = False

 describe()

 "a Schema (...)" or "the natural key of a Feature (...)".

 Return type:
 "str"

class lamindb_setup.evolve.MemberMigrationContext(schema, features, report=<factory>, accepted_nulls=<factory>, *, rows_omitting)

 What a "DataMigration" attached to a *schema* receives.

 The counterpart of "MigrationContext" for the other narrowing a
 plan can declare a migration for: making an optional schema member
 required again. Nothing about a feature's dtype changes; what has
 to be fixed up is the rows that omitted the member, since those are
 what the block exists to protect.

 "schema" is the live LaminDB "Schema", its optional set already
 narrowed by the engine, and "features" are the live members it no
 longer marks optional.  The callable annotates every row that lacks
 one of them -- "missing()" enumerates exactly those -- and returns;
 the engine then re-counts them and fails the apply if any is left,
 so a partial backfill rolls back rather than silently invalidating
 records.

 A row backfilled with null is the one exception.  lamindb has no
 stored null -- "add_values" skips a "None", a categorical value is
 a foreign key, and both JSON stores are "NOT NULL" columns -- so an
 un-annotated row *is* a null one, whatever the member's dtype.  A
 migration that filled a row with null says so with "accept_null()",
 which exempts that row from the re-count; a row merely left alone
 is not exempted and still fails the apply.

 "report" collects per-row outcomes for the plan preview (see
 "MigrationReport").  "rows_omitting" is the engine's query behind
 "missing()", supplied by whoever constructs the context.

 accept_null(feature, row)

 Declare that "row" deliberately holds no value for "feature".

 Recorded per "(feature, row)" rather than per feature, because a
 backfill may fill some rows with a real value and leave only the
 rest null; only the rows named here are exempted from the
 engine's re-count.

 Return type:
 "None"

 missing(feature)

 The rows validated by "schema" that carry no value for
 "feature".

 Spans every registry a schema validates rows of ("Record",
 "Artifact", "Collection") and every composite schema that embeds
 this one, matching what the engine counts when it checks the
 backfill succeeded.

 Return type:
 "list"["Any"]

class lamindb_setup.evolve.MemberRemovalContext(schema, features, report=<factory>, kept=<factory>, *, rows_carrying)

 What a "DataMigration" attached to a schema *losing* a member
 receives.

 The third narrowing a plan can declare a migration for.  Removing a
 member changes nothing about the rows themselves -- it is the
 schema that stops declaring the feature -- so what has to be
 answered for is the values already stored for it, which no longer
 belong to anything the schema describes.

 "schema" is the live LaminDB "Schema", the member already unlinked
 by the engine, and "features" are the live features it no longer
 declares.  The callable clears the values those members hold on the
 rows the schema validates -- "carrying()" enumerates exactly those
 -- and returns; the engine then re-counts them and fails the apply
 if any is left.

 A migration that deliberately *keeps* the values (they stay on the
 rows as undeclared extra data) is exempt from that re-count; it
 says so with "DataMigration(keeps_values=True)", which
 "keep_member_values()" sets.

 "report" collects per-row outcomes for the plan preview (see
 "MigrationReport").  "rows_carrying" is the engine's query behind
 "carrying()", supplied by whoever constructs the context.

 keep(feature)

 Declare that "feature"'s stored values are deliberately left in
 place.

 Exempts it from the post-check that otherwise requires a removed
 member's values to be gone.  Stated per member rather than per
 migration because the declarations are not matched to members: a
 schema dropping two of them may keep one and delete the other.

 Return type:
 "None"

 carrying(feature)

 The rows validated by "schema" that hold a value for "feature".

 The exact complement of "MemberMigrationContext.missing()", over
 the same registries ("Record", "Artifact", "Collection") and the
 same composite closure, and what the engine re-counts to check
 the drop succeeded.

 Return type:
 "list"["Any"]

class lamindb_setup.evolve.IndexChangeContext(schema, previous, index, report=<factory>)

 What a "DataMigration" attached to a schema whose *index* changes
 receives.

 The fifth narrowing a plan can declare a migration for, and the
 only one with nothing to rewrite.  "Schema.index" marks which
 member identifies a row, so adding, changing or removing it changes
 how every dataset the schema already validated would be curated now
 -- and that cannot be re-checked in place.  The declaration is the
 plan author vouching that the data conforms (see
 "accept_index_change()").

 "schema" is the live LaminDB "Schema", its index already switched
 by the engine.  "previous" and "index" are the live index features
 before and after, either of which is "None" when the schema had,
 respectively has, no index.  It runs inside the apply transaction,
 like the member narrowings.

 "report" collects notes for the diff (see "MigrationReport").

class lamindb_setup.evolve.FlexibleChangeContext(schema, previous, flexible, report=<factory>, *, recorded_nonmembers)

 What a "DataMigration" attached to a schema turning "flexible" off
 receives.

 While "flexible" was on, curating a dataset against the schema also
 validated and annotated every column whose name matched a
 registered feature: each such column is listed among the columns
 the artifact records for the slot, and a categorical one carries
 label links.  Turning the flag off changes none of that.  Under
 "maximal_set=True" it is refused as well, since a dataset carrying
 such a column would no longer validate.

 Two declarations answer for it: "accept_flexible_change()" keeps
 the annotations and, on a "maximal_set" schema, vouches for the
 data; "drop_nonmember_annotations()" removes them.

 "schema" is the live LaminDB "Schema", its flag already switched;
 "previous" and "flexible" are the values before and after.
 "nonmember_columns()" lists what is left to answer for.  It runs
 inside the apply transaction, like the member narrowings.

 "report" collects notes for the diff (see "MigrationReport").
 "recorded_nonmembers" is the engine's query behind
 "nonmember_columns()", supplied by whoever constructs the context.

 nonmember_columns()

 Every artifact slot "schema" curated whose recorded columns it
 does not declare.

 One entry per artifact and slot -- "columns" for a dataframe the
 schema validated itself, else the composite's slot -- with the
 "artifact", the "slot", the "link" row recording its columns,
 the "recorded" schema that row points at and the non-member
 "features" it lists.  Trashed artifacts are left out.

 Return type:
 "list"["Any"]

class lamindb_setup.evolve.FeatureRemovalContext(feature, report=<factory>)

 What a "DataMigration" attached to a *deleted* feature receives.

 The plan has stopped declaring the feature altogether, so the
 removal pass is about to move it to the trash.  Trashing detaches
 nothing: the values stay keyed to it, invisible to every query that
 goes through a live feature, while "get_values()" still reports
 them by name -- and a feature of the same name declared later is a
 different record, so the history splits in two.

 "feature" is the live LaminDB "Feature", still on its branch: the
 migration runs before the deletion, so everything it reads is still
 there. Only the two attributes "clear_values()" needs, which is
 what lets "drop_values()" serve this case unchanged.

 Declared by natural key, since there is no plan object left to
 name:

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

class lamindb_setup.evolve.RecordTypeRemovalContext(record_type, report=<factory>, *, live_rows)

 What a "DataMigration" attached to a *deleted* record type
 receives.

 The plan has stopped declaring a "RecordType" or "Sheet" that still
 has records -- a sheet's rows, a vocabulary's values -- and
 lamindb's trash cascades to every one of them.  The removal is
 refused until the plan says what should become of them, declared by
 natural key like a deleted feature:

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

 "record_type" is the live record type, still on its branch: the
 migration runs before the deletion.  "rows()" lists its records
 that are not in the trash, sub-types left out.

 rows()

 The records typed by "record_type" that are not in the trash.

 Return type:
 "Any"

class lamindb_setup.evolve.SchemaRemovalContext(schema, report=<factory>)

 What a "DataMigration" attached to a *deleted* schema receives.

 The plan has stopped declaring a schema that artifacts or
 collections were validated against.  Trashing it leaves them
 pointing at a trashed schema, which no longer describes them for
 anyone querying live schemas, so the removal is refused until the
 plan vouches for that:

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

 "schema" is the live schema, still on its branch.

class lamindb_setup.evolve.SheetExportContext(schema, exports, report=<factory>, written=<factory>, promotions=<factory>, branch_factory=None, _branch=None, *, reexport, current_branch)

 Context for rewriting stale sheet exports after a schema migration.

 The fourth narrowing a plan can declare a migration for, and the
 only one whose subject is not stored *in* the database.  A sheet
 export is a CSV already written to storage. Renaming or retyping a
 member, or adding a required one, leaves the file describing the
 previous schema even though its "schema" foreign key points to the
 updated schema.

 "schema" is the live LaminDB "Schema", already reconciled to the
 plan, and "exports" the snapshots the change invalidated -- each
 naming its sheet, the artifact at the head of its version family,
 and why it no longer adheres. "write()" produces the new version.

 Two things set this context apart from the other three, and a hand-
 written migration has to respect both:

 * **It runs after the apply transaction has committed.** A file
 write cannot be rolled back with the database, so raising here
 does not undo the schema change -- it leaves "branch" unmerged
 and fails the command.

 * **Everything it creates lands on :attr:`branch`**, a branch
 merged into the instance only once every declared migration
 succeeded.  Write through "write()" (or pass "branch=self.branch"
 yourself), or the new version becomes visible before the run that
 produced it is known to be good.

 "branch" is created on first access rather than up front, so a
 migration that writes nothing -- "keep_stale_exports()", or a hand-
 written one that decides against it -- leaves no empty branch
 behind (lamindb never deletes them).

 "report" collects per-export outcomes for the diff (see
 "MigrationReport").  "reexport" and "current_branch" are the engine
 operations behind "write()", supplied by whoever constructs the
 context.

| branch_factory: "Callable"[[], "Any"] | "None" = None |

 property branch: Any

 The branch new export versions are written onto, created on
 demand.

 write(export)

 Write a new version of "export" from the sheet's current rows.

 Returns the saved artifact, which is the *existing* one when the
 rows hash to the content already stored -- lamindb deduplicates
 by hash, so an export that did not actually change gains no
 version, and nothing is recorded in "written".  That is the
 property a declaration relies on to be safe to leave in a plan
 forever.

 The same deduplication has two failure modes, because its lookup
 is scoped by neither key, branch, nor "is_latest": :rtype: "Any"

 * it can resolve onto a version an earlier, *failed* run parked
 on another re-export branch -- same content, stranded where
 the merge cannot reach it.  That one is adopted onto this
 run's branch.

 * it can resolve onto a **superseded** version of the family,
 when the rows happen to render exactly what some older export
 holds (a schema change and its revert, say).  Nothing promotes
 that row, so the head would keep its stale content while this
 reported a re-export.  The family already holds the right
 bytes, so the fix is to re-point it -- recorded in
 "promotions" and applied *after* the merge, since it touches
 the instance's own branch and must not become visible before
 the run succeeds.

 An artifact already on the instance's own branch is otherwise
 left alone. Moving it here would take a live artifact *off* the
 branch every query sees, to hand it back at the merge -- and to
 hide it permanently if this run failed in between.  A file write
 that cannot be rolled back must never be able to remove
 something that was already there.

class lamindb_setup.evolve.RecordUpdateContext(record, values=<factory>, fields=<factory>, report=<factory>)

 What a "DataMigration" attached to a *seeded* record receives.

 A plan seeds its records. To apply edits to an existing record,
 declare an update:

 ctx.migrate(record, update_record())

 "record" is the live record.  "values" maps each live "Feature"
 whose stored value differs from the one the plan declares to that
 declared value, and "fields" each descriptive attribute that
 differs to the plan's.  Only what the plan declares is compared: a
 feature it leaves out, or declares as "None", keeps its stored
 value.

class lamindb_setup.evolve.RecordRemovalContext(record, relocate_to=None, report=<factory>, *, value_links)

 What a "DataMigration" declared for a record the plan *drops*
 receives.

 A seeded record the plan stops declaring stays on the instance.
 Declaring its removal by natural key moves it to the trash, which
 is refused while other objects still hold it as a categorical
 value:

 ctx.migrate("RecordType:Vocabulary/Record:obsolete", drop_record())

 "record" is the live record, still live: the migration runs before
 it is trashed.  "relocate_to" is the live record its annotations
 move onto, or "None".  "links()" lists the link rows that still
 name "record" as their value, one queryset per link table.

 relocate_to: "Any" = None

 links()

 The link rows naming "record" as their value, per link table.

 Return type:
 "list"["Any"]

# Migration helpers

lamindb_setup.evolve.backfill_members(context, /, value=DEFAULT, *, feature=None)

 Annotate every row that omits one of the schema's newly-required
 members.

 "value" is either the value to write for every such row, or a
 callable receiving "(feature, row)" and returning one -- returning
 "None" leaves the row alone, which then fails the apply, since the
 engine requires the backfill to cover every row.

 Two sentinels stand for a value the *feature* defines rather than
 the declaration, and either may equally be returned from the
 callable, so a backfill can decide row by row: :rtype: "None"

 * "DEFAULT" (the default) fills the row with the member's
 "default_value", falling back to null when it declares none --
 the same order lamindb's own "DataFrameCurator.standardize()"
 fills a missing column in.  One declaration therefore covers
 members of different dtypes.

 * "NULL" fills the row with null.

 Both are refused for a member that is not nullable and defines no
 default, since a null there would not validate.  A null is not
 *written*: lamindb has no stored null -- "add_values" skips one, a
 categorical value is a foreign key, and the JSON stores are "NOT
 NULL" -- so an un-annotated row is what a null member looks like,
 whatever its dtype.  The row is instead declared settled with
 "accept_null()", which is what exempts it from the engine's post-
 check; a row merely left alone (the callable returning "None")
 still fails the apply.

 "feature" narrows this to the member of that name, so a schema
 narrowing several members can take one declaration per member (with
 a value of the right dtype for each) instead of one callable
 branching on the feature.  A name that is not among the newly-
 required members is a no-op, which is what keeps such a declaration
 idempotent once its member has been settled.

 The write deliberately bypasses "add_values": that re-curates the
 *whole* row against its type's schema, which a backfill by
 definition cannot satisfy yet -- it is running precisely because
 the row does not, and a row missing two required members would have
 its first repair rejected for still missing the second.  One
 annotation is one row in the feature's value table, so it is
 written there directly.

lamindb_setup.evolve.clear_values(context, /)

 Delete every value stored for the feature, scalar and categorical
 alike.

 The blunt instrument for a change no mapping can express: the
 feature keeps its identity and its new dtype but starts out
 unannotated.  Serves the feature's *deletion* too (see
 "FeatureRemovalContext"), where the point is that nothing is left
 keyed to a record about to be trashed.

 Return type:
 "None"

lamindb_setup.evolve.clear_member_values(context, /, *, feature=None)

 Delete the values a schema's removed members hold on the rows it
 validates.

 "feature" narrows this to the member of that name, so a schema
 dropping several members can take one declaration per member.  A
 name that is not among the removed members is a no-op, which is
 what keeps such a declaration idempotent once its member is gone.

 Only the rows *this* schema validates are touched (see
 "carrying()").  The same feature may hold values on rows some
 *other* schema validates, and those are that schema's business --
 deleting them here would invalidate it.

 A value row annotating several objects at once ("JsonValue", shared
 across the artifacts and runs it is linked to) is only *unlinked*
 from the objects in scope; the row survives for the rest.  Every
 other store holds one annotation per row, so there the row itself
 goes.

 Return type:
 "None"

lamindb_setup.evolve.clear_nonmember_annotations(context, /)

 Remove what the flexible match annotated on the artifacts a schema
 curated.

 Brings every artifact "nonmember_columns()" lists to what curating
 it against the schema with "flexible" off records: :rtype: "None"

 * the slot's recorded columns are re-pointed to a schema of the
 member columns alone -- the live one lamindb keeps for that
 content, or a new one, built as lamindb's own "annotate_artifact"
 builds it.  A slot left with no column loses its record.  The
 schema it recorded before is not edited, since other artifacts
 may record it too.

 * the label links of the non-member features are deleted, unless
 the artifact still records the feature in another slot or a
 schema it is validated against declares it: that annotation is
 not the flexible match's.

 Scalar values are left alone: curation writes none for a slot's
 columns, so any stored there were annotated some other way.

lamindb_setup.evolve.relocate_to_records(context, /, *, mapping=None, transform=None, standardize=False, field=None, element_wise=False)

 Relocate a feature's scalar values onto existing records ("str" ->
 "cat").

 Reads every stored scalar value (both stores), resolves each
 distinct one to a record of the plan's target registry, then
 rewrites the annotations onto the categorical store.  See the
 module docstring for the resolution chain and for why targets must
 already exist.

 "field" overrides the field records are matched on (defaulting to
 the registry's name field); "standardize" additionally resolves
 synonyms before a value is considered unmatched.

 "element_wise" maps each element of a stored list onto a record,
 for a "list[cat[...]]" target ("list[str] -> list[cat[...]]"); a
 single value is mapped as a list of one.

 "mapping" / "transform" may answer with "NULL" or "DEFAULT" for a
 nullable feature, which leaves the row un-annotated -- lamindb's
 way of spelling a null -- rather than mapping it onto a record.

 Return type:
 "None"

lamindb_setup.evolve.relocate_to_str(context, /, *, mapping=None, transform=None, field=None)

 Relocate a feature's categorical values to strings ("cat" ->
 "str").

 Renders each linked label as text (its name field, or "field") and
 rewrites the annotation into the scalar store.  Every label
 renders, so no value is ever unmatched: "mapping" and "transform"
 are pure rewrites here, and "None" still drops the annotation,
 while "NULL" / "DEFAULT" null it out / substitute the feature's
 default.

 Return type:
 "None"

lamindb_setup.evolve.rewrite_values(context, /, *, mapping=None, transform=None, element_wise=False)

 Rewrite a feature's scalar values for a narrowed scalar dtype.

 Each distinct value is coerced to the target dtype; one that will
 not coerce goes through "mapping" / "transform" exactly as
 elsewhere, so "transform=lambda _: None" drops the offending
 values, "transform=lambda _: 0" replaces them, and
 "transform=lambda _: NULL" nulls them out.

 "element_wise" coerces each element of a list to a "list[...]"
 target's element dtype instead ("list[str] -> list[int]"); a single
 value becomes a list of one, and an element answered with "None" is
 left out of its list.

 Return type:
 "None"