Skip to main content

Schema Evolution

As your application (or library) grows and evolves, you may need to modify the structure of your SharedTree data. SharedTree makes it possible to update your schemas while preserving existing documents and supporting other deployed application versions (see understanding compatibility). Depending on the schema changes, either an older or a newer client may need to upgrade a document created with another version of the schema before using it. Write a test using snapshotSchemaCompatibility to verify the compatibility you require.

note

For detailed information about which types of changes are safe versus breaking, see types of schema changes.

Stored vs View Schema​

When updating your schema, it's important to understand the difference between the two types of schemas:

  • View Schema: The schema defined in your application code using SchemaFactory
  • Stored Schema: The schema persisted with each document. It describes what type of tree can be stored in the document.

When a document is first created, its stored schema is derived from the view schema and its configured staged-upgrade policy. Later changes to application code do not change that stored schema until a client explicitly upgrades the document. The upgrade combines the view's requested additions with the document's existing stored schema.

Stored Schema Invariants​

The stored schema follows additional constraints that don't apply to view schemas:

1. Complete Description The stored schema completely describes all possible data in the tree. Every node and field in the document is known to the stored schema.

2. Additive Only The stored schema can grow over time but cannot shrink. Upgrades must continue to permit all content allowed by the existing stored schema. For example, when a view removes an optional field and allows unknown optional fields, upgrades retain that field, its allowed types, and the node definitions it needs. Removing the declaration therefore does not remove its data from existing documents.

3. Field Key Stability Stored field keys identify fields independently of their property names in application code. You can therefore rename a property while keeping its stored key to continue accessing the same field. Conversely, reusing that key with an incompatible definition still changes the existing field; it does not create a new field or bypass compatibility checks.

Why These Constraints?​

It's assumed that a Fluid application developer does not have absolute control over all user documents. Documents can persist for an unbounded length of time before they are re-opened by an application. Therefore, a Fluid application should be prepared to encounter any version of a document, even a very old one, and handle it appropriately.

Schema Compatibility​

When you open a document, SharedTree compares your application's view schema with the document's stored schema to determine compatibility:

  • Viewable: The view can read and edit the document using its current stored schema.
  • Upgradeable: The view's requested additions can be composed with the stored schema into a safe target that the view can read and edit. Apply that target with view.upgradeSchema().
  • Incompatible: The view can neither read and edit the document nor upgrade it to a compatible target.

To access the document's data, use a view that can already read and write it, or apply a permitted upgrade first. Accessing tree data through a view that is not compatible with the stored schema throws an error.

Initially, a document's stored schema is created to match the view schema at the time of creation, and therefore the view schema is compatible with the stored schema. However, later on the application might change the view schema. Such a change might be backwards compatible, forwards compatible, or neither or both.

Understanding Compatibility​

Backwards Compatibility​

A change to the view schema is backwards compatible if the new view can read and edit documents created with the earlier schema, either directly or after a permitted upgrade. An upgrade preserves existing content, but allowing additional content can affect whether other clients can use the document.

If a change is made that is not backwards compatible, then existing documents will "break", that is, they can no longer be loaded by the application.

Forwards Compatibility​

A change to the view schema is forwards compatible if the earlier view can read and edit documents created or upgraded with the later schema, either directly or after a permitted upgrade. An upgrade requested by an older client follows the same rules as one requested by a newer client: it must continue to allow all content permitted by the existing stored schema and produce a schema the requesting view supports. It is therefore not a downgrade of the document, even though the requesting application code is older.

If a change is made that is backwards compatible, but not forwards compatible, then old versions of the application will "break" when trying to load newer/upgraded documents. To prevent this, the application can employ a staged rollout.

Schema Change Examples​

😎 Chill​

Backwards CompatibleForwards CompatibleRollout Process
✅✅Normal

Examples:

  • Adding an optional field to an object when the older view already allows unknown optional fields.
  • Removing an optional field from an object that allows unknown optional fields.

🌶 Spicy​

Backwards CompatibleForwards CompatibleRollout Process
✅❌⚠️ Staged

Examples:

👮 Go to Jail​

Backwards CompatibleForwards CompatibleRollout Process
❌❌🚫 Forbidden

Examples:

  • Adding/removing a required field
  • Removing an allowed type from a field
  • Renaming a node identifier

Checking Compatibility​

Use TreeView.compatibility to check if your schema changes are compatible with existing documents.

Generally, the most important properties of the compatibility object to monitor are canView and canUpgrade. canView indicates that the view schema is compatible with the stored schema while canUpgrade indicates that it is valid to upgrade the schema.

Use these flags together when opening a document: if canView is false but canUpgrade is true, apply the upgrade before accessing the view's data. A true canUpgrade means that it is possible to upgrade the schema in a way that preserves existing content and supports the requesting view; it does not necessarily mean that an upgrade is required or that calling upgradeSchema() will change the stored schema.

To check compatibility across releases, use snapshot validation in addition to document-loading checks. The current view must be able to use documents from every historical snapshot, either directly or after an upgrade. For historical versions within minVersionForCollaboration, the reverse must also hold: those views must be able to view or upgrade documents created with the current schema.

important

Snapshots describe schema declarations, and the validator evaluates all of them with the currently installed version of the Fluid Framework libraries. It does not run the library versions deployed with historical clients. A historical view's canUpgrade result therefore does not establish that an older client's runtime can perform that upgrade. Use mixed-runtime integration tests to verify this before relying on upgrade-based collaboration.

Passing snapshot validation does not apply upgrades for your application or test every feature-flag configuration. The snapshot helpers currently assume restrictive staging, so supplement them with live-document tests for other policies and for code that calls upgradeSchema() when viewing requires it.

Monitoring Remote Schema Changes​

In collaborative applications, other clients may upgrade the document's schema while you're working. Listen for the schemaChanged event to handle these remote upgrades:

// Monitor for remote schema changes
view.events.on("schemaChanged", () => {
// Check view.compatibility here and handle accordingly
});

Schema Upgrade Process​

When you make backwards compatible changes to your schema, you can upgrade existing documents to use the new schema using view.upgradeSchema():

import { SchemaFactory, TreeViewConfiguration } from "@fluidframework/tree";

const factory = new SchemaFactory("WhiteboardApp");

// Updated schema with new optional field
class Note extends factory.object("Note", {
id: factory.string,
x: factory.number,
y: factory.number,
color: factory.optional(factory.string), // New optional field
}) {}

// Create tree view with updated schema
const config = new TreeViewConfiguration({ schema: Note });
const view = tree.viewWith(config);

// Check compatibility and upgrade if needed
if (!view.compatibility.canView) {
if (view.compatibility.canUpgrade) {
view.upgradeSchema(); // Upgrade document to new schema
console.log("Document upgraded successfully");
} else {
throw new Error("Schema is incompatible and cannot be upgraded");
}
}

// Now you can use the upgraded document
view.root.color = "#FF0000";

For detailed information about which types of changes are safe versus breaking, see Types of Schema Changes.

Removing Optional Fields and Rolling Back Code​

Rolling back a release or retiring an experimental feature can leave documents containing fields that the application no longer declares. If the fields are optional, a view that enables allowUnknownOptionalFields can treat them as unknown fields and continue to use the document. This option defaults to true and can be configured at the factory or object level.

For example, consider an application with a Task object schema.

import { SchemaFactory, TreeViewConfiguration } from "@fluidframework/tree";

const factory = new SchemaFactory("TaskApp");

// Original application schema.
class Task extends factory.object(
"Task",
{ title: factory.string },
) {}

A subsequent release adds an optional notes field to the Task schema.

class Task extends factory.object("Task", {
title: factory.string,
notes: factory.optional(factory.string), // New
}) {}

If that release is later rolled back, clients return to the original Task declaration without notes. They can still read and edit title in documents that contain notes, but cannot access notes through their view's properties. Further compatible upgrades preserve notes in the document's schema.

New documents created after the rollback have a different history: their stored schema has never included notes. A client that still declares the field must first upgrade such a document to use it. The two histories therefore differ as follows:

Document historyResult
Created with notes, then opened by the reduced viewThe notes field is retained in the document, and it is treated as unknown content by the view.
Created with the reduced viewThe initial stored schema has no notes field. A client that declares notes must add its field schema through an upgrade before viewing.
Runtime prerequisite

Before relying on older clients to upgrade while retaining unknown optional fields, first deploy a version of the application that uses Fluid Framework library version 3.14.0 or higher. Wait until every supported client in the collaboration window has that support before removing or replacing fields that require it. Rolling back application schema must not also roll back the required runtime support.

Keeping unknown fields in the document does not make them visible to application code that copies a node's properties. When cloning nodes, use TreeBeta.clone() to preserve those fields rather than reconstructing nodes from visible properties. See allowUnknownOptionalFields for related import and export limitations.

caution

A field's stored identifier (its stored key) is permanent in existing documents. Removing the field from a view does not free that identifier for reuse with an incompatible definition.

For example, suppose a later version of Task declares notes: factory.optional(factory.array(factory.string)) using the same stored key as the original optional string field. That view cannot load or safely upgrade documents whose stored schema still permits the original string-valued notes field. This conflict exists even if the document contains no data under the old notes definition, because the stored schema still permits strings that another client could write later.

Use a different stored key for a different, incompatible field.

To detect such conflicts before releasing a schema change, keep historical schema snapshots and use snapshotSchemaCompatibility tests.

Staged Schema Upgrades​

A staged schema upgrade is a schema change that is declared in the view schema but excluded from stored schema until explicitly enabled. This allows your application code to understand and handle the new schema shape (reading documents that contain it) before the upgrade is activated for writes.

SharedTree provides two mechanisms for defining staged schema upgrades:

  • staged() -- marks a new allowed type as staged
  • stagedOptional() -- marks a field as optionally present during migration from required to optional

Staged schema upgrades are the building blocks of staged rollouts and feature-flag-driven upgrades.

Staged Rollouts​

When deploying schema changes in production, use staged rollouts to ensure compatibility between clients running different application versions. Specifically, staged rollouts allow you to handle changes that are backwards compatible but not forwards compatible.

Why Staged Rollouts Are Necessary

In collaborative applications, multiple users with different client versions may work on the same document simultaneously. If a client upgrades a document to a new schema that older clients cannot read, those users will be locked out until they update their application.

Two-Phase Deployment Strategy

Phase 1: Deploy Schema Reading Support

  • Deploy application versions that can read the new schema without upgrading documents.
  • Monitor deployment metrics to ensure all (or "tolerably most") users have updated to the new application version. This is called client saturation.

Phase 2: Enable Document Upgrades

  • Deploy code that automatically upgrades documents to the new schema.
  • Monitor for any compatibility issues.

Alternatively, you can use feature flags to combine both phases into a single deployment and control when upgrades are enabled at runtime.

Changes that are both backwards compatible and forwards compatible are capable of cross-version collaboration without requiring a staged rollout. In that case, new clients can read and write to the same document as old clients without either one being fundamentally incompatible. However, staged rollouts are not easily avoidable. Even seemingly simple schema changes (for example, adding a new type of node to a field) may not be forwards-compatible, cannot support cross-version collaboration and therefore require a staged rollout.

Best Practices:

  • Allow appropriate amount of time between release cycles to ensure client version adoption
  • Monitor client version distribution before enabling upgrades
  • Test compatibility scenarios with mixed client versions

See Also​