This is an automated email from the ASF dual-hosted git repository.

XiaoHongbo-Hope pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new ffb1b7a71f [python] Evolve LeRobot schemas when appending datasets 
(#11080)
ffb1b7a71f is described below

commit ffb1b7a71f1a6f93a1cc0d35f1400b73e9509636
Author: Zouxxyy <[email protected]>
AuthorDate: Wed Nov 11 04:51:01 2026 +0800

    [python] Evolve LeRobot schemas when appending datasets (#11080)
---
 docs/docs/pypaimon/lerobot.md                      |  24 ++-
 .../pypaimon/multimodal/lerobot/aggregate.py       |  58 +++---
 .../pypaimon/multimodal/lerobot/schema.py          |  26 +++
 .../pypaimon/tests/lerobot_aggregate_test.py       | 201 ++++++++++++++++++++-
 4 files changed, 274 insertions(+), 35 deletions(-)

diff --git a/docs/docs/pypaimon/lerobot.md b/docs/docs/pypaimon/lerobot.md
index 0e0e4f12c0..df33b2b306 100644
--- a/docs/docs/pypaimon/lerobot.md
+++ b/docs/docs/pypaimon/lerobot.md
@@ -110,13 +110,18 @@ require an import option.
 
 `schema_evolution=True` is the default. The importer plans the union of source
 columns before creating `_frames` and any declared extra `_datasets` columns.
+For appends, it compares the incoming columns with the existing table group and
+adds new nullable columns. Existing rows read as null in those columns; 
incoming
+rows receive nulls for omitted optional columns. Existing optional columns are
+made nullable when necessary. All three component schemas are checked before
+catalog changes, and existing field IDs are preserved.
 Merged `_episodes` keeps its fixed typed controls and JSON group columns;
 source-specific keys remain inside those JSON values.
 Missing columns receive typed nulls. Optional columns become nullable; source
 indices, timestamps, task indices, and required Episode controls remain 
required.
 Common columns must have identical types, and common frame features must retain
 their dtype, shape, and names. Type promotion and nested schema changes are
-rejected before creating tables.
+rejected before creating or altering tables.
 
 ```python
 conn.load_from_lerobot(
@@ -134,7 +139,9 @@ feature statistics combine only sources with that feature.
 
 With `schema_evolution=False`, the first source defines the columns. Later
 sources may omit optional columns, which still receive nulls, but adding a 
column
-is rejected. This applies to the sources of one import into a new table group.
+is rejected. For appends, the existing tables define the allowed columns 
instead
+of the first incoming source. The setting does not allow type or tensor-shape
+changes in either workflow.
 
 Readers return `None` for missing features. The built-in training batch reader
 keeps columns containing missing features as lists with `None` entries; fully
@@ -178,16 +185,23 @@ rejected before creating target tables. Training readers 
project only required
 source metadata and skip extra text columns.
 
 Append another Dataset to a source-local group with `append_to_lerobot`.
-To make a one-source group appendable, import it as a one-element list:
+Create the group by importing a list, including a one-element list for one 
source:
 
 ```python
-conn.load_from_lerobot("robot_merged", ["/data/source_a"])
-conn.append_to_lerobot("robot_merged", "/data/source_b", 
tag_name="after-append")
+conn.load_from_lerobot("robot_merged", ["/data/source_a", "/data/source_b"])
+conn.append_to_lerobot("robot_merged", "/data/source_c", 
tag_name="after-append")
 ```
 
+If source C adds `humidity`, the append adds that column to `_frames`, keeps A
+and B, and reads their humidity values as null. New `extra_dataset_fields` 
columns
+are added to `_datasets` in the same way; omitted extra fields receive nulls.
+Pass `schema_evolution=False` to `append_to_lerobot` to reject new columns.
+
 If a process stops between component commits, call
 `conn.recover_lerobot_append("robot_merged")` before retrying. This rolls
 unfinished Frame and Episode commits back to the Dataset metadata boundary.
+Nullable columns added before a failed append remain in the schema and are
+reused on retry.
 
 For FileIO URIs, pass credentials through `source_options`:
 
diff --git a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py 
b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
index 1cc8f014bd..81bc3ca74b 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
@@ -36,8 +36,8 @@ from pypaimon.multimodal.lerobot.metadata import (
     _source_episode_tables, _validated_episode_tables,
 )
 from pypaimon.multimodal.lerobot.schema import (
-    _V3_REQUIRED_FEATURE_DTYPES, _merge_schemas,
-    _require_v3, _schema_from_info, _validate_v3_required_features,
+    _V3_REQUIRED_FEATURE_DTYPES, _merge_schemas, _plan_schema_evolution,
+    _require_v3, _schema_from_info, _validate_lerobot_schema, 
_validate_v3_required_features,
     _video_feature_names,
 )
 from pypaimon.multimodal.lerobot.source import (
@@ -87,11 +87,6 @@ def _json_table(table):
     return {row["key"]: json.loads(row["value"]) for row in table.to_pylist()}
 
 
-def _same_fields(left, right):
-    return len(left) == len(right) and all(
-        a.equals(b, check_metadata=False) for a, b in zip(left, right))
-
-
 def _recover_incomplete_append(connection, table_name):
     """Restore component snapshots to the Dataset table's committed counts."""
     from pypaimon.multimodal.lerobot.dataset import (
@@ -591,7 +586,7 @@ def _import_sources(connection, table_name, sources, 
batch_size, options,
                         "recover_lerobot_append before appending." % name)
             existing = (table, tables, source_rows, ranges)
         metadata, stats = _plan_merge(
-            plans, extra_dataset_fields, schema_evolution,
+            plans, extra_dataset_fields, schema_evolution if existing is None 
else True,
             source_rows if existing is not None else None)
         target_schema = metadata["frame_schema"]
         target_schema = target_schema.append(
@@ -604,32 +599,45 @@ def _import_sources(connection, table_name, sources, 
batch_size, options,
         else:
             table, tables, source_rows, ranges = existing
             first_info = ranges[0][0]
+            old_features = {}
+            for source in source_rows:
+                
old_features.update(_feature_contract(json.loads(source["info"])["features"]))
             for ordinal, plan in enumerate(plans):
                 for key in ("codebase_version", "robot_type"):
                     if first_info.get(key) != plan["info"].get(key):
                         raise ValueError(
                             "LeRobot source %d has incompatible info.%s."
                             % (ordinal, key))
-                old_features = _feature_contract(first_info["features"])
                 new_features = _feature_contract(plan["info"]["features"])
-                if old_features != new_features:
-                    raise ValueError(
-                        "LeRobot source %d has incompatible training features."
-                        % ordinal)
-            if not _same_fields(target_schema, 
_target_schema(table.raw_table)):
-                raise ValueError("LeRobot append has incompatible frame 
schema.")
-            if not _same_fields(metadata["episodes_schema"],
-                                _target_schema(tables["episodes"])):
-                raise ValueError("LeRobot append has incompatible Episode 
schema.")
-            if not _same_fields(metadata["datasets_table"].schema,
-                                _target_schema(tables["datasets"])):
-                raise ValueError("LeRobot append has incompatible Dataset 
schema.")
+                for name in old_features.keys() & new_features.keys():
+                    if old_features[name] != new_features[name]:
+                        raise ValueError("LeRobot source %d has incompatible 
features.%s."
+                                         % (ordinal, name))
             old_stats = source_rows[0]["stats"]
             new_stats = metadata["datasets_table"]["stats"][0].as_py()
-            if (old_stats is None) != (new_stats is None) or (
-                    old_stats is not None and
-                    set(json.loads(old_stats)) != set(json.loads(new_stats))):
+            if (old_stats is None) != (new_stats is None):
                 raise ValueError("LeRobot append has incompatible statistics.")
+            _validate_lerobot_schema(target_schema, 
_target_schema(table.raw_table), "append")
+            # Validate every component before making any catalog changes.
+            requests = [
+                (table.raw_table, target_schema, 
(*_V3_REQUIRED_FEATURE_DTYPES, _DATASET_INDEX_COLUMN)),
+                (tables["episodes"], metadata["episodes_schema"],
+                 (*_EPISODE_CONTROL_COLUMNS, _DATASET_INDEX_COLUMN)),
+                (tables["datasets"], metadata["datasets_table"].schema,
+                 tuple(field.name for field in _DATASETS_SCHEMA if not 
field.nullable)),
+            ]
+            video_fields = 
_video_feature_names(_json_table(metadata["info_table"]))
+            changes = [_plan_schema_evolution(
+                _target_schema(component), schema, schema_evolution, required,
+                video_fields if ordinal == 0 else ())
+                for ordinal, (component, schema, required) in 
enumerate(requests)]
+            for (component, _, _), component_changes in zip(requests, changes):
+                if component_changes:
+                    connection.catalog.alter_table(component.identifier, 
component_changes)
+            # Writers and Ray workers must use the reloaded schema, including 
new field IDs.
+            table = connection.get_table(table.identifier)
+            tables = {name: connection.catalog.get_table(component.identifier)
+                      for name, component in tables.items()}
             frame_offset = ranges[-1][4]
             dataset_offset = len(source_rows)
             for plan in plans:
@@ -639,7 +647,7 @@ def _import_sources(connection, table_name, sources, 
batch_size, options,
             for row in datasets:
                 row["index"] += dataset_offset
             metadata["datasets_table"] = pa.Table.from_pylist(
-                datasets, schema=metadata["datasets_table"].schema)
+                datasets, schema=_target_schema(tables["datasets"]))
         if existing is not None:
             stack.enter_context(_recover_failed_append(connection, table_name))
         episode_schema = _target_schema(tables["episodes"])
diff --git a/paimon-python/pypaimon/multimodal/lerobot/schema.py 
b/paimon-python/pypaimon/multimodal/lerobot/schema.py
index 73e602fe1a..ac10c73233 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/schema.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/schema.py
@@ -20,6 +20,10 @@ import json
 
 import pyarrow as pa
 
+from pypaimon.schema.data_types import PyarrowFieldParser
+from pypaimon.schema.schema_change import SchemaChange
+from pypaimon.schema.column_directive_utils import VIDEO_FRAME_FIELD_DIRECTIVE
+
 
 _SCALAR_DTYPES = {
     "bool": pa.bool_(),
@@ -212,3 +216,25 @@ def _merge_schemas(schemas, schema_evolution=True, 
required=()):
                                 for schema in schemas))
         for name, field in fields.items()
     ], metadata=schemas[0].metadata)
+
+
+def _plan_schema_evolution(target_schema, incoming_schema, schema_evolution,
+                           required=(), video_fields=()):
+    """Validate an append and plan nullable column additions without changing 
types."""
+    # Compare the storage representation, including Arrow aliases for 
STRING/ARRAY.
+    incoming_schema = PyarrowFieldParser.from_paimon_schema(
+        PyarrowFieldParser.to_paimon_schema(incoming_schema))
+    merged = _merge_schemas([target_schema, incoming_schema], 
schema_evolution, required)
+    changes = []
+    for field in merged:
+        if field.name not in target_schema.names:
+            comment = _description(field) or None
+            if field.name in video_fields:
+                comment = VIDEO_FRAME_FIELD_DIRECTIVE + ("; " + comment if 
comment else "")
+            changes.append(SchemaChange.add_column(
+                field.name, PyarrowFieldParser.to_paimon_type(field.type, 
True),
+                comment=comment))
+        elif field.name not in required and field.nullable \
+                and not target_schema.field(field.name).nullable:
+            changes.append(SchemaChange.update_column_nullability(field.name, 
True))
+    return changes
diff --git a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py 
b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
index 754b66e58e..fa6f91494d 100644
--- a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
+++ b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
@@ -137,11 +137,18 @@ def episode_rows(conn, name):
 
 
 def metadata(conn, suffix):
-    dataset = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
-    try:
-        return getattr(dataset.reader.meta, suffix)
-    finally:
-        dataset.close()
+    from pypaimon.multimodal.lerobot.dataset import (
+        _merged_source_info, _merged_source_stats, _source_vocabulary,
+    )
+
+    sources = rows(conn, "merged_datasets").sort_by("index").to_pylist()
+    tasks, _ = _source_vocabulary(sources, "task")
+    subtasks, _ = _source_vocabulary(sources, "subtask")
+    if suffix == "info":
+        return _merged_source_info(sources, tasks, subtasks)
+    if suffix == "stats":
+        return _merged_source_stats(sources, 
conn.get_table("merged_episodes").raw_table)
+    return {"tasks": tasks, "subtasks": subtasks}[suffix]
 
 
 def vocabulary(conn, singular):
@@ -509,6 +516,8 @@ def 
test_merge_rejects_non_json_episode_fields_before_create(setup, name, values
 
 
 def test_merge_reordered_source_tasks_match_published_stats(setup):
+    pytest.importorskip("datasets")
+    pytest.importorskip("torch")
     conn, sources = setup
     path = Path(sources[0][7:]) / "meta/tasks.parquet"
     tasks = pq.read_table(path)
@@ -697,6 +706,7 @@ def test_missing_stats_and_existing_target(setup):
 
 @pytest.mark.parametrize("import_parallelism", [1, 2], indirect=True)
 def test_single_source_metadata_opt_in(setup, import_parallelism):
+    pytest.importorskip("datasets")
     pytest.importorskip("torch")
     conn, sources = setup
     conn.load_from_lerobot("single", sources[0], dataset_name="single",
@@ -2099,3 +2109,184 @@ def 
test_schema_evolution_option_requires_boolean(tmp_path, value):
     with pytest.raises(ValueError, match="schema_evolution"):
         conn.load_from_lerobot("merged", "unused", schema_evolution=value)
     assert conn.catalog.list_databases() == []
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("via_load", [False, True])
+def test_append_evolves_frame_and_dataset_columns(setup, tmp_path, 
import_parallelism, via_load):
+    pytest.importorskip("datasets")
+    pytest.importorskip("torch")
+    conn, sources = setup
+    add_frame_feature(sources[0], "temperature", "float32", [1.] * 5)
+    add_frame_feature(sources[1], "pressure", "float64", [2.] * 5)
+    conn.load_from_lerobot("merged", sources, tag_name="before",
+                           extra_dataset_fields={"config": "config/*.json"})
+    before = frame_rows(conn, "merged_frames")
+    field_ids = {f.name: f.id for f in 
conn.get_table("merged_frames").raw_table.fields}
+    third = source(tmp_path / "third", fps=20)
+    add_frame_feature(third, "humidity", "float32", [40., 41., 42., 43., 44.])
+    (tmp_path / "third/notes.md").write_text("# Third dataset")
+    kwargs = dict(parallelism=import_parallelism, tag_name="after", 
dataset_name="third",
+                  extra_dataset_fields={"notes": "notes.md"})
+    if via_load:
+        from pypaimon.multimodal.lerobot import load_from_lerobot
+        load_from_lerobot(conn, "merged", third, append=True, **kwargs)
+    else:
+        conn.append_to_lerobot("merged", third, **kwargs)
+
+    frames = frame_rows(conn, "merged_frames")
+    assert frames.slice(0, 10).select(before.column_names).equals(before)
+    assert frames["humidity"].to_pylist() == [None] * 10 + [40., 41., 42., 
43., 44.]
+    assert frames["temperature"].slice(10).to_pylist() == [None] * 5
+    assert frames["pressure"].slice(10).to_pylist() == [None] * 5
+    assert frames["dataset_index"].to_pylist() == [0] * 5 + [1] * 5 + [2] * 5
+    assert frames["index"].to_pylist() == list(range(5)) * 3
+    current = conn.get_table("merged_frames").raw_table
+    assert {f.name: f.id for f in current.fields if f.name in field_ids} == 
field_ids
+    assert next(f.type.nullable for f in current.fields if f.name == 
"humidity")
+    datasets = rows(conn, "merged_datasets").sort_by("index")
+    assert datasets["notes"].to_pylist() == [None, None, "# Third dataset"]
+    assert datasets["config"].to_pylist() == [None, None, None]
+    assert datasets["index"].to_pylist() == [0, 1, 2]
+    assert metadata(conn, "stats")["humidity"]["count"] == [5]
+    assert metadata(conn, "stats")["temperature"]["count"] == [5]
+    assert set(conn.catalog.list_tables("default")) == {
+        "merged_frames", "merged_episodes", "merged_datasets"}
+    old = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"), 
tag_name="before")
+    new = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"), 
tag_name="after")
+    try:
+        assert len(old) == 10
+        assert "humidity" not in old[0]
+        assert len(new) == 15
+        samples = new.reader.get_items([0, 5, 10])
+        assert samples[0]["humidity"] is None and samples[1]["humidity"] is 
None
+        assert float(samples[2]["humidity"]) == 40.
+        assert samples[2]["temperature"] is None
+        assert new.episode_fps == (10, 10, 10, 10, 20, 20)
+    finally:
+        old.close()
+        new.close()
+
+
[email protected]("schema_evolution", [False, True])
+def test_append_missing_optional_columns_uses_existing_schema(setup, tmp_path, 
schema_evolution):
+    conn, sources = setup
+    add_frame_feature(sources[0], "temperature", "float32", [1.] * 5)
+    third = source(tmp_path / "third")
+    add_frame_feature(third, "temperature", "float32", [3.] * 5)
+    conn.load_from_lerobot("merged", [sources[0]])
+    conn.append_to_lerobot("merged", [sources[1], third], 
schema_evolution=schema_evolution)
+    assert frame_rows(conn, "merged_frames")["temperature"].to_pylist() == (
+        [1.] * 5 + [None] * 5 + [3.] * 5)
+
+
[email protected]("kind", ["frame", "dataset"])
+def test_append_disabled_evolution_rejects_new_columns(setup, tmp_path, kind):
+    conn, sources = setup
+    conn.load_from_lerobot("merged", [sources[0]])
+    kwargs = {}
+    if kind == "frame":
+        add_frame_feature(sources[1], "humidity", "float32", [1.] * 5)
+    else:
+        (Path(sources[1][7:]) / "notes.md").write_text("notes")
+        kwargs["extra_dataset_fields"] = {"notes": "notes.md"}
+    with patch.object(conn.catalog, "alter_table", 
side_effect=AssertionError("must not alter")):
+        with pytest.raises(ValueError, match="schema_evolution disabled"):
+            conn.append_to_lerobot("merged", sources[1], 
schema_evolution=False, **kwargs)
+    assert rows(conn, "merged_frames").num_rows == 5
+    assert rows(conn, "merged_datasets").num_rows == 1
+
+
[email protected]("conflict", ["dtype", "shape", "names", 
"dataset_type", "episode_type"])
+def test_append_conflicts_are_rejected_before_any_schema_changes(setup, 
tmp_path, conflict):
+    conn, sources = setup
+    add_frame_feature(sources[1], "temperature", "float32", [[1., 2.]] * 5, 
(2,))
+    conn.load_from_lerobot("merged", sources,
+                           extra_dataset_fields={"config": "config/*.json"})
+    third = source(tmp_path / "third")
+    add_frame_feature(third, "humidity", "float32", [1.] * 5)
+    kwargs = {}
+    if conflict in ("dtype", "shape", "names"):
+        shape = (3,) if conflict == "shape" else (2,)
+        add_frame_feature(third, "temperature", "float64" if conflict == 
"dtype" else "float32",
+                          [[1.] * shape[0]] * 5, shape)
+        if conflict == "names":
+            path = tmp_path / "third/meta/info.json"
+            info = json.loads(path.read_text())
+            info["features"]["temperature"]["names"] = ["a", "b"]
+            path.write_text(json.dumps(info))
+    elif conflict == "dataset_type":
+        (tmp_path / "third/config.json").write_text("{}")
+        kwargs["extra_dataset_fields"] = {"config": "config.json"}
+    else:
+        path = tmp_path / "third/meta/episodes/chunk-000/file-000.parquet"
+        data = pq.read_table(path)
+        data = data.set_column(data.schema.get_field_index("length"), 
"length", data["length"].cast(pa.int32()))
+        pq.write_table(data, path)
+    with patch.object(conn.catalog, "alter_table", 
side_effect=AssertionError("must not alter")):
+        with pytest.raises(ValueError, match="incompatible"):
+            conn.append_to_lerobot("merged", third, **kwargs)
+    assert "humidity" not in rows(conn, "merged_frames").column_names
+    assert rows(conn, "merged_frames").num_rows == 10
+    assert rows(conn, "merged_datasets").num_rows == 2
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("media", ["image", "video"])
[email protected]("add_new", [False, True])
+def test_append_nullable_visual_features(tmp_path, import_parallelism, media, 
add_new):
+    pytest.importorskip("datasets")
+    pytest.importorskip("torch")
+    conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+    sources = [source(tmp_path / name, video=media == "video" and index == 
int(add_new))
+               for index, name in enumerate(("first", "second"))]
+    key = "camera" if media == "video" else "image"
+    if media == "image":
+        import io
+        from PIL import Image
+        content = io.BytesIO()
+        Image.new("RGB", (2, 2), "red").save(content, format="PNG")
+        add_frame_feature(sources[int(add_new)], key, "image", 
[content.getvalue()] * 5, (2, 2, 3))
+    conn.load_from_lerobot("merged", [sources[0]])
+    conn.append_to_lerobot("merged", sources[1], 
parallelism=import_parallelism)
+    assert rows(conn, "merged_frames")[key].null_count == 5
+    if media == "video":
+        assert 
conn.get_table("merged_frames").raw_table.options.video_frame_fields() == {key}
+    reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"), 
video_backend="pyav")
+    try:
+        samples = reader.reader.get_items([0, 5])
+        assert samples[1 - int(add_new)][key] is None
+        assert tuple(samples[int(add_new)][key].shape) == ((3, 16, 16) if 
media == "video" else (3, 2, 2))
+    finally:
+        reader.close()
+
+
+def test_append_recovery_keeps_new_columns_nullable_and_allows_retry(setup):
+    conn, sources = setup
+    conn.load_from_lerobot("merged", [sources[0]])
+    add_frame_feature(sources[1], "humidity", "float32", [1.] * 5)
+    original_commit = aggregate._commit_messages
+    calls = 0
+
+    def fail_on_episode(commit, messages):
+        nonlocal calls
+        calls += 1
+        if calls == 2:
+            raise RuntimeError("injected Episode commit failure")
+        return original_commit(commit, messages)
+
+    with patch.object(aggregate, "_commit_messages", 
side_effect=fail_on_episode):
+        with pytest.raises(RuntimeError, match="injected Episode commit 
failure"):
+            conn.append_to_lerobot("merged", sources[1])
+    assert rows(conn, "merged_frames")["humidity"].to_pylist() == [None] * 5
+    assert rows(conn, "merged_datasets").num_rows == 1
+    path = Path(sources[1][7:]) / "meta/info.json"
+    original_info = path.read_text()
+    changed_info = json.loads(original_info)
+    changed_info["features"]["humidity"]["dtype"] = "float16"
+    path.write_text(json.dumps(changed_info))
+    with pytest.raises(ValueError, match="LeRobot feature humidity"):
+        conn.append_to_lerobot("merged", sources[1])
+    path.write_text(original_info)
+    conn.append_to_lerobot("merged", sources[1])
+    assert frame_rows(conn, "merged_frames")["humidity"].to_pylist() == [None] 
* 5 + [1.] * 5

Reply via email to