Repository navigation
Expand file tree
/
Copy pathpayload_codec.py
More file actions
2607 lines (2278 loc) · 116 KB
/
Copy pathpayload_codec.py
File metadata and controls
2607 lines (2278 loc) · 116 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
"""Wire codec for Calc/chat data crossing the LO host (plain Python) and venv (NumPy).
Large 2D grids (numeric or mixed numeric-text) use Strategy 3 ``split_grid``: the entire
grid is serialized as a single contiguous double-precision flat float64 array (stored as raw
binary bytes) plus a parallel sparse integer-keyed strings dictionary. When the strings
dictionary is empty, NumPy in the child process ingests that via C-speed ``frombuffer`` +
``reshape`` — a direct zero-copy memory view over raw buffer bytes without any Python list/loop
transpositions or Base64 decoding overhead.
Adjust thresholds below if product policy changes; bench and production share this module.
Layout: policy helpers and envelope detectors, then pack/unpack. ``@deal``
contracts and ``# crosshair: off`` markers are intentional — see
docs/scripting/serialization-verification.md. Do not strip them, and do not
split pack/unpack without serialization A/B tests
(docs/scripting/numpy-serialization.md).
Depth caps differ on purpose. ``_MAX_UNPACK_DEPTH`` (128) bounds recursive
unpack, pack, and ``wire_cell_count``. It stays well under CPython's default
recursion limit (~1000) so a cycle raises ``ValueError`` here instead of
``RecursionError``.
``find_image_payloads`` stops at ``_MAX_IMAGE_DEPTH`` (12) because image
trees are shallow (past that it returns ``[]``). The venv
``_CUSTOM_SERIALIZE_MAX_DEPTH`` (8)
bounds custom-type walks and then treats the value as a plain container.
"""
from __future__ import annotations
import array
import logging
import math
import os
import sys
import tempfile
from typing import TYPE_CHECKING, Any, cast
from plugin.framework.deal_shim import (
DEAL_MAX_COL_INDEX,
DEAL_MAX_ROW_INDEX,
DEAL_MAX_SHAPE_DIM,
DEAL_MAX_SHAPE_RANK,
DEAL_MAX_SOURCE,
_profile,
ascii_bounded,
deal,
inverse_ensure,
)
# CrossHair may invoke deal post/ensure as ``fn(*call_args, result=return_value, **kwargs)``.
# Naming a positional parameter ``result`` then raises TypeError (multiple values). Keep ``result`` keyword-only.
_DEAL_RETURN = object()
# Below the default recursion limit (~1000) so this ValueError is reached
# before RecursionError. No identity set on pack/unpack: that would skip a
# shared subtree (see find_image_payloads).
_MAX_UNPACK_DEPTH = 128
# Image trees are shallow. Deeper returns [] instead of raising, so a cyclic
# or huge result still finishes the walk. Not _MAX_UNPACK_DEPTH.
_MAX_IMAGE_DEPTH = 12
# host_unpack_data's contract, including OverflowError from int(inf) on an
# int column. venv_worker catches this same tuple so a bad envelope after
# the script has run is WORKER_IPC_ERROR, not a replay.
_HOST_UNPACK_ERRORS = (ValueError, OverflowError, TypeError, AttributeError, KeyError)
def _deal_return(*args: Any, result: Any = _DEAL_RETURN, **_kwargs: Any) -> Any:
if result is not _DEAL_RETURN:
return result
return args[-1] if args else None
def _numpy_scalar_item(v: Any) -> Any:
"""Return ``v.item()`` for a NumPy scalar; otherwise ``v``.
``calc_range._materialize_inner_grid`` calls this for object-array cells.
The import stays local so the host (LibreOffice Python, no NumPy) can
import this module.
"""
# crosshair: off # numpy import sniff (same reason as _optional_numpy).
try:
import numpy as np # local: safe on host; present in child for mixed grids
if isinstance(v, np.generic):
return v.item()
except Exception:
# numpy not present or v not a numpy scalar; fall through
pass
return v
def _to_py(v: Any) -> Any:
"""Recursively convert numpy scalars and nested sequences to native Python types.
This is only reached for mixed-type (strings-present) child materialization paths.
The import is local so the module can be imported on the host (LibreOffice's Python,
which ships without NumPy).
``obj_arr.tolist()`` may already yield builtin scalars, which would make this
walk redundant. Do not remove it without the serialization A/B suite
(docs/scripting/numpy-serialization.md): dropping it is an unpack change.
"""
# crosshair: off # recursive list/tuple Any (cover-all 33355986432: payload_codec in-flight 6h with sandbox_cache, no flushed COVER TIMING). Doable later with _deal_envelope_value_ok.
item = _numpy_scalar_item(v)
if item is not v:
return item
if isinstance(v, (list, tuple)):
return [_to_py(x) for x in v]
return v
def _optional_numpy() -> Any:
"""Return the NumPy module, or None when this interpreter has no NumPy.
``child_pack_result``, ``_needs_elementwise_pack``,
``_container_has_packable_nested``, and ``_child_unpack_single_data``
used to import NumPy before looking at the value. A plain dict or list
then raised ``ImportError`` in a venv without NumPy (LibreOffice's Python
ships without it, and some user venvs omit it). ``ModuleNotFoundError``
is an ``ImportError``. Callers skip ndarray checks when this returns
None. Numeric ``split_grid`` envelopes still import NumPy on their own.
"""
try:
import numpy as np
except ImportError:
return None
return np
if TYPE_CHECKING:
from collections.abc import Iterator
log = logging.getLogger(__name__)
# --- Optional Cython accelerator --------------------------------------------------
_CYTHON_ACCELERATOR_DISABLED = False
_CYTHON_ACCELERATOR_LOCATION: str | None = None
# Set only after a load attempt fails. None means "not attempted yet" so
# report-only status stays "Inactive (Pure Python)" until the host loads.
_CYTHON_ACCELERATOR_INACTIVE_REASON: str | None = None
fast_flatten_grid_2d: Any = None
fast_flatten_grid_1d: Any = None
def _verify_accelerator(fn2d: Any, fn1d: Any) -> bool:
"""Perform a runtime canary test to ensure the Cython binary is correct and compatible."""
# crosshair: off # Any Cython callables (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Doable later with a closed canary fixture.
try:
if fn2d is None or fn1d is None:
return False
# 2D Test: [[1.0, None], ["text", 2.0]]
test_2d = [[1.0, None], ["text", 2.0]]
buf2, strings2, _unused, has_none2, non_num2 = fn2d(test_2d, 2)
if not (
len(buf2) == 4
and buf2[0] == 1.0
and math.isnan(buf2[1])
and math.isnan(buf2[2])
and buf2[3] == 2.0
and strings2 == {2: "text"}
and has_none2 == [False, True]
and non_num2 is True
):
log.warning("payload_codec: Cython 2D canary failed")
return False
# 1D Test: [1.0, "a", None]
test_1d = [1.0, "a", None]
buf1, strings1, _unused, has_none1, non_num1 = fn1d(test_1d)
if not (
len(buf1) == 3
and buf1[0] == 1.0
and math.isnan(buf1[1])
and math.isnan(buf1[2])
and strings1 == {1: "a"}
and has_none1 == [True]
and non_num1 is True
):
log.warning("payload_codec: Cython 1D canary failed")
return False
# A plain int past ~1e308. float() raises OverflowError. An unguarded
# PyFloat_AsDouble aborts the native call (_try_accel then hides it by
# falling back) or, if the error is cleared and the -1.0 is kept,
# stores a wrong number. The cell must be the decimal text.
huge = 10**400
neg = -huge
buf_huge, strings_huge, _unused_huge, _none_huge, non_huge = fn1d([huge, neg])
if not (
len(buf_huge) == 2
and math.isnan(buf_huge[0])
and math.isnan(buf_huge[1])
and strings_huge.get(0) == str(huge)
and strings_huge.get(1) == str(neg)
and non_huge is True
):
log.warning("payload_codec: Cython huge-int canary failed")
return False
# An int subclass whose __name__ does not start with "int" or "uint"
# must pack as column state 2 (kind "int") on Cython PyLong_Check,
# which is the subclass the pure path used to tag "float".
# The expected state is absolute (not a compare against the Python flattener).
class _CanaryIntSub(int):
pass
buf_sub, strings_sub, col_states_sub, none_sub, non_sub = fn1d([_CanaryIntSub(7)])
if not (
len(buf_sub) == 1
and buf_sub[0] == 7.0
and strings_sub == {}
and col_states_sub == [2]
and none_sub == [False]
and non_sub is False
):
log.warning("payload_codec: Cython int-subclass canary failed")
return False
# dtype.kind "c" whose float() succeeds with only the real part.
# No NumPy import: host load of this canary must stay stdlib-only.
# A kind-"c" object that only fails float() would pass the old
# PyFloat_AsDouble error path and hide the data-loss bug.
class _CanaryComplexKind:
dtype: Any = type("_CanaryDtype", (), {"kind": "c"})()
def __float__(self) -> float:
return 1.0
def __str__(self) -> str:
return "(1+2j)"
cx = _CanaryComplexKind()
buf_cx, strings_cx, _unused_cx, _none_cx, non_cx = fn2d([[cx, 1.0]], 2)
if not (
len(buf_cx) == 2
and math.isnan(buf_cx[0])
and buf_cx[1] == 1.0
and strings_cx.get(0) == "(1+2j)"
and non_cx is True
):
log.warning("payload_codec: Cython complex-kind canary failed")
return False
return True
except Exception as e:
log.warning("payload_codec: Cython canary exception: %s", e)
return False
def load_cython_accelerator() -> None:
"""Attempt to load the Cython accelerator and verify it via a runtime canary test.
Host-only: the HTTP compute service calls this at startup to log Active/Inactive.
Desktop host pack also calls it from ``host_pack_data``. Compute workers unpack
via ``frombuffer`` / pack ndarrays via ``tobytes`` and must not call this
(importing unpack helpers is not a load).
``=PY()`` can reach ``host_pack_data`` off the main thread (yellow bridge).
Two first loads both bind the same canary-verified functions; the GIL makes
that check-then-act idempotent. A lock would not cover an in-flight flatten
during ``invalidate_host_cython_accelerator``. Do not add one unless
invalidate must overlap a pack that is already running.
"""
# crosshair: off # sys.path/import sniffs (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Engine-hostile; keep off.
global fast_flatten_grid_2d, fast_flatten_grid_1d
global _CYTHON_ACCELERATOR_DISABLED, _CYTHON_ACCELERATOR_LOCATION, _CYTHON_ACCELERATOR_INACTIVE_REASON
if fast_flatten_grid_2d is not None or _CYTHON_ACCELERATOR_DISABLED:
return
# Ensure native binary directories (installed user_config or in-tree repo contrib) are on sys.path
try:
from plugin.scripting.native_binaries import ensure_native_binaries_on_path
ensure_native_binaries_on_path()
except Exception as exc:
log.debug("load_cython_accelerator path ensure exception: %s", exc)
fn2d = None
fn1d = None
loc = "none"
# Search import targets in priority order. These four layouts are real
# (checkout, audio_binaries, bare sys.path, legacy plugin.contrib). Skip
# unifying with native_binaries.py — easy to drop the accelerator.
import importlib
for mod_name in (
"contrib.vec_pack",
"writeragent_vec",
"vec_pack",
"plugin.contrib.vec_pack",
):
if fn2d is not None and fn1d is not None:
break
try:
mod = importlib.import_module(mod_name)
except ImportError:
continue
except Exception as exc:
# A broken install must not abort the search. The first layout
# already logged and continued; the later three only caught
# ImportError and would have crashed host pack.
log.warning("load_cython_accelerator exception importing %s: %s", mod_name, exc)
continue
candidate_2d = getattr(mod, "fast_flatten_grid_2d", None)
candidate_1d = getattr(mod, "fast_flatten_grid_1d", None)
if candidate_2d is not None and candidate_1d is not None:
fn2d = candidate_2d
fn1d = candidate_1d
loc = mod_name
# Perform runtime canary test before activating global state
if fn2d is not None and fn1d is not None:
if _verify_accelerator(fn2d, fn1d):
fast_flatten_grid_2d = fn2d
fast_flatten_grid_1d = fn1d
_CYTHON_ACCELERATOR_LOCATION = loc
_CYTHON_ACCELERATOR_DISABLED = False
_CYTHON_ACCELERATOR_INACTIVE_REASON = None
log.debug("payload_codec: Cython accelerator (%s) verified and loaded", loc)
else:
_CYTHON_ACCELERATOR_DISABLED = True
_CYTHON_ACCELERATOR_LOCATION = None
_CYTHON_ACCELERATOR_INACTIVE_REASON = "canary failed"
log.warning("payload_codec: Cython accelerator found at %s but failed canary check; using pure Python", loc)
else:
_CYTHON_ACCELERATOR_DISABLED = True
_CYTHON_ACCELERATOR_LOCATION = None
_CYTHON_ACCELERATOR_INACTIVE_REASON = "not found"
log.debug("payload_codec: Cython accelerator not found, using pure Python")
def invalidate_host_cython_accelerator() -> None:
"""Drop in-process accelerator state after host natives were replaced on disk.
Redownload uses atomic replace (new inode), but ``sys.modules`` may still hold
the old ``writeragent_vec`` module object. Clear globals and module cache so
the next load binds the new file instead of calling into a stale mapping.
"""
# crosshair: off # sys.modules sniffs (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Engine-hostile; keep off.
global fast_flatten_grid_2d, fast_flatten_grid_1d
global _CYTHON_ACCELERATOR_DISABLED, _CYTHON_ACCELERATOR_LOCATION, _CYTHON_ACCELERATOR_INACTIVE_REASON
fast_flatten_grid_2d = None
fast_flatten_grid_1d = None
_CYTHON_ACCELERATOR_DISABLED = False
_CYTHON_ACCELERATOR_LOCATION = None
_CYTHON_ACCELERATOR_INACTIVE_REASON = None
for key in list(sys.modules):
if key in ("writeragent_vec", "contrib.vec_pack", "vec_pack", "plugin.contrib.vec_pack") or key.startswith(
("writeragent_vec.", "contrib.vec_pack.", "vec_pack.", "plugin.contrib.vec_pack.")
):
sys.modules.pop(key, None)
def reload_host_cython_accelerator() -> None:
"""Re-attempt loading the host-side Cython pack accelerator (main thread)."""
global _CYTHON_ACCELERATOR_DISABLED
_CYTHON_ACCELERATOR_DISABLED = False
load_cython_accelerator()
def get_cython_status_info() -> tuple[bool, str | None, str]:
"""Return tuple of (is_active, source_location, status_line)."""
if fast_flatten_grid_2d is not None:
loc = _CYTHON_ACCELERATOR_LOCATION
# Location is a module name (contrib.vec_pack, writeragent_vec, …) or
# missing. It is never the literal "active".
if loc:
return True, loc, f"Cython Accelerator: Active (Optimized, source: {loc})"
return True, loc, "Cython Accelerator: Active (Optimized)"
if _CYTHON_ACCELERATOR_INACTIVE_REASON:
return False, None, f"Cython Accelerator: Inactive (Pure Python; {_CYTHON_ACCELERATOR_INACTIVE_REASON})"
return False, None, "Cython Accelerator: Inactive (Pure Python)"
def host_cython_status_line(*, reload: bool = False) -> str:
"""Human-readable host Cython status for Settings -> Python Test probe header.
Default is report-only (no import/reload). Pass ``reload=True`` on the main
thread after ``native_binaries.ensure_native_binaries_on_path`` when a fresh load is wanted.
"""
if reload:
reload_host_cython_accelerator()
return get_cython_status_info()[2]
# Do not load at import. Compute workers import unpack helpers from this
# module; eager load would make every formula child pay for / claim Cython.
# Host paths call load_cython_accelerator() (HTTP startup, host_pack_data).
# --- Wire kind (JSON-safe dict tag) -----------------------------------------------
PAYLOAD_SPLIT_GRID = "split_grid"
"""Unified 2D grids: dense numeric flat float64 array and sparse strings dictionary."""
PAYLOAD_MULTI_DATA = "multi_data"
"""Multiple Calc ranges: list of split_grid or nested-list payloads."""
PAYLOAD_IMAGE = "image"
"""Matplotlib figure or other visualization serialized as SVG or PNG bytes."""
PAYLOAD_DATAFRAME = "dataframe"
"""Pandas DataFrame (or named Series) egress envelope: column labels + rectangular data grid.
The inner 'data' uses split_grid for large numeric/mixed rectangular results (same as plain arrays)
so that we avoid the expensive list-of-dicts records path while preserving column order/names."""
PAYLOAD_CALC_RANGE = "calc_range"
"""Ingress envelope: one rectangular Calc range. Inner ``data`` is list or split_grid.
User scripts see :class:`plugin.scripting.calc_range.CalcRange`, not the raw wire dict."""
# --- When to use binary envelope (default: at least 100 cells) -----------------------
BINARY_MIN_CELLS = 100
"""Use split_grid when total cell count is at least this."""
MAX_BENCH_CELLS = 100_000
"""Upper cap for benchmark grids (scripts/bench_serialization.py; production cap is scripting.python_max_data_cells)."""
ForceBinary = str
# Envelope ``dtype`` tag only. The buffer codec hardcodes array.array("d") and np.float64.
SPLIT_GRID_WIRE_DTYPE = "float64"
# array.array("d") / np.float64 item size. Buffer length must be a multiple of this.
_FLOAT64_BYTES = 8
def _is_grid_sequence(grid: object) -> bool:
"""True for empty, 1D, or 2D list/tuple grids (jagged 2D allowed; flatten raises ValueError)."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if not isinstance(grid, (list, tuple)):
return False
if len(grid) == 0:
return True
first = grid[0]
if isinstance(first, (list, tuple)):
return all(isinstance(row, (list, tuple)) for row in grid)
return True
def _bounded_rect_grid_ok(grid: object, max_rows: int, max_cols: int) -> bool:
"""True for an empty, 1D, or rectangular-enough 2D list/tuple inside the caps.
1D length uses ``max_rows`` (the outer sequence). A 2D row uses ``max_cols``.
``_deal_grid_ok`` and ``_deal_product_grid_ok`` are the same check with
different caps; this is the one copy.
"""
if not _is_grid_sequence(grid) or not isinstance(grid, (list, tuple)):
return False
if len(grid) > max_rows:
return False
if len(grid) == 0:
return True
first = grid[0]
if isinstance(first, (list, tuple)):
for row in grid:
if not isinstance(row, (list, tuple)) or len(row) > max_cols:
return False
return True
def _deal_grid_ok(grid: object) -> bool:
"""CrossHair domain for list grids. Production ``_is_grid_sequence`` stays uncapped.
Unbounded lists let deep check materialize huge nested grids in
``is_numeric_grid`` / pack. Side length follows ``DEAL_MAX_SHAPE_DIM``
(pytest 256 still fits 100×100 pack-speed tests; CrossHair uses 4).
"""
return _bounded_rect_grid_ok(grid, DEAL_MAX_SHAPE_DIM, DEAL_MAX_SHAPE_DIM)
def _deal_product_grid_ok(grid: object) -> bool:
"""Deal domain for live Calc→worker pack (``host_pack_*`` / flatten).
``_deal_grid_ok`` stays ``DEAL_MAX_SHAPE_DIM``-sized for CrossHair/small helpers.
Product pack must accept real sheet ranges (Population A1:H1517 tripped the
256-row SHAPE_DIM cap: PreContractError surfaced as =PY cell Error text).
Caps at Calc sheet bounds (``DEAL_MAX_ROW_INDEX`` / ``DEAL_MAX_COL_INDEX``).
"""
return _bounded_rect_grid_ok(grid, DEAL_MAX_ROW_INDEX + 1, DEAL_MAX_COL_INDEX + 1)
def _deal_numeric_cell_ok_pytest(value: object) -> bool:
"""Pytest/production: the detector is total.
A list, a long string, or non-ASCII text used to raise PreContractError
instead of False. The body already returns a bool. CrossHair keeps the
scalar/ascii domain. ``value`` is unused.
"""
return True
def _deal_numeric_cell_ok_crosshair(value: object) -> bool:
"""CrossHair domain for ``is_numeric_coercible``.
Numpy scalars stay allowed in the body (``type(value).__name__``);
the pre keeps SMT off ``Any`` + ``startswith``.
"""
if value is None:
return True
t = type(value)
if t is bool:
return True
if t is int or t is float:
return True
if t is str:
return ascii_bounded(value, DEAL_MAX_SOURCE)
return False
_deal_numeric_cell_ok = _profile(_deal_numeric_cell_ok_crosshair, _deal_numeric_cell_ok_pytest)
def _deal_wire_dict_ok_crosshair(obj: object) -> bool:
"""Short top-level key cap for the CrossHair table only.
Real split_grid.strings maps have thousands of cell entries (Gemini AFC: 7588);
do not deep-walk. Detectors are already crosshair: off. The short table still
rejects a dict wider than SHAPE_DIM (4) so the domain stays closed.
"""
if not isinstance(obj, dict):
return True
return len(obj) <= DEAL_MAX_SHAPE_DIM
def _deal_wire_dict_ok_pytest(obj: object) -> bool:
"""Pytest and production, including compute_service where deal stays installed.
Envelope detectors are total predicates. The body returns False for a
plain dict. The old shallow cap (len <= DEAL_MAX_SHAPE_DIM) raised
PreContractError, which subclasses AssertionError, so ValueError handlers
never saw it. host_unpack_data's @deal.pre calls the deal-wrapped
_is_any_payload_envelope, so a word-frequency dict (>256 keys) died before
the isinstance(dict) arm. json_egress is_* calls failed the same way.
Release OXTs strip deal and already accepted these dicts. Do not deep-walk.
``obj`` is unused: every value, including a huge plain dict, is in domain.
"""
return True
_deal_wire_dict_ok = _profile(_deal_wire_dict_ok_crosshair, _deal_wire_dict_ok_pytest)
def _is_multi_data_envelope(envelope: object) -> bool:
# CrossHair TypeError on typing.Literal['a','b','rc'] when proxying empty dict (FV §8.1 D).
# crosshair: off
if not isinstance(envelope, dict):
return False
env_dict = cast("dict[str, Any]", envelope)
if env_dict.get("__wa_payload__") != PAYLOAD_MULTI_DATA:
return False
items = env_dict.get("items")
if not isinstance(items, list):
return False
return all(isinstance(item, (list, dict)) for item in items)
@deal.pre(lambda obj: _deal_wire_dict_ok(obj))
@deal.post(lambda result: isinstance(result, bool))
@inverse_ensure(
lambda obj, result: not result
or (
isinstance(obj, dict)
and obj.get("__wa_payload__") == PAYLOAD_MULTI_DATA
and isinstance(obj.get("items"), list)
)
)
def is_multi_data(obj: Any) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
return _is_multi_data_envelope(obj)
def _is_image_payload_envelope(envelope: object) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if not isinstance(envelope, dict):
return False
env_dict = cast("dict[str, Any]", envelope)
return (
env_dict.get("__wa_payload__") == PAYLOAD_IMAGE
and isinstance(env_dict.get("data"), bytes)
and isinstance(env_dict.get("format"), str)
)
@deal.pre(lambda obj: _deal_wire_dict_ok(obj))
@deal.post(lambda result: isinstance(result, bool))
@inverse_ensure(
lambda obj, result: not result
or (
isinstance(obj, dict)
and obj.get("__wa_payload__") == PAYLOAD_IMAGE
and isinstance(obj.get("data"), bytes)
and isinstance(obj.get("format"), str)
)
)
def is_image_payload(obj: Any) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
return _is_image_payload_envelope(obj)
def find_image_payloads(
obj: Any,
*,
_depth: int = 0,
_seen: set[int] | None = None,
) -> list[dict[str, Any]]:
"""Recursively find all image payloads in the object.
Depth and an identity set stop a cyclic result from blowing the stack.
The set is checked on containers, after an image payload is returned, so
two keys pointing at the same image dict both count. A container already
visited (a shared wrapper, or a cycle) is skipped, so that wrapper's
images are reported once.
"""
# crosshair: off # recursive Any dict/list (cover-all 33355986432: payload_codec in-flight 6h with sandbox_cache, no flushed COVER TIMING). Doable later with _deal_envelope_value_ok.
if _depth > _MAX_IMAGE_DEPTH:
return []
if is_image_payload(obj):
return [obj]
if isinstance(obj, (dict, list, tuple)):
if _seen is None:
_seen = set()
marker = id(obj)
if marker in _seen:
return []
_seen.add(marker)
items = obj.values() if isinstance(obj, dict) else obj
res = []
for item in items:
res.extend(find_image_payloads(item, _depth=_depth + 1, _seen=_seen))
return res
return []
def image_payload_suffix(payload: dict[str, Any]) -> str:
"""Return a temp-file suffix for *payload* (``.svg`` or ``.png``)."""
# crosshair: off
# cover-all 33797534946 (~46.5m payload_codec, 710 examples). Dict Any format probe. Doable later with closed format Literal.
fmt = str(payload.get("format") or "png").lower()
return ".svg" if fmt == "svg" else ".png"
def write_image_payload_to_temp(payload: dict[str, Any]) -> str:
"""Write image bytes from *payload* to a persistent temp file; return absolute path.
The caller owns a successful path. Calc sheet egress and
insert_image_payload_for_doc (Writer and Draw) unlink after GraphicURL loads.
A path returned to the caller, such as PlotDataTool's non-Calc image_path,
stays. A failed write still removes the file this function created.
"""
# crosshair: off # tempfile/filesystem (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Doable later with a bytes/format domain.
suffix = image_payload_suffix(payload)
path = ""
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
path = tmp.name
tmp.write(payload["data"])
return os.path.abspath(tmp.name)
except Exception:
# delete=False leaves the file when write raises (data was not bytes):
# the with-block closes it and the exception propagates. This function
# created the file, so a failed write must not leak it. A successful
# path stays for the caller.
if path:
try:
os.unlink(path)
except OSError:
pass
raise
def _is_dataframe_envelope(envelope: object) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if not isinstance(envelope, dict):
return False
env_dict = cast("dict[str, Any]", envelope)
if env_dict.get("__wa_payload__") != PAYLOAD_DATAFRAME:
return False
cols = env_dict.get("columns")
if not isinstance(cols, list) or not all(isinstance(c, str) for c in cols):
return False
# Explicit ``data`` (including None) is required; missing key is not a DF envelope.
if "data" not in env_dict:
return False
data = env_dict.get("data")
# Accept list/tuple/dict (split_grid or nested), None, or ndarray.
# Small numeric bodies are nested lists. An ndarray is still accepted so an
# older child that skipped list egress still counts as a dataframe envelope.
return isinstance(data, (list, tuple, dict)) or data is None or _is_ndarray(data)
@deal.pre(lambda obj: _deal_wire_dict_ok(obj))
@deal.post(lambda result: isinstance(result, bool))
@inverse_ensure(
lambda obj, result: not result
or (
isinstance(obj, dict)
and obj.get("__wa_payload__") == PAYLOAD_DATAFRAME
and isinstance(obj.get("columns"), list)
and "data" in obj
)
)
def is_dataframe_payload(obj: Any) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
return _is_dataframe_envelope(obj)
def _nonneg_shape_dim(d: object) -> bool:
"""True when a shape extent is a real non-negative int.
``bool`` is a subclass of ``int``, so ``isinstance(True, int)`` accepted
``[True, 1]`` as a calc_range or split_grid shape. Pack writes Python
ints; a bare or legacy wire could pass a bool.
"""
# crosshair: off
if isinstance(d, bool) or not isinstance(d, int):
return False
return d >= 0
def _is_calc_range_envelope(envelope: object) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if not isinstance(envelope, dict):
return False
env_dict = cast("dict[str, Any]", envelope)
if env_dict.get("__wa_payload__") != PAYLOAD_CALC_RANGE:
return False
shape = env_dict.get("shape")
if not isinstance(shape, list) or len(shape) != 2:
return False
if not all(_nonneg_shape_dim(d) for d in shape):
return False
return "data" in env_dict
@deal.pre(lambda obj: _deal_wire_dict_ok(obj))
@deal.post(lambda result: isinstance(result, bool))
@inverse_ensure(
lambda obj, result: not result
or (
isinstance(obj, dict)
and obj.get("__wa_payload__") == PAYLOAD_CALC_RANGE
and isinstance(obj.get("shape"), list)
and len(obj["shape"]) == 2
and all(_nonneg_shape_dim(d) for d in obj["shape"])
and "data" in obj
)
)
def is_calc_range_payload(obj: Any) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
# Canonical wire guard. calc_range.py re-exports this; do not add a second copy.
return _is_calc_range_envelope(obj)
def _is_split_grid_envelope(envelope: object) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if not isinstance(envelope, dict):
return False
env_dict = cast("dict[str, Any]", envelope)
if env_dict.get("__wa_payload__") != PAYLOAD_SPLIT_GRID:
return False
shape = env_dict.get("shape")
if not isinstance(shape, list) or len(shape) not in (1, 2):
return False
if not all(_nonneg_shape_dim(d) for d in shape):
return False
return isinstance(env_dict.get("buffer"), bytes) or isinstance(env_dict.get("b64"), str)
@deal.pre(lambda obj: _deal_wire_dict_ok(obj))
@deal.post(lambda result: isinstance(result, bool))
def _is_any_payload_envelope(obj: object) -> bool:
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
# Body already ORs the five family detectors; a matching ensure re-ran all
# five on every CrossHair post (check-all deep 32900105768, 8:14).
return (
_is_split_grid_envelope(obj)
or _is_multi_data_envelope(obj)
or _is_image_payload_envelope(obj)
or _is_dataframe_envelope(obj)
or _is_calc_range_envelope(obj)
)
def _is_ndarray(obj: object) -> bool:
return type(obj).__name__ == "ndarray" and type(obj).__module__ == "numpy"
# Pytest accepts real sheets. ``_deal_grid_ok``'s 256-row cap raised
# PreContractError on a sheet pack accepts. CrossHair keeps that small domain.
_deal_column_kinds_grid_ok = _profile(_deal_grid_ok, _deal_product_grid_ok)
@deal.pre(lambda grid, *_unused, **__: _deal_column_kinds_grid_ok(grid))
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), list))
@deal.ensure(lambda grid, *a, result=_DEAL_RETURN, **k: all(x in ("int", "float", "bool") for x in _deal_return(*a, result=result)))
@deal.raises(ValueError)
def column_kinds_for_grid(grid: list[Any] | list[list[Any]]) -> list[str]:
"""Policy helper (tests): per-column int/float/bool from source types; mirrors host_pack_split_grid."""
# crosshair: off
# ``except Exception: return []`` hid the jagged-grid ValueError that
# flatten raises, and the small deal domain rejected a sheet pack accepts.
# Call flatten directly. pytest uses the product-grid pre, and a jagged
# grid raises.
_unused, _unused2, kinds, _unused3 = _flatten_grid_to_components(grid)
return kinds
def _uniform_column_kind(kinds: list[str]) -> str | None:
"""Return the kind when every column matches; else None (mixed columns)."""
# crosshair: off
# cover-all 33797534946 (~46.5m payload_codec, 634 examples). Combinatoric kinds list. Doable later with tiny kind alphabet.
if not kinds:
return None
first = kinds[0]
return first if all(k == first for k in kinds) else None
@deal.pre(
lambda envelope, *_unused, ncols=0, **__: _deal_wire_dict_ok(envelope)
and isinstance(ncols, int)
# Same Calc column cap as ``_deal_product_grid_ok`` (pack). SHAPE_DIM (256)
# rejected a wide sheet after pack succeeded: PreContractError on unpack.
# Release strips deal, so the body already accepts this width; the pre must too.
and 0 <= ncols <= DEAL_MAX_COL_INDEX + 1
)
def envelope_column_kinds(envelope: dict[str, Any], *, ncols: int) -> list[str]:
"""Per-column unpack kinds from wire ``column_kinds``."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
kinds = envelope.get("column_kinds")
if isinstance(kinds, list) and len(kinds) == ncols:
return ["int" if k == "int" else ("bool" if k == "bool" else "float") for k in kinds]
return ["float"] * ncols
def envelope_uniform_column_kind(envelope: dict[str, Any], *, ncols: int) -> str | None:
"""Decode-only: all-int or all-float fast path when ``column_kinds`` are uniform; None if mixed."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
return _uniform_column_kind(envelope_column_kinds(envelope, ncols=ncols))
def _apply_column_kinds_to_ndarray(arr: Any, *, uniform: str | None) -> Any:
"""Cast a uniform int or bool float64 ndarray. Mixed or float stays float64.
Callers pass ``uniform`` from ``_uniform_column_kind``. A 1-D grid has one
column, so that value is ``int``, ``bool``, or ``float``. The old
``if is_1d`` arm re-read ``column_kinds[0]`` after that and never ran.
"""
# crosshair: off # numpy astype on Any (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Doable later with an ndarray/kinds domain.
import numpy as np
if uniform == "int":
# Host unpack keeps NaN as float("nan") and raises OverflowError on inf.
# This astype(np.int64) instead stores a garbage int and emits
# RuntimeWarning: invalid value encountered in cast for NaN, inf, and
# a float outside the int64 range. Pack never writes NaN into an int
# column because column_has_none promotes it to "float". Calc ingress
# does not produce ints outside the 53-bit mantissa. child_pack of a
# uint64 array is unpacked on the host with Python int(), which stays
# non-negative and rounded, and this child cast is not that consumer.
# Do not scan for NaN, do not retag "float", and do not replace the
# fast path with a Python int() loop. Locked policy is
# docs/calc/py-data-shapes.md (Int fidelity), no int64 wire lane.
return arr.astype(np.int64)
if uniform == "bool":
# Host unpack treats only 1.0 as True. astype(bool) made every non-zero True.
# NaN becomes False here: a bool ndarray cannot store NaN. Host unpack
# keeps that NaN so a corrupt bool column still surfaces as a Calc error.
# Do not np.where the NaN back in — that promotes a clean bool column to float64.
return arr == 1.0
# float, mixed, or empty kinds: stay float64. Casting mixed columns
# one-by-one is a no-op (assignment coerces them back to float64).
return arr
def _wire_cells_for_log(data: Any) -> str:
"""Cell count for a debug line.
``wire_cell_count`` raises ``ValueError`` on a cycle. This summary is
called from ``except`` handlers; that error must not replace the caller's.
"""
try:
return str(wire_cell_count(data))
except ValueError:
return "?"
def describe_wire_value(obj: Any, *, sample: int = 3) -> str:
"""Short summary for debug logs (avoids dumping huge arrays or base64)."""
# crosshair: off # recursive Any walk (cover-all 33355986432: payload_codec in-flight 6h with sandbox_cache, no flushed COVER TIMING). Doable later with _deal_envelope_value_ok + sample bound.
if is_image_payload(obj):
return f"image format={obj.get('format')} bytes={len(obj.get('data', b''))}"
if is_multi_data(obj):
items = obj.get("items") or []
return f"multi_data items={len(items)} cells={_wire_cells_for_log(obj)}"
if is_split_grid(obj):
buf = obj.get("buffer") or b""
strings = obj.get("strings") or {}
return (
f"split_grid shape={obj.get('shape')} cells={_wire_cells_for_log(obj)} "
f"column_kinds={obj.get('column_kinds')} strings={len(strings)} raw_bytes={len(buf)}"
)
if is_dataframe_payload(obj):
cols = obj.get("columns") or []
inner = obj.get("data")
cells = _wire_cells_for_log(inner) if inner is not None else "0"
return f"dataframe cols={len(cols)} cells~{cells}"
if is_calc_range_payload(obj):
shape = obj.get("shape")
return f"calc_range shape={shape} cells={_wire_cells_for_log(obj)}"
if obj is None:
return "None"
if isinstance(obj, (str, int, float, bool)):
return f"{type(obj).__name__}={obj!r}"
if isinstance(obj, dict):
if "__wa_payload__" in obj:
return f"dict(payload={obj.get('__wa_payload__')!r} keys={list(obj)})"
keys = list(obj.keys())[:sample]
return f"dict(keys={keys}{'…' if len(obj) > sample else ''})"
if isinstance(obj, (list, tuple)):
n = len(obj)
if n == 0:
return "list[]"
first = obj[0]
if isinstance(first, (list, tuple)):
# Be defensive: some list elements may not be rows (e.g. hypothesis fancier results with mixed nesting).
try:
ncols = max((len(r) for r in obj if isinstance(r, (list, tuple))), default=0)
return f"list[{n}x{ncols}] sample_row={list(first)[:sample]!r}"
except Exception:
return f"list[{n}x?] sample_row={list(first)[:sample]!r}"
return f"list[{n}] sample={list(obj)[:sample]!r}"
return f"{type(obj).__name__}={repr(obj)[:120]}"
def _deal_shape_ok_pytest(shape: object) -> bool:
"""Wide Calc-sized shape domain for pytest / production deal checks."""
max_dim = DEAL_MAX_ROW_INDEX + 1
return (
isinstance(shape, tuple)
and len(shape) <= DEAL_MAX_SHAPE_RANK
and all(isinstance(d, int) and 0 <= d <= max_dim for d in shape)
)
def _deal_shape_ok_crosshair(shape: object) -> bool:
"""Tiny shape domain for CrossHair.
cover-all 35546602462 spent ~29m on ``should_use_binary_envelope`` /
``cell_count`` despite ``DEAL_MAX_ROW_INDEX=20``. Keep the FQNs on with a
2×{0..4} grid instead of off.
"""
return (
isinstance(shape, tuple)
and len(shape) <= 2
and all(isinstance(d, int) and 0 <= d <= 4 for d in shape)
)
_deal_shape_ok = _profile(_deal_shape_ok_crosshair, _deal_shape_ok_pytest)
@deal.pre(lambda shape: _deal_shape_ok(shape))
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), int))
@deal.ensure(lambda shape, *a, result=_DEAL_RETURN, **k: _deal_return(*a, result=result) >= 0)
@deal.ensure(lambda shape, *a, result=_DEAL_RETURN, **k: len(shape) != 0 or _deal_return(*a, result=result) == 1)
def cell_count(shape: tuple[int, ...]) -> int:
n = 1
for d in shape:
n *= d
return n
def _deal_force_min_cells_domain(min_cells: object, force: object, *, max_cells: int) -> bool:
"""Shared ``force`` / ``min_cells`` domain for policy and pack contracts.
``should_use_binary_envelope``, ``binary_envelope_skip_reason``,
``host_pack_data``, and ``host_pack_multi_data`` used to repeat this
check. Each ``@deal.pre`` stays a keyword-default lambda so CrossHair's
call shape still matches. The cap is chosen once via ``_profile``:
CrossHair keeps ``DEAL_MAX_SHAPE_DIM`` so the search domain stays small.
Pytest allows a cell-count threshold up to one full Calc column
(``DEAL_MAX_ROW_INDEX + 1``). ``DEAL_MAX_SHAPE_DIM`` (256) is a side
length; it rejected ``scripts/bench_serialization.py --min-cells 1000``.
"""
return (
force in ("auto", "always", "never")
and isinstance(min_cells, int)
and 0 <= min_cells <= max_cells
)
def _deal_force_min_cells_ok_crosshair(min_cells: object, force: object) -> bool: