Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/37766-abandoned-mirror.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/plugin-approvals': patch
---

fix(approvals): an abandoned approval never writes a closed value on its status mirror (ADR-0162 D5, Execution item 7)

Clause-②: no
Metadata-protocol: none

A request is abandoned by its submitter's recall (while it is pending, or in the revise window after a send-back), by the override arm of a recall (an administrator, or a system context), and by the sweep that releases a record held by a dead run. Each puts a value back on the field the approval mirrors its status onto. Where the object's `closedStates` lists any value for that field (ADR-0162 D1), the mirror now chooses that value so that it never closes the document again:

- **`recalled`** is written where the field declares it and the object does not close on it, as before. A declared `recalled` the object closes on is withheld, and a `warn` line says so: listing `recalled` among the closed values closes nothing through the mirror.
- **Otherwise the order**: the value held at submit, the field's declared default, empty. A closed value is passed over at each step, and on a required field an empty value at submit is passed over for the default. A pass is logged at `info`.
- **A closed value the approval did not write is left alone.** Where the field holds a closed value, the mirror asks the request table once, by the request's root run and record, whether a request of the same approval on the same record had that value as its status. Where none did, it writes nothing and logs it at `info`. A request of the approval on another record (another item of a `map`) does not count. Where it cannot tell (the request records no root run, or a request on the record that records none was opened since the approval's run started), it goes down the order.

Every other write of the mirror is unchanged, and so is every write on an object that closes on no value of the mirror field.
209 changes: 208 additions & 1 deletion packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1783,6 +1783,12 @@ function parseJson<T = any>(raw: unknown, fallback: T): T {
/** [#24577] What {@link ApprovalService.mirroredStatusValue} answers when a transition writes nothing. */
const STATUS_NOT_MIRRORED = Symbol('status-not-mirrored');

/**
* [ADR-0162 D5] The statuses the mirror writes for a request of an approval:
* a closed value outside these was not written by the approval.
*/
const MIRRORED_REQUEST_STATUSES: ReadonlySet<string> = new Set(['pending', 'returned', 'approved', 'rejected']);

/**
* [ADR-0162 Execution item 8] The request a write of the status mirror is
* about, so that a refusal on a field the object closes on can be told on that
Expand Down Expand Up @@ -5017,6 +5023,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
* is {@link mirroredStatusValue}'s answer, and `abandoned` (the request's
* row, on a transition that abandons it) is what that answer may restore.
*
* **An abandoned request never writes a closed value (ADR-0162 D5, ruling
* record 7201405662).** On a transition that abandons a request, where the
* object's `closedStates` lists any value for `field`, the value is
* {@link abandonedValueOnClosingField}'s answer instead, and that answer may
* be to write nothing. Every other write, and every write on an object that
* closes on no value of `field`, is chosen as above.
*
* **A refused write on a field the object closes on is not swallowed
* (ADR-0162 D5, Execution item 8).** A validation rule, an option's
* `visibleWhen` or a hook of the app can refuse this write, and no reading of
Expand All @@ -5038,7 +5051,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
about?: MirrorRequestRef,
): Promise<MirrorRefusal | undefined> {
try {
const value = this.mirroredStatusValue(object, field, status, abandoned);
// [ADR-0162 D5, Execution item 7] An abandoned request on a field the
// object closes on, on any value of it: no closed value is written, and
// a closed value the approval did not write is left alone.
const closed = abandoned ? this.closedValuesOf(object, field) : [];
let value: unknown;
if (abandoned && closed.length > 0) {
const choice = await this.abandonedValueOnClosingField(object, recordId, field, closed, abandoned, about);
if ('leave' in choice) return undefined;
value = choice.write;
} else {
value = this.mirroredStatusValue(object, field, status, abandoned);
}
if (value === STATUS_NOT_MIRRORED) {
this.logger?.warn?.(
`[approvals] approval status '${status}' was not written to ${object}.${field}: the field's options do not `
Expand Down Expand Up @@ -5264,6 +5288,189 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
return holdsDeclaredValues(def?.defaultValue, declared) ? def!.defaultValue : null;
}

/**
* [ADR-0162 D1] The values `object` declares closed on `field`
* (`closedStates[field]`), read from the registry the engine validates the
* mirror's write against, as {@link closesOnApprovalOutcome} reads them.
* Empty where the object declares none for the field, or where the schema
* cannot be read: the mirror then chooses as it did before the key.
*/
private closedValuesOf(object: string, field: string): string[] {
let closedStates: unknown;
try {
closedStates = (this.engine.getSchema?.(object) as { closedStates?: unknown } | undefined)?.closedStates;
} catch { /* schema unavailable — no closed value can be read */ }
if (!closedStates || typeof closedStates !== 'object') return [];
const closed = (closedStates as Record<string, unknown>)[field];
return Array.isArray(closed) ? closed.map((v) => String(v)) : [];
}

/**
* [ADR-0162 D5, Execution item 7] What the mirror writes for a request that
* is abandoned (a recall, its override arm, the dead-run sweep) where the
* object closes on `field` on any value (`closed`). Ruling record
* 7201405662: 「平台堵住:撤回不恢复关闭值」.
*
* 1. **A closed value the approval did not write is left alone.** The field
* is read as it stands. Where it holds a closed value, the request is
* placed by its root run and the request table is asked, in one probe
* ({@link approvalWroteHeldValue}), whether a request of the same
* approval on the same record had that value as its status. Where none
* did, nothing is written. Where one did, or where it cannot tell, the
* mirror goes on to 2.
* 2. **`recalled`**, where the field declares it (or declares no value set)
* and the object does not close on it. A declared `recalled` the object
* closes on is withheld, and said so.
* 3. **The order**: the value held at submit, the field's declared
* default, empty. A closed value is passed over at each step, and so is a
* value the field does not declare (#24577). On a required field an
* empty value at submit is passed over for the default; on a field that
* is not required it is put back.
*
* Each departure from what the mirror wrote before the key is logged
* (N21): a withheld `recalled` at `warn`, since the author's closed value
* on it closes nothing through the mirror; a passed-over closed value and a
* value left alone at `info`.
*/
private async abandonedValueOnClosingField(
object: string,
recordId: string,
field: string,
closed: readonly string[],
abandoned: { payloadJson: unknown },
about: MirrorRequestRef | undefined,
): Promise<{ write: unknown } | { leave: true }> {
const isClosed = (v: unknown) => (Array.isArray(v) ? v : [v]).some((x) => x != null && closed.includes(String(x)));
const isEmpty = (v: unknown) => v == null || v === '' || (Array.isArray(v) && v.length === 0);
const request = about?.request;
const where = { object, record: recordId, field, request: request?.id ?? null };

// 1. A closed value the approval did not write is left alone.
let held: unknown;
let heldRead = false;
try {
const rows = await this.engine.find(object, {
where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX,
});
const row = Array.isArray(rows) ? rows[0] : undefined;
if (row) { held = row[field]; heldRead = true; }
} catch (err: any) {
this.logger?.warn?.('[approvals] could not read the status field of an abandoned request\'s record; the mirror goes down its order', {
...where, error: err?.message ?? String(err),
});
}
if (heldRead && isClosed(held)) {
const wrote = await this.approvalWroteHeldValue(request, held);
if (wrote === 'not') {
this.logger?.info?.(
`[approvals] the abandoned approval left ${object}.${field} at '${String(held)}': the object closes on that value `
+ `and no request of this approval on the record held it, so another writer put it there and the mirror writes nothing.`,
{ ...where, value: held },
);
return { leave: true };
}
}

let def: { defaultValue?: unknown; required?: unknown } | undefined;
try {
const schema = this.engine.getSchema?.(object) as { fields?: Record<string, unknown> } | undefined;
def = schema?.fields?.[field] as typeof def;
} catch { /* schema unavailable — no declared value set */ }
const declared = declaredOptionValues(def);
const usable = (v: unknown) => !declared || holdsDeclaredValues(v, declared);
const passedOver: Array<{ from: 'submit' | 'default'; value: unknown }> = [];
const passed = () => {
if (passedOver.length === 0) return;
this.logger?.info?.(
`[approvals] the abandoned approval passed over ${passedOver.map((p) => `'${String(p.value)}' (${p.from === 'submit' ? 'the value at submit' : 'the default'})`).join(' and ')} `
+ `for ${object}.${field}: the object closes on it, and an abandoned approval never writes a closed value.`,
{ ...where, passedOver },
);
};

// 2. `recalled`, where the field may hold it and the object does not close on it.
const declaresRecalled = !declared || declared.includes('recalled');
if (declaresRecalled && !closed.includes('recalled')) return { write: 'recalled' };
if (declaresRecalled) {
this.logger?.warn?.(
`[approvals] the abandoned approval did not write 'recalled' to ${object}.${field}: the object closes on 'recalled', `
+ `and an abandoned approval never writes a closed value, so the field takes the value at submit, the default or empty. `
+ `To show a withdrawn approval on the record, remove 'recalled' from the field's closed values.`,
{ ...where, value: 'recalled' },
);
}

// 3. The order: the value held at submit, the declared default, empty.
const snapshot = parseJson<unknown>(abandoned.payloadJson, undefined);
if (snapshot && typeof snapshot === 'object' && Object.prototype.hasOwnProperty.call(snapshot, field)) {
const atSubmit = (snapshot as Record<string, unknown>)[field];
if (isEmpty(atSubmit)) {
if (def?.required !== true) { passed(); return { write: null }; }
} else if (isClosed(atSubmit)) {
passedOver.push({ from: 'submit', value: atSubmit });
} else if (usable(atSubmit)) {
passed();
return { write: atSubmit };
}
}
const fallback = def?.defaultValue;
if (!isEmpty(fallback)) {
if (isClosed(fallback)) passedOver.push({ from: 'default', value: fallback });
else if (usable(fallback)) { passed(); return { write: fallback }; }
}
passed();
return { write: null };
}

/**
* [ADR-0162 D5, Execution item 7] Whether the approval `request` belongs to
* wrote `held`, the closed value its record's status field holds: whether a
* request of the same approval on the same record had it as its status.
*
* - `'not'`: no such request — `held` is not a status the mirror writes
* (`pending`, `returned`, `approved`, `rejected`), or the probe found none;
* - `'wrote'`: the request itself held it (every request opens on
* `pending`, and a recall in the revise window abandons a `returned`
* one), or the probe found a request of the approval that did;
* - `'unknown'`: the request records no root run (seat ruling 7210700837:
* it goes down the order), the probe found a request that records none
* and was opened since the approval's run started, or the probe failed.
*
* The approval is the request's root run (`root_run_id`), and the record is
* its `object_name` and `record_id`: a `map` item's request on another
* record does not count. One probe of the request table, on the index
* slice A declared for it.
*/
private async approvalWroteHeldValue(request: any, held: unknown): Promise<'wrote' | 'not' | 'unknown'> {
if (typeof held !== 'string' || !MIRRORED_REQUEST_STATUSES.has(held)) return 'not';
if (held === 'pending' || held === String(request?.status ?? '')) return 'wrote';
const rootRunId = request?.root_run_id ? String(request.root_run_id) : '';
if (!rootRunId) return 'unknown';
const startedAt = request?.root_run_started_at ?? null;
try {
const rows = await this.engine.find('sys_approval_request', {
where: {
object_name: request.object_name,
record_id: request.record_id,
status: held,
$or: [
{ root_run_id: rootRunId },
startedAt != null ? { root_run_id: null, created_at: { $gte: startedAt } } : { root_run_id: null },
],
},
fields: ['id', 'root_run_id'], limit: 1, context: SYSTEM_CTX,
});
const found = Array.isArray(rows) ? rows[0] : undefined;
if (!found) return 'not';
return String(found.root_run_id ?? '') === rootRunId ? 'wrote' : 'unknown';
} catch (err: any) {
this.logger?.warn?.('[approvals] could not read whether an abandoned request\'s approval wrote the closed value its record holds; the mirror goes down its order', {
request: request?.id ?? null, value: held, error: err?.message ?? String(err),
});
return 'unknown';
}
}

/**
* The context a named actor's status mirror writes under (see
* {@link mirrorStatusField}): `{ isSystem: true, userId, tenantId }` and
Expand Down
Loading
Loading