Repository navigation
Expand file tree
/
Copy pathtest_cross_surface_parity.py
More file actions
692 lines (635 loc) · 20.6 KB
/
Copy pathtest_cross_surface_parity.py
File metadata and controls
692 lines (635 loc) · 20.6 KB
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
"""The SDK, REST, the CLI and MCP agree on what the same workflow does, and on what it refuses.
Each row of ``SCENARIOS`` is one operation with one input, run on a fresh workspace per
surface that offers it. Ids, timestamps and paths are scrubbed; what is compared is the data
a client reads and the code and detail it branches on. A refusal is a result too, so a row
says which code every surface must answer with.
An operation a surface does not offer is a named row in ``NOT_OFFERED``, asserted against the
real command tree or tool list, so giving one a surface fails a test until the row is moved
into ``SCENARIOS`` on purpose.
"""
from __future__ import annotations
from collections.abc import Callable
from contextlib import ExitStack
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Final
from uuid import uuid4
import pytest
import typer.main
from tests.formats.test_obb_export import ROTATED, SHIP
from tests.formats.test_ultralytics import Fixture
from tests.mcp._flow import tool_names
from tests.server._jobs import InlineDispatcher
from tests.surfaces import _world as world_
from tests.surfaces._surfaces import Cli, Mcp, Outcome, Rest, Sdk, Surface, rest_client
from visionset.cli.main import app
from visionset.kernel.domain import Annotation
from visionset.server.main import create_app
ALL: Final = ("sdk", "rest", "cli", "mcp")
NO_CLI: Final = ("sdk", "rest", "mcp")
KERNEL_AND_HTTP: Final = ("sdk", "rest")
NO_REST: Final = ("sdk", "cli", "mcp")
SIGN = world_.SIGN
LANE = world_.LANE
BOX = {"type": "bbox", "x": 1.0, "y": 2.0, "width": 10.0, "height": 8.0}
OCCLUDED = {"occluded": False}
@dataclass(frozen=True)
class Scenario:
name: str
stage: str
verb: str
arguments: dict[str, Any]
surfaces: tuple[str, ...]
refusal: str | None = None
expected: dict[str, Any] = field(default_factory=dict)
def _label(asset: int = 0, label_class: str = "sign", **overrides: Any) -> dict[str, Any]:
return {
"asset": asset,
"label_class": label_class,
"geometry": BOX,
"attributes": OCCLUDED,
**overrides,
}
def _schema(*classes: dict[str, Any], allow_destructive: bool = False) -> dict[str, Any]:
return {"classes": list(classes), "allow_destructive": allow_destructive}
SCENARIOS: Final = (
Scenario(
"schema-first-version",
"project",
"schema_create",
_schema(SIGN),
ALL,
expected={"version": 1},
),
Scenario(
"schema-reapplied-unchanged",
"schema",
"schema_create",
_schema(SIGN),
ALL,
expected={"version": 1},
),
Scenario(
"schema-widened",
"schema",
"schema_create",
_schema(SIGN, LANE),
ALL,
expected={"version": 2},
),
Scenario(
"schema-narrowing-refused",
"schema",
"schema_create",
_schema(LANE),
ALL,
refusal="DESTRUCTIVE_SCHEMA_CHANGE",
),
Scenario(
"schema-narrowing-consented",
"schema",
"schema_create",
_schema(LANE, allow_destructive=True),
ALL,
expected={"version": 2},
),
Scenario(
"batch-empty",
"schema",
"batch_create",
{"name": "curated", "project": "known", "assets": []},
NO_CLI,
),
Scenario(
"batch-of-existing-assets",
"open",
"batch_create",
{"name": "curated", "project": "known", "assets": [0, 1]},
NO_CLI,
expected={"asset_count": 2, "state": "draft"},
),
Scenario(
"batch-unknown-project",
"schema",
"batch_create",
{"name": "curated", "project": "unknown", "assets": []},
NO_CLI,
refusal="PROJECT_NOT_FOUND",
),
Scenario(
"batch-unknown-asset",
"open",
"batch_create",
{"name": "curated", "project": "known", "assets": [None]},
NO_CLI,
refusal="ASSET_NOT_FOUND",
),
Scenario(
"batch-blank-name",
"schema",
"batch_create",
{"name": " ", "project": "known", "assets": []},
NO_CLI,
refusal="INVALID_NAME",
),
Scenario("annotation-valid", "open", "annotation_add", {"items": [_label()]}, ALL),
Scenario(
"annotation-two-assets",
"open",
"annotation_add",
{"items": [_label(0), _label(1)]},
ALL,
),
Scenario(
"annotation-unknown-class",
"open",
"annotation_add",
{"items": [_label(label_class="boat")]},
ALL,
refusal="LABEL_CLASS_NOT_IN_SCHEMA",
),
Scenario(
"annotation-wrong-geometry",
"open",
"annotation_add",
{
"items": [
_label(geometry={"type": "polygon", "points": [[1.0, 1.0], [9.0, 1.0], [5.0, 8.0]]})
]
},
ALL,
refusal="DISALLOWED_GEOMETRY",
),
Scenario(
"annotation-missing-attribute",
"open",
"annotation_add",
{"items": [_label(attributes={})]},
ALL,
refusal="MISSING_REQUIRED_ATTRIBUTE",
),
Scenario(
"annotation-one-bad-refuses-all",
"open",
"annotation_add",
{"items": [_label(0), _label(1, label_class="boat")]},
ALL,
refusal="LABEL_CLASS_NOT_IN_SCHEMA",
),
Scenario(
"confirm-pre-labeled",
world_.PRE_LABELED,
"confirm_pre_labeled",
{"min_confidence": None},
ALL,
expected={"confirmed": ["<asset-0>", "<asset-1>"], "below_threshold": 0},
),
Scenario(
"confirm-pre-labeled-above-a-threshold",
world_.PRE_LABELED,
"confirm_pre_labeled",
{"min_confidence": 0.5},
ALL,
expected={"confirmed": ["<asset-0>"], "below_threshold": 1, "unscored": 0},
),
Scenario(
"confirm-pre-labeled-in-a-closed-batch",
"promoted",
"confirm_pre_labeled",
{"min_confidence": None},
ALL,
refusal="BATCH_NOT_IN_ANNOTATION",
),
Scenario(
"release-publish",
"promoted",
"release_publish",
{"tag": "v1"},
ALL,
expected={"asset_count": 3, "annotation_count": 3},
),
Scenario(
"release-blank-tag", "promoted", "release_publish", {"tag": " "}, ALL, "INVALID_NAME"
),
Scenario(
"release-tag-taken",
"released",
"release_publish",
{"tag": "v1"},
ALL,
refusal="RELEASE_TAG_TAKEN",
),
Scenario("check-lossless", "released", "export_check", {"format_name": "coco"}, ALL),
Scenario(
"check-lossy-by-declaration",
"released",
"export_check",
{"format_name": "cvat-images"},
ALL,
),
Scenario(
"check-unknown-format",
"released",
"export_check",
{"format_name": "no-such-format"},
ALL,
refusal="EXPORT_FORMAT_NOT_FOUND",
),
Scenario(
"export-lossless",
"released",
"export",
{"format_name": "coco", "allow_lossy": False},
ALL,
expected={"file_count": 4, "format": "coco"},
),
Scenario(
"export-lossy-refused",
"released",
"export",
{"format_name": "cvat-images", "allow_lossy": False},
ALL,
refusal="LOSSY_EXPORT_NOT_CONSENTED",
),
Scenario(
"export-lossy-consented",
"released",
"export",
{"format_name": "cvat-images", "allow_lossy": True},
ALL,
expected={"file_count": 4, "format": "cvat-images"},
),
Scenario("quality-clean-draft", "promoted", "quality_dataset", {}, ALL),
Scenario("quality-draft-with-open-work", "messy", "quality_dataset", {}, ALL),
Scenario("quality-release", "messy", "quality_release", {"format_name": None}, ALL),
Scenario(
"quality-release-for-a-lossy-format",
"messy",
"quality_release",
{"format_name": "cvat-images"},
ALL,
),
Scenario(
"quality-release-unknown-format",
"messy",
"quality_release",
{"format_name": "no-such-format"},
ALL,
refusal="EXPORT_FORMAT_NOT_FOUND",
),
Scenario(
"cancel-queued-job",
"empty",
"cancel_job",
{"which": "queued"},
KERNEL_AND_HTTP,
expected={"state": "cancelled"},
),
Scenario(
"cancel-unknown-job",
"empty",
"cancel_job",
{"which": "unknown"},
KERNEL_AND_HTTP,
refusal="BACKGROUND_JOB_NOT_FOUND",
),
Scenario(
"cancel-queued-pre-label-run",
"open",
"cancel_pre_label",
{"which": "open"},
ALL,
expected={"state": "cancelled"},
),
Scenario(
"cancel-pre-label-on-an-unknown-job",
"open",
"cancel_pre_label",
{"which": "unknown"},
ALL,
refusal="JOB_NOT_FOUND",
),
Scenario(
"ingest-fresh-folder",
"project",
"ingest",
{"folder": "fresh", "project": "known", "batch_name": "first"},
ALL,
expected={"processed": 3, "project_assets": 3, "project_batches": 1},
),
Scenario(
"ingest-duplicate-and-unreadable-files",
"project",
"ingest",
{"folder": "mixed", "project": "known", "batch_name": "first"},
ALL,
expected={"processed": 4, "project_assets": 2, "project_batches": 1},
),
Scenario(
"ingest-nothing-new",
"open",
"ingest",
{"folder": "known", "project": "known", "batch_name": None},
ALL,
expected={"processed": 3, "batch": None, "project_assets": 3, "project_batches": 1},
),
Scenario(
"ingest-blank-batch-name",
"project",
"ingest",
{"folder": "fresh", "project": "known", "batch_name": " "},
ALL,
refusal="INVALID_NAME",
),
Scenario(
"ingest-unknown-project",
"project",
"ingest",
{"folder": "fresh", "project": "unknown", "batch_name": None},
ALL,
refusal="PROJECT_NOT_FOUND",
),
Scenario(
"ingest-video",
"project",
"ingest_video",
{"decoder": "system", "options": {"fps": 2}},
ALL,
expected={"frame_count": 8, "cancelled": False},
),
Scenario(
"ingest-video-window-and-scale",
"project",
"ingest_video",
{
"decoder": "system",
"options": {
"fps": 2,
"start_seconds": 1,
"end_seconds": 3,
"scale": 50,
"batch_name": "window",
},
},
ALL,
expected={"frame_count": 4, "batch": {"name": "window", "state": "draft"}},
),
Scenario(
"ingest-video-ranges",
"project",
"ingest_video",
{
"decoder": "system",
"options": {
"fps": 2,
"ranges": [
{"start_seconds": 2.5},
{"start_seconds": 0, "end_seconds": 1},
{"start_seconds": 2, "end_seconds": 3},
],
},
},
ALL,
expected={"frame_count": 6, "cancelled": False},
),
Scenario(
"ingest-video-counted-ranges",
"project",
"ingest_video",
{
"decoder": "system",
"options": {
"ranges": [
{"start_seconds": 2, "end_seconds": 4, "count": 5},
{"start_seconds": 0, "end_seconds": 1, "count": 3},
],
},
},
ALL,
expected={"frame_count": 8, "cancelled": False},
),
Scenario(
"ingest-video-whole-clip-count",
"project",
"ingest_video",
{"decoder": "system", "options": {"sample_count": 7}},
ALL,
expected={"frame_count": 7, "cancelled": False},
),
Scenario(
"ingest-video-without-a-decoder",
"project",
"ingest_video",
{"decoder": "missing", "options": {"fps": 2}},
ALL,
refusal="VIDEO_DECODER_UNAVAILABLE",
),
Scenario(
"import-lossless",
"project",
"import_dataset",
{"source": "coco", "lossy": False, "consent": []},
NO_REST,
expected={"asset_count": 2, "annotations_written": 3, "schema_version": 1, "losses": []},
),
Scenario(
"import-lossy-refused",
"project",
"import_dataset",
{"source": "coco", "lossy": True, "consent": []},
NO_REST,
refusal="IMPORT_NOT_CONSENTED",
),
Scenario(
"import-lossy-consent-for-the-wrong-kind",
"project",
"import_dataset",
{"source": "coco", "lossy": True, "consent": ["image"]},
NO_REST,
refusal="IMPORT_NOT_CONSENTED",
),
Scenario(
"import-lossy-consented",
"project",
"import_dataset",
{"source": "coco", "lossy": True, "consent": ["label"]},
NO_REST,
expected={"asset_count": 2, "annotations_written": 3},
),
Scenario(
"import-unknown-format",
"project",
"import_dataset",
{"source": "no-such-format", "lossy": False, "consent": []},
NO_REST,
refusal="IMPORT_FORMAT_NOT_FOUND",
),
)
QUALITY_BLOCKING: Final = {
"quality-clean-draft": 0,
"quality-draft-with-open-work": 1,
"quality-release": 0,
"quality-release-for-a-lossy-format": 0,
}
def _surface(
name: str, world: world_.World, scratch: Path, stack: ExitStack, monkeypatch: pytest.MonkeyPatch
) -> Surface:
if name == "sdk":
return Sdk(world, scratch)
if name == "rest":
client = stack.enter_context(rest_client(world, InlineDispatcher()))
return Rest(world, scratch, client)
if name == "cli":
return Cli(world, scratch)
return Mcp(world, scratch, monkeypatch)
def run_scenario(
scenario: Scenario, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> dict[str, Outcome]:
outcomes: dict[str, Outcome] = {}
for name in scenario.surfaces:
base = tmp_path / name
base.mkdir()
world = world_.build(base / "ws", scenario.stage)
if scenario.verb == "cancel_job":
world_.queue_job(world)
if scenario.verb == "cancel_pre_label":
world_.queue_pre_label(world)
with ExitStack() as stack:
surface = _surface(name, world, base, stack, monkeypatch)
outcomes[name] = getattr(surface, scenario.verb)(**scenario.arguments)
return outcomes
@pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.name)
def test_every_offering_surface_answers_the_same(
scenario: Scenario, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
outcomes = run_scenario(scenario, tmp_path, monkeypatch)
reference = outcomes["sdk"]
for name, outcome in outcomes.items():
assert outcome == reference, f"{name} differs from sdk"
if scenario.refusal is None:
assert "ok" in reference, reference
if scenario.verb.startswith("quality_"):
report = reference["ok"]["report"]
assert report["version"] == 1
assert report["counts"]["blocking"] == QUALITY_BLOCKING[scenario.name]
for key, value in scenario.expected.items():
assert reference["ok"][key] == value, (key, reference)
else:
assert reference["refused"]["code"] == scenario.refusal, reference
def _cli_paths() -> set[tuple[str, ...]]:
found: set[tuple[str, ...]] = set()
def walk(command: Any, path: tuple[str, ...]) -> None:
for name, child in getattr(command, "commands", {}).items():
found.add((*path, name))
walk(child, (*path, name))
walk(typer.main.get_command(app), ())
return found
def _cli_has(*words: str) -> bool:
return any(word in segment for path in _cli_paths() for segment in path for word in words)
@dataclass(frozen=True)
class Gap:
probe: Callable[[], bool]
reason: str
doc: str
limit: str
def _rest_paths() -> set[str]:
return {getattr(route, "path", "") for route in create_app().routes}
NOT_OFFERED: Final[dict[tuple[str, str], Gap]] = {
("batch_create", "cli"): Gap(
lambda: ("batch", "create") in _cli_paths(),
"the CLI opens batches by ingest; creating one directly is an API and MCP step",
"batches.md",
"There is no `batch create`",
),
("cancel_job", "cli"): Gap(
lambda: any(
"cancel" in segment
for path in _cli_paths() - {("job", "cancel-pre-label")}
for segment in path
),
"the CLI has no background-job commands; it cancels a pre-labeling run by its job only",
"surfaces.md",
"The CLI and MCP cancel only pre-labeling runs.",
),
("cancel_job", "mcp"): Gap(
lambda: any("cancel" in name for name in set(tool_names()) - {"cancel_pre_label"}),
"background jobs are followed and stopped by a browser or a REST client, not a tool call",
"surfaces.md",
"The CLI and MCP cancel only pre-labeling runs.",
),
("import_dataset", "rest"): Gap(
lambda: any("import" in path and "video-import" not in path for path in _rest_paths()),
"a server-side path route would give every token holder an arbitrary-directory read",
"surfaces.md",
"No dataset import over REST or in the browser.",
),
}
"""Each known gap: the probe that finds the entry point if someone adds it, why it is absent,
and the sentence in the docs that states the limit."""
DRIVERS: Final = {"sdk": Sdk, "rest": Rest, "cli": Cli, "mcp": Mcp}
@pytest.mark.parametrize("gap", NOT_OFFERED, ids=lambda g: f"{g[0]}-on-{g[1]}")
def test_a_known_gap_has_no_entry_point(gap: tuple[str, str]) -> None:
assert not NOT_OFFERED[gap].probe(), (
f"{gap[1]} now offers {gap[0]}: move it from NOT_OFFERED into the scenarios that cover it"
)
def test_the_gaps_are_exactly_the_verbs_no_scenario_runs_on_a_surface() -> None:
verbs = {scenario.verb for scenario in SCENARIOS}
covered = {(s.verb, surface) for s in SCENARIOS for surface in s.surfaces}
uncovered = {(verb, surface) for verb in verbs for surface in ALL} - covered
assert uncovered == set(NOT_OFFERED)
for verb, surface in covered | uncovered:
assert hasattr(DRIVERS[surface], verb) is ((verb, surface) in covered)
DOCS: Final = Path(__file__).resolve().parents[2] / "docs" / "content"
@pytest.mark.parametrize("gap", NOT_OFFERED, ids=lambda g: f"{g[0]}-on-{g[1]}")
def test_a_known_gap_has_a_reason_and_the_docs_state_the_limit(gap: tuple[str, str]) -> None:
entry = NOT_OFFERED[gap]
assert entry.reason.strip(), f"{gap} has no reason"
assert entry.limit in (DOCS / entry.doc).read_text(encoding="utf-8"), (
f"{entry.doc} no longer states the limit for {gap}: {entry.limit!r}"
)
def _checked_everywhere(
world: world_.World, format_name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> dict[str, Outcome]:
outcomes: dict[str, Outcome] = {}
for name in ALL:
scratch = tmp_path / name
scratch.mkdir()
with ExitStack() as stack:
outcomes[name] = _surface(name, world, scratch, stack, monkeypatch).export_check(
format_name
)
return outcomes
def test_a_lossy_format_asks_on_every_surface_for_the_attributes_it_drops(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
world = world_.build(tmp_path / "ws", "released")
outcomes = _checked_everywhere(world, "ultralytics", tmp_path, monkeypatch)
for outcome in outcomes.values():
report = outcome["ok"]["report"]
assert report["compatible"] and report["consent_required"]
assert report["uncarried"] == ["attributes"]
def test_a_lossy_format_asks_nothing_on_any_surface_of_a_release_it_carries_whole(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fixture = Fixture(tmp_path, classes=(SHIP,))
fixture.label(
{
0: [
Annotation(
asset_id=uuid4(),
label_class="ship",
schema_version=1,
geometry=ROTATED,
provenance="human",
)
]
}
)
release_id = fixture.publish(world_.TAG)
fixture.close()
world = world_.World(tmp_path / "ws", release_id=release_id)
outcomes = _checked_everywhere(world, "yolo-obb", tmp_path, monkeypatch)
for outcome in outcomes.values():
report = outcome["ok"]["report"]
assert report["compatible"] and not report["consent_required"]
assert report["format_is_lossy"] and report["uncarried"] == []