Skip to content

Commit 62daf7d

Browse files
fix(approvals): a working-time deadline whose calendar read errors no longer fails the request open or the list (#35969)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D62xGLMbyWJaMEVnAMEjTK1)_ Fixes #35953 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:审批步骤按工作日历计时时,若读取日历本身出错,提交审批不再失败,流程照常暂停等待审批;收件箱列表和单条审批照常打开,只是这一条暂不显示到期时间。 - 为什么做:属于审批工作时间计时这条线,修补上一轮引入工作日历计时后留下的缺口:日历读取出错会让已建好、已通知审批人的申请所在流程失败,还会让整个收件箱打不开。 - 出错会怎样:最坏情况是出错的那一条暂不显示到期时间、日历恢复前不会升级提醒;其他申请不受影响,改动可直接撤回。 - 要你做什么:无。 ## What changes On `origin/main` at `7de1bad5cb`, `ApprovalService.slaDeadline` serves a calendar refusal as `sla_due_refusal` (ADR-0157 D9) and rethrows every other error, and `projectWorkingTimeDue` ran it per row with no guard. Its three callers all serve a row that is already written: `openNodeRequest` (after the `sys_approval_request` insert and the `approval.requested` notices), `listRequests`, and `loadRequest` (`getRequest`, `listActions`, and the decision paths that load the request). A calendar read that errored (a driver error reading `sys_work_calendar`, not a refusal) therefore: - made the open throw, so the approval node's `catch` answered the run `success: false` while a pending request it owns existed and its approvers had been told; - failed the whole list read, and every single read of that row. **The fix, `packages/plugins/plugin-approvals/src/approval-service.ts`:** `projectWorkingTimeDue` now guards each row. On an error from `slaDeadline` it logs a `warn` naming the request and the error, and serves that row with no deadline; the loop goes on to the next row. One guard covers all three callers, so `openNodeRequest` needs no second one: the open returns the request it wrote, and the run suspends as usual. What does not change: - A refusal is still served as `sla_due_refusal`; no new refusal code and no change to the served shape. - No wall-clock fallback (ADR-0157 D2): the erroring row carries neither `sla_due_at` nor `sla_due_refusal`. - The sweep (`runEscalations`) calls `slaDeadline` itself, inside its existing per-row `try`. It still skips the row, counts nothing for it, and asks the calendar again next pass; ADR-0042 §1 single shot is unchanged. The sweep's assertions in the new test pass on `main` too: they pin this, they do not fix it. - Log level `warn`: no persisted claim is lost, a read projection is missing one field (AGENTS.md, degradation log levels). Not done: the optional per-pass refusal memo. It does not come for free: it needs a key across rows (organization plus calendar code plus the start-and-hours inputs) and a decision on whether a memoised refusal may serve rows of other organizations. It is left for its own card if the read cost matters. Changeset `.changeset/35953-sla-deadline-error-guard.md`: `@objectstack/plugin-approvals` patch. Read first (risk order): 1. `approval-service.ts`, the `projectWorkingTimeDue` hunk: the `try`/`catch` around `slaDeadline` and the `continue` that leaves the row with no deadline. 2. `approval-service-sla-calendar-clock.test.ts`, the new last `describe`: the calendar double that throws a plain `Error` for a chosen calendar code and delegates to the real `WorkCalendarService` otherwise. ## Evals Tests are in the existing harness file `src/approval-service-sla-calendar-clock.test.ts`, as a new top-level `describe` (4 tests). The calendar double is the real `WorkCalendarService` over the file's read double, except that a calendar code in a test-controlled set throws `new Error('sys_work_calendar read failed: connection reset')`. 1. The open returns the pending request, the row exists in `sys_approval_request`, neither `sla_due_at` nor `sla_due_refusal` is served, and a warning names the request. 2. The approval node, driven through a real `AutomationEngine` flow, answers `paused` with one suspended run (on `main`: `failed`). 3. A list with one erroring row and one good row: both are listed, the good row keeps `sla_due_at` (Tuesday 12:00 Shanghai, holiday skipped), the erroring row has no deadline; `getRequest` of the erroring row answers it. 4. The sweep: the erroring row is skipped (`escalated: 1`, the good row only), escalated on the next pass once the calendar reads again, and a third pass escalates nothing. ## Verification Two-minute check: `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/approval-service-sla-calendar-clock.test.ts` prints `Tests 16 passed (16)`. <details><summary>Red on main (the guard ablated once)</summary> `approval-service.ts` restored from `7de1bad5cb` on disk under a trap (disk hash `f1d462d986` equals main's blob; guard text occurrences 0), tests from the branch, then restored from `HEAD` (`git diff HEAD` empty, `git status --porcelain` empty). The subject is imported by relative path from `src/`, so no `dist/` rebuild sits between the mutation and the run. - open: `Error: sys_work_calendar read failed: connection reset` thrown by `openNodeRequest` - node: `expected 'failed' to be 'paused'` - list: the same error thrown by `listRequests` - sweep: `runEscalations` and the good row's escalation pass; the red is the erroring row's `listActions` read (it loads the request), the read seam the fix covers - `Test Files 1 failed (1)`, `Tests 4 failed | 12 passed (16)` Green on the fix: `Tests 16 passed (16)`. </details> <details><summary>Package suite, typecheck and derived gates at dd312c3</summary> - `pnpm --filter @objectstack/plugin-approvals test`: `Test Files 126 passed (126)`, `Tests 1803 passed (1803)` - `pnpm --filter @objectstack/plugin-approvals typecheck`: exit 0, `check:test-typecheck: OK` - `node scripts/pm/dispatch-gates.mjs --commands`: 72 commands; 70 exit 0; `pnpm check:dual-build-cjs-loads` and `pnpm check:i18n` exit 3 PREREQUISITE NOT MET (they need a whole-workspace build and the built CLI closure), NOT MEASURED locally, CI runs both. `--ran` reconciliation: `72 derived famil(ies) accounted for — 70 run, 2 NOT-MEASURED`. - `node scripts/pm/overlap-check.mjs --branch=claude/area-a4W-35953`: `VERDICT clean exit 0`, merges cleanly into `origin/main`. - `test:repo` and the full dogfood battery are CI's (no `!` in the title, no narrowing arm). </details> ## Acceptance notes - An erroring row is served with neither `sla_due_at` nor `sla_due_refusal`, so a reader cannot tell it from a node with no SLA until the calendar reads again; only the server log says why. A `calendar_error` refusal code would say it on the row, but that is a served-shape change that needs a contract read, so it is out of this PR by the seat's scope. - The sweep logs its existing `escalation failed for request` warning for the erroring row on each pass; unchanged. Session: https://claude.ai/code/session_016WV4czKnDE6hsyXQzB9wB2 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 96b66ca commit 62daf7d

3 files changed

Lines changed: 145 additions & 2 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-approvals': patch
3+
---
4+
5+
fix(approvals): a working-time SLA deadline whose calendar read errors no longer fails the request open or the whole list
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
When an approval step's escalation counts `working_time` and the working calendar read itself fails (an error that is not a calendar refusal, such as a driver error reading `sys_work_calendar`), opening the request threw after the `sys_approval_request` row was written and its approvers were told, so the approval node failed its flow run. The same error failed every list read and single read that included the row, and so every decision that loads it.
11+
12+
That row is now served with no deadline and the error is logged as a warning; the open returns the request, the run suspends as usual, and the other rows of a list keep their deadlines. A calendar refusal is still served as `sla_due_refusal`, the deadline never falls back to wall-clock hours, and the escalation sweep still skips the row and asks the calendar again on its next pass. The served request shape is unchanged.

‎packages/plugins/plugin-approvals/src/approval-service-sla-calendar-clock.test.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@
2828

2929
import { describe, it, expect } from 'vitest';
3030
import { WorkCalendarService } from '@objectstack/objectql';
31+
import { AutomationEngine } from '@objectstack/service-automation';
3132
import { ApprovalService } from './approval-service.js';
33+
import { registerApprovalNode } from './approval-node.js';
3234

3335
interface Row { [k: string]: any }
3436

@@ -390,3 +392,115 @@ describe("ApprovalEscalation.clock 'working_time' counts the hours on a working
390392
expect(row?.sla_due_refusal).toBeUndefined();
391393
});
392394
});
395+
396+
// ── a calendar read that ERRORS, as opposed to one that refuses ─────────────
397+
//
398+
// A refusal (`isWorkCalendarRefusal`) is served as `sla_due_refusal` (D9). Any
399+
// other error — a driver failure reading `sys_work_calendar` — leaves that one
400+
// row with no deadline served: it never fails a request open that has already
401+
// written the row and told the approvers, never fails the rest of a list, and
402+
// never falls back to wall-clock hours (D2). The sweep skips the row and asks
403+
// again next pass.
404+
405+
const CN_BACKUP: Row = { ...CN_CALENDAR, id: 'cal_cn_backup', code: 'cn_backup', is_default: false };
406+
407+
/** The real calendar service, except that a read for a calendar code in `failing` throws a plain Error. */
408+
function erroringCalendarServiceAt(iso: string, failing: Set<string>) {
409+
let nowMs = Date.parse(iso);
410+
const engine = makeEngine();
411+
const reads = calendarReads([CN_CALENDAR, CN_BACKUP], CN_EXCEPTIONS);
412+
const real = new WorkCalendarService({ getEngine: () => reads, posture: () => 'isolated', ttlMs: 0 });
413+
const warned: Array<{ msg: string; meta: any }> = [];
414+
const logger = { info() {}, debug() {}, error() {}, warn: (msg: string, meta: any) => { warned.push({ msg, meta }); } };
415+
const svc = new ApprovalService({
416+
engine: engine as any,
417+
logger: logger as any,
418+
clock: { now: () => new Date(nowMs) },
419+
workCalendar: () => ({
420+
async addWorkingHours(scope, start, hours) {
421+
if (typeof scope.calendar === 'string' && failing.has(scope.calendar)) {
422+
throw new Error('sys_work_calendar read failed: connection reset');
423+
}
424+
return real.addWorkingHours(scope, start, hours);
425+
},
426+
}),
427+
});
428+
return { svc, engine, warned, setNow: (at: string) => { nowMs = Date.parse(at); } };
429+
}
430+
431+
describe("ApprovalEscalation.clock 'working_time': a calendar read that errors costs only that row its deadline", () => {
432+
const created = sh('2026-04-03', '17:00');
433+
434+
it('the open still returns the request it wrote and told the approvers about, with no deadline served', async () => {
435+
const { svc, engine, warned } = erroringCalendarServiceAt(created, new Set(['cn_standard']));
436+
const req = await openPending(svc, workingTimeInput('wt_error_open', 4, { calendar: 'cn_standard' }));
437+
438+
expect(engine._tables.sys_approval_request?.map((r) => r.id)).toEqual([req.id]);
439+
expect(req.status).toBe('pending');
440+
expect(req.sla_due_at).toBeUndefined();
441+
expect(req.sla_due_refusal).toBeUndefined();
442+
expect(warned.some((w) => w.meta?.request === req.id)).toBe(true);
443+
});
444+
445+
it('the approval node suspends its run instead of failing it', async () => {
446+
const { svc } = erroringCalendarServiceAt(created, new Set(['cn_standard']));
447+
const automation = new AutomationEngine({ info() {}, warn() {}, error() {}, debug() {} } as any);
448+
svc.attachAutomation(automation);
449+
registerApprovalNode(automation, svc);
450+
automation.registerFlow('wt_flow', {
451+
name: 'wt_flow',
452+
label: 'Working-time approval',
453+
type: 'autolaunched',
454+
nodes: [
455+
{ id: 'start', type: 'start', label: 'Start' },
456+
{ id: 'approve_step', type: 'approval', label: 'Approve', config: workingTimeInput('approve_step', 4, { calendar: 'cn_standard' }).config },
457+
{ id: 'end', type: 'end', label: 'End' },
458+
],
459+
edges: [
460+
{ id: 'e1', source: 'start', target: 'approve_step' },
461+
{ id: 'e2', source: 'approve_step', target: 'end', label: 'approve' },
462+
],
463+
} as any);
464+
465+
const result = await automation.execute('wt_flow', { object: 'opportunity', record: { id: 'opp1' }, userId: 'u1' });
466+
expect(result.status).toBe('paused');
467+
expect(automation.listSuspendedRuns()).toHaveLength(1);
468+
});
469+
470+
it('a list and a single read keep every other row and its deadline', async () => {
471+
const failing = new Set<string>();
472+
const { svc } = erroringCalendarServiceAt(created, failing);
473+
const good = await openPending(svc, workingTimeInput('wt_good', 4, { calendar: 'cn_standard' }));
474+
const bad = await openPending(svc, { ...workingTimeInput('wt_bad', 4, { calendar: 'cn_backup' }), recordId: 'opp2', record: { id: 'opp2', amount: 100 } });
475+
failing.add('cn_backup');
476+
477+
const list = await svc.listRequests({ status: 'pending' }, SYS);
478+
expect(list.map((r) => r.id).sort()).toEqual([good.id, bad.id].sort());
479+
expect(list.find((r) => r.id === good.id)?.sla_due_at).toBe(sh('2026-04-07', '12:00'));
480+
const listedBad = list.find((r) => r.id === bad.id);
481+
expect(listedBad?.sla_due_at).toBeUndefined();
482+
expect(listedBad?.sla_due_refusal).toBeUndefined();
483+
484+
const read = await svc.getRequest(bad.id, SYS);
485+
expect(read?.id).toBe(bad.id);
486+
expect(read?.sla_due_at).toBeUndefined();
487+
});
488+
489+
it('the sweep skips the row, asks again next pass, and still escalates it once', async () => {
490+
const failing = new Set<string>();
491+
const { svc, setNow } = erroringCalendarServiceAt(created, failing);
492+
const good = await openPending(svc, workingTimeInput('wt_sweep_good', 4, { calendar: 'cn_standard' }));
493+
const bad = await openPending(svc, { ...workingTimeInput('wt_sweep_bad', 4, { calendar: 'cn_backup' }), recordId: 'opp2', record: { id: 'opp2', amount: 100 } });
494+
failing.add('cn_backup');
495+
496+
setNow(sh('2026-04-20', '12:00'));
497+
expect(await svc.runEscalations()).toMatchObject({ escalated: 1 });
498+
expect((await svc.listActions(good.id, SYS)).some((a) => a.action === 'escalate')).toBe(true);
499+
expect((await svc.listActions(bad.id, SYS)).some((a) => a.action === 'escalate')).toBe(false);
500+
501+
failing.delete('cn_backup');
502+
expect(await svc.runEscalations()).toMatchObject({ escalated: 1 });
503+
expect((await svc.listActions(bad.id, SYS)).filter((a) => a.action === 'escalate')).toHaveLength(1);
504+
expect(await svc.runEscalations()).toMatchObject({ escalated: 0 });
505+
});
506+
});

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8336,7 +8336,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
83368336
* organization's calendar, named by `escalation.calendar` or else its default
83378337
* (D2), recomputed on every call and never stored (D12). A calendar refusal
83388338
* (none resolves, or it is not maintained that far, D8) answers
8339-
* `{ refusal }` instead of a deadline (D9); every other failure throws.
8339+
* `{ refusal }` instead of a deadline (D9); every other failure throws, and
8340+
* each caller costs only that row its deadline: the sweep skips it until the
8341+
* next pass, {@link projectWorkingTimeDue} serves it with none.
83408342
*/
83418343
private async slaDeadline(raw: any, cfg: any): Promise<SlaDeadline | undefined> {
83428344
if (!escalationCountsWorkingTime(cfg)) {
@@ -8369,12 +8371,27 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
83698371
* calendar cannot count it, through {@link slaDeadline}. `raws[i]` is the
83708372
* stored row `rows[i]` was mapped from; a `wall_clock` row already carries
83718373
* its deadline from the synchronous mapper and is left alone.
8374+
*
8375+
* A calendar read that errors (not a refusal) costs only its own row the
8376+
* deadline: it is logged and that row is served with none, never a
8377+
* wall-clock one (D2). Every caller serves a row that is already written —
8378+
* `openNodeRequest` after the insert and the approvers' notices, the list
8379+
* and single reads — so the error never fails the write or the other rows.
8380+
* The sweep reads {@link slaDeadline} itself and retries the row next pass.
83728381
*/
83738382
private async projectWorkingTimeDue(raws: readonly any[], rows: ApprovalRequestRow[]): Promise<void> {
83748383
for (let i = 0; i < rows.length; i++) {
83758384
const cfg = parseJson<any>(raws[i]?.node_config_json, undefined);
83768385
if (!escalationCountsWorkingTime(cfg)) continue;
8377-
const deadline = await this.slaDeadline(raws[i], cfg);
8386+
let deadline: SlaDeadline | undefined;
8387+
try {
8388+
deadline = await this.slaDeadline(raws[i], cfg);
8389+
} catch (err: any) {
8390+
this.logger?.warn?.('[approvals] working-time SLA deadline could not be computed; the request is served without one', {
8391+
request: raws[i]?.id, error: err?.message ?? String(err),
8392+
});
8393+
continue;
8394+
}
83788395
if (!deadline) continue;
83798396
if ('refusal' in deadline) rows[i]!.sla_due_refusal = deadline.refusal;
83808397
else rows[i]!.sla_due_at = deadline.due;

0 commit comments

Comments
 (0)