@memberjunction/search-engine 6.2.0-edge.3 → 6.2.0-edge.5
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 +1 -1
- package/dist/generic/EntitySearchProvider.d.ts +12 -4
- package/dist/generic/EntitySearchProvider.d.ts.map +1 -1
- package/dist/generic/EntitySearchProvider.js +13 -6
- package/dist/generic/EntitySearchProvider.js.map +1 -1
- package/dist/generic/FullTextSearchProvider.d.ts +8 -0
- package/dist/generic/FullTextSearchProvider.d.ts.map +1 -1
- package/dist/generic/FullTextSearchProvider.js +12 -4
- package/dist/generic/FullTextSearchProvider.js.map +1 -1
- package/dist/generic/ISearchProvider.d.ts +67 -2
- package/dist/generic/ISearchProvider.d.ts.map +1 -1
- package/dist/generic/ISearchProvider.js +63 -0
- package/dist/generic/ISearchProvider.js.map +1 -1
- package/dist/generic/ScopeDimensionResolver.d.ts +28 -0
- package/dist/generic/ScopeDimensionResolver.d.ts.map +1 -1
- package/dist/generic/ScopeDimensionResolver.js +55 -3
- package/dist/generic/ScopeDimensionResolver.js.map +1 -1
- package/dist/generic/ScopeExplanation.d.ts +24 -13
- package/dist/generic/ScopeExplanation.d.ts.map +1 -1
- package/dist/generic/ScopeExplanation.js +39 -26
- package/dist/generic/ScopeExplanation.js.map +1 -1
- package/dist/generic/ScopeFilterGuard.d.ts +18 -0
- package/dist/generic/ScopeFilterGuard.d.ts.map +1 -1
- package/dist/generic/ScopeFilterGuard.js +49 -0
- package/dist/generic/ScopeFilterGuard.js.map +1 -1
- package/dist/generic/ScopeTemplateRenderer.d.ts +3 -0
- package/dist/generic/ScopeTemplateRenderer.d.ts.map +1 -1
- package/dist/generic/ScopeTemplateRenderer.js +11 -2
- package/dist/generic/ScopeTemplateRenderer.js.map +1 -1
- package/dist/generic/ScopeValueEscaper.d.ts +10 -3
- package/dist/generic/ScopeValueEscaper.d.ts.map +1 -1
- package/dist/generic/ScopeValueEscaper.js +51 -5
- package/dist/generic/ScopeValueEscaper.js.map +1 -1
- package/dist/generic/SearchEngine.d.ts +507 -50
- package/dist/generic/SearchEngine.d.ts.map +1 -1
- package/dist/generic/SearchEngine.js +1356 -253
- package/dist/generic/SearchEngine.js.map +1 -1
- package/dist/generic/SearchEnricher.d.ts +3 -1
- package/dist/generic/SearchEnricher.d.ts.map +1 -1
- package/dist/generic/SearchEnricher.js +10 -5
- package/dist/generic/SearchEnricher.js.map +1 -1
- package/dist/generic/SearchFusion.d.ts +42 -7
- package/dist/generic/SearchFusion.d.ts.map +1 -1
- package/dist/generic/SearchFusion.js +116 -47
- package/dist/generic/SearchFusion.js.map +1 -1
- package/dist/generic/StorageSearchProvider.d.ts +37 -20
- package/dist/generic/StorageSearchProvider.d.ts.map +1 -1
- package/dist/generic/StorageSearchProvider.js +79 -105
- package/dist/generic/StorageSearchProvider.js.map +1 -1
- package/dist/generic/TagSearchProvider.d.ts +5 -1
- package/dist/generic/TagSearchProvider.d.ts.map +1 -1
- package/dist/generic/TagSearchProvider.js +5 -2
- package/dist/generic/TagSearchProvider.js.map +1 -1
- package/dist/generic/VectorSearchProvider.d.ts +3 -0
- package/dist/generic/VectorSearchProvider.d.ts.map +1 -1
- package/dist/generic/VectorSearchProvider.js +29 -9
- package/dist/generic/VectorSearchProvider.js.map +1 -1
- package/dist/generic/search.types.d.ts +125 -7
- package/dist/generic/search.types.d.ts.map +1 -1
- package/dist/generic/search.types.js +0 -9
- package/dist/generic/search.types.js.map +1 -1
- package/dist/permissions/SearchScopePermissionResolver.d.ts +6 -5
- package/dist/permissions/SearchScopePermissionResolver.d.ts.map +1 -1
- package/dist/permissions/SearchScopePermissionResolver.js +15 -13
- package/dist/permissions/SearchScopePermissionResolver.js.map +1 -1
- package/dist/providers/AzureAISearchProvider.d.ts +4 -1
- package/dist/providers/AzureAISearchProvider.d.ts.map +1 -1
- package/dist/providers/AzureAISearchProvider.js +8 -6
- package/dist/providers/AzureAISearchProvider.js.map +1 -1
- package/dist/providers/ElasticsearchSearchProvider.d.ts +3 -0
- package/dist/providers/ElasticsearchSearchProvider.d.ts.map +1 -1
- package/dist/providers/ElasticsearchSearchProvider.js +8 -7
- package/dist/providers/ElasticsearchSearchProvider.js.map +1 -1
- package/dist/providers/OpenSearchSearchProvider.d.ts +5 -1
- package/dist/providers/OpenSearchSearchProvider.d.ts.map +1 -1
- package/dist/providers/OpenSearchSearchProvider.js +9 -5
- package/dist/providers/OpenSearchSearchProvider.js.map +1 -1
- package/dist/providers/TypesenseSearchProvider.d.ts +4 -1
- package/dist/providers/TypesenseSearchProvider.d.ts.map +1 -1
- package/dist/providers/TypesenseSearchProvider.js +8 -7
- package/dist/providers/TypesenseSearchProvider.js.map +1 -1
- package/package.json +10 -10
|
@@ -19,28 +19,65 @@
|
|
|
19
19
|
*
|
|
20
20
|
* @module @memberjunction/search-engine
|
|
21
21
|
*/
|
|
22
|
-
import { CompositeKey, EntityPermissionType, LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
22
|
+
import { CompositeKey, EntityPermissionType, KeyValuePair, LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
23
23
|
import { SearchEngineBase } from '@memberjunction/core-entities';
|
|
24
|
-
import { BaseSingleton, EscapeSQLString, MJGlobal, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
24
|
+
import { BaseSingleton, EscapeSQLString, IsValidUUID, MJGlobal, NormalizeUUID, UUIDSet, UUIDsEqual } from '@memberjunction/global';
|
|
25
|
+
import { FileStorageEngine, StorageAccessEvaluator } from '@memberjunction/storage';
|
|
25
26
|
import { BaseSearchProvider } from './ISearchProvider.js';
|
|
26
|
-
import { SearchFusion } from './SearchFusion.js';
|
|
27
|
+
import { SearchFusion, ApplySemanticFloor } from './SearchFusion.js';
|
|
27
28
|
import { SearchEnricher } from './SearchEnricher.js';
|
|
28
29
|
import { FullTextSearchProvider } from './FullTextSearchProvider.js';
|
|
30
|
+
import { StorageSearchProvider } from './StorageSearchProvider.js';
|
|
29
31
|
import { BaseReRanker } from './BaseReRanker.js';
|
|
30
32
|
import { NoopReRanker, LoadNoopReRanker } from './NoopReRanker.js';
|
|
31
33
|
import { RerankerBudgetGuard } from '../rerankers/RerankerBudgetGuard.js';
|
|
32
34
|
import { RenderScopeTemplate, RenderScopeJsonTemplate } from './ScopeTemplateRenderer.js';
|
|
33
35
|
import { LaneKindForIndexType } from './ScopeValueEscaper.js';
|
|
34
|
-
import { CheckRenderedTemplate, CheckRequiredMetadataKeys, ParseRequiredMetadataKeys } from './ScopeFilterGuard.js';
|
|
36
|
+
import { CheckRenderedFolderPath, CheckRenderedTemplate, CheckRequiredMetadataKeys, ParseRequiredMetadataKeys } from './ScopeFilterGuard.js';
|
|
35
37
|
import { ScopeDimensionResolver } from './ScopeDimensionResolver.js';
|
|
36
38
|
import { GetSearchScopePermissionResolver } from '../permissions/SearchScopePermissionResolver.js';
|
|
37
39
|
/**
|
|
38
|
-
* Emitted
|
|
39
|
-
* Shared by the dry run and the search path
|
|
40
|
+
* Emitted when a GLOBAL scope configures no lanes at all — a global scope runs unconstrained, so
|
|
41
|
+
* every provider searches everything available to it. Shared by the dry run and the search path.
|
|
40
42
|
*/
|
|
41
|
-
const UNBOUNDED_SCOPE_DIAGNOSTIC = 'this scope configures NO lanes (no external indexes, entities, or storage accounts). ' +
|
|
42
|
-
'
|
|
43
|
-
|
|
43
|
+
const UNBOUNDED_SCOPE_DIAGNOSTIC = 'this global scope configures NO lanes (no external indexes, entities, or storage accounts). ' +
|
|
44
|
+
'A global scope is UNSCOPED: every provider searches everything available to it with no filter.';
|
|
45
|
+
/**
|
|
46
|
+
* Emitted when a NON-global scope configures no lanes. Each lane list reaches the providers empty,
|
|
47
|
+
* and an empty list means "nothing for this provider", so the scope reaches nothing — never everything.
|
|
48
|
+
*/
|
|
49
|
+
const NO_LANES_DIAGNOSTIC = 'this scope configures NO lanes (no external indexes, entities, or storage accounts), so it reaches nothing: ' +
|
|
50
|
+
'a non-global scope searches only what its lanes name. Add a lane to make it retrieve.';
|
|
51
|
+
/**
|
|
52
|
+
* Emitted when a NON-global scope has no enabled `MJ: Search Scope Providers` row. It runs no provider —
|
|
53
|
+
* a scope with no provider rows used to run every provider, which made disabling the last row widen it.
|
|
54
|
+
*/
|
|
55
|
+
const NO_PROVIDER_ROWS_DIAGNOSTIC = 'this scope has no enabled provider rows (MJ: Search Scope Providers), so it runs no provider and returns nothing: ' +
|
|
56
|
+
'a non-global scope runs only the providers it lists. Add an enabled provider row to make it retrieve.';
|
|
57
|
+
/** Emitted when a NON-global scope's provider rows name no provider this engine can run. */
|
|
58
|
+
function noRunnableProviderDiagnostic(isPreview) {
|
|
59
|
+
const which = isPreview ? 'configured, available provider that supports preview searches' : 'configured, available provider';
|
|
60
|
+
return `this scope's enabled provider rows name no ${which}, so it runs no provider and returns nothing. ` +
|
|
61
|
+
'Check that each provider row names an active MJ: Search Providers row whose provider initialised.';
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Emitted when a NON-global scope's runnable providers read no lane kind the scope configures
|
|
65
|
+
* (`BaseSearchProvider.ConsumesLaneKinds`) — e.g. a Vector provider row over entity lanes only. Each provider
|
|
66
|
+
* would get an empty list for every lane it reads, so none is called and the scope reaches nothing.
|
|
67
|
+
*/
|
|
68
|
+
function noProviderReadsALaneDiagnostic(providers, lanes) {
|
|
69
|
+
const listed = providers.map(p => `${p.DisplayName} (reads ${p.Provider.ConsumesLaneKinds.join(', ') || 'no lane'})`).join('; ');
|
|
70
|
+
const configured = Array.from(new Set(lanes.filter(l => l.Status === 'Active').map(l => l.Kind))).join(', ');
|
|
71
|
+
return `none of this scope's providers reads a lane kind it configures — providers: ${listed}; active lanes: ${configured}. ` +
|
|
72
|
+
'It reaches nothing: add a lane each provider reads (e.g. a Vector external-index row for a vector provider), ' +
|
|
73
|
+
'or a provider row for a provider that reads these lanes.';
|
|
74
|
+
}
|
|
75
|
+
/** Emitted (dry run only) when a lane is skipped: the real search refuses on the first such lane. */
|
|
76
|
+
function refusedLanesDiagnostic(skipped) {
|
|
77
|
+
const named = skipped.map(l => `${l.Kind} "${l.Target}"`).join(', ');
|
|
78
|
+
return `a real search would be refused: ${skipped.length === 1 ? 'a lane is' : `${skipped.length} lanes are`} unusable (${named}). ` +
|
|
79
|
+
'A search refuses a scope with any unusable lane rather than search the others; fix the lane(s) to make it retrieve.';
|
|
80
|
+
}
|
|
44
81
|
// Keep the default re-ranker registration alive under tree-shaking
|
|
45
82
|
LoadNoopReRanker();
|
|
46
83
|
/**
|
|
@@ -105,6 +142,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
105
142
|
static { this.CACHE_TTL_MS = 30_000; }
|
|
106
143
|
/** Maximum cached entries across all users. LRU-evicted on overflow. */
|
|
107
144
|
static { this.CACHE_MAX_ENTRIES = 500; }
|
|
145
|
+
/**
|
|
146
|
+
* Ceiling on the per-provider over-fetch multiplier, whatever its source (caller, scope metadata or
|
|
147
|
+
* the engine default). Above it a single metadata edit would multiply every provider call for every
|
|
148
|
+
* caller of the scope, and vector providers bill per candidate.
|
|
149
|
+
*/
|
|
150
|
+
static { this.MAX_OVERFETCH_FACTOR = 20; }
|
|
108
151
|
/**
|
|
109
152
|
* Resolver for a scope's declared Search Context dimensions. Overridable so a host can
|
|
110
153
|
* supply additional derivation sources (e.g. an external signal) without forking the engine.
|
|
@@ -135,7 +178,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
135
178
|
if (this._configured && !forceRefresh)
|
|
136
179
|
return;
|
|
137
180
|
this._defaultMaxResults = config.DefaultMaxResults ?? 20;
|
|
138
|
-
|
|
181
|
+
// `??` passes NaN/Infinity through; a non-finite default would have become the provider topK.
|
|
182
|
+
const configuredDefault = config.DefaultPermissionOverfetchFactor;
|
|
183
|
+
this._defaultOverfetchFactor = typeof configuredDefault === 'number' && Number.isFinite(configuredDefault)
|
|
184
|
+
? this.clampOverfetchFactor(configuredDefault, 'the engine default')
|
|
185
|
+
: 2;
|
|
139
186
|
this._providerEntries = [];
|
|
140
187
|
// Ensure SearchEngineBase has loaded provider + scope metadata
|
|
141
188
|
await this.Base.Config(forceRefresh, contextUser);
|
|
@@ -182,6 +229,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
182
229
|
let invocationBudgetGuard = null;
|
|
183
230
|
let invocationRerankerName = null;
|
|
184
231
|
try {
|
|
232
|
+
// A malformed audience fails the search here rather than being skipped later: a reader the
|
|
233
|
+
// host failed to map would otherwise restrict nothing, and the room would see the caller's reach.
|
|
234
|
+
this.validateAudience(params.Audience);
|
|
185
235
|
// Defensive null-check: `params.Query.trim()` throws on null/undefined,
|
|
186
236
|
// and Sage's LLM has been observed to emit empty/missing tool args.
|
|
187
237
|
// Coerce to string before validating so we surface a clean error
|
|
@@ -225,12 +275,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
225
275
|
const topK = params.MaxResults ?? this._defaultMaxResults;
|
|
226
276
|
const mode = params.Mode ?? 'full';
|
|
227
277
|
const isPreview = mode === 'preview';
|
|
228
|
-
const overfetchFactor = Math.max(1, params.PermissionOverfetchFactor ?? this._defaultOverfetchFactor);
|
|
229
|
-
const providerTopK = Math.max(topK, Math.ceil(topK * overfetchFactor));
|
|
230
278
|
// ──────────────────────────────────────────────────────────
|
|
231
279
|
// Resolve scopes (when supplied)
|
|
232
280
|
// ──────────────────────────────────────────────────────────
|
|
233
|
-
const resolvedScopes = this.resolveScopes(params.ScopeIDs);
|
|
281
|
+
const { Bundles: resolvedScopes, Unresolved: unresolvedScopeIDs } = this.resolveScopes(params.ScopeIDs);
|
|
282
|
+
if (unresolvedScopeIDs.length > 0) {
|
|
283
|
+
// Before the cache lookup: a scope deactivated seconds ago must not be served from its old entry.
|
|
284
|
+
return this.refuseUnresolvableScopes(unresolvedScopeIDs, params, contextUser, startTime);
|
|
285
|
+
}
|
|
234
286
|
const isUnconstrained = resolvedScopes.length === 0 || resolvedScopes.some(s => s.Scope.IsGlobal);
|
|
235
287
|
// ──────────────────────────────────────────────────────────
|
|
236
288
|
// Cache lookup (next PR #2532). Skip preview searches — they're already
|
|
@@ -250,6 +302,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
250
302
|
if (hit)
|
|
251
303
|
this._cache.delete(cacheKey); // expired
|
|
252
304
|
}
|
|
305
|
+
// Resolved after the cache lookup, so a cache hit never pays for scope-config parsing or logs a clamp.
|
|
306
|
+
const overfetchFactor = this.ResolvePermissionOverfetchFactor(params, resolvedScopes);
|
|
307
|
+
const providerTopK = Math.max(topK, Math.ceil(topK * overfetchFactor));
|
|
308
|
+
// Per-provider events report a count of hits taken before any permission pass. Cap it at the
|
|
309
|
+
// caller's own topK so the over-fetch factor does not inflate what a stream client is told.
|
|
310
|
+
const partialEvents = onProviderResolved
|
|
311
|
+
? (ev) => onProviderResolved({ ...ev, results: ev.results.slice(0, topK) })
|
|
312
|
+
: undefined;
|
|
253
313
|
// ──────────────────────────────────────────────────────────
|
|
254
314
|
// Execute providers — either unscoped (original path) or per-scope
|
|
255
315
|
// ──────────────────────────────────────────────────────────
|
|
@@ -259,14 +319,14 @@ export class SearchEngine extends BaseSingleton {
|
|
|
259
319
|
// the unconstrained path, which resolves no scope and therefore decides nothing.
|
|
260
320
|
const scopeDecisions = [];
|
|
261
321
|
if (isUnconstrained) {
|
|
262
|
-
const labeledLists = await this.executeProviders(params.Query, providerTopK, params.Filters, contextUser, isPreview, undefined,
|
|
322
|
+
const labeledLists = await this.executeProviders(params.Query, providerTopK, params.Filters, contextUser, isPreview, undefined, partialEvents, params.MinScore);
|
|
263
323
|
sourceCounts = this.countSources(labeledLists);
|
|
264
324
|
const defaultFusionWeights = params.FusionWeightsOverride;
|
|
265
325
|
fusedResults = this._fusion.Fuse(labeledLists, providerTopK, defaultFusionWeights);
|
|
266
326
|
}
|
|
267
327
|
else {
|
|
268
328
|
// Run each scope independently, then cross-scope RRF
|
|
269
|
-
const perScopeRunResults = await Promise.all(resolvedScopes.map(bundle => this.executeScopeBundle(params.Query, providerTopK, params.Filters, contextUser, isPreview, bundle, params.SearchContext, params.FusionWeightsOverride, this.principalsFrom(params),
|
|
329
|
+
const perScopeRunResults = await Promise.all(resolvedScopes.map(bundle => this.executeScopeBundle(params.Query, providerTopK, params.Filters, contextUser, isPreview, bundle, params.SearchContext, params.FusionWeightsOverride, this.principalsFrom(params), partialEvents, params.MinScore)));
|
|
270
330
|
const sc = { Vector: 0, FullText: 0, Entity: 0, Storage: 0 };
|
|
271
331
|
const perScopeFused = new Map();
|
|
272
332
|
for (const r of perScopeRunResults) {
|
|
@@ -303,20 +363,31 @@ export class SearchEngine extends BaseSingleton {
|
|
|
303
363
|
// Dedup → content-item promotion/exclusion → merge promoted entities → permission safety net → score threshold → enrich
|
|
304
364
|
// ──────────────────────────────────────────────────────────
|
|
305
365
|
let results = this._fusion.Deduplicate(fusedResults);
|
|
306
|
-
|
|
307
|
-
|
|
366
|
+
if (isUnconstrained) {
|
|
367
|
+
// Scoped results were promoted per scope, before their lane bounds were applied (boundScopeHits):
|
|
368
|
+
// promoting here, after fusion, would let a promoted hit skip its origin entity's lane ExtraFilter.
|
|
369
|
+
this._enricher.Provider = this.ProviderToUse;
|
|
370
|
+
results = await this._enricher.ExcludeEntitySourcedContentItems(results, contextUser);
|
|
371
|
+
results = this._fusion.Deduplicate(results);
|
|
372
|
+
}
|
|
308
373
|
const beforePermCount = results.length;
|
|
309
|
-
|
|
310
|
-
|
|
374
|
+
const permissionStats = { OriginGateRemoved: 0 };
|
|
375
|
+
results = await this.filterByPermissions(results, contextUser, permissionStats);
|
|
376
|
+
if (permissionStats.OriginGateRemoved > 0) {
|
|
377
|
+
// By design, not a push-down gap: content derived from a record the user may not read.
|
|
378
|
+
const removed = permissionStats.OriginGateRemoved;
|
|
379
|
+
LogStatus(`SearchEngine: origin-record gate removed ${removed} result(s) derived from records the user may not read.`);
|
|
380
|
+
}
|
|
381
|
+
// Origin-gate removals are counted above, so this stays the push-down signal it always was.
|
|
382
|
+
const lateFilteredCount = beforePermCount - results.length - permissionStats.OriginGateRemoved;
|
|
311
383
|
if (lateFilteredCount > 0) {
|
|
312
384
|
// Observability: Section 3.6 — if a provider's push-down is complete, this
|
|
313
385
|
// number should be zero (the safety net should never trim anything).
|
|
314
386
|
LogStatus(`SearchEngine: Residual permission filter removed ${lateFilteredCount} result(s) — consider tightening provider push-down.`);
|
|
315
387
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
388
|
+
results = await this.FilterForAudience(results, params, contextUser);
|
|
389
|
+
// MinScore was applied to the semantic lane before fusion (ApplySemanticFloor). The
|
|
390
|
+
// fused Score is rank-based RRF, so it is deliberately not compared to MinScore here.
|
|
320
391
|
// Trim to caller's requested topK (we overfetched earlier)
|
|
321
392
|
if (results.length > topK)
|
|
322
393
|
results = results.slice(0, topK);
|
|
@@ -376,36 +447,31 @@ export class SearchEngine extends BaseSingleton {
|
|
|
376
447
|
}
|
|
377
448
|
}
|
|
378
449
|
/**
|
|
379
|
-
* Streaming variant of {@link Search}
|
|
380
|
-
*
|
|
381
|
-
* before fusion + reranking complete.
|
|
450
|
+
* Streaming variant of {@link Search}: the same pipeline, with a progress event as each provider
|
|
451
|
+
* returns, so a UI or agent can show progress before fusion, the permission pass and enrichment finish.
|
|
382
452
|
*
|
|
383
|
-
* **
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
* concurrent emission once we measure that the synthetic phase is the
|
|
391
|
-
* actual bottleneck.
|
|
453
|
+
* **Progress, not partial results.** A `provider` event carries the provider's name, its duration and
|
|
454
|
+
* `resultCount` — how many hits it returned, capped at `MaxResults` — and never the hits themselves
|
|
455
|
+
* (`results` is always empty). They arrive before the permission pass, so they include rows the caller's
|
|
456
|
+
* row filters would drop, external-index hits not yet verified against the entity they name, and content
|
|
457
|
+
* whose origin record the caller may not read. Results arrive only in `fused` and `final`, which carry
|
|
458
|
+
* exactly what {@link Search} returns. `resultCount` is counted before the permission and audience passes,
|
|
459
|
+
* like `SearchResult.SourceCounts`, so don't show it to a room.
|
|
392
460
|
*
|
|
393
|
-
* Cancellation: the consumer can stop iterating at any point — the
|
|
394
|
-
*
|
|
395
|
-
* discarded. AbortSignal-based mid-pipeline cancellation is a Phase 2C
|
|
396
|
-
* v2 concern.
|
|
461
|
+
* Cancellation: the consumer can stop iterating at any point — the underlying search runs to
|
|
462
|
+
* completion and its result is discarded. Mid-pipeline AbortSignal cancellation is not supported.
|
|
397
463
|
*
|
|
398
464
|
* Event ordering:
|
|
399
|
-
* 1.
|
|
465
|
+
* 1. One `provider` event per provider that ran, in the order they return (a provider that failed
|
|
466
|
+
* reports `resultCount: 0`)
|
|
400
467
|
* 2. Exactly one `fused` event
|
|
401
|
-
* 3.
|
|
402
|
-
* 4.
|
|
403
|
-
* 5. On error: a single `error` event in place of `final`.
|
|
468
|
+
* 3. Exactly one `final` event (`reranked` is part of the type but not emitted today)
|
|
469
|
+
* 4. On error: a single `error` event in place of `fused` and `final`.
|
|
404
470
|
*
|
|
405
471
|
* @example
|
|
406
472
|
* for await (const ev of SearchEngine.Instance.streamSearch(params, user)) {
|
|
407
473
|
* switch (ev.phase) {
|
|
408
|
-
* case 'provider': scratchpad.append(`${ev.providerName}: ${ev.
|
|
474
|
+
* case 'provider': scratchpad.append(`${ev.providerName}: ${ev.resultCount} hits`); break;
|
|
409
475
|
* case 'final': scratchpad.commit(ev.results); break;
|
|
410
476
|
* case 'error': scratchpad.fail(ev.error); break;
|
|
411
477
|
* }
|
|
@@ -452,12 +518,16 @@ export class SearchEngine extends BaseSingleton {
|
|
|
452
518
|
entity: 'Entity',
|
|
453
519
|
storage: 'Storage',
|
|
454
520
|
};
|
|
521
|
+
// A provider's hits arrive before any permission pass, so its event carries progress only: the name,
|
|
522
|
+
// the duration and a count. The hits themselves reach the caller in `fused`/`final`, after the
|
|
523
|
+
// permission pass (and, under an audience, after the audience pass).
|
|
455
524
|
const onProviderResolved = (ev) => {
|
|
456
525
|
const label = sourceTypeToLabel[ev.sourceType.toLowerCase()] ?? ev.sourceType;
|
|
457
526
|
push({
|
|
458
527
|
phase: 'provider',
|
|
459
528
|
providerName: label,
|
|
460
|
-
results:
|
|
529
|
+
results: [],
|
|
530
|
+
resultCount: ev.results.length,
|
|
461
531
|
durationMs: ev.durationMs,
|
|
462
532
|
});
|
|
463
533
|
};
|
|
@@ -600,9 +670,155 @@ export class SearchEngine extends BaseSingleton {
|
|
|
600
670
|
// into expansion queries. Two searches identical but for the active skill are NOT
|
|
601
671
|
// interchangeable, so they must not share a cache entry.
|
|
602
672
|
AISkillID: params.AISkillID ?? undefined,
|
|
673
|
+
// The audience narrows the result set, so a search the caller ran alone must never be
|
|
674
|
+
// served from the cache to a room, nor a room's result to the caller alone. Sorted so
|
|
675
|
+
// the same readers in any order share an entry. IDs only: within the TTL, a reader object
|
|
676
|
+
// with the same ID but different roles gets the cached verdict (see SearchParams.Audience).
|
|
677
|
+
AudienceReaderIDs: this.audienceReaderIDs(params.Audience, contextUser),
|
|
603
678
|
};
|
|
604
679
|
return `${userKey}|${trimmed}|${this.stableStringify(projection)}`;
|
|
605
680
|
}
|
|
681
|
+
/**
|
|
682
|
+
* Throw when `audience` is present but cannot be honoured. Called first in `searchInternal`, whose catch
|
|
683
|
+
* turns the throw into a `Success: false` result. A malformed reader is refused rather than skipped:
|
|
684
|
+
* skipping it would restrict nothing, and the room would see the caller's full reach.
|
|
685
|
+
*/
|
|
686
|
+
validateAudience(audience) {
|
|
687
|
+
if (audience === undefined)
|
|
688
|
+
return;
|
|
689
|
+
const problem = this.audienceProblem(audience);
|
|
690
|
+
if (problem)
|
|
691
|
+
throw new Error(`SearchEngine: invalid Audience — ${problem}`);
|
|
692
|
+
}
|
|
693
|
+
/** What is wrong with an audience, or `null` when it is well formed. Takes `unknown`: hosts assemble it at runtime. */
|
|
694
|
+
audienceProblem(audience) {
|
|
695
|
+
if (audience === null || typeof audience !== 'object') {
|
|
696
|
+
return `expected { Readers: UserInfo[] }, got ${this.describeValue(audience)}. Omit Audience for a search with no audience.`;
|
|
697
|
+
}
|
|
698
|
+
const readers = 'Readers' in audience ? audience.Readers : undefined;
|
|
699
|
+
if (!Array.isArray(readers)) {
|
|
700
|
+
return `Readers must be an array of hydrated UserInfo objects, got ${this.describeValue(readers)}.`;
|
|
701
|
+
}
|
|
702
|
+
const list = readers;
|
|
703
|
+
for (let i = 0; i < list.length; i++) {
|
|
704
|
+
const problem = this.audienceReaderProblem(list[i]);
|
|
705
|
+
if (problem)
|
|
706
|
+
return `Readers[${i}] ${problem}`;
|
|
707
|
+
}
|
|
708
|
+
return null;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* What is wrong with one reader, or `null`. A reader needs a non-empty `ID` and a `UserRoles` array:
|
|
712
|
+
* `[]` is a reader with no roles (legitimate, reads nothing); a missing array means it was never hydrated.
|
|
713
|
+
*/
|
|
714
|
+
audienceReaderProblem(reader) {
|
|
715
|
+
if (reader === null || typeof reader !== 'object') {
|
|
716
|
+
return `is ${this.describeValue(reader)}, not a UserInfo — map every participant to a hydrated user before searching for them.`;
|
|
717
|
+
}
|
|
718
|
+
const id = 'ID' in reader ? reader.ID : undefined;
|
|
719
|
+
if (typeof id !== 'string' || id.trim() === '') {
|
|
720
|
+
return 'has no ID — a reader the host could not map to a user would restrict nothing, so the search is refused.';
|
|
721
|
+
}
|
|
722
|
+
const roles = 'UserRoles' in reader ? reader.UserRoles : undefined;
|
|
723
|
+
if (!Array.isArray(roles)) {
|
|
724
|
+
return `(${id}) has no UserRoles array — pass hydrated UserInfo (e.g. from UserCache); a reader with no roles is \`UserRoles: []\`.`;
|
|
725
|
+
}
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
/** `null`, `an array`, or the `typeof` name: validation messages name a bad value's kind rather than echo it. */
|
|
729
|
+
describeValue(value) {
|
|
730
|
+
if (value === null)
|
|
731
|
+
return 'null';
|
|
732
|
+
if (Array.isArray(value))
|
|
733
|
+
return 'an array';
|
|
734
|
+
return typeof value;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* The readers an audience actually adds: one per distinct ID (case-insensitive), the caller's own ID left
|
|
738
|
+
* out. Empty when the audience changes nothing. Expects an audience that passed `validateAudience`.
|
|
739
|
+
*/
|
|
740
|
+
distinctReaders(audience, contextUser) {
|
|
741
|
+
if (!audience)
|
|
742
|
+
return [];
|
|
743
|
+
const seen = new Set();
|
|
744
|
+
const callerID = contextUser.ID?.toLowerCase();
|
|
745
|
+
if (callerID)
|
|
746
|
+
seen.add(callerID);
|
|
747
|
+
const readers = [];
|
|
748
|
+
for (const reader of audience.Readers) {
|
|
749
|
+
const id = reader.ID.toLowerCase();
|
|
750
|
+
if (seen.has(id))
|
|
751
|
+
continue;
|
|
752
|
+
seen.add(id);
|
|
753
|
+
readers.push(reader);
|
|
754
|
+
}
|
|
755
|
+
return readers;
|
|
756
|
+
}
|
|
757
|
+
/** The distinct reader IDs, lower-cased and sorted, for the cache key. `undefined` when the audience adds no reader, so it keys like no audience. */
|
|
758
|
+
audienceReaderIDs(audience, contextUser) {
|
|
759
|
+
const ids = this.distinctReaders(audience, contextUser).map(r => r.ID.toLowerCase()).sort();
|
|
760
|
+
return ids.length > 0 ? ids : undefined;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Keep only the results every reader in `params.Audience` may read, on top of the caller's own filter.
|
|
764
|
+
* Each reader gets the same safety net the caller did (`filterByPermissions`: entity read, row filters,
|
|
765
|
+
* ownership), so a shared conversation's results are the intersection of what every participant may see —
|
|
766
|
+
* the asker's reach is the ceiling, each other reader's reach lowers it. Readers are checked concurrently;
|
|
767
|
+
* a reader with the caller's own ID, or listed twice, is checked once. Expects a validated audience
|
|
768
|
+
* (`searchInternal` validates it before doing any work).
|
|
769
|
+
*
|
|
770
|
+
* Two things the pass cannot do, both failing closed:
|
|
771
|
+
* - **Storage hits are refused under an audience.** Their permission model is the storage account's;
|
|
772
|
+
* `filterByPermissions` re-checks a `storage-file` hit's account for the user it is given, but this pass
|
|
773
|
+
* does not yet combine those per-reader answers for storage, so a storage hit is not shown to the room.
|
|
774
|
+
* - **A reader with no roles (`UserRoles: []`) reads nothing.** Permissions and row filters are
|
|
775
|
+
* evaluated from `UserInfo.UserRoles`, so such a reader empties the result. A reader with no
|
|
776
|
+
* `UserRoles` array at all never gets here: validation refuses it.
|
|
777
|
+
*
|
|
778
|
+
* **Identity contract.** A result survives when every reader's `filterByPermissions` returns it. Survivors
|
|
779
|
+
* are matched to the input by `EntityName|RecordID` (the record the result names), falling back to object
|
|
780
|
+
* identity for a result that names no record. An override of `filterByPermissions` may therefore return
|
|
781
|
+
* copies, but must not rewrite `EntityName` or `RecordID`.
|
|
782
|
+
*
|
|
783
|
+
* Protected so a host can change how an audience combines (a host that materializes a shared reach in one
|
|
784
|
+
* query can replace the per-reader pass). It receives the whole `params`, so an override can see the anchor
|
|
785
|
+
* (`SearchContext`) and the scopes. The default is the intersection.
|
|
786
|
+
*/
|
|
787
|
+
async FilterForAudience(results, params, contextUser) {
|
|
788
|
+
const readers = this.distinctReaders(params.Audience, contextUser);
|
|
789
|
+
if (readers.length === 0 || results.length === 0)
|
|
790
|
+
return results;
|
|
791
|
+
const checkable = results.filter(r => r.ResultType !== 'storage-file');
|
|
792
|
+
if (checkable.length < results.length) {
|
|
793
|
+
LogStatus(`SearchEngine: ${results.length - checkable.length} storage result(s) dropped under an audience — ` +
|
|
794
|
+
'storage hits are re-checked for the caller only; per-reader storage checks are a follow-up.');
|
|
795
|
+
}
|
|
796
|
+
const survivors = await Promise.all(readers.map(reader => this.filterByPermissions(checkable, reader)));
|
|
797
|
+
this.logAudienceNarrowing(readers, survivors, checkable.length);
|
|
798
|
+
const keptByEveryReader = survivors.map(list => new Set(list.map(r => this.audienceIdentity(r))));
|
|
799
|
+
return checkable.filter(r => {
|
|
800
|
+
const identity = this.audienceIdentity(r);
|
|
801
|
+
return keptByEveryReader.every(kept => kept.has(identity));
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
/** `EntityName|RecordID` for a result that names a record, else the object itself — see `FilterForAudience`'s identity contract. */
|
|
805
|
+
audienceIdentity(result) {
|
|
806
|
+
return result.EntityName && result.RecordID ? `${result.EntityName}|${result.RecordID}` : result;
|
|
807
|
+
}
|
|
808
|
+
/** Log, per reader, why the shared result set shrank: a reader with no roles, or results a reader cannot read. */
|
|
809
|
+
logAudienceNarrowing(readers, survivors, checkedCount) {
|
|
810
|
+
readers.forEach((reader, i) => {
|
|
811
|
+
if (reader.UserRoles.length === 0) {
|
|
812
|
+
LogStatus(`SearchEngine: Audience reader ${reader.ID} has no roles (UserRoles: []) — permissions resolve ` +
|
|
813
|
+
'from roles, so expect it to read nothing and the shared result set to be empty.');
|
|
814
|
+
}
|
|
815
|
+
const dropped = checkedCount - survivors[i].length;
|
|
816
|
+
if (dropped > 0) {
|
|
817
|
+
LogStatus(`SearchEngine: Audience reader ${reader.ID} cannot read ${dropped} result(s) the caller can — ` +
|
|
818
|
+
'removed from the shared result set.');
|
|
819
|
+
}
|
|
820
|
+
});
|
|
821
|
+
}
|
|
606
822
|
/** Insert into the LRU cache, evicting oldest entries when over capacity. */
|
|
607
823
|
cachePut(key, result) {
|
|
608
824
|
if (this._cache.size >= SearchEngine.CACHE_MAX_ENTRIES) {
|
|
@@ -663,7 +879,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
663
879
|
*
|
|
664
880
|
* Unlike a real search this never throws for a scope-level problem; a scope that would fail
|
|
665
881
|
* closed comes back with `Reachable: false` and the reason, since "it would have failed"
|
|
666
|
-
* is precisely the finding the caller asked for.
|
|
882
|
+
* is precisely the finding the caller asked for. A scope that cannot be resolved (inactive,
|
|
883
|
+
* expired, or missing) refuses the whole search, so when one is named every scope comes back
|
|
884
|
+
* unreachable, each saying why.
|
|
667
885
|
*
|
|
668
886
|
* @param input scopes to explain plus the hypothetical caller context and principals
|
|
669
887
|
* @param contextUser the user to evaluate entitlement for
|
|
@@ -674,7 +892,23 @@ export class SearchEngine extends BaseSingleton {
|
|
|
674
892
|
for (const scopeID of input.ScopeIDs) {
|
|
675
893
|
explanations.push(await this.explainOneScope(scopeID, input, contextUser));
|
|
676
894
|
}
|
|
677
|
-
return explanations;
|
|
895
|
+
return this.markRefusedTogether(explanations, this.resolveScopes(input.ScopeIDs).Unresolved);
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* A search naming a scope it cannot resolve is refused outright (see `refuseUnresolvableScopes`), so a dry
|
|
899
|
+
* run over the same IDs reaches nothing through ANY of them — including a scope that is reachable on its
|
|
900
|
+
* own. Each such scope is marked unreachable with the reason; the unresolvable ones already explain
|
|
901
|
+
* themselves.
|
|
902
|
+
*/
|
|
903
|
+
markRefusedTogether(explanations, unresolved) {
|
|
904
|
+
if (unresolved.length === 0)
|
|
905
|
+
return explanations;
|
|
906
|
+
const note = `searched together with ${unresolved.join(', ')}, which cannot be resolved, the search is refused — `
|
|
907
|
+
+ 'this scope reaches nothing in it (on its own it would be searched as explained above)';
|
|
908
|
+
const unresolvedIDs = new UUIDSet(unresolved);
|
|
909
|
+
return explanations.map(e => unresolvedIDs.Has(e.ScopeID)
|
|
910
|
+
? e
|
|
911
|
+
: { ...e, Reachable: false, Diagnostics: [...e.Diagnostics, note] });
|
|
678
912
|
}
|
|
679
913
|
/**
|
|
680
914
|
* Build the principal set a dimension's expansion query may bind.
|
|
@@ -693,8 +927,10 @@ export class SearchEngine extends BaseSingleton {
|
|
|
693
927
|
}
|
|
694
928
|
/** Explain a single scope. Never throws — a failure to resolve IS the explanation. */
|
|
695
929
|
async explainOneScope(scopeID, input, contextUser) {
|
|
696
|
-
|
|
697
|
-
|
|
930
|
+
// Active first, as the search resolves it: `GetScopeBundle` alone finds a scope of any status, so an
|
|
931
|
+
// inactive or expired scope used to be explained as searchable while the search refused it.
|
|
932
|
+
const scope = this.Base.GetActiveScopeByID(scopeID);
|
|
933
|
+
const bundle = scope ? this.Base.GetScopeBundle(scopeID) : undefined;
|
|
698
934
|
if (!bundle || !scope) {
|
|
699
935
|
return this.buildUnresolvableExplanation(scopeID, input, contextUser);
|
|
700
936
|
}
|
|
@@ -728,7 +964,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
728
964
|
// principal-side — the principal IS the reason — yet their ids were still bound into the
|
|
729
965
|
// expansion query. This is the same set the Scoped Search action classifies as
|
|
730
966
|
// ACCESS_DENIED rather than PERMISSION_DENIED, for the same reason.
|
|
731
|
-
// A TOTAL MAP, NOT A LIST: `
|
|
967
|
+
// A TOTAL MAP, NOT A LIST: `EntitlementSource` is a closed union, so writing
|
|
732
968
|
// this as `Record<Source, boolean>` makes the compiler demand an answer for any source
|
|
733
969
|
// added later. As a `string[]` a new principal-side source would silently default to
|
|
734
970
|
// "bind it" — which is the exact defect this block exists to fix, re-openable by an
|
|
@@ -748,6 +984,8 @@ export class SearchEngine extends BaseSingleton {
|
|
|
748
984
|
DirectGrant: false,
|
|
749
985
|
RoleGrant: false,
|
|
750
986
|
NoGrant: false,
|
|
987
|
+
// Scope-side, and unreachable here: an unresolvable scope is explained before entitlement.
|
|
988
|
+
ScopeUnresolvable: false,
|
|
751
989
|
};
|
|
752
990
|
const principalsJudged = entitlement.Allowed || !IS_PRINCIPAL_SIDE[entitlement.Source];
|
|
753
991
|
if (!principalsJudged && (input.AIAgentID || input.AISkillID)) {
|
|
@@ -775,16 +1013,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
775
1013
|
const lanes = dimensionFailure
|
|
776
1014
|
? this.buildAllLanesSkipped(bundle, `dimension resolution failed: ${dimensionFailure}`)
|
|
777
1015
|
: this.explainLanes(bundle, effectiveContext);
|
|
778
|
-
//
|
|
779
|
-
//
|
|
780
|
-
//
|
|
781
|
-
//
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
if (!hasLanes) {
|
|
785
|
-
diagnostics.push(UNBOUNDED_SCOPE_DIAGNOSTIC);
|
|
786
|
-
}
|
|
787
|
-
const canRetrieve = hasLanes ? lanes.some((l) => l.Status === 'Active') : true;
|
|
1016
|
+
// What the scope's rows let it reach — which providers run (listed, configured, available, and reading
|
|
1017
|
+
// a lane kind the scope configures) over which lanes — by the same judgement the search path makes, for
|
|
1018
|
+
// a full (non-preview) search. A lane skipped here is one the real search would refuse on, so a skipped
|
|
1019
|
+
// lane makes the scope unreachable rather than "reachable through the others".
|
|
1020
|
+
const bound = this.judgeScopeBound(bundle, lanes, false);
|
|
1021
|
+
diagnostics.push(...bound.Diagnostics);
|
|
788
1022
|
return {
|
|
789
1023
|
ScopeID: scope.ID,
|
|
790
1024
|
ScopeName: scope.Name,
|
|
@@ -792,11 +1026,75 @@ export class SearchEngine extends BaseSingleton {
|
|
|
792
1026
|
Dimensions: dimensions,
|
|
793
1027
|
Lanes: lanes,
|
|
794
1028
|
Diagnostics: diagnostics,
|
|
795
|
-
Reachable: entitlement.Allowed &&
|
|
796
|
-
Unbounded:
|
|
1029
|
+
Reachable: entitlement.Allowed && bound.CanRetrieve && !dimensionFailure,
|
|
1030
|
+
Unbounded: bound.Unbounded,
|
|
797
1031
|
ResolvedContext: effectiveContext,
|
|
798
1032
|
};
|
|
799
1033
|
}
|
|
1034
|
+
/**
|
|
1035
|
+
* What a scope's configuration lets it reach. One judgement, used by the dry run and the search path — and
|
|
1036
|
+
* the search path calls exactly the `Providers` it returns, so the two cannot disagree about who runs.
|
|
1037
|
+
*
|
|
1038
|
+
* A GLOBAL scope runs unconstrained (the search path never builds constraints for it), so with no
|
|
1039
|
+
* lanes it is unbounded. A NON-global scope is bounded by its rows: it runs only the providers its enabled
|
|
1040
|
+
* rows name that are configured and available (and support preview, for a preview search), and of those
|
|
1041
|
+
* only the ones that read a lane kind the scope has an active lane of (`BaseSearchProvider.ConsumesLaneKinds`).
|
|
1042
|
+
* With none of those, it reaches nothing — an empty configuration never means "everything". A skipped lane
|
|
1043
|
+
* (only a dry run has one) is a problem the real search refuses on, so it makes the scope unreachable too.
|
|
1044
|
+
*/
|
|
1045
|
+
judgeScopeBound(bundle, lanes, isPreview) {
|
|
1046
|
+
if (bundle.Scope.IsGlobal)
|
|
1047
|
+
return this.judgeGlobalScopeBound(lanes, isPreview);
|
|
1048
|
+
const runnable = this.runnableScopeProviders(bundle, isPreview);
|
|
1049
|
+
const serving = this.providersWithAnActiveLane(runnable, lanes);
|
|
1050
|
+
const skipped = lanes.filter((l) => l.Status === 'Skipped');
|
|
1051
|
+
const diagnostics = [];
|
|
1052
|
+
if (bundle.Providers.length === 0)
|
|
1053
|
+
diagnostics.push(NO_PROVIDER_ROWS_DIAGNOSTIC);
|
|
1054
|
+
else if (runnable.length === 0)
|
|
1055
|
+
diagnostics.push(noRunnableProviderDiagnostic(isPreview));
|
|
1056
|
+
if (lanes.length === 0)
|
|
1057
|
+
diagnostics.push(NO_LANES_DIAGNOSTIC);
|
|
1058
|
+
if (skipped.length > 0)
|
|
1059
|
+
diagnostics.push(refusedLanesDiagnostic(skipped));
|
|
1060
|
+
const hasActiveLane = lanes.some((l) => l.Status === 'Active');
|
|
1061
|
+
if (runnable.length > 0 && hasActiveLane && serving.length === 0)
|
|
1062
|
+
diagnostics.push(noProviderReadsALaneDiagnostic(runnable, lanes));
|
|
1063
|
+
const canRetrieve = serving.length > 0 && skipped.length === 0;
|
|
1064
|
+
return { CanRetrieve: canRetrieve, Unbounded: false, Diagnostics: diagnostics, Providers: canRetrieve ? serving : [] };
|
|
1065
|
+
}
|
|
1066
|
+
/** {@link judgeScopeBound} for a global scope, which runs every available provider unconstrained. */
|
|
1067
|
+
judgeGlobalScopeBound(lanes, isPreview) {
|
|
1068
|
+
const hasLanes = lanes.length > 0;
|
|
1069
|
+
return {
|
|
1070
|
+
CanRetrieve: hasLanes ? lanes.some((l) => l.Status === 'Active') : true,
|
|
1071
|
+
Unbounded: !hasLanes,
|
|
1072
|
+
Diagnostics: hasLanes ? [] : [UNBOUNDED_SCOPE_DIAGNOSTIC],
|
|
1073
|
+
Providers: this.availableProviders(isPreview),
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
/** The configured entries a search may call: available now, and preview-capable for a preview search. */
|
|
1077
|
+
availableProviders(isPreview) {
|
|
1078
|
+
return this._providerEntries.filter(entry => entry.Provider.IsAvailable() && (!isPreview || entry.SupportsPreview));
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* The available entries a NON-global scope's enabled provider rows name. A non-global scope runs ONLY the
|
|
1082
|
+
* providers it lists: no enabled row means no provider, never every provider (disabling a scope's last row
|
|
1083
|
+
* used to widen it to all of them).
|
|
1084
|
+
*/
|
|
1085
|
+
runnableScopeProviders(bundle, isPreview) {
|
|
1086
|
+
const listed = new Set(bundle.Providers.map(p => NormalizeUUID(p.SearchProviderID)));
|
|
1087
|
+
return this.availableProviders(isPreview).filter(entry => listed.has(NormalizeUUID(entry.ID)));
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Of `entries`, the ones with at least one ACTIVE lane of a kind they read (`ConsumesLaneKinds`). A provider
|
|
1091
|
+
* whose lane kinds are all empty in the scope is never called: it could only search nothing, or — written with
|
|
1092
|
+
* the old `?.length` pattern — fall back to its unscoped default.
|
|
1093
|
+
*/
|
|
1094
|
+
providersWithAnActiveLane(entries, lanes) {
|
|
1095
|
+
const activeKinds = new Set(lanes.filter((l) => l.Status === 'Active').map((l) => l.Kind));
|
|
1096
|
+
return entries.filter(entry => entry.Provider.ConsumesLaneKinds.some(kind => activeKinds.has(kind)));
|
|
1097
|
+
}
|
|
800
1098
|
/** Resolve entitlement for the dry run, including the skill and tenant principals.
|
|
801
1099
|
* `protected`, like {@link principalsFrom}, so a test can drive it without weak-typed casts.
|
|
802
1100
|
*/
|
|
@@ -933,10 +1231,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
933
1231
|
Kind: 'StorageAccount',
|
|
934
1232
|
Target: row.FileStorageAccountID,
|
|
935
1233
|
LaneID: row.ID,
|
|
936
|
-
// FolderPath
|
|
937
|
-
//
|
|
938
|
-
Status: 'Active',
|
|
1234
|
+
// FolderPath restricts the lane to one folder, so a path that rendered empty, with an
|
|
1235
|
+
// empty segment, or with traversal makes the lane unusable — as buildScopeConstraints rules.
|
|
1236
|
+
Status: problems.has(row.ID) ? 'Skipped' : 'Active',
|
|
939
1237
|
RenderedFilter: rendered?.FolderPath ?? null,
|
|
1238
|
+
Reason: problems.get(row.ID),
|
|
940
1239
|
});
|
|
941
1240
|
}
|
|
942
1241
|
return lanes;
|
|
@@ -990,11 +1289,13 @@ export class SearchEngine extends BaseSingleton {
|
|
|
990
1289
|
buildUnresolvableExplanation(scopeID, input, contextUser) {
|
|
991
1290
|
return {
|
|
992
1291
|
ScopeID: scopeID,
|
|
993
|
-
|
|
1292
|
+
// An inactive or expired scope still has a row, and its name is what an admin will recognise.
|
|
1293
|
+
ScopeName: this.Base.GetScopeByID(scopeID)?.Name ?? '(not found)',
|
|
994
1294
|
Entitlement: {
|
|
995
1295
|
Allowed: false,
|
|
996
1296
|
Level: 'None',
|
|
997
|
-
|
|
1297
|
+
// Not 'NoGrant': nothing about the caller's grants was judged — the scope's status refused it.
|
|
1298
|
+
Source: 'ScopeUnresolvable',
|
|
998
1299
|
Reason: 'the scope is inactive, expired, or does not exist, so no search can use it',
|
|
999
1300
|
Principals: {
|
|
1000
1301
|
UserID: contextUser.ID ?? null,
|
|
@@ -1005,7 +1306,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1005
1306
|
},
|
|
1006
1307
|
Dimensions: [],
|
|
1007
1308
|
Lanes: [],
|
|
1008
|
-
Diagnostics: [`scope "${scopeID}" is not an active scope`],
|
|
1309
|
+
Diagnostics: [`scope "${scopeID}" is not an active scope — a search naming it is refused, never widened to a global search`],
|
|
1009
1310
|
Reachable: false,
|
|
1010
1311
|
// Not "known to be bounded" — the scope could not be loaded, so nothing about its
|
|
1011
1312
|
// configuration was observed. It is unreachable either way.
|
|
@@ -1033,24 +1334,56 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1033
1334
|
// Scope resolution
|
|
1034
1335
|
// ────────────────────────────────────────────────────────────────
|
|
1035
1336
|
/**
|
|
1036
|
-
* Load `ScopeBundle`
|
|
1037
|
-
*
|
|
1337
|
+
* Load the `ScopeBundle` of each requested scope ID that names a scope active right now, and collect the IDs
|
|
1338
|
+
* that do not (inactive, expired, or missing). A search refuses when any ID is unresolved
|
|
1339
|
+
* ({@link refuseUnresolvableScopes}); `ExplainScope` reports the same. No IDs → no bundles, which the
|
|
1340
|
+
* search treats as Global.
|
|
1038
1341
|
*/
|
|
1039
1342
|
resolveScopes(scopeIDs) {
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
for (const id of scopeIDs) {
|
|
1044
|
-
const scope = this.Base.GetActiveScopeByID(id);
|
|
1045
|
-
if (!scope) {
|
|
1046
|
-
LogStatus(`SearchEngine: Requested scope "${id}" is not active or does not exist — skipping.`);
|
|
1047
|
-
continue;
|
|
1048
|
-
}
|
|
1049
|
-
const bundle = this.Base.GetScopeBundle(id);
|
|
1343
|
+
const resolution = { Bundles: [], Unresolved: [] };
|
|
1344
|
+
for (const id of scopeIDs ?? []) {
|
|
1345
|
+
const bundle = this.Base.GetActiveScopeByID(id) ? this.Base.GetScopeBundle(id) : undefined;
|
|
1050
1346
|
if (bundle)
|
|
1051
|
-
|
|
1347
|
+
resolution.Bundles.push(bundle);
|
|
1348
|
+
else
|
|
1349
|
+
resolution.Unresolved.push(id);
|
|
1052
1350
|
}
|
|
1053
|
-
return
|
|
1351
|
+
return resolution;
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Refuse a search that named a scope the engine cannot resolve (inactive, expired, or missing): an error
|
|
1355
|
+
* result and a `Failure` row in `MJ: Search Execution Logs`, never a wider search.
|
|
1356
|
+
*
|
|
1357
|
+
* Before, an unresolvable scope was skipped, and a search whose scopes were all skipped ran UNSCOPED —
|
|
1358
|
+
* every provider, every entity, no scope filter — because no resolved scope reads as Global. Refused when
|
|
1359
|
+
* ANY named scope fails, not only when all do: dropping one of several scopes silently changes what the
|
|
1360
|
+
* caller asked for, and nothing in the results would tell them. An error result is how the engine already
|
|
1361
|
+
* reports a scope it refuses (a `ScopeDimensionError`, a restricting filter that did not render).
|
|
1362
|
+
*/
|
|
1363
|
+
refuseUnresolvableScopes(unresolved, params, contextUser, startTime) {
|
|
1364
|
+
const named = `${unresolved.length === 1 ? 'scope' : 'scopes'} ${unresolved.map(id => `"${id}"`).join(', ')}`;
|
|
1365
|
+
const message = `SearchEngine: search refused — ${named} could not be resolved (inactive, expired, or not found). ` +
|
|
1366
|
+
'A search naming a scope it cannot resolve is refused, never run without that scope.';
|
|
1367
|
+
LogError(message);
|
|
1368
|
+
this.logSearchExecution({
|
|
1369
|
+
Status: 'Failure',
|
|
1370
|
+
FailureReason: message,
|
|
1371
|
+
Query: params.Query,
|
|
1372
|
+
// The log row's SearchScopeID is a foreign key, so it names a scope row that exists, or none — and it
|
|
1373
|
+
// must name a scope that was REFUSED: the first unresolved scope that has a row (inactive or expired),
|
|
1374
|
+
// never a valid scope searched beside a missing one, which would attribute the refusal to it.
|
|
1375
|
+
ScopeIDs: unresolved.filter(id => this.Base.GetScopeByID(id) !== undefined).slice(0, 1),
|
|
1376
|
+
StartTime: startTime,
|
|
1377
|
+
ResultCount: 0,
|
|
1378
|
+
RerankerName: null,
|
|
1379
|
+
RerankerCostCents: null,
|
|
1380
|
+
SourceCounts: undefined,
|
|
1381
|
+
ContextUser: contextUser,
|
|
1382
|
+
AIAgentID: params.AIAgentID ?? null,
|
|
1383
|
+
AISkillID: params.AISkillID ?? null,
|
|
1384
|
+
PrimaryScopeRecordID: params.SearchContext?.PrimaryScopeRecordID ?? null,
|
|
1385
|
+
});
|
|
1386
|
+
return this.buildErrorResult(message, startTime);
|
|
1054
1387
|
}
|
|
1055
1388
|
/**
|
|
1056
1389
|
* Execute all scoped providers for a single scope bundle and return per-scope fused results.
|
|
@@ -1064,7 +1397,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1064
1397
|
* one at search time — making the preview quietly wrong in the only direction anybody
|
|
1065
1398
|
* cares about.
|
|
1066
1399
|
*/
|
|
1067
|
-
principals, onProviderResolved) {
|
|
1400
|
+
principals, onProviderResolved, minScore) {
|
|
1068
1401
|
const scope = bundle.Scope;
|
|
1069
1402
|
const scopeConfig = this.parseJson(scope.ScopeConfig);
|
|
1070
1403
|
// Resolve this scope's DECLARED dimensions before building any constraint. For a scope
|
|
@@ -1088,46 +1421,27 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1088
1421
|
// than re-rendering every template a second time. Reaching this line means every lane
|
|
1089
1422
|
// guard passed (buildScopeConstraints throws otherwise), so the problem map is empty
|
|
1090
1423
|
// and every lane is Active.
|
|
1091
|
-
const
|
|
1092
|
-
|
|
1093
|
-
|
|
1424
|
+
const lanes = this.buildLaneExplanations(bundle, constraints, new Map());
|
|
1425
|
+
// The same judgement the dry run makes, so both produce the same verdict and the same prose —
|
|
1426
|
+
// an auditor reading a log row should not have to know which path wrote it. Its `Providers` are the ones
|
|
1427
|
+
// this search calls: listed by an enabled row, configured, available (preview-capable for a preview), and
|
|
1428
|
+
// reading a lane kind this scope configures.
|
|
1429
|
+
const bound = this.judgeScopeBound(bundle, lanes, isPreview);
|
|
1094
1430
|
const decision = {
|
|
1095
1431
|
ScopeID: scope.ID,
|
|
1096
1432
|
ScopeName: scope.Name,
|
|
1097
1433
|
Entitlement: null,
|
|
1098
1434
|
Dimensions: dimensionResult.Provenance,
|
|
1099
|
-
Lanes:
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
Diagnostics: unbounded
|
|
1104
|
-
? [...dimensionResult.Diagnostics, UNBOUNDED_SCOPE_DIAGNOSTIC]
|
|
1105
|
-
: dimensionResult.Diagnostics,
|
|
1106
|
-
Reachable: true,
|
|
1107
|
-
Unbounded: unbounded,
|
|
1435
|
+
Lanes: lanes,
|
|
1436
|
+
Diagnostics: [...dimensionResult.Diagnostics, ...bound.Diagnostics],
|
|
1437
|
+
Reachable: bound.CanRetrieve,
|
|
1438
|
+
Unbounded: bound.Unbounded,
|
|
1108
1439
|
ResolvedContext: effectiveContext,
|
|
1109
1440
|
};
|
|
1110
|
-
|
|
1111
|
-
const scopeProviderIDs = new Set(bundle.Providers.map(p => NormalizeUUID(p.SearchProviderID)));
|
|
1112
|
-
const allowAllProviders = scopeProviderIDs.size === 0; // empty = scope is IsGlobal or all-inclusive
|
|
1113
|
-
const applicableProviders = this._providerEntries.filter(entry => {
|
|
1114
|
-
if (!entry.Provider.IsAvailable())
|
|
1115
|
-
return false;
|
|
1116
|
-
if (isPreview && !entry.SupportsPreview)
|
|
1117
|
-
return false;
|
|
1118
|
-
if (allowAllProviders)
|
|
1119
|
-
return true;
|
|
1120
|
-
return scopeProviderIDs.has(NormalizeUUID(entry.ID));
|
|
1121
|
-
});
|
|
1441
|
+
const applicableProviders = bound.Providers;
|
|
1122
1442
|
if (applicableProviders.length === 0) {
|
|
1123
|
-
LogStatus(`SearchEngine: Scope "${scope.Name}"
|
|
1124
|
-
return {
|
|
1125
|
-
scopeID: scope.ID,
|
|
1126
|
-
fused: [],
|
|
1127
|
-
sourceCounts: { Vector: 0, FullText: 0, Entity: 0, Storage: 0 },
|
|
1128
|
-
decision: { ...decision, Reachable: false,
|
|
1129
|
-
Diagnostics: [...decision.Diagnostics, 'no applicable providers for this scope'] },
|
|
1130
|
-
};
|
|
1443
|
+
LogStatus(`SearchEngine: Scope "${scope.Name}" runs no provider — skipping. ${bound.Diagnostics.join(' ')}`);
|
|
1444
|
+
return { scopeID: scope.ID, fused: [], sourceCounts: { Vector: 0, FullText: 0, Entity: 0, Storage: 0 }, decision };
|
|
1131
1445
|
}
|
|
1132
1446
|
// Resolve per-provider `SearchScopeProvider.MaxResultsOverride` if present
|
|
1133
1447
|
const promises = applicableProviders.map(async (entry) => {
|
|
@@ -1144,7 +1458,7 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1144
1458
|
// (Note: actual Nunjucks-rendered `QueryTransformTemplateID` resolution for
|
|
1145
1459
|
// stored templates lives in AgentPreExecutionRAG/ScopedSearchAction, not here.
|
|
1146
1460
|
// This engine only forwards already-rendered strings that the caller provides.)
|
|
1147
|
-
const providerResults = await entry.Provider.Search(query, effectiveTopK, filters, contextUser, perProviderConstraints);
|
|
1461
|
+
const providerResults = ApplySemanticFloor(entry.Provider.SourceType, await entry.Provider.Search(query, effectiveTopK, filters, contextUser, perProviderConstraints), minScore);
|
|
1148
1462
|
// Stamp provider metadata onto each result
|
|
1149
1463
|
for (const r of providerResults) {
|
|
1150
1464
|
r.ProviderId = entry.ID;
|
|
@@ -1184,7 +1498,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1184
1498
|
return { Source: entry.Provider.SourceType, Results: [] };
|
|
1185
1499
|
}
|
|
1186
1500
|
});
|
|
1187
|
-
|
|
1501
|
+
// A lane's ExtraFilter bounds its entity for EVERY provider, not only the entity lane that applies it in SQL —
|
|
1502
|
+
// including a content-item hit promoted to its origin record, which is promoted here, per scope, for that reason.
|
|
1503
|
+
const labeled = await this.boundScopeHits(await Promise.all(promises), constraints, contextUser, scope.Name);
|
|
1188
1504
|
const sourceCounts = this.countSources(labeled);
|
|
1189
1505
|
// Per-scope fusion with weight resolution:
|
|
1190
1506
|
// agent fusion weights > scope.ScopeConfig.fusionWeights > engine defaults
|
|
@@ -1195,6 +1511,148 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1195
1511
|
const fused = this._fusion.Fuse(labeled, topK, fusionWeights);
|
|
1196
1512
|
return { scopeID: scope.ID, fused, sourceCounts, decision };
|
|
1197
1513
|
}
|
|
1514
|
+
// ────────────────────────────────────────────────────────────────
|
|
1515
|
+
// Lane ExtraFilter: one bound per entity, for every provider
|
|
1516
|
+
// ────────────────────────────────────────────────────────────────
|
|
1517
|
+
/**
|
|
1518
|
+
* Hold one scope's hits to its lane bounds, before fusion, in three steps:
|
|
1519
|
+
* 1. every hit, against the lane `ExtraFilter` of the entity it names ({@link enforceLaneExtraFilters});
|
|
1520
|
+
* 2. content-item promotion: a `MJ: Content Items` hit derived from an entity record becomes that record,
|
|
1521
|
+
* marked `PromotedFromContentItemID` (`SearchEnricher.ExcludeEntitySourcedContentItems`);
|
|
1522
|
+
* 3. every PROMOTED hit, against the lane `ExtraFilter` of the origin entity it now names.
|
|
1523
|
+
*
|
|
1524
|
+
* Step 1 holds a content-item hit to a Content Items lane; step 3 holds the record it became to that
|
|
1525
|
+
* record's lane. Promotion used to run once, after cross-scope fusion, so a promoted hit met no lane bound:
|
|
1526
|
+
* a vector hit on a content item became a row of a bounded entity from outside the bound. `searchInternal`
|
|
1527
|
+
* promotes only unconstrained results (which have no lane bounds), so nothing is promoted twice.
|
|
1528
|
+
*/
|
|
1529
|
+
async boundScopeHits(lists, constraints, contextUser, scopeName) {
|
|
1530
|
+
const bounded = await this.enforceLaneExtraFilters(lists, constraints, contextUser, scopeName, 'all');
|
|
1531
|
+
const promoted = await this.promoteContentItems(bounded, contextUser);
|
|
1532
|
+
return this.enforceLaneExtraFilters(promoted, constraints, contextUser, scopeName, 'promoted');
|
|
1533
|
+
}
|
|
1534
|
+
/** Content-item promotion, per provider list. A list with no `MJ: Content Items` hit comes back unchanged, unread. */
|
|
1535
|
+
async promoteContentItems(lists, contextUser) {
|
|
1536
|
+
this._enricher.Provider = this.ProviderToUse;
|
|
1537
|
+
return Promise.all(lists.map(async (list) => ({
|
|
1538
|
+
...list,
|
|
1539
|
+
Results: await this._enricher.ExcludeEntitySourcedContentItems(list.Results, contextUser),
|
|
1540
|
+
})));
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* Enforce each entity lane's rendered `ExtraFilter` on the hits of every OTHER provider.
|
|
1544
|
+
*
|
|
1545
|
+
* The entity lane applies its ExtraFilter in SQL. The full-text and tag lanes take only the lanes'
|
|
1546
|
+
* entity NAMES, and the vector and 3rd-party lanes key off their own index rows — so a scope that bounds
|
|
1547
|
+
* an entity with an ExtraFilter still returned rows outside it through every lane but one. Here a hit for
|
|
1548
|
+
* an entity with a lane ExtraFilter in this scope is kept only when its record satisfies that filter,
|
|
1549
|
+
* read as the user: `PK IN (...) AND (<ExtraFilter>)`, one RunView per filtered entity per scope (the
|
|
1550
|
+
* permission pass's readability check, with the lane's filter as the clause). The filter is the exact
|
|
1551
|
+
* string the entity lane runs: same template, same context, same escaping.
|
|
1552
|
+
*
|
|
1553
|
+
* Exemption follows the provider the ENGINE stamped on the hit (`ProviderId`, through
|
|
1554
|
+
* {@link ProviderForResult}): only a provider declaring `BaseSearchProvider.AppliesLaneExtraFilter` (the entity
|
|
1555
|
+
* provider) applied the filter already. `SourceType` is provider-declared and proves nothing, and a promoted
|
|
1556
|
+
* content-item hit is never exempt (the filter it met, if any, was the Content Items lane's). Storage files are
|
|
1557
|
+
* not entity records and pass. `pass` is `'promoted'` to check only promoted hits ({@link boundScopeHits}).
|
|
1558
|
+
* Fails closed: a failed read drops that entity's hits from the other providers.
|
|
1559
|
+
*/
|
|
1560
|
+
async enforceLaneExtraFilters(lists, constraints, contextUser, scopeName, pass) {
|
|
1561
|
+
const bounds = this.laneEntityBounds(constraints.Entities);
|
|
1562
|
+
if (bounds.size === 0)
|
|
1563
|
+
return lists;
|
|
1564
|
+
const boundOf = (item) => this.laneBoundFor(item, bounds, pass);
|
|
1565
|
+
const candidates = new Map();
|
|
1566
|
+
for (const item of lists.flatMap(l => l.Results)) {
|
|
1567
|
+
const bound = boundOf(item);
|
|
1568
|
+
if (bound)
|
|
1569
|
+
candidates.set(bound, [...(candidates.get(bound) ?? []), item]);
|
|
1570
|
+
}
|
|
1571
|
+
if (candidates.size === 0)
|
|
1572
|
+
return lists;
|
|
1573
|
+
const kept = await this.hitsInsideLaneFilters(candidates, contextUser, scopeName);
|
|
1574
|
+
const bounded = lists.map(list => ({ ...list, Results: list.Results.filter(r => !boundOf(r) || kept.has(r)) }));
|
|
1575
|
+
const removed = lists.reduce((n, l) => n + l.Results.length, 0) - bounded.reduce((n, l) => n + l.Results.length, 0);
|
|
1576
|
+
if (removed > 0) {
|
|
1577
|
+
LogStatus(`SearchEngine: scope "${scopeName}" — lane ExtraFilters removed ${removed} hit(s) ` +
|
|
1578
|
+
'that other providers returned outside the entity lane\'s bound.');
|
|
1579
|
+
}
|
|
1580
|
+
return bounded;
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Each entity's lane bound, keyed by {@link laneEntityKey}. Several lanes on one entity are a union (the
|
|
1584
|
+
* entity lane searches each), so their filters are ORed; an entity with any UNFILTERED lane is unbounded
|
|
1585
|
+
* for this scope and gets no entry. A lane whose entity could not be named is skipped.
|
|
1586
|
+
*/
|
|
1587
|
+
laneEntityBounds(lanes) {
|
|
1588
|
+
const filters = new Map();
|
|
1589
|
+
for (const lane of lanes ?? []) {
|
|
1590
|
+
const key = this.laneEntityKey(lane.EntityName);
|
|
1591
|
+
if (!key)
|
|
1592
|
+
continue;
|
|
1593
|
+
const filter = lane.ExtraFilter?.trim();
|
|
1594
|
+
const prior = filters.get(key);
|
|
1595
|
+
const merged = !filter || prior?.Filters === null ? null : [...(prior?.Filters ?? []), filter];
|
|
1596
|
+
filters.set(key, { EntityName: lane.EntityName, Filters: merged });
|
|
1597
|
+
}
|
|
1598
|
+
const bounds = new Map();
|
|
1599
|
+
for (const [key, entry] of filters) {
|
|
1600
|
+
if (!entry.Filters)
|
|
1601
|
+
continue;
|
|
1602
|
+
const clause = entry.Filters.length === 1 ? entry.Filters[0] : entry.Filters.map(f => `(${f})`).join(' OR ');
|
|
1603
|
+
bounds.set(key, { EntityName: entry.EntityName, Clause: clause });
|
|
1604
|
+
}
|
|
1605
|
+
return bounds;
|
|
1606
|
+
}
|
|
1607
|
+
/** An entity name normalised for matching a hit's `EntityName` to a lane's. */
|
|
1608
|
+
laneEntityKey(entityName) {
|
|
1609
|
+
return (entityName ?? '').trim().toLowerCase();
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* The lane bound `item` must satisfy in this `pass`, or `undefined` when it has none: a storage file, a hit
|
|
1613
|
+
* from a provider that applied the lane filter itself, a hit for an entity with no filtered lane — or, in the
|
|
1614
|
+
* `'promoted'` pass, a hit that was not promoted (step 1 of {@link boundScopeHits} already checked it).
|
|
1615
|
+
*/
|
|
1616
|
+
laneBoundFor(item, bounds, pass) {
|
|
1617
|
+
if (item.ResultType === 'storage-file')
|
|
1618
|
+
return undefined;
|
|
1619
|
+
if (pass === 'promoted' && !item.PromotedFromContentItemID)
|
|
1620
|
+
return undefined;
|
|
1621
|
+
if (this.providerThatReadRow(item)?.AppliesLaneExtraFilter === true)
|
|
1622
|
+
return undefined;
|
|
1623
|
+
return bounds.get(this.laneEntityKey(item.EntityName));
|
|
1624
|
+
}
|
|
1625
|
+
/** The candidate hits whose record satisfies its entity's lane bound — one read per entity, in parallel. */
|
|
1626
|
+
async hitsInsideLaneFilters(candidates, contextUser, scopeName) {
|
|
1627
|
+
const kept = new Set();
|
|
1628
|
+
await Promise.all(Array.from(candidates.entries()).map(async ([bound, hits]) => {
|
|
1629
|
+
for (const hit of await this.hitsInsideLaneFilter(bound, hits, contextUser, scopeName))
|
|
1630
|
+
kept.add(hit);
|
|
1631
|
+
}));
|
|
1632
|
+
return kept;
|
|
1633
|
+
}
|
|
1634
|
+
/** `hits` (all of `bound`'s entity) whose record satisfies the lane filter, read as the user; none when the read fails. */
|
|
1635
|
+
async hitsInsideLaneFilter(bound, hits, contextUser, scopeName) {
|
|
1636
|
+
try {
|
|
1637
|
+
const entity = this.ProviderToUse.EntityByName(bound.EntityName);
|
|
1638
|
+
if (!entity)
|
|
1639
|
+
throw new Error('the entity is not in metadata');
|
|
1640
|
+
const recordIDs = Array.from(new Set(hits.map(h => h.RecordID)));
|
|
1641
|
+
const keys = await this.readableRecordKeys(entity, recordIDs, bound.Clause, contextUser);
|
|
1642
|
+
if (!keys)
|
|
1643
|
+
throw new Error('the read failed');
|
|
1644
|
+
return hits.filter(h => {
|
|
1645
|
+
const key = this.recordMatchKey(entity, h.RecordID);
|
|
1646
|
+
return key !== null && keys.has(key);
|
|
1647
|
+
});
|
|
1648
|
+
}
|
|
1649
|
+
catch (e) {
|
|
1650
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1651
|
+
LogError(`SearchEngine: scope "${scopeName}" — ${hits.length} hit(s) of "${bound.EntityName}" ` +
|
|
1652
|
+
`could not be checked against the lane ExtraFilter, so they were dropped: ${msg}`);
|
|
1653
|
+
return [];
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1198
1656
|
/**
|
|
1199
1657
|
* Assemble a `ScopeConstraints` for a single scope: Nunjucks-render each template
|
|
1200
1658
|
* field against the `SearchContext`, then hand the rendered values to providers.
|
|
@@ -1203,12 +1661,12 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1203
1661
|
* Fail a search CLOSED when a scope field that RESTRICTS was authored but did not render
|
|
1204
1662
|
* usably (see `CheckRenderedTemplate`).
|
|
1205
1663
|
*
|
|
1206
|
-
* Throwing rather than dropping the offending row is deliberate. Dropping
|
|
1207
|
-
* the
|
|
1208
|
-
* `undefined` —
|
|
1209
|
-
*
|
|
1210
|
-
*
|
|
1211
|
-
*
|
|
1664
|
+
* Throwing rather than dropping the offending row is deliberate. Dropping one lane of
|
|
1665
|
+
* several would quietly change what the scope covers, and a scope's ONLY lane dropped used to
|
|
1666
|
+
* collapse to `undefined` — "unscoped" to every provider. (A non-global scope now hands providers
|
|
1667
|
+
* an empty list, which means "nothing", but a silently narrowed scope is still a wrong answer.)
|
|
1668
|
+
* A broken restricting template is a misconfiguration and should be loud and actionable, never
|
|
1669
|
+
* silently degraded.
|
|
1212
1670
|
*/
|
|
1213
1671
|
assertRestrictingTemplateRendered(source, rendered, fieldName, scopeLabel, rowLabel, laneID, collector) {
|
|
1214
1672
|
const check = CheckRenderedTemplate(source, rendered);
|
|
@@ -1261,55 +1719,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1261
1719
|
}
|
|
1262
1720
|
buildScopeConstraints(bundle, searchContext, collector) {
|
|
1263
1721
|
const scopeLabel = `${bundle.Scope.Name} (${bundle.Scope.ID})`;
|
|
1264
|
-
const externalIndexes = bundle.ExternalIndexes.map(row =>
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
const laneKind = LaneKindForIndexType(row.IndexType);
|
|
1268
|
-
const metadataFilter = RenderScopeJsonTemplate(row.MetadataFilter, searchContext, undefined, laneKind);
|
|
1269
|
-
this.assertRestrictingTemplateRendered(row.MetadataFilter, metadataFilter, 'MetadataFilter', scopeLabel, rowLabel, row.ID, collector);
|
|
1270
|
-
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, metadataFilter, scopeLabel, rowLabel, collector);
|
|
1271
|
-
// ExternalIndexConfig is JSON (namespace/routing), regardless of the filter dialect.
|
|
1272
|
-
const externalIndexConfig = RenderScopeTemplate(row.ExternalIndexConfig, searchContext, undefined, 'json');
|
|
1273
|
-
// ExternalIndexConfig can carry tenant routing (e.g. Pinecone `namespace`), so a
|
|
1274
|
-
// silent render failure here can widen retrieval just like a filter can.
|
|
1275
|
-
this.assertRestrictingTemplateRendered(row.ExternalIndexConfig, externalIndexConfig, 'ExternalIndexConfig', scopeLabel, rowLabel, row.ID, collector);
|
|
1276
|
-
return {
|
|
1277
|
-
SearchScopeExternalIndexID: row.ID,
|
|
1278
|
-
IndexType: row.IndexType,
|
|
1279
|
-
VectorIndexID: row.VectorIndexID ?? undefined,
|
|
1280
|
-
ExternalIndexName: row.ExternalIndexName ?? undefined,
|
|
1281
|
-
ExternalIndexConfig: this.parseJson(externalIndexConfig),
|
|
1282
|
-
MetadataFilter: metadataFilter
|
|
1283
|
-
};
|
|
1284
|
-
});
|
|
1285
|
-
const entities = bundle.Entities.map(row => {
|
|
1286
|
-
// The entity lane is T-SQL, so single quotes must be doubled.
|
|
1287
|
-
const extraFilter = row.ExtraFilter ? RenderScopeTemplate(row.ExtraFilter, searchContext, undefined, 'sql') : undefined;
|
|
1288
|
-
const entityLabel = this.lookupEntityName(row.EntityID) || row.EntityID;
|
|
1289
|
-
this.assertRestrictingTemplateRendered(row.ExtraFilter, extraFilter, 'ExtraFilter', scopeLabel, entityLabel, row.ID, collector);
|
|
1290
|
-
// The SQL lane loses a guarded clause exactly the way an index lane does — same
|
|
1291
|
-
// renderer, same SearchContext, same optional {% if %} blocks — and it is the lane
|
|
1292
|
-
// that reads the operational database, so it gets the same contract.
|
|
1293
|
-
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, extraFilter, scopeLabel, entityLabel, collector);
|
|
1294
|
-
return {
|
|
1295
|
-
SearchScopeEntityID: row.ID,
|
|
1296
|
-
EntityID: row.EntityID,
|
|
1297
|
-
EntityName: this.lookupEntityName(row.EntityID),
|
|
1298
|
-
ExtraFilter: extraFilter,
|
|
1299
|
-
// UserSearchString and FolderPath are NOT restrictions — they shape the query
|
|
1300
|
-
// text / a path prefix — so a soft render there cannot widen an access bound
|
|
1301
|
-
// and is deliberately left unguarded.
|
|
1302
|
-
// 'none' deliberately: this becomes QUERY TEXT, not syntax. Escaping it would corrupt
|
|
1303
|
-
// the search rather than protect it, and it cannot express a bound.
|
|
1304
|
-
UserSearchString: row.UserSearchString ? RenderScopeTemplate(row.UserSearchString, searchContext, undefined, 'none') : undefined
|
|
1305
|
-
};
|
|
1306
|
-
});
|
|
1307
|
-
const storage = bundle.StorageAccounts.map(row => ({
|
|
1308
|
-
SearchScopeStorageAccountID: row.ID,
|
|
1309
|
-
FileStorageAccountID: row.FileStorageAccountID,
|
|
1310
|
-
// Path traversal, not quoting, is the risk on a storage lane.
|
|
1311
|
-
FolderPath: row.FolderPath ? RenderScopeTemplate(row.FolderPath, searchContext, undefined, 'path') : undefined
|
|
1312
|
-
}));
|
|
1722
|
+
const externalIndexes = bundle.ExternalIndexes.map(row => this.buildExternalIndexConstraint(row, searchContext, scopeLabel, collector));
|
|
1723
|
+
const entities = bundle.Entities.map(row => this.buildEntityConstraint(row, searchContext, scopeLabel, collector));
|
|
1724
|
+
const storage = bundle.StorageAccounts.map(row => this.buildStorageConstraint(row, searchContext, scopeLabel, collector));
|
|
1313
1725
|
// Per-provider query transforms: resolved from SearchScopeProvider.QueryTransformTemplateID
|
|
1314
1726
|
// For stored template IDs we need the TemplateEngine — that resolution happens in
|
|
1315
1727
|
// Phase 1C (AgentPreExecutionRAG) before this engine is called. We still honor any
|
|
@@ -1319,15 +1731,106 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1319
1731
|
const queryTransforms = rawTransforms && typeof rawTransforms === 'object'
|
|
1320
1732
|
? { ...rawTransforms }
|
|
1321
1733
|
: undefined;
|
|
1734
|
+
// A NON-global scope hands every provider a defined list, even an empty one: an empty list means
|
|
1735
|
+
// "nothing for you", and `undefined` would read as "unscoped" — every entity, every index, no
|
|
1736
|
+
// filter. Only a global scope keeps the old collapse (it runs unconstrained anyway).
|
|
1737
|
+
const lanesOrUnscoped = (rows) => (rows.length || !bundle.Scope.IsGlobal ? rows : undefined);
|
|
1322
1738
|
return {
|
|
1323
|
-
ExternalIndexes: externalIndexes
|
|
1324
|
-
Entities: entities
|
|
1325
|
-
StorageAccounts: storage
|
|
1739
|
+
ExternalIndexes: lanesOrUnscoped(externalIndexes),
|
|
1740
|
+
Entities: lanesOrUnscoped(entities),
|
|
1741
|
+
StorageAccounts: lanesOrUnscoped(storage),
|
|
1326
1742
|
Context: searchContext,
|
|
1327
1743
|
QueryTransforms: queryTransforms,
|
|
1328
1744
|
ScopeConfig: scopeConfig ?? undefined
|
|
1329
1745
|
};
|
|
1330
1746
|
}
|
|
1747
|
+
/** One external-index lane's constraint, with its restricting fields guarded. */
|
|
1748
|
+
buildExternalIndexConstraint(row, searchContext, scopeLabel, collector) {
|
|
1749
|
+
const rowLabel = row.ExternalIndexName ?? row.ID;
|
|
1750
|
+
// §5.4: values are escaped for THIS lane's dialect automatically, derived from IndexType.
|
|
1751
|
+
const laneKind = LaneKindForIndexType(row.IndexType);
|
|
1752
|
+
const metadataFilter = RenderScopeJsonTemplate(row.MetadataFilter, searchContext, undefined, laneKind);
|
|
1753
|
+
this.assertRestrictingTemplateRendered(row.MetadataFilter, metadataFilter, 'MetadataFilter', scopeLabel, rowLabel, row.ID, collector);
|
|
1754
|
+
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, metadataFilter, scopeLabel, rowLabel, collector);
|
|
1755
|
+
// ExternalIndexConfig is JSON (namespace/routing), regardless of the filter dialect.
|
|
1756
|
+
const externalIndexConfig = RenderScopeTemplate(row.ExternalIndexConfig, searchContext, undefined, 'json');
|
|
1757
|
+
// ExternalIndexConfig can carry tenant routing (e.g. Pinecone `namespace`), so a
|
|
1758
|
+
// silent render failure here can widen retrieval just like a filter can.
|
|
1759
|
+
this.assertRestrictingTemplateRendered(row.ExternalIndexConfig, externalIndexConfig, 'ExternalIndexConfig', scopeLabel, rowLabel, row.ID, collector);
|
|
1760
|
+
return {
|
|
1761
|
+
SearchScopeExternalIndexID: row.ID,
|
|
1762
|
+
IndexType: row.IndexType,
|
|
1763
|
+
VectorIndexID: row.VectorIndexID ?? undefined,
|
|
1764
|
+
ExternalIndexName: row.ExternalIndexName ?? undefined,
|
|
1765
|
+
ExternalIndexConfig: this.parseJson(externalIndexConfig),
|
|
1766
|
+
MetadataFilter: metadataFilter
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
/** One entity lane's constraint: its `ExtraFilter` rendered for T-SQL and guarded. */
|
|
1770
|
+
buildEntityConstraint(row, searchContext, scopeLabel, collector) {
|
|
1771
|
+
// The entity lane is T-SQL, so single quotes must be doubled.
|
|
1772
|
+
const extraFilter = row.ExtraFilter ? RenderScopeTemplate(row.ExtraFilter, searchContext, undefined, 'sql') : undefined;
|
|
1773
|
+
const entityLabel = this.lookupEntityName(row.EntityID) || row.EntityID;
|
|
1774
|
+
this.assertRestrictingTemplateRendered(row.ExtraFilter, extraFilter, 'ExtraFilter', scopeLabel, entityLabel, row.ID, collector);
|
|
1775
|
+
// The SQL lane loses a guarded clause exactly the way an index lane does — same
|
|
1776
|
+
// renderer, same SearchContext, same optional {% if %} blocks — and it is the lane
|
|
1777
|
+
// that reads the operational database, so it gets the same contract.
|
|
1778
|
+
this.assertRequiredMetadataKeys(row.RequiredMetadataKeys, row.ID, extraFilter, scopeLabel, entityLabel, collector);
|
|
1779
|
+
return {
|
|
1780
|
+
SearchScopeEntityID: row.ID,
|
|
1781
|
+
EntityID: row.EntityID,
|
|
1782
|
+
EntityName: this.lookupEntityName(row.EntityID),
|
|
1783
|
+
ExtraFilter: extraFilter,
|
|
1784
|
+
// UserSearchString is NOT a restriction — it shapes the query text — so a soft
|
|
1785
|
+
// render there cannot widen an access bound and is deliberately left unguarded.
|
|
1786
|
+
// (FolderPath, by contrast, restricts; see buildStorageConstraint.)
|
|
1787
|
+
// 'none' deliberately: this becomes QUERY TEXT, not syntax. Escaping it would corrupt
|
|
1788
|
+
// the search rather than protect it, and it cannot express a bound.
|
|
1789
|
+
UserSearchString: row.UserSearchString ? RenderScopeTemplate(row.UserSearchString, searchContext, undefined, 'none') : undefined
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* One storage lane's constraint. `FolderPath` RESTRICTS — it is what confines the lane to one folder
|
|
1794
|
+
* of the account — so a FolderPath that was authored but renders empty, with an empty segment, with
|
|
1795
|
+
* a `..` segment, or with an interpolated value the `path` escaper refuses makes the lane unusable:
|
|
1796
|
+
* the search is refused (or, in a dry run, the lane is reported skipped). An absent FolderPath still
|
|
1797
|
+
* means the whole account.
|
|
1798
|
+
*/
|
|
1799
|
+
buildStorageConstraint(row, searchContext, scopeLabel, collector) {
|
|
1800
|
+
let folderPath;
|
|
1801
|
+
if (row.FolderPath) {
|
|
1802
|
+
folderPath = this.renderFolderPath(row.FolderPath, searchContext, scopeLabel, row, collector);
|
|
1803
|
+
if (folderPath !== undefined) {
|
|
1804
|
+
const check = CheckRenderedFolderPath(row.FolderPath, folderPath);
|
|
1805
|
+
if (check.Status === 'unusable')
|
|
1806
|
+
this.reportFolderPathProblem(check.Reason, scopeLabel, row, collector);
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
return {
|
|
1810
|
+
SearchScopeStorageAccountID: row.ID,
|
|
1811
|
+
FileStorageAccountID: row.FileStorageAccountID,
|
|
1812
|
+
FolderPath: folderPath,
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
/**
|
|
1816
|
+
* Render a storage lane's FolderPath on the `path` lane. The renderer throws when an interpolated value
|
|
1817
|
+
* is `..` or `.`, or contains a separator; that is reported as the lane's problem (undefined is returned
|
|
1818
|
+
* only in a dry run, where the problem is collected instead of thrown).
|
|
1819
|
+
*/
|
|
1820
|
+
renderFolderPath(source, searchContext, scopeLabel, row, collector) {
|
|
1821
|
+
try {
|
|
1822
|
+
return RenderScopeTemplate(source, searchContext, undefined, 'path');
|
|
1823
|
+
}
|
|
1824
|
+
catch (e) {
|
|
1825
|
+
this.reportFolderPathProblem(e instanceof Error ? e.message : String(e), scopeLabel, row, collector);
|
|
1826
|
+
return undefined;
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
/** A FolderPath problem, in the wording `assertRestrictingTemplateRendered` uses for every restricting field. */
|
|
1830
|
+
reportFolderPathProblem(reason, scopeLabel, row, collector) {
|
|
1831
|
+
this.reportLaneProblem(`SearchEngine: scope ${scopeLabel} — FolderPath for storage account "${row.FileStorageAccountID}" ` +
|
|
1832
|
+
`could not be rendered safely, so the search was NOT run. ${reason}`, row.ID, collector);
|
|
1833
|
+
}
|
|
1331
1834
|
/** Resolve the EntityID → EntityName via MJ Metadata (for passing to providers that key by name). */
|
|
1332
1835
|
lookupEntityName(entityID) {
|
|
1333
1836
|
try {
|
|
@@ -1369,6 +1872,50 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1369
1872
|
}
|
|
1370
1873
|
return null;
|
|
1371
1874
|
}
|
|
1875
|
+
/**
|
|
1876
|
+
* The per-provider over-fetch multiplier for this search, in priority order: the caller's
|
|
1877
|
+
* `SearchParams.PermissionOverfetchFactor`; else the **largest** of each resolved scope's declared
|
|
1878
|
+
* `ScopeConfig.permissionOverfetchFactor` (a scope that declares none counts as the engine default);
|
|
1879
|
+
* else the engine default. Clamped to `[1, MAX_OVERFETCH_FACTOR]`.
|
|
1880
|
+
*
|
|
1881
|
+
* The largest wins across scopes, not the first: over-fetch exists to compensate for late
|
|
1882
|
+
* permission filtering, and a lane trimmed heavily by it needs the extra candidates whichever
|
|
1883
|
+
* scope it belongs to. A larger factor never changes which results the caller gets (the final
|
|
1884
|
+
* list is still trimmed to `MaxResults`), but it does cost more: every provider returns more
|
|
1885
|
+
* candidates, dedup, the content exclusion and the permission passes do more work, a re-ranker is
|
|
1886
|
+
* fed up to its `inputTopN` from a bigger pool, and `streamSearch`'s per-provider partial events
|
|
1887
|
+
* (capped to the caller's `MaxResults`) draw from it. This is why a scope may declare it at all:
|
|
1888
|
+
* the scope's author knows how sparse its lanes are after permissions, and every caller shouldn't
|
|
1889
|
+
* have to.
|
|
1890
|
+
*/
|
|
1891
|
+
ResolvePermissionOverfetchFactor(params, resolvedScopes) {
|
|
1892
|
+
if (typeof params.PermissionOverfetchFactor === 'number' && Number.isFinite(params.PermissionOverfetchFactor)) {
|
|
1893
|
+
return this.clampOverfetchFactor(params.PermissionOverfetchFactor, 'the caller');
|
|
1894
|
+
}
|
|
1895
|
+
// A scope that declares nothing counts as the default, so one scope's low factor never pulls
|
|
1896
|
+
// down a neighbour that was happy with the default (the max is a floor, never a ceiling).
|
|
1897
|
+
const factors = resolvedScopes.map(bundle => this.scopeOverfetchFactor(bundle.Scope.ScopeConfig) ?? this._defaultOverfetchFactor);
|
|
1898
|
+
if (factors.length > 0)
|
|
1899
|
+
return this.clampOverfetchFactor(Math.max(...factors), 'a scope');
|
|
1900
|
+
return this._defaultOverfetchFactor;
|
|
1901
|
+
}
|
|
1902
|
+
/** A scope's declared `ScopeConfig.permissionOverfetchFactor`, when it is a finite number. Anything else is "not declared". */
|
|
1903
|
+
scopeOverfetchFactor(scopeConfigJson) {
|
|
1904
|
+
const factor = this.parseJson(scopeConfigJson)?.permissionOverfetchFactor;
|
|
1905
|
+
return typeof factor === 'number' && Number.isFinite(factor) ? factor : undefined;
|
|
1906
|
+
}
|
|
1907
|
+
/**
|
|
1908
|
+
* Hold the factor to `[1, MAX_OVERFETCH_FACTOR]`. Below 1 would under-fetch the caller's own `topK`;
|
|
1909
|
+
* above the ceiling, a single metadata edit would multiply every provider call for every caller of
|
|
1910
|
+
* the scope (vector providers bill per candidate). A clamped value is logged so the author sees it.
|
|
1911
|
+
*/
|
|
1912
|
+
clampOverfetchFactor(factor, from) {
|
|
1913
|
+
const clamped = Math.min(SearchEngine.MAX_OVERFETCH_FACTOR, Math.max(1, factor));
|
|
1914
|
+
if (clamped !== factor) {
|
|
1915
|
+
LogStatus(`SearchEngine: permission over-fetch factor ${factor} from ${from} clamped to ${clamped} (allowed range 1–${SearchEngine.MAX_OVERFETCH_FACTOR}).`);
|
|
1916
|
+
}
|
|
1917
|
+
return clamped;
|
|
1918
|
+
}
|
|
1372
1919
|
async runReRanker(query, candidates, cfg, contextUser, budgetGuard) {
|
|
1373
1920
|
if (!cfg.driverClass || candidates.length === 0)
|
|
1374
1921
|
return candidates;
|
|
@@ -1475,14 +2022,8 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1475
2022
|
* Run all available providers in parallel and return labeled result lists.
|
|
1476
2023
|
* When isPreview is true, only providers with SupportsPreview=true are included.
|
|
1477
2024
|
*/
|
|
1478
|
-
async executeProviders(query, topK, filters, contextUser, isPreview, scopeConstraints, onProviderResolved) {
|
|
1479
|
-
const entries = this.
|
|
1480
|
-
if (!e.Provider.IsAvailable())
|
|
1481
|
-
return false;
|
|
1482
|
-
if (isPreview && !e.SupportsPreview)
|
|
1483
|
-
return false;
|
|
1484
|
-
return true;
|
|
1485
|
-
});
|
|
2025
|
+
async executeProviders(query, topK, filters, contextUser, isPreview, scopeConstraints, onProviderResolved, minScore) {
|
|
2026
|
+
const entries = this.availableProviders(isPreview);
|
|
1486
2027
|
if (entries.length === 0) {
|
|
1487
2028
|
LogStatus('SearchEngine: No providers available');
|
|
1488
2029
|
return [];
|
|
@@ -1491,7 +2032,9 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1491
2032
|
const providerStart = Date.now();
|
|
1492
2033
|
try {
|
|
1493
2034
|
const providerTopK = entry.MaxResultsOverride ?? topK;
|
|
1494
|
-
|
|
2035
|
+
// MinScore is a floor on the semantic lane's own similarity, applied here, before
|
|
2036
|
+
// streaming and fusion (see ApplySemanticFloor).
|
|
2037
|
+
const results = ApplySemanticFloor(entry.Provider.SourceType, await entry.Provider.Search(query, providerTopK, filters, contextUser, scopeConstraints), minScore);
|
|
1495
2038
|
// Stamp provider metadata onto each result
|
|
1496
2039
|
for (const r of results) {
|
|
1497
2040
|
r.ProviderId = entry.ID;
|
|
@@ -1559,34 +2102,44 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1559
2102
|
return counts;
|
|
1560
2103
|
}
|
|
1561
2104
|
// ────────────────────────────────────────────────────────────────
|
|
1562
|
-
// Permission filtering (residual late safety net)
|
|
2105
|
+
// Permission filtering (residual late safety net, then the origin-record gate)
|
|
1563
2106
|
// ────────────────────────────────────────────────────────────────
|
|
1564
2107
|
/**
|
|
1565
|
-
* Filter search results by entity-level and row-level security permissions
|
|
2108
|
+
* Filter search results by entity-level and row-level security permissions, then by whether the user
|
|
2109
|
+
* may read the record each content result was derived from.
|
|
1566
2110
|
*
|
|
1567
|
-
* **
|
|
1568
|
-
* push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If
|
|
1569
|
-
*
|
|
1570
|
-
*
|
|
2111
|
+
* **Steps 1–4 are a safety net.** Providers are expected to do per-provider permission
|
|
2112
|
+
* push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If those steps remove more
|
|
2113
|
+
* than a handful of results in practice, the responsible provider's push-down is incomplete
|
|
2114
|
+
* and should be fixed. **Step 5 is not**: it drops by design, because no provider can push
|
|
2115
|
+
* an origin record's own row filters down into a content index. Its removals are counted
|
|
2116
|
+
* into `stats.OriginGateRemoved`, so the late-filter count keeps its meaning.
|
|
1571
2117
|
*
|
|
1572
2118
|
* Groups results by entity for efficient permission checking:
|
|
1573
2119
|
* 1. Unknown entities are excluded (fail closed).
|
|
1574
2120
|
* 2. If the user lacks entity-level CanRead, all results for that entity are dropped.
|
|
1575
2121
|
* 3. If the user is exempt from RLS, all results pass through.
|
|
1576
2122
|
* 4. If RLS applies, a RunView validates which record IDs the user can read.
|
|
2123
|
+
* 5. Content items and chunks are kept only when the user may read the record they were
|
|
2124
|
+
* derived from ({@link VerifyOriginRecords}).
|
|
2125
|
+
*
|
|
2126
|
+
* `storage-file` results take their own path ({@link filterStorageResults}): they are re-checked against
|
|
2127
|
+
* the storage-account permission model for this user, never passed through on the strength of their type.
|
|
2128
|
+
*
|
|
2129
|
+
* @param stats optional per-call counters; `OriginGateRemoved` is incremented by step 5's removals
|
|
1577
2130
|
*/
|
|
1578
|
-
async filterByPermissions(results, contextUser) {
|
|
2131
|
+
async filterByPermissions(results, contextUser, stats) {
|
|
1579
2132
|
if (results.length === 0)
|
|
1580
2133
|
return results;
|
|
1581
|
-
// Storage file results have their own permission model (FileStorageAccountPermission)
|
|
1582
|
-
//
|
|
2134
|
+
// Storage file results have their own permission model (FileStorageAccountPermission) — re-checked
|
|
2135
|
+
// here for this user rather than trusted from the provider (see filterStorageResults)
|
|
1583
2136
|
const storageResults = results.filter(r => r.ResultType === 'storage-file');
|
|
1584
2137
|
const entityResults = results.filter(r => r.ResultType !== 'storage-file');
|
|
1585
2138
|
const byEntity = this.groupResultsByEntity(entityResults);
|
|
1586
|
-
const permitted = [
|
|
1587
|
-
const promises = [];
|
|
2139
|
+
const permitted = [];
|
|
2140
|
+
const promises = [this.filterStorageResults(storageResults, contextUser, permitted)];
|
|
1588
2141
|
for (const [entityName, groupResults] of byEntity) {
|
|
1589
|
-
promises.push(this.filterEntityResults(entityName, groupResults, contextUser, permitted));
|
|
2142
|
+
promises.push(this.filterEntityResults(entityName, groupResults, contextUser, permitted, stats));
|
|
1590
2143
|
}
|
|
1591
2144
|
await Promise.all(promises);
|
|
1592
2145
|
// Preserve the input order (which is the RRF/re-rank order). groupResultsByEntity
|
|
@@ -1597,6 +2150,112 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1597
2150
|
permitted.sort((a, b) => (inputIndex.get(a) ?? 0) - (inputIndex.get(b) ?? 0));
|
|
1598
2151
|
return permitted;
|
|
1599
2152
|
}
|
|
2153
|
+
/**
|
|
2154
|
+
* The storage half of {@link filterByPermissions}: re-check `storage-file` results for `contextUser` and push the
|
|
2155
|
+
* ones that pass into `permitted`.
|
|
2156
|
+
*
|
|
2157
|
+
* `ResultType` is set by whichever provider produced a result, so being typed `storage-file` proves nothing. A
|
|
2158
|
+
* storage hit is kept only when ALL hold:
|
|
2159
|
+
* - its `ProviderId` — stamped by this engine on every result, overwriting whatever the provider set — names a
|
|
2160
|
+
* configured entry whose provider is a {@link StorageSearchProvider};
|
|
2161
|
+
* - the account it names (`RawMetadata.accountId`, as that provider writes it) is one `contextUser` may read now,
|
|
2162
|
+
* per `StorageAccessEvaluator` (per call; the account-without-rows rule lives there); and
|
|
2163
|
+
* - the object it names (`RawMetadata.path` / `objectId`) does not back an `MJ: Files` row `contextUser` may not
|
|
2164
|
+
* read — the tracked-file rule `CreatePreAuthDownloadUrl` applies, so a hit never names (or excerpts) a file the
|
|
2165
|
+
* caller would be refused ({@link dropUnreadableTrackedStorageHits}).
|
|
2166
|
+
*
|
|
2167
|
+
* Anything else — no or a foreign `ProviderId`, missing or unparseable metadata, an evaluator failure or throw —
|
|
2168
|
+
* drops the result (fail closed). Order is restored by the caller.
|
|
2169
|
+
*/
|
|
2170
|
+
async filterStorageResults(results, contextUser, permitted) {
|
|
2171
|
+
if (results.length === 0)
|
|
2172
|
+
return;
|
|
2173
|
+
try {
|
|
2174
|
+
const candidates = this.storageCandidates(results);
|
|
2175
|
+
if (candidates.length === 0)
|
|
2176
|
+
return;
|
|
2177
|
+
const readable = await StorageAccessEvaluator.Instance.AccessibleAccountIDs(candidates.map(c => c.AccountID), contextUser, 'Read', this.ProviderToUse);
|
|
2178
|
+
const onReadableAccounts = candidates.filter(c => readable.has(NormalizeUUID(c.AccountID)));
|
|
2179
|
+
const visible = await this.dropUnreadableTrackedStorageHits(onReadableAccounts, contextUser);
|
|
2180
|
+
permitted.push(...visible.map(c => c.Item));
|
|
2181
|
+
}
|
|
2182
|
+
catch (error) {
|
|
2183
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2184
|
+
LogError(`SearchEngine: Storage permission filtering failed — ${results.length} storage result(s) dropped: ${msg}`);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* The tracked-file rule on storage hits: grouped by account, each account's hits are checked in one batched lookup
|
|
2189
|
+
* against the `MJ: Files` rows on that account's provider (`StorageAccessEvaluator.UnreadableTrackedObjectKeys`,
|
|
2190
|
+
* compared the way the account's driver addresses keys), and a hit whose path or object ID backs a row the caller
|
|
2191
|
+
* may not read is dropped. An account whose provider or driver cannot be resolved loses all its hits (fail closed).
|
|
2192
|
+
*/
|
|
2193
|
+
async dropUnreadableTrackedStorageHits(candidates, contextUser) {
|
|
2194
|
+
const byAccount = new Map();
|
|
2195
|
+
for (const candidate of candidates) {
|
|
2196
|
+
const key = NormalizeUUID(candidate.AccountID);
|
|
2197
|
+
byAccount.set(key, [...(byAccount.get(key) ?? []), candidate]);
|
|
2198
|
+
}
|
|
2199
|
+
const kept = await Promise.all([...byAccount.values()].map(group => this.readableTrackedStorageHits(group, contextUser)));
|
|
2200
|
+
return kept.flat();
|
|
2201
|
+
}
|
|
2202
|
+
/** {@link dropUnreadableTrackedStorageHits} for one account's hits; any failure drops them all. */
|
|
2203
|
+
async readableTrackedStorageHits(group, contextUser) {
|
|
2204
|
+
const accountID = group[0].AccountID;
|
|
2205
|
+
try {
|
|
2206
|
+
await FileStorageEngine.Instance.Config(false, contextUser, this.ProviderToUse);
|
|
2207
|
+
const account = FileStorageEngine.Instance.GetAccountById(accountID);
|
|
2208
|
+
if (!account) {
|
|
2209
|
+
LogError(`SearchEngine: storage account ${accountID} is not in the storage cache — its ${group.length} hit(s) dropped`);
|
|
2210
|
+
return [];
|
|
2211
|
+
}
|
|
2212
|
+
const driver = await FileStorageEngine.Instance.GetDriver(account.ID, contextUser);
|
|
2213
|
+
const unreadable = await StorageAccessEvaluator.Instance.UnreadableTrackedObjectKeys(account.ProviderID, group.flatMap(c => c.ObjectKeys), contextUser, this.ProviderToUse, driver);
|
|
2214
|
+
return group.filter(c => !c.ObjectKeys.some(key => unreadable.has(key)));
|
|
2215
|
+
}
|
|
2216
|
+
catch (error) {
|
|
2217
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2218
|
+
LogError(`SearchEngine: tracked-file check failed for storage account ${accountID} — its ${group.length} hit(s) dropped: ${msg}`);
|
|
2219
|
+
return [];
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* The storage results that came from a configured {@link StorageSearchProvider} entry and name a well-formed account
|
|
2224
|
+
* and at least one object key, paired with them. Everything else is left out, which drops it.
|
|
2225
|
+
*/
|
|
2226
|
+
storageCandidates(results) {
|
|
2227
|
+
const storageProviderIDs = new Set(this._providerEntries.filter(e => e.Provider instanceof StorageSearchProvider).map(e => NormalizeUUID(e.ID)));
|
|
2228
|
+
const candidates = [];
|
|
2229
|
+
for (const item of results) {
|
|
2230
|
+
if (!item.ProviderId || !storageProviderIDs.has(NormalizeUUID(item.ProviderId)))
|
|
2231
|
+
continue;
|
|
2232
|
+
const location = this.storageLocationOf(item);
|
|
2233
|
+
if (location)
|
|
2234
|
+
candidates.push({ Item: item, ...location });
|
|
2235
|
+
}
|
|
2236
|
+
return candidates;
|
|
2237
|
+
}
|
|
2238
|
+
/**
|
|
2239
|
+
* The account (`RawMetadata.accountId`) and object keys (`RawMetadata.path`, `RawMetadata.objectId`) a
|
|
2240
|
+
* `storage-file` result names, or null when the account is absent or malformed or no object key is present.
|
|
2241
|
+
*/
|
|
2242
|
+
storageLocationOf(item) {
|
|
2243
|
+
if (!item.RawMetadata)
|
|
2244
|
+
return null;
|
|
2245
|
+
try {
|
|
2246
|
+
const parsed = JSON.parse(item.RawMetadata);
|
|
2247
|
+
if (!parsed || typeof parsed !== 'object')
|
|
2248
|
+
return null;
|
|
2249
|
+
const accountId = parsed.accountId;
|
|
2250
|
+
const objectKeys = [parsed.path, parsed.objectId].filter((k) => typeof k === 'string' && k.length > 0);
|
|
2251
|
+
if (typeof accountId !== 'string' || !IsValidUUID(accountId) || objectKeys.length === 0)
|
|
2252
|
+
return null;
|
|
2253
|
+
return { AccountID: accountId, ObjectKeys: objectKeys };
|
|
2254
|
+
}
|
|
2255
|
+
catch {
|
|
2256
|
+
return null;
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
1600
2259
|
/**
|
|
1601
2260
|
* Group search result items by EntityName for batch permission checking.
|
|
1602
2261
|
*/
|
|
@@ -1615,10 +2274,11 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1615
2274
|
}
|
|
1616
2275
|
/**
|
|
1617
2276
|
* Check permissions for a single entity's batch of results.
|
|
1618
|
-
* Permitted results are pushed into the shared `permitted` array
|
|
2277
|
+
* Permitted results are pushed into the shared `permitted` array; rows the origin-record gate removes are
|
|
2278
|
+
* counted into `stats` when it is supplied.
|
|
1619
2279
|
* On any error, results are excluded (fail closed).
|
|
1620
2280
|
*/
|
|
1621
|
-
async filterEntityResults(entityName, entityResults, contextUser, permitted) {
|
|
2281
|
+
async filterEntityResults(entityName, entityResults, contextUser, permitted, stats) {
|
|
1622
2282
|
try {
|
|
1623
2283
|
const md = this.ProviderToUse;
|
|
1624
2284
|
let entity = null;
|
|
@@ -1637,33 +2297,13 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1637
2297
|
return;
|
|
1638
2298
|
// Check row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
1639
2299
|
const rlsClause = entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, '');
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
// documents that are not that entity's records at all.
|
|
1648
|
-
//
|
|
1649
|
-
// Results from a lane that queried the entity directly need no such check — their ids
|
|
1650
|
-
// came out of a RunView against it. So pass those through untouched (this is the hot
|
|
1651
|
-
// path and its cost is unchanged) and verify only the rest.
|
|
1652
|
-
const selfEvident = [];
|
|
1653
|
-
const unverified = [];
|
|
1654
|
-
for (const item of entityResults) {
|
|
1655
|
-
(SearchEngine.lanesWithSelfEvidentOwnership.has(item.SourceType) ? selfEvident : unverified)
|
|
1656
|
-
.push(item);
|
|
1657
|
-
}
|
|
1658
|
-
permitted.push(...selfEvident);
|
|
1659
|
-
if (unverified.length > 0) {
|
|
1660
|
-
await this.verifyOwnershipAndRowFilters(entity, unverified, undefined, contextUser, permitted);
|
|
1661
|
-
}
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
// A row filter applies — validate record IDs via RunView. Unchanged: this path already
|
|
1665
|
-
// verified ownership as a side effect of filtering, for every lane.
|
|
1666
|
-
await this.verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, permitted);
|
|
2300
|
+
// A row the user may read is not yet a row they may be shown: content derived from a record they
|
|
2301
|
+
// cannot read is still theirs to miss, so the admitted rows pass the origin gate next.
|
|
2302
|
+
const ownRows = await this.admitOwnRows(entity, entityResults, rlsClause, contextUser);
|
|
2303
|
+
const kept = await this.VerifyOriginRecords(entity, ownRows, contextUser);
|
|
2304
|
+
if (stats)
|
|
2305
|
+
stats.OriginGateRemoved += Math.max(0, ownRows.length - kept.length);
|
|
2306
|
+
permitted.push(...kept);
|
|
1667
2307
|
}
|
|
1668
2308
|
catch (error) {
|
|
1669
2309
|
// Fail closed — if anything goes wrong, exclude the results
|
|
@@ -1672,10 +2312,88 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1672
2312
|
}
|
|
1673
2313
|
}
|
|
1674
2314
|
/**
|
|
1675
|
-
*
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
*
|
|
2315
|
+
* Gate 1: the results that are rows of `entity` the user may read.
|
|
2316
|
+
*
|
|
2317
|
+
* With no row filter (or a user exempt from row filtering) that settles WHICH ROWS of this entity they may
|
|
2318
|
+
* see — it does not establish that these results ARE this entity's rows. `EntityName` is provider output,
|
|
2319
|
+
* and for the vector and 3rd-party lanes it comes from the index: vector metadata's `Entity` key, or the
|
|
2320
|
+
* index name. Admitting on that label alone lets whoever writes the index choose which entity's
|
|
2321
|
+
* permissions get evaluated, so a label naming an entity the user CAN read admits documents that are not
|
|
2322
|
+
* that entity's records at all.
|
|
2323
|
+
*
|
|
2324
|
+
* Results that came out of a RunView against the entity need no such check, so those pass untouched (this
|
|
2325
|
+
* is the hot path and its cost is unchanged) and only the rest are verified — see {@link isSelfEvidentRow}
|
|
2326
|
+
* for which results qualify. When a row filter applies, every result is verified: ownership is checked as
|
|
2327
|
+
* a side effect of filtering.
|
|
2328
|
+
*/
|
|
2329
|
+
async admitOwnRows(entity, entityResults, rlsClause, contextUser) {
|
|
2330
|
+
const ownRows = [];
|
|
2331
|
+
if (rlsClause) {
|
|
2332
|
+
await this.verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, ownRows);
|
|
2333
|
+
return ownRows;
|
|
2334
|
+
}
|
|
2335
|
+
const unverified = [];
|
|
2336
|
+
for (const item of entityResults) {
|
|
2337
|
+
(this.isSelfEvidentRow(item) ? ownRows : unverified).push(item);
|
|
2338
|
+
}
|
|
2339
|
+
if (unverified.length > 0) {
|
|
2340
|
+
await this.verifyOwnershipAndRowFilters(entity, unverified, undefined, contextUser, ownRows);
|
|
2341
|
+
}
|
|
2342
|
+
return ownRows;
|
|
2343
|
+
}
|
|
2344
|
+
/**
|
|
2345
|
+
* Whether `item` is self-evidently a row of the entity it is labelled with: the engine stamped it with a
|
|
2346
|
+
* configured provider that reads that entity through `RunView`
|
|
2347
|
+
* ({@link BaseSearchProvider.ResultsAreRowsOfLabelledEntity}), AND it carries one of the lanes in
|
|
2348
|
+
* {@link lanesWithSelfEvidentOwnership}.
|
|
2349
|
+
*
|
|
2350
|
+
* Trust follows the engine's stamp, never the label. `SourceType` is provider output and `SearchSource` is a
|
|
2351
|
+
* closed union, so every shipped external-index provider (Azure AI Search, Typesense, Elasticsearch,
|
|
2352
|
+
* OpenSearch) stamps `'fulltext'` with the index name as `EntityName`, and a third-party provider may stamp
|
|
2353
|
+
* `'entity'`. A result with no `ProviderId` (a fusion fallback, a hand-built hit) or one naming no configured
|
|
2354
|
+
* provider is verified, and so is a hit promoted from a content item to its origin record
|
|
2355
|
+
* (`PromotedFromContentItemID`): its provider read the content item, never the origin row.
|
|
2356
|
+
*
|
|
2357
|
+
* Fusion and dedup never move a `ProviderId` onto another item's `EntityName`/`RecordID`/`SourceType`: each
|
|
2358
|
+
* merged result is one provider's item, whole, and only scores, `ScoreBreakdown`, tags and (dedup) a snippet
|
|
2359
|
+
* replacing a generic one are taken from the items it absorbed. Those may be from rows nothing verified:
|
|
2360
|
+
* `Deduplicate` merges items sharing `EntityName` + `RecordID`, but per-scope RRF (`SearchFusion.applyRRF`)
|
|
2361
|
+
* merges `ScoreBreakdown` across items sharing only a `RecordID` — of any entity — keeping the first. So a
|
|
2362
|
+
* merge can lend a trusted item another item's scores, never its trust: trust is the surviving item's own.
|
|
2363
|
+
*/
|
|
2364
|
+
isSelfEvidentRow(item) {
|
|
2365
|
+
if (!SearchEngine.lanesWithSelfEvidentOwnership.has(item.SourceType))
|
|
2366
|
+
return false;
|
|
2367
|
+
return this.providerThatReadRow(item)?.ResultsAreRowsOfLabelledEntity === true;
|
|
2368
|
+
}
|
|
2369
|
+
/**
|
|
2370
|
+
* The configured provider that read the row `item` names — {@link ProviderForResult}, except for a hit the
|
|
2371
|
+
* engine promoted from a content item to its origin record (`PromotedFromContentItemID`), whose row no
|
|
2372
|
+
* provider read. Both per-provider trust decisions resolve through here: ownership
|
|
2373
|
+
* (`ResultsAreRowsOfLabelledEntity`, {@link isSelfEvidentRow}) and the lane `ExtraFilter` exemption
|
|
2374
|
+
* (`AppliesLaneExtraFilter`, {@link laneBoundFor}).
|
|
2375
|
+
*/
|
|
2376
|
+
providerThatReadRow(item) {
|
|
2377
|
+
return item.PromotedFromContentItemID ? undefined : this.ProviderForResult(item);
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* The configured provider whose engine-stamped `ProviderId` `item` carries, or `undefined` when it carries
|
|
2381
|
+
* none or names no configured provider. The engine overwrites `ProviderId` on every result a provider
|
|
2382
|
+
* returns, before fusion.
|
|
2383
|
+
*
|
|
2384
|
+
* Protected so a probe can map a hand-built hit to a provider instance without configuring the engine. It
|
|
2385
|
+
* decides which results skip ownership verification and which skip the lane `ExtraFilter` re-check, so an
|
|
2386
|
+
* override must only ever return the provider that actually produced the result.
|
|
2387
|
+
*/
|
|
2388
|
+
ProviderForResult(item) {
|
|
2389
|
+
if (!item.ProviderId)
|
|
2390
|
+
return undefined;
|
|
2391
|
+
return this._providerEntries.find(e => UUIDsEqual(e.ID, item.ProviderId))?.Provider;
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Lanes whose results can be self-evident rows of the entity they are labelled with — a necessary
|
|
2395
|
+
* condition only: the provider that produced the result must also say it reads that entity through
|
|
2396
|
+
* `RunView` (see {@link isSelfEvidentRow}). The vector lane, and anything else, is always verified.
|
|
1679
2397
|
*
|
|
1680
2398
|
* An allowlist rather than a denylist on purpose: a `SourceType` nobody anticipated is verified by
|
|
1681
2399
|
* default instead of trusted by default.
|
|
@@ -1688,11 +2406,43 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1688
2406
|
* record of this entity is dropped whether or not a row filter exists.
|
|
1689
2407
|
*/
|
|
1690
2408
|
async verifyOwnershipAndRowFilters(entity, entityResults, rlsClause, contextUser, permitted) {
|
|
2409
|
+
const validKeys = await this.readableRecordKeys(entity, entityResults.map(r => r.RecordID), rlsClause, contextUser);
|
|
2410
|
+
if (!validKeys)
|
|
2411
|
+
return; // fail closed — already logged
|
|
2412
|
+
for (const item of entityResults) {
|
|
2413
|
+
const key = this.recordMatchKey(entity, item.RecordID);
|
|
2414
|
+
if (key !== null && validKeys.has(key)) {
|
|
2415
|
+
permitted.push(item);
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Ask the database, as `contextUser`, which of `recordIDs` are rows of `entity` the user may read:
|
|
2421
|
+
* `PK IN (...)`, ANDed with `rlsClause` when one applies, run through RunView so the user's own row
|
|
2422
|
+
* filters apply as well. Returns the matching keys in {@link canonicalKeyValues} form, or `null`
|
|
2423
|
+
* when the question could not be asked (no primary key, no usable record id, RunView failed) — the
|
|
2424
|
+
* caller fails closed.
|
|
2425
|
+
*/
|
|
2426
|
+
async readableRecordKeys(entity, recordIDs, rlsClause, contextUser) {
|
|
2427
|
+
const params = this.readableKeysParams(entity, recordIDs, rlsClause);
|
|
2428
|
+
if (!params)
|
|
2429
|
+
return null;
|
|
2430
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2431
|
+
return this.readableKeySet(entity, await rv.RunView(params, contextUser));
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* The RunView behind {@link readableRecordKeys}, projecting only the key. `null` when it cannot be asked:
|
|
2435
|
+
* the entity has no primary key, or no record id names a key of it (both logged).
|
|
2436
|
+
*
|
|
2437
|
+
* `MaxRows` is the number of ids, since each matches at most one row: left unset, the entity's
|
|
2438
|
+
* `UserViewMaxRows` could truncate the answer and silently drop readable results.
|
|
2439
|
+
*/
|
|
2440
|
+
readableKeysParams(entity, recordIDs, rlsClause) {
|
|
1691
2441
|
const pkField = entity.FirstPrimaryKey; // first-pk-ok: presence check; Name is only used under the PrimaryKeys.length === 1 branch
|
|
1692
2442
|
if (!pkField) {
|
|
1693
2443
|
// Cannot verify without a primary key — exclude results
|
|
1694
2444
|
LogError(`SearchEngine: Entity "${entity.Name}" has no primary key, cannot verify result ownership`);
|
|
1695
|
-
return;
|
|
2445
|
+
return null;
|
|
1696
2446
|
}
|
|
1697
2447
|
// `RecordID` is a compact CompositeKey segment: the bare value for a single-column key, a
|
|
1698
2448
|
// "F1|v1||F2|v2" segment for a composite one. A single-column key is verified with one IN();
|
|
@@ -1700,40 +2450,393 @@ export class SearchEngine extends BaseSingleton {
|
|
|
1700
2450
|
// alone could never match the segment, and this check fails closed, so every composite-key
|
|
1701
2451
|
// result would have been dropped as unauthorized.
|
|
1702
2452
|
const membership = entity.PrimaryKeys.length === 1
|
|
1703
|
-
? this.buildSingleKeyMembership(pkField.Name,
|
|
1704
|
-
: this.buildCompositeKeyMembership(entity,
|
|
2453
|
+
? this.buildSingleKeyMembership(entity, pkField.Name, recordIDs)
|
|
2454
|
+
: this.buildCompositeKeyMembership(entity, recordIDs);
|
|
2455
|
+
if (!membership)
|
|
2456
|
+
return null;
|
|
1705
2457
|
// Without a row filter this is a pure existence check against the entity's own view.
|
|
1706
2458
|
const filter = rlsClause ? `(${membership}) AND (${rlsClause})` : membership;
|
|
1707
|
-
|
|
1708
|
-
const result = await rv.RunView({
|
|
2459
|
+
return {
|
|
1709
2460
|
EntityName: entity.Name,
|
|
1710
2461
|
ExtraFilter: filter,
|
|
1711
2462
|
Fields: entity.PrimaryKeys.map(pk => pk.Name),
|
|
1712
|
-
ResultType: 'simple'
|
|
1713
|
-
|
|
1714
|
-
|
|
2463
|
+
ResultType: 'simple',
|
|
2464
|
+
MaxRows: recordIDs.length
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
/** The keys a {@link readableKeysParams} RunView returned, in {@link canonicalKeyValues} form; `null` (logged) when it failed. */
|
|
2468
|
+
readableKeySet(entity, result) {
|
|
2469
|
+
if (!result?.Success) {
|
|
1715
2470
|
// RunView failed — fail closed, exclude all results
|
|
1716
|
-
LogError(`SearchEngine: ownership/RLS RunView failed for entity "${entity.Name}": ${result
|
|
1717
|
-
return;
|
|
2471
|
+
LogError(`SearchEngine: ownership/RLS RunView failed for entity "${entity.Name}": ${result?.ErrorMessage ?? 'unknown error'}`);
|
|
2472
|
+
return null;
|
|
1718
2473
|
}
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
2474
|
+
return new Set(result.Results.map(r => this.canonicalKeyValues(entity, CompositeKey.FromEntityRecord(entity, r))));
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* `PK IN ('a','b',...)` — the fast path for the overwhelmingly common single-column key. Each id is
|
|
2478
|
+
* read as a key segment first, so a bare value and a prefixed `ID|value` segment (the encoding
|
|
2479
|
+
* `CompositeKey.ToRecordID()` writes) both compare on the value alone.
|
|
2480
|
+
*/
|
|
2481
|
+
buildSingleKeyMembership(entity, pkFieldName, recordIDs) {
|
|
2482
|
+
const values = recordIDs.map(id => {
|
|
2483
|
+
const key = CompositeKey.FromURLSegment(entity, id);
|
|
2484
|
+
return String(key.KeyValuePairs[0]?.Value ?? id);
|
|
2485
|
+
});
|
|
2486
|
+
const ids = values.map(v => `'${EscapeSQLString(v)}'`).join(',');
|
|
2487
|
+
return `${pkFieldName} IN (${ids})`;
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* `(F1='v1' AND F2='v2') OR (...)` — one term per composite-key record. The field names come from the
|
|
2491
|
+
* record id, so only a segment {@link parseCompositeKey} accepts reaches the SQL, under the metadata's own
|
|
2492
|
+
* names; any other is dropped (logged). Empty when no segment is usable.
|
|
2493
|
+
*/
|
|
2494
|
+
buildCompositeKeyMembership(entity, recordIDs) {
|
|
2495
|
+
const terms = [];
|
|
2496
|
+
for (const id of recordIDs) {
|
|
2497
|
+
const key = this.parseCompositeKey(entity, id);
|
|
2498
|
+
if (key)
|
|
2499
|
+
terms.push(`(${key.ToWhereClause()})`);
|
|
2500
|
+
else
|
|
2501
|
+
LogError(`SearchEngine: record id "${id}" does not name the primary key of "${entity.Name}"; dropping it`);
|
|
2502
|
+
}
|
|
2503
|
+
return terms.join(' OR ');
|
|
2504
|
+
}
|
|
2505
|
+
/**
|
|
2506
|
+
* A composite-key segment rebuilt on `entity`'s own primary-key names, or `null` when it names a field that
|
|
2507
|
+
* is not a primary key of `entity` or leaves one out. Names match case-insensitively and are replaced by
|
|
2508
|
+
* the metadata's, so nothing parsed from a record id is interpolated into SQL as an identifier.
|
|
2509
|
+
*/
|
|
2510
|
+
parseCompositeKey(entity, recordID) {
|
|
2511
|
+
const pairs = CompositeKey.FromURLSegment(entity, recordID).KeyValuePairs;
|
|
2512
|
+
if (pairs.length !== entity.PrimaryKeys.length)
|
|
2513
|
+
return null;
|
|
2514
|
+
const rebuilt = [];
|
|
2515
|
+
for (const pk of entity.PrimaryKeys) {
|
|
2516
|
+
const match = pairs.find(kv => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
|
|
2517
|
+
if (!match)
|
|
2518
|
+
return null;
|
|
2519
|
+
rebuilt.push(new KeyValuePair(pk.Name, match.Value));
|
|
2520
|
+
}
|
|
2521
|
+
return CompositeKey.FromKeyValuePairs(rebuilt);
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* The {@link canonicalKeyValues} form of the key `recordID` names in `entity`, to match against the rows a
|
|
2525
|
+
* readability check returned. `null` for a composite-key segment {@link parseCompositeKey} rejects.
|
|
2526
|
+
*/
|
|
2527
|
+
recordMatchKey(entity, recordID) {
|
|
2528
|
+
if (entity.PrimaryKeys.length === 1)
|
|
2529
|
+
return this.canonicalKeyValues(entity, CompositeKey.FromURLSegment(entity, recordID));
|
|
2530
|
+
const key = this.parseCompositeKey(entity, recordID);
|
|
2531
|
+
return key ? this.canonicalKeyValues(entity, key) : null;
|
|
2532
|
+
}
|
|
2533
|
+
// ────────────────────────────────────────────────────────────────────────────────────────────
|
|
2534
|
+
// Origin records: a second gate for content derived from another MJ record
|
|
2535
|
+
// ────────────────────────────────────────────────────────────────────────────────────────────
|
|
2536
|
+
/**
|
|
2537
|
+
* Second gate, after a result is known to be a readable row of its own entity: may the user also
|
|
2538
|
+
* read the record the row was DERIVED from?
|
|
2539
|
+
*
|
|
2540
|
+
* Row-level security on a content entity settles who may read the content table. It cannot say
|
|
2541
|
+
* whether the person may read the file, task or conversation that content was extracted from —
|
|
2542
|
+
* that permission lives on the origin entity, under its own row filters. Without this gate, a
|
|
2543
|
+
* chunk of a document the user may not open passes the first gate and is quoted anyway.
|
|
2544
|
+
*
|
|
2545
|
+
* For `MJ: Content Items` and `MJ: Content Item Chunks` (and any IS-A subtype of either) the
|
|
2546
|
+
* default follows chunk → item (→ root item, for a split child) → `MJ: Entity Record Documents`
|
|
2547
|
+
* → the origin record, and keeps a result only when the origin is a row the user may read,
|
|
2548
|
+
* verified the way {@link verifyOwnershipAndRowFilters} verifies the result's own entity. A
|
|
2549
|
+
* content row with no Entity Record Document (crawled, uploaded, external) has no origin and
|
|
2550
|
+
* passes unchanged, as does every result of a non-content entity.
|
|
2551
|
+
*
|
|
2552
|
+
* Every lookup runs as the user, and that is a NEW requirement on who may see content hits: read on
|
|
2553
|
+
* the base `MJ: Content Items` for anyone who sees chunk hits (the chunk → item hop reads it), and read
|
|
2554
|
+
* on `MJ: Entity Record Documents` for anyone who sees hits derived from a record (the item → document
|
|
2555
|
+
* hop reads it). An app that indexes documents behind its own permissions grants those, under its
|
|
2556
|
+
* own row filters. Without them the affected rows are dropped: every row of the group for the chunk
|
|
2557
|
+
* and item hops, only the document-bearing rows for the document hop.
|
|
2558
|
+
*
|
|
2559
|
+
* The origin's own permissions are checked once; an origin that is itself a content row is not walked
|
|
2560
|
+
* again. Protected so a host can extend the rule to another derived-content family. Fails closed: a
|
|
2561
|
+
* lookup that reports failure, or returns a row without a column it asked for (field-level security),
|
|
2562
|
+
* drops the rows that depended on it; a lookup that throws drops the whole group. It never widens.
|
|
2563
|
+
*/
|
|
2564
|
+
async VerifyOriginRecords(entity, results, contextUser) {
|
|
2565
|
+
if (results.length === 0)
|
|
2566
|
+
return results;
|
|
2567
|
+
const level = this.contentFamilyLevel(entity);
|
|
2568
|
+
if (!level)
|
|
2569
|
+
return results;
|
|
2570
|
+
try {
|
|
2571
|
+
const origins = await this.resolveContentOrigins(entity, level, results, contextUser);
|
|
2572
|
+
return await this.keepReadableOrigins(entity, results, origins, contextUser);
|
|
2573
|
+
}
|
|
2574
|
+
catch (error) {
|
|
2575
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2576
|
+
LogError(`SearchEngine: origin-record check failed for entity "${entity.Name}": ${msg}`);
|
|
2577
|
+
return [];
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
/**
|
|
2581
|
+
* Where `entity` sits in the content family: `'chunk'` for `MJ: Content Item Chunks` or a subtype,
|
|
2582
|
+
* `'item'` for `MJ: Content Items` or a subtype, `null` for anything else. Walks `ParentID` on the
|
|
2583
|
+
* request's provider; a cycle in the metadata ends the walk rather than looping.
|
|
2584
|
+
*/
|
|
2585
|
+
contentFamilyLevel(entity) {
|
|
2586
|
+
const provider = this.ProviderToUse;
|
|
2587
|
+
const visited = new Set();
|
|
2588
|
+
let current = entity;
|
|
2589
|
+
while (current && !visited.has(current.ID)) {
|
|
2590
|
+
if (current.Name === 'MJ: Content Item Chunks')
|
|
2591
|
+
return 'chunk';
|
|
2592
|
+
if (current.Name === 'MJ: Content Items')
|
|
2593
|
+
return 'item';
|
|
2594
|
+
visited.add(current.ID);
|
|
2595
|
+
current = current.ParentID ? provider.EntityByID(current.ParentID) : undefined;
|
|
2596
|
+
}
|
|
2597
|
+
return null;
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* A content result's `RecordID` as the key value the origin lookups query and the origin map is keyed by.
|
|
2601
|
+
* Read as a key segment, exactly as gate 1 reads it, so a prefixed `ID|value` id resolves to its value.
|
|
2602
|
+
* Empty when the segment does not name the entity's key.
|
|
2603
|
+
*/
|
|
2604
|
+
contentRecordKey(entity, recordID) {
|
|
2605
|
+
// canonicalKeyValues of a single-column key is the NormalizeUUID'd value itself.
|
|
2606
|
+
const key = CompositeKey.FromURLSegment(entity, recordID);
|
|
2607
|
+
return this.canonicalKeyValues(entity, key); // first-pk-ok: the content family is single-column by design (IS-A subtypes share the base key)
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* Resolve each result to its origin record. The returned map is keyed by {@link contentRecordKey}; a
|
|
2611
|
+
* value of `null` means "a content row with no origin" (it passes); a missing key means a link in the
|
|
2612
|
+
* chain could not be read as this user (it is dropped).
|
|
2613
|
+
*
|
|
2614
|
+
* Failures are scoped to the rows that depended on the failed hop. Every row depends on the chunk
|
|
2615
|
+
* and item hops, so a failed lookup there throws and the caller drops the group. Only split children
|
|
2616
|
+
* depend on the root hop, and only document-bearing items on the Entity Record Document hop, so a
|
|
2617
|
+
* failure there leaves just those rows unresolved and lets the rest through on their own merits.
|
|
2618
|
+
*/
|
|
2619
|
+
async resolveContentOrigins(entity, level, results, contextUser) {
|
|
2620
|
+
const recordIDs = Array.from(new Set(results.map(r => this.contentRecordKey(entity, r.RecordID)))).filter(id => id !== '');
|
|
2621
|
+
const itemOfRecord = level === 'chunk'
|
|
2622
|
+
? await this.lookupChunkItems(entity, recordIDs, contextUser)
|
|
2623
|
+
: new Map(recordIDs.map(id => [id, id]));
|
|
2624
|
+
const itemIDs = Array.from(new Set(itemOfRecord.values()));
|
|
2625
|
+
const erdOfItem = await this.lookupItemOrigins(itemIDs, contextUser);
|
|
2626
|
+
const erdIDs = Array.from(new Set(Array.from(erdOfItem.values()).filter((id) => id !== null)));
|
|
2627
|
+
const originOfErd = await this.lookupEntityRecordDocuments(erdIDs, contextUser);
|
|
2628
|
+
const origins = new Map();
|
|
2629
|
+
for (const id of recordIDs) {
|
|
2630
|
+
const itemID = itemOfRecord.get(id);
|
|
2631
|
+
if (itemID === undefined)
|
|
2632
|
+
continue; // the chunk is not a row the user can read
|
|
2633
|
+
const erdID = erdOfItem.get(itemID);
|
|
2634
|
+
if (erdID === undefined)
|
|
2635
|
+
continue; // the item (or its root) is not a row the user can read
|
|
2636
|
+
if (erdID === null) {
|
|
2637
|
+
origins.set(id, null);
|
|
2638
|
+
continue;
|
|
2639
|
+
} // external content: no origin
|
|
2640
|
+
const origin = originOfErd.get(erdID);
|
|
2641
|
+
if (origin)
|
|
2642
|
+
origins.set(id, origin); // else: the document is not readable → dropped
|
|
2643
|
+
}
|
|
2644
|
+
return origins;
|
|
2645
|
+
}
|
|
2646
|
+
/**
|
|
2647
|
+
* chunk id → owning Content Item id, read through the chunk entity's own view as the user. Every
|
|
2648
|
+
* chunk result depends on this hop, so a failed lookup throws and the group is dropped.
|
|
2649
|
+
*/
|
|
2650
|
+
async lookupChunkItems(entity, chunkIDs, contextUser) {
|
|
2651
|
+
const pkName = entity.FirstPrimaryKey.Name; // first-pk-ok: IS-A family shares the parent's single-column key
|
|
2652
|
+
const rows = await this.runLookup(entity.Name, [pkName, 'ContentItemID'], pkName, chunkIDs, contextUser);
|
|
2653
|
+
if (!rows)
|
|
2654
|
+
throw new Error(`lookup of "${entity.Name}" failed; every result depends on it`);
|
|
2655
|
+
const map = new Map();
|
|
2656
|
+
for (const row of rows) {
|
|
2657
|
+
const itemID = row['ContentItemID'];
|
|
2658
|
+
if (typeof row[pkName] === 'string' && typeof itemID === 'string') {
|
|
2659
|
+
map.set(NormalizeUUID(row[pkName]), NormalizeUUID(itemID));
|
|
1724
2660
|
}
|
|
1725
2661
|
}
|
|
2662
|
+
return map;
|
|
1726
2663
|
}
|
|
1727
|
-
/**
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
2664
|
+
/**
|
|
2665
|
+
* Content Item id → its Entity Record Document id, `null` when it has none.
|
|
2666
|
+
*
|
|
2667
|
+
* Always read through the base `MJ: Content Items`, whatever entity the result was labelled with:
|
|
2668
|
+
* `RootParentID` is a view-computed column, and an IS-A subtype's view projects only its parent's
|
|
2669
|
+
* base columns, so reading a subtype would silently lose the root link and let a split child
|
|
2670
|
+
* through as "no origin". The key is shared across the family, so the base view holds every row.
|
|
2671
|
+
*
|
|
2672
|
+
* A split child is judged by its own document first and by its root's only when it has none — one more
|
|
2673
|
+
* hop, taken once. A failed root lookup leaves only those children unresolved (dropped); a failed item
|
|
2674
|
+
* lookup throws, since every row depends on it.
|
|
2675
|
+
*/
|
|
2676
|
+
async lookupItemOrigins(itemIDs, contextUser) {
|
|
2677
|
+
const fields = ['ID', 'ParentID', 'RootParentID', 'EntityRecordDocumentID'];
|
|
2678
|
+
const rows = await this.runLookup('MJ: Content Items', fields, 'ID', itemIDs, contextUser);
|
|
2679
|
+
if (!rows)
|
|
2680
|
+
throw new Error('lookup of "MJ: Content Items" failed; every result depends on it');
|
|
2681
|
+
const map = new Map();
|
|
2682
|
+
const rootOfChild = this.classifyItemRows(rows, map);
|
|
2683
|
+
if (rootOfChild.size === 0)
|
|
2684
|
+
return map;
|
|
2685
|
+
const roots = Array.from(new Set(rootOfChild.values()));
|
|
2686
|
+
const rootRows = (await this.runLookup('MJ: Content Items', fields, 'ID', roots, contextUser)) ?? [];
|
|
2687
|
+
const docOfRoot = new Map(rootRows.map(r => [NormalizeUUID(r.ID), r.EntityRecordDocumentID ? NormalizeUUID(r.EntityRecordDocumentID) : null]));
|
|
2688
|
+
for (const [child, root] of rootOfChild) {
|
|
2689
|
+
const doc = docOfRoot.get(root);
|
|
2690
|
+
if (doc !== undefined)
|
|
2691
|
+
map.set(child, doc); // an unreadable root leaves the child unresolved → dropped
|
|
2692
|
+
}
|
|
2693
|
+
return map;
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* Sort item rows: an item with its own document, or a root (no `ParentID`) with none, goes straight into
|
|
2697
|
+
* `map`; a split child with no document of its own is returned as child → root, to be judged by its root.
|
|
2698
|
+
* The view gives a root its own id as `RootParentID`, so a root is never re-read. A child whose
|
|
2699
|
+
* `RootParentID` is missing or names itself (the view could not walk its `ParentID` chain) goes nowhere:
|
|
2700
|
+
* unresolved, so dropped, rather than passed as "no origin".
|
|
2701
|
+
*/
|
|
2702
|
+
classifyItemRows(rows, map) {
|
|
2703
|
+
const rootOfChild = new Map();
|
|
2704
|
+
for (const row of rows) {
|
|
2705
|
+
const id = NormalizeUUID(row.ID);
|
|
2706
|
+
const root = row.RootParentID ? NormalizeUUID(row.RootParentID) : null;
|
|
2707
|
+
if (row.EntityRecordDocumentID)
|
|
2708
|
+
map.set(id, NormalizeUUID(row.EntityRecordDocumentID));
|
|
2709
|
+
else if (!row.ParentID)
|
|
2710
|
+
map.set(id, null); // a root with no document: no origin
|
|
2711
|
+
else if (root && root !== id)
|
|
2712
|
+
rootOfChild.set(id, root); // a split child: judged by its root
|
|
2713
|
+
else
|
|
2714
|
+
LogError(`SearchEngine: content item ${id} has a ParentID but no resolvable root; its hits are dropped`);
|
|
2715
|
+
}
|
|
2716
|
+
return rootOfChild;
|
|
2717
|
+
}
|
|
2718
|
+
/**
|
|
2719
|
+
* Entity Record Document id → the (entity, record) it documents, read as the user. Only document-bearing
|
|
2720
|
+
* items depend on this hop, so a failed lookup resolves nothing here and drops those rows alone. A
|
|
2721
|
+
* document that names no entity or record resolves nothing either.
|
|
2722
|
+
*/
|
|
2723
|
+
async lookupEntityRecordDocuments(erdIDs, contextUser) {
|
|
2724
|
+
const map = new Map();
|
|
2725
|
+
if (erdIDs.length === 0)
|
|
2726
|
+
return map;
|
|
2727
|
+
const fields = ['ID', 'Entity', 'RecordID'];
|
|
2728
|
+
const rows = (await this.runLookup('MJ: Entity Record Documents', fields, 'ID', erdIDs, contextUser)) ?? [];
|
|
2729
|
+
for (const row of rows) {
|
|
2730
|
+
if (row.Entity && row.RecordID)
|
|
2731
|
+
map.set(NormalizeUUID(row.ID), { EntityName: row.Entity, RecordID: row.RecordID });
|
|
2732
|
+
}
|
|
2733
|
+
return map;
|
|
1731
2734
|
}
|
|
1732
|
-
/**
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
2735
|
+
/**
|
|
2736
|
+
* One `Fields` projection of `entityName` where `keyField IN (ids)`, as the user. `null` (logged) when the
|
|
2737
|
+
* RunView fails, or when a row comes back without one of `fields`: field-level security drops a denied
|
|
2738
|
+
* column from the projection silently, and reading the absent column as null would turn "may not see the
|
|
2739
|
+
* link" into "has no origin" and let the hit through. The caller decides how far the failure reaches.
|
|
2740
|
+
* `MaxRows` is the number of ids (each matches at most one row), so `UserViewMaxRows` cannot truncate it.
|
|
2741
|
+
*/
|
|
2742
|
+
async runLookup(entityName, fields, keyField, ids, contextUser) {
|
|
2743
|
+
if (ids.length === 0)
|
|
2744
|
+
return [];
|
|
2745
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2746
|
+
const result = await rv.RunView({
|
|
2747
|
+
EntityName: entityName,
|
|
2748
|
+
Fields: fields,
|
|
2749
|
+
ExtraFilter: `${keyField} IN (${ids.map(id => `'${EscapeSQLString(id)}'`).join(',')})`,
|
|
2750
|
+
ResultType: 'simple',
|
|
2751
|
+
MaxRows: ids.length
|
|
2752
|
+
}, contextUser);
|
|
2753
|
+
if (!result.Success) {
|
|
2754
|
+
LogError(`SearchEngine: origin lookup of "${entityName}" failed for user ${contextUser.ID}: ${result.ErrorMessage ?? 'unknown error'}`);
|
|
2755
|
+
return null;
|
|
2756
|
+
}
|
|
2757
|
+
const missing = fields.find(field => result.Results.some(row => !Object.prototype.hasOwnProperty.call(row, field)));
|
|
2758
|
+
if (missing) {
|
|
2759
|
+
LogError(`SearchEngine: origin lookup of "${entityName}" returned no "${missing}" column for user ${contextUser.ID} ` +
|
|
2760
|
+
'(denied by field-level security?); the rows that depend on it are dropped');
|
|
2761
|
+
return null;
|
|
2762
|
+
}
|
|
2763
|
+
return result.Results;
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Keep the results whose origin record the user may read. Origins are verified through
|
|
2767
|
+
* {@link ReadableOriginRecordIDs}: one batch, one view per origin entity.
|
|
2768
|
+
*/
|
|
2769
|
+
async keepReadableOrigins(entity, results, origins, contextUser) {
|
|
2770
|
+
const idsByEntity = new Map();
|
|
2771
|
+
for (const origin of origins.values()) {
|
|
2772
|
+
if (!origin)
|
|
2773
|
+
continue;
|
|
2774
|
+
const ids = idsByEntity.get(origin.EntityName) ?? new Set();
|
|
2775
|
+
ids.add(origin.RecordID);
|
|
2776
|
+
idsByEntity.set(origin.EntityName, ids);
|
|
2777
|
+
}
|
|
2778
|
+
const readable = await this.ReadableOriginRecordIDs(new Map(Array.from(idsByEntity, ([entityName, ids]) => [entityName, Array.from(ids)])), contextUser);
|
|
2779
|
+
return results.filter(r => {
|
|
2780
|
+
const origin = origins.get(this.contentRecordKey(entity, r.RecordID));
|
|
2781
|
+
if (origin === undefined)
|
|
2782
|
+
return false;
|
|
2783
|
+
if (origin === null)
|
|
2784
|
+
return true;
|
|
2785
|
+
return readable.get(origin.EntityName)?.has(origin.RecordID) ?? false;
|
|
2786
|
+
});
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* For each origin entity, those of its record ids the user may read under that entity's own permissions and
|
|
2790
|
+
* row filters — the check {@link verifyOwnershipAndRowFilters} gives a result's own entity. All entities are
|
|
2791
|
+
* asked in one `RunViews` batch. An entity the provider does not know, the user may not read at all, or
|
|
2792
|
+
* whose view fails gets no entry, so only the rows derived from it are dropped.
|
|
2793
|
+
*
|
|
2794
|
+
* Protected so a host extending {@link VerifyOriginRecords} to another derived-content family can reuse it.
|
|
2795
|
+
*
|
|
2796
|
+
* @param idsByEntity origin entity name → record ids, each a bare key value or a key segment
|
|
2797
|
+
* @returns origin entity name → the ids (as given) of the rows the user may read
|
|
2798
|
+
*/
|
|
2799
|
+
async ReadableOriginRecordIDs(idsByEntity, contextUser) {
|
|
2800
|
+
const readable = new Map();
|
|
2801
|
+
const checks = this.originReadChecks(idsByEntity, contextUser);
|
|
2802
|
+
if (checks.length === 0)
|
|
2803
|
+
return readable;
|
|
2804
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
2805
|
+
const results = await rv.RunViews(checks.map(c => c.Params), contextUser);
|
|
2806
|
+
checks.forEach((check, i) => {
|
|
2807
|
+
const keys = this.readableKeySet(check.Entity, results[i]);
|
|
2808
|
+
if (!keys)
|
|
2809
|
+
return; // logged; only the rows derived from this entity are dropped
|
|
2810
|
+
readable.set(check.EntityName, new Set(check.RecordIDs.filter(id => {
|
|
2811
|
+
const key = this.recordMatchKey(check.Entity, id);
|
|
2812
|
+
return key !== null && keys.has(key);
|
|
2813
|
+
})));
|
|
2814
|
+
});
|
|
2815
|
+
return readable;
|
|
2816
|
+
}
|
|
2817
|
+
/** The readability view for each origin entity the user may read at all. The rest get none: not readable. */
|
|
2818
|
+
originReadChecks(idsByEntity, contextUser) {
|
|
2819
|
+
const checks = [];
|
|
2820
|
+
for (const [entityName, recordIDs] of idsByEntity) {
|
|
2821
|
+
let entity;
|
|
2822
|
+
try {
|
|
2823
|
+
entity = this.ProviderToUse.EntityByName(entityName);
|
|
2824
|
+
}
|
|
2825
|
+
catch {
|
|
2826
|
+
entity = undefined;
|
|
2827
|
+
}
|
|
2828
|
+
if (!entity) {
|
|
2829
|
+
LogError(`SearchEngine: origin entity "${entityName}" is not in metadata; the hits derived from it are dropped`);
|
|
2830
|
+
continue;
|
|
2831
|
+
}
|
|
2832
|
+
if (!entity.GetUserPermisions(contextUser)?.CanRead)
|
|
2833
|
+
continue;
|
|
2834
|
+
const rlsClause = entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, '') || undefined;
|
|
2835
|
+
const params = this.readableKeysParams(entity, recordIDs, rlsClause);
|
|
2836
|
+
if (params)
|
|
2837
|
+
checks.push({ EntityName: entityName, Entity: entity, RecordIDs: recordIDs, Params: params });
|
|
2838
|
+
}
|
|
2839
|
+
return checks;
|
|
1737
2840
|
}
|
|
1738
2841
|
/**
|
|
1739
2842
|
* Key values in primary-key metadata order, UUID-normalized and joined — the comparison form for
|