forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpayload_codec.py
More file actions
1793 lines (1561 loc) · 75.2 KB
/
Copy pathpayload_codec.py
File metadata and controls
1793 lines (1561 loc) · 75.2 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.
Do not split pack/unpack without serialization A/B tests
(docs/scripting/numpy-serialization.md). Do not move ``_deal_*`` scaffolding
to test-support: the contracts live on the pack functions.
"""
from __future__ import annotations
import array
import logging
import math
import os
import sys
import tempfile
from typing import TYPE_CHECKING, Any, Literal, cast
from plugin.framework.deal_shim import (
DEAL_MAX_ARGV,
DEAL_MAX_COL_INDEX,
DEAL_MAX_ROW_INDEX,
DEAL_MAX_SHAPE_DIM,
DEAL_MAX_SHAPE_RANK,
DEAL_MAX_SOURCE,
DEAL_MAX_TOKEN,
ascii_bounded,
deal,
inverse_ensure,
str_bounded,
)
# 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()
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 _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).
"""
# 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.
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
if isinstance(v, (list, tuple)):
return [_to_py(x) for x in v]
return v
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
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
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."""
# 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, _CYTHON_ACCELERATOR_DISABLED, _CYTHON_ACCELERATOR_LOCATION
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_downloaded_audio_on_path
ensure_downloaded_audio_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.
# 1. contrib.vec_pack (in-tree repository checkout)
try:
import contrib.vec_pack as _vp # type: ignore
fn2d = getattr(_vp, "fast_flatten_grid_2d", None)
fn1d = getattr(_vp, "fast_flatten_grid_1d", None)
if fn2d is not None and fn1d is not None:
loc = "contrib.vec_pack"
except ImportError:
pass
# 2. writeragent_vec (installed under user_config_dir/audio_binaries or standalone package)
if fn2d is None or fn1d is None:
try:
import writeragent_vec as _wv # type: ignore
fn2d = getattr(_wv, "fast_flatten_grid_2d", None)
fn1d = getattr(_wv, "fast_flatten_grid_1d", None)
if fn2d is not None and fn1d is not None:
loc = "writeragent_vec"
except ImportError:
pass
# 3. vec_pack (direct module on sys.path)
if fn2d is None or fn1d is None:
try:
import vec_pack as _vp # type: ignore
fn2d = getattr(_vp, "fast_flatten_grid_2d", None)
fn1d = getattr(_vp, "fast_flatten_grid_1d", None)
if fn2d is not None and fn1d is not None:
loc = "vec_pack"
except ImportError:
pass
# 4. plugin.contrib.vec_pack (legacy fallback)
if fn2d is None or fn1d is None:
try:
import plugin.contrib.vec_pack as _vp # type: ignore
fn2d = getattr(_vp, "fast_flatten_grid_2d", None)
fn1d = getattr(_vp, "fast_flatten_grid_1d", None)
if fn2d is not None and fn1d is not None:
loc = "plugin.contrib.vec_pack"
except ImportError:
pass
# 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
log.debug("payload_codec: Cython accelerator (%s) verified and loaded", loc)
else:
_CYTHON_ACCELERATOR_DISABLED = True
_CYTHON_ACCELERATOR_LOCATION = None
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
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, _CYTHON_ACCELERATOR_DISABLED, _CYTHON_ACCELERATOR_LOCATION
fast_flatten_grid_2d = None
fast_flatten_grid_1d = None
_CYTHON_ACCELERATOR_DISABLED = False
_CYTHON_ACCELERATOR_LOCATION = 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
if loc and loc != "active":
return True, loc, f"Cython Accelerator: Active (Optimized, source: {loc})"
return True, loc, "Cython Accelerator: Active (Optimized)"
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_downloaded_audio_on_path`` when a fresh load is wanted.
"""
if reload:
reload_host_cython_accelerator()
return get_cython_status_info()[2]
# Initial load attempt
load_cython_accelerator()
# --- 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
SPLIT_GRID_WIRE_DTYPE = "float64"
ColumnKind = Literal["int", "float", "bool"]
"""Wire column kind tag. Use ``str`` in function annotations (CrossHair cannot proxy ``Literal``)."""
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 _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).
"""
if not _is_grid_sequence(grid) or not isinstance(grid, (list, tuple)):
return False
if len(grid) > DEAL_MAX_SHAPE_DIM:
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) > DEAL_MAX_SHAPE_DIM:
return False
return True
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``).
"""
if not _is_grid_sequence(grid) or not isinstance(grid, (list, tuple)):
return False
max_rows = DEAL_MAX_ROW_INDEX + 1
max_cols = DEAL_MAX_COL_INDEX + 1
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_numeric_cell_ok(value: object) -> bool:
"""CrossHair domain for ``is_numeric_coercible`` / ``is_numeric_grid`` cells.
Numpy scalars stay allowed in the body (``type(value).__name__``) for
production; 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
def _deal_envelope_value_ok(val: object, *, depth: int) -> bool:
"""Size-capped nests; leaves (scalars, bytes, numpy, dates) are not expanded.
Detectors must still return False on garbage dicts, so values are not
restricted to ascii tokens — only nested list/dict size is capped.
"""
if depth > 10:
return False
if type(val) is str:
return str_bounded(val, DEAL_MAX_SOURCE)
if type(val) is list:
return len(val) <= DEAL_MAX_SHAPE_DIM and all(
_deal_envelope_value_ok(item, depth=depth + 1) for item in val
)
if type(val) is dict:
return _deal_dict_ok_at(val, depth=depth + 1)
return True
def _deal_dict_ok_at(obj: object, *, depth: int) -> bool:
if not isinstance(obj, dict):
return True
if len(obj) > DEAL_MAX_SHAPE_DIM:
return False
for k, v in obj.items():
if type(k) is str:
if not str_bounded(k, DEAL_MAX_TOKEN):
return False
elif type(k) is int:
if abs(k) > DEAL_MAX_ARGV:
return False
else:
return False
if not _deal_envelope_value_ok(v, depth=depth):
return False
return True
def _deal_wire_dict_ok(obj: object) -> bool:
"""Shallow deal domain for live wire envelope detectors (is_split_grid, etc).
_deal_dict_ok_at deep-walks nested dicts and caps them at DEAL_MAX_SHAPE_DIM.
Real split_grid.strings maps have thousands of cell entries (Gemini AFC: 7588);
worker is_split_grid(data) raised PreContractError after host pack succeeded.
Top-level envelope key count stays small; do not deep-walk.
Detectors are already crosshair: off.
"""
if not isinstance(obj, dict):
return True
return len(obj) <= DEAL_MAX_SHAPE_DIM
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) -> list[dict[str, Any]]:
"""Recursively find all image payloads in the object."""
# 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 is_image_payload(obj):
return [obj]
if isinstance(obj, dict):
res = []
for v in obj.values():
res.extend(find_image_payloads(v))
return res
if isinstance(obj, (list, tuple)):
res = []
for x in obj:
res.extend(find_image_payloads(x))
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."""
# 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)
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(payload["data"])
return os.path.abspath(tmp.name)
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 DF/Series data left as ndarray
# by child_pack_result below BINARY_MIN_CELLS per design choice; host unpack tolerates ndarray).
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 _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(isinstance(d, int) and d >= 0 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(isinstance(d, int) and d >= 0 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(isinstance(d, int) and d >= 0 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"
@deal.pre(lambda grid, *_unused, **__: _deal_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)))
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
try:
_unused, _unused2, kinds, _unused3 = _flatten_grid_to_components(grid)
return kinds
except Exception:
return []
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)
and 0 <= ncols <= DEAL_MAX_SHAPE_DIM
)
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 _host_cell_from_float(val: float, *, kind: str) -> Any: # pyright: ignore[reportUnusedFunction] # test helper for host cell kind coercion
# crosshair: off
# cover-all 33797534946 (~46.5m payload_codec). Float/kind coercion leftover. Doable later with closed kind Literal.
if math.isnan(val):
return None
return int(val) if kind == "int" else val
def _apply_column_kinds_to_ndarray(
arr: Any,
column_kinds: list[str],
*,
ncols: int,
is_1d: bool,
uniform: str | None = None,
) -> Any:
"""Cast float64 ndarray columns to int64 where pack declared int (NumPy trusts column metadata)."""
# 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 is None:
uniform = _uniform_column_kind(column_kinds)
if uniform == "int":
return arr.astype(np.int64)
if uniform == "bool":
return arr.astype(np.bool_)
if uniform == "float":
return arr
if is_1d:
if column_kinds[0] == "int":
return arr.astype(np.int64)
if column_kinds[0] == "bool":
return arr.astype(np.bool_)
return arr
# If it's a mixed 2D ndarray, it must remain float64 to hold float columns.
# Casting individual columns is a no-op (coerced back to float64 on assignment).
# We can just return the float64 array directly, saving a massive arr.copy() allocation!
return arr
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_cell_count(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_cell_count(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")
n = wire_cell_count(inner) if inner is not None else 0
return f"dataframe cols={len(cols)} cells~{n}"
if is_calc_range_payload(obj):
shape = obj.get("shape")
return f"calc_range shape={shape} cells={wire_cell_count(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(shape: object) -> bool:
"""True iff *shape* is a rank-bounded tuple of Calc-sized dims.
Unbounded rank or dims let CrossHair deep multiply forever in ``cell_count``.
Dims follow ``DEAL_MAX_ROW_INDEX`` (CrossHair 20; pytest/debug full Calc rows),
not ``DEAL_MAX_SHAPE_DIM`` (256) — Gemini AFC hit PreContractError on (300, 1)
in ``should_use_binary_envelope`` after grid/wire-dict fixes.
"""
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)
)
@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
@deal.pre(lambda shape, *_unused, **__: _deal_shape_ok(shape))
@deal.pre(
lambda shape, *_unused, min_cells=BINARY_MIN_CELLS, force="auto", **__: force in ("auto", "always", "never")
and isinstance(min_cells, int)
and 0 <= min_cells <= DEAL_MAX_SHAPE_DIM
)
# CrossHair may pass call args + result=; never bind ``result`` as a positional parameter.
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), bool))
@deal.ensure(lambda *a, result=_DEAL_RETURN, force="auto", **k: force != "always" or _deal_return(*a, result=result) is True)
@deal.ensure(lambda *a, result=_DEAL_RETURN, force="auto", **k: force != "never" or _deal_return(*a, result=result) is False)
def should_use_binary_envelope(
shape: tuple[int, ...],
*,
min_cells: int = BINARY_MIN_CELLS,
force: ForceBinary = "auto",
) -> bool:
"""Return True if policy says pack data as split_grid instead of JSON lists."""
if force == "always":
return True
if force == "never":
return False
# ``bool(shape)`` on a CrossHair symbolic tuple returns SymbolicBool;
# Python's ``and`` then TypeErrors (``__bool__`` must return bool) —
# should_use_binary_envelope((), min_cells=0, force='auto') on check-all
# deep 32900105768. Empty tuple is still False via len; keep this FQN on.
return len(shape) > 0 and cell_count(shape) >= min_cells
@deal.pre(lambda shape, *_unused, **__: _deal_shape_ok(shape))
@deal.pre(
lambda shape, *_unused, min_cells=BINARY_MIN_CELLS, force="auto", **__: force in ("auto", "always", "never")
and isinstance(min_cells, int)
and 0 <= min_cells <= DEAL_MAX_SHAPE_DIM
)
def binary_envelope_skip_reason(
shape: tuple[int, ...],
*,
min_cells: int = BINARY_MIN_CELLS,
force: ForceBinary = "auto",
) -> str | None:
"""Human-readable reason split_grid was not used; None if envelope would be used."""
# crosshair: off
# cover-all 33797534946 (~46.5m payload_codec, 937 examples). Combinatoric skip-reason strings. Keep should_use_binary_envelope on (_CROSSHAIR_TARGETS). Doable later with closed force/shape domain.
if should_use_binary_envelope(shape, min_cells=min_cells, force=force):
return None
if force == "never":
return "force=never"
ncells = cell_count(shape)
return f"needs cells >= {min_cells} (got {ncells} in shape {shape})"
def _is_numeric_coercible_impl(value: Any) -> bool:
"""Body of ``is_numeric_coercible`` without ``@deal.pre`` (used by ``is_numeric_grid``)."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if value is None or isinstance(value, (bool, int, float)):
return True
# Fast direct type inspection for NumPy scalar types on the child side without module-level imports
tname = type(value).__name__
if tname.startswith(("int", "float", "bool", "uint")):
return True
if isinstance(value, str):
return not value.strip()
return False
@deal.pre(lambda value: _deal_numeric_cell_ok(value))
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), bool))
@deal.ensure(
lambda value, *a, result=_DEAL_RETURN, **k: not (isinstance(value, str) and value.strip())
or _deal_return(*a, result=result) is False
)
@deal.ensure(lambda value, *a, result=_DEAL_RETURN, **k: value is not None or _deal_return(*a, result=result) is True)
@deal.ensure(
lambda value, *a, result=_DEAL_RETURN, **k: not isinstance(value, (bool, int, float))
or _deal_return(*a, result=result) is True
)
def is_numeric_coercible(value: Any) -> bool:
"""True when a cell is numeric-only for ``is_numeric_grid`` / ``np.array(list)`` paths.
Non-empty strings are never coercible here — even ``\"02138\"`` parses as a float — so
mixed grids stay lists after child split_grid unpack (zip codes and labels preserved).
Empty strings match Calc empty cells (``None``).
"""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
return _is_numeric_coercible_impl(value)
@deal.pre(lambda grid: isinstance(grid, list) and _deal_product_grid_ok(grid))
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), bool))
@deal.ensure(lambda grid, *a, result=_DEAL_RETURN, **k: len(grid) > 0 or _deal_return(*a, result=result) is True)
def is_numeric_grid(grid: list[Any] | list[list[Any]]) -> bool:
"""True when every cell is numeric-coercible (safe for numeric-only split_grid fast-path)."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if len(grid) == 0:
return True
if type(grid[0]) in (list, tuple):
return all(_is_numeric_coercible_impl(cell) for row in grid for cell in row)
return all(_is_numeric_coercible_impl(cell) for cell in grid)
@deal.post(lambda *a, result=_DEAL_RETURN, **k: isinstance(_deal_return(*a, result=result), int) and _deal_return(*a, result=result) >= 0)
@deal.ensure(lambda data, *a, result=_DEAL_RETURN, **k: data is not None or _deal_return(*a, result=result) == 0)
def wire_cell_count(data: Any) -> int:
"""Cell count for size limits; works on lists or split_grid / multi_data / calc_range envelopes."""
# crosshair: off
# Envelope detectors + typed payload tags hit CrossHairInternal/Literal proxy errors on garbage dicts.
if is_calc_range_payload(data):
shape = data.get("shape") or [0, 0]
if isinstance(shape, list) and len(shape) == 2:
return int(shape[0]) * int(shape[1])
return wire_cell_count(data.get("data"))
if is_multi_data(data):
items = data.get("items") or []
return sum(wire_cell_count(item) for item in items)
if is_split_grid(data):
return cell_count(tuple(int(x) for x in data["shape"]))
if is_dataframe_payload(data):
return wire_cell_count(data.get("data"))
if data is None:
return 0
if type(data) not in (list, tuple):
return 1
if not data:
return 0
first = data[0]
if type(first) in (list, tuple):
return sum(len(row) for row in data)
return len(data)
@deal.pre(lambda grid: isinstance(grid, list) and _deal_product_grid_ok(grid))
@deal.post(lambda result: isinstance(result, list))
def grid_from_nested_list(grid: list[Any] | list[list[Any]]) -> list[Any] | list[list[Any]]:
"""Normalize to flat or 2D Python lists for small grids (below BINARY_MIN_CELLS) or non-split_grid results."""
# crosshair: off # combinatoric Any/envelope detector (cover-all 33418536119: payload_codec 11581s after PR 523). Doable later with a closed envelope alphabet.
if len(grid) == 0:
return []
if type(grid[0]) in (list, tuple) and all(isinstance(r, (list, tuple)) for r in grid):
return [[_cell_for_json(c) for c in row] for row in grid]
return [_cell_for_json(x) for x in grid]
def _cell_for_json(value: Any) -> Any:
"""Normalize a single egress cell for list paths.
Python None (from mixed/text results or explicit) becomes None (later mapped to empty cell in Calc).
float('nan') / np.nan is preserved so it surfaces as a Calc error (cascades) rather than a silent blank.
This applies to small grids (< BINARY_MIN_CELLS) and list results that do not use the split_grid envelope.
"""
if value is None:
return None
return value
def _flatten_update_column_state(column_states: list[int], c: int, val: Any) -> None:
"""Upgrade per-column numeric kind after a successful float(val) on the fast path."""
# crosshair: off # Any val sibling of already-off flatten (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Doable later with a tiny cell domain.
st = column_states[c]
if st == 3:
return
if val is True or val is False:
if st == 0:
column_states[c] = 1
return
tv = type(val)
if tv is float:
column_states[c] = 3
return
if tv is int:
if st < 2:
column_states[c] = 2
return
dtype = getattr(val, "dtype", None)
if dtype is not None:
kind = getattr(dtype, "kind", None)
if kind == "f":
column_states[c] = 3
elif kind in ("i", "u") and st < 2:
column_states[c] = 2
elif kind == "b" and st == 0:
column_states[c] = 1
return
tname = tv.__name__
if tname.startswith("bool"):
if st == 0:
column_states[c] = 1
elif tname.startswith(("int", "uint")):
if st < 2:
column_states[c] = 2
elif tname.startswith("float"):
column_states[c] = 3
else:
# Decimal/Fraction/etc. already survived float(val). Default to float,
# matching Cython _update_column_state — not int (state 0).
column_states[c] = 3
def _flatten_append_cell_slow(
val: Any,
c: int,
idx: int,
*,
buf_append: Any,
strings: dict[int, str],
column_states: list[int],
column_has_none: list[bool],
nan: float,
) -> None:
"""Full per-cell flatten semantics (None, strings, NumPy scalars, column metadata)."""
# crosshair: off # Any val sibling of already-off flatten (cover-all 33355986432: payload_codec in-flight 6h, no flushed COVER TIMING). Doable later with a tiny cell domain.