@tpsdev-ai/flair 0.59.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/SECURITY.md +36 -0
- package/config.yaml +12 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +991 -248
- package/dist/commands/agent.js +224 -43
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +592 -146
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +97 -35
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +24 -0
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1168 -326
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +76 -12
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +110 -39
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +20 -11
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +4 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +5 -2
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +12 -6
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
|
@@ -62,7 +62,7 @@ export const MAX_AUTH_HEADER_LEN = 4096;
|
|
|
62
62
|
* agentId / nonce / signature never contains whitespace, so excluding it is
|
|
63
63
|
* behavior-preserving for well-formed headers.
|
|
64
64
|
*/
|
|
65
|
-
export const TPS_ED25519_HEADER_RE = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)
|
|
65
|
+
export const TPS_ED25519_HEADER_RE = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)$/i;
|
|
66
66
|
/**
|
|
67
67
|
* Parse a TPS-Ed25519 `Authorization` header value into its fields, or return
|
|
68
68
|
* null if it is over `MAX_AUTH_HEADER_LEN` or doesn't match the grammar.
|
|
@@ -2,32 +2,52 @@
|
|
|
2
2
|
* embedding-space-guard.ts — the QUERY-TIME vector-space uniformity gate
|
|
3
3
|
* (embedding-provider-seam design §3, slice 1; K&S-final).
|
|
4
4
|
*
|
|
5
|
-
* ─── The bug this closes ────────────────────────────────────────────────────
|
|
6
|
-
* There is NO query-time embedding-space guard today. Search cosines a query
|
|
7
|
-
* against every stored vector regardless of its `embeddingModel` stamp;
|
|
8
|
-
* Harper's `cosineDistance` silently zero-pads a mismatched-dimension vector
|
|
9
|
-
* and returns a garbage score instead of throwing (same-dims/different-space
|
|
10
|
-
* is silent garbage too), and `health.ts` only *warns*. So a mixed-space
|
|
11
|
-
* corpus — the transient state during ANY re-embed / model change — serves
|
|
12
|
-
* silently-wrong recall. This module makes a mismatched-space cosine
|
|
13
|
-
* impossible by construction on BOTH runtime cosine legs (recall + write-time
|
|
14
|
-
* dedup), the load-bearing safety piece Kern made a condition of sign-off.
|
|
15
|
-
*
|
|
16
5
|
* ─── Shape ──────────────────────────────────────────────────────────────────
|
|
17
6
|
* A PURE core (`normalizeStamp` / `currentSpaceRawForms` / `isUniformStampSet`
|
|
18
7
|
* — Harper-free, unit-testable directly, same discipline as dedup.ts / bm25.ts)
|
|
19
8
|
* plus a boot-computed + write-maintained "corpus uniform in the current space"
|
|
20
9
|
* LATCH so the gate costs ~nothing per query:
|
|
21
|
-
* - boot pre-warm scans the
|
|
22
|
-
* same convention as embeddings-boot.ts / migration-boot.ts);
|
|
10
|
+
* - boot pre-warm scans the corpus;
|
|
23
11
|
* - a write persisting a FOREIGN stamp (federation / replication / an
|
|
24
12
|
* explicit-stamp PUT) trips the latch immediately, no rescan;
|
|
25
13
|
* - while tripped, a consult re-verifies at most once per RECHECK_MS, so a
|
|
26
14
|
* completed re-embed REOPENS the gate automatically (any re-embed path —
|
|
27
15
|
* the boot migration OR a live `flair reembed`), with no cross-process
|
|
28
16
|
* signal needed.
|
|
29
|
-
* Both runtime legs consult the SAME
|
|
30
|
-
*
|
|
17
|
+
* Both runtime legs consult the SAME verdict — the recall leg through
|
|
18
|
+
* `embeddingSpaceVerdict()`, the dedup leg through `isEmbeddingSpaceUniform()`,
|
|
19
|
+
* both over one consult — a single chokepoint (like `prefixesEnabled()`), never
|
|
20
|
+
* scattered per-call-site checks.
|
|
21
|
+
*
|
|
22
|
+
* ─── Unknown verdict = FAIL CLOSED (flair#2530) ──────────────────────────────
|
|
23
|
+
* A scan can be pending (before the first scan completes) or fail (a boot race,
|
|
24
|
+
* a transient read error). The verdict is then UNKNOWN, and "unknown" is NOT
|
|
25
|
+
* "known uniform". The scan counts rows with any array or typed array, empty
|
|
26
|
+
* included, whose `embeddingModel` is not a trusted current-space stamp — an
|
|
27
|
+
* absent stamp, the hash-fallback marker `hash-512d`, or a foreign model — using
|
|
28
|
+
* the vector query's raw stamp comparison,
|
|
29
|
+
* and a count above zero makes the verdict non-uniform (flair#2573 slice 1).
|
|
30
|
+
* Raw operations-API inserts are uncovered until a rescan; the latch observes
|
|
31
|
+
* only writes that call `noteWriteStamp`. Caller-supplied vector bytes remain
|
|
32
|
+
* unverified (slice 2). Every non-uniform state — pending
|
|
33
|
+
* (`unverified`), a failed scan (`scan-failed`), a non-current stamp observed
|
|
34
|
+
* by a scan or a foreign write (`mixed`), or an excluded array or typed array
|
|
35
|
+
* (`excluded`) — makes a consumer take its
|
|
36
|
+
* MIXED-space path: when a query embedding is available outside bm25-only
|
|
37
|
+
* mode, the recall leg drops it and
|
|
38
|
+
* serves keyword-only results (none, for a request with no query text; for
|
|
39
|
+
* `explain: true`, a plan with no embedding leg) with a state-named warning;
|
|
40
|
+
* the dedup leg no-ops. A recall in bm25-only mode (which never uses a query
|
|
41
|
+
* embedding, so a supplied one is dropped unconsulted) or after a failed
|
|
42
|
+
* embedding generation never consults the guard and has no state to name. A
|
|
43
|
+
* consult never blocks on an in-flight scan to obtain a verdict; it fails closed now,
|
|
44
|
+
* and only a later SUCCESSFUL scan that finds the stamps uniform reopens the
|
|
45
|
+
* gate. An error from the scan's table lookup or corpus read is classified into
|
|
46
|
+
* a bounded reason (never row content); a published failure is logged once per
|
|
47
|
+
* reason, a refused stale one each time it is refused; the consult schedule
|
|
48
|
+
* retries unchanged. A known foreign stamp outranks a scan error: the state is
|
|
49
|
+
* `mixed` whenever one is known, and `reason` keeps the last failed scan's
|
|
50
|
+
* error whether that scan failed before or after the stamp was seen.
|
|
31
51
|
*
|
|
32
52
|
* ─── Why the harper import is deferred ──────────────────────────────────────
|
|
33
53
|
* `harper` is dynamic-imported inside the scan only (never a top-level import)
|
|
@@ -38,15 +58,9 @@
|
|
|
38
58
|
* carry no harper dependency at all.
|
|
39
59
|
*/
|
|
40
60
|
import { EMBEDDING_ENGINE, getModelId } from "./embeddings-provider.js";
|
|
61
|
+
import { TEST_FAULT_INJECTION_ENV, txnPausePoint } from "./txn-pause-point.js";
|
|
41
62
|
// ─── Pure core (Harper-free) ────────────────────────────────────────────────
|
|
42
|
-
/**
|
|
43
|
-
* Stamps that denote "no real vector space" and so never contribute to the
|
|
44
|
-
* uniformity set: an absent/empty stamp, and the legacy `hash-512d`
|
|
45
|
-
* hash-fallback marker (a row with no genuine model embedding). A missing or
|
|
46
|
-
* empty stored embedding cosines to a safe 0 (retrieval-core / dedup both
|
|
47
|
-
* guard `Array.isArray(embedding) ? … : []`), never a cross-space garbage
|
|
48
|
-
* score, so excluding these mirrors health.ts's own `realModels` filter.
|
|
49
|
-
*/
|
|
63
|
+
/** Stamps omitted from the space-bearing stamp set. */
|
|
50
64
|
const NON_SPACE_STAMPS = new Set(["hash-512d"]);
|
|
51
65
|
/**
|
|
52
66
|
* Canonicalize an `embeddingModel` stamp to its ENGINE-QUALIFIED space id, or
|
|
@@ -93,11 +107,17 @@ export function isCurrentSpaceStamp(stamp, currentModelId) {
|
|
|
93
107
|
const n = normalizeStamp(stamp);
|
|
94
108
|
return n !== null && n === normalizeStamp(currentModelId);
|
|
95
109
|
}
|
|
96
|
-
/**
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
110
|
+
/** Pure: is the stored value an array or typed array, including an empty one? */
|
|
111
|
+
export function hasStoredVector(value) {
|
|
112
|
+
return Array.isArray(value) || (ArrayBuffer.isView(value) && !(value instanceof DataView));
|
|
113
|
+
}
|
|
114
|
+
/** Pure: is `stamp` EXACTLY one of the current space's raw forms? The vector
|
|
115
|
+
* query's stamp condition matches raw strings (Harper `equals`), so this is the
|
|
116
|
+
* comparison the admission rule makes — no trimming. */
|
|
117
|
+
export function isTrustedRawStamp(stamp, currentModelId) {
|
|
118
|
+
return typeof stamp === "string" && currentSpaceRawForms(currentModelId).includes(stamp);
|
|
119
|
+
}
|
|
120
|
+
/** Pure: are all space-bearing stamps current? An empty set is uniform. */
|
|
101
121
|
export function isUniformStampSet(distinctStamps, currentModelId) {
|
|
102
122
|
const current = normalizeStamp(currentModelId);
|
|
103
123
|
for (const raw of distinctStamps) {
|
|
@@ -120,37 +140,135 @@ let _modelIdGetter = getModelId;
|
|
|
120
140
|
// than caching a verdict we could not compute.
|
|
121
141
|
let _uniform = undefined;
|
|
122
142
|
let _activeStamps = []; // normalized, capped — for the degrade diagnostic only
|
|
143
|
+
// Rows with an array or typed array (empty included) and no trusted stamp in
|
|
144
|
+
// the last published scan. Null means no count has published.
|
|
145
|
+
let _excluded = null;
|
|
146
|
+
// Guard-notified writes that may change the count invalidate in-flight scans.
|
|
147
|
+
// A scan publishing a fresh count clears this flag.
|
|
148
|
+
let _excludedStale = false;
|
|
123
149
|
let _lastScanAt = 0;
|
|
124
150
|
let _scanning;
|
|
151
|
+
// flair#2481 — foreign-space write notes invalidate an in-flight scan's verdict.
|
|
152
|
+
let _writeEpoch = 0;
|
|
153
|
+
// flair#2530 — the bounded reason of the last failed scan that published, or
|
|
154
|
+
// null; cleared when a later scan publishes a verdict. It reads as
|
|
155
|
+
// `scan-failed` unless a foreign stamp is known, which makes the state `mixed`
|
|
156
|
+
// (see guardSnapshot).
|
|
157
|
+
let _lastScanError = null;
|
|
158
|
+
const _loggedScanErrorReasons = new Set();
|
|
159
|
+
// flair#2508 — scan-start ordering. `recomputeLatch()` (the boot pre-warm's
|
|
160
|
+
// path) runs `scan()` directly, bypassing the `_scanning` latch that serialises
|
|
161
|
+
// consult scans, so two scans can overlap; a scan that started earlier and
|
|
162
|
+
// finishes later must not overwrite the verdict of one that started later.
|
|
163
|
+
// Each scan takes the next sequence number when it begins and publishes only
|
|
164
|
+
// when no scan that started later has already published. When the write epoch
|
|
165
|
+
// is unchanged, a refused publish is named and writes nothing; when a foreign
|
|
166
|
+
// write changed the epoch, the #2481 check in scan() runs first instead,
|
|
167
|
+
// discarding the scan and resetting the retry timer. A failed scan's error
|
|
168
|
+
// (flair#2530) is an outcome under the same rules: it publishes, and advances
|
|
169
|
+
// `_publishedScanSeq`, only when no later-started scan has published.
|
|
170
|
+
let _scanSeq = 0;
|
|
171
|
+
let _publishedScanSeq = 0;
|
|
125
172
|
// While the latch is TRIPPED, re-verify at most this often, so a completed
|
|
126
173
|
// re-embed reopens the gate without paying a scan on every degraded query.
|
|
127
174
|
// The happy (uniform) path never scans here at all — it returns in O(1).
|
|
128
175
|
const RECHECK_MS = 30_000;
|
|
129
176
|
const MAX_DIAG_STAMPS = 12;
|
|
130
177
|
async function scan() {
|
|
131
|
-
const
|
|
178
|
+
const startEpoch = _writeEpoch;
|
|
179
|
+
const scanSeq = ++_scanSeq;
|
|
180
|
+
// Test-only: inert unless the fault-injection opt-in is set and this point is
|
|
181
|
+
// armed. It holds this scan before its read, so a consult that arrives while
|
|
182
|
+
// the boot pre-warm is parked observes the unknown (not-yet-verified) verdict
|
|
183
|
+
// a real boot window exposes.
|
|
184
|
+
const parked = txnPausePoint("space-guard-scan");
|
|
185
|
+
if (parked)
|
|
186
|
+
await parked;
|
|
187
|
+
const currentStamp = _modelIdGetter();
|
|
188
|
+
const currentNorm = normalizeStamp(currentStamp);
|
|
189
|
+
// The raw forms that denote the current space, compared EXACTLY as the vector
|
|
190
|
+
// query's stamp condition compares them (Harper `equals` applies no whitespace
|
|
191
|
+
// or prefix normalisation). The query's stamp condition filters a row whose raw
|
|
192
|
+
// stamp is not one of these from the returned set; HNSW can still compute that
|
|
193
|
+
// row's distance during traversal, so the protection at traversal level is this
|
|
194
|
+
// scan's verdict, not the condition.
|
|
195
|
+
const trustedRaw = new Set(currentSpaceRawForms(currentStamp));
|
|
132
196
|
const seen = new Set();
|
|
133
197
|
let uniform = true;
|
|
198
|
+
// Count every array or typed array without a trusted stamp, including empty ones.
|
|
199
|
+
let excluded = 0;
|
|
200
|
+
// Which half of the scan threw, for the bounded failure reason below.
|
|
201
|
+
let phase = "table";
|
|
134
202
|
try {
|
|
135
203
|
const table = await _tableGetter();
|
|
136
|
-
|
|
137
|
-
//
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
204
|
+
phase = "read";
|
|
205
|
+
// Project the stamp and the vector attribute. Two rules, kept separate:
|
|
206
|
+
// - uniformity (flair#2481, unchanged): any space-bearing stamp that is not
|
|
207
|
+
// the current space makes the corpus `mixed`, whether or not the row
|
|
208
|
+
// stores a vector;
|
|
209
|
+
// - the excluded count (flair#2573): any array or typed array, empty included,
|
|
210
|
+
// without a trusted current-space stamp.
|
|
211
|
+
for await (const row of table.search({ select: ["embeddingModel", "embedding"] })) {
|
|
212
|
+
const rec = row;
|
|
213
|
+
const raw = typeof rec.embeddingModel === "string" ? rec.embeddingModel : null;
|
|
214
|
+
const n = normalizeStamp(raw);
|
|
215
|
+
if (n !== null) {
|
|
216
|
+
if (seen.size < MAX_DIAG_STAMPS)
|
|
217
|
+
seen.add(n);
|
|
218
|
+
if (n !== currentNorm)
|
|
219
|
+
uniform = false;
|
|
220
|
+
}
|
|
221
|
+
if (hasStoredVector(rec.embedding) && !(raw !== null && trustedRaw.has(raw)))
|
|
222
|
+
excluded++;
|
|
223
|
+
}
|
|
224
|
+
// Test-only: inert unless the fault-injection opt-in is set and this point
|
|
225
|
+
// is armed (flair#2508). It holds this scan after its read, so a scan that
|
|
226
|
+
// started later can read and publish before this one resumes.
|
|
227
|
+
const paused = txnPausePoint("scan-verdict");
|
|
228
|
+
if (paused)
|
|
229
|
+
await paused;
|
|
230
|
+
// A changed epoch discards this scan's verdict and makes the next consult rescan.
|
|
231
|
+
if (_writeEpoch !== startEpoch) {
|
|
232
|
+
_lastScanAt = 0;
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// flair#2508 — a scan that started later already published its verdict; this
|
|
236
|
+
// stale one must not overwrite it. Refused by name; nothing is written.
|
|
237
|
+
if (scanSeq < _publishedScanSeq) {
|
|
238
|
+
console.warn(`embedding-space-guard: stale scan verdict refused (scan ${scanSeq} superseded by scan ${_publishedScanSeq}); nothing written`);
|
|
239
|
+
return;
|
|
146
240
|
}
|
|
147
241
|
_activeStamps = [...seen];
|
|
148
242
|
_uniform = uniform;
|
|
243
|
+
_excluded = excluded;
|
|
244
|
+
_excludedStale = false;
|
|
245
|
+
_publishedScanSeq = scanSeq;
|
|
149
246
|
_lastScanAt = Date.now();
|
|
247
|
+
// A published verdict clears any earlier failed-scan state.
|
|
248
|
+
_lastScanError = null;
|
|
150
249
|
}
|
|
151
250
|
catch {
|
|
152
|
-
//
|
|
153
|
-
//
|
|
251
|
+
// The same two checks as the verdict publish above, in the same order. A
|
|
252
|
+
// changed epoch discards this scan (flair#2481) — the foreign write already
|
|
253
|
+
// closed the gate.
|
|
254
|
+
if (_writeEpoch !== startEpoch) {
|
|
255
|
+
_lastScanAt = 0;
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
// flair#2508 — a scan that started later already published its outcome; this
|
|
259
|
+
// stale failure must not turn that verdict back to unknown. Refused by name.
|
|
260
|
+
if (scanSeq < _publishedScanSeq) {
|
|
261
|
+
console.warn(`embedding-space-guard: stale scan failure refused (scan ${scanSeq} superseded by scan ${_publishedScanSeq}); nothing written`);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// Record a bounded reason (never row content) and log each reason once; the
|
|
265
|
+
// prior verdict is left untouched and the consult schedule retries. The
|
|
266
|
+
// state now reads `scan-failed`, or stays `mixed` when a foreign stamp is
|
|
267
|
+
// known; either way consumers fail closed (flair#2530). The failure is this
|
|
268
|
+
// scan's published outcome, so an earlier-started scan that finishes later
|
|
269
|
+
// cannot clear it.
|
|
270
|
+
noteScanFailure(phase === "table" ? SCAN_ERROR_TABLE_UNAVAILABLE : SCAN_ERROR_SCAN_FAILED);
|
|
271
|
+
_publishedScanSeq = scanSeq;
|
|
154
272
|
}
|
|
155
273
|
}
|
|
156
274
|
function runScan() {
|
|
@@ -158,48 +276,196 @@ function runScan() {
|
|
|
158
276
|
_scanning = scan().finally(() => { _scanning = undefined; });
|
|
159
277
|
return _scanning;
|
|
160
278
|
}
|
|
279
|
+
/** The state-named warning a guard-degraded consumer surfaces when it refuses
|
|
280
|
+
* its embedding leg (flair#2530, flair#2559). The verdict is never `uniform`
|
|
281
|
+
* here (that state is never degraded), so the four cases are exactly the
|
|
282
|
+
* non-uniform states. Each names itself; the non-current-stamp wording is used
|
|
283
|
+
* ONLY for the `mixed` state. `response` says what the caller gets back:
|
|
284
|
+
* keyword-only results (the request has query text), no results (it has none),
|
|
285
|
+
* or an `explain` plan with no embedding leg. Shared by the recall leg
|
|
286
|
+
* (resources/SemanticSearch.ts) and MemoryBootstrap's task-relevant selection
|
|
287
|
+
* (resources/MemoryBootstrap.ts) so both name the state with ONE wording. */
|
|
288
|
+
export function spaceGuardWarning(v, response) {
|
|
289
|
+
const outcome = response === "keyword" ? "results are keyword-only"
|
|
290
|
+
: response === "none" ? "no results (the request has no query text to fall back on)"
|
|
291
|
+
: "the plan has no embedding leg";
|
|
292
|
+
if (v.state === "scan-failed") {
|
|
293
|
+
return `semantic search unavailable — embedding space unverified: last scan failed (${v.reason}); ${outcome}.`;
|
|
294
|
+
}
|
|
295
|
+
if (v.state === "unverified") {
|
|
296
|
+
return `semantic search unavailable — embedding space not yet verified; ${outcome}.`;
|
|
297
|
+
}
|
|
298
|
+
if (v.state === "excluded") {
|
|
299
|
+
return (`semantic search unavailable — the last scan found a stored vector with no trusted current-space stamp ` +
|
|
300
|
+
`(${v.excluded ?? "unknown"} row(s)); ${outcome}. Re-embed or remove the row`);
|
|
301
|
+
}
|
|
302
|
+
return (`semantic search unavailable — a non-current embedding model stamp was observed ` +
|
|
303
|
+
`(current: ${v.current}; found: ${v.found.join(", ")}); ${outcome}. ` +
|
|
304
|
+
`Reconcile to one space with: flair reembed --stale-only`);
|
|
305
|
+
}
|
|
306
|
+
/** Bounded, row-content-free reasons a scan can fail with. An error from the
|
|
307
|
+
* scan's table lookup or corpus read is classified into one of these; the raw
|
|
308
|
+
* message is never surfaced or logged. */
|
|
309
|
+
export const SCAN_ERROR_TABLE_UNAVAILABLE = "the Memory table was not available";
|
|
310
|
+
export const SCAN_ERROR_SCAN_FAILED = "the Memory corpus scan failed";
|
|
311
|
+
/** Record a scan failure: remember the bounded reason and log each reason ONCE.
|
|
312
|
+
* The consult schedule retries unchanged; this only names the state. Never
|
|
313
|
+
* logs the raw error (which could carry row content). */
|
|
314
|
+
function noteScanFailure(reason) {
|
|
315
|
+
_lastScanError = reason;
|
|
316
|
+
if (_loggedScanErrorReasons.has(reason))
|
|
317
|
+
return;
|
|
318
|
+
_loggedScanErrorReasons.add(reason);
|
|
319
|
+
console.warn(`embedding-space-guard: corpus scan failed (${reason}); ` +
|
|
320
|
+
`the store is not known to be uniform until a scan succeeds`);
|
|
321
|
+
}
|
|
322
|
+
/** Read the verdict + its state together, without scanning. Callers must not
|
|
323
|
+
* use this to decide AND expect it to reflect a scan they just started. */
|
|
324
|
+
function guardSnapshot() {
|
|
325
|
+
const current = normalizeStamp(_modelIdGetter()) ?? _modelIdGetter();
|
|
326
|
+
const found = [..._activeStamps];
|
|
327
|
+
const excluded = _excluded;
|
|
328
|
+
// A known foreign stamp comes first, so no failed scan, earlier or later,
|
|
329
|
+
// turns the `mixed` state into an advisory `scan-failed`; the error rides in `reason`.
|
|
330
|
+
if (_uniform === false)
|
|
331
|
+
return { uniform: false, state: "mixed", reason: _lastScanError, current, found, excluded };
|
|
332
|
+
if (_lastScanError !== null) {
|
|
333
|
+
return { uniform: false, state: "scan-failed", reason: _lastScanError, current, found, excluded };
|
|
334
|
+
}
|
|
335
|
+
// flair#2573 — a guard-notified write may have changed the count since
|
|
336
|
+
// publication. An unknown count fails closed until a scan republishes.
|
|
337
|
+
if (_excludedStale)
|
|
338
|
+
return { uniform: false, state: "unverified", reason: null, current, found, excluded };
|
|
339
|
+
if (_uniform === true) {
|
|
340
|
+
if (excluded !== null && excluded > 0) {
|
|
341
|
+
// The scan found an array or typed array without a trusted stamp and no foreign space-bearing stamp.
|
|
342
|
+
return { uniform: false, state: "excluded", reason: null, current, found, excluded };
|
|
343
|
+
}
|
|
344
|
+
return { uniform: true, state: "uniform", reason: null, current, found, excluded };
|
|
345
|
+
}
|
|
346
|
+
return { uniform: false, state: "unverified", reason: null, current, found, excluded };
|
|
347
|
+
}
|
|
348
|
+
/** The consult decision. Fails closed and never awaits an in-flight scan: an
|
|
349
|
+
* unknown verdict must be reported NOW (the caller takes its mixed-space path).
|
|
350
|
+
* Non-uniform verdicts trigger rescans immediately when unknown or stale,
|
|
351
|
+
* otherwise after RECHECK_MS.
|
|
352
|
+
* The snapshot is taken synchronously, so the state cannot drift from the
|
|
353
|
+
* decision. */
|
|
354
|
+
function consultGuard() {
|
|
355
|
+
if (guardSnapshot().uniform)
|
|
356
|
+
return guardSnapshot();
|
|
357
|
+
if (_uniform === undefined || _excludedStale || Date.now() - _lastScanAt >= RECHECK_MS) {
|
|
358
|
+
void runScan();
|
|
359
|
+
}
|
|
360
|
+
return guardSnapshot();
|
|
361
|
+
}
|
|
362
|
+
/** Returns the guard verdict: only a successful scan with no excluded arrays or
|
|
363
|
+
* typed arrays and no foreign space-bearing stamps permits the embedding leg. */
|
|
364
|
+
export function isEmbeddingSpaceUniform() {
|
|
365
|
+
return Promise.resolve(consultGuard().uniform);
|
|
366
|
+
}
|
|
161
367
|
/**
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
368
|
+
* flair#2573 slice 1 — is `stamp` a trusted current-space model stamp for the
|
|
369
|
+
* configured model? True only for a space-bearing stamp that denotes the current
|
|
370
|
+
* space (the engine-qualified id or its bare-name equivalent), compared exactly
|
|
371
|
+
* as the vector query's stamp condition compares it. An absent stamp, the
|
|
372
|
+
* `hash-512d` marker and a foreign model are all untrusted. Reads the injectable
|
|
373
|
+
* model-id getter so tests can pin the space. Metadata compare only (never a
|
|
374
|
+
* vector-byte comparison).
|
|
168
375
|
*/
|
|
169
|
-
export
|
|
170
|
-
|
|
171
|
-
return true;
|
|
172
|
-
if (_uniform === undefined || Date.now() - _lastScanAt >= RECHECK_MS) {
|
|
173
|
-
await runScan();
|
|
174
|
-
}
|
|
175
|
-
return _uniform ?? true;
|
|
376
|
+
export function isTrustedVectorStamp(stamp) {
|
|
377
|
+
return isTrustedRawStamp(stamp, _modelIdGetter());
|
|
176
378
|
}
|
|
177
379
|
/**
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
380
|
+
* flair#2573 slice 1 — the Harper condition matching rows whose `embeddingModel`
|
|
381
|
+
* is one of the current space's raw forms. This is DEFENCE IN DEPTH: the guard's
|
|
382
|
+
* verdict is the load-bearing exclusion (a non-uniform verdict makes every
|
|
383
|
+
* consumer refuse the embedding leg), and a query `conditions` entry cannot keep
|
|
384
|
+
* a vector out of Harper's HNSW traversal — its distance is computed before an
|
|
385
|
+
* admission condition is applied. Used as an ADDITIONAL condition on a vector
|
|
386
|
+
* (HNSW) query ONLY — never folded into the caller's `conditions`, which also
|
|
387
|
+
* drive the lexical leg (a row with an untrusted stamp remains eligible for
|
|
388
|
+
* lexical matching).
|
|
182
389
|
*/
|
|
183
|
-
export function
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
390
|
+
export function trustedVectorCondition() {
|
|
391
|
+
return {
|
|
392
|
+
operator: "or",
|
|
393
|
+
conditions: currentSpaceRawForms(_modelIdGetter()).map((value) => ({
|
|
394
|
+
attribute: "embeddingModel",
|
|
395
|
+
comparator: "equals",
|
|
396
|
+
value,
|
|
397
|
+
})),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/** The full verdict for a consumer that must NAME the state it degraded on
|
|
401
|
+
* (the recall leg's `_warning`). Decision and state are captured together, so
|
|
402
|
+
* the state cannot drift from the decision under a concurrent scan. Fails
|
|
403
|
+
* closed exactly as `isEmbeddingSpaceUniform()` does. */
|
|
404
|
+
export function embeddingSpaceVerdict() {
|
|
405
|
+
return Promise.resolve(consultGuard());
|
|
406
|
+
}
|
|
407
|
+
/** The guard state for an operator surface (`flair doctor` via /Health), without
|
|
408
|
+
* running a scan. Never blocks, never reads a vector. */
|
|
409
|
+
export function spaceGuardState() {
|
|
410
|
+
const v = guardSnapshot();
|
|
411
|
+
return { state: v.state, reason: v.reason, excluded: v.excluded };
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Call after persisting a vector or embeddingModel write, passing the resulting
|
|
415
|
+
* stamp (possibly absent) and the row the write replaced: `null` when there was
|
|
416
|
+
* none, omitted when the caller did not read it. Metadata-only PATCHes must not
|
|
417
|
+
* call this hook. A write invalidates the count when its stamp is untrusted or it
|
|
418
|
+
* may repair an untrusted vector: the replaced row stored one, or the replaced
|
|
419
|
+
* row is unknown while the verdict is non-uniform. A trusted write over a known
|
|
420
|
+
* row with no untrusted vector leaves the published count, and so the state,
|
|
421
|
+
* as it was. A foreign space also closes the latch.
|
|
422
|
+
*/
|
|
423
|
+
export function noteWriteStamp(stamp, previous) {
|
|
424
|
+
let n;
|
|
425
|
+
let current;
|
|
426
|
+
try {
|
|
427
|
+
const currentStamp = _modelIdGetter();
|
|
428
|
+
const replacesUntrusted = hasStoredVector(previous?.embedding) &&
|
|
429
|
+
!isTrustedRawStamp(typeof previous?.embeddingModel === "string" ? previous.embeddingModel : null, currentStamp);
|
|
430
|
+
if (isTrustedRawStamp(stamp, currentStamp) && !replacesUntrusted &&
|
|
431
|
+
(previous !== undefined || guardSnapshot().uniform))
|
|
432
|
+
return;
|
|
433
|
+
n = normalizeStamp(stamp);
|
|
434
|
+
current = normalizeStamp(currentStamp);
|
|
435
|
+
}
|
|
436
|
+
catch (err) {
|
|
437
|
+
// The stamp could not be read against the current space: fail closed, as
|
|
438
|
+
// for any other unreadable state, and invalidate an in-flight scan.
|
|
439
|
+
_uniform = false;
|
|
440
|
+
_excludedStale = true;
|
|
441
|
+
_writeEpoch++;
|
|
442
|
+
throw err;
|
|
443
|
+
}
|
|
444
|
+
// This notified write may change the excluded count. Invalidate an in-flight
|
|
445
|
+
// scan; the next published scan clears the stale flag.
|
|
446
|
+
_excludedStale = true;
|
|
447
|
+
_writeEpoch++;
|
|
448
|
+
// A space-bearing, non-current stamp additionally trips the uniformity latch
|
|
449
|
+
// now, with no rescan, and is named in the diagnostic.
|
|
450
|
+
if (n !== null && n !== current) {
|
|
188
451
|
if (!_activeStamps.includes(n) && _activeStamps.length < MAX_DIAG_STAMPS)
|
|
189
452
|
_activeStamps.push(n);
|
|
190
453
|
_uniform = false;
|
|
191
454
|
}
|
|
192
455
|
}
|
|
193
456
|
/**
|
|
194
|
-
* Force a fresh corpus scan
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
457
|
+
* Force a fresh corpus scan, then return the current published latch
|
|
458
|
+
* decision: true only when the latch reads verified uniform with no scan error.
|
|
459
|
+
* The explicit "re-embed completion clears it" primitive — used by the boot
|
|
460
|
+
* pre-warm, and callable after a bulk re-embed to reopen the gate promptly
|
|
461
|
+
* rather than waiting out RECHECK_MS. A later-started scan may have published
|
|
462
|
+
* that decision, so it does not say whether THIS scan succeeded.
|
|
198
463
|
*/
|
|
199
464
|
export async function recomputeLatch() {
|
|
200
465
|
_lastScanAt = 0; // bypass the throttle
|
|
201
466
|
await scan();
|
|
202
|
-
|
|
467
|
+
// Any excluded array or typed array makes the verdict non-uniform.
|
|
468
|
+
return _uniform === true && _lastScanError === null && !_excludedStale && (_excluded === null || _excluded === 0);
|
|
203
469
|
}
|
|
204
470
|
/**
|
|
205
471
|
* Structured diagnostic for the degrade path — the current space id and the
|
|
@@ -213,15 +479,34 @@ export function spaceGuardDiagnostics() {
|
|
|
213
479
|
// ─── Boot pre-warm (module side effect) ──────────────────────────────────────
|
|
214
480
|
// Best-effort, single-shot, deferred to after the current synchronous load
|
|
215
481
|
// phase (same setImmediate convention as migration-boot.ts). If it fires
|
|
216
|
-
// before the Memory table is live, the scan
|
|
217
|
-
// consult
|
|
218
|
-
//
|
|
482
|
+
// before the Memory table is live, the scan fails (`scan-failed`) and a later
|
|
483
|
+
// consult rescans — correctness never depends on this pre-warm (fail-closed
|
|
484
|
+
// either way); it only decides whether the first queries serve embeddings or
|
|
485
|
+
// take the mixed-space path until a scan completes.
|
|
219
486
|
let _prewarmScheduled = false;
|
|
487
|
+
// Settles when the most recently scheduled pre-warm's scan has finished,
|
|
488
|
+
// whatever its outcome. Read only through `_prewarmSettledForTests()`.
|
|
489
|
+
let _prewarmSettled;
|
|
220
490
|
export function scheduleSpaceGuardPrewarm() {
|
|
221
491
|
if (_prewarmScheduled)
|
|
222
492
|
return;
|
|
223
493
|
_prewarmScheduled = true;
|
|
224
|
-
|
|
494
|
+
_prewarmSettled = new Promise((resolve) => {
|
|
495
|
+
setImmediate(() => { void recomputeLatch().catch(() => { }).then(() => resolve()); });
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Test-only barrier (flair#2508): resolves once the most recently scheduled
|
|
500
|
+
* pre-warm's scan has finished, so a test can wait for it before it injects a
|
|
501
|
+
* table getter or arms a pause point. Gated like the pause points: returns
|
|
502
|
+
* `undefined` unless the fault-injection opt-in
|
|
503
|
+
* (`FLAIR_ENABLE_TEST_FAULT_INJECTION=1`) is set, and also when no pre-warm
|
|
504
|
+
* was ever scheduled.
|
|
505
|
+
*/
|
|
506
|
+
export function _prewarmSettledForTests(env = process.env) {
|
|
507
|
+
if (env[TEST_FAULT_INJECTION_ENV] !== "1")
|
|
508
|
+
return undefined;
|
|
509
|
+
return _prewarmSettled;
|
|
225
510
|
}
|
|
226
511
|
// Test-only seams — mirror embeddings-boot.ts's `_resetEmbeddingsBackendRegistrationForTests`.
|
|
227
512
|
export function _setGuardTableGetterForTests(fn) { _tableGetter = fn; }
|
|
@@ -231,8 +516,17 @@ export function _resetGuardForTests() {
|
|
|
231
516
|
_modelIdGetter = getModelId;
|
|
232
517
|
_uniform = undefined;
|
|
233
518
|
_activeStamps = [];
|
|
519
|
+
_excluded = null;
|
|
520
|
+
_excludedStale = false;
|
|
234
521
|
_lastScanAt = 0;
|
|
235
522
|
_scanning = undefined;
|
|
523
|
+
_writeEpoch = 0;
|
|
524
|
+
_lastScanError = null;
|
|
525
|
+
_loggedScanErrorReasons.clear();
|
|
526
|
+
_scanSeq = 0;
|
|
527
|
+
_publishedScanSeq = 0;
|
|
528
|
+
// `_prewarmSettled` is kept: a reset cannot cancel a pre-warm that is already
|
|
529
|
+
// scheduled, so its barrier must stay awaitable.
|
|
236
530
|
_prewarmScheduled = false;
|
|
237
531
|
}
|
|
238
532
|
scheduleSpaceGuardPrewarm();
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { ENGINE_VERSION_STAMP } from "../src/engine-version-contract.js";
|
|
7
|
+
/** The flair package root (`<pkg>/dist/resources/x.js` → `<pkg>`). */
|
|
8
|
+
function packageRoot() {
|
|
9
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
10
|
+
}
|
|
11
|
+
/** Attempt to stamp the data directory. */
|
|
12
|
+
export function stampEngineVersionOnBoot(dataDir = process.env.ROOTPATH || join((process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME) || homedir(), ".flair", "data")) {
|
|
13
|
+
try {
|
|
14
|
+
if (!existsSync(dataDir))
|
|
15
|
+
return;
|
|
16
|
+
for (const name of ["harper", "@harperfast/harper"]) {
|
|
17
|
+
let version;
|
|
18
|
+
try {
|
|
19
|
+
const pkgPath = join(packageRoot(), "node_modules", ...name.split("/"), "package.json");
|
|
20
|
+
version = JSON.parse(readFileSync(pkgPath, "utf8")).version;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (version) {
|
|
26
|
+
const stampPath = join(dataDir, ENGINE_VERSION_STAMP);
|
|
27
|
+
const temporary = `${stampPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
28
|
+
let fd;
|
|
29
|
+
try {
|
|
30
|
+
fd = openSync(temporary, "wx", 0o600);
|
|
31
|
+
writeFileSync(fd, `${version}\n`, "utf8");
|
|
32
|
+
fsyncSync(fd);
|
|
33
|
+
closeSync(fd);
|
|
34
|
+
fd = undefined;
|
|
35
|
+
renameSync(temporary, stampPath);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
if (fd !== undefined)
|
|
39
|
+
closeSync(fd);
|
|
40
|
+
try {
|
|
41
|
+
unlinkSync(temporary);
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Best-effort: a stamp write is never allowed to fail a boot.
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
stampEngineVersionOnBoot();
|