@outputai/core 0.16.1-next.a7e9891.0 → 0.16.1-next.b04d8e2.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/package.json +1 -1
- package/src/helpers/error_serializer.js +26 -5
- package/src/helpers/number.js +20 -0
- package/src/llm/index.d.ts +18 -0
- package/src/llm/utils/attributes/llm_generation.js +28 -0
- package/src/llm/utils/attributes/llm_generation_cost.js +99 -0
- package/src/llm/utils/attributes/llm_generation_usage.js +51 -0
- package/src/llm/utils/cost.js +15 -116
- package/src/llm/utils/metering.js +16 -7
- package/src/llm/utils/request_details.js +7 -0
- package/src/llm/utils/usage.js +13 -67
- package/src/worker/configs.js +40 -11
- package/src/worker/index.js +23 -5
- package/src/worker/shutdown.js +5 -11
- package/src/worker/temporal_logger.js +45 -12
- package/src/worker/worker_options.js +4 -4
package/package.json
CHANGED
|
@@ -50,8 +50,29 @@ const Marker = {
|
|
|
50
50
|
TruncatedString: '... [:v more characters omitted]'
|
|
51
51
|
};
|
|
52
52
|
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
/** Whether the code unit is the first half of a character that takes two code units, such as an emoji (a high surrogate) */
|
|
54
|
+
const isHighSurrogateChar = code => code >= 0xD800 && code <= 0xDBFF;
|
|
55
|
+
|
|
56
|
+
/** Whether the code unit is the second half of a character that takes two code units (a low surrogate) */
|
|
57
|
+
const isLowSurrogateChar = code => code >= 0xDC00 && code <= 0xDFFF;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Truncates a string to `max` code units and appends how many were omitted.
|
|
61
|
+
* The cut never splits a character in two. The content is otherwise kept as it is.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} v
|
|
64
|
+
* @param {number} [max]
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export const truncateString = ( v, max = MAX_STRING_LEN ) => {
|
|
68
|
+
if ( v.length <= max ) {
|
|
69
|
+
return v;
|
|
70
|
+
}
|
|
71
|
+
// A cut between the two halves of a character would keep only the first half, so that half is dropped too
|
|
72
|
+
const splitsCharacter = isHighSurrogateChar( v.charCodeAt( max - 1 ) ) && isLowSurrogateChar( v.charCodeAt( max ) );
|
|
73
|
+
const keepLength = max - ( splitsCharacter ? 1 : 0 );
|
|
74
|
+
return v.slice( 0, keepLength ) + Marker.TruncatedString.replace( ':v', v.length - keepLength );
|
|
75
|
+
};
|
|
55
76
|
|
|
56
77
|
export const truncateArray = ( v, max = MAX_ARRAY_SIZE ) =>
|
|
57
78
|
v.length <= max ? v : v.slice( 0, max ).concat( Marker.TruncatedArray.replace( ':v', v.length - max ) );
|
|
@@ -138,7 +159,7 @@ const serializeValue = ( target, options, state = { depth: 0, seen: new GlobalCo
|
|
|
138
159
|
}
|
|
139
160
|
|
|
140
161
|
if ( target instanceof RegExp ) {
|
|
141
|
-
return target.toString();
|
|
162
|
+
return truncateString( target.toString() );
|
|
142
163
|
}
|
|
143
164
|
|
|
144
165
|
if ( typeof target === 'bigint' ) {
|
|
@@ -150,13 +171,13 @@ const serializeValue = ( target, options, state = { depth: 0, seen: new GlobalCo
|
|
|
150
171
|
}
|
|
151
172
|
|
|
152
173
|
if ( typeof target === 'function' ) {
|
|
153
|
-
return `[Function: ${target.name || '(anonymous)'}]`;
|
|
174
|
+
return `[Function: ${truncateString( String( target.name || '(anonymous)' ) )}]`;
|
|
154
175
|
}
|
|
155
176
|
|
|
156
177
|
// Buffers, typed arrays, and raw ArrayBuffers
|
|
157
178
|
if ( ArrayBuffer.isView( target ) || target instanceof ArrayBuffer ) {
|
|
158
179
|
const sizeKey = target instanceof ArrayBuffer || target instanceof DataView ? 'byteLength' : 'length';
|
|
159
|
-
return `${target.constructor.name}(${target[sizeKey]})`;
|
|
180
|
+
return `${truncateString( String( target.constructor.name ) )}(${target[sizeKey]})`;
|
|
160
181
|
}
|
|
161
182
|
|
|
162
183
|
if ( typeof target === 'string' ) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns true if the value is a finite number greater than or equal to zero.
|
|
3
|
+
* @param {unknown} v
|
|
4
|
+
* @returns {boolean}
|
|
5
|
+
*/
|
|
6
|
+
export const isNonNegativeNumber = v => Number.isFinite( v ) && v >= 0;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Returns true if the value is a safe integer greater than or equal to zero.
|
|
10
|
+
* @param {unknown} v
|
|
11
|
+
* @returns {boolean}
|
|
12
|
+
*/
|
|
13
|
+
export const isNonNegativeInteger = v => Number.isSafeInteger( v ) && v >= 0;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Sums the non-negative safe integers among the values, ignoring all others.
|
|
17
|
+
* @param {...unknown} values
|
|
18
|
+
* @returns {number}
|
|
19
|
+
*/
|
|
20
|
+
export const safeSum = ( ...values ) => values.filter( isNonNegativeInteger ).reduce( ( t, v ) => t + v, 0 );
|
package/src/llm/index.d.ts
CHANGED
|
@@ -363,11 +363,25 @@ export interface LLMGenerationUsageItem {
|
|
|
363
363
|
amount: number;
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
+
/** Provider requests behind one LLM generation. */
|
|
367
|
+
export interface LLMRequestDetails {
|
|
368
|
+
/** Provider request ID of every request that exposed one, in request order. Empty when the provider exposes none. */
|
|
369
|
+
ids: string[];
|
|
370
|
+
/** Number of provider requests, one per step. Can be greater than `ids.length`. */
|
|
371
|
+
count: number;
|
|
372
|
+
/** Milliseconds from the start of the call until billing starts, rounded up. */
|
|
373
|
+
duration: number;
|
|
374
|
+
}
|
|
375
|
+
|
|
366
376
|
/** Normalized LLM token usage trace attribute. */
|
|
367
377
|
export interface LLMGenerationUsage extends BaseAttribute {
|
|
368
378
|
type: 'llm:generation:usage';
|
|
369
379
|
providerId: string;
|
|
370
380
|
modelId: string;
|
|
381
|
+
/** Name of the prompt that made the call. Absent on usage recorded before this field existed. */
|
|
382
|
+
promptName?: string;
|
|
383
|
+
/** Absent on usage recorded before this field existed. */
|
|
384
|
+
requestDetails?: LLMRequestDetails;
|
|
371
385
|
input: number | null;
|
|
372
386
|
output: number | null;
|
|
373
387
|
total: number | null;
|
|
@@ -422,6 +436,10 @@ export interface LLMGenerationCost extends BaseAttribute {
|
|
|
422
436
|
type: 'llm:generation:cost';
|
|
423
437
|
providerId: string;
|
|
424
438
|
modelId: string;
|
|
439
|
+
/** Name of the prompt that made the call. Absent on costs recorded before this field existed. */
|
|
440
|
+
promptName?: string;
|
|
441
|
+
/** Absent on costs recorded before this field existed. */
|
|
442
|
+
requestDetails?: LLMRequestDetails;
|
|
425
443
|
input: number | null;
|
|
426
444
|
output: number | null;
|
|
427
445
|
tools: number | null;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { BaseAttribute } from '#trace_attribute';
|
|
2
|
+
|
|
3
|
+
export class LLMRequestDetails {
|
|
4
|
+
ids;
|
|
5
|
+
count;
|
|
6
|
+
duration;
|
|
7
|
+
|
|
8
|
+
constructor( ids, count, duration ) {
|
|
9
|
+
this.ids = ids;
|
|
10
|
+
this.count = count;
|
|
11
|
+
this.duration = duration;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class LLMGeneration extends BaseAttribute {
|
|
16
|
+
modelId;
|
|
17
|
+
providerId;
|
|
18
|
+
promptName;
|
|
19
|
+
requestDetails;
|
|
20
|
+
|
|
21
|
+
constructor( type, modelId, providerId, promptName, requestDetails ) {
|
|
22
|
+
super( type );
|
|
23
|
+
this.modelId = modelId;
|
|
24
|
+
this.providerId = providerId;
|
|
25
|
+
this.promptName = promptName;
|
|
26
|
+
this.requestDetails = requestDetails;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Freshness } from '../models_pricing.js';
|
|
2
|
+
import { LLMGenerationUsage, LLMGenerationUsageItem } from './llm_generation_usage.js';
|
|
3
|
+
import Decimal from 'decimal.js';
|
|
4
|
+
import { isNonNegativeNumber } from '#helpers/number';
|
|
5
|
+
import { LLMGeneration } from './llm_generation.js';
|
|
6
|
+
|
|
7
|
+
export class LLMGenerationCostItem {
|
|
8
|
+
static Status = Object.freeze( {
|
|
9
|
+
OK: 'ok',
|
|
10
|
+
FALLBACK: 'fallback',
|
|
11
|
+
UNCERTAIN: 'uncertain',
|
|
12
|
+
MISSING: 'missing'
|
|
13
|
+
} );
|
|
14
|
+
|
|
15
|
+
group;
|
|
16
|
+
label;
|
|
17
|
+
amount;
|
|
18
|
+
ppm;
|
|
19
|
+
total;
|
|
20
|
+
status;
|
|
21
|
+
|
|
22
|
+
constructor( group, label, amount, ppm, total, status, tier = undefined ) {
|
|
23
|
+
this.group = group;
|
|
24
|
+
this.label = label;
|
|
25
|
+
this.amount = amount;
|
|
26
|
+
this.ppm = ppm;
|
|
27
|
+
this.total = total;
|
|
28
|
+
this.status = status;
|
|
29
|
+
if ( tier ) {
|
|
30
|
+
this.tier = { type: tier.type, size: tier.size };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
get key() {
|
|
35
|
+
return JSON.stringify( [ this.group, this.label, this.ppm, this.status, this.tier?.type, this.tier?.size ] );
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class LLMGenerationCost extends LLMGeneration {
|
|
40
|
+
static TYPE = 'llm:generation:cost';
|
|
41
|
+
static Status = Object.freeze( {
|
|
42
|
+
PRECISE: 'precise',
|
|
43
|
+
IMPRECISE: 'imprecise',
|
|
44
|
+
INCOMPLETE: 'incomplete'
|
|
45
|
+
} );
|
|
46
|
+
|
|
47
|
+
input = null;
|
|
48
|
+
output = null;
|
|
49
|
+
tools = null;
|
|
50
|
+
total = null;
|
|
51
|
+
status = LLMGenerationCost.Status.INCOMPLETE;
|
|
52
|
+
pricingFreshness = null;
|
|
53
|
+
items = [];
|
|
54
|
+
|
|
55
|
+
constructor( modelId, providerId, promptName, requestDetails, items, usageStatus, pricingFreshness ) {
|
|
56
|
+
super( LLMGenerationCost.TYPE, modelId, providerId, promptName, requestDetails );
|
|
57
|
+
|
|
58
|
+
// group items with the same key, summing amount
|
|
59
|
+
this.items = Map.groupBy( items, e => e.key )
|
|
60
|
+
.values()
|
|
61
|
+
.toArray()
|
|
62
|
+
.map( items => {
|
|
63
|
+
if ( items.length === 1 ) {
|
|
64
|
+
return items[0];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const { group, label, ppm, status, tier } = items[0];
|
|
68
|
+
const amount = items.reduce( ( sum, item ) => sum + item.amount, 0 );
|
|
69
|
+
const total = isNonNegativeNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
|
|
70
|
+
return new LLMGenerationCostItem( group, label, amount, ppm, total, status, tier );
|
|
71
|
+
} );
|
|
72
|
+
|
|
73
|
+
this.pricingFreshness = pricingFreshness;
|
|
74
|
+
|
|
75
|
+
const meaningfulItems = this.items.filter( v => v.amount > 0 );
|
|
76
|
+
const hasMissingItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.MISSING );
|
|
77
|
+
const hasFallbackItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.FALLBACK );
|
|
78
|
+
const hasUncertainItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.UNCERTAIN );
|
|
79
|
+
|
|
80
|
+
if ( hasMissingItems || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
|
|
81
|
+
this.status = LLMGenerationCost.Status.INCOMPLETE;
|
|
82
|
+
} else if ( hasFallbackItems || pricingFreshness === Freshness.SNAPSHOT || hasUncertainItems ) {
|
|
83
|
+
this.status = LLMGenerationCost.Status.IMPRECISE;
|
|
84
|
+
} else {
|
|
85
|
+
this.status = LLMGenerationCost.Status.PRECISE;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const sumGroup = group => {
|
|
89
|
+
const groupItems = this.items.filter( p => p.group === group && isNonNegativeNumber( p.total ) );
|
|
90
|
+
return groupItems.length > 0 ? groupItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
|
|
91
|
+
};
|
|
92
|
+
this.input = sumGroup( LLMGenerationUsageItem.Group.INPUT );
|
|
93
|
+
this.output = sumGroup( LLMGenerationUsageItem.Group.OUTPUT );
|
|
94
|
+
this.tools = sumGroup( LLMGenerationUsageItem.Group.TOOLS );
|
|
95
|
+
if ( isNonNegativeNumber( this.input ) || isNonNegativeNumber( this.output ) || isNonNegativeNumber( this.tools ) ) {
|
|
96
|
+
this.total = Decimal( this.input ?? 0 ).add( this.output ?? 0 ).add( this.tools ?? 0 ).toNumber();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import Decimal from 'decimal.js';
|
|
2
|
+
import { isNonNegativeInteger } from '#helpers/number';
|
|
3
|
+
import { LLMGeneration } from './llm_generation.js';
|
|
4
|
+
|
|
5
|
+
export class LLMGenerationUsageItem {
|
|
6
|
+
static Group = { INPUT: 'input', OUTPUT: 'output', TOOLS: 'tools' };
|
|
7
|
+
|
|
8
|
+
group;
|
|
9
|
+
label;
|
|
10
|
+
amount;
|
|
11
|
+
|
|
12
|
+
constructor( group, label, amount ) {
|
|
13
|
+
this.group = group;
|
|
14
|
+
this.label = label;
|
|
15
|
+
this.amount = amount;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class LLMGenerationUsage extends LLMGeneration {
|
|
20
|
+
static TYPE = 'llm:generation:usage';
|
|
21
|
+
|
|
22
|
+
static Status = Object.freeze( {
|
|
23
|
+
COMPLETE: 'complete',
|
|
24
|
+
INCOMPLETE: 'incomplete'
|
|
25
|
+
} );
|
|
26
|
+
|
|
27
|
+
status = LLMGenerationUsage.Status.INCOMPLETE;
|
|
28
|
+
input = null;
|
|
29
|
+
output = null;
|
|
30
|
+
total = null;
|
|
31
|
+
items = [];
|
|
32
|
+
|
|
33
|
+
constructor( modelId, providerId, promptName, requestDetails, items ) {
|
|
34
|
+
super( LLMGenerationUsage.TYPE, modelId, providerId, promptName, requestDetails );
|
|
35
|
+
|
|
36
|
+
this.items = items;
|
|
37
|
+
const inputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.INPUT );
|
|
38
|
+
if ( inputItems.length > 0 ) {
|
|
39
|
+
this.input = inputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
40
|
+
}
|
|
41
|
+
const outputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.OUTPUT );
|
|
42
|
+
if ( outputItems.length > 0 ) {
|
|
43
|
+
this.output = outputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if ( isNonNegativeInteger( this.input ) || isNonNegativeInteger( this.output ) ) {
|
|
47
|
+
this.total = ( this.input ?? 0 ) + ( this.output ?? 0 );
|
|
48
|
+
}
|
|
49
|
+
this.status = LLMGenerationUsage.Status[isNonNegativeInteger( this.input ) && isNonNegativeInteger( this.output ) ? 'COMPLETE' : 'INCOMPLETE'];
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/llm/utils/cost.js
CHANGED
|
@@ -1,117 +1,18 @@
|
|
|
1
|
-
import { fetchModelsPricing
|
|
2
|
-
import {
|
|
3
|
-
import { LLMGenerationUsage, LLMGenerationUsageItem } from './usage.js';
|
|
1
|
+
import { fetchModelsPricing } from './models_pricing.js';
|
|
2
|
+
import { LLMGenerationUsage, LLMGenerationUsageItem } from './attributes/llm_generation_usage.js';
|
|
4
3
|
import { resolveWebSearchPpm } from './web_search.js';
|
|
5
4
|
import { Logger } from '#runtime_logger';
|
|
5
|
+
import { LLMGenerationCost, LLMGenerationCostItem } from './attributes/llm_generation_cost.js';
|
|
6
6
|
import Decimal from 'decimal.js';
|
|
7
|
-
|
|
8
|
-
// Checks whether a pricing value can be used in cost calculations.
|
|
9
|
-
const isValidNumber = v => Number.isFinite( v ) && v >= 0;
|
|
10
|
-
|
|
11
|
-
export class LLMGenerationCostItem {
|
|
12
|
-
static Status = Object.freeze( {
|
|
13
|
-
OK: 'ok',
|
|
14
|
-
FALLBACK: 'fallback',
|
|
15
|
-
UNCERTAIN: 'uncertain',
|
|
16
|
-
MISSING: 'missing'
|
|
17
|
-
} );
|
|
18
|
-
|
|
19
|
-
group;
|
|
20
|
-
label;
|
|
21
|
-
amount;
|
|
22
|
-
ppm;
|
|
23
|
-
total;
|
|
24
|
-
status;
|
|
25
|
-
|
|
26
|
-
constructor( group, label, amount, ppm, total, status, tier = undefined ) {
|
|
27
|
-
this.group = group;
|
|
28
|
-
this.label = label;
|
|
29
|
-
this.amount = amount;
|
|
30
|
-
this.ppm = ppm;
|
|
31
|
-
this.total = total;
|
|
32
|
-
this.status = status;
|
|
33
|
-
if ( tier ) {
|
|
34
|
-
this.tier = { type: tier.type, size: tier.size };
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
get key() {
|
|
39
|
-
return JSON.stringify( [ this.group, this.label, this.ppm, this.status, this.tier?.type, this.tier?.size ] );
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export class LLMGenerationCost extends BaseAttribute {
|
|
44
|
-
static TYPE = 'llm:generation:cost';
|
|
45
|
-
static Status = Object.freeze( {
|
|
46
|
-
PRECISE: 'precise',
|
|
47
|
-
IMPRECISE: 'imprecise',
|
|
48
|
-
INCOMPLETE: 'incomplete'
|
|
49
|
-
} );
|
|
50
|
-
providerId;
|
|
51
|
-
modelId;
|
|
52
|
-
input = null;
|
|
53
|
-
output = null;
|
|
54
|
-
tools = null;
|
|
55
|
-
total = null;
|
|
56
|
-
status = LLMGenerationCost.Status.INCOMPLETE;
|
|
57
|
-
pricingFreshness = null;
|
|
58
|
-
items = [];
|
|
59
|
-
|
|
60
|
-
constructor( modelId, providerId, items, usageStatus, pricingFreshness ) {
|
|
61
|
-
super( LLMGenerationCost.TYPE );
|
|
62
|
-
this.modelId = modelId;
|
|
63
|
-
this.providerId = providerId;
|
|
64
|
-
|
|
65
|
-
// group items with the same key, summing amount
|
|
66
|
-
this.items = Map.groupBy( items, e => e.key )
|
|
67
|
-
.values()
|
|
68
|
-
.toArray()
|
|
69
|
-
.map( items => {
|
|
70
|
-
if ( items.length === 1 ) {
|
|
71
|
-
return items[0];
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const { group, label, ppm, status, tier } = items[0];
|
|
75
|
-
const amount = items.reduce( ( sum, item ) => sum + item.amount, 0 );
|
|
76
|
-
const total = isValidNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
|
|
77
|
-
return new LLMGenerationCostItem( group, label, amount, ppm, total, status, tier );
|
|
78
|
-
} );
|
|
79
|
-
|
|
80
|
-
this.pricingFreshness = pricingFreshness;
|
|
81
|
-
|
|
82
|
-
const meaningfulItems = this.items.filter( v => v.amount > 0 );
|
|
83
|
-
const hasMissingItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.MISSING );
|
|
84
|
-
const hasFallbackItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.FALLBACK );
|
|
85
|
-
const hasUncertainItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.UNCERTAIN );
|
|
86
|
-
|
|
87
|
-
if ( hasMissingItems || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
|
|
88
|
-
this.status = LLMGenerationCost.Status.INCOMPLETE;
|
|
89
|
-
} else if ( hasFallbackItems || pricingFreshness === Freshness.SNAPSHOT || hasUncertainItems ) {
|
|
90
|
-
this.status = LLMGenerationCost.Status.IMPRECISE;
|
|
91
|
-
} else {
|
|
92
|
-
this.status = LLMGenerationCost.Status.PRECISE;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const sumGroup = group => {
|
|
96
|
-
const groupItems = this.items.filter( p => p.group === group && isValidNumber( p.total ) );
|
|
97
|
-
return groupItems.length > 0 ? groupItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
|
|
98
|
-
};
|
|
99
|
-
this.input = sumGroup( LLMGenerationUsageItem.Group.INPUT );
|
|
100
|
-
this.output = sumGroup( LLMGenerationUsageItem.Group.OUTPUT );
|
|
101
|
-
this.tools = sumGroup( LLMGenerationUsageItem.Group.TOOLS );
|
|
102
|
-
if ( isValidNumber( this.input ) || isValidNumber( this.output ) || isValidNumber( this.tools ) ) {
|
|
103
|
-
this.total = Decimal( this.input ?? 0 ).add( this.output ?? 0 ).add( this.tools ?? 0 ).toNumber();
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
7
|
+
import { isNonNegativeNumber } from '#helpers/number';
|
|
107
8
|
|
|
108
9
|
// Selects the exact rate, then the first available fallback rate.
|
|
109
10
|
const resolveValue = values => {
|
|
110
|
-
if (
|
|
11
|
+
if ( isNonNegativeNumber( values[0] ) ) {
|
|
111
12
|
return { ppm: values[0], status: LLMGenerationCostItem.Status.OK };
|
|
112
13
|
}
|
|
113
|
-
const fallback = values.slice( 1 ).find(
|
|
114
|
-
if (
|
|
14
|
+
const fallback = values.slice( 1 ).find( isNonNegativeNumber );
|
|
15
|
+
if ( isNonNegativeNumber( fallback ) ) {
|
|
115
16
|
return { ppm: fallback, status: LLMGenerationCostItem.Status.FALLBACK };
|
|
116
17
|
}
|
|
117
18
|
return { ppm: null, status: LLMGenerationCostItem.Status.MISSING };
|
|
@@ -127,11 +28,9 @@ const resolvePrice = ( { providerId, group, label, pricing, isReasoning } ) => {
|
|
|
127
28
|
return resolveValue( [] );
|
|
128
29
|
}
|
|
129
30
|
if ( group === LLMGenerationUsageItem.Group.OUTPUT ) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
return resolveValue( values );
|
|
31
|
+
// Reasoning is billed as output unless the catalog lists a separate rate, so using the output rate is not a fallback
|
|
32
|
+
const rate = label === 'reasoning' && isNonNegativeNumber( pricing.reasoning ) ? pricing.reasoning : pricing.output;
|
|
33
|
+
return resolveValue( [ rate ] );
|
|
135
34
|
}
|
|
136
35
|
|
|
137
36
|
const values = [ pricing.input ];
|
|
@@ -146,7 +45,7 @@ const resolvePrice = ( { providerId, group, label, pricing, isReasoning } ) => {
|
|
|
146
45
|
// Finds the highest context threshold crossed by this request's input.
|
|
147
46
|
const resolvePricingTier = ( modelPricing, input ) => {
|
|
148
47
|
// DESC sort by size
|
|
149
|
-
const supportedTiers = modelPricing.cost.tiers.filter( t => t?.tier?.type === 'context' &&
|
|
48
|
+
const supportedTiers = modelPricing.cost.tiers.filter( t => t?.tier?.type === 'context' && isNonNegativeNumber( t.tier.size ) );
|
|
150
49
|
const hasUnsupported = supportedTiers.length !== modelPricing.cost.tiers.length;
|
|
151
50
|
|
|
152
51
|
const sortedTiers = supportedTiers.toSorted( ( t1, t2 ) => t2.tier.size - t1.tier.size );
|
|
@@ -160,7 +59,7 @@ const calculateCostItems = ( { usage, pricing, isReasoning, uncertain } ) => {
|
|
|
160
59
|
const { providerId } = usage;
|
|
161
60
|
return usage.items.map( ( { group, label, amount } ) => {
|
|
162
61
|
const { ppm, status } = resolvePrice( { providerId, isReasoning, group, label, pricing } );
|
|
163
|
-
const total =
|
|
62
|
+
const total = isNonNegativeNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
|
|
164
63
|
|
|
165
64
|
const isTool = group === LLMGenerationUsageItem.Group.TOOLS;
|
|
166
65
|
const isCostOk = status === LLMGenerationCostItem.Status.OK;
|
|
@@ -198,7 +97,7 @@ const calculateTieredUsage = ( totalUsage, stepsUsage, modelPricing ) => {
|
|
|
198
97
|
|
|
199
98
|
return ( isMultiStep ? stepsUsage : [ totalUsage ] ).flatMap( usage => {
|
|
200
99
|
// output usage can't have tier billing
|
|
201
|
-
if ( !
|
|
100
|
+
if ( !isNonNegativeNumber( usage.input ) ) {
|
|
202
101
|
return calculateCostItems( { usage, pricing, isReasoning } );
|
|
203
102
|
}
|
|
204
103
|
|
|
@@ -244,7 +143,7 @@ export const calculateCosts = async ( usage, stepsUsage ) => {
|
|
|
244
143
|
Logger.warn( 'Tool call with no rate for model', { namespace: 'LLM', modelId, providerId, type: unrated.label } );
|
|
245
144
|
}
|
|
246
145
|
|
|
247
|
-
return new LLMGenerationCost( modelId, providerId, items, usage.status, pricingFreshness );
|
|
146
|
+
return new LLMGenerationCost( modelId, providerId, usage.promptName, usage.requestDetails, items, usage.status, pricingFreshness );
|
|
248
147
|
};
|
|
249
148
|
|
|
250
149
|
/**
|
|
@@ -263,5 +162,5 @@ export const calculateLegacyCosts = async usage => {
|
|
|
263
162
|
const modelPricing = models.get( `${providerId}/${modelId}` );
|
|
264
163
|
const items = calculateStandardUsage( usage, modelPricing );
|
|
265
164
|
|
|
266
|
-
return new LLMGenerationCost( modelId, providerId, items, usage.status, pricingFreshness );
|
|
165
|
+
return new LLMGenerationCost( modelId, providerId, null, null, items, usage.status, pricingFreshness );
|
|
267
166
|
};
|
|
@@ -4,6 +4,7 @@ import { stepEventBus } from '#bus';
|
|
|
4
4
|
import { addEventActionWithContext, EventAction } from '#tracing';
|
|
5
5
|
import { Logger } from '#runtime_logger';
|
|
6
6
|
import { convertCostToLegacy } from './legacy_cost_attribute.js';
|
|
7
|
+
import { parseRequestDetails } from './request_details.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Collects the usage of a single LLM call and bills it once.
|
|
@@ -16,6 +17,7 @@ import { convertCostToLegacy } from './legacy_cost_attribute.js';
|
|
|
16
17
|
export class Metering {
|
|
17
18
|
#recordedSteps = [];
|
|
18
19
|
#billed = false;
|
|
20
|
+
#startedAt;
|
|
19
21
|
#prompt;
|
|
20
22
|
#traceId;
|
|
21
23
|
#toolIdsByName;
|
|
@@ -25,14 +27,14 @@ export class Metering {
|
|
|
25
27
|
legacy: null
|
|
26
28
|
};
|
|
27
29
|
|
|
28
|
-
async #createAttributes( { usage, steps } ) {
|
|
29
|
-
const
|
|
30
|
-
const stepsUsage = steps.map( step => parseLLMUsage( {
|
|
30
|
+
async #createAttributes( { usage, steps, requestDetails } ) {
|
|
31
|
+
const baseUsageArgs = {
|
|
31
32
|
prompt: this.#prompt,
|
|
32
|
-
usage: step.usage,
|
|
33
|
-
steps: [ step ],
|
|
34
33
|
toolIdsByName: this.#toolIdsByName
|
|
35
|
-
}
|
|
34
|
+
};
|
|
35
|
+
// Only the call-level usage carries the request details; the per-step usages feed the tiered cost items only
|
|
36
|
+
const totalUsage = parseLLMUsage( { ...baseUsageArgs, usage, steps, requestDetails } );
|
|
37
|
+
const stepsUsage = steps.map( step => parseLLMUsage( { ...baseUsageArgs, usage: step.usage, steps: [ step ] } ) );
|
|
36
38
|
|
|
37
39
|
this.#attributes.usage = totalUsage;
|
|
38
40
|
if ( this.#attributes.usage ) {
|
|
@@ -77,6 +79,7 @@ export class Metering {
|
|
|
77
79
|
this.#traceId = traceId;
|
|
78
80
|
this.#prompt = prompt;
|
|
79
81
|
this.#toolIdsByName = toolIdsByName;
|
|
82
|
+
this.#startedAt = performance.now();
|
|
80
83
|
}
|
|
81
84
|
|
|
82
85
|
/**
|
|
@@ -108,6 +111,7 @@ export class Metering {
|
|
|
108
111
|
}
|
|
109
112
|
|
|
110
113
|
try {
|
|
114
|
+
const duration = Math.ceil( performance.now() - this.#startedAt );
|
|
111
115
|
const responseSteps = response?.steps;
|
|
112
116
|
const steps = Array.isArray( responseSteps ) && responseSteps.length > 0 ? responseSteps : this.#recordedSteps;
|
|
113
117
|
const usage = response?.usage;
|
|
@@ -116,9 +120,14 @@ export class Metering {
|
|
|
116
120
|
return;
|
|
117
121
|
}
|
|
118
122
|
|
|
123
|
+
const requestsHeaders = steps.length > 0 ?
|
|
124
|
+
steps.map( step => step?.response?.headers ) :
|
|
125
|
+
( response?.responses ?? [] ).map( r => r?.headers );
|
|
126
|
+
const requestDetails = parseRequestDetails( { requestsHeaders, duration } );
|
|
127
|
+
|
|
119
128
|
this.#billed = true;
|
|
120
129
|
|
|
121
|
-
await this.#createAttributes( { usage, steps } );
|
|
130
|
+
await this.#createAttributes( { usage, steps, requestDetails } );
|
|
122
131
|
this.#attachAttributes();
|
|
123
132
|
this.#emitEvents();
|
|
124
133
|
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { LLMRequestDetails } from './attributes/llm_generation.js';
|
|
2
|
+
|
|
3
|
+
export const parseRequestDetails = ( { requestsHeaders, duration } ) => {
|
|
4
|
+
const ids = requestsHeaders.map( h => h?.['request-id'] ?? h?.['x-request-id'] ).filter( Boolean );
|
|
5
|
+
|
|
6
|
+
return new LLMRequestDetails( ids, requestsHeaders.length, duration );
|
|
7
|
+
};
|
package/src/llm/utils/usage.js
CHANGED
|
@@ -1,62 +1,7 @@
|
|
|
1
|
-
import Decimal from 'decimal.js';
|
|
2
|
-
import { BaseAttribute } from '#trace_attribute';
|
|
3
1
|
import { extractUsageFromSteps } from './usage_tools.js';
|
|
4
2
|
import { parseWebSearchUsage } from './web_search.js';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const safeSum = ( ...values ) => values.filter( isValidTokenCount ).reduce( ( t, v ) => t + v, 0 );
|
|
9
|
-
|
|
10
|
-
export class LLMGenerationUsageItem {
|
|
11
|
-
static Group = { INPUT: 'input', OUTPUT: 'output', TOOLS: 'tools' };
|
|
12
|
-
|
|
13
|
-
group;
|
|
14
|
-
label;
|
|
15
|
-
amount;
|
|
16
|
-
|
|
17
|
-
constructor( group, label, amount ) {
|
|
18
|
-
this.group = group;
|
|
19
|
-
this.label = label;
|
|
20
|
-
this.amount = amount;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export class LLMGenerationUsage extends BaseAttribute {
|
|
25
|
-
static TYPE = 'llm:generation:usage';
|
|
26
|
-
|
|
27
|
-
static Status = Object.freeze( {
|
|
28
|
-
COMPLETE: 'complete',
|
|
29
|
-
INCOMPLETE: 'incomplete'
|
|
30
|
-
} );
|
|
31
|
-
|
|
32
|
-
providerId;
|
|
33
|
-
modelId;
|
|
34
|
-
status = LLMGenerationUsage.Status.INCOMPLETE;
|
|
35
|
-
input = null;
|
|
36
|
-
output = null;
|
|
37
|
-
total = null;
|
|
38
|
-
items = [];
|
|
39
|
-
|
|
40
|
-
constructor( modelId, providerId, items ) {
|
|
41
|
-
super( LLMGenerationUsage.TYPE );
|
|
42
|
-
this.providerId = providerId;
|
|
43
|
-
this.modelId = modelId;
|
|
44
|
-
this.items = items;
|
|
45
|
-
const inputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.INPUT );
|
|
46
|
-
if ( inputItems.length > 0 ) {
|
|
47
|
-
this.input = inputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
48
|
-
}
|
|
49
|
-
const outputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.OUTPUT );
|
|
50
|
-
if ( outputItems.length > 0 ) {
|
|
51
|
-
this.output = outputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
if ( isValidTokenCount( this.input ) || isValidTokenCount( this.output ) ) {
|
|
55
|
-
this.total = ( this.input ?? 0 ) + ( this.output ?? 0 );
|
|
56
|
-
}
|
|
57
|
-
this.status = LLMGenerationUsage.Status[isValidTokenCount( this.input ) && isValidTokenCount( this.output ) ? 'COMPLETE' : 'INCOMPLETE'];
|
|
58
|
-
}
|
|
59
|
-
}
|
|
3
|
+
import { LLMGenerationUsage, LLMGenerationUsageItem } from './attributes/llm_generation_usage.js';
|
|
4
|
+
import { isNonNegativeInteger, safeSum } from '#helpers/number';
|
|
60
5
|
|
|
61
6
|
/**
|
|
62
7
|
* Returns usage from response or reconstruct it from steps.
|
|
@@ -65,7 +10,7 @@ export class LLMGenerationUsage extends BaseAttribute {
|
|
|
65
10
|
* every token count undefined, and the steps are then the only record of what was already spent.
|
|
66
11
|
*/
|
|
67
12
|
const resolveUsage = ( { usage, steps } ) => {
|
|
68
|
-
if ( usage && (
|
|
13
|
+
if ( usage && ( isNonNegativeInteger( usage.inputTokens ) || isNonNegativeInteger( usage.outputTokens ) ) ) {
|
|
69
14
|
return usage;
|
|
70
15
|
}
|
|
71
16
|
return Array.isArray( steps ) && steps.length > 0 ? extractUsageFromSteps( steps ) : null;
|
|
@@ -83,10 +28,11 @@ const resolveUsage = ( { usage, steps } ) => {
|
|
|
83
28
|
* @param {object} [args.usage] - AI SDK response usage
|
|
84
29
|
* @param {object} [args.steps] - AI SDK response steps
|
|
85
30
|
* @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
|
|
31
|
+
* @param {LLMRequestDetails} [args.requestDetails] - Request ids, count and duration of the whole call
|
|
86
32
|
*
|
|
87
33
|
* @returns {LLMGenerationUsage | null} LLM generation usage with input, output, total and detailed breakdown
|
|
88
34
|
*/
|
|
89
|
-
export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], toolIdsByName = null } ) => {
|
|
35
|
+
export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], toolIdsByName = null, requestDetails = null } ) => {
|
|
90
36
|
const usage = resolveUsage( { usage: usageArg, steps } );
|
|
91
37
|
if ( !usage ) {
|
|
92
38
|
return null;
|
|
@@ -98,19 +44,19 @@ export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], too
|
|
|
98
44
|
|
|
99
45
|
const items = [];
|
|
100
46
|
|
|
101
|
-
if (
|
|
47
|
+
if ( isNonNegativeInteger( inputTokens ) ) {
|
|
102
48
|
// the sum of the components must be equal to the tokens
|
|
103
49
|
const useDetails = inputTokens > 0 && safeSum( noCacheTokens, cacheReadTokens, cacheWriteTokens ) === inputTokens;
|
|
104
50
|
const group = LLMGenerationUsageItem.Group.INPUT;
|
|
105
51
|
|
|
106
52
|
if ( useDetails ) {
|
|
107
|
-
if (
|
|
53
|
+
if ( isNonNegativeInteger( noCacheTokens ) ) {
|
|
108
54
|
items.push( new LLMGenerationUsageItem( group, 'no_cache', noCacheTokens ) );
|
|
109
55
|
}
|
|
110
|
-
if (
|
|
56
|
+
if ( isNonNegativeInteger( cacheReadTokens ) ) {
|
|
111
57
|
items.push( new LLMGenerationUsageItem( group, 'cache_read', cacheReadTokens ) );
|
|
112
58
|
}
|
|
113
|
-
if (
|
|
59
|
+
if ( isNonNegativeInteger( cacheWriteTokens ) ) {
|
|
114
60
|
items.push( new LLMGenerationUsageItem( group, 'cache_write', cacheWriteTokens ) );
|
|
115
61
|
}
|
|
116
62
|
} else {
|
|
@@ -118,16 +64,16 @@ export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], too
|
|
|
118
64
|
}
|
|
119
65
|
}
|
|
120
66
|
|
|
121
|
-
if (
|
|
67
|
+
if ( isNonNegativeInteger( outputTokens ) ) {
|
|
122
68
|
// the sum of the components must be equal to the tokens
|
|
123
69
|
const useDetails = outputTokens > 0 && safeSum( textTokens, reasoningTokens ) === outputTokens;
|
|
124
70
|
const group = LLMGenerationUsageItem.Group.OUTPUT;
|
|
125
71
|
|
|
126
72
|
if ( useDetails ) {
|
|
127
|
-
if (
|
|
73
|
+
if ( isNonNegativeInteger( textTokens ) ) {
|
|
128
74
|
items.push( new LLMGenerationUsageItem( group, 'text', textTokens ) );
|
|
129
75
|
}
|
|
130
|
-
if (
|
|
76
|
+
if ( isNonNegativeInteger( reasoningTokens ) ) {
|
|
131
77
|
items.push( new LLMGenerationUsageItem( group, 'reasoning', reasoningTokens ) );
|
|
132
78
|
}
|
|
133
79
|
} else {
|
|
@@ -151,5 +97,5 @@ export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], too
|
|
|
151
97
|
return null;
|
|
152
98
|
}
|
|
153
99
|
|
|
154
|
-
return new LLMGenerationUsage( modelId, providerId, items );
|
|
100
|
+
return new LLMGenerationUsage( modelId, providerId, prompt.name, requestDetails, items );
|
|
155
101
|
};
|
package/src/worker/configs.js
CHANGED
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
import * as z from 'zod';
|
|
2
2
|
import { isStringboolTrue } from '#helpers/string';
|
|
3
|
+
import { createChildLogger } from '#logger';
|
|
3
4
|
import { workerTunerEnvSchema } from './configs_tuner_schema.js';
|
|
4
5
|
|
|
6
|
+
const log = createChildLogger( 'Worker' );
|
|
7
|
+
|
|
5
8
|
class InvalidEnvVarsErrors extends Error { }
|
|
6
9
|
|
|
7
10
|
const coalesceEmptyString = v => v === '' ? undefined : v;
|
|
8
11
|
|
|
9
|
-
const
|
|
12
|
+
const durationUnitsMs = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
13
|
+
|
|
14
|
+
// Plain integer ms, or `<n>(ms|s|m|h|d)` where n may be decimal
|
|
15
|
+
const durationPattern = /^(?:(?<plainMs>\d+)|(?<amount>\d+(?:\.\d+)?)\s?(?<unit>ms|s|m|h|d))$/i;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Converts a duration matching `durationPattern` into milliseconds.
|
|
19
|
+
* @param {string} value
|
|
20
|
+
* @returns {number}
|
|
21
|
+
*/
|
|
22
|
+
const convertDurationToMs = value => {
|
|
23
|
+
const { plainMs, amount, unit } = value.match( durationPattern ).groups;
|
|
24
|
+
return plainMs === undefined ? Math.round( Number( amount ) * durationUnitsMs[unit.toLowerCase()] ) : Number( plainMs );
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const durationMsSchema = z.preprocess(
|
|
10
28
|
coalesceEmptyString,
|
|
11
|
-
z.string()
|
|
12
|
-
.regex( /^\d+$|^\d+(\.\d+)?\s?(ms|s|m|h|d)$/i )
|
|
13
|
-
.optional()
|
|
29
|
+
z.string().regex( durationPattern ).transform( convertDurationToMs ).optional()
|
|
14
30
|
);
|
|
15
31
|
|
|
16
32
|
const envVarSchema = z.object( {
|
|
@@ -54,13 +70,18 @@ const envVarSchema = z.object( {
|
|
|
54
70
|
OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 2 * 60 * 1000 ) ), // 2min
|
|
55
71
|
// Whether to send activity heartbeats (enabled by default)
|
|
56
72
|
OUTPUT_ACTIVITY_HEARTBEAT_ENABLED: z.transform( v => v === undefined ? true : isStringboolTrue( v ) ),
|
|
57
|
-
// Set temporal worker shutdown force time.
|
|
58
|
-
//
|
|
59
|
-
TEMPORAL_SHUTDOWN_FORCE_TIME:
|
|
73
|
+
// Set temporal worker shutdown force time. Worst case shutdown is force time + OUTPUT_HOOK_FLUSH_TIMEOUT_MS,
|
|
74
|
+
// which must fit the window the platform allows before SIGKILL (30s by default on Render and Kubernetes).
|
|
75
|
+
TEMPORAL_SHUTDOWN_FORCE_TIME: durationMsSchema.default( 20_000 ), // 20s
|
|
60
76
|
// Set temporal worker shutdown grace time, when in-flight activities are asked to cancel
|
|
61
|
-
TEMPORAL_SHUTDOWN_GRACE_TIME:
|
|
77
|
+
TEMPORAL_SHUTDOWN_GRACE_TIME: durationMsSchema.default( 15_000 ), // 15s
|
|
62
78
|
// How long the worker awaits pending hook callbacks once the drain is over, before exiting anyway
|
|
63
|
-
OUTPUT_HOOK_FLUSH_TIMEOUT_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default(
|
|
79
|
+
OUTPUT_HOOK_FLUSH_TIMEOUT_MS: z.preprocess( coalesceEmptyString, z.coerce.number().int().positive().default( 5_000 ) ), // 5s
|
|
80
|
+
// Verbosity of the Temporal SDK and Core logs. Takes Temporal levels, not Winston ones. Case-insensitive.
|
|
81
|
+
OUTPUT_TEMPORAL_LOG_LEVEL: z.preprocess(
|
|
82
|
+
v => coalesceEmptyString( v )?.toUpperCase(),
|
|
83
|
+
z.enum( [ 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR' ] ).default( 'INFO' )
|
|
84
|
+
),
|
|
64
85
|
// HTTP CONNECT proxy for Temporal gRPC connections (e.g. "proxy-host:8080").
|
|
65
86
|
// Must be a bare host:port — no scheme (Temporal's native HTTP CONNECT
|
|
66
87
|
// option is not a URL).
|
|
@@ -75,6 +96,13 @@ if ( error ) {
|
|
|
75
96
|
throw new InvalidEnvVarsErrors( z.prettifyError( error ) );
|
|
76
97
|
}
|
|
77
98
|
|
|
99
|
+
if ( envVars.TEMPORAL_SHUTDOWN_FORCE_TIME <= envVars.TEMPORAL_SHUTDOWN_GRACE_TIME ) {
|
|
100
|
+
log.warn( 'Temporal shutdown force time is not bigger than its grace time, so activities have no window to react to cancellation', {
|
|
101
|
+
shutdownForceTimeMs: envVars.TEMPORAL_SHUTDOWN_FORCE_TIME,
|
|
102
|
+
shutdownGraceTimeMs: envVars.TEMPORAL_SHUTDOWN_GRACE_TIME
|
|
103
|
+
} );
|
|
104
|
+
}
|
|
105
|
+
|
|
78
106
|
export const address = envVars.TEMPORAL_ADDRESS;
|
|
79
107
|
export const apiKey = envVars.TEMPORAL_API_KEY;
|
|
80
108
|
export const maxConcurrentActivityTaskExecutions = envVars.TEMPORAL_MAX_CONCURRENT_ACTIVITY_TASK_EXECUTIONS;
|
|
@@ -90,7 +118,8 @@ export const catalogId = envVars.OUTPUT_CATALOG_ID;
|
|
|
90
118
|
export const workerTelemetryIntervalMs = envVars.OUTPUT_WORKER_TELEMETRY_INTERVAL_MS;
|
|
91
119
|
export const activityHeartbeatIntervalMs = envVars.OUTPUT_ACTIVITY_HEARTBEAT_INTERVAL_MS;
|
|
92
120
|
export const activityHeartbeatEnabled = envVars.OUTPUT_ACTIVITY_HEARTBEAT_ENABLED;
|
|
93
|
-
export const
|
|
94
|
-
export const
|
|
121
|
+
export const shutdownForceTimeMs = envVars.TEMPORAL_SHUTDOWN_FORCE_TIME;
|
|
122
|
+
export const shutdownGraceTimeMs = envVars.TEMPORAL_SHUTDOWN_GRACE_TIME;
|
|
95
123
|
export const hookFlushTimeoutMs = envVars.OUTPUT_HOOK_FLUSH_TIMEOUT_MS;
|
|
124
|
+
export const temporalLogLevel = envVars.OUTPUT_TEMPORAL_LOG_LEVEL;
|
|
96
125
|
export const grpcProxy = envVars.TEMPORAL_GRPC_PROXY;
|
package/src/worker/index.js
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { Worker, NativeConnection } from '@temporalio/worker';
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
address,
|
|
4
|
+
apiKey,
|
|
5
|
+
namespace,
|
|
6
|
+
taskQueue,
|
|
7
|
+
grpcProxy,
|
|
8
|
+
hookFlushTimeoutMs,
|
|
9
|
+
shutdownForceTimeMs,
|
|
10
|
+
shutdownGraceTimeMs
|
|
11
|
+
} from './configs.js';
|
|
3
12
|
import { loadActivities } from './loader/activities.js';
|
|
4
13
|
import { loadWorkflows } from './loader/workflows.js';
|
|
5
14
|
import { loadHooks } from './loader/hooks.js';
|
|
@@ -134,7 +143,14 @@ const execute = async () => {
|
|
|
134
143
|
execute()
|
|
135
144
|
.catch( async error => abortController.abort( error ) )
|
|
136
145
|
.finally( async () => {
|
|
137
|
-
|
|
146
|
+
log.info( 'Shutting down', {
|
|
147
|
+
shutdownForceTimeMs,
|
|
148
|
+
shutdownGraceTimeMs,
|
|
149
|
+
hookFlushTimeoutMs
|
|
150
|
+
} );
|
|
151
|
+
|
|
152
|
+
const shutdownStartedAt = Date.now();
|
|
153
|
+
await shutdownServices( services );
|
|
138
154
|
|
|
139
155
|
const hasError = signal.aborted && !( signal.reason instanceof KillSignError );
|
|
140
156
|
if ( hasError ) {
|
|
@@ -145,10 +161,12 @@ execute()
|
|
|
145
161
|
log.info( 'Flushing hook callbacks...' );
|
|
146
162
|
await flushPendingHooks( hookFlushTimeoutMs );
|
|
147
163
|
|
|
148
|
-
const workerFailedToStop = shutdownFailures.some( v => v.service === 'worker' );
|
|
149
|
-
const exitCode = workerFailedToStop || hasError ? 1 : 0;
|
|
150
164
|
setTimeout( () => {
|
|
151
|
-
|
|
165
|
+
const exitCode = hasError ? 1 : 0;
|
|
166
|
+
log.info( 'Bye', {
|
|
167
|
+
exitCode,
|
|
168
|
+
shutdownDurationMs: Date.now() - shutdownStartedAt
|
|
169
|
+
} );
|
|
152
170
|
process.exit( exitCode );
|
|
153
171
|
} );
|
|
154
172
|
} );
|
package/src/worker/shutdown.js
CHANGED
|
@@ -5,49 +5,43 @@ const log = createChildLogger( 'Worker Shutdown' );
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Gracefully shuts every running service down, in order.
|
|
8
|
-
* A service that fails to stop never interrupts the sequence
|
|
9
|
-
* @returns {Promise<Array<{ service: string, error: Error }>>} one entry per service that failed to stop
|
|
8
|
+
* A service that fails to stop never interrupts the sequence
|
|
10
9
|
*/
|
|
11
10
|
export const shutdownServices = async ( { workerRunner, connectionMonitor, catalogPublisher, connection } ) => {
|
|
12
11
|
const shutdownJobs = [
|
|
13
12
|
{
|
|
14
|
-
service: 'worker',
|
|
15
13
|
label: 'Stopping Worker',
|
|
16
14
|
isActive: () => workerRunner?.running,
|
|
17
15
|
stop: () => workerRunner.stop()
|
|
18
16
|
},
|
|
19
17
|
{
|
|
20
|
-
service: 'connection_monitor',
|
|
21
18
|
label: 'Stopping Connection Monitor',
|
|
22
19
|
isActive: () => connectionMonitor?.running,
|
|
23
20
|
stop: () => connectionMonitor.stop()
|
|
24
21
|
},
|
|
25
22
|
{
|
|
26
|
-
service: 'catalog_publisher',
|
|
27
23
|
label: 'Interrupting Catalog Publisher',
|
|
28
24
|
isActive: () => catalogPublisher?.running,
|
|
29
25
|
stop: () => catalogPublisher.interrupt()
|
|
30
26
|
},
|
|
31
27
|
{
|
|
32
|
-
service: 'connection',
|
|
33
28
|
label: 'Closing Connection',
|
|
34
29
|
isActive: () => connection,
|
|
35
30
|
stop: () => connection.close()
|
|
36
31
|
}
|
|
37
32
|
];
|
|
38
33
|
|
|
39
|
-
const
|
|
40
|
-
for ( const { service, label, isActive, stop } of shutdownJobs ) {
|
|
34
|
+
for ( const { label, isActive, stop } of shutdownJobs ) {
|
|
41
35
|
if ( isActive() ) {
|
|
36
|
+
const shutdownStartedAt = Date.now();
|
|
42
37
|
log.info( `${label}...` );
|
|
43
38
|
// a try covers a service that throws instead of rejecting, which a catch on the promise would miss
|
|
44
39
|
try {
|
|
45
40
|
await stop();
|
|
41
|
+
log.info( `${label} complete`, { shutdownDurationMs: Date.now() - shutdownStartedAt } );
|
|
46
42
|
} catch ( error ) {
|
|
47
|
-
|
|
48
|
-
log.warn( `${label} error`, { error: serializeError( error ) } );
|
|
43
|
+
log.warn( `${label} failed`, { error: serializeError( error ), shutdownDurationMs: Date.now() - shutdownStartedAt } );
|
|
49
44
|
}
|
|
50
45
|
}
|
|
51
46
|
}
|
|
52
|
-
return failures;
|
|
53
47
|
};
|
|
@@ -1,32 +1,65 @@
|
|
|
1
|
-
import { DefaultLogger,
|
|
1
|
+
import { DefaultLogger, GracefulShutdownPeriodExpiredError, Runtime } from '@temporalio/worker';
|
|
2
2
|
import { createChildLogger } from '#logger';
|
|
3
|
+
import { serializeError } from '#helpers/error_serializer';
|
|
4
|
+
import { temporalLogLevel } from './configs.js';
|
|
3
5
|
|
|
4
6
|
const log = createChildLogger( 'Temporal' );
|
|
5
7
|
const OMITTED_MESSAGES = [ 'Activity failed', 'Workflow failed' ];
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
/** Whether the entry reports the shutdown force time expiring, an expected outcome of a deploy that is logged as a warning, not an error */
|
|
10
|
+
const isForcedShutdownEntry = ( { meta } ) => meta?.error instanceof GracefulShutdownPeriodExpiredError;
|
|
11
|
+
|
|
12
|
+
/** Serializes Error values in the meta, otherwise they would be logged as an empty object */
|
|
13
|
+
const serializeMetaErrors = meta => meta && Object.fromEntries(
|
|
14
|
+
Object.entries( meta ).map( ( [ key, value ] ) => [ key, value instanceof Error ? serializeError( value ) : value ] )
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
const TemporalLogLevel = {
|
|
18
|
+
TRACE: 'TRACE',
|
|
19
|
+
DEBUG: 'DEBUG',
|
|
20
|
+
INFO: 'INFO',
|
|
21
|
+
WARN: 'WARN',
|
|
22
|
+
ERROR: 'ERROR'
|
|
13
23
|
};
|
|
14
24
|
|
|
15
|
-
|
|
16
|
-
|
|
25
|
+
const temporalToInternalLogLevel = {
|
|
26
|
+
[TemporalLogLevel.TRACE]: 'debug',
|
|
27
|
+
[TemporalLogLevel.DEBUG]: 'debug',
|
|
28
|
+
[TemporalLogLevel.INFO]: 'info',
|
|
29
|
+
[TemporalLogLevel.WARN]: 'warn',
|
|
30
|
+
[TemporalLogLevel.ERROR]: 'error'
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const temporalLogLevelsOrder = [
|
|
34
|
+
TemporalLogLevel.TRACE,
|
|
35
|
+
TemporalLogLevel.DEBUG,
|
|
36
|
+
TemporalLogLevel.INFO,
|
|
37
|
+
TemporalLogLevel.WARN,
|
|
38
|
+
TemporalLogLevel.ERROR
|
|
39
|
+
];
|
|
17
40
|
|
|
41
|
+
const isLogLevelEnabled = ( configuredLevel, entryLevel ) =>
|
|
42
|
+
temporalLogLevelsOrder.indexOf( entryLevel ) >= temporalLogLevelsOrder.indexOf( configuredLevel );
|
|
43
|
+
|
|
44
|
+
export const setupTemporalLogger = () => {
|
|
18
45
|
Runtime.install( {
|
|
19
|
-
logger: new DefaultLogger(
|
|
46
|
+
logger: new DefaultLogger( temporalLogLevel, entry => {
|
|
20
47
|
// Already reported by Output activity logs and traces.
|
|
21
48
|
if ( OMITTED_MESSAGES.includes( entry.message ) ) {
|
|
22
49
|
return;
|
|
23
50
|
}
|
|
24
|
-
|
|
51
|
+
const forcedShutdown = isForcedShutdownEntry( entry );
|
|
52
|
+
if ( forcedShutdown && !isLogLevelEnabled( temporalLogLevel, TemporalLogLevel.WARN ) ) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const level = temporalToInternalLogLevel[forcedShutdown ? TemporalLogLevel.WARN : entry.level];
|
|
57
|
+
log.log( level, entry.message, serializeMetaErrors( entry.meta ) );
|
|
25
58
|
} ),
|
|
26
59
|
telemetryOptions: {
|
|
27
60
|
logging: {
|
|
28
61
|
forward: {},
|
|
29
|
-
filter:
|
|
62
|
+
filter: { core: temporalLogLevel, other: temporalLogLevel }
|
|
30
63
|
}
|
|
31
64
|
}
|
|
32
65
|
} );
|
|
@@ -10,8 +10,8 @@ const {
|
|
|
10
10
|
maxConcurrentActivityTaskPolls,
|
|
11
11
|
maxConcurrentWorkflowTaskPolls,
|
|
12
12
|
workflowThreadPoolSize,
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
shutdownForceTimeMs,
|
|
14
|
+
shutdownGraceTimeMs,
|
|
15
15
|
workerTuner
|
|
16
16
|
} = configs;
|
|
17
17
|
|
|
@@ -37,7 +37,7 @@ export const buildWorkerOptions = () => {
|
|
|
37
37
|
maxConcurrentWorkflowTaskPolls,
|
|
38
38
|
// Omitted when unset so @temporalio/worker applies its own default, which depends on reuseV8Context.
|
|
39
39
|
...( workflowThreadPoolSize !== undefined && { workflowThreadPoolSize } ),
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
shutdownForceTime: shutdownForceTimeMs,
|
|
41
|
+
shutdownGraceTime: shutdownGraceTimeMs
|
|
42
42
|
};
|
|
43
43
|
};
|