PineForge HPO 0.1.0
Native hyperparameter optimization for PineForge strategies
Loading...
Searching...
No Matches
artifact.py
Go to the documentation of this file.
1"""Content-addressed PineScript strategy artifact builder."""
2
3from __future__ import annotations
4
5from contextlib import AbstractContextManager
6import ctypes
7from dataclasses import dataclass
8from datetime import datetime, timezone
9import hashlib
10import json
11import os
12from pathlib import Path
13import platform
14import shutil
15import subprocess
16import sys
17import tempfile
18import time
19from typing import Any, Callable, Mapping, Sequence
20
21from .transpile import (
22 TranspileDiagnostic,
23 TranspileFailure,
24 codegen_identity,
25 transpile_source,
26)
27
28
29
30CANONICAL_COMPILE_FLAGS = (
31 "-std=c++17",
32 "-O2",
33 "-ffp-contract=off",
34 "-fPIC",
35 "-shared",
36)
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56class ArtifactBuildError(RuntimeError):
57 """A configuration, transpile, compile, or cache publication failure."""
58
60 self,
61 stage: str,
62 message: str,
63 *,
64 command: Sequence[str] = (),
65 stdout: str = "",
66 stderr: str = "",
67 diagnostics: Sequence[TranspileDiagnostic] = (),
68 ) -> None:
69 self.stage = stage
70 self.command = tuple(command)
71 self.stdout = stdout
72 self.stderr = stderr
73 self.diagnostics = tuple(diagnostics)
74 super().__init__(message)
75
76
77@dataclass(frozen=True)
79 """Paths and metadata consumed by the native strategy-plugin loader."""
80
81 artifact_key: str
82 request_key: str
83 plugin_path: Path
84 generated_cpp_path: Path
85 manifest_path: Path
86 provenance_path: Path
87 cache_hit: bool
88 inputs: tuple[dict[str, Any], ...]
89 strategy_params: Mapping[str, Any]
90
91 @property
92 def library_path(self) -> Path:
93 """Compatibility alias for callers that call plugins libraries."""
94
95 return self.plugin_path
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
265 """Transpile and compile a Pine strategy once per compatible request identity."""
266
268 self,
269 *,
270 engine_root: str | os.PathLike[str],
271 cache_dir: str | os.PathLike[str] | None = None,
272 compiler: str | os.PathLike[str] | None = None,
273 eigen_include: str | os.PathLike[str] | None = None,
274 plugin_validator: Callable[[Path, int], Mapping[str, Any]] | None = None,
275 lock_timeout_seconds: float = 120.0,
276 compile_timeout_seconds: float = 300.0,
277 ) -> None:
278 self.engine_root = Path(engine_root).expanduser().resolve()
279 self.cache_dir = (
280 Path(cache_dir).expanduser().resolve()
281 if cache_dir
282 else _default_cache_dir()
283 )
284 self.compiler = os.fspath(compiler) if compiler is not None else None
286 Path(eigen_include).expanduser().resolve()
287 if eigen_include is not None
288 else None
289 )
290 self.plugin_validator = plugin_validator or self._validate_plugin
291 self.lock_timeout_seconds = lock_timeout_seconds
292 self.compile_timeout_seconds = compile_timeout_seconds
293
294 def build(self, pine_source: str, *, filename: str = "<input>") -> StrategyArtifact:
295 if not isinstance(pine_source, str):
296 raise TypeError("pine_source must be a string")
297 if self.lock_timeout_seconds <= 0 or self.compile_timeout_seconds <= 0:
298 raise ArtifactBuildError("configuration", "build timeouts must be positive")
299
300 engine = self._resolve_engine_layout()
301 compiler = self._resolve_compiler_identity()
302 eigen = self._resolve_eigen_identity(engine)
303 try:
304 codegen = codegen_identity()
305 except ModuleNotFoundError as error:
306 raise ArtifactBuildError(
307 "configuration",
308 "pineforge-codegen is required to compile PineScript; install "
309 "pineforge-hpo[transpile] or provide a precompiled artifact",
310 ) from error
311 output_extension, link_mode = self._platform_link_mode()
312 compile_spec = {
313 "flags": list(CANONICAL_COMPILE_FLAGS),
314 "include_dirs": [
315 str(path) for path in (*engine.include_dirs, eigen.include_dir)
316 ],
317 "link_mode": link_mode,
318 "output_extension": output_extension,
319 }
320 request_identity = {
321 "source_sha256": hashlib.sha256(pine_source.encode("utf-8")).hexdigest(),
322 "codegen": codegen.to_dict(),
323 "engine": engine.identity_dict(),
324 "compiler": compiler.to_dict(),
325 "eigen": eigen.to_dict(),
326 "platform": {
327 "system": platform.system(),
328 "release": platform.release(),
329 "machine": platform.machine(),
330 "sys_platform": sys.platform,
331 "python_implementation": platform.python_implementation(),
332 "python_version": platform.python_version(),
333 },
334 "compiler_environment": {
335 key: os.environ.get(key, "") for key in _COMPILER_ENV_KEYS
336 },
337 "compile": compile_spec,
338 }
339 request_key = _json_sha256(request_identity)
340
341 hit = self._lookup_request(request_key, request_identity, output_extension)
342 if hit is not None:
343 return hit
344
345 lock_path = self.cache_dir / "locks" / f"{request_key}.lock"
346 with _KeyLock(lock_path, self.lock_timeout_seconds):
347 hit = self._lookup_request(request_key, request_identity, output_extension)
348 if hit is not None:
349 return hit
350
351 transpile_result = transpile_source(pine_source, filename=filename)
352 try:
353 generated_cpp = transpile_result.require_success()
354 except TranspileFailure as error:
355 raise ArtifactBuildError(
356 "transpile",
357 str(error),
358 diagnostics=transpile_result.diagnostics,
359 ) from error
360
361 generated_cpp_sha256 = hashlib.sha256(
362 generated_cpp.encode("utf-8")
363 ).hexdigest()
364 artifact_identity = {
365 "request_identity": request_identity,
366 "generated_cpp_sha256": generated_cpp_sha256,
367 }
368 artifact_key = _json_sha256(artifact_identity)
369 existing = self._load_artifact(
370 artifact_key=artifact_key,
371 request_key=request_key,
372 request_identity=request_identity,
373 output_extension=output_extension,
374 cache_hit=True,
375 )
376 if existing is not None:
377 self._write_request_index(request_key, artifact_key)
378 return existing
379
380 artifact = self._compile_and_publish(
381 artifact_key=artifact_key,
382 request_key=request_key,
383 request_identity=request_identity,
384 output_extension=output_extension,
385 generated_cpp=generated_cpp,
386 generated_cpp_sha256=generated_cpp_sha256,
387 inputs=transpile_result.inputs,
388 strategy_params=transpile_result.strategy_params,
389 diagnostics=transpile_result.diagnostics,
390 source_name=filename,
391 compiler=compiler,
392 engine=engine,
393 eigen=eigen,
394 )
395 self._write_request_index(request_key, artifact_key)
396 return artifact
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
921def build_strategy_artifact(
922 pine_source: str,
923 *,
924 engine_root: str | os.PathLike[str],
925 cache_dir: str | os.PathLike[str] | None = None,
926 compiler: str | os.PathLike[str] | None = None,
927 eigen_include: str | os.PathLike[str] | None = None,
928 filename: str = "<input>",
929) -> StrategyArtifact:
930 """Convenience entry point for a one-off CLI artifact build."""
931
932 builder = ArtifactBuilder(
933 engine_root=engine_root,
934 cache_dir=cache_dir,
935 compiler=compiler,
936 eigen_include=eigen_include,
937 )
938 return builder.build(pine_source, filename=filename)
939
940
941
942
943
944
945
946
947
None __init__(self, str stage, str message, *Sequence[str] command=(), str stdout="", str stderr="", Sequence[TranspileDiagnostic] diagnostics=())
Definition artifact.py:68
StrategyArtifact build(self, str pine_source, *str filename="<input>")
Definition artifact.py:294
None __init__(self, *str|os.PathLike[str] engine_root, str|os.PathLike[str]|None cache_dir=None, str|os.PathLike[str]|None compiler=None, str|os.PathLike[str]|None eigen_include=None, Callable[[Path, int], Mapping[str, Any]]|None plugin_validator=None, float lock_timeout_seconds=120.0, float compile_timeout_seconds=300.0)
Definition artifact.py:277