-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.py
More file actions
executable file
·1358 lines (1125 loc) · 46.6 KB
/
Copy pathhook.py
File metadata and controls
executable file
·1358 lines (1125 loc) · 46.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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
#!/usr/bin/env python3
"""Codex hook prototype for deterministic context-format selection.
This hook is intentionally conservative:
- It only optimizes files explicitly referenced in the user prompt.
- It only emits lossless representations for JSON/CSV/TSV input.
- It chooses the lowest model-token count from a fixed candidate set.
The selector is deterministic. Better token counters can be plugged in without
changing the selection contract.
"""
from __future__ import annotations
import csv
import hashlib
import importlib.util
import io
import json
import os
import re
import shlex
import sys
import time
import tomllib
from dataclasses import asdict, dataclass, replace
from functools import lru_cache
from pathlib import Path
from typing import Any, Iterable
SUPPORTED_EXTENSIONS = {".json", ".jsonl", ".csv", ".tsv"}
SAFE_CANDIDATES = {"raw", "compact-json", "column-json", "csv", "tsv"}
CANDIDATE_TIERS = {
"safe": SAFE_CANDIDATES,
"advanced": SAFE_CANDIDATES | {"codebook-json", "typed-csv", "typed-tsv"},
}
DEFAULT_CANDIDATE_TIER = "safe"
SCHEMA_VERSION = "context-selector/v1"
DEFAULT_MAX_BYTES = 5_000_000
DEFAULT_INLINE_MAX_CHARS = 12_000
DEFAULT_MIN_SAVINGS_RATIO = 0.05
DEFAULT_MIN_SAVED_TOKENS = 128
DEFAULT_PROVIDER_INPUT_TOKENS_PER_SECOND = 0.0
DEFAULT_MIN_NET_LATENCY_SAVED_MS = 0.0
DEFAULT_MAX_HOOK_LATENCY_MS = 500
RAW_INTENT_RE = re.compile(
r"\b("
r"exact bytes|verbatim|original formatting|whitespace|line numbers?|raw text|"
r"show (?:me )?the file|quote the file|as-is|line-by-line|delimiter|comma|tab|json syntax"
r")\b",
re.I,
)
try:
csv.field_size_limit(sys.maxsize)
except OverflowError:
csv.field_size_limit(2**31 - 1)
@dataclass(frozen=True)
class SourceData:
path: Path
kind: str
value: Any
raw_text: str
@dataclass(frozen=True)
class Candidate:
name: str
text: str
reversible: bool
instructions: str
notes: tuple[str, ...] = ()
@dataclass(frozen=True)
class ModelProfile:
slug: str
provider: str
tokenizer_family: str
token_counter: str
context_window: int | None
auto_compact_token_limit: int | None
source: str
@dataclass(frozen=True)
class Choice:
source: Path
candidate: Candidate
raw_tokens: int
payload_tokens: int
instruction_tokens: int
total_tokens: int
savings_ratio: float
output_path: Path | None = None
@dataclass(frozen=True)
class RewritePlan:
choices: tuple[Choice, ...]
updated_command: str
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception as exc:
return emit_error(f"Invalid hook JSON: {exc}")
event_name = payload.get("hook_event_name") or payload.get("hookEventName")
if event_name == "UserPromptSubmit":
return handle_user_prompt_submit(payload)
if event_name == "PreToolUse":
return handle_pre_tool_use(payload)
return emit_noop()
def handle_user_prompt_submit(payload: dict[str, Any]) -> int:
if os.environ.get("CONTEXT_OPTIMIZER_VISIBLE_PROMPT_INJECTION") != "1":
return emit_noop()
prompt = str(payload.get("prompt") or "")
cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
max_bytes = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES))
inline_max_chars = int(os.environ.get("CONTEXT_OPTIMIZER_INLINE_MAX_CHARS", DEFAULT_INLINE_MAX_CHARS))
policy = savings_policy_from_env()
candidate_tier = candidate_tier_from_env()
report_skips = os.environ.get("CONTEXT_OPTIMIZER_REPORT_SKIPS") == "1"
if prompt_requests_raw_file(prompt):
return emit_noop()
paths = discover_paths(prompt, cwd)
choices: list[Choice] = []
skipped: list[str] = []
cache_dir = cwd / ".codex" / "context-cache"
for path in paths:
try:
if path.stat().st_size > max_bytes:
skipped.append(f"{path}: skipped; over {max_bytes} bytes")
continue
source = load_source(path)
choice = choose_best(source, model_profile, cache_dir, candidate_tier, persist_sidecar=False)
if should_inject(choice, policy):
choices.append(choice_with_sidecar(choice, source, cache_dir, model_profile, candidate_tier))
elif report_skips:
skipped.append(
f"{path}: no injection; best={choice.candidate.name}, savings={choice.savings_ratio:.1%}"
)
except Exception as exc:
if report_skips:
skipped.append(f"{path}: skipped; {exc}")
if not choices and not skipped:
return emit_noop()
context = build_additional_context(choices, skipped, model_profile, inline_max_chars)
print(
json.dumps(
{
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": context,
}
},
ensure_ascii=False,
)
)
return 0
def handle_pre_tool_use(payload: dict[str, Any]) -> int:
tool_name = str(payload.get("tool_name") or payload.get("toolName") or "")
if tool_name != "Bash":
return emit_noop()
tool_input = payload.get("tool_input") or payload.get("toolInput") or {}
if not isinstance(tool_input, dict):
return emit_noop()
command = str(tool_input.get("command") or "")
cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve()
paths = plain_cat_paths(command, cwd)
if not paths:
return emit_noop()
try:
plan = build_rewrite_plan(paths, payload, cwd)
if plan is None:
return emit_noop()
except Exception:
return emit_noop()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
report_path = write_hook_report(plan.choices, cwd, model_profile, "codex-pre-tool-use")
if not verify_hook_report(report_path):
return emit_noop()
hook_output: dict[str, Any] = {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {"command": plan.updated_command},
}
if os.environ.get("CONTEXT_OPTIMIZER_EXPLAIN_REWRITES") == "1":
summary = "; ".join(rewrite_summary(choice) for choice in plan.choices)
hook_output["additionalContext"] = (
"Context optimizer rewrote a whole-file context read to optimized sidecar file(s). "
f"{summary}"
)
print(
json.dumps(
{
"hookSpecificOutput": hook_output
},
ensure_ascii=False,
)
)
return 0
def emit_noop() -> int:
print("{}")
return 0
def emit_error(message: str) -> int:
print(f"Context optimizer hook error: {message}", file=sys.stderr)
return emit_noop()
def prompt_requests_raw_file(prompt: str) -> bool:
return bool(RAW_INTENT_RE.search(prompt))
def discover_paths(prompt: str, cwd: Path) -> list[Path]:
"""Find plausible local data paths mentioned in the prompt."""
candidates: set[Path] = set()
quoted = re.findall(r"""['"`]([^'"`\n]+\.(?:jsonl?|csv|tsv))['"`]""", prompt, flags=re.I)
bare = re.findall(r"""(?<![\w:/.-])((?:\./|\.\./|/|[A-Za-z0-9_.-]+/)?[A-Za-z0-9_./-]+\.(?:jsonl?|csv|tsv))(?![\w.-])""", prompt, flags=re.I)
for raw in [*quoted, *bare]:
raw = raw.strip()
if not raw:
continue
resolved = resolve_supported_file(raw, cwd)
if resolved is not None:
candidates.add(resolved)
return sorted(candidates)
def plain_cat_paths(command: str, cwd: Path) -> list[Path]:
try:
parts = shlex.split(command)
except ValueError:
return []
if len(parts) >= 3 and parts[0] == "cat" and parts[1] == "--":
raw_paths = parts[2:]
elif len(parts) >= 2 and parts[0] == "cat":
raw_paths = parts[1:]
else:
return []
paths: list[Path] = []
for raw_path in raw_paths:
if raw_path.startswith("-"):
return []
resolved = resolve_supported_file(raw_path, cwd)
if resolved is None:
return []
paths.append(resolved)
return paths
def resolve_supported_file(raw_path: str, cwd: Path) -> Path | None:
path = Path(raw_path).expanduser()
if not path.is_absolute():
path = cwd / path
try:
resolved = path.resolve()
except OSError:
return None
if resolved.exists() and resolved.is_file() and resolved.suffix.lower() in SUPPORTED_EXTENSIONS:
return resolved
return None
def build_rewrite_plan(paths: list[Path], payload: dict[str, Any], cwd: Path) -> RewritePlan | None:
if not paths:
return None
started_at = time.perf_counter()
max_bytes = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES))
max_hook_ms = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_HOOK_LATENCY_MS", DEFAULT_MAX_HOOK_LATENCY_MS))
policy = savings_policy_from_env()
candidate_tier = candidate_tier_from_env()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
cache_dir = cwd / ".codex" / "context-cache"
pending: list[tuple[SourceData, Choice]] = []
for path in paths:
if pending and elapsed_milliseconds(started_at) > max_hook_ms:
return None
if path.stat().st_size > max_bytes:
return None
source = load_source(path)
choice = choose_best(source, model_profile, cache_dir, candidate_tier, persist_sidecar=False)
if not should_inject(choice, policy):
return None
pending.append((source, choice))
local_milliseconds = elapsed_milliseconds(started_at)
choices = [choice for _source, choice in pending]
if not should_rewrite_for_latency(choices, local_milliseconds, latency_policy_from_env()):
return None
persisted = [
choice_with_sidecar(choice, source, cache_dir, model_profile, candidate_tier)
for source, choice in pending
]
updated_command = "cat -- " + " ".join(shlex.quote(str(require_output_path(choice))) for choice in persisted)
return RewritePlan(tuple(persisted), updated_command)
def rewrite_summary(choice: Choice) -> str:
percent = round(choice.savings_ratio * 100, 1)
return (
f"Source: {choice.source}. Optimized: {require_output_path(choice)}. "
f"Selected format: {choice.candidate.name}. "
f"{token_count_label(choice)}: {choice.total_tokens} vs raw {choice.raw_tokens} ({percent}% savings)."
)
def write_hook_report(
choices: tuple[Choice, ...],
cwd: Path,
model_profile: ModelProfile,
adapter: str,
) -> Path:
for choice in choices:
require_output_path(choice)
report_dir = cwd / ".codex" / "context-cache" / "reports"
report_dir.mkdir(parents=True, exist_ok=True)
digest_input = "\n".join(
f"{choice.source}\0{choice.output_path}\0{choice.total_tokens}"
for choice in choices
)
digest = hashlib.sha256(digest_input.encode("utf-8")).hexdigest()[:16]
report_path = report_dir / f"{adapter}.{digest}.json"
raw_tokens = sum(choice.raw_tokens for choice in choices)
selected_tokens = sum(choice.total_tokens for choice in choices)
report = {
"schema_version": SCHEMA_VERSION,
"adapter": adapter,
"cwd": str(cwd),
"out_dir": str(cwd / ".codex" / "context-cache"),
"model_profile": asdict(model_profile),
"policy": {
"supported_extensions": sorted(SUPPORTED_EXTENSIONS),
"max_bytes": int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES)),
"max_hook_latency_milliseconds": int(
os.environ.get("CONTEXT_OPTIMIZER_MAX_HOOK_LATENCY_MS", DEFAULT_MAX_HOOK_LATENCY_MS)
),
"candidate_tier": candidate_tier_from_env(),
**savings_policy_from_env(),
**latency_policy_from_env(),
"include_candidates": False,
},
"summary": {
"files": len(choices),
"selected_files": len(choices),
"raw_tokens": raw_tokens,
"selected_tokens": selected_tokens,
"saved_tokens": raw_tokens - selected_tokens,
"savings_ratio": 0.0 if raw_tokens == 0 else 1.0 - (selected_tokens / raw_tokens),
},
"results": [choice_report(choice, model_profile) for choice in choices],
}
report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return report_path
def verify_hook_report(report_path: Path) -> bool:
try:
from verify_selector_report import validate_report
report = json.loads(report_path.read_text(encoding="utf-8"))
errors = validate_report(report, check_files=True)
except Exception:
return False
return not errors
def choice_report(choice: Choice, model_profile: ModelProfile) -> dict[str, Any]:
output_path = require_output_path(choice)
return {
"source": str(choice.source),
"source_name": choice.source.name,
"selected": True,
"decision": "selected",
"read_path": str(output_path),
"kind": choice.source.suffix.lower().lstrip("."),
"bytes": choice.source.stat().st_size,
"sha256": sha256_file(choice.source),
"raw_tokens": choice.raw_tokens,
"selected_format": choice.candidate.name,
"selected_tokens": choice.total_tokens,
"payload_tokens": choice.payload_tokens,
"instruction_tokens": choice.instruction_tokens,
"saved_tokens": choice.raw_tokens - choice.total_tokens,
"savings_ratio": choice.savings_ratio,
"token_counter_label": "estimated" if model_profile.token_counter == "deterministic-fallback" else "exact",
"output_path": str(output_path),
"output_sha256": sha256_file(output_path),
"notes": list(choice.candidate.notes),
}
def sha256_file(path: Path) -> str:
with path.open("rb") as handle:
return hashlib.file_digest(handle, "sha256").hexdigest()
def load_source(path: Path) -> SourceData:
suffix = path.suffix.lower()
text = path.read_text(encoding="utf-8-sig")
if suffix == ".json":
return SourceData(path=path, kind="json", value=json.loads(text), raw_text=text)
if suffix == ".jsonl":
rows = [json.loads(line) for line in text.splitlines() if line.strip()]
return SourceData(path=path, kind="jsonl", value=rows, raw_text=text)
if suffix in {".csv", ".tsv"}:
delimiter = "\t" if suffix == ".tsv" else ","
reader = csv.DictReader(io.StringIO(text), delimiter=delimiter)
rows = [dict(row) for row in reader]
return SourceData(path=path, kind=suffix[1:], value=rows, raw_text=text)
raise ValueError(f"unsupported extension {suffix}")
def choose_best(
source: SourceData,
model_profile: ModelProfile,
cache_dir: Path,
candidate_tier: str | None = None,
persist_sidecar: bool = True,
raw_tokens: int | None = None,
) -> Choice:
if raw_tokens is None:
raw_tokens = count_tokens(source.raw_text, model_profile)
tier = normalize_candidate_tier(candidate_tier or DEFAULT_CANDIDATE_TIER)
candidates = generated_candidates_for_profile(source, model_profile, tier)
if not candidates:
raise ValueError("no safe candidates generated")
ranked = sorted(
((candidate_token_metrics(candidate, model_profile), candidate) for candidate in candidates),
key=lambda item: candidate_rank_key(item[1], item[0]),
)
for metrics, candidate in ranked:
if candidate_matches_source(source, candidate):
best = candidate_with_roundtrip_note(candidate)
break
else:
raise ValueError("no reversible candidates generated")
total_tokens, payload_tokens, instruction_tokens = metrics
output_path = (
write_candidate_sidecar(source, best, cache_dir, model_profile, tier)
if persist_sidecar
else None
)
savings_ratio = 0.0 if raw_tokens == 0 else 1.0 - (total_tokens / raw_tokens)
return Choice(
source=source.path,
candidate=best,
raw_tokens=raw_tokens,
payload_tokens=payload_tokens,
instruction_tokens=instruction_tokens,
total_tokens=total_tokens,
savings_ratio=savings_ratio,
output_path=output_path,
)
def choice_with_sidecar(
choice: Choice,
source: SourceData,
cache_dir: Path,
model_profile: ModelProfile,
candidate_tier: str,
) -> Choice:
output_path = write_candidate_sidecar(source, choice.candidate, cache_dir, model_profile, candidate_tier)
return replace(choice, output_path=output_path)
def require_output_path(choice: Choice) -> Path:
if choice.output_path is None:
raise ValueError("selected choice is missing optimized sidecar path")
return choice.output_path
def candidate_token_metrics(candidate: Candidate, model_profile: ModelProfile) -> tuple[int, int, int]:
return (
count_tokens(candidate_blob(candidate), model_profile),
count_tokens(candidate.text, model_profile),
count_tokens(candidate.instructions, model_profile),
)
def candidate_rank_key(candidate: Candidate, metrics: tuple[int, int, int]) -> tuple[int, int, int, str]:
total_tokens, payload_tokens, _instruction_tokens = metrics
return (total_tokens, payload_tokens, len(candidate.text), candidate.name)
def savings_policy_from_env() -> dict[str, float | int]:
return {
"min_savings_ratio": float(os.environ.get("CONTEXT_OPTIMIZER_MIN_SAVINGS_RATIO", DEFAULT_MIN_SAVINGS_RATIO)),
"min_saved_tokens": int(os.environ.get("CONTEXT_OPTIMIZER_MIN_SAVED_TOKENS", DEFAULT_MIN_SAVED_TOKENS)),
}
def latency_policy_from_env() -> dict[str, float | bool]:
provider_tps = float(
os.environ.get(
"CONTEXT_OPTIMIZER_PROVIDER_INPUT_TOKENS_PER_SECOND",
DEFAULT_PROVIDER_INPUT_TOKENS_PER_SECOND,
)
)
min_net_saved_ms = float(
os.environ.get(
"CONTEXT_OPTIMIZER_MIN_NET_LATENCY_SAVED_MS",
DEFAULT_MIN_NET_LATENCY_SAVED_MS,
)
)
return {
"latency_gate_enabled": provider_tps > 0,
"provider_input_tokens_per_second": provider_tps,
"min_net_latency_saved_milliseconds": min_net_saved_ms,
}
def candidate_tier_from_env() -> str:
return normalize_candidate_tier(os.environ.get("CONTEXT_OPTIMIZER_CANDIDATE_TIER", DEFAULT_CANDIDATE_TIER))
def normalize_candidate_tier(raw_tier: str) -> str:
tier = raw_tier.strip().lower()
if tier not in CANDIDATE_TIERS:
return DEFAULT_CANDIDATE_TIER
return tier
def should_inject(choice: Choice, policy: dict[str, float | int]) -> bool:
saved_tokens = choice.raw_tokens - choice.total_tokens
return (
choice.candidate.name != "raw"
and choice.savings_ratio >= float(policy["min_savings_ratio"])
and saved_tokens >= int(policy["min_saved_tokens"])
)
def should_rewrite_for_latency(
choices: list[Choice],
local_milliseconds: float,
policy: dict[str, float | bool],
) -> bool:
provider_tps = float(policy["provider_input_tokens_per_second"])
if provider_tps <= 0:
return True
saved_tokens = sum(choice.raw_tokens - choice.total_tokens for choice in choices)
projected_saved_ms = saved_tokens * 1000.0 / provider_tps
return projected_saved_ms - local_milliseconds >= float(policy["min_net_latency_saved_milliseconds"])
def elapsed_milliseconds(started_at: float) -> float:
return (time.perf_counter() - started_at) * 1000.0
def with_fallback_note(candidates: list[Candidate]) -> list[Candidate]:
return [
Candidate(
candidate.name,
candidate.text,
candidate.reversible,
candidate.instructions,
(*candidate.notes, "fallback token estimate"),
)
for candidate in candidates
]
def candidates_for_profile(
source: SourceData,
model_profile: ModelProfile,
candidate_tier: str | None = None,
) -> list[Candidate]:
return verify_candidates(source, generated_candidates_for_profile(source, model_profile, candidate_tier))
def generated_candidates_for_profile(
source: SourceData,
model_profile: ModelProfile,
candidate_tier: str | None = None,
) -> list[Candidate]:
tier = normalize_candidate_tier(candidate_tier or DEFAULT_CANDIDATE_TIER)
candidates = generate_candidates(source, CANDIDATE_TIERS[tier])
if model_profile.token_counter != "deterministic-fallback":
return candidates
return with_fallback_note(
[candidate for candidate in candidates if candidate.name in SAFE_CANDIDATES]
)
def sidecar_digest(source: SourceData, candidate: Candidate, model_profile: ModelProfile, candidate_tier: str) -> str:
stat = source.path.stat()
digest_input = {
"schema_version": SCHEMA_VERSION,
"source": str(source.path),
"source_size": stat.st_size,
"source_mtime_ns": stat.st_mtime_ns,
"source_sha256": sha256_file(source.path),
"model_slug": model_profile.slug,
"token_counter": model_profile.token_counter,
"tokenizer_family": model_profile.tokenizer_family,
"candidate_tier": candidate_tier,
"candidate_name": candidate.name,
"candidate_text_sha256": hashlib.sha256(candidate.text.encode("utf-8")).hexdigest(),
}
return hashlib.sha256(json.dumps(digest_input, sort_keys=True).encode("utf-8")).hexdigest()[:16]
def write_candidate_sidecar(
source: SourceData,
candidate: Candidate,
out_dir: Path,
model_profile: ModelProfile,
candidate_tier: str,
) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
digest = sidecar_digest(source, candidate, model_profile, candidate_tier)
output_path = out_dir / f"{source.path.stem}.{digest}.{candidate.name}.txt"
if not output_path.exists():
output_path.write_text(candidate_blob(candidate), encoding="utf-8")
return output_path
def generate_candidates(source: SourceData, allowed_names: set[str] | None = None) -> list[Candidate]:
allowed = allowed_names or set().union(*CANDIDATE_TIERS.values())
value = source.value
candidates = [
Candidate(
"raw",
source.raw_text,
True,
"",
("original bytes normalized as UTF-8 text",),
),
Candidate(
"compact-json",
compact_json(value),
True,
"Minified JSON.",
("lossless parsed data",),
),
]
rows = rows_from_value(value)
if rows:
headers = stable_headers(rows)
if headers and rows_are_uniform(rows, headers):
if "column-json" in allowed:
candidates.append(
Candidate(
"column-json",
column_json_text(rows, headers),
True,
"JSON [columns,rows].",
("lossless columnar JSON",),
)
)
if "codebook-json" in allowed:
codebook_json = codebook_json_text(rows, headers)
if codebook_json:
candidates.append(
Candidate(
"codebook-json",
codebook_json,
True,
"JSON [cols,dicts,rows]; dicts=[col,values]; codes=indexes.",
("lossless columnar JSON with categorical dictionaries",),
)
)
if {"typed-csv", "typed-tsv"} & allowed:
typed_columns = infer_typed_columns(rows, headers)
else:
typed_columns = None
if typed_columns:
if "typed-csv" in allowed:
candidates.append(
Candidate(
"typed-csv",
typed_table_text(rows, headers, typed_columns, ","),
True,
"Types: i=int n=num b=bool s=str ?=nullable ~=null.",
("lossless typed table",),
)
)
if "typed-tsv" in allowed:
candidates.append(
Candidate(
"typed-tsv",
typed_table_text(rows, headers, typed_columns, "\t"),
True,
"Types: i=int n=num b=bool s=str ?=nullable ~=null.",
("lossless typed table",),
)
)
if "csv" in allowed:
candidates.append(
Candidate(
"csv",
table_text(rows, headers, ","),
True,
"Cells=JSON CSV.",
("lossless parsed table",),
)
)
if "tsv" in allowed:
candidates.append(
Candidate(
"tsv",
table_text(rows, headers, "\t"),
True,
"Cells=JSON TSV.",
("lossless parsed table",),
),
)
return dedupe_candidates(candidates)
def validated_candidates(source: SourceData, allowed_names: set[str] | None = None) -> list[Candidate]:
return verify_candidates(source, generate_candidates(source, allowed_names))
def verify_candidates(source: SourceData, candidates: Iterable[Candidate]) -> list[Candidate]:
verified: list[Candidate] = []
for candidate in candidates:
if not candidate.reversible:
continue
if candidate_matches_source(source, candidate):
verified.append(candidate_with_roundtrip_note(candidate))
return verified
def candidate_with_roundtrip_note(candidate: Candidate) -> Candidate:
if "roundtrip verified" in candidate.notes:
return candidate
return Candidate(
candidate.name,
candidate.text,
candidate.reversible,
candidate.instructions,
(*candidate.notes, "roundtrip verified"),
)
def candidate_matches_source(source: SourceData, candidate: Candidate) -> bool:
try:
return decode_candidate_value(candidate.name, candidate.text, source.kind) == source.value
except Exception:
return False
def candidate_blob(candidate: Candidate) -> str:
if not candidate.instructions:
return candidate.text
return candidate.instructions + "\n" + candidate.text
def candidate_text_from_blob(candidate_name: str, blob: str) -> str:
if candidate_name == "raw":
return blob
_instructions, separator, text = blob.partition("\n")
if not separator:
raise ValueError("candidate blob is missing decoder instruction line")
return text
def rows_from_value(value: Any) -> list[dict[str, Any]]:
if isinstance(value, list) and all(isinstance(item, dict) for item in value):
return [dict(item) for item in value]
if isinstance(value, dict):
for key in ("rows", "data", "items", "records", "results"):
nested = value.get(key)
if isinstance(nested, list) and all(isinstance(item, dict) for item in nested):
return [dict(item) for item in nested]
return []
def stable_headers(rows: list[dict[str, Any]]) -> list[str]:
return list(dict.fromkeys(str(key) for row in rows for key in row))
def rows_are_uniform(rows: list[dict[str, Any]], headers: list[str]) -> bool:
expected = set(headers)
return all(set(str(key) for key in row) == expected for row in rows)
def compact_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=False)
def table_text(rows: list[dict[str, Any]], headers: list[str], delimiter: str) -> str:
output = io.StringIO()
writer = csv.writer(output, delimiter=delimiter, lineterminator="\n")
writer.writerow(headers)
for row in rows:
writer.writerow([cell_json(row.get(header)) for header in headers])
return output.getvalue().rstrip("\n")
def column_json_text(rows: list[dict[str, Any]], headers: list[str]) -> str:
return json.dumps(
[headers, [[row.get(header) for header in headers] for row in rows]],
ensure_ascii=False,
separators=(",", ":"),
)
def codebook_json_text(rows: list[dict[str, Any]], headers: list[str]) -> str | None:
cell_rows = [[cell_json(row.get(header)) for header in headers] for row in rows]
dictionaries = build_json_cell_dictionaries(cell_rows, headers)
if not dictionaries:
return None
dicts: list[list[Any]] = []
for index, header in enumerate(headers):
mapping = dictionaries.get(header)
if not mapping:
continue
values: list[Any] = [None] * len(mapping)
for raw, code in mapping.items():
values[code] = json.loads(raw)
dicts.append([index, values])
encoded_rows: list[list[Any]] = []
for row, cell_row in zip(rows, cell_rows):
encoded_row: list[Any] = []
for index, header in enumerate(headers):
mapping = dictionaries.get(header)
encoded_row.append(mapping[cell_row[index]] if mapping else row.get(header))
encoded_rows.append(encoded_row)
return json.dumps([headers, dicts, encoded_rows], ensure_ascii=False, separators=(",", ":"))
def build_json_cell_dictionaries(rows: list[list[str]], headers: list[str]) -> dict[str, dict[str, int]]:
dictionaries: dict[str, dict[str, int]] = {}
for index, header in enumerate(headers):
values = [row[index] for row in rows]
unique = list(dict.fromkeys(values))
if len(unique) == len(values):
continue
mapping = {value: code for code, value in enumerate(unique)}
raw_len = sum(len(value) for value in values)
encoded_len = sum(len(str(mapping[value])) for value in values)
dict_values = [json.loads(value) for value in unique]
dict_entry_len = len(json.dumps([index, dict_values], ensure_ascii=False, separators=(",", ":")))
if raw_len > encoded_len + dict_entry_len + 1:
dictionaries[header] = mapping
return dictionaries
def typed_table_text(
rows: list[dict[str, Any]],
headers: list[str],
typed_columns: dict[str, str],
delimiter: str,
) -> str:
output = io.StringIO()
output.write("t:" + ",".join(typed_columns[header] for header in headers) + "\n")
writer = csv.writer(output, delimiter=delimiter, lineterminator="\n")
writer.writerow(headers)
for row in rows:
writer.writerow([typed_cell(row.get(header), typed_columns[header]) for header in headers])
return output.getvalue().rstrip("\n")
def infer_typed_columns(rows: list[dict[str, Any]], headers: list[str]) -> dict[str, str] | None:
typed: dict[str, str] = {}
for header in headers:
values = [row.get(header) for row in rows]
kind = infer_column_type(values)
if kind is None:
return None
typed[header] = kind
return typed
def infer_column_type(values: list[Any]) -> str | None:
non_null = [value for value in values if value is not None]
nullable = len(non_null) != len(values)
suffix = "?" if nullable else ""
if not non_null:
return "s?"
if all(isinstance(value, bool) for value in non_null):
return "b" + suffix
if all(isinstance(value, int) and not isinstance(value, bool) for value in non_null):
return "i" + suffix
if all(is_number(value) for value in non_null):
return "n" + suffix
if all(isinstance(value, str) for value in non_null):
if nullable and any(value == "~" for value in non_null):
return None
return "s" + suffix
return None
def is_number(value: Any) -> bool:
if isinstance(value, bool):
return False
if not isinstance(value, (int, float)):
return False
return value == value and value not in (float("inf"), float("-inf"))
def typed_cell(value: Any, kind: str) -> str:
base = kind.removesuffix("?")
if value is None:
return "~"
if base == "b":
return "1" if value else "0"
return str(value)
def cell_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=False)
def decode_candidate_value(name: str, text: str, source_kind: str) -> Any:
if name == "raw":
return decode_raw_value(text, source_kind)
if name == "compact-json":
return json.loads(text)
if name == "column-json":
return decode_column_json(text)
if name == "codebook-json":
return decode_codebook_json(text)
if name == "csv":
return decode_json_table(text, ",")
if name == "tsv":
return decode_json_table(text, "\t")
if name == "typed-csv":
return decode_typed_table(text, ",")
if name == "typed-tsv":
return decode_typed_table(text, "\t")
raise ValueError(f"unsupported candidate {name}")
def decode_raw_value(text: str, source_kind: str) -> Any:
if source_kind == "json":
return json.loads(text)
if source_kind == "jsonl":
return [json.loads(line) for line in text.splitlines() if line.strip()]
if source_kind in {"csv", "tsv"}:
delimiter = "\t" if source_kind == "tsv" else ","
return [dict(row) for row in csv.DictReader(io.StringIO(text), delimiter=delimiter)]
raise ValueError(f"unsupported source kind {source_kind}")
def decode_json_table(text: str, delimiter: str) -> list[dict[str, Any]]:
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
try:
headers = next(reader)
except StopIteration:
return []
return [
{header: json.loads(cell) for header, cell in zip(headers, row)}
for row in reader