plugin-document-understanding 1.1.11 → 1.1.12

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.
@@ -0,0 +1,259 @@
1
+ import { AsyncJobManager, pollLeaseMs } from '../services/AsyncJobManager';
2
+ import { ExternalApiClient } from '../services/ExternalApiClient';
3
+ import { PipelineExecutor } from '../services/PipelineExecutor';
4
+
5
+ function row(attributes: Record<string, unknown>) {
6
+ return {
7
+ id: attributes.id,
8
+ get: (name: string) => attributes[name],
9
+ };
10
+ }
11
+
12
+ function transactionDb(jobsRepo: Record<string, any>, pipelinesRepo?: Record<string, any>) {
13
+ return {
14
+ getRepository: vi.fn((name: string) =>
15
+ name === 'doc_understanding_jobs' ? jobsRepo : pipelinesRepo ?? { findOne: vi.fn() },
16
+ ),
17
+ sequelize: {
18
+ transaction: vi.fn(async (fn: (transaction: unknown) => Promise<void>) => fn({ LOCK: { UPDATE: 'UPDATE' } })),
19
+ },
20
+ };
21
+ }
22
+
23
+ describe('PipelineExecutor resume claim', () => {
24
+ const pipeline = {
25
+ id: 1,
26
+ steps: [
27
+ { stepOrder: 1, name: 'ocr', outputAlias: 'ocr', endpoint: { executionMode: 'polling' } },
28
+ { stepOrder: 2, name: 'summarize', outputAlias: 'summary', endpoint: { executionMode: 'sync' } },
29
+ ],
30
+ };
31
+
32
+ function createExecutor(jobAttributes: Record<string, unknown>) {
33
+ const jobsRepo = {
34
+ findOne: vi.fn().mockResolvedValue(row(jobAttributes)),
35
+ update: vi.fn().mockResolvedValue([]),
36
+ };
37
+ const pipelinesRepo = { findOne: vi.fn().mockResolvedValue(pipeline) };
38
+ const db = transactionDb(jobsRepo, pipelinesRepo);
39
+ const executor = new PipelineExecutor(db as never, {} as never, {} as never, { error: vi.fn() }, 'node-a');
40
+ const runSteps = vi.fn().mockResolvedValue(undefined);
41
+ (executor as any).runSteps = runSteps;
42
+ return { executor, jobsRepo, runSteps };
43
+ }
44
+
45
+ it('resumes a job that is still polling and claims ownership', async () => {
46
+ const { executor, jobsRepo, runSteps } = createExecutor({
47
+ id: 7,
48
+ status: 'polling',
49
+ pipelineId: 1,
50
+ currentStep: 1,
51
+ stepResults: {},
52
+ input: { file: 'x' },
53
+ });
54
+
55
+ await executor.resumeFromStep(7, { text: 'parsed' });
56
+
57
+ expect(jobsRepo.update).toHaveBeenCalledWith(
58
+ expect.objectContaining({
59
+ filterByTk: 7,
60
+ values: expect.objectContaining({
61
+ status: 'running',
62
+ ownedBy: 'node-a',
63
+ stepResults: { ocr: { text: 'parsed' } },
64
+ }),
65
+ }),
66
+ );
67
+ expect(runSteps).toHaveBeenCalledTimes(1);
68
+ expect(runSteps.mock.calls[0][3]).toBe(2);
69
+ });
70
+
71
+ it('does not resume a job that was already resumed by another node', async () => {
72
+ const { executor, jobsRepo, runSteps } = createExecutor({
73
+ id: 7,
74
+ status: 'running',
75
+ pipelineId: 1,
76
+ currentStep: 1,
77
+ stepResults: {},
78
+ input: {},
79
+ });
80
+
81
+ await executor.resumeFromStep(7, { text: 'parsed' });
82
+
83
+ expect(jobsRepo.update).not.toHaveBeenCalled();
84
+ expect(runSteps).not.toHaveBeenCalled();
85
+ });
86
+
87
+ it('does not resume a completed job when a webhook is retried', async () => {
88
+ const { executor, jobsRepo, runSteps } = createExecutor({
89
+ id: 7,
90
+ status: 'completed',
91
+ pipelineId: 1,
92
+ currentStep: 2,
93
+ stepResults: {},
94
+ input: {},
95
+ });
96
+
97
+ await executor.resumeFromStep(7, { text: 'parsed' });
98
+
99
+ expect(jobsRepo.update).not.toHaveBeenCalled();
100
+ expect(runSteps).not.toHaveBeenCalled();
101
+ });
102
+ });
103
+
104
+ describe('AsyncJobManager orphan handling', () => {
105
+ function createManager(jobsRepo: Record<string, any>, nodeId = 'node-a') {
106
+ const db = transactionDb(jobsRepo);
107
+ return new AsyncJobManager(
108
+ db as never,
109
+ {} as ExternalApiClient,
110
+ { onJobComplete: vi.fn(), onJobError: vi.fn() },
111
+ { warn: vi.fn() },
112
+ nodeId,
113
+ );
114
+ }
115
+
116
+ it('fails only jobs this node owned or whose lease expired', async () => {
117
+ const update = vi.fn().mockResolvedValue([]);
118
+ const manager = createManager({ update });
119
+
120
+ await manager.failOrphanedActiveJobs();
121
+
122
+ expect(update).toHaveBeenCalledTimes(2);
123
+ expect(update.mock.calls[0][0]).toEqual({
124
+ filter: { status: { $in: ['pending', 'running'] }, ownedBy: 'node-a' },
125
+ values: expect.objectContaining({ status: 'failed', error: 'Server restarted during execution' }),
126
+ });
127
+ expect(update.mock.calls[1][0].filter).toEqual({
128
+ status: { $in: ['pending', 'running'] },
129
+ $or: [{ leaseExpiresAt: { $lt: expect.any(Date) } }, { leaseExpiresAt: null }],
130
+ });
131
+ expect(update.mock.calls[1][0].values.completedAt).toBeInstanceOf(Date);
132
+ });
133
+
134
+ it('adopts an orphaned polling job whose lease expired', async () => {
135
+ const expiredLease = new Date(Date.now() - 60_000);
136
+ const jobsRepo = {
137
+ find: vi.fn().mockResolvedValue([
138
+ {
139
+ id: 11,
140
+ pipelineId: 1,
141
+ currentStep: 1,
142
+ externalTaskIds: { '1': 'task-9' },
143
+ ownedBy: 'dead-node',
144
+ leaseExpiresAt: expiredLease,
145
+ },
146
+ ]),
147
+ findOne: vi
148
+ .fn()
149
+ .mockResolvedValue(row({ id: 11, status: 'polling', ownedBy: 'dead-node', leaseExpiresAt: expiredLease })),
150
+ update: vi.fn().mockResolvedValue([]),
151
+ };
152
+ const pipelinesRepo = {
153
+ findOne: vi.fn().mockResolvedValue({
154
+ steps: [{ stepOrder: 1, endpoint: { executionMode: 'polling', pollInterval: 5000 } }],
155
+ }),
156
+ };
157
+ const db = transactionDb(jobsRepo, pipelinesRepo);
158
+ const manager = new AsyncJobManager(
159
+ db as never,
160
+ {} as ExternalApiClient,
161
+ { onJobComplete: vi.fn(), onJobError: vi.fn() },
162
+ { warn: vi.fn() },
163
+ 'node-a',
164
+ );
165
+ const startPolling = vi.spyOn(manager, 'startPolling').mockResolvedValue(undefined);
166
+
167
+ await manager.adoptOrphanedPollingJobs();
168
+
169
+ expect(jobsRepo.update).toHaveBeenCalledWith(
170
+ expect.objectContaining({
171
+ filterByTk: 11,
172
+ values: expect.objectContaining({ ownedBy: 'node-a' }),
173
+ }),
174
+ );
175
+ expect(startPolling).toHaveBeenCalledWith(11, expect.objectContaining({ executionMode: 'polling' }), 'task-9');
176
+ });
177
+
178
+ it('leaves a polling job alone while another node holds a valid lease', async () => {
179
+ const validLease = new Date(Date.now() + 60_000);
180
+ const jobsRepo = {
181
+ find: vi.fn().mockResolvedValue([
182
+ {
183
+ id: 12,
184
+ pipelineId: 1,
185
+ currentStep: 1,
186
+ externalTaskIds: { '1': 'task-9' },
187
+ ownedBy: 'node-b',
188
+ leaseExpiresAt: validLease,
189
+ },
190
+ ]),
191
+ findOne: vi
192
+ .fn()
193
+ .mockResolvedValue(row({ id: 12, status: 'polling', ownedBy: 'node-b', leaseExpiresAt: validLease })),
194
+ update: vi.fn().mockResolvedValue([]),
195
+ };
196
+ const pipelinesRepo = {
197
+ findOne: vi.fn().mockResolvedValue({
198
+ steps: [{ stepOrder: 1, endpoint: { executionMode: 'polling', pollInterval: 5000 } }],
199
+ }),
200
+ };
201
+ const db = transactionDb(jobsRepo, pipelinesRepo);
202
+ const manager = new AsyncJobManager(
203
+ db as never,
204
+ {} as ExternalApiClient,
205
+ { onJobComplete: vi.fn(), onJobError: vi.fn() },
206
+ { warn: vi.fn() },
207
+ 'node-a',
208
+ );
209
+ const startPolling = vi.spyOn(manager, 'startPolling').mockResolvedValue(undefined);
210
+
211
+ await manager.adoptOrphanedPollingJobs();
212
+
213
+ expect(jobsRepo.update).not.toHaveBeenCalled();
214
+ expect(startPolling).not.toHaveBeenCalled();
215
+ });
216
+
217
+ it('never adopts webhook-mode jobs because any node can serve the callback', async () => {
218
+ const expiredLease = new Date(Date.now() - 60_000);
219
+ const jobsRepo = {
220
+ find: vi.fn().mockResolvedValue([
221
+ {
222
+ id: 13,
223
+ pipelineId: 1,
224
+ currentStep: 1,
225
+ externalTaskIds: { '1': 'task-9' },
226
+ ownedBy: 'dead-node',
227
+ leaseExpiresAt: expiredLease,
228
+ },
229
+ ]),
230
+ findOne: vi.fn(),
231
+ update: vi.fn().mockResolvedValue([]),
232
+ };
233
+ const pipelinesRepo = {
234
+ findOne: vi.fn().mockResolvedValue({
235
+ steps: [{ stepOrder: 1, endpoint: { executionMode: 'webhook' } }],
236
+ }),
237
+ };
238
+ const db = transactionDb(jobsRepo, pipelinesRepo);
239
+ const manager = new AsyncJobManager(
240
+ db as never,
241
+ {} as ExternalApiClient,
242
+ { onJobComplete: vi.fn(), onJobError: vi.fn() },
243
+ { warn: vi.fn() },
244
+ 'node-a',
245
+ );
246
+ const startPolling = vi.spyOn(manager, 'startPolling').mockResolvedValue(undefined);
247
+
248
+ await manager.adoptOrphanedPollingJobs();
249
+
250
+ expect(jobsRepo.findOne).not.toHaveBeenCalled();
251
+ expect(startPolling).not.toHaveBeenCalled();
252
+ });
253
+
254
+ it('computes polling leases with a floor above the poll interval', () => {
255
+ expect(pollLeaseMs(5000)).toBe(60_000);
256
+ expect(pollLeaseMs(60_000)).toBe(180_000);
257
+ expect(pollLeaseMs(undefined)).toBe(60_000);
258
+ });
259
+ });
@@ -19,6 +19,11 @@ export default {
19
19
  { type: 'json', name: 'externalTaskIds' },
20
20
  { type: 'date', name: 'startedAt' },
21
21
  { type: 'date', name: 'completedAt' },
22
+ // Cluster ownership: which node is executing/polling this job, and until when
23
+ // its lease is valid. Orphaned jobs (owner restarted or lease expired) are
24
+ // failed or re-adopted by the maintenance sweep.
25
+ { type: 'string', name: 'ownedBy', length: 255 },
26
+ { type: 'date', name: 'leaseExpiresAt' },
22
27
  {
23
28
  type: 'belongsTo',
24
29
  name: 'createdBy',
@@ -26,4 +31,12 @@ export default {
26
31
  foreignKey: 'createdById',
27
32
  },
28
33
  ],
34
+ indexes: [
35
+ {
36
+ fields: ['status'],
37
+ },
38
+ {
39
+ fields: ['leaseExpiresAt'],
40
+ },
41
+ ],
29
42
  } as CollectionOptions;
@@ -1,11 +1,24 @@
1
1
  import { Database } from '@nocobase/database';
2
2
  import { ExternalApiClient } from './ExternalApiClient';
3
- import { EndpointDef, JobState } from '../types';
3
+ import { EndpointDef } from '../types';
4
4
 
5
5
  interface LoggerLike {
6
6
  warn: (...args: unknown[]) => void;
7
7
  }
8
8
 
9
+ // Lease for inline (pending/running) execution. Refreshed at the start of every
10
+ // pipeline step; must outlive the slowest step (endpoint timeout x retries).
11
+ export const JOB_RUN_LEASE_MS = 10 * 60 * 1000;
12
+ // Lease for polling jobs. Refreshed on every poll tick, so it only needs to
13
+ // outlive a few missed ticks before another node may adopt the job.
14
+ const JOB_POLL_LEASE_MIN_MS = 60 * 1000;
15
+
16
+ export function pollLeaseMs(pollInterval?: number): number {
17
+ return Math.max((pollInterval || 5000) * 3, JOB_POLL_LEASE_MIN_MS);
18
+ }
19
+
20
+ const JOBS_COLLECTION = 'doc_understanding_jobs';
21
+
9
22
  export class AsyncJobManager {
10
23
  private db: Database;
11
24
  private apiClient: ExternalApiClient;
@@ -13,6 +26,7 @@ export class AsyncJobManager {
13
26
  private onJobComplete: (jobId: number, result: any) => Promise<void>;
14
27
  private onJobError: (jobId: number, error: string) => Promise<void>;
15
28
  private logger: LoggerLike;
29
+ private nodeId: string;
16
30
 
17
31
  constructor(
18
32
  db: Database,
@@ -22,12 +36,14 @@ export class AsyncJobManager {
22
36
  onJobError: (jobId: number, error: string) => Promise<void>;
23
37
  },
24
38
  logger: LoggerLike,
39
+ nodeId: string,
25
40
  ) {
26
41
  this.db = db;
27
42
  this.apiClient = apiClient;
28
43
  this.onJobComplete = callbacks.onJobComplete;
29
44
  this.onJobError = callbacks.onJobError;
30
45
  this.logger = logger;
46
+ this.nodeId = nodeId;
31
47
  }
32
48
 
33
49
  async startPolling(
@@ -52,8 +68,16 @@ export class AsyncJobManager {
52
68
  return;
53
69
  }
54
70
 
71
+ // Renew our lease; if the row no longer matches (job finished, or another
72
+ // node adopted it after our lease expired) stop polling immediately.
73
+ if (!(await this.refreshLease(jobId, endpoint))) {
74
+ this.stopPolling(jobId);
75
+ return;
76
+ }
77
+
55
78
  const pollResultSubpath = endpoint.pollResultSubpath;
56
79
  if (!pollResultSubpath) {
80
+ this.stopPolling(jobId);
57
81
  await this.onJobError(jobId, 'Polling result subpath is not configured');
58
82
  return;
59
83
  }
@@ -95,61 +119,103 @@ export class AsyncJobManager {
95
119
  this.intervals.set(jobId, timer);
96
120
  }
97
121
 
122
+ private async refreshLease(jobId: number, endpoint: EndpointDef): Promise<boolean> {
123
+ const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
124
+ const updated = await jobsRepo.update({
125
+ filter: { id: jobId, status: 'polling', ownedBy: this.nodeId },
126
+ values: { leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)) },
127
+ });
128
+ return Array.isArray(updated) ? updated.length > 0 : Boolean(updated);
129
+ }
130
+
98
131
  /**
99
- * Transition pending and running jobs to failed state during startup.
132
+ * Fail pending/running jobs that can no longer be executing. First the jobs
133
+ * this node owned (in-memory execution state is lost across a restart), then
134
+ * any remaining job whose owner lease expired. Rows without a lease predate
135
+ * ownership tracking and are treated as orphaned too.
100
136
  */
101
- async cleanupStuckJobs(): Promise<void> {
102
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
103
- const stuckJobs = await jobsRepo.find({
137
+ async failOrphanedActiveJobs(): Promise<void> {
138
+ const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
139
+ const now = new Date();
140
+
141
+ await jobsRepo.update({
142
+ filter: { status: { $in: ['pending', 'running'] }, ownedBy: this.nodeId },
143
+ values: { status: 'failed', error: 'Server restarted during execution', completedAt: now },
144
+ });
145
+
146
+ await jobsRepo.update({
104
147
  filter: {
105
- status: ['pending', 'running'],
148
+ status: { $in: ['pending', 'running'] },
149
+ $or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }],
106
150
  },
151
+ values: { status: 'failed', error: 'Job lease expired before completion', completedAt: now },
107
152
  });
108
-
109
- for (const job of stuckJobs) {
110
- await jobsRepo.update({
111
- filterByTk: job.id,
112
- values: {
113
- status: 'failed',
114
- error: 'Server restarted during execution',
115
- completedAt: new Date(),
116
- },
117
- });
118
- }
119
153
  }
120
154
 
121
155
  /**
122
- * Recover polling jobs that were in-flight when server restarted.
123
- * Call this during service initialization.
156
+ * Re-adopt 'polling' jobs whose owner can no longer be polling them: jobs this
157
+ * node owned before a restart, jobs whose lease expired, and legacy rows without
158
+ * ownership. Webhook-mode jobs are skipped — nothing polls them, and any node
159
+ * can process the webhook when it arrives.
124
160
  */
125
- async recoverPollingJobs(): Promise<void> {
126
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
127
- const stuckJobs = await jobsRepo.find({ filter: { status: 'polling' } });
128
-
129
- for (const job of stuckJobs) {
130
- if (!job.externalTaskIds) continue;
161
+ async adoptOrphanedPollingJobs(): Promise<void> {
162
+ const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
163
+ const now = new Date();
164
+ const candidates = await jobsRepo.find({
165
+ filter: {
166
+ status: 'polling',
167
+ $or: [{ ownedBy: this.nodeId }, { leaseExpiresAt: { $lt: now } }, { ownedBy: null }],
168
+ },
169
+ });
131
170
 
132
- // Find the current step's endpoint and taskId
133
- const stepKey = job.currentStep.toString();
134
- const taskId = job.externalTaskIds[stepKey];
171
+ for (const job of candidates) {
172
+ const externalTaskIds = (job.externalTaskIds || {}) as Record<string, string>;
173
+ const stepKey = String(job.currentStep);
174
+ const taskId = externalTaskIds[stepKey];
135
175
  if (!taskId) continue;
136
176
 
137
- // We need the endpoint definition for this step
138
177
  const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
139
178
  const pipeline = await pipelineRepo.findOne({
140
179
  filter: { id: job.pipelineId },
141
180
  appends: ['steps', 'steps.endpoint'],
142
181
  });
143
-
144
182
  if (!pipeline) continue;
145
183
 
146
- const step = (pipeline as any).steps?.find((s: any) => s.stepOrder === job.currentStep);
184
+ const steps = ((pipeline as any).steps || []) as Array<{ stepOrder: number; endpoint?: EndpointDef }>;
185
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
147
186
  if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
148
187
 
149
- await this.startPolling(job.id, step.endpoint, taskId);
188
+ if (await this.claimJobForPolling(job.id, step.endpoint)) {
189
+ await this.startPolling(job.id, step.endpoint, taskId);
190
+ }
150
191
  }
151
192
  }
152
193
 
194
+ private async claimJobForPolling(jobId: number, endpoint: EndpointDef): Promise<boolean> {
195
+ return this.db.sequelize.transaction(async (transaction: { LOCK: { UPDATE: string } }): Promise<boolean> => {
196
+ const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
197
+ const row = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
198
+ if (!row) return false;
199
+ if (String(row.get('status')) !== 'polling') return false;
200
+
201
+ const owner = row.get('ownedBy') as string | null;
202
+ const lease = row.get('leaseExpiresAt') as Date | string | null;
203
+ const leaseValid = lease != null && new Date(lease).getTime() > Date.now();
204
+ // A different node still owns the job with a valid lease: leave it alone.
205
+ if (owner !== this.nodeId && leaseValid) return false;
206
+
207
+ await jobsRepo.update({
208
+ filterByTk: jobId,
209
+ values: {
210
+ ownedBy: this.nodeId,
211
+ leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)),
212
+ },
213
+ transaction,
214
+ });
215
+ return true;
216
+ });
217
+ }
218
+
153
219
  stopPolling(jobId: number) {
154
220
  const timer = this.intervals.get(jobId);
155
221
  if (timer) {
@@ -15,11 +15,17 @@ export class DocumentUnderstandingService {
15
15
  private initialized = false;
16
16
  private startupRecoveryCompleted = false;
17
17
  private initializationPromise?: Promise<void>;
18
+ private maintenanceTimer?: NodeJS.Timeout;
19
+ // Unique per process; used as the job owner so other nodes can tell orphaned
20
+ // jobs apart from jobs that are still being processed.
21
+ private readonly nodeId: string;
18
22
  private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
23
+ private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
19
24
 
20
25
  constructor(app: Application, db: Database) {
21
26
  this.app = app;
22
27
  this.db = db;
28
+ this.nodeId = `${app?.name || 'app'}:${process.pid}:${crypto.randomUUID()}`;
23
29
  }
24
30
 
25
31
  async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
@@ -43,6 +49,7 @@ export class DocumentUnderstandingService {
43
49
  const config = await this.ensureConfig();
44
50
 
45
51
  this.jobManager?.destroy();
52
+ this.stopMaintenance();
46
53
  this.apiClient = new ExternalApiClient(config);
47
54
  this.jobManager = new AsyncJobManager(
48
55
  this.db,
@@ -60,19 +67,57 @@ export class DocumentUnderstandingService {
60
67
  },
61
68
  },
62
69
  this.app.logger,
70
+ this.nodeId,
63
71
  );
64
72
 
65
- this.pipelineExecutor = new PipelineExecutor(this.db, this.apiClient, this.jobManager, this.app.logger);
73
+ this.pipelineExecutor = new PipelineExecutor(
74
+ this.db,
75
+ this.apiClient,
76
+ this.jobManager,
77
+ this.app.logger,
78
+ this.nodeId,
79
+ );
66
80
 
67
81
  if (recoverJobs && !this.startupRecoveryCompleted) {
68
- await this.jobManager.cleanupStuckJobs();
69
- await this.jobManager.recoverPollingJobs();
82
+ await this.maintainJobs();
70
83
  this.startupRecoveryCompleted = true;
71
84
  }
85
+ this.startMaintenance();
72
86
 
73
87
  this.initialized = true;
74
88
  }
75
89
 
90
+ /**
91
+ * Cluster maintenance sweep: fails active jobs whose owner is gone and
92
+ * re-adopts orphaned polling jobs. Safe to run on every node — all state
93
+ * transitions are guarded by ownership checks and row-level claims.
94
+ */
95
+ async maintainJobs(): Promise<void> {
96
+ if (!this.jobManager) return;
97
+ try {
98
+ await this.jobManager.failOrphanedActiveJobs();
99
+ await this.jobManager.adoptOrphanedPollingJobs();
100
+ } catch (err) {
101
+ this.app.logger.warn('Document Understanding: job maintenance sweep failed.', err);
102
+ }
103
+ }
104
+
105
+ private startMaintenance(): void {
106
+ this.stopMaintenance();
107
+ this.maintenanceTimer = setInterval(() => {
108
+ this.maintainJobs();
109
+ }, DocumentUnderstandingService.MAINTENANCE_INTERVAL_MS);
110
+ // The sweep must never keep the process alive on shutdown.
111
+ this.maintenanceTimer.unref?.();
112
+ }
113
+
114
+ private stopMaintenance(): void {
115
+ if (this.maintenanceTimer) {
116
+ clearInterval(this.maintenanceTimer);
117
+ this.maintenanceTimer = undefined;
118
+ }
119
+ }
120
+
76
121
  private async ensureConfig(): Promise<ServiceConfig> {
77
122
  const configRepo = this.db.getRepository<any>('doc_understanding_config');
78
123
  let config = await configRepo.findOne();
@@ -126,6 +171,7 @@ export class DocumentUnderstandingService {
126
171
  }
127
172
 
128
173
  destroy(): void {
174
+ this.stopMaintenance();
129
175
  this.jobManager?.destroy();
130
176
  this.initialized = false;
131
177
  this.startupRecoveryCompleted = false;