@ancientpantheon/khronoton-core 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +8 -0
- package/dist/blockchain/stoachain.d.ts +1 -1
- package/dist/blockchain/stoachain.js +16 -1
- package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
- package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
- package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
- package/dist/handlers/execute.d.ts +12 -4
- package/dist/handlers/execute.js +42 -5
- package/dist/handlers/index.d.ts +2 -1
- package/dist/handlers/index.js +4 -1
- package/dist/handlers/read.d.ts +11 -0
- package/dist/handlers/read.js +65 -1
- package/dist/handlers/steps.d.ts +3 -0
- package/dist/handlers/steps.js +152 -0
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- package/dist/provider/index.js +33 -2
- package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
- package/dist/server/executor.d.ts +14 -1
- package/dist/server/executor.js +144 -26
- package/dist/server/index.d.ts +12 -2
- package/dist/server/index.js +38 -1
- package/dist/server/loop.d.ts +17 -13
- package/dist/server/loop.js +19 -12
- package/dist/server/planners/evict.d.ts +20 -0
- package/dist/server/planners/evict.js +143 -0
- package/dist/server/planners/inject.d.ts +22 -0
- package/dist/server/planners/inject.js +120 -0
- package/dist/server/planners/registry.d.ts +118 -0
- package/dist/server/planners/registry.js +94 -0
- package/dist/server/planners/stoa-unwrap.d.ts +23 -0
- package/dist/server/planners/stoa-unwrap.js +204 -0
- package/dist/server/planners/stoa-wrap.d.ts +26 -0
- package/dist/server/planners/stoa-wrap.js +229 -0
- package/dist/server/planners/unstall.d.ts +25 -0
- package/dist/server/planners/unstall.js +135 -0
- package/dist/server/pure/run-advance.d.ts +76 -0
- package/dist/server/pure/run-advance.js +94 -0
- package/dist/server/pure/split-plan.d.ts +144 -0
- package/dist/server/pure/split-plan.js +362 -0
- package/dist/server/pure/yields.d.ts +57 -0
- package/dist/server/pure/yields.js +101 -0
- package/dist/server/resolvers.js +48 -6
- package/dist/server/runs-driver.d.ts +92 -0
- package/dist/server/runs-driver.js +582 -0
- package/dist/server/schema.d.ts +6 -2
- package/dist/server/schema.js +89 -1
- package/dist/server/seams.d.ts +28 -0
- package/dist/server/seams.js +4 -0
- package/dist/server/store/errors.d.ts +38 -0
- package/dist/server/store/errors.js +61 -0
- package/dist/server/store/index.d.ts +7 -2
- package/dist/server/store/index.js +8 -2
- package/dist/server/store/mappers.d.ts +11 -0
- package/dist/server/store/mappers.js +20 -0
- package/dist/server/store/runs.d.ts +233 -0
- package/dist/server/store/runs.js +341 -0
- package/dist/server/store/steps.d.ts +54 -0
- package/dist/server/store/steps.js +74 -0
- package/dist/server/store/yields.d.ts +46 -0
- package/dist/server/store/yields.js +73 -0
- package/dist/server/tick.d.ts +7 -0
- package/dist/server/tick.js +50 -1
- package/dist/server/types.d.ts +42 -3
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* split-plan — the generic gas-probe-and-pack algorithm, ported faithfully
|
|
3
|
+
* from OuroborosNetwork's OuronetUI (`src/lib/signing/measureSplit.ts`;
|
|
4
|
+
* `evenSplit` from its `@ouronet/papyrus` dependency,
|
|
5
|
+
* `node_modules/@ouronet/papyrus/dist/batch.js`). Full rationale in
|
|
6
|
+
* `docs/work/khronoton-chained-runs-phase-4.1/design.md` §B.
|
|
7
|
+
*
|
|
8
|
+
* Given N items and a way to probe a candidate batch's real gas cost, this
|
|
9
|
+
* produces the fewest batches that each fit under a ceiling, using at most
|
|
10
|
+
* two cheap probes to SIZE the job (never probing the full selection, which
|
|
11
|
+
* the real source's own comments document as the exact call a node times
|
|
12
|
+
* out on) plus a small, strictly-bounded number of probes to CONFIRM and
|
|
13
|
+
* then tighten the plan. No DB, no chain client, no I/O — pure and
|
|
14
|
+
* dependency-free, following `run-advance.ts`/`capability.ts`'s convention
|
|
15
|
+
* of keeping types local to the module that owns them.
|
|
16
|
+
*
|
|
17
|
+
* Deliberately NOT ported (per design.md §B): `onProgress` callbacks (UI
|
|
18
|
+
* decoration) and the source's own "give up and submit one unmeasured
|
|
19
|
+
* giant batch anyway" fallback — a failure here is a plain `{ok:false,
|
|
20
|
+
* reason, ...}` return, never a thrown error and never a silently-accepted
|
|
21
|
+
* oversized batch. The caller decides what to do with it.
|
|
22
|
+
*/
|
|
23
|
+
export interface SplitModel {
|
|
24
|
+
/** Gas a transaction costs before any item is processed. Clamped to >= 0. */
|
|
25
|
+
fixed: number;
|
|
26
|
+
/** Marginal gas per item. Clamped to > 0. */
|
|
27
|
+
perItem: number;
|
|
28
|
+
}
|
|
29
|
+
/** What a probe of one candidate batch came back with. A refusal still
|
|
30
|
+
* carries information: `floor` is the gas the chain reported before
|
|
31
|
+
* stopping, a lower bound (never a total) on the true cost. */
|
|
32
|
+
export type ProbeOutcome = {
|
|
33
|
+
ok: true;
|
|
34
|
+
gas: number;
|
|
35
|
+
} | {
|
|
36
|
+
ok: false;
|
|
37
|
+
floor: number | null;
|
|
38
|
+
};
|
|
39
|
+
export type SplitSizing = {
|
|
40
|
+
ok: true;
|
|
41
|
+
/** The whole selection fits in ONE transaction. MEASURED, not modelled. */
|
|
42
|
+
fitsInOne: boolean;
|
|
43
|
+
/** The measured gas of the whole selection — non-null only when `fitsInOne`. */
|
|
44
|
+
measuredGas: number | null;
|
|
45
|
+
/** `fixed + perItem * n`: what one transaction would cost. Modelled unless `fitsInOne`. */
|
|
46
|
+
estimatedTotalGas: number;
|
|
47
|
+
/** How many transactions a split is expected to need. Modelled; planning may differ. */
|
|
48
|
+
estimatedTransactions: number;
|
|
49
|
+
model: SplitModel;
|
|
50
|
+
probes: number;
|
|
51
|
+
/** Carried into `planFromSizing` so the two probes are not paid for twice. */
|
|
52
|
+
readings: {
|
|
53
|
+
one: {
|
|
54
|
+
n: number;
|
|
55
|
+
gas: number;
|
|
56
|
+
};
|
|
57
|
+
sample: {
|
|
58
|
+
n: number;
|
|
59
|
+
gas: number;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
} | {
|
|
63
|
+
ok: false;
|
|
64
|
+
reason: string;
|
|
65
|
+
/** Set when a SINGLE item already busts the ceiling — no split can fix that. */
|
|
66
|
+
infeasible?: {
|
|
67
|
+
singleItemGas: number;
|
|
68
|
+
ceiling: number;
|
|
69
|
+
};
|
|
70
|
+
estimatedTotalGas?: number;
|
|
71
|
+
probes: number;
|
|
72
|
+
};
|
|
73
|
+
export type SplitResult<T> = {
|
|
74
|
+
ok: true;
|
|
75
|
+
/** In-selection-order slices; concatenating them reproduces the selection exactly. */
|
|
76
|
+
batches: T[][];
|
|
77
|
+
/** MEASURED gas of the largest batch in `batches` — not an estimate, not a total. */
|
|
78
|
+
worstBatchGas: number;
|
|
79
|
+
/** `fixed + perItem * n` for the whole selection — an ESTIMATE, labelled as one. */
|
|
80
|
+
estimatedTotalGas: number;
|
|
81
|
+
model: SplitModel;
|
|
82
|
+
probes: number;
|
|
83
|
+
} | {
|
|
84
|
+
ok: false;
|
|
85
|
+
reason: string;
|
|
86
|
+
infeasible?: {
|
|
87
|
+
singleItemGas: number;
|
|
88
|
+
ceiling: number;
|
|
89
|
+
};
|
|
90
|
+
estimatedTotalGas?: number;
|
|
91
|
+
probes: number;
|
|
92
|
+
};
|
|
93
|
+
/** Fit the exact line through two points, clamped to a physically meaningful model. */
|
|
94
|
+
export declare function lineThrough(a: {
|
|
95
|
+
n: number;
|
|
96
|
+
gas: number;
|
|
97
|
+
}, b: {
|
|
98
|
+
n: number;
|
|
99
|
+
gas: number;
|
|
100
|
+
}): SplitModel;
|
|
101
|
+
/**
|
|
102
|
+
* Items one transaction can carry under `ceiling`, per `model`, with a
|
|
103
|
+
* safety margin. Pass `CONFIRMED_MARGIN` (0.99) when the model has been
|
|
104
|
+
* refitted through a real measurement at the size being planned — see
|
|
105
|
+
* that constant's own doc for why the two margins differ.
|
|
106
|
+
*/
|
|
107
|
+
export declare function capacityFor(model: SplitModel, ceiling: number, margin?: number): number;
|
|
108
|
+
/**
|
|
109
|
+
* Split `items` into `count` batches as EQUAL as possible — the first
|
|
110
|
+
* `items.length % count` batches absorb one extra item each, never "full
|
|
111
|
+
* chunks plus a near-empty remainder" (a near-empty last batch is one more
|
|
112
|
+
* signature for almost nothing). Exact port of `@ouronet/papyrus`'s
|
|
113
|
+
* `evenSplit` (`dist/batch.js`).
|
|
114
|
+
*/
|
|
115
|
+
export declare function evenSplit<T>(items: readonly T[], count: number): T[][];
|
|
116
|
+
/**
|
|
117
|
+
* STAGE 1 — size the work. At most two probes, both bounded in size, never
|
|
118
|
+
* the full selection: probe 1 item (fixed-cost reading), then probe
|
|
119
|
+
* `min(n, SAMPLE_SIZE)` items (slope reading). `fitsInOne` is the one
|
|
120
|
+
* claim here that is MEASURED rather than modelled: true only when the
|
|
121
|
+
* sample call covered the whole selection and it came back under ceiling.
|
|
122
|
+
*/
|
|
123
|
+
export declare function measureSize<T>(items: readonly T[], probe: (batch: readonly T[]) => Promise<ProbeOutcome>, ceiling: number): Promise<SplitSizing>;
|
|
124
|
+
/**
|
|
125
|
+
* STAGE 2 — turn a sizing into a confirmed plan. Takes the sizing rather
|
|
126
|
+
* than re-deriving it, so the two cheap probes `measureSize` already spent
|
|
127
|
+
* are not paid for twice; `probes` continues from `sizing.probes`.
|
|
128
|
+
*/
|
|
129
|
+
export declare function planFromSizing<T>(items: readonly T[], sizing: Extract<SplitSizing, {
|
|
130
|
+
ok: true;
|
|
131
|
+
}>, probe: (batch: readonly T[]) => Promise<ProbeOutcome>, ceiling: number): Promise<SplitResult<T>>;
|
|
132
|
+
/**
|
|
133
|
+
* Measure the selection and return the split, in one call — the ONE
|
|
134
|
+
* function any planner in this codebase actually needs. `measureSize`/
|
|
135
|
+
* `planFromSizing` stay exported separately only because the ported
|
|
136
|
+
* source itself exports them separately (and splitting them keeps each
|
|
137
|
+
* stage independently testable); the two-stage split exists in the
|
|
138
|
+
* source only to let a human approve between sizing and planning, which
|
|
139
|
+
* has no equivalent for a headless automaton here (design.md §B).
|
|
140
|
+
*
|
|
141
|
+
* Never throws for a probe failure — every failure path returns
|
|
142
|
+
* `{ok: false, reason, ...}`. The caller decides what to do with it.
|
|
143
|
+
*/
|
|
144
|
+
export declare function splitPlan<T>(items: readonly T[], probe: (batch: readonly T[]) => Promise<ProbeOutcome>, ceiling: number): Promise<SplitResult<T>>;
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* split-plan — the generic gas-probe-and-pack algorithm, ported faithfully
|
|
3
|
+
* from OuroborosNetwork's OuronetUI (`src/lib/signing/measureSplit.ts`;
|
|
4
|
+
* `evenSplit` from its `@ouronet/papyrus` dependency,
|
|
5
|
+
* `node_modules/@ouronet/papyrus/dist/batch.js`). Full rationale in
|
|
6
|
+
* `docs/work/khronoton-chained-runs-phase-4.1/design.md` §B.
|
|
7
|
+
*
|
|
8
|
+
* Given N items and a way to probe a candidate batch's real gas cost, this
|
|
9
|
+
* produces the fewest batches that each fit under a ceiling, using at most
|
|
10
|
+
* two cheap probes to SIZE the job (never probing the full selection, which
|
|
11
|
+
* the real source's own comments document as the exact call a node times
|
|
12
|
+
* out on) plus a small, strictly-bounded number of probes to CONFIRM and
|
|
13
|
+
* then tighten the plan. No DB, no chain client, no I/O — pure and
|
|
14
|
+
* dependency-free, following `run-advance.ts`/`capability.ts`'s convention
|
|
15
|
+
* of keeping types local to the module that owns them.
|
|
16
|
+
*
|
|
17
|
+
* Deliberately NOT ported (per design.md §B): `onProgress` callbacks (UI
|
|
18
|
+
* decoration) and the source's own "give up and submit one unmeasured
|
|
19
|
+
* giant batch anyway" fallback — a failure here is a plain `{ok:false,
|
|
20
|
+
* reason, ...}` return, never a thrown error and never a silently-accepted
|
|
21
|
+
* oversized batch. The caller decides what to do with it.
|
|
22
|
+
*/
|
|
23
|
+
/** The size of the second sizing sample — large enough that the slope
|
|
24
|
+
* reading isn't swamped by measurement noise on the fixed cost, small
|
|
25
|
+
* enough that the probe is an ordinary, cheap batch. Clamped down to `n`
|
|
26
|
+
* when the selection is smaller, in which case this single probe also
|
|
27
|
+
* settles the whole question (see `measureSize`'s `fitsInOne` check). */
|
|
28
|
+
const SAMPLE_SIZE = 64;
|
|
29
|
+
/** Plan for this fraction of the ceiling when the model is still an
|
|
30
|
+
* EXTRAPOLATED two-point fit (probe(1), probe(<=64)) — the line carries
|
|
31
|
+
* real extrapolation error when stretched to a batch an order of
|
|
32
|
+
* magnitude larger, and a cheap margin is the fix. */
|
|
33
|
+
const PLANNING_MARGIN = 0.92;
|
|
34
|
+
/** How many times the confirmation probe may refuse before planFromSizing
|
|
35
|
+
* gives up on this capacity. */
|
|
36
|
+
const MAX_CONFIRMATIONS = 3;
|
|
37
|
+
/** Capacity shrink applied after each refused confirmation. A refusal
|
|
38
|
+
* carries no usable magnitude (execution halts AT the declared limit, so
|
|
39
|
+
* the reported floor UNDER-states the true cost) — shrinking by a
|
|
40
|
+
* constant factor rather than refitting is the honest response. */
|
|
41
|
+
const SHRINK = 0.75;
|
|
42
|
+
/** The margin applied ONCE the model has been refitted through a
|
|
43
|
+
* confirmed batch measured at the size actually being planned — a
|
|
44
|
+
* different, tighter margin for a different (anchored, not
|
|
45
|
+
* extrapolated) model. */
|
|
46
|
+
const CONFIRMED_MARGIN = 0.99;
|
|
47
|
+
/** How many times the plan may be refitted upward from a confirmed
|
|
48
|
+
* measurement. A growth probe that is refused, or comes back over
|
|
49
|
+
* ceiling, leaves the last confirmed plan standing — growth can never
|
|
50
|
+
* make the answer worse. */
|
|
51
|
+
const MAX_GROWTHS = 2;
|
|
52
|
+
/** Fit the exact line through two points, clamped to a physically meaningful model. */
|
|
53
|
+
export function lineThrough(a, b) {
|
|
54
|
+
if (a.n === b.n) {
|
|
55
|
+
// No slope is determined by two readings at the same size. The only
|
|
56
|
+
// honest reading left is a through-the-origin rate, which OVER-states
|
|
57
|
+
// the marginal cost and so UNDER-states capacity — conservative in the
|
|
58
|
+
// direction that cannot produce a refused transaction.
|
|
59
|
+
return { fixed: 0, perItem: Math.max(a.gas / Math.max(a.n, 1), Number.MIN_VALUE) };
|
|
60
|
+
}
|
|
61
|
+
const slope = (b.gas - a.gas) / (b.n - a.n);
|
|
62
|
+
if (!(slope > 0)) {
|
|
63
|
+
// A non-positive slope is noise. The honest conservative reading of two
|
|
64
|
+
// measurements that do not increase is the HIGHEST observed rate
|
|
65
|
+
// through the origin: it over-states the marginal cost, so the plan
|
|
66
|
+
// has more transactions than it needs, which costs signatures rather
|
|
67
|
+
// than a refused transaction.
|
|
68
|
+
const rate = Math.max(a.gas / Math.max(a.n, 1), b.gas / Math.max(b.n, 1));
|
|
69
|
+
return { fixed: 0, perItem: Math.max(rate, Number.MIN_VALUE) };
|
|
70
|
+
}
|
|
71
|
+
const fixed = a.gas - slope * a.n;
|
|
72
|
+
return { fixed: Math.max(0, fixed), perItem: slope };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Items one transaction can carry under `ceiling`, per `model`, with a
|
|
76
|
+
* safety margin. Pass `CONFIRMED_MARGIN` (0.99) when the model has been
|
|
77
|
+
* refitted through a real measurement at the size being planned — see
|
|
78
|
+
* that constant's own doc for why the two margins differ.
|
|
79
|
+
*/
|
|
80
|
+
export function capacityFor(model, ceiling, margin = PLANNING_MARGIN) {
|
|
81
|
+
const room = ceiling * margin - model.fixed;
|
|
82
|
+
return room <= 0 ? 0 : Math.floor(room / model.perItem);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Split `items` into `count` batches as EQUAL as possible — the first
|
|
86
|
+
* `items.length % count` batches absorb one extra item each, never "full
|
|
87
|
+
* chunks plus a near-empty remainder" (a near-empty last batch is one more
|
|
88
|
+
* signature for almost nothing). Exact port of `@ouronet/papyrus`'s
|
|
89
|
+
* `evenSplit` (`dist/batch.js`).
|
|
90
|
+
*/
|
|
91
|
+
export function evenSplit(items, count) {
|
|
92
|
+
const n = items.length;
|
|
93
|
+
const batches = Math.max(1, Math.min(count, n || 1));
|
|
94
|
+
if (n === 0)
|
|
95
|
+
return [[]];
|
|
96
|
+
const base = Math.floor(n / batches);
|
|
97
|
+
const extra = n % batches; // the first `extra` batches absorb one extra item each
|
|
98
|
+
const out = [];
|
|
99
|
+
let i = 0;
|
|
100
|
+
for (let b = 0; b < batches; b++) {
|
|
101
|
+
const size = base + (b < extra ? 1 : 0);
|
|
102
|
+
out.push(items.slice(i, i + size));
|
|
103
|
+
i += size;
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* STAGE 1 — size the work. At most two probes, both bounded in size, never
|
|
109
|
+
* the full selection: probe 1 item (fixed-cost reading), then probe
|
|
110
|
+
* `min(n, SAMPLE_SIZE)` items (slope reading). `fitsInOne` is the one
|
|
111
|
+
* claim here that is MEASURED rather than modelled: true only when the
|
|
112
|
+
* sample call covered the whole selection and it came back under ceiling.
|
|
113
|
+
*/
|
|
114
|
+
export async function measureSize(items, probe, ceiling) {
|
|
115
|
+
const n = items.length;
|
|
116
|
+
let probes = 0;
|
|
117
|
+
const run = async (batch) => {
|
|
118
|
+
probes++;
|
|
119
|
+
return probe(batch);
|
|
120
|
+
};
|
|
121
|
+
if (n === 0) {
|
|
122
|
+
return {
|
|
123
|
+
ok: true,
|
|
124
|
+
fitsInOne: true,
|
|
125
|
+
measuredGas: 0,
|
|
126
|
+
estimatedTotalGas: 0,
|
|
127
|
+
estimatedTransactions: 1,
|
|
128
|
+
model: { fixed: 0, perItem: 0 },
|
|
129
|
+
probes: 0,
|
|
130
|
+
readings: { one: { n: 0, gas: 0 }, sample: { n: 0, gas: 0 } },
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// 1] ONE ITEM — the fixed cost. Without this point the only line
|
|
134
|
+
// available passes through the origin, which charges every item a
|
|
135
|
+
// share of the per-transaction overhead and systematically
|
|
136
|
+
// under-splits. The single cheapest call the operation has.
|
|
137
|
+
const one = await run(items.slice(0, 1));
|
|
138
|
+
if (!one.ok) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
probes,
|
|
142
|
+
reason: "a single item could not be simulated" +
|
|
143
|
+
(one.floor != null ? ` (the chain stopped at ${one.floor.toLocaleString()} gas)` : "") +
|
|
144
|
+
".",
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
if (one.gas > ceiling) {
|
|
148
|
+
return {
|
|
149
|
+
ok: false,
|
|
150
|
+
probes,
|
|
151
|
+
estimatedTotalGas: one.gas * n,
|
|
152
|
+
infeasible: { singleItemGas: one.gas, ceiling },
|
|
153
|
+
reason: `one item alone costs ${one.gas.toLocaleString()} gas, over the ` +
|
|
154
|
+
`${ceiling.toLocaleString()} a transaction may use. No split can fix that — ` +
|
|
155
|
+
`this operation needs a multi-step route.`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
// A one-item selection is already answered — and it is a MEASUREMENT,
|
|
159
|
+
// not a model.
|
|
160
|
+
if (n === 1) {
|
|
161
|
+
return {
|
|
162
|
+
ok: true,
|
|
163
|
+
fitsInOne: true,
|
|
164
|
+
measuredGas: one.gas,
|
|
165
|
+
estimatedTotalGas: one.gas,
|
|
166
|
+
estimatedTransactions: 1,
|
|
167
|
+
model: { fixed: 0, perItem: one.gas },
|
|
168
|
+
probes,
|
|
169
|
+
readings: { one: { n: 1, gas: one.gas }, sample: { n: 1, gas: one.gas } },
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
// 2] A SAMPLE BATCH — the slope. Capped at SAMPLE_SIZE so this probe is
|
|
173
|
+
// always an ordinary batch, never the full selection.
|
|
174
|
+
const sampleN = Math.min(n, SAMPLE_SIZE);
|
|
175
|
+
const sample = await run(items.slice(0, sampleN));
|
|
176
|
+
if (!sample.ok) {
|
|
177
|
+
return {
|
|
178
|
+
ok: false,
|
|
179
|
+
probes,
|
|
180
|
+
reason: `a ${sampleN}-item sample could not be simulated` +
|
|
181
|
+
(sample.floor != null ? ` (the chain stopped at ${sample.floor.toLocaleString()} gas)` : "") +
|
|
182
|
+
". Try a smaller selection.",
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const model = lineThrough({ n: 1, gas: one.gas }, { n: sampleN, gas: sample.gas });
|
|
186
|
+
const estimatedTotalGas = Math.round(model.fixed + model.perItem * n);
|
|
187
|
+
const readings = { one: { n: 1, gas: one.gas }, sample: { n: sampleN, gas: sample.gas } };
|
|
188
|
+
// THE WHOLE SELECTION ALREADY FITS, and the sample proves it when the
|
|
189
|
+
// sample IS the selection.
|
|
190
|
+
if (sampleN === n && sample.gas <= ceiling) {
|
|
191
|
+
return {
|
|
192
|
+
ok: true,
|
|
193
|
+
fitsInOne: true,
|
|
194
|
+
measuredGas: sample.gas,
|
|
195
|
+
estimatedTotalGas,
|
|
196
|
+
estimatedTransactions: 1,
|
|
197
|
+
model,
|
|
198
|
+
probes,
|
|
199
|
+
readings,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
const capacity = capacityFor(model, ceiling);
|
|
203
|
+
if (capacity < 1) {
|
|
204
|
+
return {
|
|
205
|
+
ok: false,
|
|
206
|
+
probes,
|
|
207
|
+
estimatedTotalGas,
|
|
208
|
+
infeasible: { singleItemGas: one.gas, ceiling },
|
|
209
|
+
reason: `the fixed cost of one transaction (about ` +
|
|
210
|
+
`${Math.round(model.fixed).toLocaleString()} gas) leaves no room under the ` +
|
|
211
|
+
`${ceiling.toLocaleString()} limit. This operation needs a multi-step route.`,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
ok: true,
|
|
216
|
+
fitsInOne: false,
|
|
217
|
+
measuredGas: null,
|
|
218
|
+
estimatedTotalGas,
|
|
219
|
+
estimatedTransactions: Math.max(1, Math.ceil(n / capacity)),
|
|
220
|
+
model,
|
|
221
|
+
probes,
|
|
222
|
+
readings,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* STAGE 2 — turn a sizing into a confirmed plan. Takes the sizing rather
|
|
227
|
+
* than re-deriving it, so the two cheap probes `measureSize` already spent
|
|
228
|
+
* are not paid for twice; `probes` continues from `sizing.probes`.
|
|
229
|
+
*/
|
|
230
|
+
export async function planFromSizing(items, sizing, probe, ceiling) {
|
|
231
|
+
const n = items.length;
|
|
232
|
+
let probes = sizing.probes;
|
|
233
|
+
const { model, estimatedTotalGas } = sizing;
|
|
234
|
+
const one = sizing.readings.one;
|
|
235
|
+
const run = async (batch) => {
|
|
236
|
+
probes++;
|
|
237
|
+
return probe(batch);
|
|
238
|
+
};
|
|
239
|
+
let capacity = capacityFor(model, ceiling);
|
|
240
|
+
if (capacity < 1) {
|
|
241
|
+
return {
|
|
242
|
+
ok: false,
|
|
243
|
+
probes,
|
|
244
|
+
estimatedTotalGas,
|
|
245
|
+
infeasible: { singleItemGas: one.gas, ceiling },
|
|
246
|
+
reason: `the fixed cost of one transaction (about ` +
|
|
247
|
+
`${Math.round(model.fixed).toLocaleString()} gas) leaves no room under the ` +
|
|
248
|
+
`${ceiling.toLocaleString()} limit. This operation needs a multi-step route.`,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/** Cut the selection at a capacity and name the batch whose measurement describes the plan. */
|
|
252
|
+
const planAt = (cap) => {
|
|
253
|
+
const count = Math.max(1, Math.ceil(n / Math.max(1, cap)));
|
|
254
|
+
const batches = evenSplit(items, count);
|
|
255
|
+
const first = batches[0];
|
|
256
|
+
if (first === undefined)
|
|
257
|
+
return null;
|
|
258
|
+
return { batches, largest: batches.reduce((a, b) => (b.length > a.length ? b : a), first) };
|
|
259
|
+
};
|
|
260
|
+
// CONFIRM THE PLAN ACTUALLY BEING RETURNED — the largest batch of the
|
|
261
|
+
// exact split handed back, so `worstBatchGas` describes this plan, not a
|
|
262
|
+
// nearby batch measured on the way.
|
|
263
|
+
let best = null;
|
|
264
|
+
for (let attempt = 0; attempt < MAX_CONFIRMATIONS; attempt++) {
|
|
265
|
+
const planned = planAt(capacity);
|
|
266
|
+
if (!planned) {
|
|
267
|
+
return { ok: false, probes, estimatedTotalGas, reason: "the split produced no batches." };
|
|
268
|
+
}
|
|
269
|
+
const got = await run(planned.largest);
|
|
270
|
+
if (got.ok && got.gas <= ceiling) {
|
|
271
|
+
best = { batches: planned.batches, gas: got.gas, size: planned.largest.length };
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
// Refused or over. The line under-estimated; shrink capacity and try
|
|
275
|
+
// once more. A refusal carries no usable magnitude, which is why this
|
|
276
|
+
// shrinks by a constant rather than refitting.
|
|
277
|
+
const shrunk = Math.floor(capacity * SHRINK);
|
|
278
|
+
if (shrunk < 1 || shrunk === capacity)
|
|
279
|
+
break;
|
|
280
|
+
capacity = shrunk;
|
|
281
|
+
}
|
|
282
|
+
if (!best) {
|
|
283
|
+
return {
|
|
284
|
+
ok: false,
|
|
285
|
+
probes,
|
|
286
|
+
estimatedTotalGas,
|
|
287
|
+
reason: `could not confirm a batch size under ${ceiling.toLocaleString()} gas after ` +
|
|
288
|
+
`${probes} simulation(s). Try a smaller selection.`,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
// PACK TIGHTER. The line from stage 1 is fitted at n=1 and n<=64 and
|
|
292
|
+
// extrapolated to the operating size, which is why PLANNING_MARGIN
|
|
293
|
+
// exists; stage 2 has just measured a real batch AT the planned size — a
|
|
294
|
+
// point the fit never had, and the only point that actually matters.
|
|
295
|
+
// Refitting through it replaces an extrapolation with an anchor, so the
|
|
296
|
+
// margin can step aside for CONFIRMED_MARGIN. This can never make the
|
|
297
|
+
// answer worse: `best` only ever advances on a confirmed measurement
|
|
298
|
+
// under ceiling, so a refused or over-ceiling growth probe just breaks
|
|
299
|
+
// the loop and leaves the previously confirmed plan exactly as it was.
|
|
300
|
+
let fitted = model;
|
|
301
|
+
for (let growth = 0; growth < MAX_GROWTHS; growth++) {
|
|
302
|
+
fitted = lineThrough({ n: 1, gas: one.gas }, { n: best.size, gas: best.gas });
|
|
303
|
+
const grown = capacityFor(fitted, ceiling, CONFIRMED_MARGIN);
|
|
304
|
+
if (grown <= best.size)
|
|
305
|
+
break;
|
|
306
|
+
const planned = planAt(grown);
|
|
307
|
+
// Fewer BATCHES is the only gain worth a probe. A larger capacity that
|
|
308
|
+
// still rounds to the same transaction count buys nothing.
|
|
309
|
+
if (!planned || planned.batches.length >= best.batches.length)
|
|
310
|
+
break;
|
|
311
|
+
const got = await run(planned.largest);
|
|
312
|
+
if (!got.ok || got.gas > ceiling)
|
|
313
|
+
break;
|
|
314
|
+
best = { batches: planned.batches, gas: got.gas, size: planned.largest.length };
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
ok: true,
|
|
318
|
+
batches: best.batches,
|
|
319
|
+
worstBatchGas: best.gas,
|
|
320
|
+
// Reported from the REFITTED line: it is anchored at the operating
|
|
321
|
+
// size, so it is a better estimate of the whole job than the
|
|
322
|
+
// small-sample line that produced the first plan.
|
|
323
|
+
estimatedTotalGas: Math.round(fitted.fixed + fitted.perItem * n),
|
|
324
|
+
model: fitted,
|
|
325
|
+
probes,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Measure the selection and return the split, in one call — the ONE
|
|
330
|
+
* function any planner in this codebase actually needs. `measureSize`/
|
|
331
|
+
* `planFromSizing` stay exported separately only because the ported
|
|
332
|
+
* source itself exports them separately (and splitting them keeps each
|
|
333
|
+
* stage independently testable); the two-stage split exists in the
|
|
334
|
+
* source only to let a human approve between sizing and planning, which
|
|
335
|
+
* has no equivalent for a headless automaton here (design.md §B).
|
|
336
|
+
*
|
|
337
|
+
* Never throws for a probe failure — every failure path returns
|
|
338
|
+
* `{ok: false, reason, ...}`. The caller decides what to do with it.
|
|
339
|
+
*/
|
|
340
|
+
export async function splitPlan(items, probe, ceiling) {
|
|
341
|
+
const sizing = await measureSize(items, probe, ceiling);
|
|
342
|
+
if (!sizing.ok) {
|
|
343
|
+
return {
|
|
344
|
+
ok: false,
|
|
345
|
+
probes: sizing.probes,
|
|
346
|
+
reason: sizing.reason,
|
|
347
|
+
estimatedTotalGas: sizing.estimatedTotalGas,
|
|
348
|
+
infeasible: sizing.infeasible,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
if (sizing.fitsInOne) {
|
|
352
|
+
return {
|
|
353
|
+
ok: true,
|
|
354
|
+
batches: [[...items]],
|
|
355
|
+
worstBatchGas: sizing.measuredGas ?? 0,
|
|
356
|
+
estimatedTotalGas: sizing.estimatedTotalGas,
|
|
357
|
+
model: sizing.model,
|
|
358
|
+
probes: sizing.probes,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
return planFromSizing(items, sizing, probe, ceiling);
|
|
362
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* yields — the pure `$yield` placeholder resolver
|
|
3
|
+
* (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a yield").
|
|
4
|
+
*
|
|
5
|
+
* A step references a value a prior step produced by writing a structured
|
|
6
|
+
* placeholder, `{"$yield": "<name>"}`, anywhere a literal value would
|
|
7
|
+
* normally go inside its stored `payload_json`/`planner_params_json`.
|
|
8
|
+
* `resolveYieldRefs` walks a parsed JSON value and substitutes every such
|
|
9
|
+
* placeholder against a run's yield pool (a flat `{name: value}` map — see
|
|
10
|
+
* `store/yields.ts`'s `getYieldPool`), leaving everything else untouched. No
|
|
11
|
+
* DB, no chain client, no I/O: pure and dependency-free, following
|
|
12
|
+
* `run-advance.ts`/`split-plan.ts`'s convention of keeping types local to the
|
|
13
|
+
* module that owns them.
|
|
14
|
+
*
|
|
15
|
+
* A yielded value is returned as-is, never recursed into further — it is
|
|
16
|
+
* already fully resolved (it was produced by a planner's return value or a
|
|
17
|
+
* confirmed leg's on-chain result, not itself written with placeholders).
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Thrown by `resolveYieldRefs` when a `{"$yield": "<name>"}` placeholder
|
|
21
|
+
* names a yield that has not been produced yet in this run (typo, wrong
|
|
22
|
+
* step order, or referenced before it was ever produced) — mirroring
|
|
23
|
+
* `runs-driver.ts`'s `PlannerNotRegisteredError` precedent of living next
|
|
24
|
+
* to its own primary thrower rather than in `store/errors.ts`, and this
|
|
25
|
+
* package's existing "never silently guess" posture: a missing yield must
|
|
26
|
+
* never silently resolve to `null`/`undefined`.
|
|
27
|
+
*/
|
|
28
|
+
export declare class YieldNotFoundError extends Error {
|
|
29
|
+
constructor(name: string);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Recursively walks `value`, substituting every `{"$yield": "<name>"}`
|
|
33
|
+
* placeholder against `pool`. Arrays map each element through
|
|
34
|
+
* `resolveYieldRefs`; a placeholder object resolves to `pool[name]` (not
|
|
35
|
+
* recursed into further); any other plain object has every one of its own
|
|
36
|
+
* entries individually resolved; anything else (string/number/boolean/
|
|
37
|
+
* null) returns as-is.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveYieldRefs(value: unknown, pool: Record<string, unknown>): unknown;
|
|
40
|
+
/**
|
|
41
|
+
* The `mode:'single'` analog of `planners/registry.ts`'s `resolvePlannerFor`:
|
|
42
|
+
* build a shallow clone of a step row with its `payload_json` field's
|
|
43
|
+
* `$yield` placeholders resolved against `pool`, ready to pass straight into
|
|
44
|
+
* `store/mappers.ts`'s `stepRowToDefinition`. Planner-mode steps get this
|
|
45
|
+
* exact pattern for free via `resolvePlannerFor`; a review finding caught
|
|
46
|
+
* that the single-mode case had quietly re-derived the identical
|
|
47
|
+
* JSON.parse/resolveYieldRefs/JSON.stringify/spread sequence independently
|
|
48
|
+
* in both `runs-driver.ts` and `handlers/steps.ts` instead of sharing one
|
|
49
|
+
* implementation — the exact drift risk `resolvePlannerFor` itself was
|
|
50
|
+
* extracted to close for the planner-mode case, left open for this sibling
|
|
51
|
+
* one. A generic constraint (not importing `CodexCronotonStepRow` by name)
|
|
52
|
+
* keeps this module import-free, matching its own "pure and dependency-free"
|
|
53
|
+
* doc claim above.
|
|
54
|
+
*/
|
|
55
|
+
export declare function resolveSingleStepPayload<T extends {
|
|
56
|
+
payload_json: string | null;
|
|
57
|
+
}>(step: T, pool: Record<string, unknown>): T;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* yields — the pure `$yield` placeholder resolver
|
|
3
|
+
* (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a yield").
|
|
4
|
+
*
|
|
5
|
+
* A step references a value a prior step produced by writing a structured
|
|
6
|
+
* placeholder, `{"$yield": "<name>"}`, anywhere a literal value would
|
|
7
|
+
* normally go inside its stored `payload_json`/`planner_params_json`.
|
|
8
|
+
* `resolveYieldRefs` walks a parsed JSON value and substitutes every such
|
|
9
|
+
* placeholder against a run's yield pool (a flat `{name: value}` map — see
|
|
10
|
+
* `store/yields.ts`'s `getYieldPool`), leaving everything else untouched. No
|
|
11
|
+
* DB, no chain client, no I/O: pure and dependency-free, following
|
|
12
|
+
* `run-advance.ts`/`split-plan.ts`'s convention of keeping types local to the
|
|
13
|
+
* module that owns them.
|
|
14
|
+
*
|
|
15
|
+
* A yielded value is returned as-is, never recursed into further — it is
|
|
16
|
+
* already fully resolved (it was produced by a planner's return value or a
|
|
17
|
+
* confirmed leg's on-chain result, not itself written with placeholders).
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Thrown by `resolveYieldRefs` when a `{"$yield": "<name>"}` placeholder
|
|
21
|
+
* names a yield that has not been produced yet in this run (typo, wrong
|
|
22
|
+
* step order, or referenced before it was ever produced) — mirroring
|
|
23
|
+
* `runs-driver.ts`'s `PlannerNotRegisteredError` precedent of living next
|
|
24
|
+
* to its own primary thrower rather than in `store/errors.ts`, and this
|
|
25
|
+
* package's existing "never silently guess" posture: a missing yield must
|
|
26
|
+
* never silently resolve to `null`/`undefined`.
|
|
27
|
+
*/
|
|
28
|
+
export class YieldNotFoundError extends Error {
|
|
29
|
+
constructor(name) {
|
|
30
|
+
super(`no yield named "${name}" has been produced yet in this run`);
|
|
31
|
+
this.name = "YieldNotFoundError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** True for a plain object whose OWN keys are exactly `["$yield"]` and whose
|
|
35
|
+
* `$yield` value is a string — the one shape `resolveYieldRefs` treats as a
|
|
36
|
+
* placeholder rather than an ordinary object to recurse into. */
|
|
37
|
+
function isYieldPlaceholder(value) {
|
|
38
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
39
|
+
return false;
|
|
40
|
+
const keys = Object.keys(value);
|
|
41
|
+
return (keys.length === 1 &&
|
|
42
|
+
keys[0] === "$yield" &&
|
|
43
|
+
typeof value.$yield === "string");
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Recursively walks `value`, substituting every `{"$yield": "<name>"}`
|
|
47
|
+
* placeholder against `pool`. Arrays map each element through
|
|
48
|
+
* `resolveYieldRefs`; a placeholder object resolves to `pool[name]` (not
|
|
49
|
+
* recursed into further); any other plain object has every one of its own
|
|
50
|
+
* entries individually resolved; anything else (string/number/boolean/
|
|
51
|
+
* null) returns as-is.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveYieldRefs(value, pool) {
|
|
54
|
+
if (Array.isArray(value)) {
|
|
55
|
+
return value.map((item) => resolveYieldRefs(item, pool));
|
|
56
|
+
}
|
|
57
|
+
if (isYieldPlaceholder(value)) {
|
|
58
|
+
const name = value.$yield;
|
|
59
|
+
// `Object.prototype.hasOwnProperty.call`, NEVER the `in` operator —
|
|
60
|
+
// `in` walks the full prototype chain, so for a pool that is (or
|
|
61
|
+
// ever could be) a plain object literal, a never-produced name like
|
|
62
|
+
// "toString"/"constructor"/"valueOf"/"hasOwnProperty" would silently
|
|
63
|
+
// resolve to an inherited Object.prototype function instead of
|
|
64
|
+
// throwing YieldNotFoundError, exactly defeating this module's own
|
|
65
|
+
// "never silently guess" invariant (see the class doc above). This
|
|
66
|
+
// check is safe regardless of how `pool` was constructed — it does
|
|
67
|
+
// not rely on every caller remembering to build a prototype-less
|
|
68
|
+
// object (`store/yields.ts`'s `getYieldPool` does, via
|
|
69
|
+
// `Object.create(null)`, but `handlers/steps.ts`'s standalone-fire
|
|
70
|
+
// route passes a bare `{}` literal directly).
|
|
71
|
+
if (!Object.prototype.hasOwnProperty.call(pool, name)) {
|
|
72
|
+
throw new YieldNotFoundError(name);
|
|
73
|
+
}
|
|
74
|
+
return pool[name];
|
|
75
|
+
}
|
|
76
|
+
if (value !== null && typeof value === "object") {
|
|
77
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveYieldRefs(v, pool)]));
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The `mode:'single'` analog of `planners/registry.ts`'s `resolvePlannerFor`:
|
|
83
|
+
* build a shallow clone of a step row with its `payload_json` field's
|
|
84
|
+
* `$yield` placeholders resolved against `pool`, ready to pass straight into
|
|
85
|
+
* `store/mappers.ts`'s `stepRowToDefinition`. Planner-mode steps get this
|
|
86
|
+
* exact pattern for free via `resolvePlannerFor`; a review finding caught
|
|
87
|
+
* that the single-mode case had quietly re-derived the identical
|
|
88
|
+
* JSON.parse/resolveYieldRefs/JSON.stringify/spread sequence independently
|
|
89
|
+
* in both `runs-driver.ts` and `handlers/steps.ts` instead of sharing one
|
|
90
|
+
* implementation — the exact drift risk `resolvePlannerFor` itself was
|
|
91
|
+
* extracted to close for the planner-mode case, left open for this sibling
|
|
92
|
+
* one. A generic constraint (not importing `CodexCronotonStepRow` by name)
|
|
93
|
+
* keeps this module import-free, matching its own "pure and dependency-free"
|
|
94
|
+
* doc claim above.
|
|
95
|
+
*/
|
|
96
|
+
export function resolveSingleStepPayload(step, pool) {
|
|
97
|
+
return {
|
|
98
|
+
...step,
|
|
99
|
+
payload_json: JSON.stringify(resolveYieldRefs(JSON.parse(step.payload_json ?? "{}"), pool)),
|
|
100
|
+
};
|
|
101
|
+
}
|