@selvajs/server 0.2.0-beta.2 → 0.2.0-beta.3

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.
Files changed (72) hide show
  1. package/dist/compute/__tests__/client-cache.test.js +18 -0
  2. package/dist/compute/__tests__/client-cache.test.js.map +1 -1
  3. package/dist/compute/__tests__/definition-byte-cache.test.d.ts +2 -0
  4. package/dist/compute/__tests__/definition-byte-cache.test.d.ts.map +1 -0
  5. package/dist/compute/__tests__/definition-byte-cache.test.js +107 -0
  6. package/dist/compute/__tests__/definition-byte-cache.test.js.map +1 -0
  7. package/dist/compute/__tests__/solve-cache.test.d.ts +13 -0
  8. package/dist/compute/__tests__/solve-cache.test.d.ts.map +1 -0
  9. package/dist/compute/__tests__/solve-cache.test.js +234 -0
  10. package/dist/compute/__tests__/solve-cache.test.js.map +1 -0
  11. package/dist/compute/__tests__/solve-pipeline.test.js +267 -2
  12. package/dist/compute/__tests__/solve-pipeline.test.js.map +1 -1
  13. package/dist/compute/client-cache.d.ts +12 -0
  14. package/dist/compute/client-cache.d.ts.map +1 -1
  15. package/dist/compute/client-cache.js +12 -3
  16. package/dist/compute/client-cache.js.map +1 -1
  17. package/dist/compute/definition-byte-cache.d.ts +85 -0
  18. package/dist/compute/definition-byte-cache.d.ts.map +1 -0
  19. package/dist/compute/definition-byte-cache.js +110 -0
  20. package/dist/compute/definition-byte-cache.js.map +1 -0
  21. package/dist/compute/index.d.ts +7 -2
  22. package/dist/compute/index.d.ts.map +1 -1
  23. package/dist/compute/index.js +6 -1
  24. package/dist/compute/index.js.map +1 -1
  25. package/dist/compute/limits.d.ts +52 -0
  26. package/dist/compute/limits.d.ts.map +1 -1
  27. package/dist/compute/limits.js +33 -1
  28. package/dist/compute/limits.js.map +1 -1
  29. package/dist/compute/memory-solve-cache.d.ts +58 -0
  30. package/dist/compute/memory-solve-cache.d.ts.map +1 -0
  31. package/dist/compute/memory-solve-cache.js +0 -0
  32. package/dist/compute/memory-solve-cache.js.map +1 -0
  33. package/dist/compute/solve-cache-envelope.d.ts +53 -0
  34. package/dist/compute/solve-cache-envelope.d.ts.map +1 -0
  35. package/dist/compute/solve-cache-envelope.js +66 -0
  36. package/dist/compute/solve-cache-envelope.js.map +1 -0
  37. package/dist/compute/solve-cache-key.d.ts +65 -0
  38. package/dist/compute/solve-cache-key.d.ts.map +1 -0
  39. package/dist/compute/solve-cache-key.js +50 -0
  40. package/dist/compute/solve-cache-key.js.map +1 -0
  41. package/dist/compute/solve-cache-single-flight.d.ts +35 -0
  42. package/dist/compute/solve-cache-single-flight.d.ts.map +1 -0
  43. package/dist/compute/solve-cache-single-flight.js +48 -0
  44. package/dist/compute/solve-cache-single-flight.js.map +1 -0
  45. package/dist/compute/solve-pipeline.d.ts +71 -8
  46. package/dist/compute/solve-pipeline.d.ts.map +1 -1
  47. package/dist/compute/solve-pipeline.js +178 -8
  48. package/dist/compute/solve-pipeline.js.map +1 -1
  49. package/dist/definitions/__tests__/definition-service.test.d.ts +14 -0
  50. package/dist/definitions/__tests__/definition-service.test.d.ts.map +1 -0
  51. package/dist/definitions/__tests__/definition-service.test.js +95 -0
  52. package/dist/definitions/__tests__/definition-service.test.js.map +1 -0
  53. package/dist/definitions/definition-service.d.ts +1 -1
  54. package/dist/definitions/definition-service.d.ts.map +1 -1
  55. package/dist/definitions/definition-service.js +8 -4
  56. package/dist/definitions/definition-service.js.map +1 -1
  57. package/package.json +2 -2
  58. package/src/compute/__tests__/client-cache.test.ts +20 -0
  59. package/src/compute/__tests__/definition-byte-cache.test.ts +129 -0
  60. package/src/compute/__tests__/solve-cache.test.ts +268 -0
  61. package/src/compute/__tests__/solve-pipeline.test.ts +320 -1
  62. package/src/compute/client-cache.ts +24 -3
  63. package/src/compute/definition-byte-cache.ts +168 -0
  64. package/src/compute/index.ts +34 -0
  65. package/src/compute/limits.ts +79 -1
  66. package/src/compute/memory-solve-cache.ts +0 -0
  67. package/src/compute/solve-cache-envelope.ts +98 -0
  68. package/src/compute/solve-cache-key.ts +85 -0
  69. package/src/compute/solve-cache-single-flight.ts +59 -0
  70. package/src/compute/solve-pipeline.ts +279 -15
  71. package/src/definitions/__tests__/definition-service.test.ts +131 -0
  72. package/src/definitions/definition-service.ts +8 -4
@@ -38,6 +38,23 @@ export function readPositiveInt(env: EnvRecord, name: string, fallback: number):
38
38
  return Math.floor(parsed);
39
39
  }
40
40
 
41
+ /**
42
+ * Parse a non-negative integer env value — like {@link readPositiveInt} but `0`
43
+ * is a valid value (used by knobs where `0` means "disable", e.g. a cache
44
+ * budget). Returns `fallback` when absent, and warns + falls back when present
45
+ * but not a finite non-negative number.
46
+ */
47
+ export function readNonNegativeInt(env: EnvRecord, name: string, fallback: number): number {
48
+ const raw = env[name];
49
+ if (!raw) return fallback;
50
+ const parsed = Number(raw);
51
+ if (!Number.isFinite(parsed) || parsed < 0) {
52
+ console.warn(`[selva] Invalid ${name}=${raw}, falling back to ${fallback}`);
53
+ return fallback;
54
+ }
55
+ return Math.floor(parsed);
56
+ }
57
+
41
58
  /**
42
59
  * Parse a boolean env flag. Accepts `true/1/yes/on` (case-insensitive) as true
43
60
  * and `false/0/no/off` as false; any other / absent value falls back.
@@ -125,6 +142,51 @@ export interface ComputeLimits {
125
142
  * app instances each apply their own cap.
126
143
  */
127
144
  computeMaxConcurrentSolves: number;
145
+ /**
146
+ * Backpressure — max solves allowed to WAIT in the per-server FIFO queue (i.e.
147
+ * excluding the `computeMaxConcurrentSolves` already in flight). A solve that
148
+ * arrives to a full queue is shed immediately (scheduler `QUEUE_FULL`, mapped
149
+ * to HTTP 503 + `Retry-After`) instead of piling up unbounded. `0` = unbounded
150
+ * (the pre-shedding default): the queue grows without limit, matching prior
151
+ * behavior. Size it to roughly 2–3× `computeMaxConcurrentSolves` once the
152
+ * Rhino pool's real capacity is known — shedding fast beats a hung request.
153
+ */
154
+ computeMaxQueueDepth: number;
155
+ /**
156
+ * Backpressure — longest (ms) a solve may sit QUEUED before it starts
157
+ * executing; still-waiting past this it's shed (scheduler `QUEUE_TIMEOUT` →
158
+ * HTTP 503 + `Retry-After`) rather than burning compute on a stale request.
159
+ * Bounds tail latency: the scheduler's `timeoutMs` clock starts at execution,
160
+ * so without this a solve's total wait is unbounded and invisible. `0` = no
161
+ * queue deadline (the default). A sensible tuned value is ≈ `maxSolveDurationMs`.
162
+ */
163
+ computeQueueWaitMs: number;
164
+ /**
165
+ * Total-byte budget (bytes) for the in-process definition-byte cache keyed on
166
+ * immutable version id. A warm entry lets a solve skip `storage.get` entirely,
167
+ * and a pointer-known solve never loads bytes at all. `0` disables the cache
168
+ * (every solve re-reads storage). Sized as a total-byte LRU because definitions
169
+ * span KB→hundreds of MB; env value is MB, converted here.
170
+ */
171
+ computeDefinitionByteCacheBytes: number;
172
+ /**
173
+ * Default per-definition entry quota for the durable L2 solve cache (H1), used
174
+ * when a definition's `solveCacheLimit` is absent (inherit). A definition may
175
+ * override this; `0` on the definition turns caching off for it. This global
176
+ * default `0` means the L2 is effectively off until an operator sets a quota —
177
+ * safe because the memory backend also ships only under
178
+ * `SOLVE_CACHE_PROVIDER=memory`. Counts, not bytes: authors think in "how many
179
+ * solves to remember"; the byte backstop below is the operator's memory guard.
180
+ */
181
+ solveCacheDefaultMaxEntries: number;
182
+ /**
183
+ * Global byte backstop (bytes) across ALL definitions' L2 entries, evicted
184
+ * global-LRU regardless of per-definition counts. Entries range KB→100s of MB,
185
+ * so a count quota alone can't bound memory. `0` disables the backstop (rely on
186
+ * per-definition counts only — not recommended in the memory backend). Env value
187
+ * is MB, converted here. On Redis this moves to `maxmemory allkeys-lru`.
188
+ */
189
+ solveCacheMaxTotalBytes: number;
128
190
  }
129
191
 
130
192
  /**
@@ -154,6 +216,22 @@ export function resolveComputeLimits(env: EnvRecord): ComputeLimits {
154
216
  computeServerCachesolve: readBool(env, 'COMPUTE_SERVER_CACHESOLVE', true),
155
217
  computeCacheErroredSolves: readBool(env, 'COMPUTE_CACHE_ERRORED_SOLVES', false),
156
218
  // 4 matches rhino.compute's default --childcount; tune to the actual VM.
157
- computeMaxConcurrentSolves: readPositiveInt(env, 'COMPUTE_MAX_CONCURRENT', 4)
219
+ computeMaxConcurrentSolves: readPositiveInt(env, 'COMPUTE_MAX_CONCURRENT', 4),
220
+ // Both 0 (unbounded / no deadline) by default — nothing sheds until an
221
+ // operator who's measured their pool opts in. readNonNegativeInt so `0` is a
222
+ // valid "disabled" value, not treated as invalid.
223
+ computeMaxQueueDepth: readNonNegativeInt(env, 'COMPUTE_MAX_QUEUE_DEPTH', 0),
224
+ computeQueueWaitMs: readNonNegativeInt(env, 'COMPUTE_QUEUE_WAIT_MS', 0),
225
+ // Env is MB; 0 disables. Default 256 MB holds a handful of typical
226
+ // definitions warm without pinning gigabytes. readNonNegativeInt so `0`
227
+ // (disable) is honored rather than treated as invalid.
228
+ computeDefinitionByteCacheBytes:
229
+ readNonNegativeInt(env, 'COMPUTE_DEFINITION_BYTE_CACHE_MB', 256) * MB,
230
+ // L2 durable solve cache (H1). Default per-definition quota 0 = inherit-to-off
231
+ // until an operator opts in; the memory backend also only mounts under
232
+ // SOLVE_CACHE_PROVIDER=memory, so nothing caches by accident. Byte backstop
233
+ // 512 MB caps total heap use across all definitions (env is MB).
234
+ solveCacheDefaultMaxEntries: readNonNegativeInt(env, 'SOLVE_CACHE_DEFAULT_MAX_ENTRIES', 0),
235
+ solveCacheMaxTotalBytes: readNonNegativeInt(env, 'SOLVE_CACHE_MAX_TOTAL_MB', 512) * MB
158
236
  };
159
237
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * L2 cache entry format (R6). An entry is the gzipped response body plus a tiny
3
+ * metadata header, so a hit is near-CPU-free: no `JSON.stringify`, no re-solve —
4
+ * gzip clients get the stored bytes verbatim, and the header carries just enough
5
+ * to rebuild the `ok` outcome (error/warning counts for the metric, uncompressed
6
+ * length for the `Content-Length` on a gunzip fallback).
7
+ *
8
+ * Wire layout (opaque to the `ISolveResultCache` backend, which sees only bytes):
9
+ *
10
+ * [ 4 bytes: header length N, big-endian uint32 ]
11
+ * [ N bytes: UTF-8 JSON EnvelopeHeader ]
12
+ * [ rest: gzipped JSON response body ]
13
+ *
14
+ * The `algo` echo (M3) is already stripped at the source in the package's
15
+ * `runSolve`, so the body never carries the base64 definition — entries stay
16
+ * small without a strip step here.
17
+ */
18
+
19
+ import { gunzipSync } from 'node:zlib';
20
+
21
+ /** Metadata stored beside the gzipped body. Small; parsed on every hit. */
22
+ export interface EnvelopeHeader {
23
+ /** Grasshopper runtime error count, for the solve metric. */
24
+ errorCount: number;
25
+ /** Grasshopper runtime warning count, for the solve metric. */
26
+ warningCount: number;
27
+ /** Uncompressed JSON body length in bytes (Content-Length for a gunzip fallback). */
28
+ serializedBytes: number;
29
+ /**
30
+ * SHA-256 hex of the canonical input preimage (H2 defense-in-depth). A hit
31
+ * verifies this equals the requesting key's hash before serving — a wide-hash
32
+ * collision that produced the same storage key still can't serve the wrong
33
+ * geometry.
34
+ */
35
+ inputHash: string;
36
+ }
37
+
38
+ /**
39
+ * Encode a cache entry from the gzipped body + header. The body MUST already be
40
+ * gzipped (the pipeline gzips before storing so every hit serves compressed
41
+ * bytes; a rare non-gzip client gunzips on read).
42
+ */
43
+ export function encodeSolveCacheEntry(header: EnvelopeHeader, gzippedBody: Uint8Array): Uint8Array {
44
+ const headerJson = Buffer.from(JSON.stringify(header), 'utf8');
45
+ const out = Buffer.allocUnsafe(4 + headerJson.byteLength + gzippedBody.byteLength);
46
+ out.writeUInt32BE(headerJson.byteLength, 0);
47
+ headerJson.copy(out, 4);
48
+ Buffer.from(gzippedBody.buffer, gzippedBody.byteOffset, gzippedBody.byteLength).copy(
49
+ out,
50
+ 4 + headerJson.byteLength
51
+ );
52
+ return out;
53
+ }
54
+
55
+ /** A decoded entry: the parsed header + the still-gzipped body slice. */
56
+ export interface DecodedSolveCacheEntry {
57
+ header: EnvelopeHeader;
58
+ gzippedBody: Uint8Array;
59
+ }
60
+
61
+ /**
62
+ * Decode a cache entry. Returns `null` on any malformed input (truncated, bad
63
+ * length prefix, non-JSON header) — a corrupt entry is treated as a miss, never
64
+ * an error, matching the best-effort cache contract.
65
+ */
66
+ export function decodeSolveCacheEntry(bytes: Uint8Array): DecodedSolveCacheEntry | null {
67
+ if (bytes.byteLength < 4) return null;
68
+ const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
69
+ const headerLen = buf.readUInt32BE(0);
70
+ const headerEnd = 4 + headerLen;
71
+ if (headerEnd > buf.byteLength) return null;
72
+ let header: EnvelopeHeader;
73
+ try {
74
+ header = JSON.parse(buf.toString('utf8', 4, headerEnd)) as EnvelopeHeader;
75
+ } catch {
76
+ return null;
77
+ }
78
+ if (
79
+ typeof header?.errorCount !== 'number' ||
80
+ typeof header?.warningCount !== 'number' ||
81
+ typeof header?.serializedBytes !== 'number' ||
82
+ typeof header?.inputHash !== 'string'
83
+ ) {
84
+ return null;
85
+ }
86
+ // Slice (view, no copy) of the gzipped remainder.
87
+ const gzippedBody = new Uint8Array(
88
+ bytes.buffer,
89
+ bytes.byteOffset + headerEnd,
90
+ bytes.byteLength - headerEnd
91
+ );
92
+ return { header, gzippedBody };
93
+ }
94
+
95
+ /** Gunzip a stored body back to the JSON string, for a non-gzip client (rare). */
96
+ export function gunzipEntryBody(gzippedBody: Uint8Array): string {
97
+ return gunzipSync(gzippedBody).toString('utf8');
98
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Durable L2 cache-key derivation (H2 / R8 / R13).
3
+ *
4
+ * The in-process L1 cache keys on a 32-bit FNV hash — fine for a 20-entry Map,
5
+ * unsafe for a durable, cross-user cache where a collision serves user A's
6
+ * geometry to user B (CONTEXT.md L92–97 records exactly this bug shipping once).
7
+ * So the L2 key is a wide SHA-256 hash, and the entry stores the canonical
8
+ * preimage so a hit can compare it byte-for-byte (defense-in-depth).
9
+ *
10
+ * What goes into the key:
11
+ * - The **transformed** input tree (R13) — the exact tree handed to the
12
+ * scheduler, canonicalized with the package's exported `stableStringify` so
13
+ * the L2 key parity-matches the L1 canonicalization path.
14
+ * - A **config subset** (R8): everything OTHER than definition+inputs that
15
+ * changes a solve's result — model units, tolerances, `dataversion`, the
16
+ * compute contract version, and (when known) the Rhino server identity. A
17
+ * durable key of `(versionId, inputHash)` alone would collide across
18
+ * differing server configs or Rhino versions.
19
+ *
20
+ * `versionId`, `definitionId`, and `orgId` are NOT hashed in here — they're
21
+ * separate parts of the {@link SolveCacheKey} tuple so the backend can scope its
22
+ * keyspace (per-definition quota, per-org isolation) without unpacking the hash.
23
+ */
24
+
25
+ import { createHash } from 'node:crypto';
26
+ import { stableStringify } from '@selvajs/compute';
27
+ import { COMPUTE_CONTRACT_VERSION } from './solve-pipeline.js';
28
+
29
+ /**
30
+ * Solve-affecting configuration folded into the key alongside the input tree.
31
+ * Every field here is something that, if it changed, would legitimately change
32
+ * the solve output for the SAME definition + inputs. Assemble it from the app's
33
+ * resolved solve config; unset fields are simply absent from the canonical form.
34
+ */
35
+ export interface SolveCacheConfigSubset {
36
+ /** Rhino model unit system, if the app pins one (else the definition/server default). */
37
+ modelUnits?: string;
38
+ /** Absolute tolerance, if pinned. */
39
+ absoluteTolerance?: number;
40
+ /** Angle tolerance, if pinned. */
41
+ angleTolerance?: number;
42
+ /** Grasshopper `dataversion` / data-tree schema version, if pinned. */
43
+ dataVersion?: number | string;
44
+ /**
45
+ * Compute-server identity (id or URL). Folds in because two servers can run
46
+ * different Rhino/plugin versions that yield different geometry for the same
47
+ * inputs. Optional — omit for a single-pool deployment where it's constant.
48
+ */
49
+ computeServerId?: string;
50
+ }
51
+
52
+ /** The canonical preimage + its SHA-256 digest. Store both in the L2 entry header. */
53
+ export interface SolveCacheInputKey {
54
+ /** The canonical string that was hashed (for hit-time byte comparison). */
55
+ canonical: string;
56
+ /** SHA-256 hex of {@link canonical} — the `inputKey` part of the storage key. */
57
+ hash: string;
58
+ }
59
+
60
+ /**
61
+ * Derive the durable `inputKey` from the transformed input tree and the solve
62
+ * config subset. Deterministic and stable across processes/instances: the same
63
+ * tree + config always produce the same hash, which is what lets a shared cache
64
+ * hit across app instances.
65
+ *
66
+ * @param transformedTree the tree AFTER `transformInputParameter`/`TreeBuilder`
67
+ * (R13) — the exact object handed to `scheduler.solve`.
68
+ * @param config solve-affecting config (R8); `COMPUTE_CONTRACT_VERSION` is folded
69
+ * in automatically so a wire-contract bump invalidates old entries for free.
70
+ */
71
+ export function deriveSolveCacheInputKey(
72
+ transformedTree: unknown,
73
+ config: SolveCacheConfigSubset
74
+ ): SolveCacheInputKey {
75
+ // stableStringify sorts keys deterministically — same content, same string,
76
+ // regardless of property insertion order. Tag each part so a value can't shift
77
+ // across the tree/config boundary and collide (e.g. tree "]" meeting config "[").
78
+ const canonical = stableStringify({
79
+ v: COMPUTE_CONTRACT_VERSION,
80
+ tree: transformedTree,
81
+ config
82
+ });
83
+ const hash = createHash('sha256').update(canonical).digest('hex');
84
+ return { canonical, hash };
85
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * In-process single-flight (R4) — dogpile protection above the L2 cache.
3
+ *
4
+ * N identical live solves arriving while the first is still running would each
5
+ * enqueue and each hit Rhino (the scheduler has no in-flight coalescing, and
6
+ * Rhino's `cachesolve` still costs a round trip per repeat). The classic cold-key
7
+ * stampede: a hot public definition + a deploy = a thundering herd onto compute.
8
+ *
9
+ * This coalesces them: the first caller for a key runs the work; concurrent
10
+ * callers for the SAME key await the same promise and share its result. Once the
11
+ * work settles (resolve OR reject), the key is released so the next request runs
12
+ * fresh — the map never retains a settled entry, so it can't serve a stale
13
+ * result or leak memory.
14
+ *
15
+ * It sits ABOVE the `ISolveResultCache` interface (in-process, per app instance).
16
+ * A cross-instance lease (Redis `SET NX`) is a later backend capability; this is
17
+ * the free first slice that covers the common same-instance burst.
18
+ *
19
+ * Correctness note: the shared promise resolves to ONE value for all waiters, so
20
+ * the wrapped work must return an immutable / independently-serializable result
21
+ * (the solve pipeline returns a fresh envelope object — safe to share by
22
+ * reference here because the app serializes it per response).
23
+ */
24
+
25
+ export interface SolveCacheSingleFlight {
26
+ /**
27
+ * Run `work` under `key`, coalescing concurrent identical calls. The first
28
+ * caller executes; overlapping callers for the same key await the same promise.
29
+ * The key is freed as soon as the promise settles (success or failure).
30
+ */
31
+ run<T>(key: string, work: () => Promise<T>): Promise<T>;
32
+ /** Number of keys currently in flight (observability / tests). */
33
+ inFlight(): number;
34
+ }
35
+
36
+ export function createSolveCacheSingleFlight(): SolveCacheSingleFlight {
37
+ const inflight = new Map<string, Promise<unknown>>();
38
+
39
+ return {
40
+ run<T>(key: string, work: () => Promise<T>): Promise<T> {
41
+ const existing = inflight.get(key);
42
+ if (existing) return existing as Promise<T>;
43
+
44
+ // `.finally` releases the key on both settle paths. Start the work inside
45
+ // the promise chain so a synchronous throw in `work` still rejects the
46
+ // shared promise (and still frees the key) rather than escaping.
47
+ const p = (async () => work())().finally(() => {
48
+ // Only delete if it's still OUR promise — a key freed and re-taken by a
49
+ // later caller must not be clobbered.
50
+ if (inflight.get(key) === p) inflight.delete(key);
51
+ });
52
+ inflight.set(key, p);
53
+ return p;
54
+ },
55
+ inFlight(): number {
56
+ return inflight.size;
57
+ }
58
+ };
59
+ }