File size: 28,010 Bytes
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a323dd
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a323dd
 
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c802b2
 
 
 
 
 
 
 
2b87a3b
b559d9f
2b87a3b
b559d9f
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b559d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c802b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a323dd
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b559d9f
2b87a3b
 
 
 
 
b559d9f
 
 
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b559d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b87a3b
 
 
 
b559d9f
2b87a3b
 
 
 
 
b559d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b87a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""Selection-unit tests. The real datasets loading test is explicit and optional.

Run: python -m unittest discover -s tools -p test_workflow_subsets.py -v
"""
import copy
import importlib.util
import io
import json
import os
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest import mock

import yaml
import build_workflow_subsets as build

HEADER = [
    "file_name", "record_id", "work_id", "recording_start_local", "recording_start_basis",
    "documented_finish_date", "documented_finish_time", "finish_label_scope", "collection_tier",
    "is_canonical", "acquisition_protocol_version", "date", "time", "tool", "medium", "support",
    "dimensions", "duration_seconds", "width_px", "height_px", "orientation", "encoded_frame_rate",
    "video_codec", "pixel_format", "container", "has_audio", "hub_xet_hash", "original_filename",
    "provenance_status", "legacy_provenance_path", "legacy_related_references", "evidence_method",
    "provenance_reference_duration_delta_seconds", "size_bytes", "notes", "recording_mode",
]
NUMERIC = {"duration_seconds": "float64", "width_px": "int64", "height_px": "int64",
           "encoded_frame_rate": "float64", "provenance_reference_duration_delta_seconds": "float64",
           "size_bytes": "int64"}
FEATURES = [{"name": "video" if field == "file_name" else field,
             "dtype": "video" if field == "file_name" else
                 "bool" if field in {"is_canonical", "has_audio"} else NUMERIC.get(field, "large_string")}
            for field in HEADER]


def row(number, protocol="standard-2025-07-13", tier="standard"):
    r = {field: "" for field in HEADER}
    r.update(file_name=f"Standard_Time_Lapses/fixture-{number}.mp4", record_id=f"tla-{number:016x}",
             collection_tier=tier, is_canonical="true", acquisition_protocol_version=protocol,
             recording_start_basis="not_in_timing_snapshot", width_px="3840", height_px="2160",
             duration_seconds="11.500000", encoded_frame_rate="30.000000", has_audio="False",
             size_bytes="123456", hub_xet_hash=f"{number:064x}", notes='preserve "quotes", comma; and\na newline',
             recording_mode="time_lapse")
    if tier == "pre_standard":
        r.update(file_name=f"fixture-{number}.mp4", is_canonical="false", acquisition_protocol_version="")
    return r


def sample_rows():
    a, b, c = row(1), row(2, "standard-2026-08-27"), row(3, "standard-2026-08-27")
    b.update(recording_start_local="2026-09-18T20:48:03-04:00",
             recording_start_basis="device_filename_interpreted_in_declared_timezone")
    c.update(recording_start_basis="unknown")
    return [a, b, c]


def fixture(root, rows=None, indent=2):
    rows = copy.deepcopy(sample_rows() if rows is None else rows)
    (root / "Pre_Standard_Time_Lapses").mkdir(parents=True)
    (root / "metadata.csv").write_bytes(build.csv_bytes(HEADER, rows))
    (root / build.PRE_SOURCE).write_bytes(build.csv_bytes(HEADER, [row(100, tier="pre_standard")]))
    (root / "Work_Identity").mkdir(exist_ok=True)
    work_fields = ["work_id", "status", "superseded_by_work_id", "creation_evidence", "retirement_reason"]
    link_fields = ["work_id", "record_id", "owner_confirmation_state", "source_hub_revision", "evidence_state"]
    work_ids = {r["work_id"] for r in rows if r["work_id"]}
    works = [dict(zip(work_fields, [wid, "active", "", "https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/blob/" + "a" * 40 + "/receipt.md", ""])) for wid in sorted(work_ids)]
    links = [dict(zip(link_fields, [r["work_id"], r["record_id"], "owner_confirmed", "a" * 40, "published_creator_confirmation"])) for r in rows if r["work_id"]]
    (root / build.WORKS_PATH).write_bytes(build.csv_bytes(work_fields, works))
    (root / build.LINKS_PATH).write_bytes(build.csv_bytes(link_fields, links))
    canonical = {"config_name": "canonical", "default": True, "features": copy.deepcopy(FEATURES),
                 "data_files": [{"split": "archive", "path": "viewer/canonical.parquet"}]}
    pre = {"config_name": "pre_standard", "features": copy.deepcopy(FEATURES),
           "data_files": [{"split": "archive", "path": "viewer/pre_standard.parquet"}]}
    metadata = {"license": "cc-by-nc-4.0", "pretty_name": "Fixture, not a repository snapshot",
                "dataset_info": [{"config_name": "canonical", "features": copy.deepcopy(FEATURES),
                                  "splits": [{"name": "archive", "num_examples": len(rows)}]},
                                 {"config_name": "pre_standard", "features": copy.deepcopy(FEATURES),
                                  "splits": [{"name": "archive", "num_examples": 1}]}],
                "configs": [canonical, pre], "tags": ["fixture"]}
    header_text = yaml.safe_dump(metadata, sort_keys=False, allow_unicode=True, indent=indent)
    body = ("# Test fixture\n\nThe Hub exposes two configurations, both using the split name `archive`:\n\n"
            "Existing text, documentation, and semantics must remain here.\n\n## Browse and load\n\n"
            "Existing loading instructions remain here.\n")
    (root / "README.md").write_text("---\n" + header_text + "---\n" + body, encoding="utf-8", newline="\n")
    # No real videos: decode-disabled native tests must never open these stubs.
    for r in rows + [row(100, tier="pre_standard")]:
        p = root / (r["file_name"] if r["collection_tier"] == "standard" else "Pre_Standard_Time_Lapses/" + r["file_name"])
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(b"test-only LFS-like pointer; not media\n")
    return metadata


def fixture_native_inputs(root):
    """Create only tiny local tables; the video references are never opened."""
    import pyarrow as pa
    import pyarrow.parquet as pq
    from datasets import Features, Value, Video
    features = Features({entry["name"]: Video(decode=False) if entry["name"] == "video"
                         else Value(entry["dtype"]) for entry in FEATURES})
    _, groups, _ = build.partition((root / build.SOURCE).read_bytes(), (root / build.PRE_SOURCE).read_bytes())
    groups["canonical"] = build.read_table((root / build.SOURCE).read_bytes(), build.SOURCE)[1]
    for name, population in groups.items():
        rows = []
        for original in population:
            row = {"video": {"path": f"hf://datasets/{build.SOURCE_REPOSITORY}@{'a' * 40}/{original['file_name']}",
                             "bytes": None}}
            for entry in FEATURES[1:]:
                value = original[entry["name"]]
                row[entry["name"]] = (None if value == "" else value.lower() == "true"
                                      if entry["dtype"] == "bool" else int(value)
                                      if entry["dtype"] == "int64" else float(value)
                                      if entry["dtype"] == "float64" else value)
            rows.append(row)
        path = root / f"viewer/{name}.parquet"
        path.parent.mkdir(exist_ok=True)
        pq.write_table(pa.Table.from_pylist(rows, schema=features.arrow_schema), path)


class WorkflowSubsetTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.root = Path(self.temp.name)
        self.original_card = fixture(self.root)

    def tearDown(self):
        self.temp.cleanup()

    def plan(self):
        return build.make_plan(self.root)

    def mutate(self, operation, pre=False):
        path = self.root / (build.PRE_SOURCE if pre else build.SOURCE)
        fields, rows = build.read_table(path.read_bytes(), str(path))
        operation(rows)
        path.write_bytes(build.csv_bytes(fields, rows))

    def test_exact_disjoint_exhaustive_partition(self):
        _, out, report = self.plan()
        a = build.read_table(out["Workflow_Subsets/standard_earlier.csv"], "a")[1]
        b = build.read_table(out["Workflow_Subsets/standard_individual_recordings.csv"], "b")[1]
        self.assertEqual(a, sample_rows()[:1])
        self.assertEqual(b, sample_rows()[1:])
        self.assertEqual(report["standard_rows"], 3)
        self.assertEqual(report["pre_standard_rows"], 1)

    def test_shared_work_is_counted_once_in_combined_total(self):
        rows = sample_rows()
        for r in rows:
            r["work_id"] = "tlaw-0000000000000001"
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            fixture(root, rows)
            _, outputs, report = build.make_plan(root)
        counts = report["registered_works"]
        self.assertEqual(counts["by_workflow"], dict.fromkeys(build.SUBSETS, 1))
        self.assertEqual(counts["distinct_combined"], 1)
        self.assertEqual(counts["shared_between_workflows"], 1)
        self.assertIn(b"1 works occur in both workflows", outputs["README.md"])

    def test_unregistered_projected_work_is_rejected(self):
        self.mutate(lambda rows: rows[0].update(work_id="tlaw-0000000000000001"))
        with self.assertRaisesRegex(build.ContractError, "Stale work-ID projection"):
            self.plan()

    def test_all_source_columns_and_values_preserved(self):
        _, out, _ = self.plan()
        expected = {r["record_id"]: r for r in sample_rows()}
        for name in build.SUBSETS:
            fields, rows = build.read_table(out[f"Workflow_Subsets/{name}.csv"], name)
            self.assertEqual(fields, HEADER)
            for r in rows:
                self.assertEqual(r, expected[r["record_id"]])

    def test_unknown_start_and_work_id_are_not_excluded(self):
        _, out, _ = self.plan()
        rows = build.read_table(out["Workflow_Subsets/standard_individual_recordings.csv"], "view")[1]
        unknown = next(r for r in rows if r["record_id"] == "tla-0000000000000003")
        self.assertEqual(unknown["recording_start_local"], "")
        self.assertEqual(unknown["recording_start_basis"], "unknown")
        self.assertEqual(unknown["work_id"], "")

    def test_date_and_rec_suffix_do_not_classify(self):
        def change(rows):
            rows[0]["file_name"] = "Standard_Time_Lapses/2099-01-01.Rec99.mp4"
            rows[0]["date"] = "2099-01-01"
            rows[1]["file_name"] = "Standard_Time_Lapses/2000-01-01.mp4"
            rows[1]["date"] = "2000-01-01"
        self.mutate(change)
        _, outputs, _ = self.plan()
        earlier = build.read_table(outputs["Workflow_Subsets/standard_earlier.csv"], "a")[1]
        self.assertEqual(earlier[0]["record_id"], "tla-0000000000000001")

    def test_unknown_protocol_rejected(self):
        self.mutate(lambda rows: rows[1].update(acquisition_protocol_version="new-unreviewed-protocol"))
        with self.assertRaisesRegex(build.ContractError, "Unrecognized"):
            self.plan()

    def test_blank_protocol_rejected(self):
        self.mutate(lambda rows: rows[1].update(acquisition_protocol_version=""))
        with self.assertRaisesRegex(build.ContractError, "Unrecognized"):
            self.plan()

    def test_duplicate_id_rejected(self):
        self.mutate(lambda rows: rows[1].update(record_id=rows[0]["record_id"]))
        with self.assertRaisesRegex(build.ContractError, "Duplicate record"):
            self.plan()

    def test_cross_tier_id_collision_rejected(self):
        self.mutate(lambda rows: rows[0].update(record_id="tla-0000000000000001"), pre=True)
        with self.assertRaisesRegex(build.ContractError, "Duplicate record"):
            self.plan()

    def test_duplicate_media_path_rejected(self):
        self.mutate(lambda rows: rows[1].update(file_name=rows[0]["file_name"]))
        with self.assertRaisesRegex(build.ContractError, "Duplicate media"):
            self.plan()

    def test_wrong_tier_rejected(self):
        self.mutate(lambda rows: rows[0].update(collection_tier="pre_standard"))
        with self.assertRaisesRegex(build.ContractError, "Wrong collection"):
            self.plan()

    def test_noncanonical_standard_rejected(self):
        self.mutate(lambda rows: rows[0].update(is_canonical="false"))
        with self.assertRaisesRegex(build.ContractError, "Wrong canonical"):
            self.plan()

    def test_pre_standard_protocol_rejected(self):
        self.mutate(lambda rows: rows[0].update(acquisition_protocol_version="standard-2025-07-13"), pre=True)
        with self.assertRaisesRegex(build.ContractError, "Pre-Standard record"):
            self.plan()

    def test_traversal_and_glob_paths_rejected(self):
        for bad in ["../outside.mp4", "Standard_Time_Lapses/../outside.mp4", "Standard_Time_Lapses/*.mp4"]:
            with self.subTest(path=bad):
                source = (self.root / build.SOURCE).read_bytes()
                self.mutate(lambda rows: rows[0].update(file_name=bad))
                with self.assertRaises(build.ContractError):
                    self.plan()
                (self.root / build.SOURCE).write_bytes(source)

    def test_malformed_csv_rejected(self):
        path = self.root / build.SOURCE
        path.write_bytes(path.read_bytes() + b"malformed,short,row\n")
        with self.assertRaisesRegex(build.ContractError, "malformed CSV"):
            self.plan()

    def test_duplicate_csv_columns_rejected(self):
        with self.assertRaisesRegex(build.ContractError, "duplicate CSV"):
            build.read_table(b"a,a\n1,2\n", "bad")

    def test_existing_configs_and_default_preserved(self):
        _, out, _ = self.plan()
        card = build.card_data(build.split_card(out["README.md"].decode())[0])
        for key in ["configs", "dataset_info"]:
            self.assertEqual(card[key][:2], self.original_card[key])
        self.assertTrue(card["configs"][0]["default"])
        self.assertFalse(any(entry.get("default") for entry in card["configs"][2:]))
        self.assertEqual(card["license"], self.original_card["license"])
        self.assertEqual(card["tags"], ["fixture"])

    def test_native_projection_inputs_embody_protocol_partition(self):
        _, out, _ = self.plan()
        card = build.card_data(build.split_card(out["README.md"].decode())[0])
        configs = build.named_entries(card, "configs")
        for name, protocol in build.SUBSETS.items():
            cfg = configs[name]
            self.assertEqual(cfg["data_files"], [{"split": "archive", "path": f"viewer/{name}.parquet"}])
            self.assertNotIn("filters", cfg)
            self.assertNotIn("metadata_filenames", cfg)
            self.assertEqual(cfg["features"], FEATURES)
            self.assertNotIn("*", str(cfg["data_files"]))

    def test_no_train_test_partition_created(self):
        _, out, _ = self.plan()
        card = build.card_data(build.split_card(out["README.md"].decode())[0])
        for cfg in card["configs"]:
            self.assertEqual([r["split"] for r in cfg["data_files"]], ["archive"])

    def test_rebuild_is_byte_idempotent(self):
        before, outputs, _ = self.plan()
        build.install_plan(self.root, before, outputs)
        _, again, _ = self.plan()
        self.assertEqual(outputs, again)
        build.install_plan(self.root, {p: (self.root / p).read_bytes() for p in before}, again)
        self.assertEqual({p: (self.root / p).read_bytes() for p in outputs}, outputs)

    def test_source_indexes_and_unrelated_evidence_untouched(self):
        evidence = self.root / "Standard_Time_Lapses/Provenance/frozen.json"
        evidence.parent.mkdir(parents=True, exist_ok=True)
        evidence.write_bytes(b'{"keep":"unchanged"}\n')
        before, outputs, _ = self.plan()
        build.install_plan(self.root, before, outputs)
        self.assertEqual((self.root / build.SOURCE).read_bytes(), before[build.SOURCE])
        self.assertEqual((self.root / build.PRE_SOURCE).read_bytes(), before[build.PRE_SOURCE])
        self.assertEqual(evidence.read_bytes(), b'{"keep":"unchanged"}\n')

    def test_missing_or_changed_source_rejected_before_write(self):
        before, outputs, _ = self.plan()
        original_readme = (self.root / "README.md").read_bytes()
        (self.root / build.SOURCE).write_bytes(before[build.SOURCE] + b"\n")
        with self.assertRaisesRegex(build.ContractError, "Concurrent source"):
            build.install_plan(self.root, before, outputs)
        self.assertEqual((self.root / "README.md").read_bytes(), original_readme)
        self.assertFalse((self.root / "Workflow_Subsets").exists())

    def test_write_failure_rolls_back_completed_replacements(self):
        before, outputs, _ = self.plan()
        original_replace = build.os.replace
        calls = [0]
        def fail_second(source, dest):
            calls[0] += 1
            if calls[0] == 2:
                raise OSError("simulated disk failure")
            original_replace(source, dest)
        with mock.patch.object(build.os, "replace", side_effect=fail_second):
            with self.assertRaisesRegex(OSError, "disk failure"):
                build.install_plan(self.root, before, outputs)
        self.assertEqual((self.root / "README.md").read_bytes(), before["README.md"])
        self.assertFalse((self.root / "Workflow_Subsets/standard_earlier.csv").exists())

    def test_unmanaged_output_not_overwritten(self):
        path = self.root / "Workflow_Subsets/standard_earlier.csv"
        path.parent.mkdir()
        path.write_bytes(b"unrelated existing data")
        with self.assertRaisesRegex(build.ContractError, "unmanaged output"):
            self.plan()

    def test_duplicate_yaml_key_rejected(self):
        path = self.root / "README.md"
        path.write_text(path.read_text().replace("license: cc-by-nc-4.0", "license: cc-by-nc-4.0\nlicense: other"), encoding="utf-8", newline="\n")
        with self.assertRaisesRegex(build.ContractError, "Duplicate YAML"):
            self.plan()

    def test_damaged_marker_rejected(self):
        sources, outputs, _ = self.plan()
        build.install_plan(self.root, sources, outputs)
        path = self.root / "README.md"
        path.write_text(path.read_text().replace("# END generated workflow-subsets configs", "# damaged"), encoding="utf-8", newline="\n")
        with self.assertRaisesRegex(build.ContractError, "Damaged"):
            self.plan()

    def test_source_count_mismatch_requires_normal_ingest_completion(self):
        self.mutate(lambda rows: rows.append(row(4, "standard-2026-08-27")))
        with self.assertRaisesRegex(build.ContractError, "stale"):
            self.plan()

    def test_growth_updates_all_generated_views(self):
        sources, outputs, _ = self.plan()
        build.install_plan(self.root, sources, outputs)
        self.mutate(lambda rows: rows.append(row(4, "standard-2026-08-27")))
        # Normal ingestion has also updated the existing canonical count.
        p = self.root / "README.md"
        p.write_text(p.read_text().replace("num_examples: 3", "num_examples: 4", 1), encoding="utf-8", newline="\n")
        _, new_outputs, report = self.plan()
        self.assertEqual(report["subsets"]["standard_individual_recordings"]["rows"], 3)
        self.assertEqual(len(build.read_table(new_outputs["Workflow_Subsets/standard_individual_recordings.csv"], "b")[1]), 3)

    def test_false_old_configuration_count_removed(self):
        _, out, _ = self.plan()
        text = out["README.md"].decode()
        self.assertNotIn("The Hub exposes two configurations", text)
        self.assertIn("Their totals must not be added", text)
        self.assertIn("Existing loading instructions remain here.", text)

    def test_csv_exports_are_not_extra_native_input_files(self):
        _, out, _ = self.plan()
        card = build.card_data(build.split_card(out["README.md"].decode())[0])
        for cfg in card["configs"]:
            self.assertNotIn("Workflow_Subsets/", str(cfg["data_files"]))

    def test_symlink_output_cannot_escape_checkout(self):
        with tempfile.TemporaryDirectory() as outside:
            link = self.root / "Workflow_Subsets"
            if os.name == "nt":
                # Junctions exercise real path redirection without requiring
                # Windows Developer Mode or symbolic-link administrator rights.
                import _winapi
                _winapi.CreateJunction(outside, str(link))
            else:
                link.symlink_to(outside, target_is_directory=True)
            with self.assertRaisesRegex(build.ContractError, "escapes checkout"):
                self.plan()

    def test_required_native_check_reports_missing_dependency(self):
        real_import = __import__
        def unavailable(name, *args, **kwargs):
            if name == "datasets":
                raise ImportError("fixture missing dependency")
            return real_import(name, *args, **kwargs)
        with mock.patch("builtins.__import__", side_effect=unavailable):
            with self.assertRaisesRegex(build.ContractError, "Native loading NOT tested"):
                build.check_native_loading(self.root)

    def test_native_write_requires_explicit_immutable_revision(self):
        with mock.patch.object(build.subprocess, "run") as run:
            with self.assertRaisesRegex(build.ContractError, "--write requires --source-revision"):
                build.refresh_native_views(self.root, None, True)
            run.assert_not_called()

    def test_native_check_uses_bound_manifest_revision(self):
        (self.root / "viewer").mkdir()
        (self.root / build.NATIVE_MANIFEST).write_text(json.dumps({"source_revision": "a" * 40}))
        (self.root / "tools").mkdir()
        (self.root / "tools/build_native_viewer.py").write_text("# mock generator\n")
        with mock.patch.object(build.subprocess, "run", return_value=mock.Mock(returncode=0, stdout="", stderr="")) as run:
            result = build.refresh_native_views(self.root, None, False)
        self.assertEqual(result["source_revision"], "a" * 40)
        self.assertEqual(run.call_args.args[0][-2:], ["--source-revision", "a" * 40])
        self.assertNotIn("--write", run.call_args.args[0])

    def test_native_refresh_failure_is_not_silently_accepted(self):
        (self.root / "tools").mkdir()
        (self.root / "tools/build_native_viewer.py").write_text("# mock generator\n")
        failed = mock.Mock(returncode=1, stdout="", stderr="stale native projection")
        with mock.patch.object(build.subprocess, "run", return_value=failed):
            with self.assertRaisesRegex(build.ContractError, "stale native projection"):
                build.refresh_native_views(self.root, "b" * 40, True)

    def test_native_write_invokes_projection_refresh(self):
        (self.root / "tools").mkdir()
        (self.root / "tools/build_native_viewer.py").write_text("# mock generator\n")
        with mock.patch.object(build.subprocess, "run", return_value=mock.Mock(returncode=0, stdout="", stderr="")) as run:
            result = build.refresh_native_views(self.root, "c" * 40, True)
        self.assertEqual(result["status"], "generated")
        self.assertEqual(run.call_args.args[0][-1], "--write")

    def test_combined_write_rolls_back_native_files_if_selection_install_fails(self):
        sources, outputs, _ = self.plan()
        native = self.root / build.NATIVE_OUTPUTS[0]
        native.parent.mkdir()
        native.write_bytes(b"old projection")
        def refresh(*args):
            native.write_bytes(b"new projection")
            (self.root / build.NATIVE_MANIFEST).write_bytes(b"new manifest")
            return {"status": "generated"}
        with mock.patch.object(build, "refresh_native_views", side_effect=refresh), \
                mock.patch.object(build, "install_plan", side_effect=OSError("disk failure")):
            with self.assertRaisesRegex(OSError, "disk failure"):
                build.install_with_native_views(self.root, sources, outputs, "a" * 40)
        self.assertEqual(native.read_bytes(), b"old projection")
        self.assertFalse((self.root / build.NATIVE_MANIFEST).exists())
        self.assertEqual((self.root / build.README).read_bytes(), sources[build.README])

    def test_video_reference_requires_original_repo_and_immutable_revision(self):
        good = f"hf://datasets/{build.SOURCE_REPOSITORY}@{'a' * 40}/Standard_Time_Lapses/a.mp4"
        self.assertEqual(build.reference_path(good), "Standard_Time_Lapses/a.mp4")
        for bad in [good.replace("@" + "a" * 40, "@main"),
                    good.replace(build.SOURCE_REPOSITORY, "another/dataset"), good + "?token=bad"]:
            with self.subTest(path=bad), self.assertRaises(build.ContractError):
                build.reference_path(bad)

    @unittest.skipUnless(importlib.util.find_spec("datasets") is not None, "datasets is not installed; native loading NOT verified")
    def test_native_named_configuration_loading_without_video_reads(self):
        sources, outputs, _ = self.plan()
        build.install_plan(self.root, sources, outputs)
        fixture_native_inputs(self.root)
        result = build.check_native_loading(self.root)
        self.assertEqual(result["status"], "passed")
        self.assertEqual(result["video_payload_reads"], 0)


class SelectedFrontConfigTests(unittest.TestCase):
    @unittest.skipUnless(importlib.util.find_spec("pyarrow") is not None, "pyarrow is required")
    def test_metadata_projection_emits_native_paired_input_with_same_features(self):
        import pyarrow as pa
        import build_selected_front_projection as selected
        features = {"file_name": {"dtype": "string", "_type": "Value"},
                    "image": {"_type": "Image"},
                    "record_id": {"dtype": "large_string", "_type": "Value"}}
        table = pa.table({"file_name": ["a.mp4"], "image": [None], "record_id": ["tla-0000000000000001"]})
        table = table.replace_schema_metadata({b"huggingface": json.dumps({"info": {"features": features}}).encode()})
        with tempfile.TemporaryDirectory() as temp:
            output = Path(temp) / "paired_config.proposed.yaml"
            selected.write_config(table, output)
            config = yaml.safe_load(output.read_text())[0]
        self.assertEqual(config["config_name"], "recording_physical_references")
        self.assertEqual(config["data_files"], [{"split": "archive", "path": "viewer/recording_physical_references.parquet"}])
        self.assertNotIn("metadata_filenames", config)
        self.assertEqual(config["features"], [{"name": "video", "dtype": "video"},
                                              {"name": "image", "dtype": "image"},
                                              {"name": "record_id", "dtype": "large_string"}])


class RepositoryWorkflowViewTests(unittest.TestCase):
    @unittest.skipUnless(
        (Path(__file__).resolve().parents[1] / "metadata.csv").is_file()
        and importlib.util.find_spec("datasets") is not None,
        "Full repository and datasets are required; native repository loading NOT run",
    )
    def test_native_current_repository_configurations_without_video_reads(self):
        root = Path(__file__).resolve().parents[1]
        result = build.check_native_loading(root)
        self.assertEqual(result["status"], "passed")
        self.assertEqual(result["video_payload_reads"], 0)

    @unittest.skipUnless((Path(__file__).resolve().parents[1] / "metadata.csv").is_file(),
                         "Full repository indexes are not mounted; repository-state check NOT run")
    def test_generated_views_match_current_repository(self):
        root = Path(__file__).resolve().parents[1]
        build.validate_source_contract(root)
        _, outputs, _ = build.make_plan(root)
        for relative, expected in outputs.items():
            with self.subTest(path=relative):
                self.assertTrue((root / relative).is_file(), "Generated output missing")
                self.assertEqual((root / relative).read_bytes(), expected,
                                 "Run the workflow subset generator after the usual ingest projections")


if __name__ == "__main__":
    unittest.main()