File size: 13,354 Bytes
f61b9bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/env python

# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""

Tests for processor migration detection functionality.

"""

import json
import tempfile
from pathlib import Path

import pytest

from lerobot.processor.pipeline import DataProcessorPipeline, ProcessorMigrationError
from lerobot.utils.constants import ACTION, OBS_STATE


def test_is_processor_config_valid_configs():
    """Test processor config detection with valid configurations."""
    valid_configs = [
        {"steps": []},  # Empty steps
        {"steps": [{"class": "MyClass"}]},  # Class-based step
        {"steps": [{"registry_name": "my_step"}]},  # Registry-based step
        {"steps": [{"class": "A"}, {"registry_name": "B"}]},  # Mixed
        {"name": "Test", "steps": [{"class": "MyClass"}]},  # With name
    ]

    for i, config in enumerate(valid_configs):
        assert DataProcessorPipeline._is_processor_config(config), (
            f"Valid config {i} should be detected as processor config: {config}"
        )


def test_is_processor_config_invalid_configs():
    """Test processor config detection with invalid configurations."""
    invalid_configs = [
        {},  # No steps field
        {"steps": "not a list"},  # Steps is not a list
        {"steps": [{}]},  # Step without class or registry_name
        {"steps": ["not a dict"]},  # Step is not a dict
        {"steps": [{"other_field": "value"}]},  # Step with wrong fields
        {"other_field": "value"},  # Completely different structure
    ]

    for i, config in enumerate(invalid_configs):
        assert not DataProcessorPipeline._is_processor_config(config), (
            f"Invalid config {i} should not be detected as processor config: {config}"
        )


def test_should_suggest_migration_with_processor_config():
    """Test that migration is NOT suggested when processor config exists."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create a valid processor config
        processor_config = {
            "name": "TestProcessor",
            "steps": [
                {
                    "class": "lerobot.processor.normalize.NormalizeStep",
                    "config": {"mean": 0.0, "std": 1.0},
                }
            ],
        }

        with open(tmp_path / "processor.json", "w") as f:
            json.dump(processor_config, f)

        # Should NOT suggest migration (processor config exists)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert not result


def test_should_suggest_migration_with_empty_processor_config():
    """Test that migration is NOT suggested when empty processor config exists."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create an empty processor config
        empty_processor_config = {
            "name": "EmptyProcessor",
            "steps": [],  # Empty steps is valid
        }

        with open(tmp_path / "empty_processor.json", "w") as f:
            json.dump(empty_processor_config, f)

        # Should NOT suggest migration (processor config exists, even if empty)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert not result


def test_should_suggest_migration_with_model_config_only():
    """Test that migration IS suggested when only model config exists."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create a model config (like old LeRobot format)
        model_config = {
            "type": "act",
            "input_features": {OBS_STATE: {"shape": [7]}},
            "output_features": {ACTION: {"shape": [7]}},
            "hidden_dim": 256,
            "n_obs_steps": 1,
            "n_action_steps": 1,
        }

        with open(tmp_path / "config.json", "w") as f:
            json.dump(model_config, f)

        # SHOULD suggest migration (model config exists but no processor)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert result


def test_should_suggest_migration_no_json_files():
    """Test that migration is NOT suggested when no JSON files exist."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create some non-JSON files
        with open(tmp_path / "model.safetensors", "w") as f:
            f.write("fake model data")

        with open(tmp_path / "README.md", "w") as f:
            f.write("# Model README")

        # Should NOT suggest migration (no JSON files)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert not result


def test_should_suggest_migration_random_json_files():
    """Test that migration IS suggested when JSON files exist but none are processor configs."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create some random JSON file (not a processor config)
        random_config = {"some_field": "some_value", "another_field": 123}

        with open(tmp_path / "random.json", "w") as f:
            json.dump(random_config, f)

        # SHOULD suggest migration (JSON files exist but none are processor configs)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert result


def test_should_suggest_migration_mixed_configs():
    """Test that migration is NOT suggested when processor config exists alongside other configs."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create both a processor config and a model config
        processor_config = {"name": "TestProcessor", "steps": [{"registry_name": "normalize_step"}]}

        model_config = {"type": "diffusion", "hidden_dim": 512}

        with open(tmp_path / "processor.json", "w") as f:
            json.dump(processor_config, f)

        with open(tmp_path / "config.json", "w") as f:
            json.dump(model_config, f)

        # Should NOT suggest migration (processor config exists)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert not result


def test_should_suggest_migration_invalid_json():
    """Test that invalid JSON is handled gracefully."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create an invalid JSON file
        with open(tmp_path / "invalid.json", "w") as f:
            f.write("{ invalid json")

        # Create a valid non-processor config
        model_config = {"type": "act"}
        with open(tmp_path / "model.json", "w") as f:
            json.dump(model_config, f)

        # SHOULD suggest migration (invalid JSON is ignored, but we have non-processor JSON)
        result = DataProcessorPipeline._should_suggest_migration(tmp_path)
        assert result


def test_from_pretrained_multiple_json_files_migration_error():
    """Test that multiple JSON files trigger ProcessorMigrationError."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create multiple non-processor configs
        model_config = {"type": "act", "hidden_dim": 128}
        train_config = {"batch_size": 32, "lr": 0.001}

        with open(tmp_path / "config.json", "w") as f:
            json.dump(model_config, f)

        with open(tmp_path / "train_config.json", "w") as f:
            json.dump(train_config, f)

        # Should raise ProcessorMigrationError
        with pytest.raises(ProcessorMigrationError) as exc_info:
            DataProcessorPipeline.from_pretrained(tmp_path, config_filename="config.json")

        # Check the error details
        error = exc_info.value
        assert str(tmp_path) in str(error.model_path)
        assert "migrate_policy_normalization.py" in error.migration_command
        assert "not a valid processor configuration" in error.original_error


def test_from_pretrained_no_processor_config_migration_error():
    """Test that missing processor config triggers ProcessorMigrationError."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create a model config but no processor
        model_config = {"type": "diffusion", "hidden_dim": 256}

        with open(tmp_path / "config.json", "w") as f:
            json.dump(model_config, f)

        # Should raise ProcessorMigrationError
        with pytest.raises(ProcessorMigrationError) as exc_info:
            DataProcessorPipeline.from_pretrained(tmp_path, config_filename="config.json")

        # Check the error details
        error = exc_info.value
        assert str(tmp_path) in str(error.model_path)
        assert "migrate_policy_normalization.py" in error.migration_command
        assert "not a valid processor configuration" in error.original_error


def test_from_pretrained_valid_processor_no_migration_error():
    """Test that valid processor config does NOT trigger migration error."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create a valid processor config
        processor_config = {
            "name": "TestProcessor",
            "steps": [],  # Empty is valid
        }

        with open(tmp_path / "processor.json", "w") as f:
            json.dump(processor_config, f)

        # Should succeed and create pipeline
        pipeline = DataProcessorPipeline.from_pretrained(tmp_path, config_filename="processor.json")
        assert pipeline is not None
        assert pipeline.name == "TestProcessor"
        assert len(pipeline) == 0


def test_from_pretrained_no_json_files_no_migration_error():
    """Test that directories with no JSON files don't trigger migration errors."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create some non-JSON files
        with open(tmp_path / "model.safetensors", "w") as f:
            f.write("fake model data")

        # Should raise FileNotFoundError (config file not found)
        with pytest.raises(FileNotFoundError, match="not found in directory"):
            DataProcessorPipeline.from_pretrained(tmp_path, config_filename="processor.json")


def test_processor_migration_error_creation():
    """Test that ProcessorMigrationError is created correctly."""
    model_path = "/path/to/model"
    migration_command = "python migrate.py --path /path/to/model"
    original_error = "Config not found"

    error = ProcessorMigrationError(model_path, migration_command, original_error)

    assert error.model_path == model_path
    assert error.migration_command == migration_command
    assert error.original_error == original_error
    assert model_path in str(error)
    assert migration_command in str(error)
    assert original_error in str(error)


def test_processor_migration_error_attributes():
    """Test that ProcessorMigrationError has correct attributes."""
    model_path = Path("/test/path")
    migration_command = "python test.py"
    original_error = "Test error"

    error = ProcessorMigrationError(model_path, migration_command, original_error)

    # Test that attributes are accessible
    assert hasattr(error, "model_path")
    assert hasattr(error, "migration_command")
    assert hasattr(error, "original_error")

    # Test that it's still an Exception
    assert isinstance(error, Exception)


def test_migration_suggestion_raises_error():
    """Test that migration suggestion always raises ProcessorMigrationError."""
    with pytest.raises(ProcessorMigrationError) as exc_info:
        DataProcessorPipeline._suggest_processor_migration("/test/path", "Test error")

    error = exc_info.value
    assert "/test/path" in str(error.model_path)
    assert "Test error" in error.original_error
    assert "migrate_policy_normalization.py" in error.migration_command


def test_migration_error_always_raised_for_invalid_configs():
    """Test that ProcessorMigrationError is always raised for invalid configs."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = Path(tmp_dir)

        # Create a model config
        model_config = {"type": "test", "param": "value"}
        with open(tmp_path / "config.json", "w") as f:
            json.dump(model_config, f)

        # Should always raise ProcessorMigrationError
        with pytest.raises(ProcessorMigrationError):
            DataProcessorPipeline.from_pretrained(tmp_path, config_filename="config.json")