Skip to content

Commit d86bc4c

Browse files
authored
Merge pull request #1534 from qtomlinson/qt/refactor_computeLock-v2
Eliminate _upgradeLock by unifying serialization under computeLock
2 parents 504812c + ee6bf17 commit d86bc4c

18 files changed

Lines changed: 522 additions & 213 deletions

‎business/definitionService.d.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,19 @@ export declare class DefinitionService {
430430
toolRevision: string
431431
): Promise<Definition | undefined>
432432

433+
/**
434+
* Acquire computeLock, evaluate shouldCompute(), and conditionally compute+store+curate.
435+
* Serializes compute per coordinate — check-then-act is atomic inside the lock.
436+
*
437+
* @param coordinates - The coordinates to compute
438+
* @param shouldCompute - Returns true to proceed with compute, false to skip
439+
* @returns The computed definition or undefined if skipped
440+
*/
441+
computeStoreAndCurateIf(
442+
coordinates: EntityCoordinates,
443+
shouldCompute: () => Promise<boolean>
444+
): Promise<Definition | undefined>
445+
433446
/**
434447
* Compute the final representation of the specified definition
435448
*

‎business/definitionService.js‎

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ const computeLock = memoryCache({
6969

7070
const currentSchema = '1.7.0'
7171

72+
const COMPUTE_LOCK_WARN_MS = 60_000
73+
7274
const weights = {
7375
declared: 30,
7476
discovered: 25,
@@ -379,19 +381,60 @@ class DefinitionService {
379381
* @returns {Promise<Definition>} The computed definition
380382
*/
381383
async computeStoreAndCurate(coordinates) {
382-
// one coordinate a time through this method so no duplicate auto curation will be created.
384+
return this._withComputeLock(coordinates, async () => {
385+
const definition = await this._computeAndStore(coordinates)
386+
await this.curationService.autoCurate(definition)
387+
return definition
388+
})
389+
}
390+
391+
/**
392+
* Acquire computeLock, evaluate shouldCompute(), and conditionally compute+store+curate.
393+
* @param {EntityCoordinates} coordinates
394+
* @param {() => Promise<boolean>} shouldCompute - Returns true to proceed, false to skip.
395+
* Should be lightweight and read-only (e.g. getStored + validate); it runs inside the lock.
396+
* @returns {Promise<Definition | undefined>}
397+
*/
398+
async computeStoreAndCurateIf(coordinates, shouldCompute) {
399+
return this._withComputeLock(coordinates, async () => {
400+
if (!(await shouldCompute())) {
401+
return undefined
402+
}
403+
const definition = await this._computeAndStore(coordinates)
404+
await this.curationService.autoCurate(definition)
405+
return definition
406+
})
407+
}
408+
409+
/**
410+
* Acquire computeLock and run the action while holding the lock.
411+
* @param {EntityCoordinates} coordinates
412+
* @param {() => Promise<T>} action - Work to perform while holding the lock.
413+
* @returns {Promise<T>}
414+
* @template T
415+
* @private
416+
*/
417+
async _withComputeLock(coordinates, action) {
383418
this.logger.debug('3:memory_lock:start', {
384419
ts: new Date().toISOString(),
385420
coordinates: coordinates.toString()
386421
})
422+
const lockWaitStart = Date.now()
423+
let lockWarnLogged = false
387424
while (computeLock.get(coordinates.toString())) {
388425
await new Promise(resolve => setTimeout(resolve, 500))
426+
if (!lockWarnLogged && Date.now() - lockWaitStart > COMPUTE_LOCK_WARN_MS) {
427+
this.logger.warn(`computeLock spin-wait exceeded ${COMPUTE_LOCK_WARN_MS / 1000}s`, {
428+
coordinates: coordinates.toString()
429+
})
430+
lockWarnLogged = true
431+
}
389432
}
390433
try {
434+
// No `await` between the while-exit and set() — this is intentional.
435+
// Inserting an async call here would break the lock.
391436
computeLock.set(coordinates.toString(), true)
392-
const definition = await this._computeAndStore(coordinates)
393-
await this.curationService.autoCurate(definition)
394-
return definition
437+
return await action()
395438
} finally {
396439
computeLock.delete(coordinates.toString())
397440
}
@@ -403,15 +446,7 @@ class DefinitionService {
403446
* @returns {Promise<Definition>} The computed definition
404447
*/
405448
async computeAndStore(coordinates) {
406-
while (computeLock.get(coordinates.toString())) {
407-
await new Promise(resolve => setTimeout(resolve, 500)) // one coordinate a time through this method so we always get latest
408-
}
409-
try {
410-
computeLock.set(coordinates.toString(), true)
411-
return await this._computeAndStore(coordinates)
412-
} finally {
413-
computeLock.delete(coordinates.toString())
414-
}
449+
return this._withComputeLock(coordinates, () => this._computeAndStore(coordinates))
415450
}
416451

417452
/**
@@ -422,11 +457,7 @@ class DefinitionService {
422457
* @returns {Promise<Definition | undefined>} The computed definition or undefined if skipped
423458
*/
424459
async computeAndStoreIfNecessary(coordinates, tool, toolRevision) {
425-
while (computeLock.get(coordinates.toString())) {
426-
await new Promise(resolve => setTimeout(resolve, 500)) // one coordinate a time through this method so we always get latest
427-
}
428-
try {
429-
computeLock.set(coordinates.toString(), true)
460+
return this._withComputeLock(coordinates, async () => {
430461
if (!(await this._isToolResultNew(coordinates, tool, toolRevision))) {
431462
this.logger.info('definition computation skipped: tool result processed', {
432463
coordinates: coordinates.toString(),
@@ -436,9 +467,7 @@ class DefinitionService {
436467
return undefined
437468
}
438469
return await this._computeAndStore(coordinates)
439-
} finally {
440-
computeLock.delete(coordinates.toString())
441-
}
470+
})
442471
}
443472

444473
/**

‎providers/logging/winstonConfig.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ function factory(options) {
116116
const logFormat = winston.format.combine(
117117
sanitizeMeta(),
118118
winston.format.timestamp(),
119-
winston.format.errors({ stack: true }),
119+
winston.format.errors({ stack: true, cause: true }),
120120
winston.format.printf(({ timestamp, level, message, ...meta }) => {
121121
const metaKeys = Object.keys(meta)
122122
const metaString = metaKeys.length ? `\n${JSON.stringify(meta, null, 2)}` : ''
@@ -152,7 +152,9 @@ function factory(options) {
152152
const properties = buildProperties(info)
153153
if (info.level === 'error') {
154154
if (info.stack) {
155-
aiClient.trackException({ exception: new Error(info.message), properties })
155+
const exception = info.cause ? new Error(info.message, { cause: info.cause }) : new Error(info.message)
156+
exception.stack = info.stack
157+
aiClient.trackException({ exception, properties })
156158
} else {
157159
aiClient.trackTrace({
158160
message: info.message,

‎providers/upgrade/computePolicy.d.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,9 @@
44
import type { Definition, DefinitionService, RecomputeContext } from '../../business/definitionService.js'
55
import type { EntityCoordinates } from '../../lib/entityCoordinates.js'
66
import type { Logger } from '../logging/index.js'
7-
import type { ICache } from '../caching/index.js'
87

98
export interface MissingDefinitionComputePolicy {
109
initialize?(): Promise<void> | void
11-
setupProcessing?(
12-
definitionService?: DefinitionService,
13-
logger?: Logger,
14-
once?: boolean,
15-
cache?: ICache
16-
): Promise<void> | void
10+
setupProcessing?(definitionService?: DefinitionService, logger?: Logger, once?: boolean): Promise<void> | void
1711
compute(definitionService: RecomputeContext, coordinates: EntityCoordinates): Promise<Definition>
1812
}

‎providers/upgrade/defUpgradeQueue.d.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
import type { Definition, DefinitionService } from '../../business/definitionService.js'
55
import type { IQueue } from '../queueing/index.js'
66
import type { Logger } from '../logging/index.js'
7-
import type { ICache } from '../caching/index.js'
87
import type { DefinitionVersionChecker, DefinitionVersionCheckerOptions } from './defVersionCheck.js'
98

9+
/** Configuration options for DefinitionQueueUpgrader */
1010
export interface DefinitionQueueUpgraderOptions extends DefinitionVersionCheckerOptions {
1111
/** Factory function that creates the upgrade queue */
1212
queue: () => IQueue
@@ -42,9 +42,8 @@ declare class DefinitionQueueUpgrader extends DefinitionVersionChecker {
4242
* @param definitionService - The service used to recompute definitions
4343
* @param logger - Logger instance
4444
* @param once - If true, process one batch and stop (for testing)
45-
* @param cache - Optional lock cache
4645
*/
47-
setupProcessing(definitionService: DefinitionService, logger: Logger, once?: boolean, cache?: ICache): Promise<void>
46+
setupProcessing(definitionService: DefinitionService, logger: Logger, once?: boolean): Promise<void>
4847
}
4948

5049
export default DefinitionQueueUpgrader

‎providers/upgrade/defUpgradeQueue.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { setup } from './process.js'
88
* @typedef {import('../../business/definitionService').Definition} Definition
99
* @typedef {import('../../business/definitionService').DefinitionService} DefinitionService
1010
* @typedef {import('../logging').Logger} Logger
11-
* @typedef {import('../caching').ICache} ICache
1211
*/
1312

1413
class DefinitionQueueUpgrader extends DefinitionVersionChecker {
@@ -73,12 +72,11 @@ class DefinitionQueueUpgrader extends DefinitionVersionChecker {
7372
* @param {DefinitionService} definitionService
7473
* @param {Logger} logger
7574
* @param {boolean} [once]
76-
* @param {ICache} [cache]
7775
*/
78-
setupProcessing(definitionService, logger, once, cache) {
76+
setupProcessing(definitionService, logger, once) {
7977
// Use a plain DefinitionVersionChecker (not `this`) so the queue processor returns undefined
8078
// for stale definitions and triggers recompute — rather than re-queuing them again.
81-
return setup(this._upgrade, definitionService, logger, once, new DefinitionVersionChecker(this.options), cache)
79+
return setup(this._upgrade, definitionService, logger, once, new DefinitionVersionChecker(this.options))
8280
}
8381
}
8482

‎providers/upgrade/defVersionCheck.d.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// SPDX-License-Identifier: MIT
33

44
import type { Logger } from '../logging/index.js'
5-
import type { ICache } from '../caching/index.js'
65
import type { Definition, DefinitionService, UpgradeHandler } from '../../business/definitionService.js'
76

87
/** Configuration options for DefinitionVersionChecker */
@@ -37,7 +36,7 @@ export declare class DefinitionVersionChecker implements UpgradeHandler {
3736
initialize(): Promise<void>
3837

3938
/** No-op setup (exists for interface compatibility with subclass overrides) */
40-
setupProcessing(definitionService?: DefinitionService, logger?: Logger, once?: boolean, cache?: ICache): void
39+
setupProcessing(definitionService?: DefinitionService, logger?: Logger, once?: boolean): void
4140

4241
/**
4342
* Extracts a string representation of coordinates from a definition.

‎providers/upgrade/delayedComputePolicy.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export declare class DelayedComputePolicy implements MissingDefinitionComputePol
2121

2222
initialize(): Promise<void>
2323

24-
setupProcessing(definitionService: DefinitionService, logger: Logger, once?: boolean, cache?: ICache): Promise<void>
24+
setupProcessing(definitionService: DefinitionService, logger: Logger, once?: boolean): Promise<void>
2525

2626
compute(definitionService: RecomputeContext, coordinates: EntityCoordinates): Promise<Definition>
2727
}

‎providers/upgrade/delayedComputePolicy.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { SkipUpgradePolicy } from './skipUpgradePolicy.js'
1212
/** @typedef {import('../../business/definitionService').Definition} Definition */
1313
/** @typedef {import('../../lib/entityCoordinates')} EntityCoordinates */
1414
/** @typedef {import('../logging').Logger} Logger */
15-
/** @typedef {import('../caching').ICache} ICache */
1615

1716
class DelayedComputePolicy {
1817
static _enqueueCacheTtlSeconds = 60 * 20 /* 20 mins */
@@ -35,11 +34,10 @@ class DelayedComputePolicy {
3534
* @param {DefinitionService} definitionService
3635
* @param {Logger} logger
3736
* @param {boolean} [once]
38-
* @param {ICache} [cache]
3937
*/
40-
setupProcessing(definitionService, logger, once, cache) {
38+
setupProcessing(definitionService, logger, once) {
4139
const upgradePolicy = new SkipUpgradePolicy()
42-
return setup(this._compute, definitionService, logger, once, upgradePolicy, cache)
40+
return setup(this._compute, definitionService, logger, once, upgradePolicy)
4341
}
4442

4543
/**

‎providers/upgrade/process.d.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// SPDX-License-Identifier: MIT
33

44
import type { DefinitionService, UpgradeHandler } from '../../business/definitionService.js'
5-
import type { ICache } from '../caching/index.js'
65
import type { Logger } from '../logging/index.js'
76
import type { DequeuedMessage, IQueue } from '../queueing/index.js'
87

@@ -36,21 +35,17 @@ export declare class QueueHandler {
3635

3736
/**
3837
* Processes upgrade messages by recomputing stale definitions.
39-
* Uses an in-memory lock to prevent concurrent upgrades for the same coordinates.
38+
* Serialization is handled by computeLock in definitionService via computeStoreAndCurateIf.
4039
*/
4140
export declare class DefinitionUpgrader implements MessageHandler {
42-
/** Delay in milliseconds between lock-retry attempts */
43-
static readonly delayInMSeconds: number
44-
4541
logger: Logger
4642

4743
/**
4844
* @param definitionService - Service for fetching and recomputing definitions
4945
* @param logger - Logger instance
5046
* @param upgradePolicy - Policy that validates whether stored definitions need upgrade
51-
* @param cache - Lock cache; defaults to a new in-memory cache with 5 min TTL
5247
*/
53-
constructor(definitionService: DefinitionService, logger: Logger, upgradePolicy: UpgradeHandler, cache?: ICache)
48+
constructor(definitionService: DefinitionService, logger: Logger, upgradePolicy: UpgradeHandler)
5449

5550
/**
5651
* Processes a single dequeued upgrade message.
@@ -68,13 +63,11 @@ export declare class DefinitionUpgrader implements MessageHandler {
6863
* @param logger - Logger instance
6964
* @param once - If true, processes one batch and stops
7065
* @param upgradePolicy - Upgrade policy (defaults to a new DefinitionVersionChecker)
71-
* @param cache - Optional lock cache; passed through to DefinitionUpgrader
7266
*/
7367
export declare function setup(
7468
queue: IQueue,
7569
definitionService: DefinitionService,
7670
logger: Logger,
7771
once?: boolean,
78-
upgradePolicy?: UpgradeHandler,
79-
cache?: ICache
72+
upgradePolicy?: UpgradeHandler
8073
): Promise<void>

0 commit comments

Comments
 (0)