File size: 12,299 Bytes
bee361b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Program Space: the set of valid implementations for a stub.

A ProgramSpace is a collection of Program instances that all satisfy the stub's
constraints. It supports:
  - Adding/removing programs
  - Filtering by execution correctness
  - Computing diversity metrics (DA@K from AlgoDiv, 2503.00691)
  - Clustering by behavioral equivalence
"""

from __future__ import annotations

import ast
import hashlib
import traceback
import sys
import io
from math import comb, log, exp
from dataclasses import dataclass, field
from typing import Any, Optional, Callable
from collections import defaultdict

from reason_first_program.stub import Stub


@dataclass
class ExecutionTrace:
    """Execution trace for a single program on a single input."""

    input_args: dict[str, Any]
    output: Any = None
    stdout: str = ""
    stderr: str = ""
    exception: Optional[str] = None
    execution_time_ms: float = 0.0
    # Behavioral fingerprint components
    branch_coverage: Optional[list[bool]] = None
    variable_snapshots: Optional[dict[str, list[Any]]] = None

    @property
    def succeeded(self) -> bool:
        return self.exception is None

    @property
    def output_hash(self) -> str:
        """Hash of the output for functional equivalence checking."""
        return hashlib.md5(repr(self.output).encode()).hexdigest()


@dataclass
class Program:
    """
    A single implementation in the program space.

    Attributes:
        source: The implementation source code (function body only)
        full_source: The complete function including signature
        stub_id: ID of the stub this implements
        model_id: Which model generated this (for diversity tracking)
        traces: Execution traces from running against test inputs
        metadata: Arbitrary metadata (temperature, prompt style, etc.)
    """

    source: str
    full_source: str
    stub_id: str
    model_id: str = "unknown"
    traces: list[ExecutionTrace] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)
    concept_scores: dict[str, float] = field(default_factory=dict)

    @property
    def program_id(self) -> str:
        """Unique identifier based on source content."""
        return hashlib.sha256(self.source.encode()).hexdigest()[:16]

    @property
    def is_valid(self) -> bool:
        """Whether all execution traces succeeded."""
        return len(self.traces) > 0 and all(t.succeeded for t in self.traces)

    @property
    def functional_signature(self) -> str:
        """
        A string that identifies the program's functional behavior.
        Two programs with the same functional signature produce identical
        outputs on all test inputs (functional equivalence, per 2302.05433).
        """
        if not self.traces:
            return "untested"
        return "|".join(t.output_hash for t in self.traces if t.succeeded)

    @property
    def syntactic_hash(self) -> str:
        """Normalized AST hash for syntactic deduplication."""
        try:
            tree = ast.parse(self.source)
            return hashlib.md5(ast.dump(tree).encode()).hexdigest()[:12]
        except SyntaxError:
            return hashlib.md5(self.source.encode()).hexdigest()[:12]

    def behavioral_vector(self) -> list[float]:
        """
        Extract a behavioral feature vector from execution traces.
        Based on TRACED (2306.07487): quantized variable values + branch coverage.
        """
        features = []
        for trace in self.traces:
            if trace.succeeded:
                # Output type encoding
                output_type = type(trace.output).__name__
                type_map = {
                    "int": 0, "float": 1, "str": 2, "list": 3,
                    "dict": 4, "tuple": 5, "set": 6, "bool": 7, "NoneType": 8
                }
                features.append(type_map.get(output_type, 9))

                # Output magnitude (quantized)
                try:
                    if isinstance(trace.output, (int, float)):
                        features.append(float(trace.output))
                    elif isinstance(trace.output, (list, tuple, set, dict)):
                        features.append(float(len(trace.output)))
                    else:
                        features.append(0.0)
                except (TypeError, ValueError):
                    features.append(0.0)

                # Execution time quantile
                features.append(trace.execution_time_ms)

        return features


def execute_program(
    program: Program,
    stub: Stub,
    test_inputs: list[dict[str, Any]],
    timeout_seconds: float = 5.0,
) -> Program:
    """
    Execute a program against test inputs and record traces.

    Args:
        program: The program to execute
        stub: The stub definition (for function name, signature)
        test_inputs: List of input dicts
        timeout_seconds: Max execution time per input

    Returns:
        The program with traces populated
    """
    import time

    program.traces = []

    for inputs in test_inputs:
        trace = ExecutionTrace(input_args=inputs)

        try:
            # Build execution namespace with the program
            namespace: dict[str, Any] = {}

            # Include imports from the stub's module context
            if stub.module_source:
                try:
                    exec(
                        "\n".join(
                            line
                            for line in stub.module_source.split("\n")
                            if line.strip().startswith(("import ", "from "))
                        ),
                        namespace,
                    )
                except Exception:
                    pass

            # Execute the full function definition
            exec(program.full_source, namespace)

            # Call the function
            func = namespace[stub.name]
            start = time.perf_counter()
            result = func(**inputs)
            elapsed = (time.perf_counter() - start) * 1000

            trace.output = result
            trace.execution_time_ms = elapsed

        except Exception as e:
            trace.exception = f"{type(e).__name__}: {e}"
            trace.stderr = traceback.format_exc()

        program.traces.append(trace)

    return program


class ProgramSpace:
    """
    The set of valid implementations for a stub.

    This is the central data structure of the framework. It holds all sampled
    programs, supports filtering, clustering, and diversity measurement.
    """

    def __init__(self, stub: Stub):
        self.stub = stub
        self._programs: dict[str, Program] = {}  # program_id -> Program
        self._clusters: Optional[list[list[str]]] = None  # Cached clustering
        self._cluster_labels: Optional[dict[str, str]] = None

    @property
    def programs(self) -> list[Program]:
        return list(self._programs.values())

    @property
    def valid_programs(self) -> list[Program]:
        return [p for p in self._programs.values() if p.is_valid]

    def __len__(self) -> int:
        return len(self._programs)

    def add(self, program: Program) -> str:
        """Add a program to the space. Returns program_id."""
        self._programs[program.program_id] = program
        self._clusters = None  # Invalidate cache
        return program.program_id

    def add_many(self, programs: list[Program]) -> list[str]:
        """Add multiple programs. Returns list of program_ids."""
        return [self.add(p) for p in programs]

    def get(self, program_id: str) -> Optional[Program]:
        return self._programs.get(program_id)

    def remove(self, program_id: str) -> None:
        self._programs.pop(program_id, None)
        self._clusters = None

    def filter_valid(self) -> ProgramSpace:
        """Return a new ProgramSpace containing only valid programs."""
        new_space = ProgramSpace(self.stub)
        for p in self.valid_programs:
            new_space.add(p)
        return new_space

    def deduplicate_syntactic(self) -> ProgramSpace:
        """Remove syntactically identical programs (normalized AST)."""
        seen: set[str] = set()
        new_space = ProgramSpace(self.stub)
        for p in self.programs:
            h = p.syntactic_hash
            if h not in seen:
                seen.add(h)
                new_space.add(p)
        return new_space

    def deduplicate_functional(self) -> ProgramSpace:
        """Remove functionally equivalent programs (same outputs on all inputs)."""
        seen: set[str] = set()
        new_space = ProgramSpace(self.stub)
        for p in self.programs:
            sig = p.functional_signature
            if sig not in seen:
                seen.add(sig)
                new_space.add(p)
        return new_space

    # ---- Diversity Metrics (from AlgoDiv, 2503.00691) ----

    def functional_clusters(self) -> list[list[Program]]:
        """
        Cluster programs by functional equivalence.
        Programs with identical output signatures go in the same cluster.
        """
        clusters: dict[str, list[Program]] = defaultdict(list)
        for p in self.valid_programs:
            clusters[p.functional_signature].append(p)
        return list(clusters.values())

    def da_at_k(self, k: int) -> float:
        """
        DA@K: Expected number of distinct algorithms in K samples.
        From Definition 3.1 of AlgoDiv (2503.00691):

        DA@K = Σ_m (1 - C(N - s_m, K) / C(N, K))

        where M = number of clusters, s_m = size of cluster m, N = total programs.
        """
        clusters = self.functional_clusters()
        n = len(self.valid_programs)
        if n == 0 or k == 0 or k > n:
            return 0.0

        da = 0.0
        for cluster in clusters:
            s_m = len(cluster)
            # Probability that cluster m is represented in a sample of size K
            if n - s_m >= k:
                prob_missing = comb(n - s_m, k) / comb(n, k)
            else:
                prob_missing = 0.0
            da += (1 - prob_missing)
        return da

    def entropy_diversity(self) -> float:
        """
        EA: Entropy-based algorithmic diversity index.
        EA = exp(-Σ p_m log p_m) where p_m = s_m / N
        """
        clusters = self.functional_clusters()
        n = len(self.valid_programs)
        if n == 0:
            return 0.0

        entropy = 0.0
        for cluster in clusters:
            p = len(cluster) / n
            if p > 0:
                entropy -= p * log(p)
        return exp(entropy)

    def diversity_report(self) -> dict[str, Any]:
        """Comprehensive diversity report for the program space."""
        clusters = self.functional_clusters()
        n_valid = len(self.valid_programs)
        n_total = len(self._programs)

        return {
            "total_programs": n_total,
            "valid_programs": n_valid,
            "syntactically_unique": len(
                set(p.syntactic_hash for p in self.programs)
            ),
            "functionally_unique_clusters": len(clusters),
            "cluster_sizes": sorted(
                [len(c) for c in clusters], reverse=True
            ),
            "da_at_5": self.da_at_k(5) if n_valid >= 5 else None,
            "da_at_10": self.da_at_k(10) if n_valid >= 10 else None,
            "entropy_diversity": self.entropy_diversity(),
            "models_used": list(
                set(p.model_id for p in self.programs)
            ),
        }

    def to_dict(self) -> dict[str, Any]:
        """Serialize the program space for storage."""
        return {
            "stub_id": self.stub.stub_id,
            "stub_name": self.stub.name,
            "programs": [
                {
                    "program_id": p.program_id,
                    "source": p.source,
                    "full_source": p.full_source,
                    "model_id": p.model_id,
                    "is_valid": p.is_valid,
                    "functional_signature": p.functional_signature,
                    "concept_scores": p.concept_scores,
                    "metadata": p.metadata,
                }
                for p in self.programs
            ],
            "diversity": self.diversity_report(),
        }