File size: 28,457 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import hashlib
import json
import math
import struct
from pathlib import Path
from typing import Any, Mapping, Sequence


POLICY_SCHEMA = "speech2face.decoder-geometry-topology-policy/v1"
SYNTHETIC_SCHEMA = "speech2face.decoder-geometry-synthetic-fixture/v1"
EXPECTED_POLICY_SIZE = 8_766
EXPECTED_POLICY_SHA256 = "c426bd750ed25299e331cdb38b54d411bebb358fa88c3f8459e7c9e5fb5fb07d"
LANDMARK_COUNT = 98
VECTOR_DIMENSIONS = 196
POLYHARMONIC_REGULARIZATION = 1e-5
POLYHARMONIC_CONDITION_LIMIT = 100_000_000.0
BOUNDARY_POINTS = (
    (-1.0, -1.0),
    (0.0, -1.0),
    (1.0, -1.0),
    (1.0, 0.0),
    (1.0, 1.0),
    (0.0, 1.0),
    (-1.0, 1.0),
    (-1.0, 0.0),
)
SPLITS = frozenset({"train", "validation", "test"})
_ROOT_KEYS = {
    "schema",
    "status",
    "reviewed",
    "execution_allowed",
    "evidence",
    "cole65_decision",
    "proposed_geometry",
    "target_reduction",
    "required_implementation_after_approval",
    "claims",
}
_RECORD_KEYS = {"sample_id", "identity", "split", "wflw98_landmarks_normalized"}


class GeometryPolicyError(ValueError):
    pass


def _duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    result: dict[str, Any] = {}
    for key, value in pairs:
        if key in result:
            raise GeometryPolicyError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result


def canonical_sha256(value: Any) -> str:
    payload = json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def parse_geometry_policy_bytes(raw: bytes) -> Mapping[str, Any]:
    if (
        len(raw) != EXPECTED_POLICY_SIZE
        or hashlib.sha256(raw).hexdigest() != EXPECTED_POLICY_SHA256
    ):
        raise GeometryPolicyError("Geometry policy size or SHA-256 changed")
    try:
        payload = json.loads(
            raw.decode("utf-8", errors="strict"),
            object_pairs_hook=_duplicates,
            parse_constant=lambda value: (_ for _ in ()).throw(
                GeometryPolicyError(f"Non-finite JSON constant: {value}")
            ),
        )
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise GeometryPolicyError("Geometry policy is not strict UTF-8 JSON") from exc
    if type(payload) is not dict or set(payload) != _ROOT_KEYS:
        raise GeometryPolicyError("Geometry policy root fields changed")
    if (
        payload["schema"] != POLICY_SCHEMA
        or payload["status"] != "review_required"
        or payload["reviewed"] is not False
        or payload["execution_allowed"] is not False
    ):
        raise GeometryPolicyError("Geometry review gate changed")
    if payload["cole65_decision"] != {
        "exact_numeric_topology_available": False,
        "spiga_wflw98_crosswalk_available": False,
        "mapping_config_must_remain_empty_and_unreviewed": True,
        "indices_54_76_82_may_not_be_used_as_a_guessed_five_point_mapping": True,
        "paper_faithful_cole65_claim_allowed": False,
        "status": "no_go",
    }:
        raise GeometryPolicyError("Cole-65 decision changed")
    geometry = payload["proposed_geometry"]
    if (
        type(geometry) is not dict
        or geometry.get("decision")
        != "intentional_non_paper_faithful_native_wflw98_substitution"
        or geometry.get("topology") != "spiga_wflw98"
        or geometry.get("landmark_count") != LANDMARK_COUNT
        or geometry.get("geometry_vector_dimensions") != VECTOR_DIMENSIONS
        or geometry.get("source_subset_or_crosswalk") is not None
        or geometry.get("pixel_coordinate_convention")
        != "zero_based_pixel_centers_xy_origin_top_left"
        or geometry.get("decoder_coordinate_convention")
        != "align_corners_true_normalized_negative1_to_positive1"
        or geometry.get("pixel_to_decoder_formula")
        != "x_norm=2*x_pixel/223-1;y_norm=2*y_pixel/223-1"
        or geometry.get("off_canvas_policy")
        != "allow_without_clipping_within_registered_numeric_excursion"
        or geometry.get("maximum_absolute_normalized_coordinate") != 2.0
        or geometry.get("equivalent_pixel_center_range_inclusive") != [-111.5, 334.5]
        or geometry.get("out_of_range_policy")
        != "pre_freeze_drop_with_landmark_numeric_excursion_no_replacement"
        or geometry.get("polyharmonic_k1_conditioning")
        != {
            "basis": "cole_phi1_euclidean_distance_r_not_thin_plate_spline",
            "regularization_diagonal": POLYHARMONIC_REGULARIZATION,
            "control_order": (
                "wflw98_target_points_index_0_through_97_then_registered_boundary_points"
            ),
            "boundary_points_normalized_xy": [list(point) for point in BOUNDARY_POINTS],
            "system_definition": (
                "A=[[cdist_l2(C,C)+1e-5*I,P],[P_transpose,zeros_3x3]];"
                "P_columns=[1,x,y]"
            ),
            "system_shape": [109, 109],
            "condition_dtype": "float64",
            "condition_number": (
                "spectral_2_norm_sigma_max_over_sigma_min_"
                "numpy_linalg_svd_compute_uv_false"
            ),
            "maximum_condition_number_inclusive": POLYHARMONIC_CONDITION_LIMIT,
            "solve_dtype": "float64_system_rhs_and_coefficients",
            "dense_query_dtype": (
                "input_float32_after_radial_and_affine_coefficients_"
                "cast_once_to_float32"
            ),
            "target_generation_control_displacement_range_inclusive": [-4.0, 4.0],
            "runtime_predicted_control_displacement_range_inclusive": [-4.0, 4.0],
            "normwise_relative_solve_residual": (
                "inf_norm_Ax_minus_b_divided_by_inf_norm_A_times_inf_norm_x_"
                "plus_inf_norm_b_with_float64_tiny_denominator_floor"
            ),
            "maximum_normwise_relative_solve_residual_inclusive": 1e-10,
            "production_solve_backend": (
                "differentiable_torch_float64_autograd_with_coefficient_cast_"
                "on_gradient_path"
            ),
            "pre_freeze_identity_evaluation": (
                "each_minimum_three_provisional_identity_mean_in_every_split"
            ),
            "identity_system_failure_policy": (
                "exclude_entire_identity_no_replacement_on_nonfinite_svd_or_"
                "condition_failure"
            ),
            "per_image_to_identity_rhs": (
                "identity_mean_minus_persisted_image_landmarks_with_system_"
                "controls_identity_mean"
            ),
            "per_image_to_identity_solve_order": (
                "identity_utf8_then_sample_id_utf8"
            ),
            "per_image_to_identity_failure_policy": (
                "exclude_entire_identity_no_replacement_on_nonfinite_solve_or_"
                "residual_failure"
            ),
            "global_train_evaluation": (
                "equal_identity_mean_over_remaining_eligible_train_identities"
            ),
            "global_mean_compute_policy": (
                "compute_once_after_all_identity_system_and_per_image_solve_exclusions"
            ),
            "global_system_failure_policy": (
                "fail_entire_stage_on_nonfinite_svd_or_condition_failure_no_"
                "recompute_no_backfill"
            ),
            "identity_to_global_rhs": (
                "global_train_mean_minus_identity_mean_with_system_controls_"
                "global_train_mean_for_every_remaining_identity_all_splits"
            ),
            "identity_to_global_solve_order": "identity_utf8",
            "identity_to_global_failure_policy": (
                "fail_entire_stage_on_nonfinite_solve_or_residual_failure_no_"
                "identity_exclusion_no_recompute_no_backfill"
            ),
            "accepted_manifest_freeze_policy": (
                "freeze_only_after_all_registered_coordinate_condition_and_"
                "residual_gates_pass"
            ),
            "runtime_condition_evaluation": (
                "every_batch_item_predicted_target_geometry_before_solve"
            ),
            "runtime_predicted_geometry_policy": (
                "fail_run_receipted_no_clamp_no_skip_no_retry_on_nonfinite_"
                "condition_or_residual_violation"
            ),
        }
        or geometry.get("all_four_perceptual_arms_share_identical_geometry_targets") is not True
        or geometry.get("loss_formula_and_weights_unchanged") is not True
        or geometry.get("warp_control_topology_changes_from_65_to_98") is not True
        or geometry.get("runtime_mean_landmark_range_change")
        != "permit_registered_finite_range_negative2_to_positive2_without_clipping"
        or geometry.get("runtime_predicted_landmark_head")
        != "linear_196_output_no_tanh"
        or geometry.get("runtime_predicted_landmark_range")
        != "finite_negative2_to_positive2_required_before_loss_or_warp_else_fail_run"
    ):
        raise GeometryPolicyError("Native WFLW98 geometry contract changed")
    reduction = payload["target_reduction"]
    if (
        type(reduction) is not dict
        or reduction.get("minimum_accepted_images_per_identity") != 3
        or reduction.get("identity_split_disjoint_required") is not True
        or reduction.get("input_record_order")
        != "identity_utf8_bytes_then_sample_id_utf8_bytes"
        or reduction.get("aligned_affine_source")
        != (
            "opencv_getAffineTransform_from_float32_x_sorted_pupils_and_"
            "constructed_third_points_returns_2x3_float64"
        )
        or reduction.get("aligned_affine_application")
        != (
            "promote_source_float32_xy_to_float64_then_math_fsum_m00_times_x_"
            "m01_times_y_m02_and_same_for_y_no_intermediate_rounding"
        )
        or reduction.get("pixel_to_normalized_computation")
        != "binary64_formula_then_cast_once_to_ieee754_float32"
        or reduction.get("persisted_per_image_landmarks")
        != (
            "numpy_lib_format_write_array_version_2_0_little_endian_float32_"
            "c_order_shape_98x2_allow_pickle_false"
        )
        or reduction.get("within_identity_accumulation")
        != (
            "math_fsum_binary64_over_persisted_float32_coordinates_then_"
            "divide_by_count_then_cast_once_to_float32"
        )
        or reduction.get("global_mean_eligible_split") != "train"
        or reduction.get("global_mean_weighting") != "equal_weight_per_eligible_train_identity"
        or reduction.get("global_mean_accumulation")
        != (
            "math_fsum_binary64_over_persisted_float32_identity_means_then_"
            "divide_by_identity_count_then_cast_once_to_float32"
        )
        or reduction.get("persisted_identity_and_global_means")
        != (
            "numpy_lib_format_write_array_version_2_0_little_endian_float32_"
            "c_order_shape_98x2_allow_pickle_false"
        )
        or reduction.get("conditioning_input_precision")
        != "persisted_float32_geometry_promoted_exactly_to_float64"
        or reduction.get("validation_or_test_identity_may_affect_global_mean") is not False
        or reduction.get("validation_and_test_targets_use_frozen_train_global_mean") is not True
        or reduction.get("outcome_backfill") is not False
        or reduction.get("retained_identity_or_image_count_target") is not None
    ):
        raise GeometryPolicyError("Target-reduction contract changed")
    if any(value is not False for value in payload["claims"].values()):
        raise GeometryPolicyError("Blocked geometry claims changed")
    return payload


def load_geometry_policy(path: str | Path) -> Mapping[str, Any]:
    original = Path(path).absolute()
    try:
        info = original.lstat()
    except OSError as exc:
        raise GeometryPolicyError("Geometry policy is missing") from exc
    if (
        original.is_symlink()
        or bool(getattr(info, "st_file_attributes", 0) & 0x400)
        or not original.is_file()
        or info.st_nlink != 1
    ):
        raise GeometryPolicyError("Geometry policy must be one regular non-link file")
    return parse_geometry_policy_bytes(original.read_bytes())


def verify_bound_evidence(policy: Mapping[str, Any], repository_root: str | Path) -> None:
    root = Path(repository_root).resolve(strict=True)
    evidence = policy["evidence"]
    evidence_payloads: dict[str, bytes] = {}
    for label, binding in evidence.items():
        lexical = root.joinpath(*binding["path"].split("/"))
        info = lexical.lstat()
        if (
            lexical.is_symlink()
            or bool(getattr(info, "st_file_attributes", 0) & 0x400)
            or not lexical.is_file()
            or info.st_nlink != 1
        ):
            raise GeometryPolicyError(f"Unsafe evidence file: {label}")
        candidate = lexical.resolve(strict=True)
        try:
            candidate.relative_to(root)
        except ValueError as exc:
            raise GeometryPolicyError(f"Evidence path escapes repository: {label}") from exc
        expected_size = binding["size_bytes"]
        if type(expected_size) is not int or info.st_size != expected_size:
            raise GeometryPolicyError(f"Evidence size changed: {label}")
        digest = hashlib.sha256()
        raw_parts: list[bytes] = []
        total = 0
        with candidate.open("rb") as handle:
            while total < expected_size:
                chunk = handle.read(min(65_536, expected_size - total))
                if not chunk:
                    break
                total += len(chunk)
                digest.update(chunk)
                raw_parts.append(chunk)
        after = lexical.lstat()
        if (
            total != expected_size
            or after.st_size != expected_size
            or after.st_ino != info.st_ino
            or after.st_mtime_ns != info.st_mtime_ns
            or digest.hexdigest() != binding["sha256"]
        ):
            raise GeometryPolicyError(f"Evidence binding changed: {label}")
        evidence_payloads[label] = b"".join(raw_parts)
    cole = json.loads(evidence_payloads["cole65_mapping_config"].decode("utf-8"))
    if cole.get("reviewed") is not False or any(
        cole.get(field)
        for field in ("indices", "left_eye_source_indices", "right_eye_source_indices")
    ):
        raise GeometryPolicyError("Cole-65 mapping is no longer empty and blocked")


def _point(value: Any, label: str) -> tuple[float, float]:
    if type(value) not in (list, tuple) or len(value) != 2:
        raise GeometryPolicyError(f"{label} is not a point")
    if any(type(item) not in (int, float) or not math.isfinite(item) for item in value):
        raise GeometryPolicyError(f"{label} is not finite")
    result = float(value[0]), float(value[1])
    if any(item < -2.0 or item > 2.0 for item in result):
        raise GeometryPolicyError(f"{label} is outside normalized decoder coordinates")
    return result


def _float32(value: float) -> float:
    try:
        rounded = struct.unpack("<f", struct.pack("<f", float(value)))[0]
    except (OverflowError, struct.error) as exc:
        raise GeometryPolicyError("Coordinate cannot be represented as float32") from exc
    if not math.isfinite(rounded):
        raise GeometryPolicyError("Coordinate is non-finite after float32 cast")
    return rounded


def _displacement(value: Any, label: str) -> tuple[float, float]:
    if type(value) not in (list, tuple) or len(value) != 2:
        raise GeometryPolicyError(f"{label} is not a displacement vector")
    if any(type(item) not in (int, float) or not math.isfinite(item) for item in value):
        raise GeometryPolicyError(f"{label} is not finite")
    result = float(value[0]), float(value[1])
    if any(item < -4.0 or item > 4.0 for item in result):
        raise GeometryPolicyError(f"{label} exceeds the registered displacement range")
    return result


def _polyharmonic_k1_system(
    landmarks: Sequence[Sequence[float]],
) -> tuple[Any, Any]:
    try:
        import numpy as np
    except ImportError as exc:
        raise GeometryPolicyError("NumPy is required for conditioning validation") from exc
    if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT:
        raise GeometryPolicyError("Conditioning requires exactly 98 landmarks")
    points = [
        _point(point, f"conditioning landmark {index}")
        for index, point in enumerate(landmarks)
    ]
    controls = np.asarray([*points, *BOUNDARY_POINTS], dtype=np.float64)
    delta = controls[:, None, :] - controls[None, :, :]
    radial = np.sqrt(np.sum(delta * delta, axis=2, dtype=np.float64))
    radial.flat[:: radial.shape[0] + 1] += POLYHARMONIC_REGULARIZATION
    affine = np.column_stack(
        [np.ones((controls.shape[0],), dtype=np.float64), controls]
    )
    system = np.block(
        [
            [radial, affine],
            [affine.T, np.zeros((3, 3), dtype=np.float64)],
        ]
    )
    if system.shape != (109, 109) or not np.isfinite(system).all():
        raise GeometryPolicyError("Registered polyharmonic system is malformed")
    return system, np


def polyharmonic_k1_condition_number(
    landmarks: Sequence[Sequence[float]],
) -> float:
    system, np = _polyharmonic_k1_system(landmarks)
    singular_values = np.linalg.svd(system, compute_uv=False)
    smallest = float(singular_values[-1])
    result = (
        math.inf
        if smallest <= 0.0
        else float(singular_values[0]) / smallest
    )
    if not math.isfinite(result):
        raise GeometryPolicyError("Polyharmonic system condition number is non-finite")
    return result


def polyharmonic_k1_solve_relative_residual(
    landmarks: Sequence[Sequence[float]],
    displacements: Sequence[Sequence[float]],
) -> float:
    system, np = _polyharmonic_k1_system(landmarks)
    if type(displacements) not in (list, tuple) or len(displacements) != LANDMARK_COUNT:
        raise GeometryPolicyError("Residual check requires exactly 98 displacements")
    values = np.asarray(
        [
            _displacement(value, f"conditioning displacement {index}")
            for index, value in enumerate(displacements)
        ],
        dtype=np.float64,
    )
    rhs = np.concatenate(
        [values, np.zeros((len(BOUNDARY_POINTS) + 3, 2), dtype=np.float64)],
        axis=0,
    )
    coefficients = np.linalg.solve(system, rhs)
    residual = system @ coefficients - rhs
    denominator = (
        np.linalg.norm(system, ord=np.inf) * np.linalg.norm(coefficients, ord=np.inf)
        + np.linalg.norm(rhs, ord=np.inf)
    )
    result = float(
        np.linalg.norm(residual, ord=np.inf)
        / max(float(denominator), np.finfo(np.float64).tiny)
    )
    if not math.isfinite(result):
        raise GeometryPolicyError("Polyharmonic solve residual is non-finite")
    return result


def derive_synthetic_geometry_fixture(
    policy: Mapping[str, Any],
    records: Sequence[Mapping[str, Any]],
    *,
    fixture_id: str,
) -> dict[str, Any]:
    if policy["reviewed"] is not False or policy["execution_allowed"] is not False:
        raise GeometryPolicyError("Synthetic review requires the blocked policy")
    if type(fixture_id) is not str or not fixture_id.startswith("synthetic:"):
        raise GeometryPolicyError("fixture_id must use the synthetic: namespace")
    if type(records) not in (list, tuple) or not records:
        raise GeometryPolicyError("Synthetic records are required")
    parsed: list[tuple[bytes, bytes, str, str, tuple[tuple[float, float], ...]]] = []
    seen_samples: set[str] = set()
    identity_splits: dict[str, str] = {}
    for ordinal, record in enumerate(records):
        if type(record) is not dict or set(record) != _RECORD_KEYS:
            raise GeometryPolicyError(f"Synthetic record {ordinal} fields changed")
        sample_id = record["sample_id"]
        identity = record["identity"]
        split = record["split"]
        if (
            type(sample_id) is not str
            or not sample_id.startswith("synthetic:")
            or type(identity) is not str
            or not identity.startswith("synthetic:")
            or split not in SPLITS
        ):
            raise GeometryPolicyError(f"Synthetic record {ordinal} identity changed")
        if sample_id in seen_samples:
            raise GeometryPolicyError(f"Duplicate sample_id: {sample_id}")
        seen_samples.add(sample_id)
        prior = identity_splits.setdefault(identity, split)
        if prior != split:
            raise GeometryPolicyError(f"Identity {identity!r} leaks across splits")
        landmarks = record["wflw98_landmarks_normalized"]
        if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT:
            raise GeometryPolicyError("Synthetic WFLW98 landmark count changed")
        points = tuple(
            tuple(
                _float32(coordinate)
                for coordinate in _point(point, f"record {ordinal} landmark {index}")
            )
            for index, point in enumerate(landmarks)
        )
        parsed.append((identity.encode(), sample_id.encode(), identity, split, points))
    parsed.sort(key=lambda row: (row[0], row[1]))
    grouped: dict[
        tuple[str, str],
        list[tuple[str, tuple[tuple[float, float], ...]]],
    ] = {}
    for _identity_bytes, sample_bytes, identity, split, points in parsed:
        grouped.setdefault((identity, split), []).append(
            (sample_bytes.decode("utf-8"), points)
        )
    eligible = {key: values for key, values in grouped.items() if len(values) >= 3}
    means: list[dict[str, Any]] = []
    conditioning_failures: list[dict[str, Any]] = []
    for (identity, split), observations in sorted(
        eligible.items(), key=lambda item: (item[0][0].encode(), item[0][1].encode())
    ):
        mean = [
            [
                _float32(
                    math.fsum(points[index][axis] for _sample_id, points in observations)
                    / len(observations)
                )
                for axis in range(2)
            ]
            for index in range(LANDMARK_COUNT)
        ]
        try:
            condition_number = polyharmonic_k1_condition_number(mean)
        except Exception as exc:
            conditioning_failures.append(
                {
                    "identity": identity,
                    "split": split,
                    "failure_stage": "identity_system",
                    "failure_kind": type(exc).__name__,
                    "reason": "landmark_conditioning_failure",
                }
            )
            continue
        if condition_number > POLYHARMONIC_CONDITION_LIMIT:
            conditioning_failures.append(
                {
                    "identity": identity,
                    "split": split,
                    "failure_stage": "identity_system",
                    "condition_number": condition_number,
                    "reason": "landmark_conditioning_failure",
                }
            )
            continue
        maximum_per_image_residual = 0.0
        residual_failure: dict[str, Any] | None = None
        for sample_id, points in observations:
            displacement = [
                [mean[index][axis] - points[index][axis] for axis in range(2)]
                for index in range(LANDMARK_COUNT)
            ]
            try:
                residual = polyharmonic_k1_solve_relative_residual(
                    mean, displacement
                )
            except Exception as exc:
                residual_failure = {
                    "identity": identity,
                    "split": split,
                    "sample_id": sample_id,
                    "failure_stage": "per_image_to_identity_solve",
                    "failure_kind": type(exc).__name__,
                    "reason": "landmark_conditioning_failure",
                }
                break
            maximum_per_image_residual = max(maximum_per_image_residual, residual)
            if residual > 1e-10:
                residual_failure = {
                    "identity": identity,
                    "split": split,
                    "sample_id": sample_id,
                    "failure_stage": "per_image_to_identity_solve",
                    "relative_residual": residual,
                    "reason": "landmark_conditioning_failure",
                }
                break
        if residual_failure is not None:
            conditioning_failures.append(residual_failure)
            continue
        means.append(
            {
                "identity": identity,
                "split": split,
                "accepted_images": len(observations),
                "mean_landmarks": mean,
                "polyharmonic_k1_condition_number_float64": condition_number,
                "maximum_per_image_to_identity_relative_residual_float64": (
                    maximum_per_image_residual
                ),
            }
        )
    train_means = [row["mean_landmarks"] for row in means if row["split"] == "train"]
    if not train_means:
        raise GeometryPolicyError("No eligible synthetic train identity")
    global_mean = [
        [
            _float32(
                math.fsum(mean[index][axis] for mean in train_means)
                / len(train_means)
            )
            for axis in range(2)
        ]
        for index in range(LANDMARK_COUNT)
    ]
    try:
        global_condition = polyharmonic_k1_condition_number(global_mean)
    except Exception as exc:
        raise GeometryPolicyError(
            "Global train polyharmonic system validation failed"
        ) from exc
    if global_condition > POLYHARMONIC_CONDITION_LIMIT:
        raise GeometryPolicyError(
            "Global train geometry exceeds the polyharmonic conditioning limit"
        )
    maximum_identity_to_global_residual = 0.0
    for row in means:
        displacement = [
            [
                global_mean[index][axis] - row["mean_landmarks"][index][axis]
                for axis in range(2)
            ]
            for index in range(LANDMARK_COUNT)
        ]
        try:
            residual = polyharmonic_k1_solve_relative_residual(
                global_mean, displacement
            )
        except Exception as exc:
            raise GeometryPolicyError(
                "Identity-to-global polyharmonic solve validation failed for "
                f"{row['identity']}"
            ) from exc
        if residual > 1e-10:
            raise GeometryPolicyError(
                "Identity-to-global polyharmonic residual exceeds the limit for "
                f"{row['identity']}"
            )
        row["identity_to_global_relative_residual_float64"] = residual
        maximum_identity_to_global_residual = max(
            maximum_identity_to_global_residual, residual
        )
    result = {
        "schema": SYNTHETIC_SCHEMA,
        "fixture_id": fixture_id,
        "sealable": False,
        "topology": "spiga_wflw98",
        "landmark_count": LANDMARK_COUNT,
        "geometry_vector_dimensions": VECTOR_DIMENSIONS,
        "eligible_identity_means": means,
        "conditioning_failures": conditioning_failures,
        "eligible_train_identity_count": len(train_means),
        "global_train_equal_identity_mean": global_mean,
        "global_train_polyharmonic_k1_condition_number_float64": global_condition,
        "maximum_identity_to_global_relative_residual_float64": (
            maximum_identity_to_global_residual
        ),
        "claims": {
            "cole65_mapping_used": False,
            "validation_or_test_used_in_global_mean": False,
            "real_target_generated": False,
            "training_authorized": False,
        },
    }
    result["synthetic_identity_sha256"] = canonical_sha256(result)
    return result


__all__ = [
    "BOUNDARY_POINTS",
    "EXPECTED_POLICY_SHA256",
    "EXPECTED_POLICY_SIZE",
    "GeometryPolicyError",
    "LANDMARK_COUNT",
    "POLICY_SCHEMA",
    "POLYHARMONIC_CONDITION_LIMIT",
    "POLYHARMONIC_REGULARIZATION",
    "SYNTHETIC_SCHEMA",
    "VECTOR_DIMENSIONS",
    "derive_synthetic_geometry_fixture",
    "load_geometry_policy",
    "parse_geometry_policy_bytes",
    "polyharmonic_k1_condition_number",
    "polyharmonic_k1_solve_relative_residual",
    "verify_bound_evidence",
]