Repository navigation
Expand file tree
/
Copy pathevaluation.py
More file actions
2106 lines (1949 loc) · 75.7 KB
/
Copy pathevaluation.py
File metadata and controls
2106 lines (1949 loc) · 75.7 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
"""Run the batch comparison, scope study, and always-online comparison.
Each synthesis request runs in a separate, persistent worker process. The
driver can therefore enforce a safety timeout on every request and kill the
worker without leaving a Python/JVM process behind. Each request constructs one
complete batch, so the timeout bounds total batch synthesis. Main-scope results
are reused by the scope and online studies, and results are written
incrementally so a long evaluation can be resumed safely.
"""
from __future__ import annotations
import argparse
from copy import deepcopy
from contextlib import redirect_stdout
from datetime import datetime, timezone
import io
import json
import math
import os
from pathlib import Path
import selectors
import statistics
import subprocess
import sys
from timeit import default_timer as timer
from typing import Optional
from evaluation_report import batch_preparation_seconds
ALGORITHMS = ("balanced-split", "arbitrary-split", "joint-cover", "enumerated-cover")
SCOPE_STUDY_ALGORITHMS = ALGORITHMS
TEMPORAL_STUDY_ALGORITHMS = ALGORITHMS
TRACE_STUDY_ALGORITHMS = TEMPORAL_STUDY_ALGORITHMS
METHOD_METADATA = {
"balanced-split": {
"display_name": "Balanced Split",
"family": "tree-guided",
},
"arbitrary-split": {
"display_name": "Arbitrary Split",
"family": "tree-guided",
},
"joint-cover": {
"display_name": "Joint Cover",
"family": "cover-based",
},
"enumerated-cover": {
"display_name": "Enumerated Cover",
"family": "cover-based",
},
}
CURRENT_FORMAT_VERSION = 8
ALLOYMAX_VERSION = "1.0.2"
DEFAULT_ONLINE_TIMEOUT_SECONDS = 180.0
RESULT_PREFIX = "__SPEC_NARROWING_RESULT__"
ONLINE_RESULT_PREFIX = "__SPEC_NARROWING_ONLINE_RESULT__"
def _trace_length_argument(trace_length: Optional[int]) -> str:
return "none" if trace_length is None else str(trace_length)
def _parse_trace_length_argument(value: str) -> Optional[int]:
return None if value == "none" else int(value)
def method_metadata(algorithms):
"""Return JSON-friendly display metadata for the selected method IDs."""
return {
algorithm: dict(METHOD_METADATA[algorithm])
for algorithm in algorithms
}
def _percentile(values: list[float], fraction: float) -> float:
ordered = sorted(values)
if len(ordered) == 1:
return ordered[0]
position = fraction * (len(ordered) - 1)
lower = math.floor(position)
upper = math.ceil(position)
if lower == upper:
return ordered[lower]
weight = position - lower
return ordered[lower] * (1 - weight) + ordered[upper] * weight
def number_stats(values) -> Optional[dict[str, float]]:
"""Return descriptive statistics in a JSON-friendly dictionary."""
numbers = [float(value) for value in values if value is not None]
if not numbers:
return None
return {
"count": len(numbers),
"mean": round(statistics.mean(numbers), 2),
"median": round(statistics.median(numbers), 2),
"stdev": round(statistics.pstdev(numbers), 2),
"min": round(min(numbers), 2),
"p25": round(_percentile(numbers, 0.25), 2),
"p75": round(_percentile(numbers, 0.75), 2),
"p95": round(_percentile(numbers, 0.95), 2),
"max": round(max(numbers), 2),
}
def _worker_server(
algorithm: str,
filename: str,
scope: int,
trace_length: Optional[int],
) -> int:
"""Serve newline-delimited synthesis requests on stdin/stdout."""
from arbitrary_split import arbitrary_split_batch
from balanced_split import balanced_split_batch
from enumerated_cover import enumerated_cover_batch
from joint_cover import joint_cover_batch
content = Path(filename).read_text()
strategy = {
"balanced-split": balanced_split_batch,
"joint-cover": joint_cover_batch,
"arbitrary-split": arbitrary_split_batch,
"enumerated-cover": enumerated_cover_batch,
}[algorithm]
for line in sys.stdin:
request = json.loads(line)
if request.get("stop"):
return 0
messages = io.StringIO()
algorithm_statistics = None
try:
start = timer()
with redirect_stdout(messages):
if algorithm in {"balanced-split", "enumerated-cover"}:
algorithm_statistics = {}
strategy_arguments = (
content,
scope,
trace_length,
algorithm_statistics,
)
else:
strategy_arguments = (content, scope, trace_length)
batch = strategy(*strategy_arguments)
instances = [instance.alloy5 for instance in batch]
truth_table = [instance.truth_vector for instance in batch]
response = {
"status": "completed",
"synthesis_seconds": timer() - start,
"instances": instances,
"truth_table": truth_table,
}
if messages.getvalue().strip():
response["messages"] = messages.getvalue().strip()
if algorithm_statistics is not None:
response[algorithm] = algorithm_statistics
except BaseException as error:
response = {
"status": "error",
"error": f"{type(error).__name__}: {error}",
}
print(RESULT_PREFIX + json.dumps(response), flush=True)
return 0
def _online_worker(
filename: str,
scope: int,
trace_length: Optional[int],
) -> int:
"""Measure all oracle paths of adaptive iterative classification."""
from balanced_split import iterative_classification_path_costs
try:
result = iterative_classification_path_costs(
Path(filename).read_text(), scope, trace_length
)
result["status"] = "completed"
except BaseException as error:
result = {
"status": "error",
"error": f"{type(error).__name__}: {error}",
}
print(ONLINE_RESULT_PREFIX + json.dumps(result), flush=True)
return 0
def _run_online_problem(
filename: Path,
scope: int,
timeout_seconds: float,
trace_length: Optional[int] = None,
):
"""Run one online comparison in an isolated, time-bounded process."""
try:
completed = subprocess.run(
[
sys.executable,
str(Path(__file__).resolve()),
"_online_worker",
str(filename),
str(scope),
_trace_length_argument(trace_length),
],
capture_output=True,
text=True,
timeout=timeout_seconds,
check=False,
)
except subprocess.TimeoutExpired:
return {
"status": "timeout",
"synthesis_timeout_seconds": timeout_seconds,
}
for line in completed.stdout.splitlines():
if line.startswith(ONLINE_RESULT_PREFIX):
return json.loads(line[len(ONLINE_RESULT_PREFIX) :])
return {
"status": "error",
"error": completed.stderr.strip() or "online worker returned no result",
}
class SynthesisServer:
"""A restartable synthesis worker with a timeout for each request."""
def __init__(
self,
algorithm,
filename,
scope,
timeout_seconds,
trace_length=None,
):
self.algorithm = algorithm
self.filename = str(filename)
self.scope = scope
self.timeout_seconds = timeout_seconds
self.trace_length = trace_length
self.process = None
def start(self):
if self.process is not None and self.process.poll() is None:
return
self.process = subprocess.Popen(
[
sys.executable,
str(Path(__file__).resolve()),
"_worker",
self.algorithm,
self.filename,
str(self.scope),
_trace_length_argument(self.trace_length),
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
)
def request(self, candidates=None):
self.start()
request = {} if candidates is None else {"candidates": candidates}
try:
self.process.stdin.write(json.dumps(request) + "\n")
self.process.stdin.flush()
except (BrokenPipeError, OSError) as error:
self.stop()
return {"status": "error", "error": str(error)}
deadline = timer() + self.timeout_seconds
selector = selectors.DefaultSelector()
selector.register(self.process.stdout, selectors.EVENT_READ)
try:
while True:
remaining = deadline - timer()
if remaining <= 0 or not selector.select(remaining):
self.stop()
return {
"status": "timeout",
"timeout_seconds": self.timeout_seconds,
}
line = self.process.stdout.readline()
if not line:
result = {
"status": "error",
"error": f"synthesis worker exited with {self.process.poll()}",
}
self.stop()
return result
if line.startswith(RESULT_PREFIX):
return json.loads(line[len(RESULT_PREFIX) :])
finally:
selector.close()
def stop(self):
process = self.process
self.process = None
if process is None:
return
if process.poll() is None:
try:
process.stdin.write(json.dumps({"stop": True}) + "\n")
process.stdin.flush()
process.wait(timeout=1)
except (BrokenPipeError, OSError, subprocess.TimeoutExpired):
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
if process.stdin is not None:
process.stdin.close()
if process.stdout is not None:
process.stdout.close()
def __enter__(self):
self.start()
return self
def __exit__(self, _type, _value, _traceback):
self.stop()
def fixed_classification_counts(predicates, truth_table):
"""Adaptively order a fixed suite for every possible ground truth."""
counts = {}
errors = {}
for oracle in predicates:
remaining = list(predicates)
answered = set()
classifications = 0
while len(remaining) > 1:
ranked = []
for index, truths in enumerate(truth_table):
if index in answered:
continue
desirable = [p for p in remaining if truths[p]]
undesirable = [p for p in remaining if not truths[p]]
if not desirable or not undesirable:
continue
ranked.append(
(
max(len(desirable), len(undesirable)),
-len(desirable) * len(undesirable),
index,
)
)
if not ranked:
errors[oracle] = "fixed suite does not distinguish remaining candidates"
break
index = min(ranked)[2]
answered.add(index)
answer = truth_table[index][oracle]
remaining = [p for p in remaining if truth_table[index][p] == answer]
classifications += 1
counts[oracle] = classifications if remaining == [oracle] else None
return counts, errors
def evaluate_batch(
collector,
filename,
algorithm,
scope,
timeout_seconds,
trace_length=None,
):
predicates = list(collector.predicates)
with SynthesisServer(
algorithm,
filename,
scope,
timeout_seconds,
trace_length,
) as server:
synthesis = server.request()
result = {
"algorithm": algorithm,
"status": synthesis["status"],
"synthesis_status": synthesis["status"],
"evaluation_status": "not_run",
"synthesis_timeout_seconds": timeout_seconds,
"classifications": {predicate: None for predicate in predicates},
"classification_stats": None,
"completed_oracles": 0,
"total_oracles": len(predicates),
}
if collector.temporal:
result["trace_length"] = collector.trace_length
if synthesis["status"] != "completed":
result.update(
{
key: value
for key, value in synthesis.items()
if key not in {"status", "timeout_seconds"}
}
)
result["failure_stage"] = "synthesis"
return result
instances = synthesis["instances"]
# Retain successful synthesis even if later table handling or review fails.
result.update({
"test_suite_size": len(instances),
"synthesis_seconds": round(synthesis["synthesis_seconds"], 2),
})
if synthesis.get("messages"):
result["messages"] = synthesis["messages"]
for method in ("enumerated-cover", "balanced-split"):
if synthesis.get(method) is not None:
details = dict(synthesis[method])
for key in ("enumeration_seconds", "cover_seconds"):
if details.get(key) is not None:
details[key] = round(details[key], 2)
result[method] = details
try:
truth_table = synthesis.get("truth_table")
if not isinstance(truth_table, list) or len(truth_table) != len(instances) or any(
not isinstance(row, dict)
or any(type(row.get(predicate)) is not bool for predicate in predicates)
for row in truth_table
):
raise ValueError("synthesis returned incomplete candidate predictions")
result["truth_vector_source"] = "synthesis"
except Exception as error:
result.update({
"status": "error",
"evaluation_status": "error",
"failure_stage": "truth_vector_validation",
"error": f"{type(error).__name__}: {error}",
})
return result
result["evaluation_status"] = "completed"
counts, errors = fixed_classification_counts(predicates, truth_table)
result.update(
{
"classifications": counts,
"classification_stats": number_stats(counts.values()),
"completed_oracles": sum(value is not None for value in counts.values()),
"total_oracles": len(predicates),
}
)
if errors:
result["oracle_errors"] = errors
result["status"] = "partial"
result["failure_stage"] = "classification"
return result
def _problem_key(path: Path):
parts = path.stem.rsplit("_", 2)
try:
size = int(parts[-1])
except (ValueError, IndexError):
size = 0
return size, path.name
def _problem_metadata(path: Path, predicates, collector=None):
parts = path.stem.rsplit("_", 2)
metadata = {
"file": path.name,
"model": parts[0] if len(parts) == 3 else None,
"requirement": parts[1] if len(parts) == 3 else None,
"declared_size": int(parts[2]) if len(parts) == 3 else len(predicates),
"candidate_count": len(predicates),
"candidates": list(predicates),
}
if collector is not None:
metadata["temporal"] = collector.temporal
if collector.temporal:
metadata["trace_length"] = collector.trace_length
return metadata
def _format_stats(stats):
if stats is None:
return "no completed oracles"
return (
f"mean {stats['mean']:.2f}, median {stats['median']:.2f}, "
f"min {stats['min']:.2f}, p95 {stats['p95']:.2f}, "
f"max {stats['max']:.2f}"
)
def print_algorithm_result(key, result):
suffix = _format_stats(result.get("classification_stats"))
extra = ""
if result.get("failure_stage"):
extra = f"; failure during {result['failure_stage']}"
if "test_suite_size" in result:
extra += (
f"; suite {result['test_suite_size']}; "
f"synthesis {result['synthesis_seconds']:.2f} seconds"
)
if result.get("enumerated-cover"):
enumeration = result["enumerated-cover"]
extra += (
f"; enumerated {enumeration['separation_patterns']} "
"separation patterns in "
f"{enumeration.get('enumeration_solver_calls', 'unknown')} "
"SAT calls; "
"enumeration/cover "
f"{enumeration['enumeration_seconds']:.2f}/"
f"{enumeration['cover_seconds']:.2f} seconds"
)
if result.get("balanced-split"):
balanced = result["balanced-split"]
extra += (
f"; MaxSAT calls {balanced['maxsat_calls']}; "
f"reuses {balanced['ideal_reuses'] + balanced['matched_reuses']}"
)
print(
f" {key:24} {result['status']:9} "
f"{result.get('completed_oracles', 0)}/{result.get('total_oracles', 0)} "
f"oracles; classifications {suffix}{extra}",
flush=True,
)
def synthesis_completed(result):
"""Separate batch synthesis from later validation and review simulation."""
return result.get("synthesis_status", result.get("status")) == "completed"
def grouped_summary(problems):
summary = {}
for key in ALGORITHMS:
by_size = {}
for problem in problems:
size = str(problem["candidate_count"])
result = problem["algorithms"].get(key)
if result is None:
continue
bucket = by_size.setdefault(
size,
{
"problems": 0,
"completed_problems": 0,
"synthesis_completed_problems": 0,
"post_synthesis_errors": 0,
"completed_oracles": 0,
"total_oracles": 0,
"classifications": [],
"test_suite_sizes": [],
"synthesis_seconds": [],
"enumerated_instances": [],
"separation_patterns": [],
"enumeration_solver_calls": [],
"enumeration_seconds": [],
"cover_seconds": [],
},
)
bucket["problems"] += 1
bucket["completed_problems"] += result["status"] == "completed"
bucket["synthesis_completed_problems"] += synthesis_completed(result)
bucket["post_synthesis_errors"] += synthesis_completed(result) and result["status"] != "completed"
bucket["completed_oracles"] += result.get("completed_oracles", 0)
bucket["total_oracles"] += result.get("total_oracles", 0)
bucket["classifications"].extend(
value
for value in result.get("classifications", {}).values()
if value is not None
)
if result.get("test_suite_size") is not None:
bucket["test_suite_sizes"].append(result["test_suite_size"])
if result.get("enumerated-cover"):
enumeration = result["enumerated-cover"]
bucket["enumerated_instances"].append(
enumeration["enumerated_instances"]
)
bucket["separation_patterns"].append(
enumeration["separation_patterns"]
)
if enumeration.get("enumeration_solver_calls") is not None:
bucket["enumeration_solver_calls"].append(
enumeration["enumeration_solver_calls"]
)
bucket["enumeration_seconds"].append(
enumeration["enumeration_seconds"]
)
bucket["cover_seconds"].append(enumeration["cover_seconds"])
if result.get("synthesis_seconds") is not None:
bucket["synthesis_seconds"].append(result["synthesis_seconds"])
summary[key] = {}
for size, bucket in by_size.items():
summary[key][size] = {
key: value
for key, value in bucket.items()
if key
not in {
"classifications",
"test_suite_sizes",
"synthesis_seconds",
"enumerated_instances",
"separation_patterns",
"enumeration_solver_calls",
"enumeration_seconds",
"cover_seconds",
}
}
summary[key][size]["classification_stats"] = number_stats(
bucket["classifications"]
)
if bucket["test_suite_sizes"]:
summary[key][size]["test_suite_size_stats"] = number_stats(
bucket["test_suite_sizes"]
)
for values_key, stats_key in (
("synthesis_seconds", "synthesis_seconds_stats"),
("enumerated_instances", "enumerated_instances_stats"),
("separation_patterns", "separation_patterns_stats"),
(
"enumeration_solver_calls",
"enumeration_solver_calls_stats",
),
("enumeration_seconds", "enumeration_seconds_stats"),
("cover_seconds", "cover_seconds_stats"),
):
if bucket[values_key]:
summary[key][size][stats_key] = number_stats(bucket[values_key])
return summary
def _scope_study_problem(main_problem):
"""Copy stable problem metadata without duplicating main-study results."""
return {
key: deepcopy(main_problem[key])
for key in (
"file",
"model",
"requirement",
"declared_size",
"candidate_count",
"candidates",
"temporal",
"trace_length",
)
if key in main_problem
} | {"scopes": {}}
def _trace_study_problem(main_problem):
"""Copy stable problem metadata for the temporal-depth study."""
return {
key: deepcopy(main_problem[key])
for key in (
"file",
"model",
"requirement",
"declared_size",
"candidate_count",
"candidates",
"temporal",
"trace_length",
)
if key in main_problem
} | {"trace_lengths": {}}
def scope_study_summary(study):
"""Summarize completed scope runs and the Joint Cover completion subset."""
scopes = [str(scope) for scope in study["configuration"]["scopes"]]
algorithm_keys = list(
dict.fromkeys(
study["configuration"]["algorithms"]
+ study["configuration"].get("temporal_algorithms", [])
)
)
by_scope = {key: {} for key in algorithm_keys}
for key in algorithm_keys:
for scope in scopes:
results = [
problem.get("scopes", {}).get(scope, {}).get(key)
for problem in study.get("problems", [])
]
results = [result for result in results if result is not None]
completed = [
result for result in results if result.get("status") == "completed"
]
synthesized = [result for result in results if synthesis_completed(result)]
by_scope[key][scope] = {
"problems": len(results),
"completed_problems": len(completed),
"synthesis_completed_problems": len(synthesized),
"post_synthesis_errors": sum(result.get("status") != "completed" for result in synthesized),
"completed_oracles": sum(
result.get("completed_oracles", 0) for result in results
),
"total_oracles": sum(
result.get("total_oracles", 0) for result in results
),
"test_suite_size_stats": number_stats(
result.get("test_suite_size") for result in completed
),
"classification_stats": number_stats(
classification
for result in completed
for classification in result.get("classifications", {}).values()
if classification is not None
),
"synthesis_seconds_stats": number_stats(
result.get("synthesis_seconds") for result in synthesized
),
}
joint_cover_key = "joint-cover"
paired_problems = [
problem
for problem in study.get("problems", [])
if all(
problem.get("scopes", {})
.get(scope, {})
.get(joint_cover_key, {})
.get("status")
== "completed"
for scope in scopes
)
]
paired_algorithms = {key: {} for key in algorithm_keys}
for key in algorithm_keys:
for scope in scopes:
results = [
problem["scopes"][scope].get(key) for problem in paired_problems
]
results = [
result
for result in results
if result is not None and result.get("status") == "completed"
]
paired_algorithms[key][scope] = {
"completed_problems": len(results),
"test_suite_size_stats": number_stats(
result.get("test_suite_size") for result in results
),
"classification_stats": number_stats(
classification
for result in results
for classification in result.get("classifications", {}).values()
if classification is not None
),
}
return {
"by_scope": by_scope,
"paired_joint_cover_completed_all_scopes": {
"problem_count": len(paired_problems),
"files": [problem["file"] for problem in paired_problems],
"algorithms": paired_algorithms,
},
}
def trace_study_summary(study):
"""Summarize the independent temporal trace-length experiment."""
trace_lengths = [
str(trace_length)
for trace_length in study["configuration"]["trace_lengths"]
]
algorithm_keys = study["configuration"]["algorithms"]
by_trace_length = {key: {} for key in algorithm_keys}
for key in algorithm_keys:
for trace_length in trace_lengths:
results = [
problem.get("trace_lengths", {}).get(trace_length, {}).get(key)
for problem in study.get("problems", [])
]
results = [result for result in results if result is not None]
completed = [
result for result in results if result.get("status") == "completed"
]
synthesized = [result for result in results if synthesis_completed(result)]
by_trace_length[key][trace_length] = {
"problems": len(results),
"completed_problems": len(completed),
"synthesis_completed_problems": len(synthesized),
"post_synthesis_errors": sum(result.get("status") != "completed" for result in synthesized),
"completed_oracles": sum(
result.get("completed_oracles", 0) for result in results
),
"total_oracles": sum(
result.get("total_oracles", 0) for result in results
),
"test_suite_size_stats": number_stats(
result.get("test_suite_size") for result in completed
),
"classification_stats": number_stats(
classification
for result in completed
for classification in result.get("classifications", {}).values()
if classification is not None
),
"synthesis_seconds_stats": number_stats(
result.get("synthesis_seconds") for result in synthesized
),
}
paired_problems = [
problem
for problem in study.get("problems", [])
if all(
problem.get("trace_lengths", {})
.get(trace_length, {})
.get("joint-cover", {})
.get("status")
== "completed"
for trace_length in trace_lengths
)
]
return {
"by_trace_length": by_trace_length,
"paired_joint_cover_completed_all_trace_lengths": {
"problem_count": len(paired_problems),
"files": [problem["file"] for problem in paired_problems],
},
}
def online_comparison_summary(document):
"""Compare upfront batch synthesis with cumulative iterative oracle paths."""
study = document.get("online_comparison", {})
batch_by_file = {
problem["file"]: problem["algorithms"]["balanced-split"]
for problem in document.get("problems", [])
if problem.get("algorithms", {}).get("balanced-split", {}).get("status")
== "completed"
}
completed = [
result
for result in study.get("problems", [])
if result.get("status") == "completed" and result["file"] in batch_by_file
]
if not completed:
return {"completed_configurations": 0}
timed = [
result for result in completed
if batch_preparation_seconds(batch_by_file[result["file"]]) is not None
]
counts = {
"completed_configurations": len(completed),
"timed_configurations": len(timed),
"completed_oracle_paths": sum(len(result["path_synthesis_seconds"]) for result in completed),
}
if not timed:
return counts
batch_seconds = [
batch_preparation_seconds(batch_by_file[result["file"]]) for result in timed
]
online_configuration_means = [
statistics.mean(result["path_synthesis_seconds"].values())
for result in timed
]
online_paths = [
seconds
for result in timed
for seconds in result["path_synthesis_seconds"].values()
]
ratios = [
online / batch
for online, batch in zip(online_configuration_means, batch_seconds)
if batch > 0
]
paired_differences = [
batch - online
for batch, online in zip(batch_seconds, online_configuration_means)
]
return {
**counts,
"batch_preparation_seconds": {
"mean": statistics.mean(batch_seconds),
"median": statistics.median(batch_seconds),
},
"online_mean_path_synthesis_seconds": {
"mean_across_configurations": statistics.mean(
online_configuration_means
),
"median_across_configurations": statistics.median(
online_configuration_means
),
"path_weighted_mean": statistics.mean(online_paths),
"path_weighted_median": statistics.median(online_paths),
},
"online_to_batch_ratio": {
"mean": statistics.mean(ratios),
"median": statistics.median(ratios),
},
"paired_batch_minus_online_seconds": {
"mean": statistics.mean(paired_differences),
"median": statistics.median(paired_differences),
"min": min(paired_differences),
"max": max(paired_differences),
"batch_slower_configurations": sum(
difference > 0 for difference in paired_differences
),
},
}
def _normalize_study_trace_length(configuration, trace_length, label):
"""Add a trace bound to legacy study metadata or verify an existing one."""
if "temporal_trace_length" not in configuration:
configuration["temporal_trace_length"] = trace_length
return True
existing = configuration["temporal_trace_length"]
if existing is not None and existing != trace_length:
raise ValueError(
f"cannot resume: existing {label} temporal trace length "
"does not match --trace-length"
)
if existing is None and trace_length is not None:
configuration["temporal_trace_length"] = trace_length
return True
return False
def ensure_online_comparison(document, timeout_seconds, trace_length=None):
"""Initialize and normalize metadata for the paired iterative baseline."""
expected = {
"baseline_method": "iterative",
"paired_batch_method": "balanced-split",
"scope": document["configuration"]["scope"],
"temporal_trace_length": trace_length,
"synthesis_timeout_seconds": timeout_seconds,
"eligible_batch_status": "completed",
"aggregation": "mean oracle-path cost per configuration",
"batch_runtime_components": ["synthesis_seconds"],
}
changed = False
study = document.get("online_comparison")
if study is None:
study = {
"configuration": expected,
"problems": [],
}
document["online_comparison"] = study
changed = True
else:
configuration = study.setdefault("configuration", {})
changed |= _normalize_study_trace_length(
configuration, trace_length, "online-comparison"
)
old_timeout = configuration.pop("timeout_seconds", None)
if old_timeout is not None:
changed = True
if old_timeout is not None and "synthesis_timeout_seconds" not in configuration:
configuration["synthesis_timeout_seconds"] = old_timeout
# The legacy field conflated the baseline with its paired batch method.
if "method" in configuration:
del configuration["method"]
changed = True
for key, value in expected.items():
if configuration.get(key) != value:
if (
key in {"scope", "synthesis_timeout_seconds"}
and configuration.get(key) is not None
):
raise ValueError(
"cannot resume: existing online-comparison scope or "
"timeout does not match the requested configuration"
)
configuration[key] = value
changed = True
if configuration.pop("batch_results", None) is not None:
changed = True
if configuration.pop("problems_directory", None) is not None:
changed = True
summary = online_comparison_summary(document)
if study.get("summary") != summary:
study["summary"] = summary
changed = True
return changed
def ensure_scope_study(
document,
candidate_count,
scopes,
timeout_seconds,
trace_length=None,