@memberjunction/record-set-processor 6.1.2 → 6.2.0-edge.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RecordProcessExecutor.d.ts +3 -1
- package/dist/RecordProcessExecutor.d.ts.map +1 -1
- package/dist/RecordProcessExecutor.js +86 -7
- package/dist/RecordProcessExecutor.js.map +1 -1
- package/dist/RecordSetProcessor.d.ts.map +1 -1
- package/dist/RecordSetProcessor.js +134 -2
- package/dist/RecordSetProcessor.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/processors/ActionRecordProcessor.d.ts +2 -2
- package/dist/processors/ActionRecordProcessor.d.ts.map +1 -1
- package/dist/processors/ActionRecordProcessor.js.map +1 -1
- package/dist/processors/AgentRecordProcessor.d.ts +2 -2
- package/dist/processors/AgentRecordProcessor.d.ts.map +1 -1
- package/dist/processors/AgentRecordProcessor.js.map +1 -1
- package/dist/processors/InferProcessor.d.ts +84 -7
- package/dist/processors/InferProcessor.d.ts.map +1 -1
- package/dist/processors/InferProcessor.js +652 -14
- package/dist/processors/InferProcessor.js.map +1 -1
- package/dist/processors/WriteBackProcessor.d.ts +16 -2
- package/dist/processors/WriteBackProcessor.d.ts.map +1 -1
- package/dist/processors/WriteBackProcessor.js +85 -1
- package/dist/processors/WriteBackProcessor.js.map +1 -1
- package/dist/watermark/WatermarkService.d.ts +81 -0
- package/dist/watermark/WatermarkService.d.ts.map +1 -0
- package/dist/watermark/WatermarkService.js +224 -0
- package/dist/watermark/WatermarkService.js.map +1 -0
- package/dist/writeBack.d.ts +82 -19
- package/dist/writeBack.d.ts.map +1 -1
- package/dist/writeBack.js +372 -35
- package/dist/writeBack.js.map +1 -1
- package/package.json +16 -13
|
@@ -3,47 +3,542 @@
|
|
|
3
3
|
* returns the structured result as the record's `ResultPayload`. Write-back is NOT done here: the
|
|
4
4
|
* `WriteBackProcessor` wrapper (added by `RecordProcessExecutor` when an OutputMapping is set)
|
|
5
5
|
* applies the Record Process's OutputMapping uniformly across Action / Agent / Infer work types.
|
|
6
|
+
*
|
|
7
|
+
* Supports DataFeatureSpec context (EntityDocumentID template rendering with __Parent context,
|
|
8
|
+
* QueryID parameterized execution, Field projections), Layer-1 constraint injection, Layer-2
|
|
9
|
+
* constraint validation with OnViolation policies, and lifecycle hooks (P1-6).
|
|
10
|
+
*
|
|
6
11
|
* @module @memberjunction/record-set-processor
|
|
7
12
|
*/
|
|
8
|
-
import {
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { LogError, Metadata, RunQuery, RunView } from '@memberjunction/core';
|
|
15
|
+
import { UUIDsEqual, Canonicalize, ComputeContentHashAsync, EscapeSQLString, resolveMappingRef, resolveValueMapping } from '@memberjunction/global';
|
|
9
16
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
10
17
|
import { AIPromptRunner } from '@memberjunction/ai-prompts';
|
|
11
18
|
import { AIPromptParams } from '@memberjunction/ai-core-plus';
|
|
19
|
+
import { FeatureValueCacheService, renderConstraintBlock, validateOutputValue, } from '@memberjunction/feature-pipelines';
|
|
20
|
+
import { EntityDocumentCache, EntityDocumentTemplateParser } from '@memberjunction/entity-documents';
|
|
12
21
|
/** Runs an AI Prompt per record and returns its structured output (write-back is the wrapper's job). */
|
|
13
22
|
export class InferProcessor {
|
|
14
23
|
/**
|
|
15
24
|
* @param promptID - The `MJ: AI Prompts` ID to run for each record.
|
|
16
25
|
* @param inputMapping - Optional mapping shaping the data passed to the prompt (default: `{ record }`).
|
|
26
|
+
* @param spec - Optional DataFeatureSpec defining outputs, constraints, and caching policy.
|
|
17
27
|
*/
|
|
18
|
-
constructor(promptID, inputMapping) {
|
|
28
|
+
constructor(promptID, inputMapping, spec) {
|
|
19
29
|
this.promptID = promptID;
|
|
20
30
|
this.inputMapping = inputMapping;
|
|
31
|
+
this.spec = spec;
|
|
21
32
|
}
|
|
22
|
-
async ProcessRecord(record, context) {
|
|
33
|
+
async ProcessRecord(record, context, options) {
|
|
34
|
+
await this.ensureRecordsLoaded([record], context);
|
|
23
35
|
await AIEngine.Instance.Config(false, context.contextUser);
|
|
24
36
|
const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
|
|
25
37
|
if (!prompt) {
|
|
26
38
|
return { Status: 'Failed', ErrorMessage: `AI Prompt '${this.promptID}' not found` };
|
|
27
39
|
}
|
|
40
|
+
const isCacheable = this.spec?.Caching?.Cacheable === true;
|
|
41
|
+
const promptVersionHash = this.computePromptVersionHash(prompt, this.spec);
|
|
42
|
+
const constraintHash = this.computeConstraintHash(this.spec);
|
|
43
|
+
let keyInfo;
|
|
44
|
+
// P1-7c Dedup Cache lookup
|
|
45
|
+
if (isCacheable) {
|
|
46
|
+
keyInfo =
|
|
47
|
+
options?.keyInfo ??
|
|
48
|
+
(await FeatureValueCacheService.Instance.computeCacheKey({
|
|
49
|
+
keyFields: this.spec?.Caching?.KeyFields,
|
|
50
|
+
recordData: this.recordToPlain(record),
|
|
51
|
+
}));
|
|
52
|
+
if (!options?.skipLookup) {
|
|
53
|
+
const cached = await FeatureValueCacheService.Instance.Lookup({
|
|
54
|
+
recordProcessID: context.recordProcessID,
|
|
55
|
+
scope: this.spec?.Caching?.Scope,
|
|
56
|
+
promptID: prompt.ID,
|
|
57
|
+
promptVersionHash,
|
|
58
|
+
constraintHash,
|
|
59
|
+
keyHash: keyInfo.keyHash,
|
|
60
|
+
contextUser: context.contextUser,
|
|
61
|
+
provider: context.provider,
|
|
62
|
+
});
|
|
63
|
+
if (cached) {
|
|
64
|
+
let cachedPayload = JSON.parse(cached.OutputsJSON);
|
|
65
|
+
if (typeof cachedPayload === 'string') {
|
|
66
|
+
try {
|
|
67
|
+
cachedPayload = JSON.parse(cachedPayload);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// keep as string
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
await this.recordFeatureValuesHistory({
|
|
74
|
+
record,
|
|
75
|
+
context,
|
|
76
|
+
payload: cachedPayload,
|
|
77
|
+
reasoning: cached.Reasoning,
|
|
78
|
+
promptID: prompt.ID,
|
|
79
|
+
promptVersionHash,
|
|
80
|
+
constraintHash,
|
|
81
|
+
aiPromptRunID: cached.AIPromptRunID,
|
|
82
|
+
featureValueCacheID: cached.ID,
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
Status: 'Succeeded',
|
|
86
|
+
ResultPayload: cachedPayload,
|
|
87
|
+
AIPromptRunID: cached.AIPromptRunID ?? undefined,
|
|
88
|
+
PromptVersionHash: promptVersionHash,
|
|
89
|
+
FeatureValueCacheID: cached.ID,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// P1-6 Hook: beforeBuildContext
|
|
95
|
+
await this.beforeBuildContext(record, context);
|
|
96
|
+
// Carry ValidationBehavior on the execution run (AIPromptParams.validationBehavior)
|
|
97
|
+
// and wrap the prompt in an execution-scoped Proxy so reads of params.prompt.ValidationBehavior
|
|
98
|
+
// see the execution's behavior without mutating the shared entity in AIEngine cache (R11-B).
|
|
99
|
+
const targetValidationBehavior = (this.spec?.Outputs && this.spec.Outputs.length > 0) ? 'Strict' : prompt.ValidationBehavior;
|
|
100
|
+
const executionPrompt = new Proxy(prompt, {
|
|
101
|
+
get(target, prop, receiver) {
|
|
102
|
+
if (prop === 'ValidationBehavior') {
|
|
103
|
+
return targetValidationBehavior;
|
|
104
|
+
}
|
|
105
|
+
return Reflect.get(target, prop, receiver);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
28
108
|
const params = new AIPromptParams();
|
|
29
|
-
params.prompt =
|
|
30
|
-
params.
|
|
109
|
+
params.prompt = executionPrompt;
|
|
110
|
+
params.validationBehavior = targetValidationBehavior;
|
|
111
|
+
params.data = await this.buildPromptData(record, context);
|
|
31
112
|
params.contextUser = context.contextUser;
|
|
113
|
+
// P1-6 Hook: beforePromptExecute
|
|
114
|
+
await this.beforePromptExecute(params, record, context);
|
|
32
115
|
const result = await new AIPromptRunner().ExecutePrompt(params);
|
|
33
116
|
const aiPromptRunID = result.promptRun?.ID;
|
|
34
117
|
if (!result.success) {
|
|
35
|
-
return {
|
|
118
|
+
return {
|
|
119
|
+
Status: 'Failed',
|
|
120
|
+
ErrorMessage: result.errorMessage ?? 'AI prompt execution failed',
|
|
121
|
+
AIPromptRunID: aiPromptRunID,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// P1-6 Hook: afterPromptExecute
|
|
125
|
+
let rawResult = await this.afterPromptExecute(result, record, context);
|
|
126
|
+
if (typeof rawResult === 'string') {
|
|
127
|
+
try {
|
|
128
|
+
rawResult = JSON.parse(rawResult);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// leave as raw string if not JSON
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// Layer 2: Validate outputs against constraints and apply OnViolation policy
|
|
135
|
+
const validationOutcome = await this.validateOutputs(this.spec?.Outputs ?? [], rawResult, record, context);
|
|
136
|
+
if (!validationOutcome.valid) {
|
|
137
|
+
return {
|
|
138
|
+
Status: 'Failed',
|
|
139
|
+
ErrorMessage: validationOutcome.errorMessage ?? 'Constraint violation',
|
|
140
|
+
AIPromptRunID: aiPromptRunID,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
let featureValueCacheID;
|
|
144
|
+
const reasoning = typeof rawResult === 'object' && rawResult !== null ? rawResult.reasoning : undefined;
|
|
145
|
+
// P1-7c Dedup Cache store
|
|
146
|
+
if (isCacheable && keyInfo) {
|
|
147
|
+
try {
|
|
148
|
+
const stored = await FeatureValueCacheService.Instance.Store({
|
|
149
|
+
recordProcessID: context.recordProcessID,
|
|
150
|
+
scope: this.spec?.Caching?.Scope,
|
|
151
|
+
promptID: prompt.ID,
|
|
152
|
+
promptVersionHash,
|
|
153
|
+
constraintHash,
|
|
154
|
+
keyHash: keyInfo.keyHash,
|
|
155
|
+
keyDisplay: keyInfo.keyDisplay,
|
|
156
|
+
keyJSON: keyInfo.keyJSON,
|
|
157
|
+
outputsJSON: JSON.stringify(validationOutcome.payload),
|
|
158
|
+
reasoning: reasoning ?? null,
|
|
159
|
+
aiPromptRunID: aiPromptRunID ?? null,
|
|
160
|
+
ttlSeconds: this.spec?.Caching?.TTLSeconds,
|
|
161
|
+
contextUser: context.contextUser,
|
|
162
|
+
provider: context.provider,
|
|
163
|
+
});
|
|
164
|
+
featureValueCacheID = stored.ID;
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
LogError(`InferProcessor: failed storing cache entry: ${e instanceof Error ? e.message : String(e)}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// P1-7c History tracking in MJ: Feature Values
|
|
171
|
+
await this.recordFeatureValuesHistory({
|
|
172
|
+
record,
|
|
173
|
+
context,
|
|
174
|
+
payload: validationOutcome.payload,
|
|
175
|
+
reasoning,
|
|
176
|
+
promptID: prompt.ID,
|
|
177
|
+
promptVersionHash,
|
|
178
|
+
constraintHash,
|
|
179
|
+
aiPromptRunID,
|
|
180
|
+
featureValueCacheID,
|
|
181
|
+
});
|
|
182
|
+
return {
|
|
183
|
+
Status: 'Succeeded',
|
|
184
|
+
ResultPayload: validationOutcome.payload,
|
|
185
|
+
AIPromptRunID: aiPromptRunID,
|
|
186
|
+
PromptVersionHash: promptVersionHash,
|
|
187
|
+
FeatureValueCacheID: featureValueCacheID,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Two-phase batch execution (P1-7c). Resolves distinct keys across the batch first,
|
|
192
|
+
* checks the dedup cache in one batch query, executes LLM prompts ONCE per distinct key,
|
|
193
|
+
* and fans results back across all matching rows.
|
|
194
|
+
*/
|
|
195
|
+
async ProcessBatch(records, context) {
|
|
196
|
+
await this.ensureRecordsLoaded(records, context);
|
|
197
|
+
const results = new Map();
|
|
198
|
+
if (!this.spec?.Caching?.Cacheable || records.length === 0) {
|
|
199
|
+
for (const r of records) {
|
|
200
|
+
results.set(r.RecordID, await this.ProcessRecord(r, context));
|
|
201
|
+
}
|
|
202
|
+
return results;
|
|
203
|
+
}
|
|
204
|
+
await AIEngine.Instance.Config(false, context.contextUser);
|
|
205
|
+
const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
|
|
206
|
+
if (!prompt) {
|
|
207
|
+
for (const r of records) {
|
|
208
|
+
results.set(r.RecordID, { Status: 'Failed', ErrorMessage: `AI Prompt '${this.promptID}' not found` });
|
|
209
|
+
}
|
|
210
|
+
return results;
|
|
211
|
+
}
|
|
212
|
+
const promptVersionHash = this.computePromptVersionHash(prompt, this.spec);
|
|
213
|
+
const constraintHash = this.computeConstraintHash(this.spec);
|
|
214
|
+
// Phase 1: Compute distinct cache keys across the batch
|
|
215
|
+
const keyGroupMap = new Map();
|
|
216
|
+
for (const record of records) {
|
|
217
|
+
const recordData = this.recordToPlain(record);
|
|
218
|
+
const keyInfo = await FeatureValueCacheService.Instance.computeCacheKey({
|
|
219
|
+
keyFields: this.spec.Caching.KeyFields,
|
|
220
|
+
recordData,
|
|
221
|
+
});
|
|
222
|
+
let group = keyGroupMap.get(keyInfo.keyHash);
|
|
223
|
+
if (!group) {
|
|
224
|
+
group = { keyInfo, records: [] };
|
|
225
|
+
keyGroupMap.set(keyInfo.keyHash, group);
|
|
226
|
+
}
|
|
227
|
+
group.records.push(record);
|
|
228
|
+
}
|
|
229
|
+
// Phase 2: Batch lookup existing cache entries for all distinct keys
|
|
230
|
+
const distinctKeyHashes = Array.from(keyGroupMap.keys());
|
|
231
|
+
const cacheMap = await FeatureValueCacheService.Instance.BatchLookup({
|
|
232
|
+
recordProcessID: context.recordProcessID,
|
|
233
|
+
scope: this.spec.Caching.Scope,
|
|
234
|
+
promptID: prompt.ID,
|
|
235
|
+
promptVersionHash,
|
|
236
|
+
constraintHash,
|
|
237
|
+
keyHashes: distinctKeyHashes,
|
|
238
|
+
contextUser: context.contextUser,
|
|
239
|
+
provider: context.provider,
|
|
240
|
+
});
|
|
241
|
+
// Phase 3: Fan out hits; execute misses ONCE per distinct key and fan out
|
|
242
|
+
for (const [keyHash, group] of keyGroupMap.entries()) {
|
|
243
|
+
const cached = cacheMap.get(keyHash);
|
|
244
|
+
if (cached) {
|
|
245
|
+
// CACHE HIT: fan out immediately to all matching records without calling LLM!
|
|
246
|
+
let cachedPayload = JSON.parse(cached.OutputsJSON);
|
|
247
|
+
if (typeof cachedPayload === 'string') {
|
|
248
|
+
try {
|
|
249
|
+
cachedPayload = JSON.parse(cachedPayload);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
// keep as string
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const rec of group.records) {
|
|
256
|
+
await this.recordFeatureValuesHistory({
|
|
257
|
+
record: rec,
|
|
258
|
+
context,
|
|
259
|
+
payload: cachedPayload,
|
|
260
|
+
reasoning: cached.Reasoning,
|
|
261
|
+
promptID: prompt.ID,
|
|
262
|
+
promptVersionHash,
|
|
263
|
+
constraintHash,
|
|
264
|
+
aiPromptRunID: cached.AIPromptRunID,
|
|
265
|
+
featureValueCacheID: cached.ID,
|
|
266
|
+
});
|
|
267
|
+
results.set(rec.RecordID, {
|
|
268
|
+
Status: 'Succeeded',
|
|
269
|
+
ResultPayload: cachedPayload,
|
|
270
|
+
AIPromptRunID: cached.AIPromptRunID ?? undefined,
|
|
271
|
+
PromptVersionHash: promptVersionHash,
|
|
272
|
+
FeatureValueCacheID: cached.ID,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
else {
|
|
277
|
+
// CACHE MISS: Execute prompt ONCE for the distinct key (using the first record in the group)
|
|
278
|
+
const sampleRecord = group.records[0];
|
|
279
|
+
const singleResult = await this.ProcessRecord(sampleRecord, context, {
|
|
280
|
+
skipLookup: true,
|
|
281
|
+
keyInfo: group.keyInfo,
|
|
282
|
+
});
|
|
283
|
+
// Fan out result to all records in this group
|
|
284
|
+
for (const rec of group.records) {
|
|
285
|
+
if (rec.RecordID === sampleRecord.RecordID) {
|
|
286
|
+
results.set(rec.RecordID, singleResult);
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
if (singleResult.Status === 'Succeeded') {
|
|
290
|
+
await this.recordFeatureValuesHistory({
|
|
291
|
+
record: rec,
|
|
292
|
+
context,
|
|
293
|
+
payload: singleResult.ResultPayload,
|
|
294
|
+
promptID: prompt.ID,
|
|
295
|
+
promptVersionHash,
|
|
296
|
+
constraintHash,
|
|
297
|
+
aiPromptRunID: singleResult.AIPromptRunID,
|
|
298
|
+
featureValueCacheID: singleResult.FeatureValueCacheID,
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
results.set(rec.RecordID, { ...singleResult });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return results;
|
|
307
|
+
}
|
|
308
|
+
/** Computes a deterministic SHA-256 hash representing the prompt version and constraint instructions. */
|
|
309
|
+
computePromptVersionHash(prompt, spec) {
|
|
310
|
+
const promptText = prompt.TemplateText ?? prompt.Description ?? prompt.Name ?? '';
|
|
311
|
+
const outputsStr = spec?.Outputs ? JSON.stringify(spec.Outputs) : '';
|
|
312
|
+
const constraintBlock = spec?.Outputs ? renderConstraintBlock(spec.Outputs) : '';
|
|
313
|
+
const hashBasis = `${prompt.ID}::${promptText}::${outputsStr}::${constraintBlock}`;
|
|
314
|
+
return createHash('sha256').update(hashBasis).digest('hex');
|
|
315
|
+
}
|
|
316
|
+
/** Computes a deterministic SHA-256 hash representing the output constraints. */
|
|
317
|
+
computeConstraintHash(spec) {
|
|
318
|
+
if (!spec?.Outputs || spec.Outputs.length === 0) {
|
|
319
|
+
return 'no-constraints';
|
|
36
320
|
}
|
|
37
|
-
|
|
321
|
+
const constraints = spec.Outputs.map((o) => ({
|
|
322
|
+
name: o.Name,
|
|
323
|
+
constraint: o.Constraint,
|
|
324
|
+
}));
|
|
325
|
+
const canonical = Canonicalize(constraints);
|
|
326
|
+
return createHash('sha256').update(canonical).digest('hex');
|
|
38
327
|
}
|
|
39
|
-
/**
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
328
|
+
/**
|
|
329
|
+
* Records historical audit rows in MJ: Feature Values for all outputs on a record.
|
|
330
|
+
*/
|
|
331
|
+
async recordFeatureValuesHistory(params) {
|
|
332
|
+
if (!this.spec?.Outputs || this.spec.Outputs.length === 0 || !params.context.recordProcessID || !params.context.entityID) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const outputsList = [];
|
|
336
|
+
const rawPayload = params.payload;
|
|
337
|
+
const sources = { $: rawPayload };
|
|
338
|
+
for (const output of this.spec.Outputs) {
|
|
339
|
+
const val = resolveMappingRef(output.Ref, sources);
|
|
340
|
+
outputsList.push({
|
|
341
|
+
featureName: output.Name,
|
|
342
|
+
value: val !== undefined ? val : null,
|
|
343
|
+
reasoning: params.reasoning,
|
|
344
|
+
confidence: params.confidence,
|
|
345
|
+
});
|
|
44
346
|
}
|
|
45
|
-
|
|
46
|
-
|
|
347
|
+
try {
|
|
348
|
+
await FeatureValueCacheService.Instance.RecordFeatureValues({
|
|
349
|
+
recordProcessID: params.context.recordProcessID,
|
|
350
|
+
entityID: params.context.entityID,
|
|
351
|
+
recordID: params.record.RecordID,
|
|
352
|
+
outputs: outputsList,
|
|
353
|
+
promptID: params.promptID,
|
|
354
|
+
promptVersionHash: params.promptVersionHash,
|
|
355
|
+
constraintHash: params.constraintHash,
|
|
356
|
+
processRunID: params.context.processRunID,
|
|
357
|
+
aiPromptRunID: params.aiPromptRunID,
|
|
358
|
+
featureValueCacheID: params.featureValueCacheID,
|
|
359
|
+
contextUser: params.context.contextUser,
|
|
360
|
+
provider: params.context.provider,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
catch (e) {
|
|
364
|
+
LogError(`InferProcessor: failed to record FeatureValues history for record '${params.record.RecordID}': ${e instanceof Error ? e.message : String(e)}`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Computes the watermark basis hash for Checksum strategy:
|
|
369
|
+
* SHA-256 over canonical { promptData, promptVersionHash }.
|
|
370
|
+
*/
|
|
371
|
+
async ComputeBasisHash(record, context) {
|
|
372
|
+
await this.ensureRecordsLoaded([record], context);
|
|
373
|
+
await AIEngine.Instance.Config(false, context.contextUser);
|
|
374
|
+
const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
|
|
375
|
+
const promptVersionHash = prompt ? this.computePromptVersionHash(prompt, this.spec) : '';
|
|
376
|
+
const promptData = await this.buildPromptData(record, context);
|
|
377
|
+
return ComputeContentHashAsync({
|
|
378
|
+
promptData,
|
|
379
|
+
promptVersionHash,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
// -------------------------------------------------------------------------------------------------
|
|
383
|
+
// P1-6 Lifecycle Hooks (overridable by subclasses registered under DataFeatureSpec.ProcessorExtensionKey)
|
|
384
|
+
// -------------------------------------------------------------------------------------------------
|
|
385
|
+
/** Lifecycle hook called before prompt data context is constructed. */
|
|
386
|
+
async beforeBuildContext(record, ctx) { }
|
|
387
|
+
/** Lifecycle hook called immediately before ExecutePrompt is invoked. */
|
|
388
|
+
async beforePromptExecute(params, record, ctx) { }
|
|
389
|
+
/** Lifecycle hook called after prompt execution returns successfully. Defaults to returning result.result. */
|
|
390
|
+
async afterPromptExecute(result, record, ctx) {
|
|
391
|
+
return result.result ?? {};
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Layer 2 output validation hook. Evaluates outputs against declared constraints, applies OnViolation
|
|
395
|
+
* policies (fail, null, coerce-to-other), and builds the processed payload.
|
|
396
|
+
*/
|
|
397
|
+
async validateOutputs(outputs, rawResult, record, ctx) {
|
|
398
|
+
if (!outputs || !Array.isArray(outputs) || outputs.length === 0) {
|
|
399
|
+
return { valid: true, payload: rawResult };
|
|
400
|
+
}
|
|
401
|
+
let payloadCopy = typeof rawResult === 'object' && rawResult !== null
|
|
402
|
+
? structuredClone(rawResult)
|
|
403
|
+
: rawResult;
|
|
404
|
+
const violations = [];
|
|
405
|
+
for (const output of outputs) {
|
|
406
|
+
if (!output.Constraint) {
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const sources = { $: rawResult };
|
|
410
|
+
const rawVal = resolveMappingRef(output.Ref, sources);
|
|
411
|
+
let targetTSType;
|
|
412
|
+
const target = output.Target;
|
|
413
|
+
if (target.Mode === 'field') {
|
|
414
|
+
const entity = ctx.provider?.EntityByID(record.EntityID);
|
|
415
|
+
const field = entity?.Fields?.find((f) => f.Name.toLowerCase() === target.EntityFieldName.toLowerCase());
|
|
416
|
+
targetTSType = field?.TSType;
|
|
417
|
+
}
|
|
418
|
+
const validation = validateOutputValue(rawVal, output.Constraint, {
|
|
419
|
+
targetFieldTSType: targetTSType,
|
|
420
|
+
});
|
|
421
|
+
if (!validation.valid) {
|
|
422
|
+
return {
|
|
423
|
+
valid: false,
|
|
424
|
+
errorMessage: `Constraint violation for '${output.Name}': ${validation.violationMessage}`,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
if (validation.violationPolicyApplied === 'null' || validation.violationPolicyApplied === 'coerce-to-other') {
|
|
428
|
+
violations.push({
|
|
429
|
+
outputName: output.Name,
|
|
430
|
+
violationMessage: validation.violationMessage ?? 'Constraint violation',
|
|
431
|
+
policy: validation.violationPolicyApplied,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
if (validation.coerced || validation.value !== rawVal) {
|
|
435
|
+
if (output.Ref === '$') {
|
|
436
|
+
payloadCopy = validation.value;
|
|
437
|
+
}
|
|
438
|
+
else if (typeof payloadCopy === 'object' && payloadCopy !== null && output.Ref.startsWith('$.')) {
|
|
439
|
+
const propPath = output.Ref.substring(2);
|
|
440
|
+
setNestedValue(payloadCopy, propPath, validation.value);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (typeof payloadCopy === 'object' && payloadCopy !== null && violations.length > 0) {
|
|
445
|
+
payloadCopy._violations = violations;
|
|
446
|
+
}
|
|
447
|
+
return { valid: true, payload: payloadCopy };
|
|
448
|
+
}
|
|
449
|
+
/** Lifecycle hook to resolve a dedup cache key for this record. Default returns null (computed by cache service). */
|
|
450
|
+
async resolveCacheKey(record, spec, ctx) {
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
/** Lifecycle hook called before write-back is executed on this record. */
|
|
454
|
+
async beforeWriteBack(mapping, result, record, ctx) { }
|
|
455
|
+
// -------------------------------------------------------------------------------------------------
|
|
456
|
+
// Context Construction & Helpers
|
|
457
|
+
// -------------------------------------------------------------------------------------------------
|
|
458
|
+
/**
|
|
459
|
+
* Builds the data object passed to the prompt.
|
|
460
|
+
* Incorporates spec.Context (EntityDocumentID rendering, QueryID parameterized execution, Field filtering),
|
|
461
|
+
* input mapping, and Layer-1 constraint instructions.
|
|
462
|
+
*/
|
|
463
|
+
async buildPromptData(record, ctx) {
|
|
464
|
+
let recordData = this.recordToPlain(record);
|
|
465
|
+
// Context.Fields projection: filter record fields if explicit fields are listed
|
|
466
|
+
if (this.spec?.Context?.Fields && this.spec.Context.Fields.length > 0) {
|
|
467
|
+
const allowed = new Set(this.spec.Context.Fields.map((f) => f.toLowerCase()));
|
|
468
|
+
const filtered = {};
|
|
469
|
+
for (const [key, val] of Object.entries(recordData)) {
|
|
470
|
+
if (allowed.has(key.toLowerCase()) || key === 'ID' || key === 'RecordID' || key === 'EntityID') {
|
|
471
|
+
filtered[key] = val;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
recordData = filtered;
|
|
475
|
+
}
|
|
476
|
+
let promptData;
|
|
477
|
+
const mappingToUse = this.inputMapping ?? this.spec?.Context?.InputMapping;
|
|
478
|
+
if (!mappingToUse) {
|
|
479
|
+
promptData = { record: recordData };
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
const mapped = resolveValueMapping(mappingToUse, { record: recordData });
|
|
483
|
+
promptData = mapped && typeof mapped === 'object' ? mapped : { record: recordData };
|
|
484
|
+
}
|
|
485
|
+
// P1-8a: EntityDocument context rendering
|
|
486
|
+
if (this.spec?.Context?.EntityDocumentID && ctx) {
|
|
487
|
+
try {
|
|
488
|
+
await EntityDocumentCache.Instance.Refresh(false, ctx.contextUser);
|
|
489
|
+
const doc = EntityDocumentCache.Instance.GetDocument(this.spec.Context.EntityDocumentID);
|
|
490
|
+
if (doc) {
|
|
491
|
+
const parser = EntityDocumentTemplateParser.CreateInstance();
|
|
492
|
+
if (ctx.provider) {
|
|
493
|
+
parser.ProviderOverride = ctx.provider;
|
|
494
|
+
}
|
|
495
|
+
const templateText = await parser.resolveDocumentTemplateText(doc, ctx.contextUser);
|
|
496
|
+
if (templateText && templateText.trim().length > 0) {
|
|
497
|
+
const rendered = await parser.Parse(templateText, record.EntityID, recordData, ctx.contextUser);
|
|
498
|
+
promptData.context = rendered;
|
|
499
|
+
promptData.RenderedContext = rendered;
|
|
500
|
+
promptData.document = rendered;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
catch (e) {
|
|
505
|
+
LogError(`InferProcessor: failed to render EntityDocument '${this.spec.Context.EntityDocumentID}': ${e instanceof Error ? e.message : String(e)}`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
// P1-8a / C7: Query context execution
|
|
509
|
+
if (this.spec?.Context?.QueryID && ctx) {
|
|
510
|
+
try {
|
|
511
|
+
const rq = new RunQuery();
|
|
512
|
+
const queryParams = {};
|
|
513
|
+
if (this.spec.Context.QueryParams) {
|
|
514
|
+
for (const [pName, pRef] of Object.entries(this.spec.Context.QueryParams)) {
|
|
515
|
+
queryParams[pName] = resolveMappingRef(pRef, { record: recordData, $: recordData });
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const qResult = await rq.RunQuery({ QueryID: this.spec.Context.QueryID, Parameters: queryParams }, ctx.contextUser);
|
|
519
|
+
if (qResult && qResult.Success) {
|
|
520
|
+
promptData.queryResult = qResult.Results;
|
|
521
|
+
if (!promptData.context) {
|
|
522
|
+
promptData.context = qResult.Results;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
LogError(`InferProcessor: RunQuery '${this.spec.Context.QueryID}' failed: ${qResult?.ErrorMessage ?? 'unknown error'}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
catch (e) {
|
|
530
|
+
LogError(`InferProcessor: failed executing Query '${this.spec.Context.QueryID}': ${e instanceof Error ? e.message : String(e)}`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
// Layer 1: Inject constraint block if feature spec declares outputs
|
|
534
|
+
if (this.spec?.Outputs && this.spec.Outputs.length > 0) {
|
|
535
|
+
const constraintBlock = renderConstraintBlock(this.spec.Outputs);
|
|
536
|
+
if (constraintBlock && constraintBlock.trim().length > 0) {
|
|
537
|
+
promptData.constraints = constraintBlock;
|
|
538
|
+
promptData.ConstraintBlock = constraintBlock;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return promptData;
|
|
47
542
|
}
|
|
48
543
|
/** Extracts a plain field map from the record (BaseEntity → GetAll(), plain object → as-is). */
|
|
49
544
|
recordToPlain(record) {
|
|
@@ -56,5 +551,148 @@ export class InferProcessor {
|
|
|
56
551
|
}
|
|
57
552
|
return { RecordID: record.RecordID, EntityID: record.EntityID };
|
|
58
553
|
}
|
|
554
|
+
/**
|
|
555
|
+
* Ensures that every record in the batch has its full field data loaded on `record.Record`.
|
|
556
|
+
* If records only have primary keys (as yielded by source pagination), batch-fetches the
|
|
557
|
+
* full records via RunView in a single query per entity.
|
|
558
|
+
*/
|
|
559
|
+
async ensureRecordsLoaded(records, context) {
|
|
560
|
+
const requiredFields = [];
|
|
561
|
+
if (this.spec?.Context?.Fields) {
|
|
562
|
+
requiredFields.push(...this.spec.Context.Fields);
|
|
563
|
+
}
|
|
564
|
+
if (this.spec?.Caching?.KeyFields) {
|
|
565
|
+
requiredFields.push(...this.spec.Caching.KeyFields);
|
|
566
|
+
}
|
|
567
|
+
const needsLoading = records.filter((r) => {
|
|
568
|
+
if (!r.Record || typeof r.Record !== 'object')
|
|
569
|
+
return true;
|
|
570
|
+
if (typeof r.Record.GetAll === 'function')
|
|
571
|
+
return false;
|
|
572
|
+
const rec = r.Record;
|
|
573
|
+
// If explicit fields are required, check if any is missing
|
|
574
|
+
if (requiredFields.length > 0) {
|
|
575
|
+
const recKeysLower = new Set(Object.keys(rec).map((k) => k.toLowerCase()));
|
|
576
|
+
const missing = requiredFields.some((f) => !recKeysLower.has(f.toLowerCase()));
|
|
577
|
+
if (missing)
|
|
578
|
+
return true;
|
|
579
|
+
return false;
|
|
580
|
+
}
|
|
581
|
+
// If no explicit fields, check if record only contains primary/identity keys
|
|
582
|
+
const nonPkKeys = Object.keys(rec).filter((k) => {
|
|
583
|
+
const lower = k.toLowerCase();
|
|
584
|
+
return lower !== 'id' && lower !== 'recordid' && lower !== 'entityid';
|
|
585
|
+
});
|
|
586
|
+
return nonPkKeys.length === 0;
|
|
587
|
+
});
|
|
588
|
+
if (needsLoading.length === 0)
|
|
589
|
+
return;
|
|
590
|
+
const candidateProvider = context.provider ?? Metadata.Provider; // global-provider-ok: fallback to global provider when not in context
|
|
591
|
+
const provider = (candidateProvider && typeof candidateProvider.EntityByID === 'function')
|
|
592
|
+
? candidateProvider
|
|
593
|
+
: undefined;
|
|
594
|
+
if (!provider)
|
|
595
|
+
return;
|
|
596
|
+
const byEntity = new Map();
|
|
597
|
+
for (const r of needsLoading) {
|
|
598
|
+
const list = byEntity.get(r.EntityID) ?? [];
|
|
599
|
+
list.push(r);
|
|
600
|
+
byEntity.set(r.EntityID, list);
|
|
601
|
+
}
|
|
602
|
+
for (const [entityID, entityRecords] of byEntity) {
|
|
603
|
+
const entity = provider.EntityByID(entityID);
|
|
604
|
+
if (!entity)
|
|
605
|
+
continue;
|
|
606
|
+
const pk = entity.FirstPrimaryKey?.Name ?? 'ID'; // first-pk-ok: batch lookup by PK for entity records
|
|
607
|
+
const chunkSize = 500;
|
|
608
|
+
for (let i = 0; i < entityRecords.length; i += chunkSize) {
|
|
609
|
+
const chunk = entityRecords.slice(i, i + chunkSize);
|
|
610
|
+
const ids = chunk.map((r) => `'${EscapeSQLString(r.RecordID)}'`).join(',');
|
|
611
|
+
const rv = new RunView();
|
|
612
|
+
const result = await rv.RunView({
|
|
613
|
+
EntityName: entity.Name,
|
|
614
|
+
ExtraFilter: `[${pk}] IN (${ids})`,
|
|
615
|
+
ResultType: 'simple',
|
|
616
|
+
MaxRows: chunk.length,
|
|
617
|
+
BypassCache: true,
|
|
618
|
+
}, context.contextUser);
|
|
619
|
+
if (result.Success && result.Results) {
|
|
620
|
+
const rowMap = new Map();
|
|
621
|
+
for (const row of result.Results) {
|
|
622
|
+
const idVal = String(row[pk]);
|
|
623
|
+
rowMap.set(idVal, row);
|
|
624
|
+
}
|
|
625
|
+
for (const r of chunk) {
|
|
626
|
+
const row = rowMap.get(r.RecordID);
|
|
627
|
+
if (row) {
|
|
628
|
+
r.Record = row;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
else {
|
|
633
|
+
const errMsg = result.ErrorMessage || 'Failed to load records from entity view';
|
|
634
|
+
LogError(`[InferProcessor] ensureRecordsLoaded failed for entity '${entity.Name}': ${errMsg}`);
|
|
635
|
+
throw new Error(`[InferProcessor] Failed to load records for entity '${entity.Name}': ${errMsg}`);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Sets a value at a dot-delimited path (e.g. 'a.b' or 'items[0].name') on an object,
|
|
643
|
+
* mutating the object in-place and creating intermediate objects or arrays as needed.
|
|
644
|
+
*/
|
|
645
|
+
export function setNestedValue(obj, path, value) {
|
|
646
|
+
if (!path)
|
|
647
|
+
return;
|
|
648
|
+
const parts = path.split('.');
|
|
649
|
+
let current = obj;
|
|
650
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
651
|
+
const part = parts[i];
|
|
652
|
+
if (!part || part === '__proto__' || part === 'constructor' || part === 'prototype') {
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const arrayMatch = part.match(/^([^[]+)\[(\d+)\]$/);
|
|
656
|
+
if (arrayMatch) {
|
|
657
|
+
const name = arrayMatch[1];
|
|
658
|
+
if (name === '__proto__' || name === 'constructor' || name === 'prototype') {
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const index = parseInt(arrayMatch[2], 10);
|
|
662
|
+
if (!Array.isArray(current[name])) {
|
|
663
|
+
current[name] = [];
|
|
664
|
+
}
|
|
665
|
+
const arr = current[name];
|
|
666
|
+
if (!arr[index] || typeof arr[index] !== 'object') {
|
|
667
|
+
arr[index] = Object.create(null);
|
|
668
|
+
}
|
|
669
|
+
current = arr[index];
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
if (current[part] === undefined || current[part] === null || typeof current[part] !== 'object') {
|
|
673
|
+
current[part] = Object.create(null);
|
|
674
|
+
}
|
|
675
|
+
current = current[part];
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
const lastPart = parts[parts.length - 1];
|
|
679
|
+
if (lastPart === '__proto__' || lastPart === 'constructor' || lastPart === 'prototype') {
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const arrayMatch = lastPart.match(/^([^[]+)\[(\d+)\]$/);
|
|
683
|
+
if (arrayMatch) {
|
|
684
|
+
const name = arrayMatch[1];
|
|
685
|
+
if (name === '__proto__' || name === 'constructor' || name === 'prototype') {
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const index = parseInt(arrayMatch[2], 10);
|
|
689
|
+
if (!Array.isArray(current[name])) {
|
|
690
|
+
current[name] = [];
|
|
691
|
+
}
|
|
692
|
+
current[name][index] = value;
|
|
693
|
+
}
|
|
694
|
+
else {
|
|
695
|
+
current[lastPart] = value;
|
|
696
|
+
}
|
|
59
697
|
}
|
|
60
698
|
//# sourceMappingURL=InferProcessor.js.map
|