@spellkave/sdk 0.0.0-bootstrap → 0.0.0-stage
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/README.md +2 -155
- package/package.json +4 -63
- package/LICENSE +0 -89
- package/src/binding_rows.ts +0 -186
- package/src/connection.ts +0 -964
- package/src/core/actor.ts +0 -62
- package/src/core/actor_control.ts +0 -193
- package/src/core/actor_control_query_methods.ts +0 -101
- package/src/core/actor_control_reaction_methods.ts +0 -79
- package/src/core/actor_control_sense_methods.ts +0 -81
- package/src/core/actor_control_source.ts +0 -57
- package/src/core/actor_session_methods.ts +0 -226
- package/src/core/binding_drift.ts +0 -301
- package/src/core/credential.ts +0 -259
- package/src/core/driver_control.ts +0 -54
- package/src/core/effective_environment_state.ts +0 -71
- package/src/core/factored_manipulation_attempt.ts +0 -158
- package/src/core/ids.ts +0 -60
- package/src/core/interaction/canonical.ts +0 -15
- package/src/core/interaction/fingerprint.ts +0 -118
- package/src/core/interaction/index.ts +0 -31
- package/src/core/interaction/intent.ts +0 -284
- package/src/core/interaction/outcome.ts +0 -67
- package/src/core/interaction/rejection_ledger.ts +0 -108
- package/src/core/kernel_contract.generated.ts +0 -10
- package/src/core/log.ts +0 -23
- package/src/core/movement.ts +0 -111
- package/src/core/node-io.ts +0 -208
- package/src/core/paths.ts +0 -220
- package/src/core/profile.ts +0 -270
- package/src/core/profiles.ts +0 -9
- package/src/core/provenance_buffer.ts +0 -102
- package/src/core/readers/_helpers.ts +0 -273
- package/src/core/readers/action_description.ts +0 -17
- package/src/core/readers/action_economy_events.ts +0 -149
- package/src/core/readers/actor_body_swaps.ts +0 -62
- package/src/core/readers/actor_snapshot.ts +0 -197
- package/src/core/readers/actor_states.ts +0 -163
- package/src/core/readers/actors_and_bodies.ts +0 -179
- package/src/core/readers/affordance_cue.ts +0 -59
- package/src/core/readers/affordance_defaults.ts +0 -158
- package/src/core/readers/affordance_group_membership.ts +0 -67
- package/src/core/readers/affordance_input.ts +0 -129
- package/src/core/readers/affordance_reference.ts +0 -41
- package/src/core/readers/apply_consequences.ts +0 -54
- package/src/core/readers/audience_trace_presentation.ts +0 -62
- package/src/core/readers/bounded_collection.ts +0 -29
- package/src/core/readers/bundle_definitions.ts +0 -74
- package/src/core/readers/bundle_entities.ts +0 -62
- package/src/core/readers/co_location.ts +0 -71
- package/src/core/readers/combat_session.ts +0 -124
- package/src/core/readers/combat_session_active.ts +0 -44
- package/src/core/readers/combat_session_feedback.ts +0 -37
- package/src/core/readers/combat_session_grid.ts +0 -117
- package/src/core/readers/combat_session_roster.ts +0 -98
- package/src/core/readers/combat_session_types.ts +0 -51
- package/src/core/readers/condition_deltas.ts +0 -53
- package/src/core/readers/container_contents.ts +0 -92
- package/src/core/readers/dialogue_guide.ts +0 -99
- package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
- package/src/core/readers/driver_control.ts +0 -64
- package/src/core/readers/entity_art.ts +0 -219
- package/src/core/readers/entity_containment.ts +0 -119
- package/src/core/readers/equipment.ts +0 -99
- package/src/core/readers/intervention_windows.ts +0 -136
- package/src/core/readers/inventory_query.ts +0 -145
- package/src/core/readers/item_detail.ts +0 -198
- package/src/core/readers/location_snapshot.ts +0 -216
- package/src/core/readers/manifest_apply_provenance.ts +0 -32
- package/src/core/readers/manifest_export.ts +0 -81
- package/src/core/readers/manipulation_context.ts +0 -475
- package/src/core/readers/map_layers.ts +0 -49
- package/src/core/readers/metadata_rows.ts +0 -56
- package/src/core/readers/object_state.ts +0 -124
- package/src/core/readers/observer_knowledge.ts +0 -41
- package/src/core/readers/observer_place_knowledge.ts +0 -37
- package/src/core/readers/observer_trace_knowledge.ts +0 -45
- package/src/core/readers/outcome_template.ts +0 -41
- package/src/core/readers/place_topology.ts +0 -109
- package/src/core/readers/reaction_options.ts +0 -156
- package/src/core/readers/resource_deltas.ts +0 -47
- package/src/core/readers/scene.ts +0 -275
- package/src/core/readers/seats.ts +0 -33
- package/src/core/readers/self.ts +0 -245
- package/src/core/readers/self_capabilities.ts +0 -159
- package/src/core/readers/self_economy.ts +0 -101
- package/src/core/readers/self_economy_budget.ts +0 -93
- package/src/core/readers/self_evaluations.ts +0 -128
- package/src/core/readers/self_identity.ts +0 -104
- package/src/core/readers/sense_context.ts +0 -112
- package/src/core/readers/session.ts +0 -207
- package/src/core/readers/session_detail.ts +0 -211
- package/src/core/readers/session_status.ts +0 -68
- package/src/core/readers/spatial_environment_state.ts +0 -74
- package/src/core/readers/spatial_niche_attachments.ts +0 -28
- package/src/core/readers/substrate_definitions.ts +0 -27
- package/src/core/readers/suggest_next_action.ts +0 -72
- package/src/core/readers/surface_membership.ts +0 -78
- package/src/core/readers/tag_reads.ts +0 -54
- package/src/core/readers/trace_query.ts +0 -120
- package/src/core/readers/trace_response.ts +0 -80
- package/src/core/readers/traces.ts +0 -124
- package/src/core/readers/travel_session.ts +0 -88
- package/src/core/readers/turn_state.ts +0 -34
- package/src/core/readers/world_events.ts +0 -43
- package/src/core/readers/world_status.ts +0 -63
- package/src/core/reducers/manipulation_args.ts +0 -239
- package/src/core/reducers/manipulation_receipt.ts +0 -66
- package/src/core/reducers/r_actor_wake_up.ts +0 -32
- package/src/core/reducers/r_inscribe_trace.ts +0 -109
- package/src/core/reducers/r_manipulate.ts +0 -163
- package/src/core/reducers/r_move.ts +0 -155
- package/src/core/reducers/r_react.ts +0 -143
- package/src/core/reducers/r_release_claim.ts +0 -81
- package/src/core/reducers/r_sense.ts +0 -84
- package/src/core/reducers/r_session_close.ts +0 -130
- package/src/core/reducers/r_session_move.ts +0 -116
- package/src/core/reducers/r_session_open.ts +0 -91
- package/src/core/reducers/session_lookup.ts +0 -64
- package/src/core/reducers/tick.ts +0 -65
- package/src/core/reducers/trace_lookup.ts +0 -29
- package/src/core/reducers/transport.ts +0 -84
- package/src/core/resolve.ts +0 -228
- package/src/core/shape_telemetry.ts +0 -146
- package/src/core/snapshot_rows.ts +0 -109
- package/src/core/tick_cadence.ts +0 -61
- package/src/core/types.ts +0 -501
- package/src/core/watch_provenance.ts +0 -113
- package/src/core/world-contract/classify.ts +0 -38
- package/src/core/world-contract/index.ts +0 -12
- package/src/core/world-contract/normalise.ts +0 -574
- package/src/core/world-contract/runtime.ts +0 -144
- package/src/core/world-contract/served.ts +0 -173
- package/src/core/world-contract/strict-reducers.ts +0 -14
- package/src/core/world-contract/typetext.ts +0 -94
- package/src/core/world_time.ts +0 -22
- package/src/index.ts +0 -262
- package/src/manifest-apply.ts +0 -497
- package/src/provenance.ts +0 -568
- package/src/reader-manifest.ts +0 -338
- package/src/readers.ts +0 -392
- package/src/replay.ts +0 -515
- package/src/watch-buffer.ts +0 -438
- package/src/world-events/builder.ts +0 -1042
package/src/provenance.ts
DELETED
|
@@ -1,568 +0,0 @@
|
|
|
1
|
-
// Read-first SDK reader surface for evaluation_provenance rows.
|
|
2
|
-
//
|
|
3
|
-
// Reads from the live SpacetimeDB subscription cache. Never calls reducers.
|
|
4
|
-
// Sorted ascending by createdAtTick (chronological) since provenanceId is a
|
|
5
|
-
// string key not suitable for numeric ordering.
|
|
6
|
-
//
|
|
7
|
-
// iter() output is camelCase per the generated bindings; no snake_case fallback.
|
|
8
|
-
|
|
9
|
-
import type { EvaluationProvenanceRow } from "./binding_rows";
|
|
10
|
-
import type { ProvenanceRingBuffer } from "./core/provenance_buffer";
|
|
11
|
-
import type { TickIntervalEstimator } from "./core/tick_cadence";
|
|
12
|
-
import { currentWorldTickOrZero } from "./core/world_time";
|
|
13
|
-
import { type RequiredTables, registerReaderManifest, type SnapshotDb } from "./reader-manifest";
|
|
14
|
-
|
|
15
|
-
export const requiredTables: RequiredTables<["visible_evaluation_provenance"]> = [
|
|
16
|
-
"visible_evaluation_provenance",
|
|
17
|
-
];
|
|
18
|
-
registerReaderManifest({ requiredTables });
|
|
19
|
-
|
|
20
|
-
export interface ReducerAttemptResult<T> {
|
|
21
|
-
status:
|
|
22
|
-
| "success"
|
|
23
|
-
| "rejected"
|
|
24
|
-
| "unobserved_timeout"
|
|
25
|
-
| "unobserved_no_provenance"
|
|
26
|
-
| "unobservable";
|
|
27
|
-
snapshot: T | null;
|
|
28
|
-
provenance: ProvenanceRow | null;
|
|
29
|
-
lagWarning: boolean;
|
|
30
|
-
observedAtTick: bigint;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface ReducerAttemptTelemetrySpan {
|
|
34
|
-
addEvent(name: string, attributes?: Record<string, unknown>): void;
|
|
35
|
-
end(status?: "unset" | "ok" | "error"): void;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Structural telemetry port: hosts may supply OpenTelemetry without making the
|
|
39
|
-
* browser-safe SDK depend on one concrete OTel implementation. */
|
|
40
|
-
export interface ReducerAttemptTelemetry {
|
|
41
|
-
startSpan(name: string, attributes?: Record<string, unknown>): ReducerAttemptTelemetrySpan;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** Host-supplied reducer context admitted to shared telemetry. This list must
|
|
45
|
-
* equal `WORLD_ACTOR_CORRELATION_ATTRIBUTE_KEYS` in
|
|
46
|
-
* `@spellkave/agent-observability` (from which the exporter allowlist is
|
|
47
|
-
* derived). Enforced by `src/__tests__/reducer-attempt-telemetry-allowlist.test.ts`.
|
|
48
|
-
* Arbitrary host objects and content-bearing values are deliberately not accepted. */
|
|
49
|
-
export const REDUCER_ATTEMPT_SAFE_TELEMETRY_ATTRIBUTES = [
|
|
50
|
-
"spellkave.reducer",
|
|
51
|
-
"spellkave.actor_id",
|
|
52
|
-
"spellkave.action_id",
|
|
53
|
-
"spellkave.target_ref",
|
|
54
|
-
"spellkave.correlation_id",
|
|
55
|
-
"spellkave.world_slug",
|
|
56
|
-
"spellkave.cause_kind",
|
|
57
|
-
"spellkave.cause_id",
|
|
58
|
-
] as const;
|
|
59
|
-
|
|
60
|
-
export type ReducerAttemptSafeTelemetryAttribute =
|
|
61
|
-
(typeof REDUCER_ATTEMPT_SAFE_TELEMETRY_ATTRIBUTES)[number];
|
|
62
|
-
export type ReducerAttemptTelemetryAttributes = Partial<
|
|
63
|
-
Record<ReducerAttemptSafeTelemetryAttribute, string | number | boolean>
|
|
64
|
-
>;
|
|
65
|
-
|
|
66
|
-
const MAX_TELEMETRY_STRING_LENGTH = 256;
|
|
67
|
-
|
|
68
|
-
export function safeReducerAttemptTelemetryAttributes(
|
|
69
|
-
value: Readonly<Record<string, unknown>> | undefined,
|
|
70
|
-
): ReducerAttemptTelemetryAttributes {
|
|
71
|
-
if (value === undefined) return {};
|
|
72
|
-
const safe: ReducerAttemptTelemetryAttributes = {};
|
|
73
|
-
for (const key of REDUCER_ATTEMPT_SAFE_TELEMETRY_ATTRIBUTES) {
|
|
74
|
-
const candidate = value[key];
|
|
75
|
-
if (typeof candidate === "string") safe[key] = candidate.slice(0, MAX_TELEMETRY_STRING_LENGTH);
|
|
76
|
-
else if (typeof candidate === "boolean") safe[key] = candidate;
|
|
77
|
-
else if (typeof candidate === "number" && Number.isFinite(candidate)) safe[key] = candidate;
|
|
78
|
-
}
|
|
79
|
-
return safe;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export interface ObserveReducerAttemptOpts<T> {
|
|
83
|
-
db: () => SnapshotDb;
|
|
84
|
-
subjectId: string;
|
|
85
|
-
invoke: () => Promise<void>;
|
|
86
|
-
successPredicate: (db: SnapshotDb) => boolean;
|
|
87
|
-
collectSnapshot: (db: SnapshotDb) => T | null;
|
|
88
|
-
timeoutMs: number;
|
|
89
|
-
pollMs: number;
|
|
90
|
-
tickEstimator?: TickIntervalEstimator;
|
|
91
|
-
/** Treat a post-baseline successful provenance row as success even without a state predicate. */
|
|
92
|
-
successOnProvenance?: boolean;
|
|
93
|
-
/** Optional: "this attempt has reached a terminal outcome that is NOT
|
|
94
|
-
* success, stop waiting". Returning true leaves the observation loop immediately;
|
|
95
|
-
* the normal post-loop classification then runs, and the CALLER decides
|
|
96
|
-
* what the outcome means.
|
|
97
|
-
*
|
|
98
|
-
* WHY (feat/travel-eta, 2026-08-18). `r_move` promotes an over-reach move
|
|
99
|
-
* into a session that walks the actor one step per world tick, so the
|
|
100
|
-
* success predicate ("actor is at the destination") cannot come true for
|
|
101
|
-
* many ticks — every long journey burned the FULL `timeoutMs` before being
|
|
102
|
-
* reported, and reported as a non-arrival at that. With 17 journeys in one
|
|
103
|
-
* recording that was ~34s of waiting for an answer the world had settled
|
|
104
|
-
* on immediately. The move wrapper passes "is a travel session open for
|
|
105
|
-
* this actor" here and turns the early exit into `status: "travelling"`. */
|
|
106
|
-
// The second argument lets receipt observers wait for the invoke acknowledgement
|
|
107
|
-
// before classifying a settled call as unobservable.
|
|
108
|
-
settledEarly?: (db: SnapshotDb, invokeSettled: boolean) => boolean;
|
|
109
|
-
provenanceBuffer?: ProvenanceRingBuffer;
|
|
110
|
-
/** Attribute only rows emitted by this reducer. Subject and baseline alone
|
|
111
|
-
* cannot distinguish its verdict from ambient or other-action evaluations. */
|
|
112
|
-
provenancePredicate?: (row: ProvenanceRow) => boolean;
|
|
113
|
-
telemetry?: ReducerAttemptTelemetry;
|
|
114
|
-
/** Safe, low-cardinality reducer context; never include credentials or raw args. */
|
|
115
|
-
telemetryAttributes?: ReducerAttemptTelemetryAttributes;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/** Wake on the asserting cache's delivered mutations or the reducer result.
|
|
119
|
-
* Snapshot-only hosts keep their polling fallback. Never add subscriptions. */
|
|
120
|
-
function attemptWakeups(snapshot: SnapshotDb) {
|
|
121
|
-
let revision = 0;
|
|
122
|
-
let pending: (() => void) | undefined;
|
|
123
|
-
const notify = () => {
|
|
124
|
-
revision++;
|
|
125
|
-
pending?.();
|
|
126
|
-
};
|
|
127
|
-
const detach: (() => void)[] = [];
|
|
128
|
-
const tables = [...new Set(Object.values(snapshot).filter((table) => table !== undefined))];
|
|
129
|
-
const eventDriven =
|
|
130
|
-
tables.length > 0 &&
|
|
131
|
-
tables.every(
|
|
132
|
-
(table) =>
|
|
133
|
-
table.onInsert &&
|
|
134
|
-
table.removeOnInsert &&
|
|
135
|
-
table.onDelete &&
|
|
136
|
-
table.removeOnDelete &&
|
|
137
|
-
(!table.onUpdate || table.removeOnUpdate),
|
|
138
|
-
);
|
|
139
|
-
if (eventDriven)
|
|
140
|
-
for (const table of tables) {
|
|
141
|
-
for (const [add, remove] of [
|
|
142
|
-
[table.onInsert, table.removeOnInsert],
|
|
143
|
-
[table.onUpdate, table.removeOnUpdate],
|
|
144
|
-
[table.onDelete, table.removeOnDelete],
|
|
145
|
-
] as const) {
|
|
146
|
-
if (add && remove) {
|
|
147
|
-
add.call(table, notify);
|
|
148
|
-
detach.push(() => remove.call(table, notify));
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return {
|
|
153
|
-
notify,
|
|
154
|
-
get revision() {
|
|
155
|
-
return revision;
|
|
156
|
-
},
|
|
157
|
-
wait(seen: number, remaining: number, pollMs: number): Promise<void> {
|
|
158
|
-
if (seen !== revision) return Promise.resolve();
|
|
159
|
-
return new Promise((resolve) => {
|
|
160
|
-
const finish = () => {
|
|
161
|
-
clearTimeout(timer);
|
|
162
|
-
if (pending === finish) pending = undefined;
|
|
163
|
-
resolve();
|
|
164
|
-
};
|
|
165
|
-
const timer = setTimeout(
|
|
166
|
-
finish,
|
|
167
|
-
Math.max(0, eventDriven ? remaining : Math.min(pollMs, remaining)),
|
|
168
|
-
);
|
|
169
|
-
pending = finish;
|
|
170
|
-
if (seen !== revision) finish();
|
|
171
|
-
});
|
|
172
|
-
},
|
|
173
|
-
close() {
|
|
174
|
-
for (const remove of detach) remove();
|
|
175
|
-
pending?.();
|
|
176
|
-
},
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Generic reducer-attempt observer. Captures a provenance baseline before
|
|
182
|
-
* invoke(), observes cache/result callbacks until successPredicate is satisfied, and returns a
|
|
183
|
-
* structured result with the outcome and nearest provenance row.
|
|
184
|
-
*
|
|
185
|
-
* Contains ZERO argument validation — caller payload goes 1:1 to invoke().
|
|
186
|
-
*/
|
|
187
|
-
export async function observeReducerAttempt<T>(
|
|
188
|
-
opts: ObserveReducerAttemptOpts<T>,
|
|
189
|
-
): Promise<ReducerAttemptResult<T>> {
|
|
190
|
-
const {
|
|
191
|
-
db,
|
|
192
|
-
subjectId,
|
|
193
|
-
invoke,
|
|
194
|
-
successPredicate,
|
|
195
|
-
collectSnapshot,
|
|
196
|
-
timeoutMs,
|
|
197
|
-
pollMs,
|
|
198
|
-
tickEstimator,
|
|
199
|
-
successOnProvenance,
|
|
200
|
-
settledEarly,
|
|
201
|
-
provenanceBuffer,
|
|
202
|
-
provenancePredicate,
|
|
203
|
-
telemetry,
|
|
204
|
-
telemetryAttributes,
|
|
205
|
-
} = opts;
|
|
206
|
-
|
|
207
|
-
// Baseline only the subject's own rows. Both later reads filter by
|
|
208
|
-
// subjectId, so unrelated row IDs would never be matched against the
|
|
209
|
-
// baseline — keeping them just inflates the Set for no benefit.
|
|
210
|
-
function readAttemptProvenance(excludeIds?: ReadonlySet<string>): ProvenanceRow[] {
|
|
211
|
-
const rows = readRecentProvenance(db(), { subjectId, excludeIds }, provenanceBuffer);
|
|
212
|
-
return provenancePredicate ? rows.filter(provenancePredicate) : rows;
|
|
213
|
-
}
|
|
214
|
-
const baselineIds = new Set(readAttemptProvenance().map((row) => row.id));
|
|
215
|
-
let span: ReducerAttemptTelemetrySpan | undefined;
|
|
216
|
-
try {
|
|
217
|
-
span = telemetry?.startSpan("spellkave.reducer_attempt", {
|
|
218
|
-
"spellkave.subject_id": subjectId,
|
|
219
|
-
"spellkave.timeout_ms": timeoutMs,
|
|
220
|
-
"spellkave.poll_ms": pollMs,
|
|
221
|
-
"spellkave.success_on_provenance": successOnProvenance === true,
|
|
222
|
-
...safeReducerAttemptTelemetryAttributes(telemetryAttributes),
|
|
223
|
-
});
|
|
224
|
-
} catch {
|
|
225
|
-
// Observability is optional and must never change a reducer outcome.
|
|
226
|
-
}
|
|
227
|
-
function addSpanEvent(name: string, attributes?: Record<string, unknown>): void {
|
|
228
|
-
try {
|
|
229
|
-
span?.addEvent(name, attributes);
|
|
230
|
-
} catch {
|
|
231
|
-
// A failing projection loses only its own diagnostic event.
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
function endSpan(status: "ok" | "error"): void {
|
|
235
|
-
try {
|
|
236
|
-
span?.end(status);
|
|
237
|
-
} catch {
|
|
238
|
-
// A failing projection never changes the authoritative result.
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
addSpanEvent("baseline_captured", { "spellkave.baseline_count": baselineIds.size });
|
|
242
|
-
let invokeFailed = false;
|
|
243
|
-
let invokeSettled = false;
|
|
244
|
-
let pollCount = 0;
|
|
245
|
-
let lastObservedProvenanceId: string | undefined;
|
|
246
|
-
|
|
247
|
-
function recordProvenance(row: ProvenanceRow | null): void {
|
|
248
|
-
if (row === null || row.id === lastObservedProvenanceId) return;
|
|
249
|
-
lastObservedProvenanceId = row.id;
|
|
250
|
-
addSpanEvent("provenance_observed", {
|
|
251
|
-
"spellkave.provenance_id": row.id,
|
|
252
|
-
"spellkave.provenance_status": row.status,
|
|
253
|
-
"spellkave.provenance_kind": row.kind,
|
|
254
|
-
...(row.failure_kind === ""
|
|
255
|
-
? {}
|
|
256
|
-
: { "spellkave.failure_class": row.failure_kind.slice(0, MAX_TELEMETRY_STRING_LENGTH) }),
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
function complete(result: ReducerAttemptResult<T>): ReducerAttemptResult<T> {
|
|
261
|
-
recordProvenance(result.provenance);
|
|
262
|
-
addSpanEvent("classified", {
|
|
263
|
-
"spellkave.result_status": result.status,
|
|
264
|
-
"spellkave.poll_count": pollCount,
|
|
265
|
-
"spellkave.invoke_settled": invokeSettled,
|
|
266
|
-
"spellkave.invoke_failed": invokeFailed,
|
|
267
|
-
"spellkave.lag_warning": result.lagWarning,
|
|
268
|
-
});
|
|
269
|
-
if (
|
|
270
|
-
result.status !== "success" &&
|
|
271
|
-
result.provenance &&
|
|
272
|
-
isSuccessStatus(result.provenance.status)
|
|
273
|
-
) {
|
|
274
|
-
addSpanEvent("classification_mismatch", {
|
|
275
|
-
"spellkave.result_status": result.status,
|
|
276
|
-
"spellkave.provenance_status": result.provenance.status,
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
endSpan(result.status === "success" ? "ok" : "error");
|
|
280
|
-
return result;
|
|
281
|
-
}
|
|
282
|
-
const wakeups = attemptWakeups(db());
|
|
283
|
-
try {
|
|
284
|
-
// `Promise.resolve().then(invoke)` shields against `invoke()` that throws
|
|
285
|
-
// synchronously instead of returning a rejected Promise — either path now
|
|
286
|
-
// lands in the reject handler and surfaces as `invokeFailed = true`.
|
|
287
|
-
void Promise.resolve()
|
|
288
|
-
.then(() => {
|
|
289
|
-
addSpanEvent("reducer_invoked");
|
|
290
|
-
return invoke();
|
|
291
|
-
})
|
|
292
|
-
.catch(() => {
|
|
293
|
-
invokeFailed = true;
|
|
294
|
-
})
|
|
295
|
-
.finally(() => {
|
|
296
|
-
invokeSettled = true;
|
|
297
|
-
wakeups.notify();
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
const endAt = Date.now() + timeoutMs;
|
|
301
|
-
while (Date.now() <= endAt) {
|
|
302
|
-
const seen = wakeups.revision;
|
|
303
|
-
pollCount += 1;
|
|
304
|
-
if (invokeFailed) {
|
|
305
|
-
const rows = readAttemptProvenance(baselineIds);
|
|
306
|
-
return complete({
|
|
307
|
-
status: "rejected",
|
|
308
|
-
snapshot: collectSnapshot(db()),
|
|
309
|
-
provenance: rows[rows.length - 1] ?? null,
|
|
310
|
-
lagWarning: false,
|
|
311
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
312
|
-
});
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const rows = readAttemptProvenance(baselineIds);
|
|
316
|
-
const latest = rows[rows.length - 1] ?? null;
|
|
317
|
-
recordProvenance(latest);
|
|
318
|
-
if (latest && isFailureStatus(latest.status)) {
|
|
319
|
-
return complete({
|
|
320
|
-
status: "rejected",
|
|
321
|
-
snapshot: collectSnapshot(db()),
|
|
322
|
-
provenance: latest,
|
|
323
|
-
lagWarning: false,
|
|
324
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
if (successPredicate(db())) {
|
|
329
|
-
return complete({
|
|
330
|
-
status: "success",
|
|
331
|
-
snapshot: collectSnapshot(db()),
|
|
332
|
-
provenance: latest,
|
|
333
|
-
lagWarning: false,
|
|
334
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
335
|
-
});
|
|
336
|
-
}
|
|
337
|
-
if (successOnProvenance === true && latest && isSuccessStatus(latest.status)) {
|
|
338
|
-
return complete({
|
|
339
|
-
status: "success",
|
|
340
|
-
snapshot: collectSnapshot(db()),
|
|
341
|
-
provenance: latest,
|
|
342
|
-
lagWarning: false,
|
|
343
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
// Checked LAST, after every success path: an outcome that could still
|
|
347
|
-
// resolve to success must be given that chance first. Only once this
|
|
348
|
-
// check has failed to see success do we ask whether the world has
|
|
349
|
-
// nonetheless settled on something terminal.
|
|
350
|
-
if (settledEarly?.(db(), invokeSettled) === true) {
|
|
351
|
-
addSpanEvent("settled_early");
|
|
352
|
-
break;
|
|
353
|
-
}
|
|
354
|
-
if (Date.now() >= endAt) break;
|
|
355
|
-
await wakeups.wait(seen, endAt - Date.now(), pollMs);
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
// Post-loop classification follows main's contract:
|
|
359
|
-
// - `unobserved_timeout` ≡ the reducer call did not settle before the
|
|
360
|
-
// deadline (caller should retry / wait longer).
|
|
361
|
-
// - `unobservable` ≡ the reducer call returned, but no provenance rows were
|
|
362
|
-
// visible to this identity within the observation window.
|
|
363
|
-
// - `unobserved_no_provenance` ≡ rows arrived but none reached a
|
|
364
|
-
// success/failure status (caller has signal but not resolution).
|
|
365
|
-
// A `Failed`/`RolledBack` row is already caught inside the loop via
|
|
366
|
-
// `isFailureStatus`; if execution reaches here there is no terminal row.
|
|
367
|
-
const rows = readAttemptProvenance(baselineIds);
|
|
368
|
-
const latest = rows[rows.length - 1] ?? null;
|
|
369
|
-
recordProvenance(latest);
|
|
370
|
-
if (latest && isFailureStatus(latest.status)) {
|
|
371
|
-
return complete({
|
|
372
|
-
status: "rejected",
|
|
373
|
-
snapshot: collectSnapshot(db()),
|
|
374
|
-
provenance: latest,
|
|
375
|
-
lagWarning: false,
|
|
376
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
if (successOnProvenance === true && latest && isSuccessStatus(latest.status)) {
|
|
380
|
-
return complete({
|
|
381
|
-
status: "success",
|
|
382
|
-
snapshot: collectSnapshot(db()),
|
|
383
|
-
provenance: latest,
|
|
384
|
-
lagWarning: false,
|
|
385
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
const lagWarning = computeLagWarning(tickEstimator);
|
|
389
|
-
return complete({
|
|
390
|
-
status:
|
|
391
|
-
rows.length > 0
|
|
392
|
-
? "unobserved_no_provenance"
|
|
393
|
-
: invokeSettled
|
|
394
|
-
? "unobservable"
|
|
395
|
-
: "unobserved_timeout",
|
|
396
|
-
snapshot: collectSnapshot(db()),
|
|
397
|
-
provenance: latest,
|
|
398
|
-
lagWarning,
|
|
399
|
-
observedAtTick: currentWorldTickOrZero(db()),
|
|
400
|
-
});
|
|
401
|
-
} finally {
|
|
402
|
-
wakeups.close();
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// Canonical PascalCase variants come from the generated binding for
|
|
407
|
-
// `EvaluationProvenanceStatus` (Started | Succeeded | Failed | RolledBack).
|
|
408
|
-
// The lowercase compare is defensive against any future runtime that
|
|
409
|
-
// serialises the tag in a different case; if `Started` ever needs
|
|
410
|
-
// separate handling, lift it into a third branch instead of folding it
|
|
411
|
-
// here.
|
|
412
|
-
function isFailureStatus(status: string): boolean {
|
|
413
|
-
const normalised = status.toLowerCase();
|
|
414
|
-
return normalised === "failed" || normalised === "failure" || normalised === "rolledback";
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
function isSuccessStatus(status: string): boolean {
|
|
418
|
-
const normalised = status.toLowerCase();
|
|
419
|
-
return normalised === "succeeded" || normalised === "success";
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
function computeLagWarning(estimator: TickIntervalEstimator | undefined): boolean {
|
|
423
|
-
if (!estimator) return false;
|
|
424
|
-
const lastMs = estimator.lastObservedAtMs();
|
|
425
|
-
if (lastMs === null) return false;
|
|
426
|
-
return Date.now() - lastMs > 2 * estimator.estimateMs();
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
export interface ProvenanceRow {
|
|
430
|
-
id: string;
|
|
431
|
-
provenance_id?: string;
|
|
432
|
-
kind: string;
|
|
433
|
-
status: string;
|
|
434
|
-
subject_id: string;
|
|
435
|
-
failure_kind: string;
|
|
436
|
-
failure_detail: string;
|
|
437
|
-
selected_template_ids: string[];
|
|
438
|
-
created_at_tick: bigint;
|
|
439
|
-
bundle_id: string;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
export interface ProvenanceWatermark {
|
|
443
|
-
created_at_tick: bigint;
|
|
444
|
-
id: string;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
function tagString(v: unknown): string {
|
|
448
|
-
if (typeof v === "string") return v;
|
|
449
|
-
// SpacetimeDB tagged-enum shape: { tag: "VariantName", value?: ... }
|
|
450
|
-
if (v && typeof v === "object") {
|
|
451
|
-
const tag = (v as { tag?: unknown }).tag;
|
|
452
|
-
if (typeof tag === "string") return tag;
|
|
453
|
-
}
|
|
454
|
-
return String(v ?? "");
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
function toRow(r: EvaluationProvenanceRow): ProvenanceRow {
|
|
458
|
-
const arr = (v: unknown): string[] => {
|
|
459
|
-
if (!Array.isArray(v)) return [];
|
|
460
|
-
return v.map((x) => String(x));
|
|
461
|
-
};
|
|
462
|
-
return {
|
|
463
|
-
id: r.provenanceId,
|
|
464
|
-
provenance_id: r.provenanceId,
|
|
465
|
-
kind: tagString(r.kind),
|
|
466
|
-
status: tagString(r.status),
|
|
467
|
-
subject_id: r.subjectId,
|
|
468
|
-
failure_kind: r.failureKind,
|
|
469
|
-
failure_detail: r.failureDetail,
|
|
470
|
-
selected_template_ids: arr(r.selectedTemplateIds),
|
|
471
|
-
created_at_tick: r.createdAtTick,
|
|
472
|
-
bundle_id: r.bundleId,
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
function iterRows(db: SnapshotDb): ProvenanceRow[] {
|
|
477
|
-
const handle =
|
|
478
|
-
db.visible_evaluation_provenance ?? db.visibleEvaluationProvenance ?? db.evaluation_provenance;
|
|
479
|
-
if (!handle) return [];
|
|
480
|
-
const rows: ProvenanceRow[] = [];
|
|
481
|
-
for (const raw of handle.iter()) {
|
|
482
|
-
rows.push(toRow(raw as unknown as EvaluationProvenanceRow));
|
|
483
|
-
}
|
|
484
|
-
return rows;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
/**
|
|
488
|
-
* Returns the latest provenance row watermark in the cache, or null if empty.
|
|
489
|
-
* When `buffer` is provided, scans the ring buffer instead of iterating the
|
|
490
|
-
* full DB cache (O(buffer-cap) rather than O(all cached rows)).
|
|
491
|
-
*/
|
|
492
|
-
export function maxProvenanceWatermark(
|
|
493
|
-
db: SnapshotDb,
|
|
494
|
-
buffer?: ProvenanceRingBuffer,
|
|
495
|
-
): ProvenanceWatermark | null {
|
|
496
|
-
if (buffer) return buffer.latestWatermark();
|
|
497
|
-
let max: ProvenanceWatermark | null = null;
|
|
498
|
-
for (const row of iterRows(db)) {
|
|
499
|
-
const watermark = { created_at_tick: row.created_at_tick, id: row.id };
|
|
500
|
-
if (!max || compareWatermark(watermark, max) > 0) max = watermark;
|
|
501
|
-
}
|
|
502
|
-
return max;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
export interface ReadRecentProvenanceOpts {
|
|
506
|
-
/** Filter to rows whose subject_id matches. */
|
|
507
|
-
subjectId?: string;
|
|
508
|
-
/** Return only rows newer than this createdAtTick/id watermark. */
|
|
509
|
-
since?: ProvenanceWatermark | null;
|
|
510
|
-
/** Exclude exact row IDs already known to the caller. */
|
|
511
|
-
excludeIds?: ReadonlySet<string>;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
/**
|
|
515
|
-
* Returns evaluation_provenance rows sorted ascending by createdAtTick.
|
|
516
|
-
* When `buffer` is provided, scans the ring buffer (O(buffer-cap)).
|
|
517
|
-
* Without buffer, iterates the full DB cache.
|
|
518
|
-
*/
|
|
519
|
-
export function readRecentProvenance(
|
|
520
|
-
db: SnapshotDb,
|
|
521
|
-
opts: ReadRecentProvenanceOpts = {},
|
|
522
|
-
buffer?: ProvenanceRingBuffer,
|
|
523
|
-
): ProvenanceRow[] {
|
|
524
|
-
let rows = buffer
|
|
525
|
-
? opts.subjectId !== undefined
|
|
526
|
-
? buffer.forSubject(opts.subjectId)
|
|
527
|
-
: allBufferRows(buffer)
|
|
528
|
-
: iterRows(db);
|
|
529
|
-
|
|
530
|
-
if (opts.since !== undefined && opts.since !== null) {
|
|
531
|
-
const baseline = opts.since;
|
|
532
|
-
rows = rows.filter(
|
|
533
|
-
(r) => compareWatermark({ created_at_tick: r.created_at_tick, id: r.id }, baseline) > 0,
|
|
534
|
-
);
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
if (opts.excludeIds !== undefined) {
|
|
538
|
-
const excluded = opts.excludeIds;
|
|
539
|
-
rows = rows.filter((r) => !excluded.has(r.id));
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
if (opts.subjectId !== undefined) {
|
|
543
|
-
const subjectId = opts.subjectId;
|
|
544
|
-
rows = rows.filter((r) => r.subject_id === subjectId);
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
rows.sort((a, b) => {
|
|
548
|
-
if (a.created_at_tick < b.created_at_tick) return -1;
|
|
549
|
-
if (a.created_at_tick > b.created_at_tick) return 1;
|
|
550
|
-
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
551
|
-
});
|
|
552
|
-
|
|
553
|
-
return rows;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
function allBufferRows(buffer: ProvenanceRingBuffer): ProvenanceRow[] {
|
|
557
|
-
const result: ProvenanceRow[] = [];
|
|
558
|
-
for (const subjectId of buffer.subjectIds()) {
|
|
559
|
-
result.push(...buffer.forSubject(subjectId));
|
|
560
|
-
}
|
|
561
|
-
return result;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
function compareWatermark(a: ProvenanceWatermark, b: ProvenanceWatermark): number {
|
|
565
|
-
if (a.created_at_tick < b.created_at_tick) return -1;
|
|
566
|
-
if (a.created_at_tick > b.created_at_tick) return 1;
|
|
567
|
-
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
568
|
-
}
|