File size: 5,893 Bytes
871e4fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Measured-completion worker and bounded atomic candidate checks.

These are real CPU threads and monotonic timestamps. They do NOT cancel GPU
commands, reserve GPU execution, guarantee native fallback latency or own DXGI.
"""
from dataclasses import dataclass
from collections import deque
import math
import threading
import time


@dataclass(frozen=True)
class Publication:
    job_id: int
    epoch: int
    submitted_s: float
    started_s: float
    completed_s: float
    value: object
    error: str | None


class LatestOnlyWorker:
    """One running and one overwriteable queued job; never a stale FIFO backlog."""
    def __init__(self, function, clock=time.perf_counter):
        self.function, self.clock = function, clock
        self.cv = threading.Condition()
        self.pending = None
        self.latest = None
        self.epoch = 0
        self.closed = False
        self.running = False
        self.replaced = 0
        self.discarded_epochs = 0
        self.completed = 0
        self.worker = threading.Thread(target=self._run, daemon=True, name='yeorin-observer')
        self.worker.start()

    def submit(self, job_id, value):
        with self.cv:
            if self.closed:
                raise RuntimeError('worker is closed')
            if self.pending is not None:
                self.replaced += 1
            self.pending = (job_id, self.epoch, self.clock(), value)
            self.cv.notify_all()

    def invalidate(self):
        with self.cv:
            self.epoch += 1
            self.pending = None
            self.latest = None
            return self.epoch

    def snapshot(self):
        with self.cv:
            return self.latest

    def _run(self):
        while True:
            with self.cv:
                while self.pending is None and not self.closed:
                    self.cv.wait()
                if self.closed:
                    return
                job_id, epoch, submitted, value = self.pending
                self.pending = None
                self.running = True
            started = self.clock()
            try:
                result, error = self.function(value), None
            except Exception as exc:
                result, error = None, type(exc).__name__ + ': ' + str(exc)
            done = self.clock()
            with self.cv:
                self.running = False
                self.completed += 1
                if epoch == self.epoch and not self.closed:
                    self.latest = Publication(job_id, epoch, submitted, started, done, result, error)
                else:
                    self.discarded_epochs += 1
                self.cv.notify_all()

    def wait_idle(self, timeout=5.0):
        end = self.clock() + timeout
        with self.cv:
            while self.running or self.pending is not None:
                remaining = end - self.clock()
                if remaining <= 0:
                    return False
                self.cv.wait(remaining)
            return True

    def close(self, timeout=5.0):
        with self.cv:
            self.closed = True
            self.pending = None
            self.cv.notify_all()
        self.worker.join(timeout)
        return not self.worker.is_alive()

    def __enter__(self): return self
    def __exit__(self, *args): self.close()


class MeasuredBudget:
    """Rolling high quantile + margin: estimate, not an execution-time theorem."""
    def __init__(self, capacity=256, quantile=.99, margin_s=.00025, warmup=32):
        if not isinstance(capacity,int) or not 1 <= warmup <= capacity or not 0 < quantile <= 1 or not math.isfinite(margin_s) or margin_s < 0:
            raise ValueError('invalid timing policy')
        self.samples = deque(maxlen=capacity)
        self.quantile, self.margin, self.warmup = quantile, margin_s, warmup
        self.overruns = 0

    @property
    def estimate(self):
        if len(self.samples) < self.warmup: return None
        s=sorted(self.samples)
        return s[min(len(s)-1, math.ceil(self.quantile*len(s))-1)] + self.margin

    def observe(self, elapsed_s):
        if not math.isfinite(elapsed_s) or elapsed_s < 0:
            raise ValueError('invalid duration')
        previous = self.estimate
        if previous is not None and elapsed_s > previous:
            self.overruns += 1
        self.samples.append(elapsed_s)

    def can_start(self, now_s, deadline_s):
        if not math.isfinite(now_s) or not math.isfinite(deadline_s): return False
        b=self.estimate
        return b is not None and now_s+b <= deadline_s


class CandidateGate:
    """Atomic identity/epoch/readiness check for a HOST-OWNED candidate.

    The result is content eligibility only. It is not a promise that submitted
    correction work had no timing impact on baseline work.
    """
    def __init__(self):
        self.lock=threading.Lock(); self.identity=None; self.last_output_id=-1
    def publish(self, frame, generation, epoch):
        if min(frame,generation,epoch)<0: raise ValueError('invalid identity')
        with self.lock: self.identity=(frame,generation,epoch)
    def commit(self, identity, output_id, now_s, deadline_s, gpu_ready, lease_published_s, lease_expires_s):
        with self.lock:
            if identity != self.identity: return False,'source_changed'
            if not isinstance(output_id,int) or output_id <= self.last_output_id: return False,'duplicate_or_old_output'
            if not all(math.isfinite(x) for x in (now_s,deadline_s,lease_published_s,lease_expires_s)):
                return False,'invalid_time'
            if now_s < lease_published_s: return False,'unpublished'
            if now_s > min(deadline_s,lease_expires_s): return False,'late'
            if not gpu_ready: return False,'gpu_not_ready'
            self.last_output_id=output_id
            return True,'content_eligible_not_latency_certified'