File size: 4,645 Bytes
aff9293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Budget accounting, anytime paired evidence, and transactional checkpoints.

The algebraic verifier is exact. The statistical gate has an explicitly
conditional null; it does not turn timing observations into universal proofs.
"""
from __future__ import annotations
from dataclasses import dataclass
import json
import math
import os
from pathlib import Path
import tempfile
from synthesis import digest

@dataclass
class CreditAccount:
    bootstrap: int
    credit: int = 0
    baseline_work: int = 0
    service_work: int = 0
    investment_work: int = 0
    def __post_init__(self):
        if self.bootstrap < 0:
            raise ValueError('Negative bootstrap allowance')
        self.credit = self.bootstrap
    def service(self, baseline, actual):
        if baseline < 0 or actual < 0:
            raise ValueError('Negative work')
        new = self.credit + baseline - actual
        if new < 0:
            raise RuntimeError('Insufficient credit for service')
        self.credit = new
        self.baseline_work += baseline
        self.service_work += actual
        self.check()
    def invest(self, cost):
        if cost < 0:
            raise ValueError('Negative investment')
        if cost > self.credit:
            return False
        self.credit -= cost
        self.investment_work += cost
        self.check()
        return True
    def check(self):
        assert self.credit == (self.bootstrap+self.baseline_work-
                               self.service_work-self.investment_work)
        assert self.credit >= 0
    def snapshot(self):
        return dict(self.__dict__)


class AnytimeGate:
    """A positive betting process for paired signs in [-1,1].

    Under E[X_t | past] <= 0 and predictable 0 <= lambda_t <= 1,
    product(1+lambda_t*X_t) is a nonnegative supermartingale.
    The j-th proposal gets alpha/[j(j+1)], allowing indefinitely many births.
    """
    def __init__(self, proposal, alpha=0.05, bet=0.5):
        if proposal < 1 or not 0 < alpha < 1 or not 0 < bet < 1:
            raise ValueError('Invalid audit configuration')
        self.proposal = proposal
        self.alpha = alpha
        self.bet = bet
        self.log_e = 0.0
        self.trials = 0
        self.threshold = math.log(proposal*(proposal+1)/alpha)
        self.accepted = False
    def update(self, x):
        if not -1 <= x <= 1:
            raise ValueError('Evidence must be bounded in [-1,1]')
        self.log_e += math.log1p(self.bet*x)
        self.trials += 1
        self.accepted |= self.log_e >= self.threshold
        return self.accepted
    def snapshot(self):
        return dict(self.__dict__)


def atomic_save(path, payload):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    envelope = {'payload': payload, 'sha256': digest(payload)}
    fd, temporary = tempfile.mkstemp(prefix=path.name+'.', dir=path.parent)
    try:
        with os.fdopen(fd, 'w') as f:
            json.dump(envelope, f, sort_keys=True, indent=2)
            f.flush()
            os.fsync(f.fileno())
        os.replace(temporary, path)
    except BaseException:
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass
        raise


def read_checkpoint(path):
    envelope = json.loads(Path(path).read_text())
    payload = envelope['payload']
    if envelope.get('sha256') != digest(payload):
        raise ValueError('Checkpoint integrity failure')
    return payload

class InvestmentReservation:
    """Debit a proved upper bound BEFORE work; refund only after settlement.

    An exception conservatively leaves the reservation charged. The caller
    must enforce or prove the upper bound; this is not a process-time limiter.
    Original exploratory lineage files use retrospective settlement and all
    their measured investments were affordable. This helper repairs the
    controller contract for future bounded deployment.
    """
    def __init__(self, account, upper_bound):
        if type(upper_bound) is not int or upper_bound < 0:
            raise ValueError('A nonnegative integer upper bound is required')
        if not account.invest(upper_bound):
            raise RuntimeError('Insufficient prepaid credit')
        self.account=account;self.upper_bound=upper_bound;self.settled=False
    def settle(self, actual):
        if self.settled or type(actual) is not int or not 0<=actual<=self.upper_bound:
            raise ValueError('Invalid reservation settlement')
        refund=self.upper_bound-actual
        self.account.credit+=refund;self.account.investment_work-=refund
        self.account.check();self.settled=True