Schema Migrations

FLYNC workspaces are stored as YAML documents whose shape is tied to a specific release of the library. When the model changes between releases, a workspace recorded by an older FLYNC may no longer map cleanly onto the installed version’s schema. The migration mechanism brings such a workspace up to date.

This mechanism operates on the raw parsed YAML documents (keyed by workspace-relative URI) before they are fed to Pydantic. Migrations therefore transform plain dictionaries, not model objects, and can be written and reasoned about independently of the model definitions.

How it works

Every workspace records the FLYNC release that last wrote it in .flync/config.yaml (the version stamp, PEP 440). On load the SDK compares that stamp with the installed FLYNC release and classifies the workspace:

State

Condition

Result

NO_VERSION

.flync/config.yaml is missing or has no version entry

Loaded as the installed schema; flync migrate --init records that (no data changed)

UP_TO_DATE

recorded == current (or nothing pending, stamp lags)

Nothing to do; stamp may be advanced

PENDING_MIGRATION

lowest_supported <= recorded < current and a chain exists

Apply migrations in order, then advance the stamp

UNSUPPORTED_OLD

recorded < LOWEST_SUPPORTED_VERSION

No path forward; re-create / re-import the workspace

NEWER

recorded > current

Refuse: a workspace from a newer FLYNC is never migrated

Migrations are keyed by the target_version (the release that introduced the change) and applied in ascending order. A migration applies when recorded < target_version <= current. Each applied migration is recorded, in order, in the append-only history manifest at .flync/migrations/history.yaml.

Safety guarantees

  • Migrations run on a deep copy of the documents; the originals are only touched once every migration in the chain succeeds.

  • Changed documents are first written to temporary files and only then swapped in, so a failure while writing leaves every document unchanged.

  • The history manifest is written atomically (temp file + os.replace), so a failure never leaves a half-written manifest.

  • The version stamp is never moved backwards, and the rest of the workspace configuration is preserved when it is advanced.

  • Saving a workspace (generate_configs or save_workspace_config) does not advance the stamp while migrations are pending or the workspace is older than LOWEST_SUPPORTED_VERSION. Saving does not migrate the documents, so the stamp keeps pointing at their actual schema until flync migrate (or auto mode) has run.

Warning

Migrated documents are re-serialized, so comments and hand-authored formatting in the documents a migration touches are lost; the order of keys is kept. The final swap of the rewritten documents is one rename per file, so an interrupted migration can still leave the workspace partly migrated, with the stamp not yet advanced. The next run then applies the whole chain again, which is why every migration must be idempotent. Commit or back up a workspace before migrating it.

  • The compatible_flync_version field (semver, user-authored) is intentionally not used as the migration baseline — it is a compatibility hint, not a format stamp.

Timing & migration_mode

By default migrations are proposed, not applied: loading a stale workspace only logs a warning. In auto mode a failing migration is logged as an error and the workspace is loaded unmigrated, with its stamp unchanged, so the migration is attempted again on the next load. Set migration_mode in .flync/config.yaml:

migration_mode: propose   # default: warn only
migration_mode: auto      # migrate before loading the model
migration_mode: off       # never check

Explicit migration is always available regardless of the mode:

flync migrate <path> --dry-run   # show what would run, change nothing
flync migrate <path>             # apply pending migrations, record history
flync migrate <path> --init      # only stamp a baseline version

For library users, Migrator orchestrates the workflow (check → plan → run), while MigrationEngine classifies a workspace and computes/executes the migration chain.

Writing a migration

Subclass FLYNCMigration, set a stable unique_id and the target_version the change ships in, and implement apply (and optionally should_apply) to transform the in-memory documents. Register it with the built-in registry via the migration() decorator.

A migration receives the workspace’s parsed YAML as a {workspace-relative URI: parsed document} mapping and mutates it in place. The engine only rewrites URIs whose content actually changed, so untouched documents keep their original formatting.

Rules for a migration:

  • target_version is a PEP 440 version; registration rejects anything else.

  • apply is idempotent: running it on documents it has already migrated leaves them unchanged.

  • should_apply is a guard, not a safety net: an exception raised in it aborts the migration run.

from flync.core.version_migrators._base import FLYNCMigration, migration


@migration
class RenameLegacyEcuField(FLYNCMigration):
    unique_id = "rename_legacy_ecu_field"     # stable & unique; stored in history.yaml
    target_version = "0.15.0"                 # release that introduced the change
    description = "Renames ECUs 'legacy_type' to 'ecu_type'."
    error_ids = ("FLYNC-ECU-MAJ-CONS-042",)   # errors from model_change_history that this fixes

    def should_apply(self, documents):
        # Optional fast-path: skip when no document has the key at all.
        return any(
            isinstance(doc, dict) and "legacy_type" in str(doc.get("ecus", ""))
            for doc in documents.values()
        )

    def apply(self, documents):
        for uri, content in documents.items():
            if not isinstance(content, dict):
                continue
            for ecu in content.get("ecus", []):
                if isinstance(ecu, dict) and "legacy_type" in ecu:
                    ecu["ecu_type"] = ecu.pop("legacy_type")

After authoring it, place the module under flync.core.version_migrators.migrations and import it from that package’s __init__ so the @migration decorator registers it. The engine then places it in the chain by target_version and applies it to any workspace older than that release.

API Reference

class FLYNCMigration

Bases: ABC

A single schema migration from an older FLYNC release to a newer one.

Subclass this, set the class attributes, and implement apply() (and optionally should_apply()). Decorate the subclass with migration() (or call MigrationRegistry.register()) so the mechanism discovers it. The base class is abstract and cannot be instantiated directly.

Attributes:
unique_id (str): Stable, globally-unique identifier for this migration (should never

change once shipped - it is written to the workspace history manifest).

target_version (str): PEP 440 FLYNC release that introduced this schema change. A

workspace older than this needs the migration applied to reach the new format.

description (str): Human-readable summary of the change, shown by flync migrate.

error_ids (tuple[str, …]): FLYNC-... error IDs from model_change_history.rst

that this migration resolves.

should_apply(documents: Dict[str, Any]) → bool

Whether this particular workspace actually needs this transform.

Runs before apply() (once the workspace is already known to be older than target_version) so migrations can be a no-op for workspaces that happen to already conform. Defaults to True; override when the trigger can be detected precisely.

Args:

documents: The parsed workspace documents, keyed by URI.

Returns:

bool: True to record the migration as applied to this workspace.

abstractmethod apply(documents: Dict[str, Any]) → None

Transform documents in place from the previous schema to target_version.

Must be idempotent: running it on documents it already migrated has to leave them unchanged. An interrupted migration rewrites some documents before the version stamp is advanced, and the next run then applies the whole chain again.

Args:
documents: The parsed workspace documents, keyed by URI. Mutate these; do not

return a new mapping. Only URIs whose content actually changes are rewritten to disk - untouched documents keep their original formatting.

class MigrationRegistry

Bases: object

Holds every FLYNCMigration and validates their invariants.

This is a singleton: MigrationRegistry() always returns the one process-wide instance (also exposed as migration_registry and populated by importing flync.core.version_migrators.migrations), so migrations registered from anywhere are visible to the engine and CLI.

Tests (or other code needing an isolated, disposable set of migrations) create an independent registry with new() and pass it explicitly to the engine.

classmethod new() → MigrationRegistry

Return a fresh, independent registry (for tests / bespoke migration sets).

register(item: FLYNCMigration | type[FLYNCMigration]) → FLYNCMigration

Register a migration (instance or class), enforcing uniqueness of ids and targets.

Args:

item: A migration class to instantiate, or an already-instantiated migration.

Returns:

FLYNCMigration: The registered (instantiated) migration.

Raises:
ValueError: If unique_id is empty/duplicated, target_version is not a PEP 440

version, or two migrations share a target_version.

get(unique_id: str) → FLYNCMigration | None

Return the migration with unique_id, or None.

all() → list[FLYNCMigration]

All registered migrations.

clear() → None

Remove all registrations (used to reset the default registry under test).

class MigrationEngine(registry: MigrationRegistry | None = None, lowest_supported: str = '0.9.0')

Bases: object

Pure decision and transform logic for schema migrations.

Args:
registry: The set of migrations to consider. Defaults to the process-global

flync.core.version_migrators._base.migration_registry.

lowest_supported: Oldest recorded release for which a migration path is guaranteed.

evaluate(recorded: BaseVersion | None, current: BaseVersion) → MigrationStatus

Classify a workspace, given its recorded version and the installed version.

Args:

recorded: Version stamp read from the workspace (None when absent). current: Installed FLYNC version.

Returns:

MigrationStatus: The classification plus the ordered chain of applicable migrations.

chain(recorded: Version, current: Version) → list[FLYNCMigration]

Return migrations that bring recorded up to current, ordered by target version.

A migration applies when recorded < target_version <= current. Sorting by target_version produces the deterministic chain the runner applies in order.

A development or pre-release build (0.16.0.dev56) counts as the release it leads to.

apply(documents: Dict[str, Any], recorded: BaseVersion, current: BaseVersion) → tuple[list[AppliedMigration], Dict[str, Any], list[str]]

Apply the required migrations to a copy of documents.

The input mapping is left untouched; the transformed copy is returned so the caller decides when (and whether) to persist it. This is what enables --dry-run.

Args:

documents: Parsed workspace documents keyed by URI. recorded: The workspace’s recorded version. current: The installed FLYNC version.

Returns:

tuple: (applied, working, changed_uris) where applied lists each run migration, working is the transformed copy, and changed_uris are the URIs whose content actually differs from the input.

class Migrator(registry: MigrationRegistry | None = None, lowest_supported: str = '0.9.0')

Bases: object

Orchestrates workspace migrations: check status, apply, or stamp a baseline.

This is the public API for both the CLI (flync migrate) and the SDK load-time policy.

Args:

registry: Override the migration registry (primarily for tests). lowest_supported: Override the lowest-supported version.

check(workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) → MigrationStatus

Determine the migration status of a workspace on disk without modifying it.

Args:

workspace_path: Root of the workspace.

workspace_config: Optional configuration; when omitted, .flync/config.yaml is

auto-discovered. Only its version is inspected.

Returns:

MigrationStatus: The classification. WorkspaceMigrationState.NO_VERSION when no configuration is given and .flync/config.yaml is missing or has no version entry. The workspace is never written to.

plan(workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) → MigrationStatus

Alias of check() - the plan for what would run (used by flync migrate --dry-run).

run(workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) → ApplicationResult

Apply pending migrations to the workspace on disk and record them in history.

This is destructive: changed documents are rewritten, the history manifest is updated and the config stamp is advanced to the installed version. It is a no-op unless the status is WorkspaceMigrationState.PENDING_MIGRATION.

Args:

workspace_path: Root of the workspace. workspace_config: Optional configuration; auto-discovered when omitted.

Returns:

ApplicationResult: Summary of what was applied.

Raises:
RuntimeError: If the workspace is unsupported (too old), from a newer FLYNC, or has no

recorded version.

apply_in_place(workspace: FLYNCWorkspace, status: MigrationStatus | None = None) → ApplicationResult

Apply pending migrations to an already-opened workspace, rewriting changed documents and recording history. Mutates workspace.documents so the caller can keep loading from them.

Args:

workspace: A workspace whose documents are opened, with migration_mode="off". status: Precomputed status; recomputed from the workspace’s configuration when omitted.

Returns:

ApplicationResult: Summary of what was applied.

static stamp(workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) → None

Record the installed FLYNC version as the workspace baseline without transforming anything.

Writes .flync/config.yaml with the current version so a workspace that has no stamp (or whose schema has not changed) stops the migration warning. flync migrate --init.

Args:

workspace_path: Root of the workspace. workspace_config: Optional configuration; auto-discovered when omitted.

class MigrationHistory(*, version: int = 1, migrations: list[MigrationRecord] = <factory>)

Bases: BaseModel

The ordered list of migrations applied to a workspace.

Parameters

versionint, optional

Schema version of the history manifest (defaults to 1).

migrationslist of MigrationRecord

The applied migrations, in the order they were applied.

applied_ids() → list[str]

Return the applied migration ids, in order.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].