evalution 2.0.0 → 2.0.1
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 +11 -11
- package/dist/{check-ci7RhMcB.d.ts → check-BKU5_IhU.d.ts} +7 -2
- package/dist/checks/index.d.ts +1 -1
- package/dist/cli/index.js +622 -336
- package/dist/client/assets/{DatasetView-BqSWI_pm.js → DatasetView-DZ2uLHKV.js} +12 -10
- package/dist/client/assets/{EvalRunView-CR6ZksSu.js → EvalRunView-T610dLVw.js} +1 -1
- package/dist/client/assets/{EvalView-JPEM5IY8.js → EvalView-Cae68vPB.js} +1 -1
- package/dist/client/assets/{data-grid-overlay-editor-B_nPhXKR.js → data-grid-overlay-editor-PtH7A6E4.js} +1 -1
- package/dist/client/assets/{highlighted-body-KPVGNVTW-dPpneB8R.js → highlighted-body-KPVGNVTW-CPtwvSJb.js} +1 -1
- package/dist/client/assets/{index-CwjMcK6S.js → index-BFH07Ynk.js} +147 -147
- package/dist/client/assets/index-KCv8AeiY.css +32 -0
- package/dist/client/assets/{number-overlay-editor-CRWFlaQs.js → number-overlay-editor-BbQhagHP.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/cost-fetching-trace-sink-Dz8gniQ6.js +262 -0
- package/dist/{dataset-types-8cDpOFYi.d.ts → dataset-types-D-Fsbg8B.d.ts} +5 -0
- package/dist/index.d.ts +517 -121
- package/dist/index.js +29 -10
- package/dist/ingest.d.ts +119 -0
- package/dist/ingest.js +3 -0
- package/dist/{trace-event-ingestor-DwI1hxGX.js → local-database-trace-provider-87-WGqfS.js} +1795 -1086
- package/dist/{trace-BlnjMp7o.d.ts → trace-BLjFYF9G.d.ts} +1 -1
- package/dist/trace-event-ingestor-B1DYEg2H.js +798 -0
- package/dist/trace-event-ingestor-JNpe-OrX.d.ts +109 -0
- package/dist/views/datasets/index.d.ts +1 -1
- package/dist/views/index.d.ts +2 -2
- package/dist/views/react/index.d.ts +1 -1
- package/package.json +23 -24
- package/dist/client/assets/index-BGcZZetP.css +0 -32
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { _ as isCheck, m as traceDuration, n as builtinCheck, o as hasCost, p as totalCost, r as builtinCheckInfos } from "./checks-Cq97JU-h.js";
|
|
2
|
+
import { o as mergeSpans } from "./trace-event-ingestor-B1DYEg2H.js";
|
|
2
3
|
import module, { createRequire } from "node:module";
|
|
3
4
|
import path, { dirname, join, resolve } from "node:path";
|
|
4
5
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
-
import fs, { access, constants, glob, mkdir, open, readdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import fs, { access, constants, copyFile, glob, mkdir, open, readdir, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
7
|
import chokidar from "chokidar";
|
|
7
8
|
import { makeRe, minimatch } from "minimatch";
|
|
8
|
-
import fs$1 from "node:fs";
|
|
9
|
+
import fs$1, { constants as constants$1 } from "node:fs";
|
|
9
10
|
import { createHash } from "node:crypto";
|
|
10
11
|
import { SpanStatusCode, isSpanContextValid } from "@opentelemetry/api";
|
|
11
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
12
13
|
import { materializeValue } from "ts-proppy";
|
|
13
|
-
import {
|
|
14
|
-
import protobuf from "protobufjs";
|
|
14
|
+
import { CHECK_ATTRIBUTE, DEPLOYMENT_ENVIRONMENT_ATTRIBUTE, EvalutionApiError, filterTraces, groupTraceSummaries, isCheckSpan, isEmptyTraceQuery } from "@evalution/sdk";
|
|
15
15
|
import { drizzle } from "drizzle-orm/tursodatabase-sync";
|
|
16
16
|
import { connect } from "@tursodatabase/sync";
|
|
17
|
-
import { Worker } from "node:worker_threads";
|
|
18
17
|
import { migrateAsync } from "drizzle-orm/sqlite-core/async/session";
|
|
18
|
+
import { Worker } from "node:worker_threads";
|
|
19
19
|
import { and, asc, desc, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
|
20
20
|
import { customType, index, integer, primaryKey, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
21
21
|
//#region src/cli/bundler-resolution-hook.ts
|
|
@@ -1268,7 +1268,7 @@ function locationKey(loc) {
|
|
|
1268
1268
|
return "instance" in loc ? `resource '${loc.instance}'` : inputKey(loc.half, loc.path);
|
|
1269
1269
|
}
|
|
1270
1270
|
/** The input kinds a run can resolve; anything else is refused up front. */
|
|
1271
|
-
const KNOWN_KINDS
|
|
1271
|
+
const KNOWN_KINDS = new Set(Object.keys({
|
|
1272
1272
|
value: true,
|
|
1273
1273
|
object: true,
|
|
1274
1274
|
input: true,
|
|
@@ -1314,7 +1314,7 @@ function findRefs(bindings, unsupported) {
|
|
|
1314
1314
|
});
|
|
1315
1315
|
break;
|
|
1316
1316
|
default:
|
|
1317
|
-
if (!KNOWN_KINDS
|
|
1317
|
+
if (!KNOWN_KINDS.has(node.kind)) unsupported?.push({
|
|
1318
1318
|
at,
|
|
1319
1319
|
kind: node.kind
|
|
1320
1320
|
});
|
|
@@ -2250,7 +2250,7 @@ var EvalRunRefusedError = class extends Error {
|
|
|
2250
2250
|
}
|
|
2251
2251
|
};
|
|
2252
2252
|
/** Resolves after `ms`. */
|
|
2253
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2253
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2254
2254
|
/** Whether `trace` is complete: over, with every span ended. */
|
|
2255
2255
|
function isComplete(trace) {
|
|
2256
2256
|
return !!trace && trace.trace.status !== "running" && trace.spans.every((s) => s.endTime !== void 0);
|
|
@@ -2599,7 +2599,7 @@ var EvalRunner = class {
|
|
|
2599
2599
|
}
|
|
2600
2600
|
try {
|
|
2601
2601
|
const timeoutMs = this.options.rowTimeoutMs ?? 3e5;
|
|
2602
|
-
const stopped = await raceSettled(settled, active.onCancel.then(() => sleep(this.traceWait().timeoutMs)), timeoutMs);
|
|
2602
|
+
const stopped = await raceSettled(settled, active.onCancel.then(() => sleep$1(this.traceWait().timeoutMs)), timeoutMs);
|
|
2603
2603
|
if (stopped) return this.skipped(active, definition, job, stopped === "cancelled" ? "The run was cancelled before this row finished" : `The prompt didn't finish within ${timeoutMs < 1e3 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1e3)}s`}`, "error", traceId);
|
|
2604
2604
|
const { trace, incomplete } = await this.waitForTrace(traceId);
|
|
2605
2605
|
const status = trace.trace.status === "error" ? "error" : "ok";
|
|
@@ -2716,7 +2716,7 @@ var EvalRunner = class {
|
|
|
2716
2716
|
incomplete: false
|
|
2717
2717
|
};
|
|
2718
2718
|
if (Date.now() >= deadline) break;
|
|
2719
|
-
await sleep(intervalMs);
|
|
2719
|
+
await sleep$1(intervalMs);
|
|
2720
2720
|
}
|
|
2721
2721
|
return {
|
|
2722
2722
|
trace: trace ?? {
|
|
@@ -2740,55 +2740,6 @@ function rowResourcesOf(row) {
|
|
|
2740
2740
|
return row.resources && Object.keys(row.resources).length > 0 ? { rowResources: stripReceipts(row.resources) } : {};
|
|
2741
2741
|
}
|
|
2742
2742
|
//#endregion
|
|
2743
|
-
//#region src/shared/helpers.ts
|
|
2744
|
-
function otelOperationToSpanKind(operationName) {
|
|
2745
|
-
switch (operationName) {
|
|
2746
|
-
case "chat":
|
|
2747
|
-
case "response":
|
|
2748
|
-
case "text_completion":
|
|
2749
|
-
case "generate_content":
|
|
2750
|
-
case "evaluate": return "LLM";
|
|
2751
|
-
case "execute_tool": return "TOOL";
|
|
2752
|
-
case "create_agent":
|
|
2753
|
-
case "invoke_agent": return "AGENT";
|
|
2754
|
-
case "embeddings": return "EMBEDDING";
|
|
2755
|
-
default: return "DEFAULT";
|
|
2756
|
-
}
|
|
2757
|
-
}
|
|
2758
|
-
const PROMPT_STYLES = {
|
|
2759
|
-
chat: true,
|
|
2760
|
-
questions: true
|
|
2761
|
-
};
|
|
2762
|
-
/** Whether `value` names a {@link PromptStyle}. */
|
|
2763
|
-
function isPromptStyle(value) {
|
|
2764
|
-
return typeof value === "string" && Object.hasOwn(PROMPT_STYLES, value);
|
|
2765
|
-
}
|
|
2766
|
-
/** Whether a property value can be edited in the UI. */
|
|
2767
|
-
function isEditable(value) {
|
|
2768
|
-
return value.kind !== "raw" && !(value.kind === "functionCall" && !value.binding);
|
|
2769
|
-
}
|
|
2770
|
-
/** Whether `value` is an array of strings with at least one in it. */
|
|
2771
|
-
function isNonEmptyStringArray(value) {
|
|
2772
|
-
return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
|
|
2773
|
-
}
|
|
2774
|
-
/** `text` parsed as JSON, or `undefined` if it isn't valid JSON. */
|
|
2775
|
-
function tryParseJson(text) {
|
|
2776
|
-
if (typeof text !== "string") return void 0;
|
|
2777
|
-
try {
|
|
2778
|
-
return JSON.parse(text);
|
|
2779
|
-
} catch {
|
|
2780
|
-
return;
|
|
2781
|
-
}
|
|
2782
|
-
}
|
|
2783
|
-
/** `v` parsed as JSON if it's a JSON-string, or `v` itself otherwise (not a string, or not valid JSON). */
|
|
2784
|
-
function parseJsonOrRaw(v) {
|
|
2785
|
-
return tryParseJson(v) ?? v;
|
|
2786
|
-
}
|
|
2787
|
-
/** The first seven characters of a version or variation id, past its prefix. */
|
|
2788
|
-
function shortId(id) {
|
|
2789
|
-
return id.replace(/^var_/, "").slice(0, 7);
|
|
2790
|
-
}
|
|
2791
|
-
//#endregion
|
|
2792
2743
|
//#region src/dataset/dataset-provider.ts
|
|
2793
2744
|
/** Thrown by a {@link DatasetProvider} when the dataset named doesn't exist. */
|
|
2794
2745
|
var DatasetNotFoundError = class extends Error {
|
|
@@ -3040,268 +2991,6 @@ var EvalNotFoundError = class extends Error {
|
|
|
3040
2991
|
name = "EvalNotFoundError";
|
|
3041
2992
|
};
|
|
3042
2993
|
//#endregion
|
|
3043
|
-
//#region src/trace/otlp/normalize.ts
|
|
3044
|
-
const HEX_RE = /^[0-9a-f]+$/i;
|
|
3045
|
-
const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
3046
|
-
function base64ToHex(b64) {
|
|
3047
|
-
try {
|
|
3048
|
-
const binary = atob(b64);
|
|
3049
|
-
let hex = "";
|
|
3050
|
-
for (let i = 0; i < binary.length; i++) hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
|
|
3051
|
-
return hex;
|
|
3052
|
-
} catch {
|
|
3053
|
-
return;
|
|
3054
|
-
}
|
|
3055
|
-
}
|
|
3056
|
-
/**
|
|
3057
|
-
* Normalizes a trace/span id that may arrive as hex (already-decoded
|
|
3058
|
-
* protobuf, or a non-conformant JSON sender) or base64 (spec-conformant
|
|
3059
|
-
* OTLP/JSON `bytes` encoding) into lowercase hex. Workers-safe replacement for
|
|
3060
|
-
* Workshop's `normalizeOtelId`, which used `Buffer`.
|
|
3061
|
-
*/
|
|
3062
|
-
function normalizeOtlpId(value, expectedByteLength) {
|
|
3063
|
-
if (!value) return void 0;
|
|
3064
|
-
const trimmed = value.trim();
|
|
3065
|
-
const expectedHexLength = expectedByteLength * 2;
|
|
3066
|
-
if (trimmed.length === expectedHexLength && HEX_RE.test(trimmed)) return trimmed.toLowerCase();
|
|
3067
|
-
if (!BASE64_RE.test(trimmed)) return trimmed;
|
|
3068
|
-
const hex = base64ToHex(trimmed);
|
|
3069
|
-
return hex && hex.length === expectedHexLength ? hex : trimmed;
|
|
3070
|
-
}
|
|
3071
|
-
function anyValueToJs(v) {
|
|
3072
|
-
if (v == null) return void 0;
|
|
3073
|
-
if (v.stringValue !== void 0) return v.stringValue;
|
|
3074
|
-
if (v.boolValue !== void 0) return v.boolValue;
|
|
3075
|
-
if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
|
|
3076
|
-
if (v.doubleValue !== void 0) return v.doubleValue;
|
|
3077
|
-
if (v.bytesValue !== void 0) return v.bytesValue;
|
|
3078
|
-
if (v.arrayValue) return (v.arrayValue.values ?? []).map(anyValueToJs);
|
|
3079
|
-
if (v.kvlistValue) return attributesToRecord(v.kvlistValue.values);
|
|
3080
|
-
}
|
|
3081
|
-
function attributesToRecord(attrs) {
|
|
3082
|
-
const out = {};
|
|
3083
|
-
for (const a of attrs ?? []) {
|
|
3084
|
-
if (!a?.key) continue;
|
|
3085
|
-
out[a.key] = anyValueToJs(a.value);
|
|
3086
|
-
}
|
|
3087
|
-
return out;
|
|
3088
|
-
}
|
|
3089
|
-
function statusCode(code) {
|
|
3090
|
-
if (code === 1) return "ok";
|
|
3091
|
-
if (code === 2) return "error";
|
|
3092
|
-
return "unset";
|
|
3093
|
-
}
|
|
3094
|
-
function nsToMs(nanos) {
|
|
3095
|
-
if (nanos === void 0 || nanos === null || nanos === "0") return 0;
|
|
3096
|
-
return Number(BigInt(nanos) / 1000000n);
|
|
3097
|
-
}
|
|
3098
|
-
function normalizeSpan(s) {
|
|
3099
|
-
const endTimeMs = nsToMs(s.endTimeUnixNano);
|
|
3100
|
-
return {
|
|
3101
|
-
traceId: normalizeOtlpId(s.traceId, 16) ?? s.traceId ?? "",
|
|
3102
|
-
spanId: normalizeOtlpId(s.spanId, 8) ?? s.spanId ?? "",
|
|
3103
|
-
parentSpanId: normalizeOtlpId(s.parentSpanId || void 0, 8),
|
|
3104
|
-
name: s.name ?? "",
|
|
3105
|
-
startTimeMs: nsToMs(s.startTimeUnixNano),
|
|
3106
|
-
endTimeMs: endTimeMs > 0 ? endTimeMs : void 0,
|
|
3107
|
-
statusCode: statusCode(s.status?.code),
|
|
3108
|
-
statusMessage: s.status?.message || void 0,
|
|
3109
|
-
attributes: attributesToRecord(s.attributes),
|
|
3110
|
-
events: s.events && s.events.length > 0 ? s.events.map((e) => ({
|
|
3111
|
-
name: e.name ?? "",
|
|
3112
|
-
timeMs: nsToMs(e.timeUnixNano),
|
|
3113
|
-
attributes: attributesToRecord(e.attributes)
|
|
3114
|
-
})) : void 0
|
|
3115
|
-
};
|
|
3116
|
-
}
|
|
3117
|
-
/**
|
|
3118
|
-
* Flattens an OTLP `ExportTraceServiceRequest` (as decoded by
|
|
3119
|
-
* `decodeOtlpProtobuf`, or `JSON.parse`d directly) into a flat list of
|
|
3120
|
-
* {@link NormalizedOtlpSpan}s, in document order.
|
|
3121
|
-
*/
|
|
3122
|
-
function normalizeOtlpRequest(body) {
|
|
3123
|
-
const spans = [];
|
|
3124
|
-
for (const rs of body?.resourceSpans ?? []) {
|
|
3125
|
-
const resource = attributesToRecord(rs.resource?.attributes);
|
|
3126
|
-
const hasResource = Object.keys(resource).length > 0;
|
|
3127
|
-
for (const ss of rs.scopeSpans ?? []) for (const s of ss.spans ?? []) {
|
|
3128
|
-
const span = normalizeSpan(s);
|
|
3129
|
-
spans.push(hasResource ? {
|
|
3130
|
-
...span,
|
|
3131
|
-
resource
|
|
3132
|
-
} : span);
|
|
3133
|
-
}
|
|
3134
|
-
}
|
|
3135
|
-
return spans;
|
|
3136
|
-
}
|
|
3137
|
-
//#endregion
|
|
3138
|
-
//#region src/trace/otlp/otlp-protobuf.ts
|
|
3139
|
-
const ExportTraceServiceRequest = protobuf.parse(`
|
|
3140
|
-
syntax = "proto3";
|
|
3141
|
-
package otlp;
|
|
3142
|
-
|
|
3143
|
-
message AnyValue {
|
|
3144
|
-
oneof value {
|
|
3145
|
-
string string_value = 1;
|
|
3146
|
-
bool bool_value = 2;
|
|
3147
|
-
int64 int_value = 3;
|
|
3148
|
-
double double_value = 4;
|
|
3149
|
-
ArrayValue array_value = 5;
|
|
3150
|
-
KeyValueList kvlist_value = 6;
|
|
3151
|
-
bytes bytes_value = 7;
|
|
3152
|
-
}
|
|
3153
|
-
}
|
|
3154
|
-
message ArrayValue { repeated AnyValue values = 1; }
|
|
3155
|
-
message KeyValueList { repeated KeyValue values = 1; }
|
|
3156
|
-
message KeyValue { string key = 1; AnyValue value = 2; }
|
|
3157
|
-
message InstrumentationScope {
|
|
3158
|
-
string name = 1;
|
|
3159
|
-
string version = 2;
|
|
3160
|
-
repeated KeyValue attributes = 3;
|
|
3161
|
-
uint32 dropped_attributes_count = 4;
|
|
3162
|
-
}
|
|
3163
|
-
message Resource {
|
|
3164
|
-
repeated KeyValue attributes = 1;
|
|
3165
|
-
uint32 dropped_attributes_count = 2;
|
|
3166
|
-
}
|
|
3167
|
-
message Status {
|
|
3168
|
-
reserved 1;
|
|
3169
|
-
string message = 2;
|
|
3170
|
-
enum StatusCode {
|
|
3171
|
-
STATUS_CODE_UNSET = 0;
|
|
3172
|
-
STATUS_CODE_OK = 1;
|
|
3173
|
-
STATUS_CODE_ERROR = 2;
|
|
3174
|
-
}
|
|
3175
|
-
StatusCode code = 3;
|
|
3176
|
-
}
|
|
3177
|
-
message Span {
|
|
3178
|
-
bytes trace_id = 1;
|
|
3179
|
-
bytes span_id = 2;
|
|
3180
|
-
string trace_state = 3;
|
|
3181
|
-
bytes parent_span_id = 4;
|
|
3182
|
-
fixed32 flags = 16;
|
|
3183
|
-
string name = 5;
|
|
3184
|
-
enum SpanKind {
|
|
3185
|
-
SPAN_KIND_UNSPECIFIED = 0;
|
|
3186
|
-
SPAN_KIND_INTERNAL = 1;
|
|
3187
|
-
SPAN_KIND_SERVER = 2;
|
|
3188
|
-
SPAN_KIND_CLIENT = 3;
|
|
3189
|
-
SPAN_KIND_PRODUCER = 4;
|
|
3190
|
-
SPAN_KIND_CONSUMER = 5;
|
|
3191
|
-
}
|
|
3192
|
-
SpanKind kind = 6;
|
|
3193
|
-
fixed64 start_time_unix_nano = 7;
|
|
3194
|
-
fixed64 end_time_unix_nano = 8;
|
|
3195
|
-
repeated KeyValue attributes = 9;
|
|
3196
|
-
uint32 dropped_attributes_count = 10;
|
|
3197
|
-
repeated Event events = 11;
|
|
3198
|
-
uint32 dropped_events_count = 12;
|
|
3199
|
-
repeated Link links = 13;
|
|
3200
|
-
uint32 dropped_links_count = 14;
|
|
3201
|
-
Status status = 15;
|
|
3202
|
-
message Event {
|
|
3203
|
-
fixed64 time_unix_nano = 1;
|
|
3204
|
-
string name = 2;
|
|
3205
|
-
repeated KeyValue attributes = 3;
|
|
3206
|
-
uint32 dropped_attributes_count = 4;
|
|
3207
|
-
}
|
|
3208
|
-
message Link {
|
|
3209
|
-
bytes trace_id = 1;
|
|
3210
|
-
bytes span_id = 2;
|
|
3211
|
-
string trace_state = 3;
|
|
3212
|
-
repeated KeyValue attributes = 4;
|
|
3213
|
-
uint32 dropped_attributes_count = 5;
|
|
3214
|
-
fixed32 flags = 6;
|
|
3215
|
-
}
|
|
3216
|
-
}
|
|
3217
|
-
message ScopeSpans {
|
|
3218
|
-
InstrumentationScope scope = 1;
|
|
3219
|
-
repeated Span spans = 2;
|
|
3220
|
-
string schema_url = 3;
|
|
3221
|
-
}
|
|
3222
|
-
message ResourceSpans {
|
|
3223
|
-
Resource resource = 1;
|
|
3224
|
-
repeated ScopeSpans scope_spans = 2;
|
|
3225
|
-
string schema_url = 3;
|
|
3226
|
-
}
|
|
3227
|
-
message ExportTraceServiceRequest {
|
|
3228
|
-
repeated ResourceSpans resource_spans = 1;
|
|
3229
|
-
}
|
|
3230
|
-
`, { keepCase: false }).root.lookupType("otlp.ExportTraceServiceRequest");
|
|
3231
|
-
function bytesToHex(bytes) {
|
|
3232
|
-
if (!bytes || bytes.length === 0) return void 0;
|
|
3233
|
-
let hex = "";
|
|
3234
|
-
for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
|
|
3235
|
-
return hex;
|
|
3236
|
-
}
|
|
3237
|
-
function convertAnyValue(v) {
|
|
3238
|
-
if (v == null) return void 0;
|
|
3239
|
-
if (v.stringValue !== void 0 || v.value === "stringValue") return { stringValue: v.stringValue ?? "" };
|
|
3240
|
-
if (v.boolValue !== void 0 || v.value === "boolValue") return { boolValue: v.boolValue ?? false };
|
|
3241
|
-
if (v.intValue !== void 0 || v.value === "intValue") return { intValue: String(v.intValue ?? 0) };
|
|
3242
|
-
if (v.doubleValue !== void 0 || v.value === "doubleValue") return { doubleValue: v.doubleValue ?? 0 };
|
|
3243
|
-
if (v.bytesValue !== void 0 || v.value === "bytesValue") return { stringValue: bytesToHex(v.bytesValue) ?? "" };
|
|
3244
|
-
if (v.arrayValue !== void 0 || v.value === "arrayValue") return { arrayValue: { values: (v.arrayValue?.values ?? []).map(convertAnyValue) } };
|
|
3245
|
-
if (v.kvlistValue !== void 0 || v.value === "kvlistValue") return { kvlistValue: { values: (v.kvlistValue?.values ?? []).map(convertKeyValue) } };
|
|
3246
|
-
}
|
|
3247
|
-
function convertKeyValue(kv) {
|
|
3248
|
-
return {
|
|
3249
|
-
key: kv.key ?? "",
|
|
3250
|
-
value: convertAnyValue(kv.value)
|
|
3251
|
-
};
|
|
3252
|
-
}
|
|
3253
|
-
function convertSpan(s) {
|
|
3254
|
-
return {
|
|
3255
|
-
traceId: bytesToHex(s.traceId) ?? "",
|
|
3256
|
-
spanId: bytesToHex(s.spanId) ?? "",
|
|
3257
|
-
parentSpanId: bytesToHex(s.parentSpanId),
|
|
3258
|
-
traceState: s.traceState,
|
|
3259
|
-
name: s.name ?? "",
|
|
3260
|
-
kind: typeof s.kind === "number" ? s.kind : 0,
|
|
3261
|
-
startTimeUnixNano: String(s.startTimeUnixNano ?? "0"),
|
|
3262
|
-
endTimeUnixNano: String(s.endTimeUnixNano ?? "0"),
|
|
3263
|
-
attributes: (s.attributes ?? []).map(convertKeyValue),
|
|
3264
|
-
events: (s.events ?? []).map((e) => ({
|
|
3265
|
-
timeUnixNano: String(e.timeUnixNano ?? "0"),
|
|
3266
|
-
name: e.name ?? "",
|
|
3267
|
-
attributes: (e.attributes ?? []).map(convertKeyValue)
|
|
3268
|
-
})),
|
|
3269
|
-
links: (s.links ?? []).map((l) => ({
|
|
3270
|
-
traceId: bytesToHex(l.traceId) ?? "",
|
|
3271
|
-
spanId: bytesToHex(l.spanId) ?? "",
|
|
3272
|
-
attributes: (l.attributes ?? []).map(convertKeyValue)
|
|
3273
|
-
})),
|
|
3274
|
-
status: s.status ? {
|
|
3275
|
-
code: typeof s.status.code === "number" ? s.status.code : 0,
|
|
3276
|
-
message: s.status.message
|
|
3277
|
-
} : void 0
|
|
3278
|
-
};
|
|
3279
|
-
}
|
|
3280
|
-
/**
|
|
3281
|
-
* Decodes an OTLP/protobuf `ExportTraceServiceRequest` payload into the same
|
|
3282
|
-
* plain-object shape as the OTLP/JSON encoding (camelCase keys, hex trace/span
|
|
3283
|
-
* ids, stringified 64-bit values) — so `../otlp/normalize.ts` can walk either
|
|
3284
|
-
* with one function.
|
|
3285
|
-
*/
|
|
3286
|
-
function decodeOtlpProtobuf(buf) {
|
|
3287
|
-
const decoded = ExportTraceServiceRequest.decode(buf);
|
|
3288
|
-
return { resourceSpans: (ExportTraceServiceRequest.toObject(decoded, {
|
|
3289
|
-
longs: String,
|
|
3290
|
-
bytes: Array,
|
|
3291
|
-
defaults: false,
|
|
3292
|
-
oneofs: true
|
|
3293
|
-
}).resourceSpans ?? []).map((rs) => ({
|
|
3294
|
-
resource: rs.resource ? { attributes: (rs.resource.attributes ?? []).map(convertKeyValue) } : { attributes: [] },
|
|
3295
|
-
scopeSpans: (rs.scopeSpans ?? []).map((ss) => ({
|
|
3296
|
-
scope: ss.scope ? {
|
|
3297
|
-
name: ss.scope.name ?? "",
|
|
3298
|
-
version: ss.scope.version
|
|
3299
|
-
} : void 0,
|
|
3300
|
-
spans: (ss.spans ?? []).map(convertSpan)
|
|
3301
|
-
}))
|
|
3302
|
-
})) };
|
|
3303
|
-
}
|
|
3304
|
-
//#endregion
|
|
3305
2994
|
//#region src/prompt/prompt-provider.ts
|
|
3306
2995
|
/** `ref` as a {@link PromptRef}: a bare id is head. */
|
|
3307
2996
|
function toPromptRef(ref) {
|
|
@@ -3506,13 +3195,28 @@ async function mkdirSelfIgnoring(dir) {
|
|
|
3506
3195
|
* Callers still owe the database a migration pass (`runMigrations` from
|
|
3507
3196
|
* `./migrate.ts`) before use — connecting alone does not create any tables.
|
|
3508
3197
|
*/
|
|
3509
|
-
async function createLocalTursoClient({ path, getCloudUrl = () => null, getAuthToken, clientName = "evalution" }) {
|
|
3510
|
-
const
|
|
3198
|
+
async function createLocalTursoClient({ path, getCloudUrl = () => null, getAuthToken, clientName = "evalution", onBootstrapFailure }) {
|
|
3199
|
+
const options = {
|
|
3511
3200
|
path,
|
|
3512
|
-
url: getCloudUrl,
|
|
3513
3201
|
...getAuthToken && { authToken: getAuthToken },
|
|
3514
3202
|
clientName
|
|
3515
|
-
}
|
|
3203
|
+
};
|
|
3204
|
+
let db;
|
|
3205
|
+
try {
|
|
3206
|
+
db = await connect({
|
|
3207
|
+
...options,
|
|
3208
|
+
url: getCloudUrl
|
|
3209
|
+
});
|
|
3210
|
+
} catch (err) {
|
|
3211
|
+
if (getCloudUrl() === null) throw err;
|
|
3212
|
+
onBootstrapFailure?.(err);
|
|
3213
|
+
let connecting = true;
|
|
3214
|
+
db = await connect({
|
|
3215
|
+
...options,
|
|
3216
|
+
url: () => connecting ? null : getCloudUrl()
|
|
3217
|
+
});
|
|
3218
|
+
connecting = false;
|
|
3219
|
+
}
|
|
3516
3220
|
await db.exec("PRAGMA foreign_keys = ON");
|
|
3517
3221
|
return db;
|
|
3518
3222
|
}
|
|
@@ -3539,6 +3243,402 @@ async function assertSqliteFile(path) {
|
|
|
3539
3243
|
await handle.close();
|
|
3540
3244
|
}
|
|
3541
3245
|
}
|
|
3246
|
+
//#endregion
|
|
3247
|
+
//#region src/trace/db/migrations/bundled.ts
|
|
3248
|
+
/** Every migration under `src/trace/db/migrations/`, in apply order. */
|
|
3249
|
+
const bundledMigrations$2 = [
|
|
3250
|
+
{
|
|
3251
|
+
"name": "20260916160325_clean_morbius",
|
|
3252
|
+
"hash": "7252af780db973fd35845362cc580e4e31fd0d991e3d083208f9af653107a24a",
|
|
3253
|
+
"folderMillis": 1789574605e3,
|
|
3254
|
+
"bps": true,
|
|
3255
|
+
"sql": [
|
|
3256
|
+
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nCREATE TABLE `annotations` (\n `id` text PRIMARY KEY,\n `trace_id` text NOT NULL,\n `span_id` text,\n `kind` text NOT NULL,\n `note` text NOT NULL,\n `source` text NOT NULL,\n `created_at` real NOT NULL,\n CONSTRAINT `fk_annotations_trace_id_traces_id_fk` FOREIGN KEY (`trace_id`) REFERENCES `traces`(`id`) ON DELETE CASCADE\n);\n",
|
|
3257
|
+
"\nCREATE TABLE `spans` (\n `id` text PRIMARY KEY,\n `trace_id` text NOT NULL,\n `parent_id` text,\n `name` text NOT NULL,\n `kind` text NOT NULL,\n `start_time` real NOT NULL,\n `end_time` real,\n `status` text,\n `error_message` text,\n `llm_provider` text,\n `llm_model` text,\n `llm_prompt_tokens` integer,\n `llm_completion_tokens` integer,\n `llm_total_tokens` integer,\n `llm_cost_prompt` real,\n `llm_cost_completion` real,\n `llm_input` text,\n `llm_output` text,\n `llm_parameters` text,\n `attributes` text,\n `prompt` text,\n `tool` text\n);\n",
|
|
3258
|
+
"\nCREATE TABLE `traces` (\n `id` text PRIMARY KEY,\n `provider_id` text,\n `name` text NOT NULL,\n `start_time` real NOT NULL,\n `end_time` real,\n `status` text NOT NULL,\n `attributes` text\n);\n",
|
|
3259
|
+
"\nCREATE INDEX `idx_annotations_trace_id` ON `annotations` (`trace_id`);",
|
|
3260
|
+
"\nCREATE INDEX `idx_spans_trace_id` ON `spans` (`trace_id`);",
|
|
3261
|
+
"\nCREATE INDEX `idx_spans_parent_id` ON `spans` (`parent_id`);",
|
|
3262
|
+
"\nCREATE INDEX `idx_traces_start_time` ON `traces` (`start_time`);",
|
|
3263
|
+
"\nCREATE TRIGGER `trg_spans_cascade_delete_trace` AFTER DELETE ON `traces` BEGIN DELETE FROM `spans` WHERE `trace_id` = OLD.`id`; END;"
|
|
3264
|
+
]
|
|
3265
|
+
},
|
|
3266
|
+
{
|
|
3267
|
+
"name": "20260919154843_rich_captain_midlands",
|
|
3268
|
+
"hash": "eae6a353961a14967d7922d786f74b2a122ebceaa3e6ef6e7385a8e8ab179965",
|
|
3269
|
+
"folderMillis": 1789832923e3,
|
|
3270
|
+
"bps": true,
|
|
3271
|
+
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_finish_reason` text;\n"]
|
|
3272
|
+
},
|
|
3273
|
+
{
|
|
3274
|
+
"name": "20261005101155_charming_black_widow",
|
|
3275
|
+
"hash": "3eb61759c7ce9c02589be63f49bba073391c4b671b286b002e43dcef58cf8cca",
|
|
3276
|
+
"folderMillis": 1791195115e3,
|
|
3277
|
+
"bps": true,
|
|
3278
|
+
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `resource` text;\n"]
|
|
3279
|
+
},
|
|
3280
|
+
{
|
|
3281
|
+
"name": "20261011235401_clean_spiral",
|
|
3282
|
+
"hash": "96cd624b624e5168a5b8d58177084f183e1bd4cb3d3b2bcefdb2f85bc6f25806",
|
|
3283
|
+
"folderMillis": 1791762841e3,
|
|
3284
|
+
"bps": true,
|
|
3285
|
+
"sql": [
|
|
3286
|
+
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_cache_read_tokens` integer;",
|
|
3287
|
+
"\nALTER TABLE `spans` ADD `llm_cache_write_tokens` integer;",
|
|
3288
|
+
"\nALTER TABLE `spans` ADD `llm_cost_cache_read` real;",
|
|
3289
|
+
"\nALTER TABLE `spans` ADD `llm_cost_cache_write` real;\n"
|
|
3290
|
+
]
|
|
3291
|
+
},
|
|
3292
|
+
{
|
|
3293
|
+
"name": "20261106230751_lively_blue_blade",
|
|
3294
|
+
"hash": "c7d45b4019aa84ada631942bcc1ce84dff0cc1d1e9902681f1c49f1ab7179dc9",
|
|
3295
|
+
"folderMillis": 1794006471e3,
|
|
3296
|
+
"bps": true,
|
|
3297
|
+
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_reasoning` text;"]
|
|
3298
|
+
}
|
|
3299
|
+
];
|
|
3300
|
+
//#endregion
|
|
3301
|
+
//#region src/trace/db/migrate.ts
|
|
3302
|
+
/** The ledger table `runMigrations` records applied migrations in. */
|
|
3303
|
+
const MIGRATIONS_TABLE = "__evalution_migrations";
|
|
3304
|
+
/**
|
|
3305
|
+
* Applies every migration in `migrations` that hasn't already run, tracked in
|
|
3306
|
+
* the {@link MIGRATIONS_TABLE} ledger. Entries are keyed by migration name, so
|
|
3307
|
+
* the trace and dataset bundles could even share one database's ledger.
|
|
3308
|
+
* Idempotent: re-running against an up-to-date database is a no-op. Called on local first-run and on
|
|
3309
|
+
* cloud provisioning alike (see §B.4) — never at import time, so a caller
|
|
3310
|
+
* controls exactly when the (transactional) DDL runs.
|
|
3311
|
+
*/
|
|
3312
|
+
async function runMigrations(db, migrations = bundledMigrations$2) {
|
|
3313
|
+
await migrateAsync(migrations, db, { migrationsTable: MIGRATIONS_TABLE });
|
|
3314
|
+
}
|
|
3315
|
+
/**
|
|
3316
|
+
* The trace database's schema version, for sync: how many migrations it has.
|
|
3317
|
+
* The cloud won't let an evalution with an older schema sync a database a
|
|
3318
|
+
* newer one has.
|
|
3319
|
+
*/
|
|
3320
|
+
const TRACE_SCHEMA_VERSION = bundledMigrations$2.length;
|
|
3321
|
+
//#endregion
|
|
3322
|
+
//#region src/sync/local-database.ts
|
|
3323
|
+
/**
|
|
3324
|
+
* Opening a local database file, and bringing it into a linked project's
|
|
3325
|
+
* sync. See PLAN §6 in the cloud repo.
|
|
3326
|
+
*
|
|
3327
|
+
* A file records the cloud databases it has synced with in
|
|
3328
|
+
* {@link SYNC_LINKS_TABLE}. It syncs only with one it has a link to. A file
|
|
3329
|
+
* that has never synced doesn't record its changes for sync, since they'd
|
|
3330
|
+
* only bloat it, so it can't simply start syncing. Instead it's *adopted*:
|
|
3331
|
+
*
|
|
3332
|
+
* 1. A copy of the cloud's database is made beside it (`<file>.adopting`).
|
|
3333
|
+
* 2. With the provider's operations paused, the file's rows are copied in.
|
|
3334
|
+
* 3. The copy takes the file's place, and the provider reopens it. Sync
|
|
3335
|
+
* pushes the copied rows like any other change.
|
|
3336
|
+
*
|
|
3337
|
+
* Only step 3 can't simply be started over. A marker file says it has
|
|
3338
|
+
* begun, so opening the file finishes it after a crash.
|
|
3339
|
+
*/
|
|
3340
|
+
/** The table recording which cloud databases a file has synced with. */
|
|
3341
|
+
const SYNC_LINKS_TABLE = "evalution_sync_links";
|
|
3342
|
+
/**
|
|
3343
|
+
* Files Turso keeps beside a database. `-wal-revert` is the sync engine's,
|
|
3344
|
+
* written while a pull sets local changes aside. `-shm` is SQLite's own, in
|
|
3345
|
+
* case another build opened it.
|
|
3346
|
+
*/
|
|
3347
|
+
const SIDECARS = [
|
|
3348
|
+
"-wal",
|
|
3349
|
+
"-wal-revert",
|
|
3350
|
+
"-shm",
|
|
3351
|
+
"-info",
|
|
3352
|
+
"-changes"
|
|
3353
|
+
];
|
|
3354
|
+
const ADOPTING = ".adopting";
|
|
3355
|
+
/** Says the adopted copy is taking the file's place. */
|
|
3356
|
+
const SWAPPING = ".adopted";
|
|
3357
|
+
/** Rows read and written at a time when copying. */
|
|
3358
|
+
const COPY_BATCH = 500;
|
|
3359
|
+
const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
3360
|
+
async function all(db, sql, ...args) {
|
|
3361
|
+
return await (await db.prepare(sql)).all(...args);
|
|
3362
|
+
}
|
|
3363
|
+
async function tableNames(db) {
|
|
3364
|
+
const rows = await all(db, "SELECT name FROM sqlite_schema WHERE type = 'table'");
|
|
3365
|
+
return new Set(rows.map((row) => String(row.name)));
|
|
3366
|
+
}
|
|
3367
|
+
/** The cloud databases `db` has synced with. */
|
|
3368
|
+
async function readSyncLinks(db) {
|
|
3369
|
+
if (!(await tableNames(db)).has("evalution_sync_links")) return [];
|
|
3370
|
+
return (await all(db, `SELECT sync_id, project_id FROM ${SYNC_LINKS_TABLE}`)).map((row) => ({
|
|
3371
|
+
syncId: String(row.sync_id),
|
|
3372
|
+
projectId: String(row.project_id)
|
|
3373
|
+
}));
|
|
3374
|
+
}
|
|
3375
|
+
/** Records that `db` holds the rows of the cloud database `credentials` name. */
|
|
3376
|
+
async function recordSyncLink(db, { syncId, projectId }) {
|
|
3377
|
+
await db.exec(`CREATE TABLE IF NOT EXISTS ${SYNC_LINKS_TABLE} (sync_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, linked_at INTEGER NOT NULL)`);
|
|
3378
|
+
await (await db.prepare(`INSERT INTO ${SYNC_LINKS_TABLE} (sync_id, project_id, linked_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING`)).run(syncId, projectId, Date.now());
|
|
3379
|
+
}
|
|
3380
|
+
/**
|
|
3381
|
+
* Stops `db`'s connection recording changes for sync, and drops what it has
|
|
3382
|
+
* recorded. Only for a file that has never synced: it has nowhere to push
|
|
3383
|
+
* them, and syncing starts by adopting the file, which doesn't need them.
|
|
3384
|
+
*/
|
|
3385
|
+
async function stopRecordingChanges(db) {
|
|
3386
|
+
await db.exec("PRAGMA capture_data_changes_conn('off')");
|
|
3387
|
+
if ((await tableNames(db)).has("turso_cdc")) await db.exec("DELETE FROM turso_cdc");
|
|
3388
|
+
}
|
|
3389
|
+
/** A database file and the files Turso keeps beside it. */
|
|
3390
|
+
function filesOf(path) {
|
|
3391
|
+
return [path, ...SIDECARS.map((suffix) => path + suffix)];
|
|
3392
|
+
}
|
|
3393
|
+
async function exists(path) {
|
|
3394
|
+
return stat(path).then(() => true, () => false);
|
|
3395
|
+
}
|
|
3396
|
+
async function removeDatabase(path) {
|
|
3397
|
+
await Promise.all(filesOf(path).map((file) => rm(file, { force: true })));
|
|
3398
|
+
}
|
|
3399
|
+
/**
|
|
3400
|
+
* Puts the adopted copy in the file's place, once the {@link SWAPPING}
|
|
3401
|
+
* marker is down: each of the file's files is removed, and the copy's put
|
|
3402
|
+
* there if it has one. The copy's files outlive the marker, so a crash
|
|
3403
|
+
* before it's removed leaves everything to run this again from, and one
|
|
3404
|
+
* after leaves a finished swap.
|
|
3405
|
+
*
|
|
3406
|
+
* Copied, not renamed: `@tursodatabase/sync` 0.7 remembers a closed
|
|
3407
|
+
* database by its file, not its path, until it's garbage collected, so a
|
|
3408
|
+
* renamed file reopened in the same process is taken for the old path's,
|
|
3409
|
+
* and fails to open. A copy into a path just emptied is a new file. (A
|
|
3410
|
+
* clone, where the file system can, so it's instant.) The closed database
|
|
3411
|
+
* also keeps its files open until then, so their inodes can't be reused
|
|
3412
|
+
* meanwhile.
|
|
3413
|
+
*/
|
|
3414
|
+
async function finishSwap(path) {
|
|
3415
|
+
const adopted = filesOf(path + ADOPTING);
|
|
3416
|
+
for (const [i, target] of filesOf(path).entries()) {
|
|
3417
|
+
const source = adopted[i];
|
|
3418
|
+
await rm(target, { force: true });
|
|
3419
|
+
if (await exists(source)) await copyFile(source, target, constants$1.COPYFILE_FICLONE);
|
|
3420
|
+
}
|
|
3421
|
+
await rm(path + SWAPPING, { force: true });
|
|
3422
|
+
await removeDatabase(path + ADOPTING);
|
|
3423
|
+
}
|
|
3424
|
+
/**
|
|
3425
|
+
* Finishes a swap a crash interrupted, or discards an adoption that hadn't
|
|
3426
|
+
* got that far: it starts over once the file is open.
|
|
3427
|
+
*/
|
|
3428
|
+
async function recoverAdoption(path) {
|
|
3429
|
+
if (await exists(path + SWAPPING)) await finishSwap(path);
|
|
3430
|
+
else await removeDatabase(path + ADOPTING);
|
|
3431
|
+
}
|
|
3432
|
+
async function columnNames(db, table) {
|
|
3433
|
+
return (await all(db, "SELECT name FROM pragma_table_info(?)", table)).map((row) => String(row.name));
|
|
3434
|
+
}
|
|
3435
|
+
/**
|
|
3436
|
+
* Copies `table`'s rows from one database into another, keeping the rows
|
|
3437
|
+
* already there. Copies the columns both have.
|
|
3438
|
+
*/
|
|
3439
|
+
async function copyTable(from, into, table, { read = {}, write = {}, map = (row) => row } = {}) {
|
|
3440
|
+
const target = new Set(await columnNames(into, table));
|
|
3441
|
+
const columns = (await columnNames(from, table)).filter((c) => target.has(c));
|
|
3442
|
+
if (columns.length === 0) return;
|
|
3443
|
+
const select = await from.prepare(`SELECT rowid AS __evalution_rowid, ${columns.map((c) => `${read[c] ?? quote(c)} AS ${quote(c)}`).join(", ")} FROM ${quote(table)} WHERE rowid > ? ORDER BY rowid LIMIT ${COPY_BATCH}`);
|
|
3444
|
+
const insert = await into.prepare(`INSERT INTO ${quote(table)} (${columns.map(quote).join(", ")}) VALUES (${columns.map((c) => write[c] ?? "?").join(", ")}) ON CONFLICT DO NOTHING`);
|
|
3445
|
+
let after = 0;
|
|
3446
|
+
for (;;) {
|
|
3447
|
+
const rows = await select.all(after);
|
|
3448
|
+
if (rows.length === 0) return;
|
|
3449
|
+
await into.transaction(async () => {
|
|
3450
|
+
for (const row of rows) {
|
|
3451
|
+
const mapped = map(row);
|
|
3452
|
+
await insert.run(...columns.map((c) => mapped[c] ?? null));
|
|
3453
|
+
}
|
|
3454
|
+
})();
|
|
3455
|
+
after = Number(rows.at(-1)?.__evalution_rowid);
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
/** Tables that aren't the database's own rows. */
|
|
3459
|
+
const NOT_ROWS = /^(sqlite_|turso_|__turso)/;
|
|
3460
|
+
/**
|
|
3461
|
+
* `tables`, each after the ones it references. Tables that reference each
|
|
3462
|
+
* other in a cycle keep the order they came in.
|
|
3463
|
+
*/
|
|
3464
|
+
async function referencedFirst(db, tables) {
|
|
3465
|
+
const included = new Set(tables);
|
|
3466
|
+
const ordered = /* @__PURE__ */ new Set();
|
|
3467
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
3468
|
+
const visit = async (table) => {
|
|
3469
|
+
if (!included.has(table) || ordered.has(table) || visiting.has(table)) return;
|
|
3470
|
+
visiting.add(table);
|
|
3471
|
+
const references = await all(db, `SELECT "table" FROM pragma_foreign_key_list(?)`, table);
|
|
3472
|
+
for (const { table: referenced } of references) await visit(String(referenced));
|
|
3473
|
+
ordered.add(table);
|
|
3474
|
+
};
|
|
3475
|
+
for (const table of tables) await visit(table);
|
|
3476
|
+
return [...ordered];
|
|
3477
|
+
}
|
|
3478
|
+
/**
|
|
3479
|
+
* Copies every row of `from` into `into`, keeping `into`'s rows where both
|
|
3480
|
+
* have one. Leaves out what isn't rows: Turso's and SQLite's own tables,
|
|
3481
|
+
* the migrations ledger, and the sync links.
|
|
3482
|
+
*
|
|
3483
|
+
* Sync pushes the rows in the order they're written here, and the cloud
|
|
3484
|
+
* checks each one's foreign keys as it arrives. A row it rejects is lost:
|
|
3485
|
+
* the rest of the push lands, and the next pull drops the row here too. So
|
|
3486
|
+
* each table is copied after the ones it references, with foreign keys
|
|
3487
|
+
* checked as the cloud checks them: a row it would reject fails the
|
|
3488
|
+
* adoption instead, before the file is touched.
|
|
3489
|
+
*/
|
|
3490
|
+
async function copyRows(from, into, merge) {
|
|
3491
|
+
await into.exec("PRAGMA foreign_keys = ON");
|
|
3492
|
+
const done = /* @__PURE__ */ new Set([
|
|
3493
|
+
MIGRATIONS_TABLE,
|
|
3494
|
+
SYNC_LINKS_TABLE,
|
|
3495
|
+
...await merge?.(from, into) ?? []
|
|
3496
|
+
]);
|
|
3497
|
+
const target = await tableNames(into);
|
|
3498
|
+
const tables = [...await tableNames(from)].filter((table) => !NOT_ROWS.test(table) && !done.has(table) && target.has(table));
|
|
3499
|
+
for (const table of await referencedFirst(into, tables)) await copyTable(from, into, table);
|
|
3500
|
+
}
|
|
3501
|
+
/**
|
|
3502
|
+
* Opens a local database file, creating it if need be, and migrates it.
|
|
3503
|
+
* With sync, a file new to this machine starts as a copy of the cloud's,
|
|
3504
|
+
* and one that isn't linked to the cloud's database is adopted once the
|
|
3505
|
+
* cloud answers.
|
|
3506
|
+
*/
|
|
3507
|
+
async function openLocalDatabase({ path, migrate, sync = () => void 0 }) {
|
|
3508
|
+
await recoverAdoption(path);
|
|
3509
|
+
const database = () => sync()?.database;
|
|
3510
|
+
let bootstrap = await exists(path) ? void 0 : database()?.currentCredentials;
|
|
3511
|
+
const client = await createLocalTursoClient({
|
|
3512
|
+
path,
|
|
3513
|
+
getCloudUrl: () => bootstrap?.url ?? database()?.getCloudUrl() ?? null,
|
|
3514
|
+
getAuthToken: async () => {
|
|
3515
|
+
const current = database();
|
|
3516
|
+
if (!current) throw new Error("This database isn't synced.");
|
|
3517
|
+
return current.getAuthToken();
|
|
3518
|
+
},
|
|
3519
|
+
onBootstrapFailure: (err) => {
|
|
3520
|
+
bootstrap = void 0;
|
|
3521
|
+
database()?.reportBootstrapFailure(err);
|
|
3522
|
+
}
|
|
3523
|
+
});
|
|
3524
|
+
const copied = bootstrap;
|
|
3525
|
+
bootstrap = void 0;
|
|
3526
|
+
try {
|
|
3527
|
+
if (copied) await recordSyncLink(client, copied);
|
|
3528
|
+
if ((await readSyncLinks(client)).length === 0) await stopRecordingChanges(client);
|
|
3529
|
+
await migrate(client);
|
|
3530
|
+
const current = sync();
|
|
3531
|
+
if (current) await startSyncing({
|
|
3532
|
+
path,
|
|
3533
|
+
client,
|
|
3534
|
+
migrate,
|
|
3535
|
+
sync: current
|
|
3536
|
+
});
|
|
3537
|
+
return client;
|
|
3538
|
+
} catch (err) {
|
|
3539
|
+
await client.close().catch(() => {});
|
|
3540
|
+
throw err;
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
/**
|
|
3544
|
+
* Starts syncing a file {@link openLocalDatabase} opened: pulls if it holds
|
|
3545
|
+
* the cloud database's rows, and adopts it once the cloud answers if not.
|
|
3546
|
+
* Starting again with the same client does nothing.
|
|
3547
|
+
*/
|
|
3548
|
+
async function startSyncing({ path, client, migrate, sync }) {
|
|
3549
|
+
const links = await readSyncLinks(client);
|
|
3550
|
+
sync.database.attach(client, {
|
|
3551
|
+
links: links.map((link) => link.syncId),
|
|
3552
|
+
onPulled: sync.onPulled,
|
|
3553
|
+
adopt: () => adopt(path, client, links, migrate, sync),
|
|
3554
|
+
...sync.onDeleted && { onDeleted: sync.onDeleted }
|
|
3555
|
+
});
|
|
3556
|
+
}
|
|
3557
|
+
/** Swaps `path` for a copy of the cloud's database holding its rows too. */
|
|
3558
|
+
async function adopt(path, client, links, migrate, sync) {
|
|
3559
|
+
const credentials = sync.database.currentCredentials;
|
|
3560
|
+
if (!credentials) return;
|
|
3561
|
+
const copy = !(sync.replaceSuperseded && links.some((link) => link.projectId === credentials.projectId));
|
|
3562
|
+
const adopting = path + ADOPTING;
|
|
3563
|
+
await removeDatabase(adopting);
|
|
3564
|
+
let into;
|
|
3565
|
+
let swapping = false;
|
|
3566
|
+
try {
|
|
3567
|
+
into = await connect({
|
|
3568
|
+
path: adopting,
|
|
3569
|
+
url: credentials.url,
|
|
3570
|
+
authToken: sync.database.getAuthToken,
|
|
3571
|
+
clientName: "evalution"
|
|
3572
|
+
});
|
|
3573
|
+
await migrate(into);
|
|
3574
|
+
await recordSyncLink(into, credentials);
|
|
3575
|
+
const copyInto = into;
|
|
3576
|
+
await sync.pause(async () => {
|
|
3577
|
+
if (copy) await copyRows(client, copyInto, sync.merge);
|
|
3578
|
+
await copyInto.close();
|
|
3579
|
+
try {
|
|
3580
|
+
await client.close();
|
|
3581
|
+
await writeFile(path + SWAPPING, "");
|
|
3582
|
+
swapping = true;
|
|
3583
|
+
await finishSwap(path);
|
|
3584
|
+
} finally {
|
|
3585
|
+
await sync.reopen();
|
|
3586
|
+
}
|
|
3587
|
+
});
|
|
3588
|
+
} finally {
|
|
3589
|
+
if (!swapping) {
|
|
3590
|
+
await into?.close().catch(() => {});
|
|
3591
|
+
await removeDatabase(adopting);
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
}
|
|
3595
|
+
//#endregion
|
|
3596
|
+
//#region src/sync/pause-gate.ts
|
|
3597
|
+
/**
|
|
3598
|
+
* Lets a provider's operations on its database run side by side, except
|
|
3599
|
+
* while the database is swapped for another file: {@link pause} waits for
|
|
3600
|
+
* the operations under way, and holds new ones until it's done.
|
|
3601
|
+
*
|
|
3602
|
+
* An operation must not start another one and wait for it — while a pause
|
|
3603
|
+
* waits on the first, the second would wait on the pause.
|
|
3604
|
+
*/
|
|
3605
|
+
var PauseGate = class {
|
|
3606
|
+
running = 0;
|
|
3607
|
+
paused;
|
|
3608
|
+
onIdle;
|
|
3609
|
+
/** Whether a pause is waiting or under way. */
|
|
3610
|
+
get isPaused() {
|
|
3611
|
+
return this.paused !== void 0;
|
|
3612
|
+
}
|
|
3613
|
+
/** Runs `op`, after any pause. */
|
|
3614
|
+
async run(op) {
|
|
3615
|
+
while (this.paused) await this.paused;
|
|
3616
|
+
this.running++;
|
|
3617
|
+
try {
|
|
3618
|
+
return await op();
|
|
3619
|
+
} finally {
|
|
3620
|
+
if (--this.running === 0) this.onIdle?.();
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
/** Runs `during` once no operation is under way, holding new ones until it settles. */
|
|
3624
|
+
async pause(during) {
|
|
3625
|
+
while (this.paused) await this.paused;
|
|
3626
|
+
let resume = () => {};
|
|
3627
|
+
this.paused = new Promise((resolve) => {
|
|
3628
|
+
resume = resolve;
|
|
3629
|
+
});
|
|
3630
|
+
try {
|
|
3631
|
+
if (this.running > 0) await new Promise((resolve) => {
|
|
3632
|
+
this.onIdle = resolve;
|
|
3633
|
+
});
|
|
3634
|
+
return await during();
|
|
3635
|
+
} finally {
|
|
3636
|
+
this.onIdle = void 0;
|
|
3637
|
+
this.paused = void 0;
|
|
3638
|
+
resume();
|
|
3639
|
+
}
|
|
3640
|
+
}
|
|
3641
|
+
};
|
|
3542
3642
|
let runaway = 0;
|
|
3543
3643
|
/**
|
|
3544
3644
|
* The worker's whole program. Mirrors `runReadOnlyQuery`, on a connection of
|
|
@@ -3703,100 +3803,90 @@ function isValidDatasetId(id) {
|
|
|
3703
3803
|
return /^[a-z0-9][a-z0-9-]{0,99}$/.test(id);
|
|
3704
3804
|
}
|
|
3705
3805
|
//#endregion
|
|
3706
|
-
//#region src/
|
|
3707
|
-
|
|
3708
|
-
|
|
3806
|
+
//#region src/dataset/db/merge.ts
|
|
3807
|
+
async function datasetIn(db) {
|
|
3808
|
+
return (await db.prepare("SELECT id, fields, next_field_id FROM datasets LIMIT 1")).get();
|
|
3809
|
+
}
|
|
3810
|
+
/**
|
|
3811
|
+
* The cloud's fields with the local ones added, and what each local field's
|
|
3812
|
+
* id becomes.
|
|
3813
|
+
*/
|
|
3814
|
+
function unionFields(remote, remoteNextId, local) {
|
|
3815
|
+
const fields = [...remote];
|
|
3816
|
+
const byName = new Map(remote.map((field) => [field.def.name, field.id]));
|
|
3817
|
+
const ids = /* @__PURE__ */ new Map();
|
|
3818
|
+
let nextFieldId = remoteNextId;
|
|
3819
|
+
for (const field of local) {
|
|
3820
|
+
const same = byName.get(field.def.name);
|
|
3821
|
+
if (same !== void 0) {
|
|
3822
|
+
ids.set(field.id, same);
|
|
3823
|
+
continue;
|
|
3824
|
+
}
|
|
3825
|
+
const id = fieldIdFor(nextFieldId++);
|
|
3826
|
+
ids.set(field.id, id);
|
|
3827
|
+
byName.set(field.def.name, id);
|
|
3828
|
+
fields.push({
|
|
3829
|
+
...field,
|
|
3830
|
+
id
|
|
3831
|
+
});
|
|
3832
|
+
}
|
|
3833
|
+
return {
|
|
3834
|
+
fields,
|
|
3835
|
+
nextFieldId,
|
|
3836
|
+
ids
|
|
3837
|
+
};
|
|
3838
|
+
}
|
|
3839
|
+
/**
|
|
3840
|
+
* Merges the dataset in `from` into the one in `into`, for `copyRows`. With
|
|
3841
|
+
* no dataset on one side, there's nothing to reconcile: the generic copy
|
|
3842
|
+
* does.
|
|
3843
|
+
*/
|
|
3844
|
+
async function mergeDatasetTables(from, into) {
|
|
3845
|
+
const local = await datasetIn(from);
|
|
3846
|
+
const remote = await datasetIn(into);
|
|
3847
|
+
if (!local || !remote) return [];
|
|
3848
|
+
const { fields, nextFieldId, ids } = unionFields(JSON.parse(remote.fields), remote.next_field_id, JSON.parse(local.fields));
|
|
3849
|
+
if (nextFieldId !== remote.next_field_id) await (await into.prepare("UPDATE datasets SET fields = ?, next_field_id = ?, updated_at = ? WHERE id = ?")).run(JSON.stringify(fields), nextFieldId, Date.now(), remote.id);
|
|
3850
|
+
await copyTable(from, into, "dataset_rows", {
|
|
3851
|
+
read: { cells: "json(cells)" },
|
|
3852
|
+
write: { cells: "jsonb(?)" },
|
|
3853
|
+
map: (row) => ({
|
|
3854
|
+
...row,
|
|
3855
|
+
dataset_id: remote.id,
|
|
3856
|
+
cells: JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(String(row.cells))).flatMap(([id, value]) => {
|
|
3857
|
+
const to = ids.get(id);
|
|
3858
|
+
return to === void 0 ? [] : [[to, value]];
|
|
3859
|
+
})))
|
|
3860
|
+
})
|
|
3861
|
+
});
|
|
3862
|
+
return ["datasets", "dataset_rows"];
|
|
3863
|
+
}
|
|
3864
|
+
//#endregion
|
|
3865
|
+
//#region src/dataset/db/migrations/bundled.ts
|
|
3866
|
+
/** Every migration under `src/dataset/db/migrations/`, in apply order. */
|
|
3867
|
+
const bundledMigrations$1 = [
|
|
3709
3868
|
{
|
|
3710
|
-
"name": "
|
|
3711
|
-
"hash": "
|
|
3712
|
-
"folderMillis":
|
|
3869
|
+
"name": "20260921135858_broad_gambit",
|
|
3870
|
+
"hash": "97b2057ebe26df83e0dcd08105ebb2bee08aaf6b7cef9a2b3d5cd17c29deaf63",
|
|
3871
|
+
"folderMillis": 1789999138e3,
|
|
3713
3872
|
"bps": true,
|
|
3714
3873
|
"sql": [
|
|
3715
|
-
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nCREATE TABLE `
|
|
3716
|
-
"\nCREATE TABLE `
|
|
3717
|
-
"\nCREATE
|
|
3718
|
-
"\nCREATE INDEX `idx_annotations_trace_id` ON `annotations` (`trace_id`);",
|
|
3719
|
-
"\nCREATE INDEX `idx_spans_trace_id` ON `spans` (`trace_id`);",
|
|
3720
|
-
"\nCREATE INDEX `idx_spans_parent_id` ON `spans` (`parent_id`);",
|
|
3721
|
-
"\nCREATE INDEX `idx_traces_start_time` ON `traces` (`start_time`);",
|
|
3722
|
-
"\nCREATE TRIGGER `trg_spans_cascade_delete_trace` AFTER DELETE ON `traces` BEGIN DELETE FROM `spans` WHERE `trace_id` = OLD.`id`; END;"
|
|
3874
|
+
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nCREATE TABLE `dataset_rows` (\n `id` text PRIMARY KEY,\n `dataset_id` text NOT NULL,\n `cells` blob NOT NULL,\n `source` blob,\n `created_at` real NOT NULL,\n CONSTRAINT `fk_dataset_rows_dataset_id_datasets_id_fk` FOREIGN KEY (`dataset_id`) REFERENCES `datasets`(`id`) ON DELETE CASCADE\n);\n",
|
|
3875
|
+
"\nCREATE TABLE `datasets` (\n `id` text PRIMARY KEY,\n `name` text NOT NULL,\n `fields` text NOT NULL,\n `next_field_id` integer NOT NULL,\n `prompt` text,\n `created_at` real NOT NULL,\n `updated_at` real NOT NULL\n);\n",
|
|
3876
|
+
"\nCREATE INDEX `idx_dataset_rows_dataset` ON `dataset_rows` (`dataset_id`,`created_at`);"
|
|
3723
3877
|
]
|
|
3724
3878
|
},
|
|
3725
3879
|
{
|
|
3726
|
-
"name": "
|
|
3727
|
-
"hash": "
|
|
3728
|
-
"folderMillis":
|
|
3729
|
-
"bps": true,
|
|
3730
|
-
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_finish_reason` text;\n"]
|
|
3731
|
-
},
|
|
3732
|
-
{
|
|
3733
|
-
"name": "20261005101155_charming_black_widow",
|
|
3734
|
-
"hash": "3eb61759c7ce9c02589be63f49bba073391c4b671b286b002e43dcef58cf8cca",
|
|
3735
|
-
"folderMillis": 1791195115e3,
|
|
3880
|
+
"name": "20261008131520_row_resources",
|
|
3881
|
+
"hash": "3d47cdd5b4a04ceef5601b30f690fc37da4ff071e6ce6c0af10be84c8ffd23e7",
|
|
3882
|
+
"folderMillis": 179146532e4,
|
|
3736
3883
|
"bps": true,
|
|
3737
|
-
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `
|
|
3884
|
+
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `dataset_rows` ADD `resources` blob;\n"]
|
|
3738
3885
|
},
|
|
3739
3886
|
{
|
|
3740
|
-
"name": "
|
|
3741
|
-
"hash": "
|
|
3742
|
-
"folderMillis":
|
|
3743
|
-
"bps": true,
|
|
3744
|
-
"sql": [
|
|
3745
|
-
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_cache_read_tokens` integer;",
|
|
3746
|
-
"\nALTER TABLE `spans` ADD `llm_cache_write_tokens` integer;",
|
|
3747
|
-
"\nALTER TABLE `spans` ADD `llm_cost_cache_read` real;",
|
|
3748
|
-
"\nALTER TABLE `spans` ADD `llm_cost_cache_write` real;\n"
|
|
3749
|
-
]
|
|
3750
|
-
},
|
|
3751
|
-
{
|
|
3752
|
-
"name": "20261106230751_lively_blue_blade",
|
|
3753
|
-
"hash": "c7d45b4019aa84ada631942bcc1ce84dff0cc1d1e9902681f1c49f1ab7179dc9",
|
|
3754
|
-
"folderMillis": 1794006471e3,
|
|
3755
|
-
"bps": true,
|
|
3756
|
-
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_reasoning` text;"]
|
|
3757
|
-
}
|
|
3758
|
-
];
|
|
3759
|
-
//#endregion
|
|
3760
|
-
//#region src/trace/db/migrate.ts
|
|
3761
|
-
/** The ledger table `runMigrations` records applied migrations in. */
|
|
3762
|
-
const MIGRATIONS_TABLE = "__evalution_migrations";
|
|
3763
|
-
/**
|
|
3764
|
-
* Applies every migration in `migrations` that hasn't already run, tracked in
|
|
3765
|
-
* the {@link MIGRATIONS_TABLE} ledger. Entries are keyed by migration name, so
|
|
3766
|
-
* the trace and dataset bundles could even share one database's ledger.
|
|
3767
|
-
* Idempotent: re-running against an up-to-date database is a no-op. Called on local first-run and on
|
|
3768
|
-
* cloud provisioning alike (see §B.4) — never at import time, so a caller
|
|
3769
|
-
* controls exactly when the (transactional) DDL runs.
|
|
3770
|
-
*/
|
|
3771
|
-
async function runMigrations(db, migrations = bundledMigrations$2) {
|
|
3772
|
-
await migrateAsync(migrations, db, { migrationsTable: MIGRATIONS_TABLE });
|
|
3773
|
-
}
|
|
3774
|
-
//#endregion
|
|
3775
|
-
//#region src/dataset/db/migrations/bundled.ts
|
|
3776
|
-
/** Every migration under `src/dataset/db/migrations/`, in apply order. */
|
|
3777
|
-
const bundledMigrations$1 = [
|
|
3778
|
-
{
|
|
3779
|
-
"name": "20260921135858_broad_gambit",
|
|
3780
|
-
"hash": "97b2057ebe26df83e0dcd08105ebb2bee08aaf6b7cef9a2b3d5cd17c29deaf63",
|
|
3781
|
-
"folderMillis": 1789999138e3,
|
|
3782
|
-
"bps": true,
|
|
3783
|
-
"sql": [
|
|
3784
|
-
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nCREATE TABLE `dataset_rows` (\n `id` text PRIMARY KEY,\n `dataset_id` text NOT NULL,\n `cells` blob NOT NULL,\n `source` blob,\n `created_at` real NOT NULL,\n CONSTRAINT `fk_dataset_rows_dataset_id_datasets_id_fk` FOREIGN KEY (`dataset_id`) REFERENCES `datasets`(`id`) ON DELETE CASCADE\n);\n",
|
|
3785
|
-
"\nCREATE TABLE `datasets` (\n `id` text PRIMARY KEY,\n `name` text NOT NULL,\n `fields` text NOT NULL,\n `next_field_id` integer NOT NULL,\n `prompt` text,\n `created_at` real NOT NULL,\n `updated_at` real NOT NULL\n);\n",
|
|
3786
|
-
"\nCREATE INDEX `idx_dataset_rows_dataset` ON `dataset_rows` (`dataset_id`,`created_at`);"
|
|
3787
|
-
]
|
|
3788
|
-
},
|
|
3789
|
-
{
|
|
3790
|
-
"name": "20261008131520_row_resources",
|
|
3791
|
-
"hash": "3d47cdd5b4a04ceef5601b30f690fc37da4ff071e6ce6c0af10be84c8ffd23e7",
|
|
3792
|
-
"folderMillis": 179146532e4,
|
|
3793
|
-
"bps": true,
|
|
3794
|
-
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `dataset_rows` ADD `resources` blob;\n"]
|
|
3795
|
-
},
|
|
3796
|
-
{
|
|
3797
|
-
"name": "20261012152455_column_layout",
|
|
3798
|
-
"hash": "a226b20ea4b58a7dd558132c94611a2fb09e97e408e34ba6237387293c8fe869",
|
|
3799
|
-
"folderMillis": 1791818695e3,
|
|
3887
|
+
"name": "20261012152455_column_layout",
|
|
3888
|
+
"hash": "a226b20ea4b58a7dd558132c94611a2fb09e97e408e34ba6237387293c8fe869",
|
|
3889
|
+
"folderMillis": 1791818695e3,
|
|
3800
3890
|
"bps": true,
|
|
3801
3891
|
"sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `datasets` ADD `layout` text;\n"]
|
|
3802
3892
|
}
|
|
@@ -3814,6 +3904,12 @@ const bundledMigrations$1 = [
|
|
|
3814
3904
|
async function runDatasetMigrations(db) {
|
|
3815
3905
|
await runMigrations(db, bundledMigrations$1);
|
|
3816
3906
|
}
|
|
3907
|
+
/**
|
|
3908
|
+
* The dataset database's schema version, for sync: how many migrations it has.
|
|
3909
|
+
* The cloud won't let an evalution with an older schema sync a database a
|
|
3910
|
+
* newer one has.
|
|
3911
|
+
*/
|
|
3912
|
+
const DATASET_SCHEMA_VERSION = bundledMigrations$1.length;
|
|
3817
3913
|
//#endregion
|
|
3818
3914
|
//#region src/dataset/db/schema.ts
|
|
3819
3915
|
/**
|
|
@@ -4378,16 +4474,7 @@ function noSuchField(datasetId, fieldId) {
|
|
|
4378
4474
|
//#region src/dataset/local-directory-dataset-provider.ts
|
|
4379
4475
|
/** Extension of a dataset file. */
|
|
4380
4476
|
const DB_EXT = ".db";
|
|
4381
|
-
|
|
4382
|
-
* Files Turso keeps beside a database, removed with it. `-shm` is SQLite's
|
|
4383
|
-
* own, listed in case a file was last opened by another SQLite build.
|
|
4384
|
-
*/
|
|
4385
|
-
const SIDECARS = [
|
|
4386
|
-
"-wal",
|
|
4387
|
-
"-shm",
|
|
4388
|
-
"-info",
|
|
4389
|
-
"-changes"
|
|
4390
|
-
];
|
|
4477
|
+
const migrateDataset = (client) => runDatasetMigrations(drizzle({ client }));
|
|
4391
4478
|
/**
|
|
4392
4479
|
* A {@link DatasetProvider} that keeps **one SQLite file per dataset** in a
|
|
4393
4480
|
* directory, each opened lazily as a {@link TursoDatasetProvider}.
|
|
@@ -4417,12 +4504,136 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4417
4504
|
reported = /* @__PURE__ */ new Set();
|
|
4418
4505
|
/** Tail of the create chain: id choice and file creation are one step. */
|
|
4419
4506
|
creates = Promise.resolve();
|
|
4507
|
+
sync;
|
|
4508
|
+
/** Per file: holds operations while sync swaps it. */
|
|
4509
|
+
gates = /* @__PURE__ */ new Map();
|
|
4510
|
+
/** Datasets being removed because they were deleted on another machine. */
|
|
4511
|
+
removals = /* @__PURE__ */ new Map();
|
|
4420
4512
|
constructor(options = {}) {
|
|
4421
4513
|
this.id = options.id ?? "local-datasets";
|
|
4422
4514
|
this.displayName = options.displayName ?? "Local Datasets";
|
|
4423
4515
|
this.description = options.description ?? "Stores each dataset in its own SQLite file in a local directory.";
|
|
4424
4516
|
this.dir = resolve(options.dir ?? "./.evalution/datasets");
|
|
4425
4517
|
}
|
|
4518
|
+
/**
|
|
4519
|
+
* Syncs each dataset with the linked project's copy (named by this
|
|
4520
|
+
* provider's id and the dataset's), once `setUpProject` hands this the
|
|
4521
|
+
* project's sync. A dataset the project has in the cloud but this machine
|
|
4522
|
+
* doesn't is fetched whenever the sync pulls, and deleting a dataset
|
|
4523
|
+
* deletes it from the cloud. Datasets already open start syncing as they
|
|
4524
|
+
* are.
|
|
4525
|
+
*
|
|
4526
|
+
* @internal Not public API yet.
|
|
4527
|
+
*/
|
|
4528
|
+
_ecSetSync(workspace) {
|
|
4529
|
+
if (this.sync) return;
|
|
4530
|
+
this.sync = workspace;
|
|
4531
|
+
workspace.onPull(() => this.fetchRemoteDatasets());
|
|
4532
|
+
for (const [datasetId, opening] of this.entries) opening.then(async (entry) => {
|
|
4533
|
+
if (!entry.ok) return;
|
|
4534
|
+
const sync = this.syncHooksFor(datasetId);
|
|
4535
|
+
if (!sync) return;
|
|
4536
|
+
try {
|
|
4537
|
+
await sync.database.prepare();
|
|
4538
|
+
await startSyncing({
|
|
4539
|
+
path: this.pathFor(datasetId),
|
|
4540
|
+
client: entry.client,
|
|
4541
|
+
migrate: migrateDataset,
|
|
4542
|
+
sync
|
|
4543
|
+
});
|
|
4544
|
+
} catch (err) {
|
|
4545
|
+
console.warn(`⚠️ Couldn't start syncing the dataset ${datasetId}:`, err);
|
|
4546
|
+
}
|
|
4547
|
+
});
|
|
4548
|
+
}
|
|
4549
|
+
/** What syncing `datasetId`'s file needs, once there's a sync. */
|
|
4550
|
+
syncHooksFor(datasetId) {
|
|
4551
|
+
const database = this.datasetSync(datasetId);
|
|
4552
|
+
return database && {
|
|
4553
|
+
database,
|
|
4554
|
+
onPulled: () => this.emit({
|
|
4555
|
+
type: "update",
|
|
4556
|
+
datasetId
|
|
4557
|
+
}),
|
|
4558
|
+
pause: (during) => this.gateFor(datasetId).pause(during),
|
|
4559
|
+
reopen: () => this.reopenEntry(datasetId),
|
|
4560
|
+
merge: mergeDatasetTables,
|
|
4561
|
+
replaceSuperseded: true,
|
|
4562
|
+
onDeleted: () => this.removeDeleted(datasetId)
|
|
4563
|
+
};
|
|
4564
|
+
}
|
|
4565
|
+
gateFor(datasetId) {
|
|
4566
|
+
let gate = this.gates.get(datasetId);
|
|
4567
|
+
if (!gate) {
|
|
4568
|
+
gate = new PauseGate();
|
|
4569
|
+
this.gates.set(datasetId, gate);
|
|
4570
|
+
}
|
|
4571
|
+
return gate;
|
|
4572
|
+
}
|
|
4573
|
+
/** Runs `op` on `datasetId`'s file, after any swap of it. */
|
|
4574
|
+
on(datasetId, op) {
|
|
4575
|
+
return this.gateFor(datasetId).run(op);
|
|
4576
|
+
}
|
|
4577
|
+
datasetSync(datasetId) {
|
|
4578
|
+
return this.sync?.database({
|
|
4579
|
+
kind: "dataset",
|
|
4580
|
+
provider: this.id,
|
|
4581
|
+
key: datasetId
|
|
4582
|
+
}, DATASET_SCHEMA_VERSION);
|
|
4583
|
+
}
|
|
4584
|
+
/**
|
|
4585
|
+
* Removes a dataset deleted on another machine, once its sync has found
|
|
4586
|
+
* this file synced with the deleted cloud copy.
|
|
4587
|
+
*/
|
|
4588
|
+
removeDeleted(datasetId) {
|
|
4589
|
+
if (this.removals.has(datasetId)) return;
|
|
4590
|
+
const removal = (async () => {
|
|
4591
|
+
await this.sync?.forgetDataset(this.id, datasetId);
|
|
4592
|
+
await this.removeLocal(datasetId);
|
|
4593
|
+
})().catch((err) => console.warn(`⚠️ Couldn't remove the dataset ${datasetId}:`, err)).finally(() => this.removals.delete(datasetId));
|
|
4594
|
+
this.removals.set(datasetId, removal);
|
|
4595
|
+
}
|
|
4596
|
+
/**
|
|
4597
|
+
* Opens this machine's datasets, so each syncs — one made before the
|
|
4598
|
+
* project was linked is brought into it — and fetches the datasets the
|
|
4599
|
+
* project has in the cloud that this machine doesn't, announcing each as
|
|
4600
|
+
* added. One gone from the cloud's list is checked on, so if it was
|
|
4601
|
+
* deleted on another machine it's removed here too. Chained with creates,
|
|
4602
|
+
* so it can't open a file a create is making.
|
|
4603
|
+
*/
|
|
4604
|
+
fetchRemoteDatasets() {
|
|
4605
|
+
const next = this.creates.then(async () => {
|
|
4606
|
+
try {
|
|
4607
|
+
await this.fetchRemoteDatasetsNow();
|
|
4608
|
+
} finally {
|
|
4609
|
+
await Promise.all(this.removals.values());
|
|
4610
|
+
}
|
|
4611
|
+
});
|
|
4612
|
+
this.creates = next.catch(() => {});
|
|
4613
|
+
return next;
|
|
4614
|
+
}
|
|
4615
|
+
async fetchRemoteDatasetsNow() {
|
|
4616
|
+
const local = new Set(await this.fileIds());
|
|
4617
|
+
for (const id of local) if (!this.entries.has(id)) await this.openEntry(id);
|
|
4618
|
+
const remote = await this.sync?.remoteDatasetIds(this.id);
|
|
4619
|
+
if (!remote) return;
|
|
4620
|
+
const listed = new Set(remote);
|
|
4621
|
+
for (const id of local) {
|
|
4622
|
+
const sync = this.datasetSync(id);
|
|
4623
|
+
if (!listed.has(id) && sync?.isAvailable) await sync.recheck();
|
|
4624
|
+
}
|
|
4625
|
+
for (const id of remote) {
|
|
4626
|
+
if (!isValidDatasetId(id) || local.has(id) || this.entries.has(id)) continue;
|
|
4627
|
+
const sync = this.datasetSync(id);
|
|
4628
|
+
await sync?.prepare();
|
|
4629
|
+
if (!sync?.isAvailable) continue;
|
|
4630
|
+
await mkdirSelfIgnoring(this.dir);
|
|
4631
|
+
if ((await this.openEntry(id)).ok) this.emit({
|
|
4632
|
+
type: "add",
|
|
4633
|
+
datasetId: id
|
|
4634
|
+
});
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4426
4637
|
pathFor(datasetId) {
|
|
4427
4638
|
return join(this.dir, `${datasetId}${DB_EXT}`);
|
|
4428
4639
|
}
|
|
@@ -4460,21 +4671,28 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4460
4671
|
}
|
|
4461
4672
|
return this.openEntry(datasetId);
|
|
4462
4673
|
}
|
|
4463
|
-
/**
|
|
4464
|
-
|
|
4674
|
+
/**
|
|
4675
|
+
* Opens (and migrates) `datasetId`'s file, caching the result. `create`
|
|
4676
|
+
* says the dataset is being made now, which may reuse a deleted one's id.
|
|
4677
|
+
*/
|
|
4678
|
+
openEntry(datasetId, { create = false } = {}) {
|
|
4465
4679
|
const cached = this.entries.get(datasetId);
|
|
4466
4680
|
if (cached) return cached;
|
|
4467
|
-
const opening = this.openUncached(datasetId);
|
|
4681
|
+
const opening = this.openUncached(datasetId, create);
|
|
4468
4682
|
this.entries.set(datasetId, opening);
|
|
4469
4683
|
return opening;
|
|
4470
4684
|
}
|
|
4471
|
-
async openUncached(datasetId) {
|
|
4685
|
+
async openUncached(datasetId, create) {
|
|
4472
4686
|
const path = this.pathFor(datasetId);
|
|
4473
4687
|
let client;
|
|
4474
4688
|
try {
|
|
4475
4689
|
await assertSqliteFile(path);
|
|
4476
|
-
|
|
4477
|
-
await
|
|
4690
|
+
await this.datasetSync(datasetId)?.prepare({ create });
|
|
4691
|
+
client = await openLocalDatabase({
|
|
4692
|
+
path,
|
|
4693
|
+
migrate: migrateDataset,
|
|
4694
|
+
sync: () => this.syncHooksFor(datasetId)
|
|
4695
|
+
});
|
|
4478
4696
|
const inner = new TursoDatasetProvider({
|
|
4479
4697
|
client,
|
|
4480
4698
|
runQuery: (query, options) => runQueryInWorker(path, query, options),
|
|
@@ -4483,10 +4701,13 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4483
4701
|
const found = await inner.listDatasets();
|
|
4484
4702
|
if (found.length > 1) throw new Error(`holds ${found.length} datasets; a dataset file must hold exactly one`);
|
|
4485
4703
|
const innerId = found[0]?.id ?? datasetId;
|
|
4486
|
-
const unwatch = inner.watch((event) =>
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
4704
|
+
const unwatch = inner.watch((event) => {
|
|
4705
|
+
this.emit({
|
|
4706
|
+
type: event.type,
|
|
4707
|
+
datasetId
|
|
4708
|
+
});
|
|
4709
|
+
this.datasetSync(datasetId)?.noteWrite();
|
|
4710
|
+
});
|
|
4490
4711
|
return {
|
|
4491
4712
|
ok: true,
|
|
4492
4713
|
client,
|
|
@@ -4507,6 +4728,18 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4507
4728
|
};
|
|
4508
4729
|
}
|
|
4509
4730
|
}
|
|
4731
|
+
/** Opens `datasetId`'s file again, after sync swapped it (and closed the old one). */
|
|
4732
|
+
async reopenEntry(datasetId) {
|
|
4733
|
+
const old = await this.entries.get(datasetId);
|
|
4734
|
+
if (old?.ok) old.unwatch();
|
|
4735
|
+
this.entries.delete(datasetId);
|
|
4736
|
+
const entry = await this.openEntry(datasetId);
|
|
4737
|
+
if (entry.ok) this.emit({
|
|
4738
|
+
type: "update",
|
|
4739
|
+
datasetId
|
|
4740
|
+
});
|
|
4741
|
+
return entry;
|
|
4742
|
+
}
|
|
4510
4743
|
/** The open entry for `datasetId`, or a {@link DatasetNotFoundError}. */
|
|
4511
4744
|
async requireEntry(datasetId) {
|
|
4512
4745
|
const entry = await this.entryFor(datasetId);
|
|
@@ -4514,15 +4747,17 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4514
4747
|
if (!entry.ok) throw new Error(`Dataset ${datasetId} could not be opened: ${entry.error}`);
|
|
4515
4748
|
return entry;
|
|
4516
4749
|
}
|
|
4517
|
-
/** `dataset` with its id rewritten to the file's. */
|
|
4750
|
+
/** `dataset` with its id rewritten to the file's, marked if the cloud has it. */
|
|
4518
4751
|
withFileId(datasetId, dataset) {
|
|
4519
4752
|
return {
|
|
4520
4753
|
...dataset,
|
|
4521
|
-
id: datasetId
|
|
4754
|
+
id: datasetId,
|
|
4755
|
+
...this.datasetSync(datasetId)?.isAvailable && { synced: true }
|
|
4522
4756
|
};
|
|
4523
4757
|
}
|
|
4524
4758
|
async listDatasets() {
|
|
4525
|
-
const
|
|
4759
|
+
const swapping = [...this.gates].filter(([, gate]) => gate.isPaused).map(([id]) => id);
|
|
4760
|
+
const ids = [.../* @__PURE__ */ new Set([...await this.fileIds(), ...swapping])].sort();
|
|
4526
4761
|
const present = new Set(ids);
|
|
4527
4762
|
for (const [id, opening] of this.entries) {
|
|
4528
4763
|
if (present.has(id)) continue;
|
|
@@ -4533,60 +4768,69 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4533
4768
|
return entry.client.close();
|
|
4534
4769
|
});
|
|
4535
4770
|
}
|
|
4536
|
-
return (await Promise.all(ids.map(
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
|
|
4540
|
-
|
|
4541
|
-
|
|
4542
|
-
|
|
4543
|
-
name: id,
|
|
4544
|
-
rowCount: 0,
|
|
4545
|
-
fields: [],
|
|
4546
|
-
updatedAt: mtime,
|
|
4547
|
-
error: entry.error
|
|
4548
|
-
};
|
|
4549
|
-
}
|
|
4550
|
-
const [summary] = await entry.inner.listDatasets();
|
|
4551
|
-
if (!summary) return {
|
|
4771
|
+
return (await Promise.all(ids.map((id) => this.on(id, () => this.summarize(id))))).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
4772
|
+
}
|
|
4773
|
+
async summarize(id) {
|
|
4774
|
+
const entry = await this.openEntry(id);
|
|
4775
|
+
if (!entry.ok) {
|
|
4776
|
+
const mtime = await stat(this.pathFor(id)).then((s) => s.mtimeMs, () => 0);
|
|
4777
|
+
return {
|
|
4552
4778
|
providerId: this.id,
|
|
4553
4779
|
id,
|
|
4554
4780
|
name: id,
|
|
4555
4781
|
rowCount: 0,
|
|
4556
4782
|
fields: [],
|
|
4557
|
-
updatedAt:
|
|
4558
|
-
error:
|
|
4783
|
+
updatedAt: mtime,
|
|
4784
|
+
error: entry.error
|
|
4559
4785
|
};
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4786
|
+
}
|
|
4787
|
+
const [summary] = await entry.inner.listDatasets();
|
|
4788
|
+
if (!summary) return {
|
|
4789
|
+
providerId: this.id,
|
|
4790
|
+
id,
|
|
4791
|
+
name: id,
|
|
4792
|
+
rowCount: 0,
|
|
4793
|
+
fields: [],
|
|
4794
|
+
updatedAt: 0,
|
|
4795
|
+
error: "holds no dataset"
|
|
4796
|
+
};
|
|
4797
|
+
return {
|
|
4798
|
+
...summary,
|
|
4799
|
+
id
|
|
4800
|
+
};
|
|
4565
4801
|
}
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4802
|
+
getDataset(datasetId) {
|
|
4803
|
+
return this.on(datasetId, async () => {
|
|
4804
|
+
const entry = await this.entryFor(datasetId);
|
|
4805
|
+
if (!entry?.ok) return void 0;
|
|
4806
|
+
const dataset = await entry.inner.getDataset(entry.innerId);
|
|
4807
|
+
return dataset && this.withFileId(datasetId, dataset);
|
|
4808
|
+
});
|
|
4571
4809
|
}
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4810
|
+
listRows(datasetId, options) {
|
|
4811
|
+
return this.on(datasetId, async () => {
|
|
4812
|
+
const entry = await this.entryFor(datasetId);
|
|
4813
|
+
if (!entry?.ok) return [];
|
|
4814
|
+
return entry.inner.listRows(entry.innerId, options);
|
|
4815
|
+
});
|
|
4576
4816
|
}
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
|
|
4817
|
+
describeRows(datasetId) {
|
|
4818
|
+
return this.on(datasetId, async () => {
|
|
4819
|
+
const entry = await this.entryFor(datasetId);
|
|
4820
|
+
if (!entry?.ok) return {
|
|
4821
|
+
rowCount: 0,
|
|
4822
|
+
fields: {},
|
|
4823
|
+
instances: {}
|
|
4824
|
+
};
|
|
4825
|
+
return entry.inner.describeRows(entry.innerId);
|
|
4826
|
+
});
|
|
4585
4827
|
}
|
|
4586
|
-
|
|
4587
|
-
|
|
4588
|
-
|
|
4589
|
-
|
|
4828
|
+
describePath(datasetId, path) {
|
|
4829
|
+
return this.on(datasetId, async () => {
|
|
4830
|
+
const entry = await this.entryFor(datasetId);
|
|
4831
|
+
if (!entry?.ok) return [];
|
|
4832
|
+
return entry.inner.describePath(entry.innerId, path);
|
|
4833
|
+
});
|
|
4590
4834
|
}
|
|
4591
4835
|
/**
|
|
4592
4836
|
* Creates `<slug>.db` (`<slug>-2.db` on collision) and the dataset inside
|
|
@@ -4600,77 +4844,85 @@ var LocalDirectoryDatasetProvider = class {
|
|
|
4600
4844
|
}
|
|
4601
4845
|
async createNow(input) {
|
|
4602
4846
|
await mkdirSelfIgnoring(this.dir);
|
|
4603
|
-
const existing = new Set(await this.fileIds());
|
|
4847
|
+
const existing = /* @__PURE__ */ new Set([...await this.fileIds(), ...await this.sync?.remoteDatasetIds(this.id) ?? []]);
|
|
4604
4848
|
const id = uniqueDatasetId(slugifyDatasetName(input.name), (candidate) => existing.has(candidate) || this.entries.has(candidate));
|
|
4605
|
-
const entry = await this.openEntry(id);
|
|
4849
|
+
const entry = await this.openEntry(id, { create: true });
|
|
4606
4850
|
if (!entry.ok) {
|
|
4607
4851
|
this.entries.delete(id);
|
|
4608
4852
|
throw new Error(`Could not create dataset file for ${id}: ${entry.error}`);
|
|
4609
4853
|
}
|
|
4610
|
-
|
|
4611
|
-
|
|
4854
|
+
return this.on(id, async () => {
|
|
4855
|
+
const created = await (await this.requireEntry(id)).inner.createDataset(input, { id });
|
|
4856
|
+
return this.withFileId(id, created);
|
|
4857
|
+
});
|
|
4612
4858
|
}
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
return this.withFileId(datasetId, renamed);
|
|
4859
|
+
/** Runs `op` on `datasetId`'s open entry, or throws if there's none. */
|
|
4860
|
+
withEntry(datasetId, op) {
|
|
4861
|
+
return this.on(datasetId, async () => op(await this.requireEntry(datasetId)));
|
|
4617
4862
|
}
|
|
4618
|
-
|
|
4863
|
+
renameDataset(datasetId, name) {
|
|
4864
|
+
return this.withEntry(datasetId, async (entry) => this.withFileId(datasetId, await entry.inner.renameDataset(entry.innerId, name)));
|
|
4865
|
+
}
|
|
4866
|
+
/**
|
|
4867
|
+
* Closes the file's client, then removes it and its sidecars. When
|
|
4868
|
+
* syncing, it's deleted from the cloud too, and so from every machine.
|
|
4869
|
+
*/
|
|
4619
4870
|
async deleteDataset(datasetId) {
|
|
4620
4871
|
if (!isValidDatasetId(datasetId)) return;
|
|
4621
|
-
|
|
4622
|
-
this.
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4872
|
+
await this.sync?.deleteDataset(this.id, datasetId);
|
|
4873
|
+
await this.removeLocal(datasetId);
|
|
4874
|
+
}
|
|
4875
|
+
/** Closes the file's client, then removes it and its sidecars. */
|
|
4876
|
+
removeLocal(datasetId) {
|
|
4877
|
+
return this.on(datasetId, async () => {
|
|
4878
|
+
const entry = await this.entries.get(datasetId);
|
|
4879
|
+
this.entries.delete(datasetId);
|
|
4880
|
+
this.reported.delete(datasetId);
|
|
4881
|
+
if (entry?.ok) {
|
|
4882
|
+
entry.unwatch();
|
|
4883
|
+
await entry.client.close();
|
|
4884
|
+
}
|
|
4885
|
+
const path = this.pathFor(datasetId);
|
|
4886
|
+
let removed = false;
|
|
4887
|
+
for (const file of filesOf(path)) try {
|
|
4888
|
+
await unlink(file);
|
|
4889
|
+
if (file === path) removed = true;
|
|
4890
|
+
} catch (err) {
|
|
4891
|
+
if (err?.code !== "ENOENT") throw err;
|
|
4892
|
+
}
|
|
4893
|
+
if (removed) this.emit({
|
|
4894
|
+
type: "remove",
|
|
4895
|
+
datasetId
|
|
4896
|
+
});
|
|
4639
4897
|
});
|
|
4640
4898
|
}
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
return entry.inner.addRows(entry.innerId, rows);
|
|
4899
|
+
addRows(datasetId, rows) {
|
|
4900
|
+
return this.withEntry(datasetId, (entry) => entry.inner.addRows(entry.innerId, rows));
|
|
4644
4901
|
}
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
await entry.inner.updateRows(entry.innerId, updates);
|
|
4902
|
+
updateRows(datasetId, updates) {
|
|
4903
|
+
return this.withEntry(datasetId, (entry) => entry.inner.updateRows(entry.innerId, updates));
|
|
4648
4904
|
}
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4905
|
+
deleteRows(datasetId, rowIds) {
|
|
4906
|
+
return this.on(datasetId, async () => {
|
|
4907
|
+
const entry = await this.entryFor(datasetId);
|
|
4908
|
+
if (!entry?.ok) return 0;
|
|
4909
|
+
return entry.inner.deleteRows(entry.innerId, rowIds);
|
|
4910
|
+
});
|
|
4653
4911
|
}
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
return entry.inner.addField(entry.innerId, def);
|
|
4912
|
+
addField(datasetId, def) {
|
|
4913
|
+
return this.withEntry(datasetId, (entry) => entry.inner.addField(entry.innerId, def));
|
|
4657
4914
|
}
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
return entry.inner.renameField(entry.innerId, fieldId, name);
|
|
4915
|
+
renameField(datasetId, fieldId, name) {
|
|
4916
|
+
return this.withEntry(datasetId, (entry) => entry.inner.renameField(entry.innerId, fieldId, name));
|
|
4661
4917
|
}
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
await entry.inner.deleteField(entry.innerId, fieldId);
|
|
4918
|
+
deleteField(datasetId, fieldId) {
|
|
4919
|
+
return this.withEntry(datasetId, (entry) => entry.inner.deleteField(entry.innerId, fieldId));
|
|
4665
4920
|
}
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
const updated = await entry.inner.setColumns(entry.innerId, columns, rowLabel);
|
|
4669
|
-
return this.withFileId(datasetId, updated);
|
|
4921
|
+
setColumns(datasetId, columns, rowLabel) {
|
|
4922
|
+
return this.withEntry(datasetId, async (entry) => this.withFileId(datasetId, await entry.inner.setColumns(entry.innerId, columns, rowLabel)));
|
|
4670
4923
|
}
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
return entry.inner.queryRows(entry.innerId, sql, options);
|
|
4924
|
+
queryRows(datasetId, sql, options) {
|
|
4925
|
+
return this.withEntry(datasetId, (entry) => entry.inner.queryRows(entry.innerId, sql, options));
|
|
4674
4926
|
}
|
|
4675
4927
|
/** Closes every open file. The provider reopens them on next use. */
|
|
4676
4928
|
async close() {
|
|
@@ -4718,6 +4970,12 @@ const bundledMigrations = [{
|
|
|
4718
4970
|
async function runEvalMigrations(db) {
|
|
4719
4971
|
await runMigrations(db, bundledMigrations);
|
|
4720
4972
|
}
|
|
4973
|
+
/**
|
|
4974
|
+
* The eval database's schema version, for sync: how many migrations it has.
|
|
4975
|
+
* The cloud won't let an evalution with an older schema sync a database a
|
|
4976
|
+
* newer one has.
|
|
4977
|
+
*/
|
|
4978
|
+
const EVAL_SCHEMA_VERSION = bundledMigrations.length;
|
|
4721
4979
|
//#endregion
|
|
4722
4980
|
//#region src/eval/db/schema.ts
|
|
4723
4981
|
/**
|
|
@@ -5287,6 +5545,7 @@ var TursoEvalProvider = class {
|
|
|
5287
5545
|
* the one place a real path gets involved, as `local-variation-store.ts` is
|
|
5288
5546
|
* for variations.
|
|
5289
5547
|
*/
|
|
5548
|
+
const migrate$1 = (client) => runEvalMigrations(drizzle({ client }));
|
|
5290
5549
|
/**
|
|
5291
5550
|
* Opens (creating if needed) the eval database at `path`, in a directory
|
|
5292
5551
|
* that ignores itself, so evals stay out of git without anyone editing their
|
|
@@ -5295,10 +5554,11 @@ var TursoEvalProvider = class {
|
|
|
5295
5554
|
async function openLocalEvalProvider(path, options = {}) {
|
|
5296
5555
|
await mkdirSelfIgnoring(dirname(path));
|
|
5297
5556
|
await assertSqliteFile(path);
|
|
5298
|
-
const client = await createLocalTursoClient({ path });
|
|
5299
|
-
await runEvalMigrations(drizzle({ client }));
|
|
5300
5557
|
return new TursoEvalProvider({
|
|
5301
|
-
client
|
|
5558
|
+
client: await openLocalDatabase({
|
|
5559
|
+
path,
|
|
5560
|
+
migrate: migrate$1
|
|
5561
|
+
}),
|
|
5302
5562
|
...options
|
|
5303
5563
|
});
|
|
5304
5564
|
}
|
|
@@ -5314,84 +5574,918 @@ var LocalEvalProvider = class {
|
|
|
5314
5574
|
path;
|
|
5315
5575
|
opened;
|
|
5316
5576
|
watchers = /* @__PURE__ */ new Set();
|
|
5577
|
+
sync;
|
|
5578
|
+
/** The open file, for sync. */
|
|
5579
|
+
client;
|
|
5580
|
+
/** Holds operations while sync swaps the database file. */
|
|
5581
|
+
gate = new PauseGate();
|
|
5317
5582
|
constructor(options = {}) {
|
|
5318
5583
|
this.id = options.id ?? "local-evals";
|
|
5319
5584
|
this.displayName = options.displayName ?? "Evals";
|
|
5320
5585
|
this.path = resolve(options.path ?? "./.evalution/evals/evals.db");
|
|
5321
5586
|
}
|
|
5587
|
+
/**
|
|
5588
|
+
* Syncs the database with the linked project's copy (named by this
|
|
5589
|
+
* provider's id), once `setUpProject` hands this the project's sync. Opens
|
|
5590
|
+
* (and creates) the database at once, since the project may already have
|
|
5591
|
+
* evals from another machine; a database already open starts syncing as
|
|
5592
|
+
* it is.
|
|
5593
|
+
*
|
|
5594
|
+
* @internal Not public API yet.
|
|
5595
|
+
*/
|
|
5596
|
+
_ecSetSync(workspace) {
|
|
5597
|
+
if (this.sync) return;
|
|
5598
|
+
this.sync = workspace.database({
|
|
5599
|
+
kind: "evals",
|
|
5600
|
+
provider: this.id
|
|
5601
|
+
}, EVAL_SCHEMA_VERSION);
|
|
5602
|
+
const opening = this.opened;
|
|
5603
|
+
(opening ? opening.then(() => this.startSyncing()) : this.open()).catch((err) => console.error(`Could not open the eval database at ${this.path}:`, err));
|
|
5604
|
+
}
|
|
5605
|
+
/** What syncing the file needs, once there's a sync. */
|
|
5606
|
+
syncHooks() {
|
|
5607
|
+
const database = this.sync;
|
|
5608
|
+
return database && {
|
|
5609
|
+
database,
|
|
5610
|
+
onPulled: () => this.emit({
|
|
5611
|
+
type: "update",
|
|
5612
|
+
evalId: ""
|
|
5613
|
+
}),
|
|
5614
|
+
pause: (during) => this.gate.pause(during),
|
|
5615
|
+
reopen: () => {
|
|
5616
|
+
this.opened = void 0;
|
|
5617
|
+
this.client = void 0;
|
|
5618
|
+
return this.open();
|
|
5619
|
+
}
|
|
5620
|
+
};
|
|
5621
|
+
}
|
|
5622
|
+
/** Starts syncing the open file. */
|
|
5623
|
+
async startSyncing() {
|
|
5624
|
+
const sync = this.syncHooks();
|
|
5625
|
+
const client = this.client;
|
|
5626
|
+
if (!sync || !client) return;
|
|
5627
|
+
await sync.database.prepare();
|
|
5628
|
+
await startSyncing({
|
|
5629
|
+
path: this.path,
|
|
5630
|
+
client,
|
|
5631
|
+
migrate: migrate$1,
|
|
5632
|
+
sync
|
|
5633
|
+
});
|
|
5634
|
+
}
|
|
5322
5635
|
/** The store, creating it if needed. Set synchronously, so concurrent first writes share one open. */
|
|
5323
5636
|
open() {
|
|
5324
5637
|
if (!this.opened) {
|
|
5325
|
-
|
|
5326
|
-
store.watch((event) =>
|
|
5327
|
-
for (const watcher of this.watchers) watcher(event);
|
|
5328
|
-
});
|
|
5638
|
+
const opening = this.openStore().then((store) => {
|
|
5639
|
+
store.watch((event) => this.emit(event));
|
|
5329
5640
|
return store;
|
|
5330
5641
|
});
|
|
5331
|
-
this.opened
|
|
5332
|
-
|
|
5642
|
+
this.opened = opening;
|
|
5643
|
+
opening.catch(() => {
|
|
5644
|
+
if (this.opened === opening) this.opened = void 0;
|
|
5333
5645
|
});
|
|
5334
5646
|
}
|
|
5335
5647
|
return this.opened;
|
|
5336
5648
|
}
|
|
5649
|
+
async openStore() {
|
|
5650
|
+
await mkdirSelfIgnoring(dirname(this.path));
|
|
5651
|
+
await assertSqliteFile(this.path);
|
|
5652
|
+
await this.sync?.prepare();
|
|
5653
|
+
const client = await openLocalDatabase({
|
|
5654
|
+
path: this.path,
|
|
5655
|
+
migrate: migrate$1,
|
|
5656
|
+
sync: () => this.syncHooks()
|
|
5657
|
+
});
|
|
5658
|
+
this.client = client;
|
|
5659
|
+
return new TursoEvalProvider({
|
|
5660
|
+
client,
|
|
5661
|
+
id: this.id,
|
|
5662
|
+
displayName: this.displayName
|
|
5663
|
+
});
|
|
5664
|
+
}
|
|
5665
|
+
emit(event) {
|
|
5666
|
+
for (const watcher of this.watchers) watcher(event);
|
|
5667
|
+
}
|
|
5668
|
+
/** Runs `op` on the store, creating it if needed. */
|
|
5669
|
+
withStore(op) {
|
|
5670
|
+
return this.gate.run(async () => op(await this.open()));
|
|
5671
|
+
}
|
|
5672
|
+
/** Runs `op` on the store if it exists yet, without creating it. */
|
|
5673
|
+
ifOpen(op, otherwise) {
|
|
5674
|
+
return this.gate.run(async () => {
|
|
5675
|
+
const store = await this.existing();
|
|
5676
|
+
return store ? op(store) : otherwise;
|
|
5677
|
+
});
|
|
5678
|
+
}
|
|
5679
|
+
/** `op`'s result, after telling the sync the database was written to. */
|
|
5680
|
+
async wrote(op) {
|
|
5681
|
+
const result = await op;
|
|
5682
|
+
this.sync?.noteWrite();
|
|
5683
|
+
return result;
|
|
5684
|
+
}
|
|
5337
5685
|
/** The store if it exists yet, without creating it. */
|
|
5338
5686
|
async existing() {
|
|
5339
|
-
return !!this.opened || await access(this.path).then(() => true, () => false) ? this.open() : void 0;
|
|
5687
|
+
return !!this.opened || !!this.sync || await access(this.path).then(() => true, () => false) ? this.open() : void 0;
|
|
5340
5688
|
}
|
|
5341
5689
|
watch(callback) {
|
|
5342
5690
|
this.watchers.add(callback);
|
|
5343
5691
|
return () => this.watchers.delete(callback);
|
|
5344
5692
|
}
|
|
5345
|
-
|
|
5346
|
-
return
|
|
5693
|
+
listEvals() {
|
|
5694
|
+
return this.ifOpen((store) => store.listEvals(), []);
|
|
5347
5695
|
}
|
|
5348
|
-
|
|
5349
|
-
return
|
|
5696
|
+
getEval(id) {
|
|
5697
|
+
return this.ifOpen((store) => store.getEval(id), void 0);
|
|
5350
5698
|
}
|
|
5351
|
-
|
|
5352
|
-
return (
|
|
5699
|
+
createEval(input) {
|
|
5700
|
+
return this.wrote(this.withStore((store) => store.createEval(input)));
|
|
5353
5701
|
}
|
|
5354
|
-
|
|
5355
|
-
return (
|
|
5702
|
+
updateEval(id, patch) {
|
|
5703
|
+
return this.wrote(this.withStore((store) => store.updateEval(id, patch)));
|
|
5356
5704
|
}
|
|
5357
|
-
|
|
5358
|
-
|
|
5705
|
+
deleteEval(id) {
|
|
5706
|
+
return this.wrote(this.ifOpen((store) => store.deleteEval(id), void 0));
|
|
5359
5707
|
}
|
|
5360
|
-
|
|
5361
|
-
return (
|
|
5708
|
+
createRun(evalId, run) {
|
|
5709
|
+
return this.wrote(this.withStore((store) => store.createRun(evalId, run)));
|
|
5362
5710
|
}
|
|
5363
|
-
|
|
5364
|
-
|
|
5711
|
+
finishRun(runId, status, options) {
|
|
5712
|
+
return this.wrote(this.withStore((store) => store.finishRun(runId, status, options)));
|
|
5365
5713
|
}
|
|
5366
|
-
|
|
5367
|
-
return
|
|
5714
|
+
interruptRuns() {
|
|
5715
|
+
return this.wrote(this.ifOpen((store) => store.interruptRuns(), 0));
|
|
5368
5716
|
}
|
|
5369
|
-
|
|
5370
|
-
return
|
|
5717
|
+
listRuns(evalId) {
|
|
5718
|
+
return this.ifOpen((store) => store.listRuns(evalId), []);
|
|
5371
5719
|
}
|
|
5372
|
-
|
|
5373
|
-
return
|
|
5720
|
+
getRun(runId) {
|
|
5721
|
+
return this.ifOpen((store) => store.getRun(runId), void 0);
|
|
5374
5722
|
}
|
|
5375
|
-
|
|
5376
|
-
|
|
5723
|
+
deleteRun(runId) {
|
|
5724
|
+
return this.wrote(this.ifOpen((store) => store.deleteRun(runId), void 0));
|
|
5377
5725
|
}
|
|
5378
|
-
|
|
5379
|
-
|
|
5726
|
+
recordRowResult(result) {
|
|
5727
|
+
return this.wrote(this.withStore((store) => store.recordRowResult(result)));
|
|
5380
5728
|
}
|
|
5381
|
-
|
|
5382
|
-
|
|
5729
|
+
recordCheckResults(results) {
|
|
5730
|
+
return this.wrote(this.withStore((store) => store.recordCheckResults(results)));
|
|
5383
5731
|
}
|
|
5384
|
-
|
|
5385
|
-
return
|
|
5732
|
+
listResults(runId) {
|
|
5733
|
+
return this.ifOpen((store) => store.listResults(runId), {
|
|
5386
5734
|
rows: [],
|
|
5387
5735
|
checks: []
|
|
5736
|
+
});
|
|
5737
|
+
}
|
|
5738
|
+
listTraceRuns() {
|
|
5739
|
+
return this.ifOpen((store) => store.listTraceRuns(), []);
|
|
5740
|
+
}
|
|
5741
|
+
resultsForTrace(traceProviderId, traceId) {
|
|
5742
|
+
return this.ifOpen((store) => store.resultsForTrace(traceProviderId, traceId), []);
|
|
5743
|
+
}
|
|
5744
|
+
};
|
|
5745
|
+
//#endregion
|
|
5746
|
+
//#region src/sync/database-sync.ts
|
|
5747
|
+
/**
|
|
5748
|
+
* Keeps one local database file in sync with its copy in Evalution Cloud
|
|
5749
|
+
* (PLAN §6 in the cloud repo): asks the cloud where the copy is and for a
|
|
5750
|
+
* token, then pushes after writes and pulls when asked. Nothing here can stop
|
|
5751
|
+
* the playground working: until the cloud answers, and for good if it says
|
|
5752
|
+
* no, the database is just local.
|
|
5753
|
+
*
|
|
5754
|
+
* A file syncs only once it holds the cloud database's rows: see
|
|
5755
|
+
* `local-database.ts` for how a file that doesn't is adopted.
|
|
5756
|
+
*/
|
|
5757
|
+
/** Writes come in bursts (a span start, then its end): push once they settle. */
|
|
5758
|
+
const DEFAULT_PUSH_DELAY_MS = 1e3;
|
|
5759
|
+
/** As long as `evalution` waits on the cloud before opening the browser. */
|
|
5760
|
+
const DEFAULT_PREPARE_TIMEOUT_MS = 2e3;
|
|
5761
|
+
/** How long before a token expires to get a new one. */
|
|
5762
|
+
const TOKEN_REFRESH_MARGIN_MS = 300 * 1e3;
|
|
5763
|
+
/** Answers that retrying won't change. */
|
|
5764
|
+
const PERMANENT_STATUSES = /* @__PURE__ */ new Set([
|
|
5765
|
+
401,
|
|
5766
|
+
403,
|
|
5767
|
+
404,
|
|
5768
|
+
409,
|
|
5769
|
+
410
|
|
5770
|
+
]);
|
|
5771
|
+
function describe(key) {
|
|
5772
|
+
switch (key.kind) {
|
|
5773
|
+
case "traces": return "the trace database";
|
|
5774
|
+
case "evals": return "the eval database";
|
|
5775
|
+
case "dataset": return `the dataset ${key.key}`;
|
|
5776
|
+
}
|
|
5777
|
+
}
|
|
5778
|
+
function sleep(ms) {
|
|
5779
|
+
return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
|
|
5780
|
+
}
|
|
5781
|
+
/**
|
|
5782
|
+
* One local database's link to its cloud copy. Hand {@link getCloudUrl} and
|
|
5783
|
+
* {@link getAuthToken} to `createLocalTursoClient`, after {@link prepare} so
|
|
5784
|
+
* a database that isn't on this machine yet can start from the copy
|
|
5785
|
+
* {@link currentCredentials} names. Then {@link attach} the open database.
|
|
5786
|
+
* `openLocalDatabase` does all this.
|
|
5787
|
+
*/
|
|
5788
|
+
var DatabaseSync = class {
|
|
5789
|
+
cloud;
|
|
5790
|
+
schemaVersion;
|
|
5791
|
+
pushDelayMs;
|
|
5792
|
+
prepareTimeoutMs;
|
|
5793
|
+
onStatusChange;
|
|
5794
|
+
log;
|
|
5795
|
+
/** What this database is, in messages. */
|
|
5796
|
+
label;
|
|
5797
|
+
/** Which of the project's synced databases this is. */
|
|
5798
|
+
key;
|
|
5799
|
+
credentials;
|
|
5800
|
+
requesting;
|
|
5801
|
+
stopped = false;
|
|
5802
|
+
closed = false;
|
|
5803
|
+
create = false;
|
|
5804
|
+
db;
|
|
5805
|
+
onPulled = () => {};
|
|
5806
|
+
/** The open file's links: see {@link AttachOptions.links}. */
|
|
5807
|
+
links = /* @__PURE__ */ new Set();
|
|
5808
|
+
adoptFile;
|
|
5809
|
+
adopting;
|
|
5810
|
+
/** Local writes may not have been pushed. */
|
|
5811
|
+
owesPush = false;
|
|
5812
|
+
pushTimer;
|
|
5813
|
+
/** The operation in flight: the engine runs one at a time. */
|
|
5814
|
+
chain = Promise.resolve();
|
|
5815
|
+
warned = false;
|
|
5816
|
+
/** The cloud said the database was deleted: settled once a file is attached. */
|
|
5817
|
+
deletion;
|
|
5818
|
+
onDeleted;
|
|
5819
|
+
constructor(options) {
|
|
5820
|
+
this.cloud = options.cloud;
|
|
5821
|
+
this.key = options.key;
|
|
5822
|
+
this.schemaVersion = options.schemaVersion;
|
|
5823
|
+
this.pushDelayMs = options.pushDelayMs ?? DEFAULT_PUSH_DELAY_MS;
|
|
5824
|
+
this.prepareTimeoutMs = options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
|
|
5825
|
+
this.onStatusChange = options.onStatusChange ?? (() => {});
|
|
5826
|
+
this.log = options.log ?? console;
|
|
5827
|
+
this.label = describe(options.key);
|
|
5828
|
+
}
|
|
5829
|
+
/** Whether the cloud has answered, and not said no. */
|
|
5830
|
+
get isAvailable() {
|
|
5831
|
+
return !!this.credentials && !this.stopped;
|
|
5832
|
+
}
|
|
5833
|
+
/** The cloud's answer, while it stands. */
|
|
5834
|
+
get currentCredentials() {
|
|
5835
|
+
return this.stopped ? void 0 : this.credentials;
|
|
5836
|
+
}
|
|
5837
|
+
/** Whether the open file holds the rows of the database the cloud names. */
|
|
5838
|
+
get isLinked() {
|
|
5839
|
+
const credentials = this.currentCredentials;
|
|
5840
|
+
return !!credentials && this.links.has(credentials.syncId);
|
|
5841
|
+
}
|
|
5842
|
+
/**
|
|
5843
|
+
* Whether the file is being adopted. Its provider's operations wait while
|
|
5844
|
+
* the copy takes its place, so this is shown.
|
|
5845
|
+
*/
|
|
5846
|
+
get isAdopting() {
|
|
5847
|
+
return this.adopting !== void 0;
|
|
5848
|
+
}
|
|
5849
|
+
/** Whether the cloud has said this database can't sync, so it never will this session. */
|
|
5850
|
+
get isStopped() {
|
|
5851
|
+
return this.stopped;
|
|
5852
|
+
}
|
|
5853
|
+
/**
|
|
5854
|
+
* Asks the cloud where the database is, waiting a little for the answer.
|
|
5855
|
+
* Never rejects: without an answer the database opens local-only and
|
|
5856
|
+
* switches sync on once one comes. `create` is for a dataset being made
|
|
5857
|
+
* now, whose id may be a deleted one's.
|
|
5858
|
+
*/
|
|
5859
|
+
async prepare({ create = false } = {}) {
|
|
5860
|
+
if (this.credentials || this.stopped) return;
|
|
5861
|
+
this.create = create;
|
|
5862
|
+
await Promise.race([this.requestCredentials(), sleep(this.prepareTimeoutMs)]);
|
|
5863
|
+
}
|
|
5864
|
+
/**
|
|
5865
|
+
* The cloud copy's URL once the file holds its rows; `null` keeps the
|
|
5866
|
+
* database local. Pulling into a file that doesn't would drop its rows.
|
|
5867
|
+
*/
|
|
5868
|
+
getCloudUrl = () => {
|
|
5869
|
+
const credentials = this.currentCredentials;
|
|
5870
|
+
return credentials && this.links.has(credentials.syncId) ? credentials.url : null;
|
|
5871
|
+
};
|
|
5872
|
+
/** A current token for the cloud copy. Only called by the engine once {@link getCloudUrl} has a URL. */
|
|
5873
|
+
getAuthToken = async () => {
|
|
5874
|
+
const current = this.credentials;
|
|
5875
|
+
if (current && current.expiresAt - Date.now() > TOKEN_REFRESH_MARGIN_MS) return current.token;
|
|
5876
|
+
const fresh = await this.requestCredentials();
|
|
5877
|
+
if (!fresh) throw new Error(`Evalution Cloud didn't sync ${this.label}`);
|
|
5878
|
+
return fresh.token;
|
|
5879
|
+
};
|
|
5880
|
+
/**
|
|
5881
|
+
* For `createLocalTursoClient`'s `onBootstrapFailure`: the file is made
|
|
5882
|
+
* empty instead, and adopted once the cloud answers.
|
|
5883
|
+
*/
|
|
5884
|
+
reportBootstrapFailure = (err) => {
|
|
5885
|
+
this.warnOnce(`⚠️ Couldn't fetch ${this.label} from Evalution Cloud (${err.message}); it starts empty here until the next sync.`);
|
|
5886
|
+
};
|
|
5887
|
+
/** Asks the cloud for credentials, sharing a request already in flight. */
|
|
5888
|
+
requestCredentials() {
|
|
5889
|
+
if (this.stopped) return Promise.resolve(void 0);
|
|
5890
|
+
this.requesting ??= (async () => {
|
|
5891
|
+
try {
|
|
5892
|
+
const credentials = await this.cloud.getSyncDatabase({
|
|
5893
|
+
...this.key,
|
|
5894
|
+
schemaVersion: this.schemaVersion,
|
|
5895
|
+
...this.create && { create: true }
|
|
5896
|
+
});
|
|
5897
|
+
if (!this.credentials) this.owesPush = true;
|
|
5898
|
+
this.credentials = credentials;
|
|
5899
|
+
this.create = false;
|
|
5900
|
+
this.warned = false;
|
|
5901
|
+
this.adoptIfUnlinked();
|
|
5902
|
+
return credentials;
|
|
5903
|
+
} catch (err) {
|
|
5904
|
+
this.reportCredentialsFailure(err);
|
|
5905
|
+
return;
|
|
5906
|
+
} finally {
|
|
5907
|
+
this.requesting = void 0;
|
|
5908
|
+
}
|
|
5909
|
+
})();
|
|
5910
|
+
return this.requesting;
|
|
5911
|
+
}
|
|
5912
|
+
reportCredentialsFailure(err) {
|
|
5913
|
+
const status = err instanceof EvalutionApiError ? err.status : void 0;
|
|
5914
|
+
if (status === void 0 || !PERMANENT_STATUSES.has(status)) {
|
|
5915
|
+
this.warnOnce(`⚠️ Couldn't reach Evalution Cloud to sync ${this.label} (${err.message}); retrying.`);
|
|
5916
|
+
return;
|
|
5917
|
+
}
|
|
5918
|
+
this.stopped = true;
|
|
5919
|
+
this.credentials = void 0;
|
|
5920
|
+
const { detail, body } = err;
|
|
5921
|
+
if (status === 410) {
|
|
5922
|
+
const syncId = body?.syncId;
|
|
5923
|
+
this.deletion = {
|
|
5924
|
+
...typeof syncId === "string" && { syncId },
|
|
5925
|
+
...detail && { detail }
|
|
5926
|
+
};
|
|
5927
|
+
if (this.db) this.settleDeletion();
|
|
5928
|
+
return;
|
|
5929
|
+
}
|
|
5930
|
+
const reason = status === 404 ? "your EVALUTION_API_KEY cannot access the project linked from .evalution/config.ts" : status === 401 || status === 403 ? "Evalution Cloud didn't accept EVALUTION_API_KEY" : detail ?? `the cloud answered ${status}`;
|
|
5931
|
+
this.log.warn(`⚠️ Not syncing ${this.label}: ${reason}. It stays on this machine.`);
|
|
5932
|
+
}
|
|
5933
|
+
/**
|
|
5934
|
+
* Removes the attached file if it synced with the deleted database, and
|
|
5935
|
+
* keeps it local-only if not: then it holds rows the cloud never had.
|
|
5936
|
+
*/
|
|
5937
|
+
settleDeletion() {
|
|
5938
|
+
const deletion = this.deletion;
|
|
5939
|
+
if (!deletion) return;
|
|
5940
|
+
this.deletion = void 0;
|
|
5941
|
+
const onDeleted = this.onDeleted;
|
|
5942
|
+
if (deletion.syncId && this.links.has(deletion.syncId) && onDeleted) {
|
|
5943
|
+
this.log.warn(`🗑️ Removing ${this.label} from this machine: it was deleted from the project in Evalution Cloud.`);
|
|
5944
|
+
onDeleted();
|
|
5945
|
+
return;
|
|
5946
|
+
}
|
|
5947
|
+
const detail = deletion.detail ? ` (${deletion.detail})` : "";
|
|
5948
|
+
this.log.warn(`⚠️ Not syncing ${this.label}: it was deleted from the project${detail}. It stays on this machine.`);
|
|
5949
|
+
}
|
|
5950
|
+
warnOnce(message) {
|
|
5951
|
+
if (this.warned) return;
|
|
5952
|
+
this.warned = true;
|
|
5953
|
+
this.log.warn(message);
|
|
5954
|
+
}
|
|
5955
|
+
/**
|
|
5956
|
+
* Starts syncing the open database: pulls what the cloud has, then pushes
|
|
5957
|
+
* what this machine has. A file with no link to the cloud's database is
|
|
5958
|
+
* adopted instead, once the cloud answers. Attaching the database that's
|
|
5959
|
+
* attached already does nothing.
|
|
5960
|
+
*/
|
|
5961
|
+
attach(db, { links, onPulled, adopt, onDeleted }) {
|
|
5962
|
+
if (this.db === db) return;
|
|
5963
|
+
this.db = db;
|
|
5964
|
+
this.links = new Set(links);
|
|
5965
|
+
this.onPulled = onPulled;
|
|
5966
|
+
this.adoptFile = adopt;
|
|
5967
|
+
this.onDeleted = onDeleted;
|
|
5968
|
+
this.owesPush = true;
|
|
5969
|
+
if (this.deletion) {
|
|
5970
|
+
this.settleDeletion();
|
|
5971
|
+
return;
|
|
5972
|
+
}
|
|
5973
|
+
if (this.isLinked) this.pull();
|
|
5974
|
+
else this.adoptIfUnlinked();
|
|
5975
|
+
}
|
|
5976
|
+
/** Settles once no adoption is under way. */
|
|
5977
|
+
async adopted() {
|
|
5978
|
+
await this.adopting;
|
|
5979
|
+
}
|
|
5980
|
+
/** Adopts the file if the cloud names a database it has no link to. Never rejects. */
|
|
5981
|
+
adoptIfUnlinked() {
|
|
5982
|
+
if (this.adopting) return this.adopting;
|
|
5983
|
+
const adopt = this.adoptFile;
|
|
5984
|
+
if (!adopt || !this.db || this.closed || !this.isAvailable) return Promise.resolve();
|
|
5985
|
+
if (this.isLinked) return Promise.resolve();
|
|
5986
|
+
this.adopting = (async () => {
|
|
5987
|
+
try {
|
|
5988
|
+
await adopt();
|
|
5989
|
+
} catch (err) {
|
|
5990
|
+
this.warnOnce(`⚠️ Couldn't start syncing ${this.label} with Evalution Cloud (${err.message}); retrying.`);
|
|
5991
|
+
} finally {
|
|
5992
|
+
this.adopting = void 0;
|
|
5993
|
+
this.onStatusChange();
|
|
5994
|
+
}
|
|
5995
|
+
})();
|
|
5996
|
+
this.onStatusChange();
|
|
5997
|
+
return this.adopting;
|
|
5998
|
+
}
|
|
5999
|
+
/**
|
|
6000
|
+
* Asks the cloud again for the database, as if for a new token: how a
|
|
6001
|
+
* dataset gone from the project's list is found to be deleted. Never
|
|
6002
|
+
* rejects.
|
|
6003
|
+
*/
|
|
6004
|
+
async recheck() {
|
|
6005
|
+
if (this.closed || this.stopped) return;
|
|
6006
|
+
await this.requestCredentials();
|
|
6007
|
+
}
|
|
6008
|
+
/** Says the database was written to: it's pushed once writes settle. */
|
|
6009
|
+
noteWrite() {
|
|
6010
|
+
if (!this.db || this.closed || this.stopped) return;
|
|
6011
|
+
this.owesPush = true;
|
|
6012
|
+
clearTimeout(this.pushTimer);
|
|
6013
|
+
this.pushTimer = setTimeout(() => {
|
|
6014
|
+
this.pushTimer = void 0;
|
|
6015
|
+
this.run(() => this.pushIfOwed());
|
|
6016
|
+
}, this.pushDelayMs);
|
|
6017
|
+
this.pushTimer.unref?.();
|
|
6018
|
+
}
|
|
6019
|
+
/**
|
|
6020
|
+
* Pulls the cloud's changes, and pushes this machine's if it has any.
|
|
6021
|
+
* `true` if the pull brought changes. Never rejects.
|
|
6022
|
+
*/
|
|
6023
|
+
async pull() {
|
|
6024
|
+
if (!this.db || this.closed || this.stopped) return false;
|
|
6025
|
+
if (!this.credentials && !await this.requestCredentials()) return false;
|
|
6026
|
+
if (!this.isLinked) {
|
|
6027
|
+
this.adoptIfUnlinked();
|
|
6028
|
+
return false;
|
|
6029
|
+
}
|
|
6030
|
+
return this.run(async () => {
|
|
6031
|
+
const db = this.db;
|
|
6032
|
+
if (!db) return false;
|
|
6033
|
+
const changed = await db.pull();
|
|
6034
|
+
await this.pushIfOwed();
|
|
6035
|
+
if (changed) this.onPulled();
|
|
6036
|
+
return changed;
|
|
6037
|
+
});
|
|
6038
|
+
}
|
|
6039
|
+
/** Folds the database's write-ahead log into it. Never rejects. */
|
|
6040
|
+
async checkpoint() {
|
|
6041
|
+
if (!this.db || this.closed || this.adopting) return;
|
|
6042
|
+
await this.run(async () => {
|
|
6043
|
+
await this.db?.checkpoint();
|
|
6044
|
+
});
|
|
6045
|
+
}
|
|
6046
|
+
async pushIfOwed() {
|
|
6047
|
+
if (!this.owesPush || !this.db || !this.getCloudUrl()) return void 0;
|
|
6048
|
+
this.owesPush = false;
|
|
6049
|
+
try {
|
|
6050
|
+
await this.db.push();
|
|
6051
|
+
} catch (err) {
|
|
6052
|
+
this.owesPush = true;
|
|
6053
|
+
throw err;
|
|
6054
|
+
}
|
|
6055
|
+
}
|
|
6056
|
+
/** Runs `op` after whatever is in flight, reporting a failure rather than rejecting. */
|
|
6057
|
+
run(op) {
|
|
6058
|
+
const result = this.chain.then(async () => {
|
|
6059
|
+
try {
|
|
6060
|
+
const value = await op();
|
|
6061
|
+
this.warned = false;
|
|
6062
|
+
return value;
|
|
6063
|
+
} catch (err) {
|
|
6064
|
+
this.warnOnce(`⚠️ Couldn't sync ${this.label} with Evalution Cloud (${err.message}); retrying.`);
|
|
6065
|
+
return false;
|
|
6066
|
+
}
|
|
6067
|
+
});
|
|
6068
|
+
this.chain = result;
|
|
6069
|
+
return result;
|
|
6070
|
+
}
|
|
6071
|
+
/** Settles once no operation is in flight. */
|
|
6072
|
+
async idle() {
|
|
6073
|
+
let seen;
|
|
6074
|
+
do {
|
|
6075
|
+
seen = this.chain;
|
|
6076
|
+
await seen;
|
|
6077
|
+
} while (seen !== this.chain);
|
|
6078
|
+
}
|
|
6079
|
+
/** Pushes what hasn't been, then stops syncing. */
|
|
6080
|
+
async close() {
|
|
6081
|
+
if (this.closed) return;
|
|
6082
|
+
clearTimeout(this.pushTimer);
|
|
6083
|
+
this.pushTimer = void 0;
|
|
6084
|
+
await this.adopting;
|
|
6085
|
+
if (this.db && !this.stopped) await this.run(() => this.pushIfOwed());
|
|
6086
|
+
this.closed = true;
|
|
6087
|
+
await this.idle();
|
|
6088
|
+
}
|
|
6089
|
+
};
|
|
6090
|
+
//#endregion
|
|
6091
|
+
//#region src/sync/workspace-sync.ts
|
|
6092
|
+
/**
|
|
6093
|
+
* Syncing a linked project's local databases — traces, evals, and one per
|
|
6094
|
+
* dataset — with Evalution Cloud. See PLAN §6 in the cloud repo.
|
|
6095
|
+
*/
|
|
6096
|
+
/** Often enough that another machine's work shows up while you look. */
|
|
6097
|
+
const DEFAULT_PULL_INTERVAL_MS = 3e4;
|
|
6098
|
+
/** Every five minutes, at the default interval. */
|
|
6099
|
+
const DEFAULT_CHECKPOINT_EVERY = 10;
|
|
6100
|
+
const DEFAULT_CLOSE_TIMEOUT_MS = 3e3;
|
|
6101
|
+
function keyOf({ kind, provider, key = "" }) {
|
|
6102
|
+
return JSON.stringify([
|
|
6103
|
+
kind,
|
|
6104
|
+
provider,
|
|
6105
|
+
key
|
|
6106
|
+
]);
|
|
6107
|
+
}
|
|
6108
|
+
function canSync(provider) {
|
|
6109
|
+
return typeof provider === "object" && provider !== null && typeof provider._ecSetSync === "function" && typeof provider.id === "string";
|
|
6110
|
+
}
|
|
6111
|
+
const KIND_NAMES = {
|
|
6112
|
+
traces: "trace",
|
|
6113
|
+
datasets: "dataset",
|
|
6114
|
+
evals: "eval"
|
|
6115
|
+
};
|
|
6116
|
+
/**
|
|
6117
|
+
* The project's synced databases. Each local provider, given this by
|
|
6118
|
+
* `syncProviders`, asks it for the {@link DatabaseSync} of each of its
|
|
6119
|
+
* databases; this pulls them all on an interval and when the playground asks
|
|
6120
|
+
* ({@link pullAll}, when its window regains focus).
|
|
6121
|
+
*/
|
|
6122
|
+
var WorkspaceSync = class {
|
|
6123
|
+
cloud;
|
|
6124
|
+
pullIntervalMs;
|
|
6125
|
+
checkpointEvery;
|
|
6126
|
+
closeTimeoutMs;
|
|
6127
|
+
log;
|
|
6128
|
+
databases = /* @__PURE__ */ new Map();
|
|
6129
|
+
hooks = /* @__PURE__ */ new Set();
|
|
6130
|
+
statusListeners = /* @__PURE__ */ new Set();
|
|
6131
|
+
pulling;
|
|
6132
|
+
timer;
|
|
6133
|
+
ticks = 0;
|
|
6134
|
+
constructor(options) {
|
|
6135
|
+
this.cloud = options.cloud;
|
|
6136
|
+
this.pullIntervalMs = options.pullIntervalMs ?? DEFAULT_PULL_INTERVAL_MS;
|
|
6137
|
+
this.checkpointEvery = options.checkpointEvery ?? DEFAULT_CHECKPOINT_EVERY;
|
|
6138
|
+
this.closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
|
|
6139
|
+
this.log = options.log ?? console;
|
|
6140
|
+
}
|
|
6141
|
+
/**
|
|
6142
|
+
* Gives each provider that can sync this, whether the config made it or
|
|
6143
|
+
* the defaults did: it syncs its own databases, named by its id. Of a
|
|
6144
|
+
* kind's providers that share an id, only the first syncs, since they'd
|
|
6145
|
+
* share databases.
|
|
6146
|
+
*
|
|
6147
|
+
* @internal Not public API yet, like `_ecSetSync`.
|
|
6148
|
+
*/
|
|
6149
|
+
syncProviders(providers) {
|
|
6150
|
+
const given = /* @__PURE__ */ new Set();
|
|
6151
|
+
for (const kind of Object.keys(KIND_NAMES)) {
|
|
6152
|
+
const ids = /* @__PURE__ */ new Set();
|
|
6153
|
+
for (const provider of providers[kind]) {
|
|
6154
|
+
if (!canSync(provider) || given.has(provider)) continue;
|
|
6155
|
+
if (ids.has(provider.id)) {
|
|
6156
|
+
this.log.warn(`⚠️ Two ${KIND_NAMES[kind]} providers have the id "${provider.id}"; only the first syncs. Give each its own id.`);
|
|
6157
|
+
continue;
|
|
6158
|
+
}
|
|
6159
|
+
ids.add(provider.id);
|
|
6160
|
+
given.add(provider);
|
|
6161
|
+
provider._ecSetSync(this);
|
|
6162
|
+
}
|
|
6163
|
+
}
|
|
6164
|
+
}
|
|
6165
|
+
/** The sync for one database, made on first ask. */
|
|
6166
|
+
database(key, schemaVersion) {
|
|
6167
|
+
const id = keyOf(key);
|
|
6168
|
+
let sync = this.databases.get(id);
|
|
6169
|
+
if (!sync) {
|
|
6170
|
+
sync = new DatabaseSync({
|
|
6171
|
+
cloud: this.cloud,
|
|
6172
|
+
key,
|
|
6173
|
+
schemaVersion,
|
|
6174
|
+
onStatusChange: () => {
|
|
6175
|
+
for (const listener of this.statusListeners) listener();
|
|
6176
|
+
},
|
|
6177
|
+
log: this.log
|
|
6178
|
+
});
|
|
6179
|
+
this.databases.set(id, sync);
|
|
6180
|
+
}
|
|
6181
|
+
return sync;
|
|
6182
|
+
}
|
|
6183
|
+
/**
|
|
6184
|
+
* The databases being adopted (see `local-database.ts`): their providers'
|
|
6185
|
+
* operations wait while each copy takes its file's place.
|
|
6186
|
+
*/
|
|
6187
|
+
adopting() {
|
|
6188
|
+
return Array.from(this.databases.values()).filter((db) => db.isAdopting).map((db) => db.key);
|
|
6189
|
+
}
|
|
6190
|
+
/** Runs `listener` whenever {@link adopting} changes. */
|
|
6191
|
+
onStatusChange(listener) {
|
|
6192
|
+
this.statusListeners.add(listener);
|
|
6193
|
+
return () => this.statusListeners.delete(listener);
|
|
6194
|
+
}
|
|
6195
|
+
/** Runs `hook` after each {@link pullAll}: how new datasets are found. */
|
|
6196
|
+
onPull(hook) {
|
|
6197
|
+
this.hooks.add(hook);
|
|
6198
|
+
return () => this.hooks.delete(hook);
|
|
6199
|
+
}
|
|
6200
|
+
/** Starts pulling on an interval. */
|
|
6201
|
+
start() {
|
|
6202
|
+
if (this.timer) return;
|
|
6203
|
+
this.timer = setInterval(() => {
|
|
6204
|
+
this.ticks++;
|
|
6205
|
+
this.pullAll().then(async () => {
|
|
6206
|
+
if (this.ticks % this.checkpointEvery === 0) await Promise.all(Array.from(this.databases.values(), (db) => db.checkpoint()));
|
|
6207
|
+
});
|
|
6208
|
+
}, this.pullIntervalMs);
|
|
6209
|
+
this.timer.unref?.();
|
|
6210
|
+
}
|
|
6211
|
+
/**
|
|
6212
|
+
* Pulls every database now, sharing a pull that's already under way. A
|
|
6213
|
+
* database being adopted is pulled (and so pushed) once it's adopted.
|
|
6214
|
+
* Never rejects.
|
|
6215
|
+
*/
|
|
6216
|
+
pullAll() {
|
|
6217
|
+
this.pulling ??= (async () => {
|
|
6218
|
+
try {
|
|
6219
|
+
await Promise.all(Array.from(this.databases.values(), async (db) => {
|
|
6220
|
+
await db.pull();
|
|
6221
|
+
if (!db.isAdopting) return;
|
|
6222
|
+
await db.adopted();
|
|
6223
|
+
await db.pull();
|
|
6224
|
+
}));
|
|
6225
|
+
for (const hook of this.hooks) await hook().catch((err) => this.log.warn(`⚠️ Sync failed: ${err.message}`));
|
|
6226
|
+
} finally {
|
|
6227
|
+
this.pulling = void 0;
|
|
6228
|
+
}
|
|
6229
|
+
})();
|
|
6230
|
+
return this.pulling;
|
|
6231
|
+
}
|
|
6232
|
+
/**
|
|
6233
|
+
* The ids of a dataset provider's datasets in the cloud, or `undefined` if
|
|
6234
|
+
* it can't be asked.
|
|
6235
|
+
*/
|
|
6236
|
+
async remoteDatasetIds(provider) {
|
|
6237
|
+
try {
|
|
6238
|
+
return (await this.cloud.listSyncDatabases()).filter((db) => db.kind === "dataset" && db.provider === provider).map((db) => db.key);
|
|
6239
|
+
} catch {
|
|
6240
|
+
return;
|
|
6241
|
+
}
|
|
6242
|
+
}
|
|
6243
|
+
/**
|
|
6244
|
+
* Stops syncing a provider's dataset, and forgets its sync, so a dataset
|
|
6245
|
+
* made again with its id starts afresh. For one deleted on another machine.
|
|
6246
|
+
*/
|
|
6247
|
+
async forgetDataset(provider, datasetId) {
|
|
6248
|
+
const id = keyOf({
|
|
6249
|
+
kind: "dataset",
|
|
6250
|
+
provider,
|
|
6251
|
+
key: datasetId
|
|
6252
|
+
});
|
|
6253
|
+
const sync = this.databases.get(id);
|
|
6254
|
+
this.databases.delete(id);
|
|
6255
|
+
await sync?.close();
|
|
6256
|
+
}
|
|
6257
|
+
/**
|
|
6258
|
+
* Deletes a provider's dataset from the cloud. Every other machine whose
|
|
6259
|
+
* copy synced with it removes it on its next pull. Never rejects.
|
|
6260
|
+
*/
|
|
6261
|
+
async deleteDataset(provider, datasetId) {
|
|
6262
|
+
await this.forgetDataset(provider, datasetId);
|
|
6263
|
+
const key = {
|
|
6264
|
+
kind: "dataset",
|
|
6265
|
+
provider,
|
|
6266
|
+
key: datasetId
|
|
5388
6267
|
};
|
|
6268
|
+
try {
|
|
6269
|
+
await this.cloud.deleteSyncDatabase(key);
|
|
6270
|
+
} catch (err) {
|
|
6271
|
+
if (err instanceof EvalutionApiError && err.status === 404) return;
|
|
6272
|
+
this.log.warn(`⚠️ Couldn't delete the dataset ${datasetId} from Evalution Cloud (${err.message}).`);
|
|
6273
|
+
}
|
|
5389
6274
|
}
|
|
5390
|
-
|
|
5391
|
-
|
|
6275
|
+
/** Stops pulling, and pushes what's left, waiting a few seconds at most. */
|
|
6276
|
+
async close() {
|
|
6277
|
+
clearInterval(this.timer);
|
|
6278
|
+
this.timer = void 0;
|
|
6279
|
+
await Promise.race([Promise.all(Array.from(this.databases.values(), (db) => db.close())), new Promise((resolve) => setTimeout(resolve, this.closeTimeoutMs).unref?.())]);
|
|
5392
6280
|
}
|
|
5393
|
-
|
|
5394
|
-
|
|
6281
|
+
};
|
|
6282
|
+
//#endregion
|
|
6283
|
+
//#region src/trace/cloud-trace-provider.ts
|
|
6284
|
+
/** How far back {@link CloudTraceProvider} lists traces by default: a week. */
|
|
6285
|
+
const DEFAULT_WINDOW_MS = 10080 * 60 * 1e3;
|
|
6286
|
+
/** How many traces {@link CloudTraceProvider} lists by default. */
|
|
6287
|
+
const DEFAULT_LIMIT = 200;
|
|
6288
|
+
/** How often {@link CloudTraceProvider} checks for new traces while watched. */
|
|
6289
|
+
const DEFAULT_POLL_INTERVAL_MS = 15e3;
|
|
6290
|
+
/** What the cloud's traces have: it keeps no annotations. */
|
|
6291
|
+
const NO_ANNOTATIONS = {
|
|
6292
|
+
issue: 0,
|
|
6293
|
+
good: 0,
|
|
6294
|
+
note: 0
|
|
6295
|
+
};
|
|
6296
|
+
/** What a summary shows that can change, so a poll can tell it changed. */
|
|
6297
|
+
function fingerprint(trace) {
|
|
6298
|
+
return [
|
|
6299
|
+
trace.status,
|
|
6300
|
+
trace.endTime,
|
|
6301
|
+
trace.spanCount,
|
|
6302
|
+
trace.totalTokens,
|
|
6303
|
+
trace.cost
|
|
6304
|
+
].join("|");
|
|
6305
|
+
}
|
|
6306
|
+
/**
|
|
6307
|
+
* The project's production traces, read from Evalution Cloud: what the apps
|
|
6308
|
+
* you deployed sent with an ingest key. Read-only. There's no live stream of
|
|
6309
|
+
* a trace's spans, and no annotations or SQL; {@link watch} polls the cloud
|
|
6310
|
+
* for new and changed traces instead.
|
|
6311
|
+
*
|
|
6312
|
+
* `evalution` adds one of these next to the configured trace providers when
|
|
6313
|
+
* `EVALUTION_API_KEY` is a personal key and `.evalution/config.ts` links a
|
|
6314
|
+
* project.
|
|
6315
|
+
*
|
|
6316
|
+
* It lists the most recent traces within a window (see
|
|
6317
|
+
* {@link CloudTraceProviderOptions}), since {@link TraceProvider.getAllTraces}
|
|
6318
|
+
* doesn't page. A search, filters and grouping run in the cloud, so they
|
|
6319
|
+
* reach every trace in the window, not only the most recent ones. A cloud
|
|
6320
|
+
* that can't be reached never fails the listing: the last traces it returned
|
|
6321
|
+
* are shown instead, and the failure is reported once.
|
|
6322
|
+
*/
|
|
6323
|
+
var CloudTraceProvider = class {
|
|
6324
|
+
id;
|
|
6325
|
+
displayName;
|
|
6326
|
+
description;
|
|
6327
|
+
client;
|
|
6328
|
+
environment;
|
|
6329
|
+
limit;
|
|
6330
|
+
windowMs;
|
|
6331
|
+
pollIntervalMs;
|
|
6332
|
+
log;
|
|
6333
|
+
watchers = /* @__PURE__ */ new Set();
|
|
6334
|
+
timer;
|
|
6335
|
+
/** What the last listing returned, by id, as {@link fingerprint}s. */
|
|
6336
|
+
known;
|
|
6337
|
+
lastListed = [];
|
|
6338
|
+
failing = false;
|
|
6339
|
+
constructor(options) {
|
|
6340
|
+
this.client = options.client;
|
|
6341
|
+
this.id = options.id ?? "cloud";
|
|
6342
|
+
this.displayName = options.displayName ?? "Production";
|
|
6343
|
+
this.description = options.description ?? "Traces your deployed apps sent to Evalution Cloud.";
|
|
6344
|
+
this.environment = options.environment;
|
|
6345
|
+
this.limit = options.limit ?? DEFAULT_LIMIT;
|
|
6346
|
+
this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
|
|
6347
|
+
this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
6348
|
+
this.log = options.log ?? console;
|
|
6349
|
+
}
|
|
6350
|
+
async getAllTraces(query) {
|
|
6351
|
+
try {
|
|
6352
|
+
return await this.list(query);
|
|
6353
|
+
} catch {
|
|
6354
|
+
return this.lastListed;
|
|
6355
|
+
}
|
|
6356
|
+
}
|
|
6357
|
+
/**
|
|
6358
|
+
* The groups of every trace in the window that `query` matches, counted in
|
|
6359
|
+
* the cloud. When it can't be reached, the last traces it listed are
|
|
6360
|
+
* grouped instead.
|
|
6361
|
+
*/
|
|
6362
|
+
async groupTraces(query) {
|
|
6363
|
+
try {
|
|
6364
|
+
const groups = await this.client.listTraceGroups({
|
|
6365
|
+
...this.window(),
|
|
6366
|
+
search: query.search,
|
|
6367
|
+
filters: query.filters,
|
|
6368
|
+
groupBy: query.groupBy,
|
|
6369
|
+
timeZone: query.timeZone
|
|
6370
|
+
});
|
|
6371
|
+
this.failing = false;
|
|
6372
|
+
return groups.map((group) => ({
|
|
6373
|
+
...group,
|
|
6374
|
+
summary: {
|
|
6375
|
+
...group.summary,
|
|
6376
|
+
annotationCounts: group.summary.annotationCounts ?? NO_ANNOTATIONS
|
|
6377
|
+
}
|
|
6378
|
+
}));
|
|
6379
|
+
} catch (error) {
|
|
6380
|
+
this.reportFailure(error);
|
|
6381
|
+
return groupTraceSummaries(filterTraces(this.lastListed, query), query.groupBy, query.timeZone);
|
|
6382
|
+
}
|
|
6383
|
+
}
|
|
6384
|
+
async getTrace(traceId) {
|
|
6385
|
+
const found = await this.client.getTrace(traceId);
|
|
6386
|
+
if (!found) return void 0;
|
|
6387
|
+
return {
|
|
6388
|
+
...found,
|
|
6389
|
+
trace: {
|
|
6390
|
+
...found.trace,
|
|
6391
|
+
providerId: this.id
|
|
6392
|
+
}
|
|
6393
|
+
};
|
|
6394
|
+
}
|
|
6395
|
+
/**
|
|
6396
|
+
* Polls the cloud while anyone is watching. Each new trace is an `add`,
|
|
6397
|
+
* each changed one an `update`, and one that's left the window a `remove`.
|
|
6398
|
+
*/
|
|
6399
|
+
watch(callback) {
|
|
6400
|
+
this.watchers.add(callback);
|
|
6401
|
+
if (this.watchers.size === 1) this.schedule(0);
|
|
6402
|
+
return () => {
|
|
6403
|
+
this.watchers.delete(callback);
|
|
6404
|
+
if (this.watchers.size === 0) {
|
|
6405
|
+
clearTimeout(this.timer);
|
|
6406
|
+
this.timer = void 0;
|
|
6407
|
+
this.known = void 0;
|
|
6408
|
+
}
|
|
6409
|
+
};
|
|
6410
|
+
}
|
|
6411
|
+
/** The traces every listing is of: the environment's, in the window. */
|
|
6412
|
+
window() {
|
|
6413
|
+
return {
|
|
6414
|
+
...this.environment && { environment: this.environment },
|
|
6415
|
+
from: Date.now() - this.windowMs
|
|
6416
|
+
};
|
|
6417
|
+
}
|
|
6418
|
+
reportFailure(error) {
|
|
6419
|
+
if (this.failing) return;
|
|
6420
|
+
this.log.warn(`⚠️ Couldn't list production traces from Evalution Cloud (${error.message}).`);
|
|
6421
|
+
this.failing = true;
|
|
6422
|
+
}
|
|
6423
|
+
/**
|
|
6424
|
+
* Lists the traces `query` matches. A listing of them all also notes what
|
|
6425
|
+
* changed since the last one.
|
|
6426
|
+
*/
|
|
6427
|
+
async list(query) {
|
|
6428
|
+
const everything = isEmptyTraceQuery(query);
|
|
6429
|
+
let listed;
|
|
6430
|
+
try {
|
|
6431
|
+
listed = await this.client.listTraces({
|
|
6432
|
+
...this.window(),
|
|
6433
|
+
limit: this.limit,
|
|
6434
|
+
...!everything && {
|
|
6435
|
+
search: query?.search,
|
|
6436
|
+
filters: query?.filters
|
|
6437
|
+
}
|
|
6438
|
+
});
|
|
6439
|
+
} catch (error) {
|
|
6440
|
+
this.reportFailure(error);
|
|
6441
|
+
throw error;
|
|
6442
|
+
}
|
|
6443
|
+
this.failing = false;
|
|
6444
|
+
const traces = listed.map((trace) => ({
|
|
6445
|
+
...trace,
|
|
6446
|
+
providerId: this.id,
|
|
6447
|
+
annotationCounts: trace.annotationCounts ?? NO_ANNOTATIONS
|
|
6448
|
+
}));
|
|
6449
|
+
if (everything) {
|
|
6450
|
+
this.lastListed = traces;
|
|
6451
|
+
this.noteChanges(traces);
|
|
6452
|
+
}
|
|
6453
|
+
return traces;
|
|
6454
|
+
}
|
|
6455
|
+
noteChanges(traces) {
|
|
6456
|
+
const previous = this.known;
|
|
6457
|
+
const current = new Map(traces.map((t) => [t.id, fingerprint(t)]));
|
|
6458
|
+
if (this.watchers.size > 0) this.known = current;
|
|
6459
|
+
if (!previous || this.watchers.size === 0) return;
|
|
6460
|
+
for (const [traceId, print] of current) {
|
|
6461
|
+
const before = previous.get(traceId);
|
|
6462
|
+
if (before === void 0) this.emit({
|
|
6463
|
+
type: "add",
|
|
6464
|
+
traceId
|
|
6465
|
+
});
|
|
6466
|
+
else if (before !== print) this.emit({
|
|
6467
|
+
type: "update",
|
|
6468
|
+
traceId
|
|
6469
|
+
});
|
|
6470
|
+
}
|
|
6471
|
+
for (const traceId of previous.keys()) if (!current.has(traceId)) this.emit({
|
|
6472
|
+
type: "remove",
|
|
6473
|
+
traceId
|
|
6474
|
+
});
|
|
6475
|
+
}
|
|
6476
|
+
schedule(delayMs) {
|
|
6477
|
+
this.timer = setTimeout(async () => {
|
|
6478
|
+
await this.list().catch(() => {});
|
|
6479
|
+
if (this.watchers.size > 0) this.schedule(this.pollIntervalMs);
|
|
6480
|
+
}, delayMs);
|
|
6481
|
+
this.timer.unref?.();
|
|
6482
|
+
}
|
|
6483
|
+
emit(event) {
|
|
6484
|
+
for (const watcher of this.watchers) try {
|
|
6485
|
+
watcher(event);
|
|
6486
|
+
} catch (error) {
|
|
6487
|
+
console.error("Trace watcher threw:", error);
|
|
6488
|
+
}
|
|
5395
6489
|
}
|
|
5396
6490
|
};
|
|
5397
6491
|
//#endregion
|
|
@@ -5418,6 +6512,10 @@ var BaseTraceProvider = class {
|
|
|
5418
6512
|
this.displayName = options.displayName;
|
|
5419
6513
|
this.description = options.description;
|
|
5420
6514
|
}
|
|
6515
|
+
/** Groups what {@link getAllTraces} lists for the query, in memory. */
|
|
6516
|
+
async groupTraces(query) {
|
|
6517
|
+
return groupTraceSummaries(await this.getAllTraces(query), query.groupBy, query.timeZone);
|
|
6518
|
+
}
|
|
5421
6519
|
async getTrace(traceId) {
|
|
5422
6520
|
const trace = await this.getTraceWithoutSpans(traceId);
|
|
5423
6521
|
if (!trace) return void 0;
|
|
@@ -5789,42 +6887,6 @@ const annotations = sqliteTable("annotations", {
|
|
|
5789
6887
|
createdAt: real("created_at").notNull()
|
|
5790
6888
|
}, (t) => [index("idx_annotations_trace_id").on(t.traceId)]);
|
|
5791
6889
|
//#endregion
|
|
5792
|
-
//#region src/trace/span-merge.ts
|
|
5793
|
-
/**
|
|
5794
|
-
* Merges a later snapshot of a span into an earlier one.
|
|
5795
|
-
*
|
|
5796
|
-
* OpenTelemetry reports each span twice — at `onStart` (creation-time
|
|
5797
|
-
* attributes only) and at `onEnd` (the full set) — and the two snapshots can
|
|
5798
|
-
* carry complementary data. This unions their `attributes` and `resource`,
|
|
5799
|
-
* and lets any *defined* field on `incoming` update `existing`, so nothing
|
|
5800
|
-
* recorded at start is lost when the span ends, and end-only fields (status,
|
|
5801
|
-
* timings, token usage, …) are filled in.
|
|
5802
|
-
*
|
|
5803
|
-
* An ended span is final: a snapshot of it after its end is a re-report of
|
|
5804
|
-
* what already happened (a durable workflow replaying a finished step from
|
|
5805
|
-
* its record, say), whose timings are the replay's, not the work's.
|
|
5806
|
-
*
|
|
5807
|
-
* The exception is a span that ended in error. A later report of it is the
|
|
5808
|
-
* work being retried, so it replaces the failed attempt outright: carrying
|
|
5809
|
-
* over the old `errorMessage`, status or attributes would describe a failure
|
|
5810
|
-
* the retry may not have had.
|
|
5811
|
-
*/
|
|
5812
|
-
function mergeSpans(existing, incoming) {
|
|
5813
|
-
if (existing.endTime !== void 0) return existing.status === "error" ? incoming : existing;
|
|
5814
|
-
const merged = { ...existing };
|
|
5815
|
-
for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
|
|
5816
|
-
const result = merged;
|
|
5817
|
-
if (existing.attributes || incoming.attributes) result.attributes = {
|
|
5818
|
-
...existing.attributes,
|
|
5819
|
-
...incoming.attributes
|
|
5820
|
-
};
|
|
5821
|
-
if (existing.resource || incoming.resource) result.resource = {
|
|
5822
|
-
...existing.resource,
|
|
5823
|
-
...incoming.resource
|
|
5824
|
-
};
|
|
5825
|
-
return result;
|
|
5826
|
-
}
|
|
5827
|
-
//#endregion
|
|
5828
6890
|
//#region src/trace/turso-trace-provider.ts
|
|
5829
6891
|
/**
|
|
5830
6892
|
* {@link TraceProvider} backed by a Turso/libSQL database — the local default
|
|
@@ -5990,7 +7052,7 @@ var TursoTraceProvider = class extends BaseTraceProvider {
|
|
|
5990
7052
|
this.writes = next.catch(() => {});
|
|
5991
7053
|
return next;
|
|
5992
7054
|
}
|
|
5993
|
-
async getAllTraces() {
|
|
7055
|
+
async getAllTraces(query) {
|
|
5994
7056
|
const ofRun = (value) => sql`case when json_extract(${spans.attributes}, ${`$."${CHECK_ATTRIBUTE}"`}) is null then ${value} end`;
|
|
5995
7057
|
const spanRollups = this.db.select({
|
|
5996
7058
|
traceId: spans.traceId,
|
|
@@ -6009,7 +7071,7 @@ var TursoTraceProvider = class extends BaseTraceProvider {
|
|
|
6009
7071
|
good: sql`sum(case when ${annotations.kind} = 'good' then 1 else 0 end)`.as("good"),
|
|
6010
7072
|
note: sql`sum(case when ${annotations.kind} = 'note' then 1 else 0 end)`.as("note")
|
|
6011
7073
|
}).from(annotations).groupBy(annotations.traceId).as("annotation_counts");
|
|
6012
|
-
return (await this.db.select({
|
|
7074
|
+
return filterTraces((await this.db.select({
|
|
6013
7075
|
id: traces.id,
|
|
6014
7076
|
providerId: traces.providerId,
|
|
6015
7077
|
name: traces.name,
|
|
@@ -6046,7 +7108,7 @@ var TursoTraceProvider = class extends BaseTraceProvider {
|
|
|
6046
7108
|
good: Number(row.annotGood),
|
|
6047
7109
|
note: Number(row.annotNote)
|
|
6048
7110
|
}
|
|
6049
|
-
}));
|
|
7111
|
+
})), query);
|
|
6050
7112
|
}
|
|
6051
7113
|
/**
|
|
6052
7114
|
* Runs one read-only query against the `traces`, `spans`, and
|
|
@@ -6150,6 +7212,7 @@ const DEFAULT_PATH = "./.evalution/traces/local.db";
|
|
|
6150
7212
|
function resolveDbPath(path) {
|
|
6151
7213
|
return resolve(path ?? DEFAULT_PATH);
|
|
6152
7214
|
}
|
|
7215
|
+
const migrate = (client) => runMigrations(drizzle({ client }));
|
|
6153
7216
|
/**
|
|
6154
7217
|
* A {@link TraceProvider} that lazily opens a {@link TursoTraceProvider} over
|
|
6155
7218
|
* a local SQLite file, creating the file (and its parent directory) only when
|
|
@@ -6167,6 +7230,12 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6167
7230
|
* migrations — and re-logging the same stack — once per span.
|
|
6168
7231
|
*/
|
|
6169
7232
|
openFailure;
|
|
7233
|
+
sync;
|
|
7234
|
+
/** The open file, for sync. */
|
|
7235
|
+
client;
|
|
7236
|
+
/** Holds operations while sync swaps the database file. */
|
|
7237
|
+
gate = new PauseGate();
|
|
7238
|
+
unwatchReal;
|
|
6170
7239
|
constructor(options = {}) {
|
|
6171
7240
|
super({
|
|
6172
7241
|
id: options.id ?? "local-db",
|
|
@@ -6189,6 +7258,54 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6189
7258
|
console.error(`Could not open the trace database at ${this.path} — traces will not be recorded this session. If it was created by an older version of evalution, deleting it will start a fresh one.
|
|
6190
7259
|
`, this.openFailure);
|
|
6191
7260
|
}
|
|
7261
|
+
/**
|
|
7262
|
+
* Syncs the database with the linked project's copy (named by this
|
|
7263
|
+
* provider's id), once `setUpProject` hands this the project's sync. Opens
|
|
7264
|
+
* (and creates) the database at once, since the project may already have
|
|
7265
|
+
* traces from another machine; a database already open starts syncing as
|
|
7266
|
+
* it is.
|
|
7267
|
+
*
|
|
7268
|
+
* @internal Not public API yet.
|
|
7269
|
+
*/
|
|
7270
|
+
_ecSetSync(workspace) {
|
|
7271
|
+
if (this.sync) return;
|
|
7272
|
+
this.sync = workspace.database({
|
|
7273
|
+
kind: "traces",
|
|
7274
|
+
provider: this.id
|
|
7275
|
+
}, TRACE_SCHEMA_VERSION);
|
|
7276
|
+
if (this.openFailure) return;
|
|
7277
|
+
this.creating = (this.real ? Promise.resolve(this.real) : this.creating ?? Promise.resolve(void 0)).then(async (existing) => {
|
|
7278
|
+
if (!existing) return this.open().catch((err) => this.reportOpenFailure(err));
|
|
7279
|
+
await this.startSyncing().catch((err) => console.warn(`⚠️ Couldn't start syncing ${this.path}:`, err));
|
|
7280
|
+
return existing;
|
|
7281
|
+
});
|
|
7282
|
+
}
|
|
7283
|
+
/** What syncing the file needs, once there's a sync. */
|
|
7284
|
+
syncHooks() {
|
|
7285
|
+
const database = this.sync;
|
|
7286
|
+
return database && {
|
|
7287
|
+
database,
|
|
7288
|
+
onPulled: () => this.emitChange({
|
|
7289
|
+
type: "update",
|
|
7290
|
+
traceId: ""
|
|
7291
|
+
}),
|
|
7292
|
+
pause: (during) => this.gate.pause(during),
|
|
7293
|
+
reopen: () => this.reopen()
|
|
7294
|
+
};
|
|
7295
|
+
}
|
|
7296
|
+
/** Starts syncing the open file. */
|
|
7297
|
+
async startSyncing() {
|
|
7298
|
+
const sync = this.syncHooks();
|
|
7299
|
+
const client = this.client;
|
|
7300
|
+
if (!sync || !client) return;
|
|
7301
|
+
await sync.database.prepare();
|
|
7302
|
+
await startSyncing({
|
|
7303
|
+
path: this.path,
|
|
7304
|
+
client,
|
|
7305
|
+
migrate,
|
|
7306
|
+
sync
|
|
7307
|
+
});
|
|
7308
|
+
}
|
|
6192
7309
|
/** The live provider if one exists, awaiting an already-in-flight open — but never starting one. */
|
|
6193
7310
|
async currentReal() {
|
|
6194
7311
|
return this.real ?? this.creating;
|
|
@@ -6209,8 +7326,13 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6209
7326
|
}
|
|
6210
7327
|
async open() {
|
|
6211
7328
|
await mkdirSelfIgnoring(dirname(this.path));
|
|
6212
|
-
|
|
6213
|
-
await
|
|
7329
|
+
await this.sync?.prepare();
|
|
7330
|
+
const client = await openLocalDatabase({
|
|
7331
|
+
path: this.path,
|
|
7332
|
+
migrate,
|
|
7333
|
+
sync: () => this.syncHooks()
|
|
7334
|
+
});
|
|
7335
|
+
this.client = client;
|
|
6214
7336
|
const real = new TursoTraceProvider({
|
|
6215
7337
|
client,
|
|
6216
7338
|
runQuery: (query, options) => runQueryInWorker(this.path, query, options),
|
|
@@ -6219,20 +7341,35 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6219
7341
|
description: this.description
|
|
6220
7342
|
});
|
|
6221
7343
|
this.real = real;
|
|
6222
|
-
real.watch((event) => this.emitChange(event));
|
|
7344
|
+
this.unwatchReal = real.watch((event) => this.emitChange(event));
|
|
6223
7345
|
for (const traceId of this.subscribers.keys()) this.bridgeTrace(real, traceId);
|
|
6224
7346
|
return real;
|
|
6225
7347
|
}
|
|
7348
|
+
/** Opens the database again, after sync swapped its file (and closed the old one). */
|
|
7349
|
+
reopen() {
|
|
7350
|
+
this.unwatchReal?.();
|
|
7351
|
+
for (const unsubscribe of this.bridgedTraceUnsubscribes.values()) unsubscribe();
|
|
7352
|
+
this.bridgedTraceUnsubscribes.clear();
|
|
7353
|
+
this.real = void 0;
|
|
7354
|
+
this.client = void 0;
|
|
7355
|
+
this.creating = void 0;
|
|
7356
|
+
return this.ensureReal();
|
|
7357
|
+
}
|
|
7358
|
+
/** `result`, after telling the sync the database was written to. */
|
|
7359
|
+
wrote(result) {
|
|
7360
|
+
this.sync?.noteWrite();
|
|
7361
|
+
return result;
|
|
7362
|
+
}
|
|
6226
7363
|
bridgeTrace(real, traceId) {
|
|
6227
7364
|
if (this.bridgedTraceUnsubscribes.has(traceId)) return;
|
|
6228
7365
|
const unsubscribe = real.subscribeTrace(traceId, (event) => this.emitStream(traceId, event));
|
|
6229
7366
|
this.bridgedTraceUnsubscribes.set(traceId, unsubscribe);
|
|
6230
7367
|
}
|
|
6231
|
-
|
|
6232
|
-
return (await this.currentReal())?.getAllTraces() ?? [];
|
|
7368
|
+
getAllTraces(query) {
|
|
7369
|
+
return this.gate.run(async () => (await this.currentReal())?.getAllTraces(query) ?? []);
|
|
6233
7370
|
}
|
|
6234
|
-
|
|
6235
|
-
return (await this.currentReal())?.hasTrace(traceId) ?? false;
|
|
7371
|
+
hasTrace(traceId) {
|
|
7372
|
+
return this.gate.run(async () => (await this.currentReal())?.hasTrace(traceId) ?? false);
|
|
6236
7373
|
}
|
|
6237
7374
|
getTraceWithoutSpans() {
|
|
6238
7375
|
throw new Error("should not be called");
|
|
@@ -6254,15 +7391,18 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6254
7391
|
* was never created. The `remove` event reaches this provider's watchers
|
|
6255
7392
|
* through the bridge set up when the database is opened.
|
|
6256
7393
|
*/
|
|
6257
|
-
|
|
6258
|
-
return await (await this.currentReal())?.deleteTrace(traceId) ?? false;
|
|
7394
|
+
deleteTrace(traceId) {
|
|
7395
|
+
return this.gate.run(async () => this.wrote(await (await this.currentReal())?.deleteTrace(traceId) ?? false));
|
|
6259
7396
|
}
|
|
6260
7397
|
/**
|
|
6261
7398
|
* Runs one read-only query — see {@link TursoTraceProvider.query}. With no
|
|
6262
7399
|
* database yet there is nothing to query, and opening one to find that out
|
|
6263
7400
|
* would create the file, so this says so instead.
|
|
6264
7401
|
*/
|
|
6265
|
-
|
|
7402
|
+
query(sql, options) {
|
|
7403
|
+
return this.gate.run(() => this.queryNow(sql, options));
|
|
7404
|
+
}
|
|
7405
|
+
async queryNow(sql, options) {
|
|
6266
7406
|
const real = await this.currentReal();
|
|
6267
7407
|
if (!real) throw new SqlQueryError(this.openFailure ? `The trace database at ${this.path} could not be opened: ${this.openFailure.message}` : "No traces have been recorded yet, so there is nothing to query.");
|
|
6268
7408
|
return real.query(sql, options);
|
|
@@ -6271,8 +7411,18 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6271
7411
|
getQuerySchema() {
|
|
6272
7412
|
return TRACE_QUERY_SCHEMA;
|
|
6273
7413
|
}
|
|
6274
|
-
|
|
6275
|
-
|
|
7414
|
+
/**
|
|
7415
|
+
* The trace with its spans. When syncing, a trace that isn't here is
|
|
7416
|
+
* pulled for once before it's reported missing: it may be a shared link to
|
|
7417
|
+
* one recorded on another machine.
|
|
7418
|
+
*/
|
|
7419
|
+
getTrace(traceId) {
|
|
7420
|
+
return this.gate.run(async () => {
|
|
7421
|
+
const real = await this.currentReal();
|
|
7422
|
+
const found = await real?.getTrace(traceId);
|
|
7423
|
+
if (found || !real || !this.sync) return found;
|
|
7424
|
+
return await this.sync.pull() ? real.getTrace(traceId) : void 0;
|
|
7425
|
+
});
|
|
6276
7426
|
}
|
|
6277
7427
|
subscribeTrace(traceId, callback) {
|
|
6278
7428
|
const superUnsubscribe = super.subscribeTrace(traceId, callback);
|
|
@@ -6285,18 +7435,20 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6285
7435
|
}
|
|
6286
7436
|
};
|
|
6287
7437
|
}
|
|
6288
|
-
|
|
6289
|
-
return (await this.ensureReal())?.recordSpanStart(span) ?? span;
|
|
7438
|
+
recordSpanStart(span) {
|
|
7439
|
+
return this.gate.run(async () => this.wrote(await (await this.ensureReal())?.recordSpanStart(span) ?? span));
|
|
6290
7440
|
}
|
|
6291
|
-
|
|
6292
|
-
return (await this.ensureReal())?.recordSpanEnd(span) ?? span;
|
|
7441
|
+
recordSpanEnd(span) {
|
|
7442
|
+
return this.gate.run(async () => this.wrote(await (await this.ensureReal())?.recordSpanEnd(span) ?? span));
|
|
6293
7443
|
}
|
|
6294
|
-
|
|
6295
|
-
|
|
7444
|
+
failTrace(traceId, errorMessage) {
|
|
7445
|
+
return this.gate.run(async () => {
|
|
7446
|
+
this.wrote(await (await this.ensureReal())?.failTrace(traceId, errorMessage));
|
|
7447
|
+
});
|
|
6296
7448
|
}
|
|
6297
7449
|
/** Lists every annotation on a trace, oldest first. Empty if nothing has been saved yet. */
|
|
6298
|
-
|
|
6299
|
-
return (await this.currentReal())?.listAnnotations(traceId) ?? [];
|
|
7450
|
+
listAnnotations(traceId) {
|
|
7451
|
+
return this.gate.run(async () => (await this.currentReal())?.listAnnotations(traceId) ?? []);
|
|
6300
7452
|
}
|
|
6301
7453
|
/**
|
|
6302
7454
|
* Creates a new annotation, minting its `id`/`createdAt`. Unlike span
|
|
@@ -6304,469 +7456,26 @@ var LocalDatabaseTraceProvider = class extends BaseTraceProvider {
|
|
|
6304
7456
|
* for this note to be saved, so dropping it silently would be worse than
|
|
6305
7457
|
* the error.
|
|
6306
7458
|
*/
|
|
6307
|
-
|
|
6308
|
-
|
|
6309
|
-
|
|
6310
|
-
|
|
7459
|
+
createAnnotation(input) {
|
|
7460
|
+
return this.gate.run(async () => {
|
|
7461
|
+
const real = await this.ensureReal();
|
|
7462
|
+
if (!real) throw new Error(`Cannot save an annotation: the trace database at ${this.path} could not be opened.`, { cause: this.openFailure });
|
|
7463
|
+
return this.wrote(await real.createAnnotation(input));
|
|
7464
|
+
});
|
|
6311
7465
|
}
|
|
6312
7466
|
/**
|
|
6313
7467
|
* Changes an annotation's `kind` and/or `note`. `undefined` if it doesn't
|
|
6314
7468
|
* exist — including when the database was never created.
|
|
6315
7469
|
*/
|
|
6316
|
-
|
|
6317
|
-
return (await this.currentReal())?.updateAnnotation(id, changes);
|
|
7470
|
+
updateAnnotation(id, changes) {
|
|
7471
|
+
return this.gate.run(async () => this.wrote(await (await this.currentReal())?.updateAnnotation(id, changes)));
|
|
6318
7472
|
}
|
|
6319
7473
|
/** Deletes an annotation by id. A no-op if the database was never created. */
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
};
|
|
6324
|
-
//#endregion
|
|
6325
|
-
//#region src/trace/otel-attributes.ts
|
|
6326
|
-
/**
|
|
6327
|
-
* Shared "attribute bag → evalution `Span` fields" rules for the two
|
|
6328
|
-
* provenances that carry OTel-shaped attributes: {@link OTelTraceIngestor}
|
|
6329
|
-
* and the OTLP ingestor. The third provenance, native Vercel AI SDK v7
|
|
6330
|
-
* telemetry, builds `Span`s directly and bypasses this module entirely — see
|
|
6331
|
-
* `specs/trace-workshopping.md` "Key findings that shape the approach". Not
|
|
6332
|
-
* dual-licensed: unlike `trace-types.ts`, nothing outside `src/trace/` needs
|
|
6333
|
-
* these rules, since an MIT-bundled SDK adapter has typed access to its own
|
|
6334
|
-
* events rather than an OTel attribute bag.
|
|
6335
|
-
*/
|
|
6336
|
-
const KNOWN_KINDS = [
|
|
6337
|
-
"LLM",
|
|
6338
|
-
"TOOL",
|
|
6339
|
-
"AGENT",
|
|
6340
|
-
"EMBEDDING",
|
|
6341
|
-
"DEFAULT"
|
|
6342
|
-
];
|
|
6343
|
-
/**
|
|
6344
|
-
* Reads a span's {@link SpanKind} from its attributes: the explicit
|
|
6345
|
-
* `evalution.span.type` attribute if present, otherwise a mapping from the
|
|
6346
|
-
* OTel GenAI semconv `gen_ai.operation.name`. Falls back to `'DEFAULT'`.
|
|
6347
|
-
*/
|
|
6348
|
-
function readKind(attributes) {
|
|
6349
|
-
attributes = liftTelemetryMetadata(attributes);
|
|
6350
|
-
const raw = attributes[SPAN_KIND_ATTRIBUTE] ?? otelOperationToSpanKind(attributes["gen_ai.operation.name"]);
|
|
6351
|
-
return typeof raw === "string" && KNOWN_KINDS.includes(raw) ? raw : "DEFAULT";
|
|
6352
|
-
}
|
|
6353
|
-
/** Where the Vercel AI SDK (≤ v6) records `experimental_telemetry.metadata`. */
|
|
6354
|
-
const TELEMETRY_METADATA_PREFIX = "ai.telemetry.metadata.";
|
|
6355
|
-
/** The attributes evalution itself defines, which may arrive as metadata. */
|
|
6356
|
-
const EVALUTION_ATTRIBUTES = [
|
|
6357
|
-
SPAN_KIND_ATTRIBUTE,
|
|
6358
|
-
PROMPT_NAME_ATTRIBUTE,
|
|
6359
|
-
PROMPT_ID_ATTRIBUTE,
|
|
6360
|
-
PROMPT_PROVIDER_ID_ATTRIBUTE,
|
|
6361
|
-
PROMPT_INPUTS_ATTRIBUTE,
|
|
6362
|
-
PROMPT_VERSION_ATTRIBUTE,
|
|
6363
|
-
PROMPT_VARIATION_ATTRIBUTE
|
|
6364
|
-
];
|
|
6365
|
-
/**
|
|
6366
|
-
* `attributes` with evalution's own attributes lifted out of
|
|
6367
|
-
* `ai.telemetry.metadata.*`, where the Vercel AI SDK's OTel spans (≤ v6)
|
|
6368
|
-
* record whatever `experimental_telemetry.metadata` held — which is how the
|
|
6369
|
-
* `prompts()` helper tags them. An attribute set directly wins.
|
|
6370
|
-
*/
|
|
6371
|
-
function liftTelemetryMetadata(attributes) {
|
|
6372
|
-
let lifted;
|
|
6373
|
-
for (const name of EVALUTION_ATTRIBUTES) {
|
|
6374
|
-
const value = attributes[TELEMETRY_METADATA_PREFIX + name];
|
|
6375
|
-
if (value === void 0 || attributes[name] !== void 0) continue;
|
|
6376
|
-
lifted ??= { ...attributes };
|
|
6377
|
-
lifted[name] = value;
|
|
6378
|
-
}
|
|
6379
|
-
return lifted ?? attributes;
|
|
6380
|
-
}
|
|
6381
|
-
/** Maps an OTel `SpanStatus` to evalution's `ok | error | undefined`. */
|
|
6382
|
-
function mapStatus(status) {
|
|
6383
|
-
if (status.code === SpanStatusCode.ERROR) return "error";
|
|
6384
|
-
if (status.code === SpanStatusCode.OK) return "ok";
|
|
6385
|
-
}
|
|
6386
|
-
const PARAM_ATTRIBUTES = [
|
|
6387
|
-
"gen_ai.request.temperature",
|
|
6388
|
-
"gen_ai.request.max_tokens",
|
|
6389
|
-
"gen_ai.request.top_k",
|
|
6390
|
-
"gen_ai.request.top_p",
|
|
6391
|
-
"gen_ai.request.frequency_penalty",
|
|
6392
|
-
"gen_ai.request.presence_penalty",
|
|
6393
|
-
"gen_ai.request.seed",
|
|
6394
|
-
"gen_ai.request.stop_sequences",
|
|
6395
|
-
"gen_ai.request.choice.count"
|
|
6396
|
-
];
|
|
6397
|
-
function str(v) {
|
|
6398
|
-
return typeof v === "string" ? v : void 0;
|
|
6399
|
-
}
|
|
6400
|
-
function num(v) {
|
|
6401
|
-
return typeof v === "number" ? v : void 0;
|
|
6402
|
-
}
|
|
6403
|
-
/**
|
|
6404
|
-
* The finish reason: OTel GenAI's `gen_ai.response.finish_reasons` is a string
|
|
6405
|
-
* array (one per choice, joined here), the Vercel AI SDK's
|
|
6406
|
-
* `ai.response.finishReason` a plain string.
|
|
6407
|
-
*/
|
|
6408
|
-
function readFinishReason(attributes) {
|
|
6409
|
-
const reasons = attributes["gen_ai.response.finish_reasons"];
|
|
6410
|
-
if (Array.isArray(reasons)) {
|
|
6411
|
-
const joined = reasons.filter((r) => typeof r === "string").join(", ");
|
|
6412
|
-
if (joined) return joined;
|
|
6413
|
-
}
|
|
6414
|
-
return str(reasons) || str(attributes["ai.response.finishReason"]);
|
|
6415
|
-
}
|
|
6416
|
-
/**
|
|
6417
|
-
* Converts a raw message `content` value (a string, or an array of
|
|
6418
|
-
* OTel/Vercel-style content parts) into a {@link SpanMessage.content}. Image
|
|
6419
|
-
* (and image-bearing `file`) parts are kept rather than dropped — see §A.5 in
|
|
6420
|
-
* `specs/trace-workshopping.md` — as are tool calls, tool results and reasoning.
|
|
6421
|
-
*/
|
|
6422
|
-
function toMessageContent(content) {
|
|
6423
|
-
if (typeof content === "string") return content;
|
|
6424
|
-
if (!Array.isArray(content)) return void 0;
|
|
6425
|
-
const parts = [];
|
|
6426
|
-
for (const c of content) {
|
|
6427
|
-
if (!c || typeof c !== "object") continue;
|
|
6428
|
-
const part = c;
|
|
6429
|
-
if (part.type === "text") {
|
|
6430
|
-
const text = str(part.text);
|
|
6431
|
-
if (text) parts.push({
|
|
6432
|
-
type: "text",
|
|
6433
|
-
text
|
|
6434
|
-
});
|
|
6435
|
-
} else if (part.type === "reasoning") {
|
|
6436
|
-
const text = str(part.text) ?? str(part.content);
|
|
6437
|
-
if (text) parts.push({
|
|
6438
|
-
type: "reasoning",
|
|
6439
|
-
text
|
|
6440
|
-
});
|
|
6441
|
-
} else if (part.type === "image") {
|
|
6442
|
-
const image = str(part.image) ?? str(part.url);
|
|
6443
|
-
if (image) parts.push({
|
|
6444
|
-
type: "image",
|
|
6445
|
-
image,
|
|
6446
|
-
...str(part.mediaType) && { mediaType: str(part.mediaType) }
|
|
6447
|
-
});
|
|
6448
|
-
} else if (part.type === "file") {
|
|
6449
|
-
const mediaType = str(part.mediaType);
|
|
6450
|
-
const data = str(part.data) ?? str(part.url);
|
|
6451
|
-
if (mediaType?.startsWith("image/") && data) parts.push({
|
|
6452
|
-
type: "image",
|
|
6453
|
-
image: data,
|
|
6454
|
-
mediaType
|
|
6455
|
-
});
|
|
6456
|
-
} else if (part.type === "tool-call") parts.push({
|
|
6457
|
-
type: "tool-call",
|
|
6458
|
-
toolCallId: str(part.toolCallId) ?? "",
|
|
6459
|
-
toolName: str(part.toolName) ?? "",
|
|
6460
|
-
input: part.input ?? part.args
|
|
6461
|
-
});
|
|
6462
|
-
else if (part.type === "tool-result") parts.push({
|
|
6463
|
-
type: "tool-result",
|
|
6464
|
-
toolCallId: str(part.toolCallId) ?? "",
|
|
6465
|
-
toolName: str(part.toolName) ?? "",
|
|
6466
|
-
...unwrapToolResultOutput(part.output ?? part.result)
|
|
7474
|
+
deleteAnnotation(id) {
|
|
7475
|
+
return this.gate.run(async () => {
|
|
7476
|
+
this.wrote(await (await this.currentReal())?.deleteAnnotation(id));
|
|
6467
7477
|
});
|
|
6468
7478
|
}
|
|
6469
|
-
if (parts.length === 0) return void 0;
|
|
6470
|
-
if (parts.every((p) => p.type === "text")) return parts.map((p) => p.text).join("");
|
|
6471
|
-
return parts;
|
|
6472
|
-
}
|
|
6473
|
-
/**
|
|
6474
|
-
* Parses the OTel GenAI / Vercel AI SDK `*.messages` attribute (a JSON string
|
|
6475
|
-
* holding an array of `{role, content}` objects) into {@link SpanMessage}s. A
|
|
6476
|
-
* message whose content parses to nothing renderable (e.g. only unsupported
|
|
6477
|
-
* part types) is dropped; a malformed value returns `undefined` rather than
|
|
6478
|
-
* throwing.
|
|
6479
|
-
*/
|
|
6480
|
-
function parseMessages(v) {
|
|
6481
|
-
const parsed = tryParseJson(v);
|
|
6482
|
-
if (!Array.isArray(parsed)) return void 0;
|
|
6483
|
-
return parsed.flatMap((msg) => {
|
|
6484
|
-
if (!msg || typeof msg !== "object") return [];
|
|
6485
|
-
const m = msg;
|
|
6486
|
-
const role = str(m.role) ?? "unknown";
|
|
6487
|
-
const content = toMessageContent(m.content);
|
|
6488
|
-
return content !== void 0 ? [{
|
|
6489
|
-
role,
|
|
6490
|
-
content
|
|
6491
|
-
}] : [];
|
|
6492
|
-
});
|
|
6493
|
-
}
|
|
6494
|
-
/**
|
|
6495
|
-
* Parses the OTel GenAI `gen_ai.output.messages` attribute (a JSON string
|
|
6496
|
-
* holding an array of `{content}` objects) into a flattened text summary.
|
|
6497
|
-
* Image content parts have no textual representation and are omitted here;
|
|
6498
|
-
* they are only ever surfaced via {@link parseMessages} on the input side.
|
|
6499
|
-
*/
|
|
6500
|
-
function parseOutput(v) {
|
|
6501
|
-
const parsed = tryParseJson(v);
|
|
6502
|
-
if (!Array.isArray(parsed)) return void 0;
|
|
6503
|
-
return parsed.flatMap((msg) => {
|
|
6504
|
-
if (!msg || typeof msg !== "object") return [];
|
|
6505
|
-
const content = msg.content;
|
|
6506
|
-
if (typeof content === "string") return [content];
|
|
6507
|
-
if (Array.isArray(content)) return content.filter((c) => !!c && typeof c === "object").filter((c) => c.type === "text").map((c) => str(c.text) ?? "");
|
|
6508
|
-
return [];
|
|
6509
|
-
}).join("\n");
|
|
6510
|
-
}
|
|
6511
|
-
/**
|
|
6512
|
-
* The tool calls a model response requested, from `gen_ai.output.messages`
|
|
6513
|
-
* (tool-call content parts) or the Vercel AI SDK's `ai.response.toolCalls`.
|
|
6514
|
-
* Without them a turn that only calls tools would have no output at all, as
|
|
6515
|
-
* {@link parseOutput} keeps just the text.
|
|
6516
|
-
*/
|
|
6517
|
-
function readOutputToolCalls(attributes) {
|
|
6518
|
-
const isToolCall = (p) => p.type === "tool-call";
|
|
6519
|
-
const fromMessages = (parseMessages(attributes["gen_ai.output.messages"]) ?? []).flatMap((m) => typeof m.content === "string" ? [] : m.content.filter(isToolCall));
|
|
6520
|
-
if (fromMessages.length > 0) return fromMessages;
|
|
6521
|
-
const calls = tryParseJson(attributes["ai.response.toolCalls"]);
|
|
6522
|
-
const parts = Array.isArray(calls) ? toMessageContent(calls.map((c) => ({
|
|
6523
|
-
...c,
|
|
6524
|
-
type: "tool-call"
|
|
6525
|
-
}))) : void 0;
|
|
6526
|
-
return Array.isArray(parts) ? parts.filter(isToolCall) : [];
|
|
6527
|
-
}
|
|
6528
|
-
/**
|
|
6529
|
-
* The reasoning a model response carried, from `gen_ai.output.messages`
|
|
6530
|
-
* (reasoning content parts) or the Vercel AI SDK's `ai.response.reasoning`,
|
|
6531
|
-
* which it records from 6.0.74 on.
|
|
6532
|
-
*/
|
|
6533
|
-
function readOutputReasoning(attributes) {
|
|
6534
|
-
return (parseMessages(attributes["gen_ai.output.messages"]) ?? []).flatMap((m) => typeof m.content === "string" ? [] : m.content.flatMap((p) => p.type === "reasoning" ? [p.text] : [])).join("") || str(attributes["ai.response.reasoning"]) || void 0;
|
|
6535
|
-
}
|
|
6536
|
-
/** A JSON-string attribute holding an object or array, or `undefined`. */
|
|
6537
|
-
function parseJsonObject(v) {
|
|
6538
|
-
const parsed = tryParseJson(v);
|
|
6539
|
-
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
6540
|
-
}
|
|
6541
|
-
/**
|
|
6542
|
-
* An `experimental_evaluate` span's input and output, from `@ai-sdk/otel`'s
|
|
6543
|
-
* `ai.evaluation.*` attributes (recorded only when its integration is built
|
|
6544
|
-
* with `experimental_evaluation: true`). The answers carry the confidence a
|
|
6545
|
-
* provider reported in `ai.response.providerMetadata`, as a native-telemetry
|
|
6546
|
-
* span's do.
|
|
6547
|
-
*/
|
|
6548
|
-
function readEvaluation(attributes) {
|
|
6549
|
-
const state = tryParseJson(attributes["ai.evaluation.state"]);
|
|
6550
|
-
const questions = tryParseJson(attributes["ai.evaluation.questions"]);
|
|
6551
|
-
const answers = tryParseJson(attributes["ai.evaluation.answers"]);
|
|
6552
|
-
return {
|
|
6553
|
-
...(state !== void 0 || questions !== void 0) && { input: {
|
|
6554
|
-
state,
|
|
6555
|
-
questions
|
|
6556
|
-
} },
|
|
6557
|
-
...answers !== void 0 && { output: answersWithConfidence(answers, tryParseJson(attributes["ai.response.providerMetadata"])) }
|
|
6558
|
-
};
|
|
6559
|
-
}
|
|
6560
|
-
/**
|
|
6561
|
-
* Reads {@link LLMSpanDetails} out of an OTel-shaped attribute bag, following
|
|
6562
|
-
* both the OTel GenAI semantic conventions and the Vercel AI SDK's own
|
|
6563
|
-
* attribute names. Returns `undefined` when nothing LLM-related is present,
|
|
6564
|
-
* so callers can decide whether to attach `llm` to a `Span` at all.
|
|
6565
|
-
*/
|
|
6566
|
-
function readLLM(attributes) {
|
|
6567
|
-
const provider = str(attributes["gen_ai.provider.name"]) ?? str(attributes["gen_ai.system"]);
|
|
6568
|
-
const model = str(attributes["gen_ai.response.model"]) ?? str(attributes["gen_ai.request.model"]);
|
|
6569
|
-
const finishReason = readFinishReason(attributes);
|
|
6570
|
-
const promptTokens = num(attributes["gen_ai.usage.input_tokens"]) ?? num(attributes["gen_ai.usage.prompt_tokens"]) ?? num(attributes["ai.usage.promptTokens"]);
|
|
6571
|
-
const completionTokens = num(attributes["gen_ai.usage.output_tokens"]) ?? num(attributes["gen_ai.usage.completion_tokens"]) ?? num(attributes["ai.usage.completionTokens"]);
|
|
6572
|
-
const cacheReadTokens = num(attributes["gen_ai.usage.cache_read.input_tokens"]);
|
|
6573
|
-
const cacheWriteTokens = num(attributes["gen_ai.usage.cache_creation.input_tokens"]);
|
|
6574
|
-
const jsonInput = parseJsonObject(attributes["evalution.llm.input"]);
|
|
6575
|
-
const messages = parseMessages(attributes["gen_ai.input.messages"] ?? attributes["ai.prompt.messages"]);
|
|
6576
|
-
const evaluation = readEvaluation(attributes);
|
|
6577
|
-
const input = jsonInput ?? evaluation.input ?? messages;
|
|
6578
|
-
const jsonOutput = tryParseJson(attributes["evalution.llm.output"]) ?? evaluation.output;
|
|
6579
|
-
const text = parseOutput(attributes["gen_ai.output.messages"]) ?? str(attributes["ai.response.text"]);
|
|
6580
|
-
const toolCalls = readOutputToolCalls(attributes);
|
|
6581
|
-
const reasoning = readOutputReasoning(attributes);
|
|
6582
|
-
const output = jsonOutput !== void 0 ? jsonOutput : text !== void 0 && attributes["gen_ai.output.type"] === "json" ? parseJsonOrRaw(text) : toolCalls.length > 0 ? toolCallingOutput(text, toolCalls) : text;
|
|
6583
|
-
const paramEntries = PARAM_ATTRIBUTES.map((key) => [key.replace("gen_ai.request.", ""), attributes[key]]).filter(([, v]) => v !== void 0);
|
|
6584
|
-
const modelParameters = paramEntries.length > 0 ? Object.fromEntries(paramEntries) : void 0;
|
|
6585
|
-
const totalTokens = promptTokens !== void 0 && completionTokens !== void 0 ? promptTokens + completionTokens : void 0;
|
|
6586
|
-
if (!provider && !model && !finishReason && !promptTokens && !completionTokens && !input && (output === void 0 || output === "") && !reasoning && !modelParameters) return;
|
|
6587
|
-
return {
|
|
6588
|
-
...provider && { provider },
|
|
6589
|
-
...model && { model },
|
|
6590
|
-
...finishReason && { finishReason },
|
|
6591
|
-
...input && { input },
|
|
6592
|
-
...output !== void 0 && output !== "" && { output },
|
|
6593
|
-
...reasoning && { reasoning },
|
|
6594
|
-
...promptTokens !== void 0 && { promptTokens },
|
|
6595
|
-
...completionTokens !== void 0 && { completionTokens },
|
|
6596
|
-
...totalTokens !== void 0 && { totalTokens },
|
|
6597
|
-
...cacheReadTokens !== void 0 && { cacheReadTokens },
|
|
6598
|
-
...cacheWriteTokens !== void 0 && { cacheWriteTokens },
|
|
6599
|
-
...modelParameters && { modelParameters }
|
|
6600
|
-
};
|
|
6601
|
-
}
|
|
6602
|
-
/**
|
|
6603
|
-
* Read back the inputs a run was launched with.
|
|
6604
|
-
*
|
|
6605
|
-
* OTel attribute values are primitives, so the inputs travel as a JSON string
|
|
6606
|
-
* (see `getPromptSpanAttributes`) and are parsed here. Without this the OTel
|
|
6607
|
-
* path could record inputs but never replay them — it was write-only.
|
|
6608
|
-
*
|
|
6609
|
-
* A malformed value is dropped rather than thrown on: a span carrying an
|
|
6610
|
-
* unreadable attribute is still a perfectly good span.
|
|
6611
|
-
*/
|
|
6612
|
-
function readInputs(attributes) {
|
|
6613
|
-
const raw = str(attributes[PROMPT_INPUTS_ATTRIBUTE]);
|
|
6614
|
-
if (!raw) return {};
|
|
6615
|
-
const parsed = tryParseJson(raw);
|
|
6616
|
-
if (!parsed || typeof parsed !== "object") return {};
|
|
6617
|
-
return {
|
|
6618
|
-
...Array.isArray(parsed.functionInputs) && { functionInputs: parsed.functionInputs },
|
|
6619
|
-
...parsed.executeInputs && typeof parsed.executeInputs === "object" ? { executeInputs: parsed.executeInputs } : {},
|
|
6620
|
-
...parsed.resources && typeof parsed.resources === "object" && !Array.isArray(parsed.resources) ? { resources: parsed.resources } : {},
|
|
6621
|
-
...Array.isArray(parsed.parameterDefinitions) && { parameterDefinitions: parsed.parameterDefinitions },
|
|
6622
|
-
...Array.isArray(parsed.executeParameterDefinitions) && { executeParameterDefinitions: parsed.executeParameterDefinitions }
|
|
6623
|
-
};
|
|
6624
|
-
}
|
|
6625
|
-
/**
|
|
6626
|
-
* Reads {@link ToolSpanDetails} out of an attribute bag, following the tool
|
|
6627
|
-
* -call attribute names of the SDKs/instrumentation libraries a `TOOL` span
|
|
6628
|
-
* is likely to come from: the Vercel AI SDK (`ai.toolCall.*`), Traceloop
|
|
6629
|
-
* (`traceloop.entity.*`, gated on `traceloop.span.kind === 'tool'`), and the
|
|
6630
|
-
* draft OTel GenAI tool-call semconv (`gen_ai.tool.*`). `input`/`output` are
|
|
6631
|
-
* JSON-parsed when they arrive as a JSON string, else kept as-is. Returns
|
|
6632
|
-
* `undefined` when no tool name is present.
|
|
6633
|
-
*/
|
|
6634
|
-
function readTool(attributes) {
|
|
6635
|
-
const name = str(attributes["gen_ai.tool.name"]) ?? str(attributes["ai.toolCall.name"]) ?? str(attributes["tool.name"]) ?? (attributes["traceloop.span.kind"] === "tool" ? str(attributes["traceloop.entity.name"]) : void 0);
|
|
6636
|
-
if (!name) return void 0;
|
|
6637
|
-
const input = parseJsonOrRaw(attributes["gen_ai.tool.call.arguments"] ?? attributes["ai.toolCall.args"] ?? attributes["tool.input"] ?? attributes["traceloop.entity.input"]);
|
|
6638
|
-
const outputRaw = attributes["gen_ai.tool.call.result"] ?? attributes["ai.toolCall.result"] ?? attributes["tool.output"] ?? attributes["traceloop.entity.output"];
|
|
6639
|
-
const toolCallId = str(attributes["gen_ai.tool.call.id"]) ?? str(attributes["ai.toolCall.id"]);
|
|
6640
|
-
return {
|
|
6641
|
-
toolName: name,
|
|
6642
|
-
...toolCallId && { toolCallId },
|
|
6643
|
-
input,
|
|
6644
|
-
...outputRaw !== void 0 && { output: parseJsonOrRaw(outputRaw) }
|
|
6645
|
-
};
|
|
6646
|
-
}
|
|
6647
|
-
/**
|
|
6648
|
-
* Reads {@link LLMSpanDetails} ({@link readLLM}), {@link ToolSpanDetails}
|
|
6649
|
-
* ({@link readTool}), and the prompt reference (`evalution.prompt.id` /
|
|
6650
|
-
* `evalution.prompt.provider.id` / `evalution.prompt.version` /
|
|
6651
|
-
* `evalution.prompt.variation` / the inputs {@link readInputs} parses) out
|
|
6652
|
-
* of an attribute bag, ready to spread onto a `Span`.
|
|
6653
|
-
*/
|
|
6654
|
-
function llmAndPrompt(attributes) {
|
|
6655
|
-
attributes = liftTelemetryMetadata(attributes);
|
|
6656
|
-
const llm = readLLM(attributes);
|
|
6657
|
-
const tool = readTool(attributes);
|
|
6658
|
-
const id = str(attributes[PROMPT_ID_ATTRIBUTE]);
|
|
6659
|
-
const providerId = str(attributes[PROMPT_PROVIDER_ID_ATTRIBUTE]);
|
|
6660
|
-
const version = str(attributes[PROMPT_VERSION_ATTRIBUTE]);
|
|
6661
|
-
const variation = str(attributes[PROMPT_VARIATION_ATTRIBUTE]);
|
|
6662
|
-
const prompt = id ? {
|
|
6663
|
-
id,
|
|
6664
|
-
...providerId && { providerId },
|
|
6665
|
-
...readInputs(attributes),
|
|
6666
|
-
...version && { version },
|
|
6667
|
-
...variation && { variation }
|
|
6668
|
-
} : void 0;
|
|
6669
|
-
return {
|
|
6670
|
-
...llm && { llm },
|
|
6671
|
-
...tool && { tool },
|
|
6672
|
-
...prompt && { prompt }
|
|
6673
|
-
};
|
|
6674
|
-
}
|
|
6675
|
-
//#endregion
|
|
6676
|
-
//#region src/trace/otlp-trace-ingestor.ts
|
|
6677
|
-
function eventErrorMessage(events) {
|
|
6678
|
-
for (const event of events ?? []) {
|
|
6679
|
-
const message = event.attributes["exception.message"] ?? event.attributes.message;
|
|
6680
|
-
if (typeof message === "string" && message) return message;
|
|
6681
|
-
}
|
|
6682
|
-
}
|
|
6683
|
-
/**
|
|
6684
|
-
* Orders a batch so a span's parent (when present in the same batch) is
|
|
6685
|
-
* always ingested before it — a cheap approximation of a topological sort by
|
|
6686
|
-
* BFS depth, not a strict one. `BaseTraceProvider` already tolerates
|
|
6687
|
-
* out-of-order arrival (provisional trace creation + `mergeSpans` on
|
|
6688
|
-
* re-delivery), so this is purely an optimisation, not a correctness
|
|
6689
|
-
* requirement.
|
|
6690
|
-
*/
|
|
6691
|
-
function sortParentsFirst(spans) {
|
|
6692
|
-
const bySpanId = new Map(spans.map((s) => [s.spanId, s]));
|
|
6693
|
-
const depths = /* @__PURE__ */ new Map();
|
|
6694
|
-
function depthOf(span, path) {
|
|
6695
|
-
const cached = depths.get(span.spanId);
|
|
6696
|
-
if (cached !== void 0) return cached;
|
|
6697
|
-
const parent = span.parentSpanId ? bySpanId.get(span.parentSpanId) : void 0;
|
|
6698
|
-
const depth = !parent || path.has(span.spanId) ? 0 : depthOf(parent, new Set(path).add(span.spanId)) + 1;
|
|
6699
|
-
depths.set(span.spanId, depth);
|
|
6700
|
-
return depth;
|
|
6701
|
-
}
|
|
6702
|
-
return [...spans].sort((a, b) => depthOf(a, /* @__PURE__ */ new Set()) - depthOf(b, /* @__PURE__ */ new Set()) || a.startTimeMs - b.startTimeMs);
|
|
6703
|
-
}
|
|
6704
|
-
function toSpan(s) {
|
|
6705
|
-
return {
|
|
6706
|
-
id: s.spanId,
|
|
6707
|
-
traceId: s.traceId,
|
|
6708
|
-
parentId: s.parentSpanId,
|
|
6709
|
-
name: s.name,
|
|
6710
|
-
kind: readKind(s.attributes),
|
|
6711
|
-
startTime: s.startTimeMs,
|
|
6712
|
-
...s.endTimeMs !== void 0 && { endTime: s.endTimeMs },
|
|
6713
|
-
...s.statusCode !== "unset" && { status: s.statusCode },
|
|
6714
|
-
...s.statusCode === "error" && { errorMessage: s.statusMessage || eventErrorMessage(s.events) },
|
|
6715
|
-
attributes: s.attributes,
|
|
6716
|
-
...s.resource && { resource: s.resource },
|
|
6717
|
-
...llmAndPrompt(s.attributes)
|
|
6718
|
-
};
|
|
6719
|
-
}
|
|
6720
|
-
/**
|
|
6721
|
-
* {@link TraceIngestor} populated by spans received over OTLP (protobuf or
|
|
6722
|
-
* JSON) from an external app or collector — see `specs/trace-workshopping.md`
|
|
6723
|
-
* §A. Unlike {@link OTelTraceIngestor}, OTLP arrives as a batch of already
|
|
6724
|
-
* -finished (or explicitly in-flight) spans with no separate start/end
|
|
6725
|
-
* lifecycle of its own.
|
|
6726
|
-
*
|
|
6727
|
-
* `BaseTraceProvider.recordSpanEnd` only *finalizes* a trace that
|
|
6728
|
-
* `recordSpanStart` already created (root detection happens there), so
|
|
6729
|
-
* {@link ingest} always calls `recordSpanStart` first — for an
|
|
6730
|
-
* already-ended span this immediately followed by `recordSpanEnd` — mirroring
|
|
6731
|
-
* the start-then-end pair {@link OTelTraceIngestor} fires for every real OTel
|
|
6732
|
-
* span. A span OTLP exported with no end time gets only the start.
|
|
6733
|
-
*
|
|
6734
|
-
* Storage-agnostic like every ingestor: works against `MemoryTraceProvider`
|
|
6735
|
-
* in tests and any other `TraceSink` in production with no code change.
|
|
6736
|
-
*/
|
|
6737
|
-
var OtlpTraceIngestor = class extends BaseTraceIngestor {
|
|
6738
|
-
/** Ingests one OTLP export batch, already normalized by `./otlp/normalize.ts`. */
|
|
6739
|
-
async ingest(spans) {
|
|
6740
|
-
for (const normalized of sortParentsFirst(spans)) {
|
|
6741
|
-
const span = toSpan(normalized);
|
|
6742
|
-
await this.recordSpanStart(span);
|
|
6743
|
-
if (span.endTime !== void 0) await this.recordSpanEnd(span);
|
|
6744
|
-
}
|
|
6745
|
-
}
|
|
6746
|
-
};
|
|
6747
|
-
//#endregion
|
|
6748
|
-
//#region src/trace/trace-event-ingestor.ts
|
|
6749
|
-
/**
|
|
6750
|
-
* {@link TraceIngestor} populated by the {@link TraceSinkEvent}s an app's
|
|
6751
|
-
* `HttpTraceSink` sends to this server. The events are already normalized
|
|
6752
|
-
* {@link TraceSink} calls, so this just replays them, in order, on its own
|
|
6753
|
-
* sinks.
|
|
6754
|
-
*/
|
|
6755
|
-
var TraceEventIngestor = class extends BaseTraceIngestor {
|
|
6756
|
-
/** Records one batch of events, in order. */
|
|
6757
|
-
async ingest(events) {
|
|
6758
|
-
for (const event of events) switch (event.type) {
|
|
6759
|
-
case "span-start":
|
|
6760
|
-
await this.recordSpanStart(event.span);
|
|
6761
|
-
break;
|
|
6762
|
-
case "span-end":
|
|
6763
|
-
await this.recordSpanEnd(event.span);
|
|
6764
|
-
break;
|
|
6765
|
-
case "trace-fail":
|
|
6766
|
-
await this.failTrace(event.traceId, event.errorMessage);
|
|
6767
|
-
break;
|
|
6768
|
-
}
|
|
6769
|
-
}
|
|
6770
7479
|
};
|
|
6771
7480
|
//#endregion
|
|
6772
|
-
export {
|
|
7481
|
+
export { InputResolutionError as $, isPathColumn as A, emptyCounts as B, promptIdOf as C, registerFreshImportHook as Ct, DEFAULT_QUERY_TIMEOUT_MS as D, DEFAULT_MAX_QUERY_ROWS as E, DatasetNotFoundError as F, parseBinding as G, evalProblems as H, DatasetValidationError as I, primitiveBase as J, parseCell as K, DEFAULT_EVAL_CONCURRENCY as L, parseColumnSpecs as M, pathField as N, SqlQueryError as O, pathInstance as P, portableDef as Q, EvalRunRefusedError as R, VariationConflictError as S, isFreshImportHookRegistered as St, EvalNotFoundError as T, InvalidCellError as U, CheckScopeTraceSink as V, fitsPrimitiveBase as W, fieldsForPrompt as X, PRIMITIVE_FIELD_TYPES as Y, isPrimitiveFieldType as Z, assertSqliteFile as _, isStandardSchema as _t, CloudTraceProvider as a, collectInputSlots as at, rollupSpans as b, isVariationLoaderHookRegistered as bt, LocalEvalProvider as c, instanceNames as ct, runEvalMigrations as d, DEFAULT_PLAYGROUND_INCLUDE_PATTERNS as dt, runPrompt as et, LocalDirectoryDatasetProvider as f, ResourceRegistry as ft, runMigrations as g, isResource as gt, MIGRATIONS_TABLE as h, isValidInstanceName as ht, BaseTraceProvider as i, stampReceipts as it, parseColumnPath as j, InvalidColumnPathError as k, openLocalEvalProvider as l, namedBindings as lt, runDatasetMigrations as m, resourceParameterNames as mt, TursoTraceProvider as n, resolveExecutionInput as nt, WorkspaceSync as o, findInputCycle as ot, TursoDatasetProvider as p, parameterDetails as pt, parseResources as q, TRACE_QUERY_SCHEMA as r, resolveExecutionInputs as rt, DatabaseSync as s, inputReferenceProblems as st, LocalDatabaseTraceProvider as t, matchSourcesToSlots as tt, TursoEvalProvider as u, DEFAULT_PLAYGROUND_IGNORE_PATTERNS as ut, createLocalTursoClient as v, resource as vt, toPromptRef as w, registerBundlerResolutionFallback as wt, datasetQueryColumns as x, registerVariationLoaderHook as xt, mkdirSelfIgnoring as y, LocalFileProvider as yt, EvalRunner as z };
|