stringforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,139 @@
1
+ # Copyright 2026 Andreas Schachner
2
+ #
3
+ # This file is part of StringForge.
4
+ #
5
+ # StringForge is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+
10
+ r"""
11
+ CLI for the Vulcan sync tier.
12
+
13
+ Examples:
14
+
15
+ # Inspect what's pending without touching HF.
16
+ python -m stringforge.vulcan status
17
+
18
+ # Drain `pending/` to the repo (one cron-tick worth of work).
19
+ python -m stringforge.vulcan sync --repo aschachner/vacua_forge
20
+
21
+ # Same as above but issue PRs instead of direct commits.
22
+ python -m stringforge.vulcan sync --repo aschachner/vacua_forge --create-pr
23
+
24
+ # Estimate what would happen without contacting HF.
25
+ python -m stringforge.vulcan sync --repo aschachner/vacua_forge --dry-run
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import os
31
+ import sys
32
+
33
+ from . import Vulcan, resolve_staging_dir
34
+ from .ratelimit import DEFAULT_BUDGET, DEFAULT_WINDOW_S
35
+ from .sync import DEFAULT_MAX_BATCH, DEFAULT_MAX_RETRIES
36
+ from .writer import list_pending
37
+
38
+
39
+ def _add_common(parser: argparse.ArgumentParser) -> None:
40
+ parser.add_argument(
41
+ "--staging-dir",
42
+ default=None,
43
+ help="Staging directory (defaults to STRINGFORGE_VULCAN_STAGING_DIR).",
44
+ )
45
+
46
+
47
+ def _cmd_status(args: argparse.Namespace) -> int:
48
+ staging = resolve_staging_dir(args.staging_dir)
49
+ pending = list_pending(staging)
50
+ print(f"staging_dir: {staging}")
51
+ print(f"pending shards: {len(pending)}")
52
+ if pending:
53
+ for sh in pending[:10]:
54
+ print(f" {sh.run_id} {sh.path_in_repo} ({sh.n_rows} rows)")
55
+ if len(pending) > 10:
56
+ print(f" ... and {len(pending) - 10} more")
57
+ return 0
58
+
59
+
60
+ def _cmd_sync(args: argparse.Namespace) -> int:
61
+ repo = args.repo or os.environ.get("STRINGFORGE_VULCAN_REPO")
62
+ if not repo:
63
+ print(
64
+ "error: --repo is required (or set STRINGFORGE_VULCAN_REPO).",
65
+ file=sys.stderr,
66
+ )
67
+ return 2
68
+
69
+ forge = Vulcan(
70
+ repo=repo,
71
+ staging_dir=args.staging_dir,
72
+ budget=args.budget,
73
+ window_s=args.window_s,
74
+ )
75
+ report = forge.sync(
76
+ budget=args.budget,
77
+ max_batch=args.max_batch,
78
+ max_retries=args.max_retries,
79
+ create_pr=args.create_pr,
80
+ dry_run=args.dry_run,
81
+ )
82
+ print(
83
+ f"committed={report.n_committed} "
84
+ f"failed={report.n_failed} "
85
+ f"remaining={report.n_remaining} "
86
+ f"commits={report.n_commits}"
87
+ )
88
+ if report.errors:
89
+ for err in report.errors:
90
+ print(f" ! {err}", file=sys.stderr)
91
+ return 1
92
+ return 0
93
+
94
+
95
+ def build_parser() -> argparse.ArgumentParser:
96
+ parser = argparse.ArgumentParser(
97
+ prog="python -m stringforge.vulcan",
98
+ description="Vulcan production vacuum-forging CLI.",
99
+ )
100
+ subs = parser.add_subparsers(dest="command", required=True)
101
+
102
+ status = subs.add_parser("status", help="Inspect the staging directory.")
103
+ _add_common(status)
104
+ status.set_defaults(func=_cmd_status)
105
+
106
+ sync = subs.add_parser(
107
+ "sync",
108
+ help="Batch staged shards into HuggingFace commits.",
109
+ )
110
+ _add_common(sync)
111
+ sync.add_argument(
112
+ "--repo",
113
+ default=None,
114
+ help="Target HF repo (or STRINGFORGE_VULCAN_REPO).",
115
+ )
116
+ sync.add_argument("--budget", type=int, default=DEFAULT_BUDGET,
117
+ help=f"Commits-per-hour ceiling (default: {DEFAULT_BUDGET}).")
118
+ sync.add_argument("--window-s", type=float, default=DEFAULT_WINDOW_S,
119
+ help=f"Rolling-window seconds (default: {DEFAULT_WINDOW_S}).")
120
+ sync.add_argument("--max-batch", type=int, default=DEFAULT_MAX_BATCH,
121
+ help=f"Files per commit (default: {DEFAULT_MAX_BATCH}).")
122
+ sync.add_argument("--max-retries", type=int, default=DEFAULT_MAX_RETRIES,
123
+ help=f"Per-batch retries on 429 (default: {DEFAULT_MAX_RETRIES}).")
124
+ sync.add_argument("--create-pr", action="store_true",
125
+ help="Open PRs instead of pushing to main.")
126
+ sync.add_argument("--dry-run", action="store_true",
127
+ help="Skip the HF call; reserve budget slots only.")
128
+ sync.set_defaults(func=_cmd_sync)
129
+
130
+ return parser
131
+
132
+
133
+ def main(argv: list[str] | None = None) -> int:
134
+ args = build_parser().parse_args(argv)
135
+ return int(args.func(args))
136
+
137
+
138
+ if __name__ == "__main__":
139
+ sys.exit(main())
@@ -0,0 +1,543 @@
1
+ # Copyright 2026 Andreas Schachner
2
+ #
3
+ # This file is part of StringForge.
4
+ #
5
+ # StringForge is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+
10
+ r"""
11
+ Certification: stamp the certified-vacuum record contract onto a shard.
12
+
13
+ This is the heart of Phase 1 of the rolling-DB plan: take a batch of
14
+ candidate vacua, *re-certify every row* with the physics cascade, stamp
15
+ the certification provenance (``verifier_id`` / ``cert_status`` /
16
+ ``cert_checks`` / the stability min-eigenvalues / ``record_id``), and
17
+ return only the rows that pass.
18
+
19
+ StringForge is deliberately solver-light (it "is not the flux-vacuum
20
+ solver"), so this module defines only the certification *contract*,
21
+ local endpoint-stability diagnostics, and record-stamping logic -- all
22
+ fully testable with a mock certifier and no JAX. The real physics
23
+ certifier (``jaxvacua.is_physical`` plus the local Vulcan stability
24
+ check) is provided by :func:`build_jaxvacua_certifier`, which lazily
25
+ imports its JAXVacua dependency so importing this module never pulls in
26
+ a solver.
27
+
28
+ The design directly answers the 2026-06-02 incident: a certifier is
29
+ described by a :class:`stringforge.vulcan.verifier.VerifierSpec`, and
30
+ every stamped row records the metric-PD eigenvalue, so a later
31
+ verifier-bug fix can both *select* affected rows (by ``verifier_id``)
32
+ and *detect* a recurrence in aggregate (by ``kahler_metric_min_eig``).
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import math
38
+ from dataclasses import dataclass, field
39
+ import inspect
40
+ from typing import Any, Callable, Dict, Mapping, Optional, Protocol
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+
45
+ from .schema import (
46
+ CERT_COLUMNS,
47
+ GEOMETRY_KEYS,
48
+ GEOMETRY_KEY_SENTINEL,
49
+ canonical_flux as _canonical_flux,
50
+ geometry_id as _geometry_id,
51
+ record_id as _record_id,
52
+ validate_cert_status,
53
+ )
54
+ from .verifier import VerifierSpec
55
+
56
+
57
+ @dataclass
58
+ class CertRow:
59
+ r"""
60
+ **Description:**
61
+ Per-row output of a :class:`Certifier`.
62
+
63
+ Attributes:
64
+ passed: Whether the row passed *all* required checks (i.e. is a
65
+ genuine, stable physical vacuum under this verifier).
66
+ checks: Per-check pass/fail booleans. Keys should be drawn
67
+ from :data:`stringforge.vulcan.verifier.CANONICAL_CHECK_NAMES`.
68
+ kahler_metric_min_eig: Minimum eigenvalue of the Kähler metric
69
+ (the quantity whose *absence* caused the 2026-06-02 bug).
70
+ ``nan`` if the certifier could not compute it.
71
+ hessian_min_eig: Minimum eigenvalue of the real Hessian.
72
+ mass_min_eig: Minimum eigenvalue of the canonically-normalised
73
+ mass matrix.
74
+ """
75
+ passed: bool
76
+ checks: Dict[str, bool] = field(default_factory=dict)
77
+ kahler_metric_min_eig: float = math.nan
78
+ hessian_min_eig: float = math.nan
79
+ mass_min_eig: float = math.nan
80
+
81
+
82
+ @dataclass
83
+ class StabilityRecord:
84
+ r"""
85
+ **Description:**
86
+ Diagnostic stability result for one candidate vacuum.
87
+
88
+ The record is intentionally small and dependency-free: callers
89
+ provide an EFT-like object with ``kahler_metric``, ``hessian`` and
90
+ ``mass_matrix`` methods, and Vulcan records the minimum eigenvalue
91
+ of each matrix together with boolean threshold checks.
92
+ """
93
+ kahler_metric_positive: bool
94
+ hessian_minimum: bool
95
+ mass_minimum: bool
96
+ stable_minimum: bool
97
+ kahler_metric_min_eig: float
98
+ real_hessian_min_eig: float
99
+ mass_matrix_min_eig: float
100
+
101
+
102
+ def _call_eft_method(
103
+ eft: Any,
104
+ names: tuple[str, ...],
105
+ *,
106
+ z: Any,
107
+ tau: Any,
108
+ flux: Any,
109
+ ) -> Any:
110
+ r"""Call the first available EFT method using supported keywords."""
111
+ for name in names:
112
+ fn = getattr(eft, name, None)
113
+ if fn is None:
114
+ continue
115
+ kwargs = {"z": z, "tau": tau, "flux": flux}
116
+ try:
117
+ sig = inspect.signature(fn)
118
+ except (TypeError, ValueError):
119
+ sig = None
120
+ if sig is not None:
121
+ params = sig.parameters
122
+ if not any(p.kind is p.VAR_KEYWORD for p in params.values()):
123
+ kwargs = {k: v for k, v in kwargs.items() if k in params}
124
+ if kwargs:
125
+ try:
126
+ return fn(**kwargs)
127
+ except TypeError:
128
+ pass
129
+ for args in ((z, tau, flux), (z, tau)):
130
+ try:
131
+ return fn(*args)
132
+ except TypeError:
133
+ continue
134
+ raise AttributeError(
135
+ "EFT object must provide one of "
136
+ f"{', '.join(names)} with z/tau/flux-compatible arguments."
137
+ )
138
+
139
+
140
+ def _min_eig(matrix: Any, *, hermitian: bool) -> float:
141
+ r"""Return the minimum real eigenvalue of a matrix-like object."""
142
+ arr = np.asarray(matrix)
143
+ if arr.size == 0:
144
+ return math.nan
145
+ if arr.ndim == 0:
146
+ return float(np.real(arr))
147
+ if arr.ndim == 1:
148
+ return float(np.min(np.real(arr)))
149
+ if arr.shape[-1] != arr.shape[-2]:
150
+ raise ValueError(f"Expected a square matrix; got shape {arr.shape}.")
151
+ if hermitian:
152
+ mat = 0.5 * (arr + np.swapaxes(np.conjugate(arr), -1, -2))
153
+ else:
154
+ mat = 0.5 * (np.real(arr) + np.swapaxes(np.real(arr), -1, -2))
155
+ vals = np.linalg.eigvalsh(mat)
156
+ return float(np.min(np.real(vals)))
157
+
158
+
159
+ def check_endpoint_stability(
160
+ eft: Any,
161
+ *,
162
+ z: Any,
163
+ tau: Any,
164
+ flux: Any,
165
+ source_index: int = -1,
166
+ W0_abs: float = math.nan,
167
+ residual: float = math.nan,
168
+ metric_tol: float = 1e-10,
169
+ hessian_tol: float = -1e-8,
170
+ mass_tol: float = -1e-8,
171
+ min_im_tau: float = 1.0,
172
+ ) -> StabilityRecord:
173
+ r"""
174
+ **Description:**
175
+ Compute Vulcan's local endpoint-stability diagnostics.
176
+
177
+ The EFT object must expose matrix methods for the Kähler metric,
178
+ real Hessian and canonically-normalised mass matrix. Method names
179
+ are accepted in both concise and explicit forms:
180
+ ``kahler_metric`` / ``get_kahler_metric``, ``hessian`` /
181
+ ``real_hessian`` / ``get_hessian``, and ``mass_matrix`` /
182
+ ``get_mass_matrix``. Methods may accept keyword arguments
183
+ ``z``, ``tau`` and ``flux``; unsupported keywords are omitted.
184
+
185
+ Args:
186
+ eft: EFT-like object with matrix-evaluation methods.
187
+ z: Complex-structure moduli vector.
188
+ tau: Axio-dilaton.
189
+ flux: Integer flux vector.
190
+ source_index: Optional source-row index, retained for API
191
+ compatibility with cluster diagnostics.
192
+ W0_abs: Optional ``|W0|`` diagnostic.
193
+ residual: Optional solver residual.
194
+ metric_tol, hessian_tol, mass_tol: Minimum-eigenvalue
195
+ thresholds.
196
+ min_im_tau: Required lower bound on ``Im(tau)``.
197
+
198
+ Returns:
199
+ StabilityRecord: Boolean checks and diagnostic eigenvalues.
200
+ """
201
+ del source_index, W0_abs, residual
202
+
203
+ metric = _call_eft_method(
204
+ eft, ("kahler_metric", "get_kahler_metric"),
205
+ z=z, tau=tau, flux=flux,
206
+ )
207
+ hessian = _call_eft_method(
208
+ eft, ("hessian", "real_hessian", "get_hessian"),
209
+ z=z, tau=tau, flux=flux,
210
+ )
211
+ mass = _call_eft_method(
212
+ eft, ("mass_matrix", "get_mass_matrix"),
213
+ z=z, tau=tau, flux=flux,
214
+ )
215
+
216
+ metric_min = _min_eig(metric, hermitian=True)
217
+ hessian_min = _min_eig(hessian, hermitian=False)
218
+ mass_min = _min_eig(mass, hermitian=False)
219
+
220
+ tau_ok = float(np.imag(tau)) >= float(min_im_tau)
221
+ metric_ok = bool(metric_min > metric_tol)
222
+ hessian_ok = bool(hessian_min >= hessian_tol)
223
+ mass_ok = bool(mass_min >= mass_tol)
224
+
225
+ return StabilityRecord(
226
+ kahler_metric_positive=metric_ok,
227
+ hessian_minimum=hessian_ok,
228
+ mass_minimum=mass_ok,
229
+ stable_minimum=bool(tau_ok and metric_ok and hessian_ok and mass_ok),
230
+ kahler_metric_min_eig=metric_min,
231
+ real_hessian_min_eig=hessian_min,
232
+ mass_matrix_min_eig=mass_min,
233
+ )
234
+
235
+
236
+ class Certifier(Protocol):
237
+ r"""
238
+ **Description:**
239
+ Callable contract for a per-row physics certifier.
240
+
241
+ A certifier receives one candidate vacuum as a mapping (the row's
242
+ columns -- at minimum ``flux``, ``moduli_re``, ``moduli_im``,
243
+ ``tau_re``, ``tau_im``) and returns a :class:`CertRow`. The
244
+ real implementation wraps ``jaxvacua.is_physical`` + the stability
245
+ suite (see :func:`build_jaxvacua_certifier`); tests use a trivial
246
+ in-process stub.
247
+ """
248
+
249
+ def __call__(self, row: Mapping[str, Any]) -> CertRow: # pragma: no cover - protocol
250
+ ...
251
+
252
+
253
+ @dataclass
254
+ class CertifyResult:
255
+ r"""
256
+ **Description:**
257
+ Outcome of :func:`certify_shard`.
258
+
259
+ Attributes:
260
+ certified: DataFrame of the rows that passed, stamped with the
261
+ full certified-record contract. Ready to hand to
262
+ :meth:`stringforge.vulcan.Vulcan.write`.
263
+ rejected: DataFrame of the rows that failed (stamped with their
264
+ ``cert_checks`` / min-eigs for diagnosis), empty when
265
+ ``keep_rejected=False``.
266
+ n_input: Number of input rows.
267
+ n_certified: Number of rows that passed.
268
+ n_rejected: Number of rows that failed.
269
+ verifier_id: The certifying verifier's id.
270
+ """
271
+ certified: pd.DataFrame
272
+ rejected: pd.DataFrame
273
+ n_input: int
274
+ n_certified: int
275
+ n_rejected: int
276
+ verifier_id: str
277
+
278
+
279
+ def _stamp_row_cols(
280
+ df: pd.DataFrame,
281
+ *,
282
+ geometry: Mapping[str, Any],
283
+ verifier_id: str,
284
+ cert_rows: list[CertRow],
285
+ status: str,
286
+ ) -> pd.DataFrame:
287
+ r"""Attach the certified-record columns to a copy of ``df``.
288
+
289
+ The certifier is authoritative on *identity* as well as
290
+ certification: ``geometry_id`` and the geometry-key columns are
291
+ (re)written from the trusted ``geometry`` argument, so a forged
292
+ ``geometry_id`` / ``ks_id`` / ... in the input can never survive
293
+ certification (defence for the community gate).
294
+ """
295
+ out = df.copy()
296
+ # Canonicalise the stored flux to integer quanta so the persisted
297
+ # flux matches the rounded flux used for record_id / dedup (the flux
298
+ # quanta are integers by definition; a near-integer submitted value
299
+ # must not produce an integer key but a non-integer stored vector).
300
+ if "flux" in out.columns and len(out):
301
+ out["flux"] = [list(_canonical_flux(f)) for f in out["flux"]]
302
+ # Authoritative identity from the trusted geometry (overwrite any
303
+ # client-supplied values).
304
+ out["geometry_id"] = _geometry_id(geometry)
305
+ for key in GEOMETRY_KEYS:
306
+ out[key] = int(geometry.get(key, GEOMETRY_KEY_SENTINEL))
307
+ out["verifier_id"] = verifier_id
308
+ out["cert_status"] = status
309
+ out["cert_checks"] = [json.dumps(cr.checks, sort_keys=True) for cr in cert_rows]
310
+ out["kahler_metric_min_eig"] = [float(cr.kahler_metric_min_eig) for cr in cert_rows]
311
+ out["hessian_min_eig"] = [float(cr.hessian_min_eig) for cr in cert_rows]
312
+ out["mass_min_eig"] = [float(cr.mass_min_eig) for cr in cert_rows]
313
+ out["record_id"] = [
314
+ _record_id(geometry, flux, verifier_id) for flux in out["flux"]
315
+ ]
316
+ return out
317
+
318
+
319
+ def certify_shard(
320
+ df: pd.DataFrame,
321
+ *,
322
+ certifier: Certifier,
323
+ verifier_spec: VerifierSpec,
324
+ geometry: Mapping[str, Any],
325
+ keep_rejected: bool = False,
326
+ ) -> CertifyResult:
327
+ r"""
328
+ **Description:**
329
+ Re-certify every row of a candidate shard and stamp the
330
+ certified-vacuum record contract.
331
+
332
+ Each row is passed to ``certifier``; rows that pass are stamped
333
+ ``cert_status="certified"`` and returned in ``result.certified``.
334
+ Rows that fail are **excluded from the certified output** (the
335
+ certified DB only ever contains certified rows); they are returned
336
+ in ``result.rejected`` only when ``keep_rejected=True`` (for
337
+ diagnosis), never with a ``certified`` status.
338
+
339
+ Args:
340
+ df: Candidate shard. Must carry at least ``flux`` plus the
341
+ moduli/tau columns the certifier needs.
342
+ certifier: The per-row physics certifier (see
343
+ :func:`build_jaxvacua_certifier` for the real one; tests
344
+ inject a stub).
345
+ verifier_spec: Description of the certifier; its
346
+ :attr:`~stringforge.vulcan.verifier.VerifierSpec.verifier_id`
347
+ is stamped onto every row and used in the ``record_id``.
348
+ geometry: The model's geometry index dict (mirror convention),
349
+ used to compute ``geometry_id`` / ``record_id``. Must be
350
+ the same convention enforced by the writer at ingest.
351
+ keep_rejected: Also return the failed rows (stamped for
352
+ diagnosis) in ``result.rejected``.
353
+
354
+ Returns:
355
+ CertifyResult: The certified rows plus counts.
356
+
357
+ Raises:
358
+ ValueError: If ``df`` lacks a ``flux`` column, or if
359
+ ``verifier_spec`` is not a :class:`VerifierSpec`.
360
+ """
361
+ if not isinstance(verifier_spec, VerifierSpec):
362
+ raise ValueError("verifier_spec must be a VerifierSpec instance")
363
+ if "flux" not in df.columns:
364
+ raise ValueError("certify_shard: input df must carry a 'flux' column")
365
+
366
+ vid = verifier_spec.verifier_id
367
+ cert_rows: list[CertRow] = [certifier(row) for _, row in df.iterrows()]
368
+ passed_mask = [cr.passed for cr in cert_rows]
369
+
370
+ pass_df = df.loc[passed_mask].reset_index(drop=True)
371
+ pass_cert = [cr for cr, ok in zip(cert_rows, passed_mask) if ok]
372
+ certified = (
373
+ _stamp_row_cols(pass_df, geometry=geometry, verifier_id=vid,
374
+ cert_rows=pass_cert, status="certified")
375
+ if len(pass_df)
376
+ else _empty_certified_frame(df)
377
+ )
378
+ # Defensive: the status we wrote must be valid.
379
+ if len(certified):
380
+ validate_cert_status("certified")
381
+
382
+ rejected = pd.DataFrame()
383
+ if keep_rejected:
384
+ fail_mask = [not ok for ok in passed_mask]
385
+ fail_df = df.loc[fail_mask].reset_index(drop=True)
386
+ fail_cert = [cr for cr, ok in zip(cert_rows, passed_mask) if not ok]
387
+ if len(fail_df):
388
+ # Rejected rows are stamped for diagnosis but NOT given a
389
+ # 'certified' status -- they must never enter the certified
390
+ # DB. We omit cert_status entirely (None) so a careless
391
+ # write cannot mistake them for accepted records.
392
+ rejected = _stamp_row_cols(
393
+ fail_df, geometry=geometry, verifier_id=vid,
394
+ cert_rows=fail_cert, status=None, # type: ignore[arg-type]
395
+ )
396
+
397
+ n_pass = int(sum(passed_mask))
398
+ return CertifyResult(
399
+ certified=certified,
400
+ rejected=rejected,
401
+ n_input=int(len(df)),
402
+ n_certified=n_pass,
403
+ n_rejected=int(len(df)) - n_pass,
404
+ verifier_id=vid,
405
+ )
406
+
407
+
408
+ def _empty_certified_frame(df: pd.DataFrame) -> pd.DataFrame:
409
+ r"""An empty frame with the input columns plus the cert columns."""
410
+ out = df.iloc[0:0].copy()
411
+ for col in CERT_COLUMNS:
412
+ out[col] = pd.Series(dtype="object")
413
+ return out
414
+
415
+
416
+ # ── real physics adapter (lazily imported; not unit-tested here) ──────────
417
+
418
+
419
+ def build_jaxvacua_certifier(
420
+ model: Any,
421
+ sampler: Any,
422
+ *,
423
+ eft: Any = None,
424
+ moduli_max: Optional[float] = None,
425
+ metric_tol: float = 1e-10,
426
+ hessian_tol: float = -1e-8,
427
+ mass_tol: float = -1e-8,
428
+ min_im_tau: float = 1.0,
429
+ stability_fn: Optional[Callable[..., Any]] = None,
430
+ is_physical_fn: Optional[Callable[..., Any]] = None,
431
+ ) -> Certifier:
432
+ r"""
433
+ **Description:**
434
+ Build a real physics :class:`Certifier` wrapping
435
+ ``jaxvacua.flux_utils.is_physical`` (the 5-check cascade incl. the
436
+ Kähler-metric positive-definiteness check) plus the extended
437
+ local stability check (``check_endpoint_stability``: Kähler-metric /
438
+ Hessian / mass-matrix minimum eigenvalues).
439
+
440
+ Dependencies are imported lazily so that importing
441
+ :mod:`stringforge.vulcan.certify` never requires JAX / jaxvacua.
442
+ For testing, ``is_physical_fn`` and ``stability_fn`` may be injected
443
+ to bypass the lazy import entirely.
444
+
445
+ The returned certifier maps each candidate row to a
446
+ :class:`CertRow` whose ``checks`` carries at least
447
+ ``"kahler_metric_pd"``, ``"hessian_min_eig"``, ``"mass_min_eig"``
448
+ (from the stability suite) and ``"is_physical"`` (the overall
449
+ cascade verdict), and whose numeric min-eig fields come from the
450
+ stability record. ``passed`` is the conjunction of the overall
451
+ ``is_physical`` verdict and the stability suite's
452
+ ``stable_minimum``.
453
+
454
+ Args:
455
+ model: A jaxvacua model accepted by ``is_physical``.
456
+ sampler: The jaxvacua sampler providing the dilaton floor etc.
457
+ eft: The EFT object passed to ``check_endpoint_stability`` (it
458
+ needs ``.kahler_metric`` / ``.hessian`` / ``.mass_matrix``).
459
+ Defaults to ``model`` when not given; pass explicitly if the
460
+ model and its EFT are distinct objects in your build.
461
+ moduli_max: Optional runaway bound forwarded to ``is_physical``.
462
+ metric_tol, hessian_tol, mass_tol, min_im_tau: Tolerances
463
+ forwarded to ``check_endpoint_stability``.
464
+ stability_fn: Override for ``check_endpoint_stability`` (tests).
465
+ is_physical_fn: Override for ``jaxvacua.flux_utils.is_physical``
466
+ (tests).
467
+
468
+ Returns:
469
+ Certifier: A per-row certifier closure.
470
+
471
+ Raises:
472
+ ImportError: If the physics dependencies are needed but absent.
473
+ """
474
+ if is_physical_fn is None: # pragma: no cover - exercised only with jaxvacua
475
+ try:
476
+ from jaxvacua.flux_utils import is_physical as is_physical_fn # type: ignore
477
+ except ImportError as exc:
478
+ raise ImportError(
479
+ "build_jaxvacua_certifier requires `jaxvacua` for the "
480
+ "physicality cascade. Install jaxvacua, or inject "
481
+ "is_physical_fn / stability_fn for testing."
482
+ ) from exc
483
+ if stability_fn is None:
484
+ stability_fn = check_endpoint_stability
485
+
486
+ def _certify(row: Mapping[str, Any]) -> CertRow: # pragma: no cover - needs solver
487
+ # The exact packing of (moduli, tau) into the vector x follows
488
+ # jaxvacua conventions; the stability call is local to Vulcan.
489
+ z = np.asarray(row["moduli_re"], dtype=float) + 1j * np.asarray(row["moduli_im"], dtype=float)
490
+ tau = float(row["tau_re"]) + 1j * float(row["tau_im"])
491
+ flux = np.asarray(row["flux"])
492
+ # jaxvacua packs the real moduli vector INTERLEAVED: it reads
493
+ # moduli = x[0:-2:2] + 1j*x[1:-2:2] (flux_eft.py:_convert_real_to_complex),
494
+ # with tau at x[-2], x[-1]. A block layout
495
+ # ([Re(z)..., Im(z)..., Re(tau), Im(tau)]) would scramble the
496
+ # evaluation point for h12>=2 -- is_physical (and its metric-PD
497
+ # check) would then certify the WRONG moduli point. Pack
498
+ # interleaved to match.
499
+ x = np.empty(2 * z.shape[0] + 2, dtype=float)
500
+ x[0:-2:2] = np.real(z)
501
+ x[1:-2:2] = np.imag(z)
502
+ x[-2] = np.real(tau)
503
+ x[-1] = np.imag(tau)
504
+
505
+ phys = bool(is_physical_fn(model, sampler, x, moduli_max=moduli_max))
506
+ stab = stability_fn(
507
+ eft if eft is not None else model,
508
+ z=z, tau=tau, flux=flux, source_index=int(row.get("source_index", -1)),
509
+ W0_abs=float(row.get("W0_abs", float("nan"))),
510
+ residual=float(row.get("residual", float("nan"))),
511
+ metric_tol=metric_tol, hessian_tol=hessian_tol, mass_tol=mass_tol,
512
+ min_im_tau=min_im_tau,
513
+ )
514
+ checks = {
515
+ "is_physical": phys,
516
+ "kahler_metric_pd": bool(getattr(stab, "kahler_metric_positive", False)),
517
+ "hessian_min_eig": bool(getattr(stab, "hessian_minimum", False)),
518
+ "mass_min_eig": bool(getattr(stab, "mass_minimum", False)),
519
+ }
520
+ passed = phys and bool(getattr(stab, "stable_minimum", False))
521
+ # StabilityRecord field names: kahler_metric_min_eig,
522
+ # real_hessian_min_eig, mass_matrix_min_eig. Reading the wrong
523
+ # names would silently store nan, so these are pinned exactly.
524
+ return CertRow(
525
+ passed=passed,
526
+ checks=checks,
527
+ kahler_metric_min_eig=float(getattr(stab, "kahler_metric_min_eig", float("nan"))),
528
+ hessian_min_eig=float(getattr(stab, "real_hessian_min_eig", float("nan"))),
529
+ mass_min_eig=float(getattr(stab, "mass_matrix_min_eig", float("nan"))),
530
+ )
531
+
532
+ return _certify
533
+
534
+
535
+ __all__ = (
536
+ "CertRow",
537
+ "StabilityRecord",
538
+ "Certifier",
539
+ "CertifyResult",
540
+ "check_endpoint_stability",
541
+ "certify_shard",
542
+ "build_jaxvacua_certifier",
543
+ )