From f23dc7a2672abad4d4ab4ba13057d2c63b0ec290 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:04:47 +0000 Subject: [PATCH 1/6] wip(sync-in): D4 provenance columns, index, write refusal and pull stamping Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- .../src/metadata-diagnostics.ts | 35 ++++- packages/objectql/src/engine-insert.ts | 7 + packages/objectql/src/engine-update.ts | 6 + packages/objectql/src/index.ts | 9 ++ .../src/registry-object-registration.ts | 14 +- packages/objectql/src/registry.ts | 29 +++- .../objectql/src/sync-provenance-index.ts | 103 ++++++++++++++ .../objectql/src/sync-provenance-write.ts | 119 ++++++++++++++++ .../service-automation/src/connector-pull.ts | 34 ++++- .../service-automation/src/datasource-pull.ts | 30 +++- .../src/sync-provenance-stamp.ts | 128 ++++++++++++++++++ .../spec/src/api/error-code-ledger.zod.ts | 7 + .../data/injected-system-column-provenance.ts | 69 +++++++++- .../spec/src/data/injected-system-columns.ts | 54 +++++++- 14 files changed, 628 insertions(+), 16 deletions(-) create mode 100644 packages/objectql/src/sync-provenance-index.ts create mode 100644 packages/objectql/src/sync-provenance-write.ts create mode 100644 packages/services/service-automation/src/sync-provenance-stamp.ts diff --git a/packages/metadata-protocol/src/metadata-diagnostics.ts b/packages/metadata-protocol/src/metadata-diagnostics.ts index e1b22209119..3ec1ebd837c 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.ts @@ -45,6 +45,7 @@ import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; import { stackKeyForType } from '@objectstack/lint/runtime'; // [#26886] The resolution's mark on options it derived from a shared picklist. import { isResolvedPicklistOptions } from '@objectstack/metadata-core'; +import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS, isInjectedColumnDefinition } from '@objectstack/spec/data'; import type { RuntimeAuthoringIssue } from '@objectstack/spec/api'; /** @@ -226,6 +227,30 @@ function withoutResolvedPicklistOptions(document: unknown): unknown { return next ? { ...(document as object), fields: next } : document; } +/** + * [ADR-0153 D4] A served object document with the platform's own `_sync_` + * provenance columns left out of its name-keyed `fields`. The injected-columns + * plan gives them to a `managedBy: 'synced'` object, the read serves the + * effective schema (#6562), and `ObjectSchema` reserves the `_sync_` prefix + * against AUTHOR fields, so judged as served every synced object would read + * `valid: false` over columns the platform added. Only a field identical to + * the platform's definition is left out: an author's `_sync_` field stays and + * is refused by name, as it must be. By reference when there is none. + */ +function withoutInjectedSyncProvenanceColumns(document: unknown): unknown { + if (!document || typeof document !== 'object') return document; + const fields = (document as { fields?: unknown }).fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return document; + let next: Record | undefined; + for (const name of SYNC_PROVENANCE_COLUMNS) { + const field = (fields as Record)[name]; + if (field === undefined || !isInjectedColumnDefinition(field, SYNC_PROVENANCE_FIELD_DEFS[name])) continue; + next ??= { ...(fields as Record) }; + delete next[name]; + } + return next ? { ...(document as object), fields: next } : document; +} + /** * Compute spec diagnostics for a single metadata document. * @@ -289,7 +314,15 @@ export function computeMetadataDiagnostics( // accepted it. For the VERDICT only: the read serves the body it was // handed. Not a redaction, so the #8154 order below is untouched: the // body judged is still the unredacted one. - const candidate = withoutResolvedPicklistOptions(storedFlowVerdictBody(singular, stripReadDecorations(item))); + // + // [ADR-0153 D4] …and judge a served object without the `_sync_` provenance + // columns the platform injected on a synced object + // ({@link withoutInjectedSyncProvenanceColumns}): the author may not write + // them, so the document the author wrote never held them. + const stripped = storedFlowVerdictBody(singular, stripReadDecorations(item)); + const candidate = withoutResolvedPicklistOptions( + singular === 'object' ? withoutInjectedSyncProvenanceColumns(stripped) : stripped, + ); // [#25783] A document parsed before against this same schema is answered // from the memo — see "The verdict memo" above. diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 4aaa6e22c5f..9691265b7e0 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -47,6 +47,7 @@ import { SummaryRecomputeError } from './summary-errors.js'; import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js'; import { DuplicateRecordError } from './duplicate-record-error.js'; import { NotNullRefusalError, envelopeDriverWriteRefusal } from './not-null-refusal-error.js'; +import { refuseSyncProvenanceWrite } from './sync-provenance-write.js'; import { ASSIGNMENT_RULE_TYPE, AssignmentRuleEvaluator, OWNERSHIP_QUEUE_SOURCE_SLOT } from './assignment-rules.js'; import type { AssignmentQueueService } from './assignment-rules.js'; import { redactBoundStatement } from '@objectstack/types'; @@ -342,6 +343,12 @@ export class InsertFacet { ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) }); this.assertWriteAllowed(object, 'insert'); + // [ADR-0153 D4] A `_sync_` provenance column is written by the sync-in pull + // alone, whatever the caller's context: judged on the caller's payload, + // before anything runs. The pull's mark is consumed here, so the hooks and + // flows this write triggers write as any other system caller. + const syncJudgedContext = refuseSyncProvenanceWrite(object, data, options?.context, 'insert'); + if (syncJudgedContext !== options?.context) options = { ...options, context: syncJudgedContext } as typeof options; // [#8844] The organization set is about to change. Dropped BEFORE the write // rather than after it, so a concurrent read cannot repopulate the memo from // a snapshot this insert is in the middle of invalidating. diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 0eec7a84db7..3a771dbdd99 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -35,6 +35,7 @@ import type { DroppedFieldsEvent, EngineUpdateOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { collectComposableReadableIds } from './filter-comparand-shape.js'; +import { refuseSyncProvenanceWrite } from './sync-provenance-write.js'; // [ADR-0155 D4] The fixed-read leaf seam reads the engine through the security // resolvers' host, built once per engine, which carries every member it reads. import { securityResolversHost } from './engine-facet-hosts.js'; @@ -188,6 +189,11 @@ export class UpdateFacet { ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Update operation starting', { object }); this.assertWriteAllowed(object, 'update'); + // [ADR-0153 D4] The insert face's rule: a `_sync_` provenance column is the + // sync-in pull's alone, judged on the caller's payload before anything + // runs, and the pull's mark does not travel past this write. + const syncJudgedContext = refuseSyncProvenanceWrite(object, data, options?.context, 'update'); + if (syncJudgedContext !== options?.context) options = { ...options, context: syncJudgedContext } as typeof options; // [#8844] See the insert face — an organization row that changes identity // invalidates the memo just as one that appears does. if (object === ORGANIZATION_OBJECT) this.invalidateOrganizationProbe(); diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 679ff7296e6..5deca89b5a6 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -320,6 +320,15 @@ export type { SummaryRecomputeFailure } from './summary-errors.js'; // holding the other realm's copy of the class gets `instanceof` === false, // silently. export { ReadonlyFieldRejectedError, READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js'; +// [ADR-0153 D4] The sync-in pull's write mark and the refusal of a `_sync_` +// provenance column in any other write. The mark is the pull's alone +// (`@objectstack/service-automation`); see `sync-provenance-write.ts`. +export { + SYNC_PULL_WRITE, + markSyncPullWrite, + SyncProvenanceWriteRefusedError, + SYNC_PROVENANCE_WRITE_REFUSED_CODE, +} from './sync-provenance-write.js'; // [#32768] What `ObjectQL#judgeFieldWriteLock` answers for a field its // `readonlyWhen` locks now: the drop reason and the strict refusal's phrase. export type { FieldWriteLock } from './engine-field-write-lock.js'; diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 3eaa3c2318b..a2ec45ab3cd 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -51,6 +51,7 @@ import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, ins import type { FieldPatchTargetMiss } from '@objectstack/metadata-core'; import { scalarOverridesPackagedBase } from '@objectstack/spec/system'; import { SEARCH_COMPANION_FIELD, provisionSearchCompanion } from './search-companion.js'; +import { provisionSyncProvenanceIndex, stripProvisionedSyncProvenanceIndexFrom } from './sync-provenance-index.js'; import { applyExtensionPlacements, fieldGroupKeysOf, placementContributorsOf } from './registry-extension-placement.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; import { applyCustomArrangement, relatedListsArrangementOf, rememberRelatedListsArrangement } from './registry-custom-arrangement.js'; @@ -1663,6 +1664,12 @@ export class ObjectRegistrationFacet { // change the answer the two steps above reached over the fields map. out = provisionTenantScopeIndex(out, { multiTenant: this.multiTenant }); + // [ADR-0153 D4] The sync-in provenance index, a document-gated stamp like + // the one above. Runs AFTER it, so the tenant index's write-side inverse + // still finds its entry last; its own inverse runs first in + // `stripMaterializedStampsFrom`. + out = provisionSyncProvenanceIndex(out); + return out; } @@ -1742,7 +1749,12 @@ export class ObjectRegistrationFacet { if (base === null || typeof base !== 'object') return base; return this.stripDeploymentTenancyFrom( this.stripProvisionedPrimaryFrom( - this.stripProvisionedSearchCompanionFrom(this.stripProvisionedTenantIndexFrom(base)), + this.stripProvisionedSearchCompanionFrom( + // [ADR-0153 D4] The sync-in provenance index is stamped last, so it + // is taken off first: the tenant inverse re-stamps and compares, and + // holds only while its own entry is the last one. + this.stripProvisionedTenantIndexFrom(stripProvisionedSyncProvenanceIndexFrom(base)), + ), ), ); } diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index e942804d510..b36b46743a4 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { ServiceObject, ObjectOwnership, type RelatedListsArrangement, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, AUDIT_PROVENANCE_FIELDS } from '@objectstack/spec/data'; +import { ServiceObject, ObjectOwnership, type RelatedListsArrangement, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, AUDIT_PROVENANCE_FIELDS, SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; // [#4513] The audit-family governance table, and [#6562] the injected-column // DEFINITION tables it governs — see the re-exports below for why both live in a // package `objectql` and `metadata-protocol` both depend on. @@ -35,6 +35,7 @@ import { import { resolveTenancyPosture, resolveSearchPinyinEnabled } from '@objectstack/types'; import { postureEnforcesWall } from '@objectstack/spec/security'; import { provisionSearchCompanion } from './search-companion.js'; +import { provisionSyncProvenanceIndex } from './sync-provenance-index.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; import { ObjectStackManifest, InstalledPackage, type InstalledPackageSource, customizationBasePackageId, type NamespaceObjectNameClash } from '@objectstack/spec/kernel'; import { applyProtection } from '@objectstack/spec/shared'; @@ -567,6 +568,8 @@ export function applySystemFields( // [ADR-0142 D3] The queue column rides with the owner anchor (the plan's // `queue` is its `owner`): "sits in Q" is `queue == Q AND owner_id IS NULL`. const wantQueue = plan.queue; + // [ADR-0153 D4] The five `_sync_` provenance columns of a `synced` object. + const wantSync = plan.sync; // Nothing to INJECT — the two opt-out rows (`systemFields: false`, // `managedBy: 'better-auth'`) and objects whose every column is already @@ -580,7 +583,7 @@ export function applySystemFields( // `systemFields.tenant` only, so `systemFields: false` leaves the wall live). // Returning `schema` here was the last exit that decided the index by NOT // asking, which is how the withholding survived #8375's convergence. - if (!wantTenant && !wantAudit && !wantOwner && !wantOwningBusinessUnit && !wantQueue) { + if (!wantTenant && !wantAudit && !wantOwner && !wantOwningBusinessUnit && !wantQueue && !wantSync) { return provisionTenantScopeIndex(schema, opts); } @@ -712,16 +715,32 @@ export function applySystemFields( additions[QUEUE_FIELD] = { ...QUEUE_FIELD_DEF }; } + // [ADR-0153 D4] The sync-in provenance columns, on a `synced` object only: + // the mapping that wrote the row, its key in the source, when and by which + // run it was last written, and D3's mark (planned with the rest, written by + // nothing until the delete marking lands). `readonly`, `system`, `hidden`: + // the pull, writing as the system, is their one writer, and the engine + // refuses any other write that names one (`refuseSyncProvenanceWrite`). No + // author field can take a `_sync_` name, so the guard below only ever admits + // the platform's own definition coming back through a re-registration. Their + // index is {@link provisionSyncProvenanceIndex}, stamped after the tenant + // index on the merged result. + if (wantSync) { + for (const name of SYNC_PROVENANCE_COLUMNS) { + if (!schema.fields?.[name]) additions[name] = { ...SYNC_PROVENANCE_FIELD_DEFS[name] }; + } + } + // [#8375] The tenant INDEX is decided over the MERGED result, never over the // input — so this function and the read-exit seam ask the same question of the // same document shape. Both cases below route through it, including the one // that adds no field at all (an object whose every system column is already // declared still owes the index decision). if (Object.keys(additions).length === 0 && Object.keys(overrides).length === 0) { - return provisionTenantScopeIndex(schema, opts); + return provisionSyncProvenanceIndex(provisionTenantScopeIndex(schema, opts)); } - return provisionTenantScopeIndex( + return provisionSyncProvenanceIndex(provisionTenantScopeIndex( { ...schema, // `additions` LOSE to an author's field (a declared `owner_id` is theirs); @@ -729,7 +748,7 @@ export function applySystemFields( fields: { ...additions, ...(schema.fields ?? {}), ...overrides }, }, opts, - ); + )); } /** diff --git a/packages/objectql/src/sync-provenance-index.ts b/packages/objectql/src/sync-provenance-index.ts new file mode 100644 index 00000000000..e8ada1b9acb --- /dev/null +++ b/packages/objectql/src/sync-provenance-index.ts @@ -0,0 +1,103 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4] The index a `managedBy: 'synced'` object carries over its + * provenance columns: (`organization_id`, `_sync_source`, `_sync_external_id`), + * which "serves the delete diff and the match" — a pull's rows of one mapping + * in one organization, by their key in the source. + * + * It is a stamp of the registered schema, like the tenant-scope index + * (`provisionTenantScopeIndex`), and it follows that stamp's two rules: + * + * - **Gated on the document, never on a flag.** It is appended when the + * object carries the two provenance columns the plan + * (`resolveInjectedSystemColumns`) gives a `synced` object. No author field + * can take a `_sync_` name (`ObjectSchema` reserves the prefix), so carrying + * them is the plan's answer, read at either site in either order. The + * tenant column leads the index when the object has one; an object without + * it gets the two provenance columns alone. + * - **Appended LAST, and removed FIRST.** The tenant index's write-side + * inverse re-stamps and compares, which holds only while its entry is the + * last one; so this stamp runs after it at both producers + * (`applySystemFields`, `materializeBaseLayer`), and its own inverse + * ({@link stripProvisionedSyncProvenanceIndexFrom}) runs before the tenant + * one in `stripMaterializedStampsFrom`. + * + * An index the author already declares with exactly these columns is not + * duplicated. + */ + +import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS } from '@objectstack/spec/data'; + +type Rec = Record; + +const [SYNC_SOURCE, SYNC_EXTERNAL_ID] = SYNC_PROVENANCE_COLUMNS; +const TENANT_COLUMN = 'organization_id'; + +function fieldsRecord(schema: unknown): Rec | undefined { + if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return undefined; + const fields = (schema as Rec).fields; + return fields && typeof fields === 'object' && !Array.isArray(fields) ? (fields as Rec) : undefined; +} + +/** + * The provenance index this object is owed, or `undefined` when it carries no + * provenance columns. + */ +export function syncProvenanceIndexFor(schema: unknown): { fields: string[] } | undefined { + const fields = fieldsRecord(schema); + if (!fields || fields[SYNC_SOURCE] === undefined || fields[SYNC_EXTERNAL_ID] === undefined) return undefined; + return { + fields: fields[TENANT_COLUMN] !== undefined + ? [TENANT_COLUMN, SYNC_SOURCE, SYNC_EXTERNAL_ID] + : [SYNC_SOURCE, SYNC_EXTERNAL_ID], + }; +} + +function sameColumns(entry: unknown, columns: readonly string[]): boolean { + const fields = entry && typeof entry === 'object' ? (entry as Rec).fields : undefined; + return Array.isArray(fields) && fields.length === columns.length && fields.every((f, i) => f === columns[i]); +} + +/** Is `entry` exactly a platform stamp (one of its two column lists, and no other key)? */ +function isPlatformEntry(entry: unknown): boolean { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false; + if (Object.keys(entry as Rec).length !== 1) return false; + return sameColumns(entry, [TENANT_COLUMN, SYNC_SOURCE, SYNC_EXTERNAL_ID]) || sameColumns(entry, [SYNC_SOURCE, SYNC_EXTERNAL_ID]); +} + +/** Append the provenance index an object is owed. Returns `schema` by reference when nothing is owed. */ +export function provisionSyncProvenanceIndex(schema: T): T { + const owed = syncProvenanceIndexFor(schema); + if (!owed) return schema; + const declared = (schema as Rec).indexes; + const present = Array.isArray(declared) ? declared : []; + if (present.some((entry) => sameColumns(entry, owed.fields))) return schema; + return { ...(schema as Rec), indexes: [...present, owed] } as T; +} + +/** + * The write-side inverse of {@link provisionSyncProvenanceIndex}: remove the + * stamp a served document picked up, so a GET → edit → PUT round trip stores + * the body the author wrote. Only the LAST entry is a candidate, and only when + * it is exactly the platform's (an author's entry with a `name` or `unique` + * stays). An emptied list is the absence of the key, as for the tenant stamp. + * + * Gated on the PLAN (`managedBy: 'synced'`), not on the document's columns: a + * body handed here may already have had its injected columns stripped, and + * either column list is accepted for the same reason (whether the tenant + * column led the stamp is not readable off a stripped body). + * Returns `base` by reference when nothing was owed. + */ +export function stripProvisionedSyncProvenanceIndexFrom(base: T): T { + if (base === null || typeof base !== 'object') return base; + if (!resolveInjectedSystemColumns(base).sync) return base; + const present = (base as Rec).indexes; + if (!Array.isArray(present) || present.length === 0) return base; + if (!isPlatformEntry(present[present.length - 1])) return base; + const kept = present.slice(0, -1); + const without = { ...(base as Rec) }; + if (kept.length === 0) delete without.indexes; + else without.indexes = kept; + return without as T; +} diff --git a/packages/objectql/src/sync-provenance-write.ts b/packages/objectql/src/sync-provenance-write.ts new file mode 100644 index 00000000000..6318485e96c --- /dev/null +++ b/packages/objectql/src/sync-provenance-write.ts @@ -0,0 +1,119 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4] "Nothing writes the `_sync_` columns except the pull. … A + * `_sync_` column in any write except the pull's is refused by name, whatever + * the caller's context." + * + * The five provenance columns (`SYNC_PROVENANCE_COLUMNS`, + * `@objectstack/spec/data`) are injected on a `managedBy: 'synced'` object. + * A member cannot write such an object at all (the engine write guard refuses + * every generic write on the bucket), but a system-context write can: a + * declared action's body runs as the system and may write a synced row's + * mapped fields (ADR-0153 D4). `readonly: true` does not stop it, because the + * static `readonly` strip exempts `isSystem`. So the engine judges the + * caller's payload by NAME, before anything else runs: a key starting + * `_sync_` is refused unless the write carries the pull's mark. + * + * ## The mark, and why it reaches exactly one write + * + * {@link SYNC_PULL_WRITE} is a symbol key on the write's CONTEXT. The pull + * writes through the import runner and the protocol's data door, which hand + * the context down by spreading it, so a context key is the one carrier that + * reaches the engine (an engine option does not cross the protocol). A symbol, + * so no context a door builds from a request can carry it (JSON has no + * symbols); `Symbol.for`, so every bundle of this package names one key, the + * shape `SUMMARY_RECOMPUTE_WRITE` takes for the same reason. + * + * A context key would otherwise travel on: a hook's `ctx.api` write carries + * the context it was handed. {@link refuseSyncProvenanceWrite} therefore + * CONSUMES the mark — the engine continues with a copy of the context without + * it — so a hook or flow the pull's write triggers writes as any other system + * caller, and is refused like one. + */ + +import { SYNC_PROVENANCE_PREFIX } from '@objectstack/spec/data'; + +/** The pull's mark on its write context (see the module header). */ +export const SYNC_PULL_WRITE: unique symbol = Symbol.for('objectstack.objectql.syncPullWrite'); + +/** + * The context the sync-in pull writes with: `context` plus {@link SYNC_PULL_WRITE}. + * Only the pull calls it (`@objectstack/service-automation`). + */ +export function markSyncPullWrite(context: C): C & { [SYNC_PULL_WRITE]: true } { + return { ...context, [SYNC_PULL_WRITE]: true as const }; +} + +/** + * The code a write naming a `_sync_` column without the pull's mark is refused + * with. Registered in `ERROR_CODE_LEDGER` under `@objectstack/objectql`. + */ +export const SYNC_PROVENANCE_WRITE_REFUSED_CODE = 'ERR_SYNC_PROVENANCE_WRITE_REFUSED' as const; + +/** + * A write named a `_sync_` provenance column and is not the pull's. Nothing was + * written: the refusal runs before the middleware, the defaults and the hooks. + * 400, since the payload itself is what is refused, whoever sent it. + * + * Identified by `code` rather than `instanceof`, the convention every engine + * error here follows. + */ +export class SyncProvenanceWriteRefusedError extends Error { + readonly code = SYNC_PROVENANCE_WRITE_REFUSED_CODE; + readonly status = 400; + /** The same number under ADR-0112 D5's spelling. */ + readonly httpStatus = 400; + + constructor( + public readonly object: string, + public readonly fields: string[], + public readonly operation: 'insert' | 'update', + ) { + super( + `Cannot ${operation} '${object}': ${fields.map((f) => `'${f}'`).join(', ')} ${fields.length === 1 ? 'is a' : 'are'} ` + + `sync-in provenance column${fields.length === 1 ? '' : 's'}, which only the sync-in pull writes (ADR-0153 D4), ` + + 'whatever the caller\'s context. Leave the _sync_ columns out of the write: the next pull of the mapping ' + + 'stamps them.', + ); + this.name = 'SyncProvenanceWriteRefusedError'; + } +} + +/** The `_sync_` keys a payload (one row or several) carries, in first-seen order. */ +function syncKeysOf(data: unknown): string[] { + const rows = Array.isArray(data) ? data : [data]; + const found: string[] = []; + for (const row of rows) { + if (row === null || typeof row !== 'object') continue; + for (const key of Object.keys(row)) { + if (key.startsWith(SYNC_PROVENANCE_PREFIX) && !found.includes(key)) found.push(key); + } + } + return found; +} + +/** + * Judge one write's caller payload and consume the pull's mark. + * + * Throws {@link SyncProvenanceWriteRefusedError} when the payload names a + * `_sync_` key and the context carries no {@link SYNC_PULL_WRITE}. Otherwise + * returns the context the engine continues with: the same reference when no + * mark was present, a copy without the mark when one was. + */ +export function refuseSyncProvenanceWrite( + object: string, + data: unknown, + context: C, + operation: 'insert' | 'update', +): C { + const marked = context !== null && typeof context === 'object' + && (context as Record)[SYNC_PULL_WRITE] === true; + if (!marked) { + const keys = syncKeysOf(data); + if (keys.length > 0) throw new SyncProvenanceWriteRefusedError(object, keys, operation); + return context; + } + const { [SYNC_PULL_WRITE]: _consumed, ...rest } = context as Record; + return rest as C; +} diff --git a/packages/services/service-automation/src/connector-pull.ts b/packages/services/service-automation/src/connector-pull.ts index 0e84c8b8954..8586199df18 100644 --- a/packages/services/service-automation/src/connector-pull.ts +++ b/packages/services/service-automation/src/connector-pull.ts @@ -82,6 +82,8 @@ import { } from './connector-input-schema.js'; import { ConnectorPullError, type ConnectorPullRefusalReason } from './pull-refusal.js'; import { pullDatasourceSource, type DatasourcePullResult } from './datasource-pull.js'; +import { markSyncPullWrite } from '@objectstack/objectql'; +import { carriesSyncProvenanceColumns, mappedSyncProvenanceTarget, stampSyncProvenance } from './sync-provenance-stamp.js'; import { SYNC_RUN_OBJECT, type SyncRunCounts, @@ -774,6 +776,25 @@ async function pullOnce( schema = await protocol.getObjectSchema(objectName, environmentId); } } catch { /* judged by nobody, coerced as pass-through — the door's rule */ } + // [ADR-0153 D4] The provenance columns are the pull's to stamp, never a + // mapping's to write. A `synced` target carries them (the plan injects + // them); one that withholds every injected column (`systemFields: false`) + // cannot record what wrote its rows, and is refused like the datasource + // pull refuses it. A target of another bucket is refused at build (a + // sourced mapping targets a `synced` object) and gets no stamp here. + const mappedSync = mappedSyncProvenanceTarget(artifact.fieldMapping); + if (mappedSync) { + return refuse('VALIDATION_ERROR', 400, 'mapping_target_refused', + `Mapping "${mappingName}": fieldMapping writes '${mappedSync}', a sync-in provenance column the pull stamps ` + + 'itself (ADR-0153 D4); remove that entry.'); + } + const stampsProvenance = carriesSyncProvenanceColumns(schema); + if (!stampsProvenance && isPlainObject(schema) && schema.managedBy === 'synced') { + return refuse('VALIDATION_ERROR', 400, 'mapping_target_refused', + `Mapping "${mappingName}": targetObject '${objectName}' carries no _sync_ provenance columns (it declares ` + + 'systemFields: false, which withholds every injected column), so a pull cannot record which mapping and ' + + 'run wrote a row. Remove systemFields: false from the synced target.'); + } const refusedTarget = refuseUnknownMappingTargets(artifact, objectName, schema); if (refusedTarget) return refuseWith(refusedTarget, 'mapping_target_refused'); @@ -876,12 +897,21 @@ async function pullOnce( }); if (!applied.ok) return refuseWith(applied, 'mapping_apply_refused'); + // [ADR-0153 D4] Stamped onto a `synced` target, and written with the + // pull's mark — the one context the engine admits a `_sync_` column from — + // as the system when the caller handed no context: the columns are + // `readonly`, which only a system write keeps. + const rows = stampsProvenance + ? stampSyncProvenance(applied.rows, matchFields, { + mapping: mappingName, runId: run.id, pulledAt: new Date().toISOString(), + }) + : applied.rows; const summary = await runImport({ p: protocol, objectName, environmentId, - context, - rows: applied.rows as Array>, + context: stampsProvenance ? markSyncPullWrite(context ?? { isSystem: true }) : context, + rows: rows as Array>, metaMap: buildFieldMetaMap(schema), writeMode, matchFields, diff --git a/packages/services/service-automation/src/datasource-pull.ts b/packages/services/service-automation/src/datasource-pull.ts index 9438ddd3bb6..09bd9a7c767 100644 --- a/packages/services/service-automation/src/datasource-pull.ts +++ b/packages/services/service-automation/src/datasource-pull.ts @@ -77,7 +77,7 @@ import { type ImportRunSummary, type MappingArtifactLike, } from '@objectstack/core'; -import { needsExternalDriverFloor, resolveExternalRowCap } from '@objectstack/objectql'; +import { markSyncPullWrite, needsExternalDriverFloor, resolveExternalRowCap } from '@objectstack/objectql'; import { EXTERNAL_SCOPE_REMEDY, externalOrganizationScopeOf } from '@objectstack/core'; import { postureEnforcesWall } from '@objectstack/spec/security'; import { resolveQueryReadLimits, resolveTenancyPosture } from '@objectstack/types'; @@ -97,6 +97,7 @@ import { // cycle of call-time references only, which neither module evaluates at load. import { refuseBlankMatchKeys } from './connector-pull.js'; import { ConnectorPullError, type ConnectorPullRefusalReason } from './pull-refusal.js'; +import { carriesSyncProvenanceColumns, mappedSyncProvenanceTarget, stampSyncProvenance } from './sync-provenance-stamp.js'; /** A datasource source's pull: the federated object, its read path and the window positions. */ export interface DatasourcePullResult { @@ -218,6 +219,21 @@ export async function pullDatasourceSource( + `${target.managedBy === undefined ? 'unset' : `'${String(target.managedBy)}'`}). A pulled copy is read-only ` + "to members, so a member's edit is never kept or lost silently by the next pull; declare managedBy: 'synced' on it."); } + // [ADR-0153 D4] The provenance columns are the pull's to stamp, never a + // mapping's to write; and a target without them (`systemFields: false` + // withholds every injected column) cannot record what wrote its rows. + const mappedSync = mappedSyncProvenanceTarget(artifact.fieldMapping); + if (mappedSync) { + return invalid('mapping_target_refused', + `fieldMapping writes '${mappedSync}', a sync-in provenance column the pull stamps itself (ADR-0153 D4); ` + + 'remove that entry.'); + } + if (!carriesSyncProvenanceColumns(target)) { + return invalid('mapping_target_refused', + `targetObject '${targetObject}' carries no _sync_ provenance columns (it declares systemFields: false, which ` + + 'withholds every injected column), so a pull cannot record which mapping and run wrote a row. Remove ' + + "systemFields: false from the synced target."); + } const refusedTarget = refuseUnknownMappingTargets(artifact, targetObject, target); if (refusedTarget) { return refuse(refusedTarget.code, refusedTarget.status, 'mapping_target_refused', `Mapping "${mapping}": ${refusedTarget.error}`); @@ -342,17 +358,25 @@ export async function pullDatasourceSource( const summary = emptySummary(); const trimWhitespace = true; const metaMap = buildFieldMetaMap(target); + // [ADR-0153 D4] The writes carry the pull's mark, the one context the + // engine admits a `_sync_` column from, and run as the system when the + // caller handed no context (as the reads do): the provenance columns are + // `readonly`, which only a system write keeps. + const writeContext = markSyncPullWrite(context ?? { isSystem: true }); const write = async (rows: Rec[]): Promise => { const applied = applyMappingToRows(rows, artifact, { objectSchema: target, trimWhitespace }); if (!applied.ok) { return refuse(applied.code, applied.status, 'mapping_apply_refused', `Mapping "${mapping}": ${applied.error}`); } + const stamped = stampSyncProvenance(applied.rows, matchFields, { + mapping, runId: run.id, pulledAt: new Date().toISOString(), + }); const ran = await runImport({ p: protocol, objectName: targetObject, environmentId, - context, - rows: applied.rows as Array>, + context: writeContext, + rows: stamped as Array>, metaMap, writeMode: 'upsert', matchFields, diff --git a/packages/services/service-automation/src/sync-provenance-stamp.ts b/packages/services/service-automation/src/sync-provenance-stamp.ts new file mode 100644 index 00000000000..51519768eda --- /dev/null +++ b/packages/services/service-automation/src/sync-provenance-stamp.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4] The provenance a sync-in pull stamps on every row it writes, + * onto the `_sync_` columns the injected-columns plan gives a + * `managedBy: 'synced'` object (`SYNC_PROVENANCE_COLUMNS`, + * `@objectstack/spec/data`): + * + * | Column | Written | + * |:--|:--| + * | `_sync_source` | the mapping's name | + * | `_sync_external_id` | the row's key in the source, as text ({@link encodeSyncExternalId}) | + * | `_sync_pulled_at` | when this write was made | + * | `_sync_run_id` | the `sys_sync_run` row of this pull, or empty when no ledger keeps the run | + * | `_sync_deleted_at` | nothing yet: D3's mark, stamped by the delete marking when it lands | + * + * Both pulls (the connector source and the datasource source) stamp through + * {@link stampSyncProvenance}, after the mapping has projected the rows and + * before the import runner writes them, and write with the pull's mark + * (`markSyncPullWrite`, `@objectstack/objectql`): the engine refuses a + * `_sync_` column in any other write, whatever its context. + */ + +import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_PREFIX } from '@objectstack/spec/data'; + +type Rec = Record; + +const [SYNC_SOURCE, SYNC_EXTERNAL_ID, SYNC_PULLED_AT, SYNC_RUN_ID] = SYNC_PROVENANCE_COLUMNS; + +const isPlainObject = (v: unknown): v is Rec => v !== null && typeof v === 'object' && !Array.isArray(v); + +/** Does the target object carry the provenance columns a pull stamps? */ +export function carriesSyncProvenanceColumns(target: unknown): boolean { + const fields = isPlainObject(target) && isPlainObject(target.fields) ? target.fields : undefined; + return fields !== undefined && [SYNC_SOURCE, SYNC_EXTERNAL_ID, SYNC_PULLED_AT, SYNC_RUN_ID].every((f) => fields[f] !== undefined); +} + +/** + * The first `fieldMapping` target that names a `_sync_` column, or `undefined`. + * A mapping may not write a provenance column: the pull stamps them, and the + * injected columns now exist on the target, so the import door's own + * unknown-target check no longer refuses one. + */ +export function mappedSyncProvenanceTarget(fieldMapping: ReadonlyArray<{ target?: unknown } | undefined>): string | undefined { + for (const entry of fieldMapping) { + const targets = Array.isArray(entry?.target) ? entry.target : [entry?.target]; + for (const t of targets) { + if (typeof t === 'string' && t.startsWith(SYNC_PROVENANCE_PREFIX)) return t; + } + } + return undefined; +} + +/** One key value, spelled as text; `undefined` for a blank value. */ +function spellKeyValue(value: unknown): string | undefined { + if (value === null || value === undefined) return undefined; + if (typeof value === 'string') { + // The pulls write with `trimWhitespace: true`, so the runner matches on the + // trimmed value; the key is spelled as it is matched. + const trimmed = value.trim(); + return trimmed === '' ? undefined : trimmed; + } + if (typeof value === 'number' || typeof value === 'bigint' || typeof value === 'boolean') return String(value); + if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString(); + return JSON.stringify(value); +} + +/** + * [ADR-0153 D4, open question "a composite `upsertKey` written as + * `_sync_external_id` text: the encoding, and an order that stays stable"] + * The row's key in the source, as text. + * + * - `values` are the values the mapping copies onto the `upsertKey` fields, in + * the order `upsertKey` declares them. For a `none` or `lookup` copy (the + * lookup resolves after this point) that is the value the source sent. + * - One field: its value spelled as text (a string trimmed, a number, bigint + * or boolean by `String`, a date as ISO 8601, anything else as JSON). + * - Several fields: a JSON array of those spellings, in `upsertKey` order. The + * order is the author's declaration, so it is stable for as long as the + * mapping is; it is never sorted, since two fields' values are not + * interchangeable. + * - Any blank key value: `undefined`. Such a row is not written (the pulls + * skip a blank match key and count it refused), so no key is stamped. + * + * Within one mapping the arity is fixed, so the one-field spelling and the + * array spelling never meet on rows of the same `_sync_source`. + */ +export function encodeSyncExternalId(values: readonly unknown[]): string | undefined { + if (values.length === 0) return undefined; + const spelled: string[] = []; + for (const value of values) { + const s = spellKeyValue(value); + if (s === undefined) return undefined; + spelled.push(s); + } + return spelled.length === 1 ? spelled[0] : JSON.stringify(spelled); +} + +/** What a pull stamps: the mapping, the run, and the write's time. */ +export interface SyncProvenanceStamp { + mapping: string; + /** The `sys_sync_run` id, when a ledger keeps the run. */ + runId: string | undefined; + /** ISO 8601; one value per batch the pull writes. */ + pulledAt: string; +} + +/** + * The mapped rows, each with its provenance columns set. Returns new row + * objects; the stamp wins over anything the mapping produced under those + * names (none can, since {@link mappedSyncProvenanceTarget} refuses one). + */ +export function stampSyncProvenance( + rows: ReadonlyArray, + matchFields: readonly string[], + stamp: SyncProvenanceStamp, +): Rec[] { + return rows.map((row) => { + const externalId = encodeSyncExternalId(matchFields.map((f) => row[f])); + return { + ...row, + [SYNC_SOURCE]: stamp.mapping, + ...(externalId !== undefined ? { [SYNC_EXTERNAL_ID]: externalId } : {}), + [SYNC_PULLED_AT]: stamp.pulledAt, + [SYNC_RUN_ID]: stamp.runId ?? null, + }; + }); +} diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 1e80bd92b0d..fc392d810c2 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -950,6 +950,13 @@ export const ERROR_CODE_LEDGER = { // any standard member: it is neither the client's bad input (the caller is // server-side automation) nor a missing precondition on a request. 'ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED', + // [ADR-0153 D4] A write named a `_sync_` provenance column of a `synced` + // object and is not the sync-in pull's. 400, judged on the caller's + // payload before the middleware, the defaults or a hook run, so nothing is + // written (`SyncProvenanceWriteRefusedError`, `sync-provenance-write.ts`). + // Refused whatever the caller's context, `isSystem` included: the pull is + // the columns' only writer. + 'ERR_SYNC_PROVENANCE_WRITE_REFUSED', // [#8846] `transaction({ require: true })` on a driver with no // `beginTransaction` — thrown BEFORE the callback runs, so nothing has // been written (`TransactionUnsupportedError`, `transaction-errors.ts`; diff --git a/packages/spec/src/data/injected-system-column-provenance.ts b/packages/spec/src/data/injected-system-column-provenance.ts index d2c1b0d1071..585aad250fe 100644 --- a/packages/spec/src/data/injected-system-column-provenance.ts +++ b/packages/spec/src/data/injected-system-column-provenance.ts @@ -39,7 +39,7 @@ */ import { AUDIT_PROVENANCE_FIELDS, type AuditProvenanceField } from './field-group-layout'; -import { resolveInjectedSystemColumns } from './injected-system-columns'; +import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS, type SyncProvenanceColumn } from './injected-system-columns'; import { SystemFieldName } from '../system/constants/system-names'; /** @@ -188,6 +188,72 @@ export const QUEUE_FIELD_DEF: Readonly> = { 'claim; with an owner it is the home queue a release returns the record to.', }; +/** + * [ADR-0153 D4] The five sync-in provenance columns of a `managedBy: 'synced'` + * object, keyed by {@link SYNC_PROVENANCE_COLUMNS} (the `satisfies` clause is + * the sync, as on {@link AUDIT_FIELD_DEFS}). + * + * `readonly: true` and `system: true`: the pull, which writes as the system, + * is their only writer, and the engine refuses any other write that names one + * whatever its context. `hidden: true`: they are the kernel's operational + * record of a copy, readable and filterable wherever the row is, never a + * field a default layout needs. Text, not lookups: a run record is swept on + * its own retention window and must never cascade into data. + */ +export const SYNC_PROVENANCE_FIELD_DEFS = { + _sync_source: { + type: 'text', + label: 'Sync Source', + required: false, + hidden: true, + readonly: true, + system: true, + description: 'The mapping whose pull wrote this row (ADR-0153 D4). Written by the pull only.', + }, + _sync_external_id: { + type: 'text', + label: 'Sync External ID', + required: false, + hidden: true, + readonly: true, + system: true, + description: + "The row's key in the source, as text: the source value of the mapping's upsertKey, or for a key of several " + + 'fields a JSON array of their values in upsertKey order (ADR-0153 D4). Written by the pull only.', + }, + _sync_pulled_at: { + type: 'datetime', + label: 'Sync Pulled At', + required: false, + hidden: true, + readonly: true, + system: true, + description: 'When a pull last wrote this row (ADR-0153 D4). Written by the pull only.', + }, + _sync_run_id: { + type: 'text', + label: 'Sync Run', + required: false, + hidden: true, + readonly: true, + system: true, + description: + 'The sys_sync_run row of the pull that last wrote this row, as text, never a lookup (ADR-0153 D4, D7). ' + + 'Empty when the pull kept no run record. Written by the pull only.', + }, + _sync_deleted_at: { + type: 'datetime', + label: 'Sync Deleted At', + required: false, + hidden: true, + readonly: true, + system: true, + description: + 'When a pull found this row gone from the source (ADR-0153 D3). Not written yet: the delete marking that ' + + 'stamps it has not landed, so it is empty on every row.', + }, +} satisfies Record>; + /** * The injected columns THIS object carries, as `name -> definition`. * @@ -210,6 +276,7 @@ export function injectedSystemColumnDefs(def: unknown): Record | readonly string[] | undefined, @@ -113,7 +149,8 @@ export type InjectedSystemColumnName = | (typeof AUDIT_PROVENANCE_FIELDS)[number] | typeof OWNER_COLUMN | typeof OWNING_BUSINESS_UNIT_COLUMN - | typeof QUEUE_COLUMN; + | typeof QUEUE_COLUMN + | SyncProvenanceColumn; /** * Which system columns an object carries, as the four independent decisions the @@ -140,6 +177,11 @@ export interface InjectedSystemColumnPlan { * no owning person. */ queue: boolean; + /** + * The {@link SYNC_PROVENANCE_COLUMNS} — [ADR-0153 D4] on a + * `managedBy: 'synced'` object only, the copy a sync-in pull writes. + */ + sync: boolean; /** * Every column addressable on this object without being authored — the * columns the flags above select, plus the driver-provisioned primary key. @@ -169,6 +211,7 @@ export interface InjectedSystemColumnPlan { * | `ownership: 'org' \| 'none'` | no ownership anchors (either tier) | * | `ownership: 'business_unit'` | `owning_business_unit_id` but NOT `owner_id` or `queue` | * | `ownership: 'user'` / omitted | both ownership anchors, and `queue` | + * | `managedBy: 'synced'` | the five `_sync_` provenance columns (ADR-0153 D4) | * * The ownership rows are a POSITIVE list, not a deny-list, for the reason * ADR-0117 D1 / #5677 record at the injection site: under a deny-list a NEW @@ -206,7 +249,7 @@ export function resolveInjectedSystemColumns( // even on the two "nothing is injected" rows below. const names = new Set([PRIMARY_KEY_COLUMN]); const nothing: InjectedSystemColumnPlan = { - tenant: false, audit: false, owner: false, owningBusinessUnit: false, queue: false, names, + tenant: false, audit: false, owner: false, owningBusinessUnit: false, queue: false, sync: false, names, }; // 1. Hard opt-out at object level (e.g. seed/migration tables). @@ -244,12 +287,17 @@ export function resolveInjectedSystemColumns( // [ADR-0142 D3] The queue column rides with the owner anchor, never apart // from it: "sits in Q" is `queue == Q AND owner_id IS NULL`. const queue = owner; + // [ADR-0153 D4] The provenance columns ride with the bucket that names a + // pulled copy, and with nothing else: the plan's two hard opt-outs above + // still withhold them, and a pull refuses a target that lacks them. + const sync = managedBy === 'synced'; if (tenant) names.add(TENANT_SCOPE_COLUMN); if (audit) for (const f of AUDIT_PROVENANCE_FIELDS) names.add(f); if (owner) names.add(OWNER_COLUMN); if (owningBusinessUnit) names.add(OWNING_BUSINESS_UNIT_COLUMN); if (queue) names.add(QUEUE_COLUMN); + if (sync) for (const column of SYNC_PROVENANCE_COLUMNS) names.add(column); - return { tenant, audit, owner, owningBusinessUnit, queue, names }; + return { tenant, audit, owner, owningBusinessUnit, queue, sync, names }; } From 5943f23817ca8139d4040fd75825ec52c9f15551 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:21:54 +0000 Subject: [PATCH 2/6] test(objectql): pin the sync provenance columns, the stamp and the write refusal Tests for both pulls' stamping, the L852 external-id spelling, the plan/registry parity cases, and the served-document diagnostics; docs, liveness notes, changeset and regenerated spec artifacts. A synced target with systemFields: false is written unstamped rather than refused. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- .changeset/32062-sync-provenance-columns.md | 21 ++ content/docs/automation/jobs.mdx | 15 + content/docs/data-modeling/objects.mdx | 2 +- .../docs/references/api/automation-api.mdx | 3 +- content/docs/references/api/contract.mdx | 3 +- .../docs/references/api/error-code-ledger.mdx | 1 + ...iagnostics.sync-provenance-columns.test.ts | 58 ++++ .../injected-system-columns-parity.test.ts | 5 + packages/objectql/src/sync-provenance.test.ts | 259 ++++++++++++++++++ .../src/connector-pull.test.ts | 60 +++- .../service-automation/src/connector-pull.ts | 14 +- .../src/datasource-pull.test.ts | 70 +++++ .../service-automation/src/datasource-pull.ts | 20 +- .../src/sync-provenance-stamp.test.ts | 78 ++++++ .../src/sync-provenance-stamp.ts | 22 +- packages/spec/api-surface/data.json | 4 + packages/spec/export-origins/data.json | 4 + packages/spec/liveness/mapping.json | 2 +- packages/spec/liveness/object.json | 2 +- .../data/injected-system-column-provenance.ts | 3 +- .../src/data/injected-system-columns.test.ts | 61 ++++- 21 files changed, 668 insertions(+), 39 deletions(-) create mode 100644 .changeset/32062-sync-provenance-columns.md create mode 100644 packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts create mode 100644 packages/objectql/src/sync-provenance.test.ts create mode 100644 packages/services/service-automation/src/sync-provenance-stamp.test.ts diff --git a/.changeset/32062-sync-provenance-columns.md b/.changeset/32062-sync-provenance-columns.md new file mode 100644 index 00000000000..332bd7a1c58 --- /dev/null +++ b/.changeset/32062-sync-provenance-columns.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/metadata-protocol': patch +'@objectstack/service-automation': patch +--- + +feat(objectql)!: every row a sync-in pull writes records where it came from, and nothing else may write those columns + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none (no skills/ page names the `_sync_` columns or the synced bucket's injected columns) + + + +ADR-0153 D4, the provenance half (#32062, slice 5). + +- **Five `_sync_` columns on every `managedBy: 'synced'` object.** `resolveInjectedSystemColumns` (`@objectstack/spec/data`) now plans `_sync_source`, `_sync_external_id`, `_sync_pulled_at`, `_sync_run_id` and `_sync_deleted_at` on that bucket only (`plan.sync`), and the registry injects them as hidden, read-only system columns, with an index on (`organization_id`, `_sync_source`, `_sync_external_id`) placed after the tenant index. New exports: `SYNC_PROVENANCE_COLUMNS`, `SYNC_PROVENANCE_PREFIX`, `SyncProvenanceColumn`, `SYNC_PROVENANCE_FIELD_DEFS`. A synced object that declares `systemFields: false` gets none of them. +- **Both pulls stamp them.** A connector pull and a datasource pull write `_sync_source` (the mapping), `_sync_external_id` (the row's `upsertKey` value as text; a key of several fields is a JSON array of the values in `upsertKey` order, such as `["10","A-1"]`), `_sync_pulled_at` and `_sync_run_id` (the `sys_sync_run` row; not written when no run ledger is composed) on every row. `_sync_deleted_at` exists but stays empty until delete marking (D3) lands. A mapping whose `fieldMapping` targets a `_sync_` column is refused with `400 mapping_target_refused` when it runs (it was refused before as an unknown target). +- **BREAKING: a `_sync_` column in any other write is refused.** The engine refuses an insert or update naming a `_sync_` key with `400 ERR_SYNC_PROVENANCE_WRITE_REFUSED`, before middleware, defaults and hooks run, whatever the caller's context, `isSystem` included. Only the pull's own write is admitted (`markSyncPullWrite`, exported from `@objectstack/objectql` with `SYNC_PULL_WRITE`, `SyncProvenanceWriteRefusedError` and `SYNC_PROVENANCE_WRITE_REFUSED_CODE`). The mark is consumed by that write, so a hook or flow it triggers writes as any other system caller and is refused the same way. Fix: leave the `_sync_` columns out of the write; the next pull of the mapping stamps them. +- Load-time diagnostics leave the injected `_sync_` columns out when they judge a served synced object, so it is not flagged for the reserved prefix; an author field under a `_sync_` name is still refused. diff --git a/content/docs/automation/jobs.mdx b/content/docs/automation/jobs.mdx index 2ad26f76b78..322ffcf87b4 100644 --- a/content/docs/automation/jobs.mdx +++ b/content/docs/automation/jobs.mdx @@ -315,6 +315,21 @@ export const OrdersPullJob = defineJob({ now reads another source object or field, or writes another target, read from `watermark.start`; a run never reads below it. The delete keys change nothing yet, and `os validate` says so. +- **Every row says where it came from.** A `synced` object carries five + hidden, read-only columns the platform adds to it, beside the tenant and audit + columns, with an index on (`organization_id`, `_sync_source`, + `_sync_external_id`). Every row a pull writes gets `_sync_source` (the + mapping's name), `_sync_external_id` (the row's `upsertKey` value as text; for + a key of several fields, a JSON array of their values in the order `upsertKey` + lists them, such as `["10","A-1"]`), `_sync_pulled_at` (when it was written) + and `_sync_run_id` (the pull's `sys_sync_run` row; not written when no run + record is kept). `_sync_deleted_at` is there but empty on every row: delete + marking has not landed yet. Nothing else writes these columns: a write that + names a `_sync_` column is refused with `400 + ERR_SYNC_PROVENANCE_WRITE_REFUSED`, a system-context one included, and a + mapping whose `fieldMapping` targets one is refused when it runs. A `synced` + target that declares `systemFields: false` has none of these columns, and its + rows are written without them. - **How a run is recorded.** A pull the platform refuses — the mapping is gone, the job's package reaches no one mapping of that name, the connector is degraded, the input breaks the read action's declared `inputSchema`, the upstream answered `ok: false` — rejects, so the diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 915f4228c2f..4243eccfdb7 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -354,7 +354,7 @@ bare bucket string. | `system-data` | Platform-defined schema holding **admin/user-writable data** (RBAC link tables, preferences, messaging config). New / Edit / Delete / Export by default — **no CSV import**, which is opt-in per object; narrow the rest with `userActions`. | | `engine-owned` | Runtime rows a platform service owns end to end — generic CRUD hidden, exposed `['get', 'list']` only, **no user writes ever**. | | `append-only` | Immutable audit trail — View + Export only. | -| `synced` | Rows a scheduled pull copies from a connector or a federated source — View + Export only. The one bucket `userActions` cannot open a write on: a member's edit would be kept or overwritten by the next pull, so a change belongs in the source. The target of every mapping with a `connectorSource` or `datasourceSource`. | +| `synced` | Rows a scheduled pull copies from a connector or a federated source — View + Export only. The one bucket `userActions` cannot open a write on: a member's edit would be kept or overwritten by the next pull, so a change belongs in the source. The target of every mapping with a `connectorSource` or `datasourceSource`. The platform adds five hidden `_sync_` provenance columns that only the pull writes (see [Jobs](/docs/automation/jobs)). | | `better-auth` | Identity tables owned by the better-auth driver — generic user-context CRUD is suppressed; mutations flow through the auth API (sign-in, invite, reset). | **`engine-owned` vs. `system-data` (ADR-0103, #3355).** Both hold a diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index b599eb63394..956559f4bb7 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -425,7 +425,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +379 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +380 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -576,6 +576,7 @@ const result = AutomationApiErrorCode.parse(data); * `ERR_HOOK_TARGET_REBIND` * `ERR_READONLY_FIELD_REJECTED` * `ERR_SUMMARY_RECOMPUTE` +* `ERR_SYNC_PROVENANCE_WRITE_REFUSED` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` * `ERR_UNIT_CODE_REQUIRED` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 72315553631..1660e81c3fc 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +379 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +380 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -186,6 +186,7 @@ const result = ApiErrorSchema.parse(data); * `ERR_HOOK_TARGET_REBIND` * `ERR_READONLY_FIELD_REJECTED` * `ERR_SUMMARY_RECOMPUTE` +* `ERR_SYNC_PROVENANCE_WRITE_REFUSED` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` * `ERR_UNIT_CODE_REQUIRED` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index 572de2d1854..317cc7145ee 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -353,6 +353,7 @@ const result = ErrorCode.parse(data); * `ERR_HOOK_TARGET_REBIND` * `ERR_READONLY_FIELD_REJECTED` * `ERR_SUMMARY_RECOMPUTE` +* `ERR_SYNC_PROVENANCE_WRITE_REFUSED` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` * `ERR_UNIT_CODE_REQUIRED` diff --git a/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts b/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts new file mode 100644 index 00000000000..ce74d8efcfc --- /dev/null +++ b/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4] Load-time diagnostics judge a `managedBy: 'synced'` object as + * its author wrote it, never with the `_sync_` provenance columns the registry + * injected onto it. + * + * `ObjectSchema` reserves the `_sync_` prefix for author fields, and every read + * of a synced object serves the five injected columns. Judging the served copy + * would flag every synced object. Only a field that is exactly the platform's + * definition is left out; an author field with a `_sync_` name, or one that + * differs from the platform's in any key, is still judged and refused. + */ +import { describe, expect, it } from 'vitest'; +import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; +import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; + +const authored = () => ({ + name: 'erp_customer', + label: 'ERP customer', + managedBy: 'synced', + fields: { code: { name: 'code', type: 'text', label: 'Code' } }, +}); + +const served = () => { + const doc = authored() as Record; + for (const name of SYNC_PROVENANCE_COLUMNS) doc.fields[name] = { ...SYNC_PROVENANCE_FIELD_DEFS[name] }; + doc.indexes = [{ fields: ['organization_id', '_sync_source', '_sync_external_id'] }]; + return doc; +}; + +const syncPaths = (d: ReturnType) => + (d?.errors ?? []).map((e) => e.path).filter((p) => p.includes('_sync_')); + +describe('[ADR-0153 D4] diagnostics — the injected sync provenance columns', () => { + it('CONTROL: the authored synced object is clean', () => { + expect(computeMetadataDiagnostics('object', authored())).toEqual({ valid: true }); + }); + + it('the served copy, carrying the five injected columns, is judged clean too', () => { + expect(syncPaths(computeMetadataDiagnostics('object', served()))).toEqual([]); + expect(computeMetadataDiagnostics('object', served())?.valid).toBe(true); + }); + + it('an author field under a _sync_ name is still refused', () => { + const doc = authored() as Record; + doc.fields._sync_note = { name: '_sync_note', type: 'text', label: 'Note' }; + const d = computeMetadataDiagnostics('object', doc); + expect(d?.valid).toBe(false); + expect(syncPaths(d).length).toBeGreaterThan(0); + }); + + it('a _sync_ column that differs from the platform definition is judged as written', () => { + const doc = served(); + doc.fields._sync_source = { ...doc.fields._sync_source, readonly: false }; + expect(syncPaths(computeMetadataDiagnostics('object', doc)).length).toBeGreaterThan(0); + }); +}); diff --git a/packages/objectql/src/injected-system-columns-parity.test.ts b/packages/objectql/src/injected-system-columns-parity.test.ts index 8e89579d7c6..44ff24cf81e 100644 --- a/packages/objectql/src/injected-system-columns-parity.test.ts +++ b/packages/objectql/src/injected-system-columns-parity.test.ts @@ -46,6 +46,10 @@ const CASES: Array<[string, Record]> = [ ['sys_* namespace', { name: 'sys_thing', fields: fields() }], ["managedBy: 'platform'", { name: 'crm_contact', managedBy: 'platform', fields: fields() }], ["managedBy: 'better-auth'", { name: 'crm_contact', managedBy: 'better-auth', fields: fields() }], + // [ADR-0153 D4] The five `_sync_` provenance columns, on this bucket only. + ["managedBy: 'synced'", { name: 'crm_contact', managedBy: 'synced', fields: fields() }], + ["managedBy: 'synced' + tenancy.enabled: false", { name: 'crm_contact', managedBy: 'synced', tenancy: { enabled: false }, fields: fields() }], + ["managedBy: 'synced' + systemFields: false", { name: 'crm_contact', managedBy: 'synced', systemFields: false, fields: fields() }], ['systemFields: false', { name: 'crm_contact', systemFields: false, fields: fields() }], ['systemFields.tenant: false', { name: 'crm_contact', systemFields: { tenant: false }, fields: fields() }], ['systemFields.audit: false', { name: 'crm_contact', systemFields: { audit: false }, fields: fields() }], @@ -95,6 +99,7 @@ describe('[#5378] resolveInjectedSystemColumns ↔ applySystemFields parity', () expect(plan.owner, `${label}: owner`).toBe(injected.has('owner_id') || declared.has('owner_id')); expect(plan.owningBusinessUnit, `${label}: owningBusinessUnit`) .toBe(injected.has('owning_business_unit_id') || declared.has('owning_business_unit_id')); + expect(plan.sync, `${label}: sync`).toBe(injected.has('_sync_source') || declared.has('_sync_source')); } }); diff --git a/packages/objectql/src/sync-provenance.test.ts b/packages/objectql/src/sync-provenance.test.ts new file mode 100644 index 00000000000..8dc4c8e03f6 --- /dev/null +++ b/packages/objectql/src/sync-provenance.test.ts @@ -0,0 +1,259 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4] The sync-in provenance columns on a `managedBy: 'synced'` + * object, as the registry and the engine hold them: + * + * - `applySystemFields` injects the five `_sync_` columns the spec's plan + * names, and the (`organization_id`, `_sync_source`, `_sync_external_id`) + * index after the tenant index; its write-side inverse takes the index off + * again so a served document round-trips; + * - the engine refuses a `_sync_` column in any write but the pull's, + * `isSystem` included, and the pull's mark reaches exactly the one write it + * is put on — a hook's `ctx.api` write inside it is refused like any other. + * + * A REAL {@link ObjectQL} over a minimal stub driver, the shape + * `engine-audit-anchor-write.test.ts` uses. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; +import { applySystemFields } from './registry.js'; +import { provisionSyncProvenanceIndex, stripProvisionedSyncProvenanceIndexFrom } from './sync-provenance-index.js'; +import { + SYNC_PROVENANCE_WRITE_REFUSED_CODE, + SYNC_PULL_WRITE, + markSyncPullWrite, +} from './sync-provenance-write.js'; + +const SYNCED = { + name: 'erp_customer', + label: 'ERP customer', + managedBy: 'synced', + sharingModel: 'read', + fields: { + code: { name: 'code', label: 'Code', type: 'text' as const }, + title: { name: 'title', label: 'Title', type: 'text' as const }, + }, +}; + +const PLAIN = { + name: 'crm_note', + label: 'Note', + fields: { title: { name: 'title', label: 'Title', type: 'text' as const } }, +}; + +function makeStubDriver() { + const stores = new Map>>(); + const storeFor = (obj: string) => { + let s = stores.get(obj); + if (!s) { s = new Map(); stores.set(obj, s); } + return s; + }; + let nextId = 0; + const calls = { create: 0, update: 0 }; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k.startsWith('$')) continue; + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + if ((row[k] ?? null) !== (expected ?? null)) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async execute() { return null; }, + async find(object: string, ast: any) { + return Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + calls.create += 1; + nextId += 1; + const id = (data.id as string) ?? `r_${nextId}`; + const row: Record = { ...data, id }; + storeFor(object).set(id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + calls.update += 1; + const s = storeFor(object); + const cur = s.get(id); + if (!cur) return null; + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return updated; + }, + async upsert(object: string, data: Record) { + const id = data.id as string | undefined; + if (id && storeFor(object).has(id)) return this.update(object, id, data); + return this.create(object, data); + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, + async bulkDelete() {}, + async updateMany() { return 0; }, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, stores, calls }; +} + +describe('[ADR-0153 D4] applySystemFields — the provenance columns and their index on a synced object', () => { + it('injects the five _sync_ columns, each the platform definition', () => { + const out: any = applySystemFields(SYNCED as any, { multiTenant: false }); + for (const name of SYNC_PROVENANCE_COLUMNS) { + expect(out.fields[name]).toEqual(SYNC_PROVENANCE_FIELD_DEFS[name]); + expect(out.fields[name]).toMatchObject({ readonly: true, system: true, hidden: true }); + } + }); + + it('CONTROL: an object of no other bucket gets none of them', () => { + const out: any = applySystemFields(PLAIN as any, { multiTenant: true }); + for (const name of SYNC_PROVENANCE_COLUMNS) expect(out.fields[name]).toBeUndefined(); + expect(out.fields.owner_id).toBeDefined(); + }); + + it('withholds them where the plan withholds every column (systemFields: false)', () => { + const out: any = applySystemFields({ ...SYNCED, systemFields: false } as any, { multiTenant: true }); + for (const name of SYNC_PROVENANCE_COLUMNS) expect(out.fields[name]).toBeUndefined(); + expect(out.indexes).toBeUndefined(); + }); + + it('appends the provenance index LAST, after the tenant index, led by the tenant column', () => { + const out: any = applySystemFields(SYNCED as any, { multiTenant: true }); + expect(out.indexes).toEqual([ + { fields: ['organization_id'] }, + { fields: ['organization_id', '_sync_source', '_sync_external_id'] }, + ]); + }); + + it('drops the tenant column from the index when the object has none', () => { + const out: any = applySystemFields({ ...SYNCED, tenancy: { enabled: false } } as any, { multiTenant: true }); + expect(out.fields.organization_id).toBeUndefined(); + expect(out.indexes).toEqual([{ fields: ['_sync_source', '_sync_external_id'] }]); + }); + + it('keeps an author index of the same columns instead of adding a second one', () => { + const declared = { ...SYNCED, indexes: [{ fields: ['organization_id', '_sync_source', '_sync_external_id'], name: 'mine' }] }; + const out: any = applySystemFields(declared as any, { multiTenant: false }); + expect(out.indexes).toEqual(declared.indexes); + }); + + it('is idempotent: a second pass over the registered schema adds nothing', () => { + const once: any = applySystemFields(SYNCED as any, { multiTenant: true }); + expect(provisionSyncProvenanceIndex(once)).toBe(once); + }); + + it('the write-side inverse takes the stamp off, and leaves the tenant stamp last for its own inverse', () => { + const served: any = applySystemFields(SYNCED as any, { multiTenant: true }); + const stripped: any = stripProvisionedSyncProvenanceIndexFrom(served); + expect(stripped.indexes).toEqual([{ fields: ['organization_id'] }]); + }); + + it('the inverse runs on a body whose injected columns are already gone (plan-gated)', () => { + const body = { ...SYNCED, indexes: [{ fields: ['organization_id', '_sync_source', '_sync_external_id'] }] }; + const stripped: any = stripProvisionedSyncProvenanceIndexFrom(body); + expect('indexes' in stripped).toBe(false); + }); + + it('CONTROL: the inverse keeps an author entry (a name) and any entry on another bucket', () => { + const named = { ...SYNCED, indexes: [{ fields: ['_sync_source', '_sync_external_id'], name: 'mine' }] }; + expect(stripProvisionedSyncProvenanceIndexFrom(named)).toBe(named); + const other = { ...PLAIN, indexes: [{ fields: ['_sync_source', '_sync_external_id'] }] }; + expect(stripProvisionedSyncProvenanceIndexFrom(other)).toBe(other); + }); +}); + +describe('[ADR-0153 D4] the engine refuses a _sync_ column in any write but the pull\'s', () => { + let engine: ObjectQL; + let rig: ReturnType; + const system = { isSystem: true }; + + beforeEach(async () => { + engine = new ObjectQL(); + rig = makeStubDriver(); + engine.registerDriver(rig.driver, true); + await engine.init(); + engine.registry.registerObject(SYNCED as any); + engine.registry.registerObject(PLAIN as any); + }); + + it('the registered synced object carries the columns and the index', () => { + const schema: any = engine.registry.getObject('erp_customer'); + for (const name of SYNC_PROVENANCE_COLUMNS) expect(schema.fields[name]).toBeDefined(); + expect(schema.indexes.at(-1).fields).toContain('_sync_external_id'); + }); + + it('refuses a system insert naming a _sync_ column, before the driver is asked', async () => { + const err: any = await engine + .insert('erp_customer', { code: 'C1', _sync_source: 'forged' }, { context: system } as any) + .catch((e) => e); + expect(err?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.status).toBe(400); + expect(err?.fields).toEqual(['_sync_source']); + expect(rig.calls.create).toBe(0); + }); + + it('refuses a system update naming a _sync_ column, before the driver is asked', async () => { + const row: any = await engine.insert('erp_customer', { code: 'C1' }, { context: system } as any); + const err: any = await engine + .update('erp_customer', { id: row.id, _sync_deleted_at: new Date().toISOString() }, { context: system } as any) + .catch((e) => e); + expect(err?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.status).toBe(400); + expect(rig.calls.update).toBe(0); + }); + + it('CONTROL: a system write of the mapped fields alone goes through', async () => { + const row: any = await engine.insert('erp_customer', { code: 'C1', title: 'Acme' }, { context: system } as any); + expect(row.title).toBe('Acme'); + }); + + it('admits the pull\'s marked write, and the stamps land', async () => { + const row: any = await engine.insert( + 'erp_customer', + { code: 'C1', _sync_source: 'erp_customers', _sync_external_id: 'C1' }, + { context: markSyncPullWrite(system) } as any, + ); + expect(row._sync_source).toBe('erp_customers'); + expect(row._sync_external_id).toBe('C1'); + const updated: any = await engine.update( + 'erp_customer', + { id: row.id, _sync_run_id: 'run_2' }, + { context: markSyncPullWrite(system) } as any, + ); + expect(updated._sync_run_id).toBe('run_2'); + }); + + it('consumes the mark: the hooks of the pull\'s write see a context without it', async () => { + const seen: unknown[] = []; + engine.registerHook('beforeInsert', async (ctx: any) => { + seen.push(ctx.input?.options?.context); + }, { object: 'erp_customer' }); + await engine.insert('erp_customer', { code: 'C1', _sync_source: 'm' }, { context: markSyncPullWrite(system) } as any); + expect(seen).toHaveLength(1); + const hookContext = seen[0] as Record; + expect(hookContext?.isSystem).toBe(true); + expect(SYNC_PULL_WRITE in hookContext).toBe(false); + }); + + it('a hook\'s ctx.api write inside the pull\'s write is refused like any other', async () => { + let nested: any; + engine.registerHook('beforeInsert', async (ctx: any) => { + nested = await ctx.api.object('erp_customer').insert({ code: 'X', _sync_source: 'forged' }).catch((e: unknown) => e); + }, { object: 'crm_note' }); + await engine.insert('crm_note', { title: 'n' }, { context: markSyncPullWrite(system) } as any); + expect(nested?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + }); +}); diff --git a/packages/services/service-automation/src/connector-pull.test.ts b/packages/services/service-automation/src/connector-pull.test.ts index 1991fdf2f74..329a990a697 100644 --- a/packages/services/service-automation/src/connector-pull.test.ts +++ b/packages/services/service-automation/src/connector-pull.test.ts @@ -24,6 +24,7 @@ import { type ConnectorPullDeps, type ConnectorPullRefusalReason, } from './connector-pull.js'; +import { SYNC_PULL_WRITE } from '@objectstack/objectql'; const silent = { debug() {}, info() {}, warn() {}, error() {} } as unknown as ConnectorPullDeps['logger']; @@ -67,6 +68,8 @@ function harness(opts: { stored?: Array>; /** The `inputSchema` the action declares on `GET /connectors`; absent ⇒ none declared. */ inputSchema?: Record; + /** The target `contact` as the protocol serves it; absent ⇒ {@link contactObject}. */ + object?: Record; } = {}): Harness { const writes: unknown[] = []; const handler = vi.fn(async () => (opts.result ?? { status: 200, ok: true, body: [] }) as Record); @@ -77,7 +80,7 @@ function harness(opts: { if (type === 'mapping' && mapping && name === (mapping as { name: string }).name) { return { type, name, item: mapping }; } - if (type === 'object' && name === 'contact') return { type, name, item: contactObject }; + if (type === 'object' && name === 'contact') return { type, name, item: opts.object ?? contactObject }; return undefined; }, async findData() { return { records: opts.stored ?? [] }; }, @@ -906,3 +909,58 @@ describe('[#31699] connector pull — the connector resolves from the mapping\'s expect(pulled).toEqual([BETA, BETA]); }); }); + +describe('[ADR-0153 D4] a connector pull stamps provenance on a synced target', () => { + const syncedContact = { ...contactObject, managedBy: 'synced' }; + const body = [{ id: 'c-1', name: 'Ada', updated_at: '2026-01-02' }, { id: 'c-2', name: 'Lin', updated_at: '2026-01-03' }]; + + it('every write carries the mapping, the source key and the write time, and no run column without a ledger, under the pull\'s mark', async () => { + const h = harness({ object: syncedContact, result: { status: 200, ok: true, body } }); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', context: { isSystem: true } }); + expect(h.writes).toHaveLength(2); + for (const [i, w] of (h.writes as Array<{ data: Record; context: Record }>).entries()) { + expect(w.data).toMatchObject({ _sync_source: 'crm_contacts', _sync_external_id: body[i]!.id }); + expect('_sync_run_id' in w.data).toBe(false); + expect(typeof w.data._sync_pulled_at).toBe('string'); + expect('_sync_deleted_at' in w.data).toBe(false); + expect(w.context[SYNC_PULL_WRITE]).toBe(true); + expect(w.context.isSystem).toBe(true); + } + }); + + it('a pull with no context writes as the system, so the read-only stamps are kept', async () => { + const h = harness({ object: syncedContact, result: { status: 200, ok: true, body: body.slice(0, 1) } }); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts' }); + const [w] = h.writes as Array<{ context: Record }>; + expect(w!.context).toMatchObject({ isSystem: true }); + expect(w!.context[SYNC_PULL_WRITE]).toBe(true); + }); + + it('CONTROL: a target of no synced bucket gets no stamp and no mark', async () => { + const h = harness({ result: { status: 200, ok: true, body: body.slice(0, 1) } }); + const context = { isSystem: true, tenantId: 'org_1' }; + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', context }); + const [w] = h.writes as Array<{ data: Record; context: unknown }>; + expect(Object.keys(w!.data).filter((k) => k.startsWith('_sync_'))).toEqual([]); + expect(w!.context).toMatchObject(context); + expect(SYNC_PULL_WRITE in (w!.context as object)).toBe(false); + }); + + it('a mapping that writes a _sync_ column itself is refused mapping_target_refused (400) before the action is called', async () => { + const h = harness({ + object: syncedContact, + mapping: baseMapping({ fieldMapping: [...baseMapping().fieldMapping, { source: 'name', target: '_sync_source' }] }), + }); + expectRefused(await refusal(h), { code: 'VALIDATION_ERROR', status: 400, reason: 'mapping_target_refused' }); + expect(h.handler).not.toHaveBeenCalled(); + expect(h.writes).toEqual([]); + }); + + it('a synced target that withholds every injected column (systemFields: false) is written unstamped, unmarked', async () => { + const h = harness({ object: { ...syncedContact, systemFields: false }, result: { status: 200, ok: true, body: body.slice(0, 1) } }); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', context: { isSystem: true } }); + const [w] = h.writes as Array<{ data: Record; context: object }>; + expect(Object.keys(w!.data).filter((k) => k.startsWith('_sync_'))).toEqual([]); + expect(SYNC_PULL_WRITE in w!.context).toBe(false); + }); +}); diff --git a/packages/services/service-automation/src/connector-pull.ts b/packages/services/service-automation/src/connector-pull.ts index 8586199df18..22fb2941df5 100644 --- a/packages/services/service-automation/src/connector-pull.ts +++ b/packages/services/service-automation/src/connector-pull.ts @@ -778,10 +778,10 @@ async function pullOnce( } catch { /* judged by nobody, coerced as pass-through — the door's rule */ } // [ADR-0153 D4] The provenance columns are the pull's to stamp, never a // mapping's to write. A `synced` target carries them (the plan injects - // them); one that withholds every injected column (`systemFields: false`) - // cannot record what wrote its rows, and is refused like the datasource - // pull refuses it. A target of another bucket is refused at build (a - // sourced mapping targets a `synced` object) and gets no stamp here. + // them) and gets them stamped. One that withholds every injected column + // (`systemFields: false`), or a target of another bucket (refused at build: + // a sourced mapping targets a `synced` object), is written unstamped, as + // before; D3's delete marking, which needs the columns, judges it. const mappedSync = mappedSyncProvenanceTarget(artifact.fieldMapping); if (mappedSync) { return refuse('VALIDATION_ERROR', 400, 'mapping_target_refused', @@ -789,12 +789,6 @@ async function pullOnce( + 'itself (ADR-0153 D4); remove that entry.'); } const stampsProvenance = carriesSyncProvenanceColumns(schema); - if (!stampsProvenance && isPlainObject(schema) && schema.managedBy === 'synced') { - return refuse('VALIDATION_ERROR', 400, 'mapping_target_refused', - `Mapping "${mappingName}": targetObject '${objectName}' carries no _sync_ provenance columns (it declares ` - + 'systemFields: false, which withholds every injected column), so a pull cannot record which mapping and ' - + 'run wrote a row. Remove systemFields: false from the synced target.'); - } const refusedTarget = refuseUnknownMappingTargets(artifact, objectName, schema); if (refusedTarget) return refuseWith(refusedTarget, 'mapping_target_refused'); diff --git a/packages/services/service-automation/src/datasource-pull.test.ts b/packages/services/service-automation/src/datasource-pull.test.ts index 253e0a93fff..a1caaae234a 100644 --- a/packages/services/service-automation/src/datasource-pull.test.ts +++ b/packages/services/service-automation/src/datasource-pull.test.ts @@ -865,3 +865,73 @@ describe('[ADR-0153 D7] retention never removes the run that holds a mapping\'s ]); }); }); + +describe('[ADR-0153 D4] every row a datasource pull writes carries its provenance', () => { + /** Every copy's provenance columns, by key. */ + async function provenance(ql: ObjectQL): Promise { + const rows = await ql.find('order_copy', { orderBy: [{ field: 'external_no', order: 'asc' }], context: SYSTEM as never }); + return rows.map((r: Rec) => ({ + external_no: r.external_no, + _sync_source: r._sync_source, + _sync_external_id: r._sync_external_id, + _sync_run_id: r._sync_run_id, + _sync_deleted_at: r._sync_deleted_at ?? null, + pulledAt: typeof r._sync_pulled_at === 'string' || r._sync_pulled_at instanceof Date, + })); + } + + it('stamps the mapping, the source key, the write time and the sys_sync_run row; D3\'s mark stays empty', async () => { + const h = await harness(THREE.slice(0, 2), { runs: true }); + const result = await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: JOB }); + expect(result.summary.errors, JSON.stringify(result.summary.results)).toBe(0); + const [run] = await runRows(h.ql); + expect(await provenance(h.ql)).toEqual([ + { external_no: 'A-1', _sync_source: MAPPING.name, _sync_external_id: 'A-1', _sync_run_id: run!.id, _sync_deleted_at: null, pulledAt: true }, + { external_no: 'A-2', _sync_source: MAPPING.name, _sync_external_id: 'A-2', _sync_run_id: run!.id, _sync_deleted_at: null, pulledAt: true }, + ]); + }); + + it('a second run restamps the run on the rows it updates', async () => { + const h = await harness(THREE.slice(0, 1), { runs: true }); + await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: JOB }); + await h.erp.knex.raw('update ERP_ORDERS set AMOUNT = 11, UPDATED_AT = ? where ORDER_NO = ?', [at(5000), 'A-1']); + await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: JOB }); + const runs = await runRows(h.ql); + expect(runs).toHaveLength(2); + expect((await provenance(h.ql))[0]!._sync_run_id).toBe(runs[1]!.id); + }); + + it('with no ledger the run column is not written (so empty on a row the pull created), and the other stamps still land', async () => { + const h = await harness(THREE.slice(0, 1)); + await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: SYSTEM }); + expect(await provenance(h.ql)).toEqual([ + { external_no: 'A-1', _sync_source: MAPPING.name, _sync_external_id: 'A-1', _sync_run_id: null, _sync_deleted_at: null, pulledAt: true }, + ]); + }); + + it('a key of several fields is stamped as a JSON array of their values in upsertKey order', async () => { + const h = await harness(THREE.slice(0, 1), { mapping: { ...MAPPING, upsertKey: ['amount', 'external_no'] } }); + await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: SYSTEM }); + expect((await provenance(h.ql))[0]!._sync_external_id).toBe('["10","A-1"]'); + }); + + it('a mapping that writes a _sync_ column itself is refused mapping_target_refused (400) and nothing is written', async () => { + const h = await harness(THREE.slice(0, 1), { + mapping: { ...MAPPING, fieldMapping: [...MAPPING.fieldMapping, { source: 'updated_at', target: '_sync_deleted_at' }] }, + }); + const err = await refusalOf(pullConnectorSource(h.deps, { mapping: MAPPING.name, context: SYSTEM })); + expect([err.code, err.status, err.reason]).toEqual(['VALIDATION_ERROR', 400, 'mapping_target_refused']); + expect(err.message).toContain('_sync_deleted_at'); + expect(await copies(h.ql)).toEqual([]); + }); + + it('a synced target that withholds every injected column (systemFields: false) is still written, unstamped', async () => { + const h = await harness(THREE.slice(0, 1), { + target: { ...TARGET, systemFields: false }, + }); + await pullConnectorSource(h.deps, { mapping: MAPPING.name, context: SYSTEM }); + const rows = await h.ql.find('order_copy', { context: SYSTEM as never }); + expect(rows).toHaveLength(1); + expect(Object.keys(rows[0] as Rec).filter((k) => k.startsWith('_sync_'))).toEqual([]); + }); +}); diff --git a/packages/services/service-automation/src/datasource-pull.ts b/packages/services/service-automation/src/datasource-pull.ts index 09bd9a7c767..ded019ee4ca 100644 --- a/packages/services/service-automation/src/datasource-pull.ts +++ b/packages/services/service-automation/src/datasource-pull.ts @@ -220,20 +220,16 @@ export async function pullDatasourceSource( + "to members, so a member's edit is never kept or lost silently by the next pull; declare managedBy: 'synced' on it."); } // [ADR-0153 D4] The provenance columns are the pull's to stamp, never a - // mapping's to write; and a target without them (`systemFields: false` - // withholds every injected column) cannot record what wrote its rows. + // mapping's to write. (A target that withholds them, `systemFields: false`, + // is written unstamped, as before: refusing it is a narrowing this slice + // does not take; D3's delete marking, which needs the columns, judges it.) const mappedSync = mappedSyncProvenanceTarget(artifact.fieldMapping); if (mappedSync) { return invalid('mapping_target_refused', `fieldMapping writes '${mappedSync}', a sync-in provenance column the pull stamps itself (ADR-0153 D4); ` + 'remove that entry.'); } - if (!carriesSyncProvenanceColumns(target)) { - return invalid('mapping_target_refused', - `targetObject '${targetObject}' carries no _sync_ provenance columns (it declares systemFields: false, which ` - + 'withholds every injected column), so a pull cannot record which mapping and run wrote a row. Remove ' - + "systemFields: false from the synced target."); - } + const stampsProvenance = carriesSyncProvenanceColumns(target); const refusedTarget = refuseUnknownMappingTargets(artifact, targetObject, target); if (refusedTarget) { return refuse(refusedTarget.code, refusedTarget.status, 'mapping_target_refused', `Mapping "${mapping}": ${refusedTarget.error}`); @@ -362,15 +358,15 @@ export async function pullDatasourceSource( // engine admits a `_sync_` column from, and run as the system when the // caller handed no context (as the reads do): the provenance columns are // `readonly`, which only a system write keeps. - const writeContext = markSyncPullWrite(context ?? { isSystem: true }); + const writeContext = stampsProvenance ? markSyncPullWrite(context ?? { isSystem: true }) : context; const write = async (rows: Rec[]): Promise => { const applied = applyMappingToRows(rows, artifact, { objectSchema: target, trimWhitespace }); if (!applied.ok) { return refuse(applied.code, applied.status, 'mapping_apply_refused', `Mapping "${mapping}": ${applied.error}`); } - const stamped = stampSyncProvenance(applied.rows, matchFields, { - mapping, runId: run.id, pulledAt: new Date().toISOString(), - }); + const stamped = stampsProvenance + ? stampSyncProvenance(applied.rows, matchFields, { mapping, runId: run.id, pulledAt: new Date().toISOString() }) + : applied.rows; const ran = await runImport({ p: protocol, objectName: targetObject, diff --git a/packages/services/service-automation/src/sync-provenance-stamp.test.ts b/packages/services/service-automation/src/sync-provenance-stamp.test.ts new file mode 100644 index 00000000000..aec3bf3480c --- /dev/null +++ b/packages/services/service-automation/src/sync-provenance-stamp.test.ts @@ -0,0 +1,78 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0153 D4, open question L852] Pins the `_sync_external_id` spelling of a + * row's source key, and the stamp both pulls put on a row. + */ + +import { describe, it, expect } from 'vitest'; +import { + carriesSyncProvenanceColumns, + encodeSyncExternalId, + mappedSyncProvenanceTarget, + stampSyncProvenance, +} from './sync-provenance-stamp.js'; + +describe('[ADR-0153 L852] encodeSyncExternalId', () => { + it('one key field: its value as plain text', () => { + expect(encodeSyncExternalId(['A-1'])).toBe('A-1'); + expect(encodeSyncExternalId([' A-1 '])).toBe('A-1'); + expect(encodeSyncExternalId([42])).toBe('42'); + expect(encodeSyncExternalId([10n])).toBe('10'); + expect(encodeSyncExternalId([true])).toBe('true'); + expect(encodeSyncExternalId([new Date('2026-01-02T03:04:05Z')])).toBe('2026-01-02T03:04:05.000Z'); + expect(encodeSyncExternalId([{ a: 1 }])).toBe('{"a":1}'); + }); + + it('a composite key: a JSON array of the spellings, in upsertKey order, never sorted', () => { + expect(encodeSyncExternalId([10, 'A-1'])).toBe('["10","A-1"]'); + expect(encodeSyncExternalId(['A-1', 10])).toBe('["A-1","10"]'); + // a value holding the array's own punctuation stays unambiguous + expect(encodeSyncExternalId(['a","b', 'c'])).toBe('["a\\",\\"b","c"]'); + expect(JSON.parse(encodeSyncExternalId(['a","b', 'c'])!)).toEqual(['a","b', 'c']); + }); + + it('the same values give the same text on every call (canonical)', () => { + expect(encodeSyncExternalId([' x', 1])).toBe(encodeSyncExternalId(['x ', '1'])); + }); + + it('any blank key value: no id', () => { + expect(encodeSyncExternalId([])).toBeUndefined(); + expect(encodeSyncExternalId([null])).toBeUndefined(); + expect(encodeSyncExternalId([' '])).toBeUndefined(); + expect(encodeSyncExternalId(['A', undefined])).toBeUndefined(); + expect(encodeSyncExternalId([new Date('nope')])).toBeUndefined(); + }); +}); + +describe('[ADR-0153 D4] the stamp', () => { + it('stamps the mapping, the source key, the time and the run, on new row objects', () => { + const rows = [{ code: 'C1', title: 'x' }]; + const out = stampSyncProvenance(rows, ['code'], { mapping: 'erp', runId: 'run_1', pulledAt: '2026-01-01T00:00:00.000Z' }); + expect(out).toEqual([{ + code: 'C1', title: 'x', + _sync_source: 'erp', _sync_external_id: 'C1', _sync_pulled_at: '2026-01-01T00:00:00.000Z', _sync_run_id: 'run_1', + }]); + expect(out[0]).not.toBe(rows[0]); + expect(rows[0]).toEqual({ code: 'C1', title: 'x' }); + }); + + it('no run record: no run column; a blank key: no external id; never _sync_deleted_at', () => { + const [row] = stampSyncProvenance([{ code: ' ' }], ['code'], { mapping: 'erp', runId: undefined, pulledAt: 't' }); + expect('_sync_run_id' in row!).toBe(false); + expect('_sync_external_id' in row!).toBe(false); + expect('_sync_deleted_at' in row!).toBe(false); + }); + + it('carriesSyncProvenanceColumns reads the plan: synced yes, others and systemFields:false no', () => { + expect(carriesSyncProvenanceColumns({ name: 'a', managedBy: 'synced' })).toBe(true); + expect(carriesSyncProvenanceColumns({ name: 'a', managedBy: 'synced', systemFields: false })).toBe(false); + expect(carriesSyncProvenanceColumns({ name: 'a' })).toBe(false); + }); + + it('mappedSyncProvenanceTarget finds a _sync_ target, single or fanned out', () => { + expect(mappedSyncProvenanceTarget([{ target: 'name' }, { target: '_sync_source' }])).toBe('_sync_source'); + expect(mappedSyncProvenanceTarget([{ target: ['a', '_sync_run_id'] }])).toBe('_sync_run_id'); + expect(mappedSyncProvenanceTarget([{ target: 'name' }, undefined])).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/sync-provenance-stamp.ts b/packages/services/service-automation/src/sync-provenance-stamp.ts index 51519768eda..06522acce40 100644 --- a/packages/services/service-automation/src/sync-provenance-stamp.ts +++ b/packages/services/service-automation/src/sync-provenance-stamp.ts @@ -11,7 +11,7 @@ * | `_sync_source` | the mapping's name | * | `_sync_external_id` | the row's key in the source, as text ({@link encodeSyncExternalId}) | * | `_sync_pulled_at` | when this write was made | - * | `_sync_run_id` | the `sys_sync_run` row of this pull, or empty when no ledger keeps the run | + * | `_sync_run_id` | the `sys_sync_run` row of this pull; not written when no ledger keeps the run | * | `_sync_deleted_at` | nothing yet: D3's mark, stamped by the delete marking when it lands | * * Both pulls (the connector source and the datasource source) stamp through @@ -21,18 +21,19 @@ * `_sync_` column in any other write, whatever its context. */ -import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_PREFIX } from '@objectstack/spec/data'; +import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_PREFIX } from '@objectstack/spec/data'; type Rec = Record; const [SYNC_SOURCE, SYNC_EXTERNAL_ID, SYNC_PULLED_AT, SYNC_RUN_ID] = SYNC_PROVENANCE_COLUMNS; -const isPlainObject = (v: unknown): v is Rec => v !== null && typeof v === 'object' && !Array.isArray(v); - -/** Does the target object carry the provenance columns a pull stamps? */ +/** + * Does the target object carry the provenance columns a pull stamps? Asked of + * the injected-columns plan, the one answer the registry injects by, so the + * verdict is the same on the served document and on the authored one. + */ export function carriesSyncProvenanceColumns(target: unknown): boolean { - const fields = isPlainObject(target) && isPlainObject(target.fields) ? target.fields : undefined; - return fields !== undefined && [SYNC_SOURCE, SYNC_EXTERNAL_ID, SYNC_PULLED_AT, SYNC_RUN_ID].every((f) => fields[f] !== undefined); + return resolveInjectedSystemColumns(target).sync; } /** @@ -99,7 +100,7 @@ export function encodeSyncExternalId(values: readonly unknown[]): string | undef /** What a pull stamps: the mapping, the run, and the write's time. */ export interface SyncProvenanceStamp { mapping: string; - /** The `sys_sync_run` id, when a ledger keeps the run. */ + /** The `sys_sync_run` id, when a ledger keeps the run; `undefined` leaves `_sync_run_id` unwritten. */ runId: string | undefined; /** ISO 8601; one value per batch the pull writes. */ pulledAt: string; @@ -122,7 +123,10 @@ export function stampSyncProvenance( [SYNC_SOURCE]: stamp.mapping, ...(externalId !== undefined ? { [SYNC_EXTERNAL_ID]: externalId } : {}), [SYNC_PULLED_AT]: stamp.pulledAt, - [SYNC_RUN_ID]: stamp.runId ?? null, + // A pull with no run ledger leaves the column out: the import runner + // reads a blank cell as "leave the field as it is", so a `null` here + // would not clear it either. The column's description says so. + ...(stamp.runId !== undefined ? { [SYNC_RUN_ID]: stamp.runId } : {}), }; }); } diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 790dc482a76..eb42223ac27 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -825,6 +825,9 @@ "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES (const)", + "SYNC_PROVENANCE_COLUMNS (const)", + "SYNC_PROVENANCE_FIELD_DEFS (const)", + "SYNC_PROVENANCE_PREFIX (const)", "SYS_ACTIVITY_BUILTIN_TYPES (const)", "SYS_ACTIVITY_PLATFORM_TYPES (const)", "Scalar (type)", @@ -904,6 +907,7 @@ "StringStoredComparandDoorFieldMeta (interface)", "StringStoredComparandDoorVerdict (type)", "StringStoredComparandRow (interface)", + "SyncProvenanceColumn (type)", "SysActivityBuiltinType (type)", "TEMPORAL_CASES (const)", "TEMPORAL_NOW (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 55df42e31e0..50cc0607808 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -813,6 +813,9 @@ "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES": "src/data/field-value.zod.ts#STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES": "src/data/field-value.zod.ts#STRUCTURED_JSON_TYPES (const)", + "SYNC_PROVENANCE_COLUMNS": "src/data/injected-system-columns.ts#SYNC_PROVENANCE_COLUMNS (const)", + "SYNC_PROVENANCE_FIELD_DEFS": "src/data/injected-system-column-provenance.ts#SYNC_PROVENANCE_FIELD_DEFS (const)", + "SYNC_PROVENANCE_PREFIX": "src/data/injected-system-columns.ts#SYNC_PROVENANCE_PREFIX (const)", "SYS_ACTIVITY_BUILTIN_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_BUILTIN_TYPES (const)", "SYS_ACTIVITY_PLATFORM_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_PLATFORM_TYPES (const)", "Scalar": "src/data/filter.zod.ts#Scalar (type)", @@ -891,6 +894,7 @@ "StringStoredComparandDoorFieldMeta": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorFieldMeta (interface)", "StringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorVerdict (type)", "StringStoredComparandRow": "src/data/filter-comparand-type-conformance.ts#StringStoredComparandRow (interface)", + "SyncProvenanceColumn": "src/data/injected-system-columns.ts#SyncProvenanceColumn (type)", "SysActivityBuiltinType": "src/data/feed.zod.ts#SysActivityBuiltinType (type)", "TEMPORAL_CASES": "src/data/temporal-conformance.ts#TEMPORAL_CASES (const)", "TEMPORAL_NOW": "src/data/temporal-conformance.ts#TEMPORAL_NOW (const)", diff --git a/packages/spec/liveness/mapping.json b/packages/spec/liveness/mapping.json index 12f3b095a82..60b86277e29 100644 --- a/packages/spec/liveness/mapping.json +++ b/packages/spec/liveness/mapping.json @@ -123,7 +123,7 @@ "verifiedAt": "2026-11-10", "authorWarn": true, "authorHint": "Keep it, but nothing reads it yet: the sync-in pull that honours it is the P2 engine card of ADR-0153, so until that release a pull marks no deleted row, whichever policy you set.", - "note": "PLANNED RECORD (ADR-0153 D3, the P2 spec card #32061): what a pull does with a row the source no longer has — `'mark'` stamps `_sync_deleted_at` and clears it if the row comes back, `'ignore'` leaves the row. Declared with NO schema `.default()` so an authored value stays distinguishable from an absent one (absent reads as `'mark'`), which is what lets this row warn the author at all. READ BY NOTHING YET: the delete marking, its completeness rule and the incremental-`mark` refusal are the P2 engine card's (#32062), which flips this row to `live` and drops `authorWarn` / `authorHint`." + "note": "PLANNED RECORD (ADR-0153 D3, the P2 spec card #32061): what a pull does with a row the source no longer has — `'mark'` stamps `_sync_deleted_at` and clears it if the row comes back, `'ignore'` leaves the row. Declared with NO schema `.default()` so an authored value stays distinguishable from an absent one (absent reads as `'mark'`), which is what lets this row warn the author at all. READ BY NOTHING YET: the delete marking, its completeness rule and the incremental-`mark` refusal are the P2 engine card's (#32062), which flips this row to `live` and drops `authorWarn` / `authorHint`. 2026-11-23 (#32062 slice 5, ADR-0153 D4): the column `_sync_deleted_at` now exists on every `synced` object (the injected-columns plan, `SYNC_PROVENANCE_COLUMNS`) and the engine refuses it in any write but the pull's, but nothing stamps it yet: it is empty on every row until the delete marking (slice 6) lands, and the column's own description says so. This row stays `planned` until then." }, "deletedField": { "status": "planned", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 49c9ee471ea..021744e9f5c 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -245,7 +245,7 @@ "status": "live", "verifiedAt": "2026-08-28", "evidence": "packages/spec/src/data/object.zod.ts#resolveCrudAffordances (`obj?.managedBy ?? 'platform'` selects the bucket's default CRUD affordance row — the `ui crudAffordances` half of this note); packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed (`const bucket = schema?.managedBy` — engine-owned buckets refuse user-context writes the bucket's affordances forbid); packages/spec/src/data/injected-system-columns.ts#resolveInjectedSystemColumns (a set `managedBy` withholds the ownership anchors, and `'better-auth'` withholds every injected column); packages/objectql/src/secret-fields.ts#collectMaskedReadFields (a `'better-auth'` table's own columns are exempted from password/secret masking, sibling `collectMaskedPasswordFields` the same); packages/core/src/security/effective-object-permissions.ts#clampManagedObjectWrites (the `/me/permissions` clamp closes a guarded bucket's writes; on `synced` whatever `userActions` says)", - "note": "default perms; ui crudAffordances. 2026-08-28: RE-ANCHORED (commit 93ea19bca) and REPOINTED — the citation was `registry.ts:208`, in range of that 3921-line file and landing on `merged.indexes = [...]`, the INDEX merge of a sibling key. registry.ts names `managedBy` on ten lines so the key-mention check passes, but nine of them are prose in comments and the tenth (:986) interpolates the value into a WARNING string — a diagnostic, not a decision. The decisions moved into @objectstack/spec (`resolveCrudAffordances`, `resolveInjectedSystemColumns`) and plugin-security: the consumer-promoted-into-another-package shape the gate's own guidance names. Re-closed by hand against c459da6bc. 2026-11-10 (ADR-0153 D4, #32061): the value `synced` lands with every mechanism ADR-0103 guards a bucket with — the engine write guard (`ENGINE_OWNED_BUCKETS`), the `apiMethods` reconciliation (through `resolveCrudAffordances`), the `/me/permissions` clamp (`GUARDED_WRITE_BUCKETS`), both `PLATFORM_INTERNAL_MANAGED_BUCKETS` mirrors and the `ui/` bucket union — and `userActions` cannot open a write on it (`MANAGED_BY_WRITE_LOCKED_BUCKETS`, refused at parse). Live as it lands: no pull writes into it until the P2 engine card, but every member write is refused today." + "note": "default perms; ui crudAffordances. 2026-08-28: RE-ANCHORED (commit 93ea19bca) and REPOINTED — the citation was `registry.ts:208`, in range of that 3921-line file and landing on `merged.indexes = [...]`, the INDEX merge of a sibling key. registry.ts names `managedBy` on ten lines so the key-mention check passes, but nine of them are prose in comments and the tenth (:986) interpolates the value into a WARNING string — a diagnostic, not a decision. The decisions moved into @objectstack/spec (`resolveCrudAffordances`, `resolveInjectedSystemColumns`) and plugin-security: the consumer-promoted-into-another-package shape the gate's own guidance names. Re-closed by hand against c459da6bc. 2026-11-10 (ADR-0153 D4, #32061): the value `synced` lands with every mechanism ADR-0103 guards a bucket with — the engine write guard (`ENGINE_OWNED_BUCKETS`), the `apiMethods` reconciliation (through `resolveCrudAffordances`), the `/me/permissions` clamp (`GUARDED_WRITE_BUCKETS`), both `PLATFORM_INTERNAL_MANAGED_BUCKETS` mirrors and the `ui/` bucket union — and `userActions` cannot open a write on it (`MANAGED_BY_WRITE_LOCKED_BUCKETS`, refused at parse). Live as it lands: no pull writes into it until the P2 engine card, but every member write is refused today. 2026-11-23 (#32062 slice 5, ADR-0153 D4): `resolveInjectedSystemColumns` plans the five `_sync_` provenance columns on `synced` only (`plan.sync`), the registry injects them with the (`organization_id`, `_sync_source`, `_sync_external_id`) index, both pulls stamp four of them on every write, and the engine refuses a `_sync_` key in any write but the pull's (`ERR_SYNC_PROVENANCE_WRITE_REFUSED`). `_sync_deleted_at` is planned but not stamped until D3's delete marking lands." }, "ownership": { "status": "live", diff --git a/packages/spec/src/data/injected-system-column-provenance.ts b/packages/spec/src/data/injected-system-column-provenance.ts index 585aad250fe..5e468a39b84 100644 --- a/packages/spec/src/data/injected-system-column-provenance.ts +++ b/packages/spec/src/data/injected-system-column-provenance.ts @@ -239,7 +239,8 @@ export const SYNC_PROVENANCE_FIELD_DEFS = { system: true, description: 'The sys_sync_run row of the pull that last wrote this row, as text, never a lookup (ADR-0153 D4, D7). ' - + 'Empty when the pull kept no run record. Written by the pull only.', + + 'Not written by a pull that keeps no run record (no run ledger is composed): empty on a row such a pull ' + + 'created, and left as it was on a row it updated. Written by the pull only.', }, _sync_deleted_at: { type: 'datetime', diff --git a/packages/spec/src/data/injected-system-columns.test.ts b/packages/spec/src/data/injected-system-columns.test.ts index 3500a0e643c..191abf889c2 100644 --- a/packages/spec/src/data/injected-system-columns.test.ts +++ b/packages/spec/src/data/injected-system-columns.test.ts @@ -3,7 +3,9 @@ import { describe, it, expect } from 'vitest'; import { AUDIT_PROVENANCE_FIELDS } from './field-group-layout'; -import { resolveInjectedSystemColumns } from './injected-system-columns'; +import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_PREFIX } from './injected-system-columns'; +import { injectedSystemColumnDefs, SYNC_PROVENANCE_FIELD_DEFS } from './injected-system-column-provenance'; +import { FieldSchema } from './field.zod'; // --------------------------------------------------------------------------- // [#5378] The per-object injected-column derivation. @@ -218,3 +220,60 @@ describe('resolveInjectedSystemColumns — the deployment\'s platform-global dec expect(resolveInjectedSystemColumns({}, { platformGlobalObjects: [''] }).tenant).toBe(true); }); }); + +// --------------------------------------------------------------------------- +// [ADR-0153 D4] The five `_sync_` provenance columns, on a `synced` object only. +// --------------------------------------------------------------------------- +describe("resolveInjectedSystemColumns — the sync-in provenance columns of a managedBy: 'synced' object", () => { + const synced = { name: 'erp_customer', managedBy: 'synced', fields: { code: { type: 'text' } } }; + + it('plans the five columns, in the order the constant declares them', () => { + const plan = resolveInjectedSystemColumns(synced); + expect(plan.sync).toBe(true); + expect(SYNC_PROVENANCE_COLUMNS).toEqual([ + '_sync_source', '_sync_external_id', '_sync_pulled_at', '_sync_run_id', '_sync_deleted_at', + ]); + for (const column of SYNC_PROVENANCE_COLUMNS) expect(plan.names.has(column)).toBe(true); + }); + + it('every planned column carries the reserved prefix no author field may take', () => { + for (const column of SYNC_PROVENANCE_COLUMNS) expect(column.startsWith(SYNC_PROVENANCE_PREFIX)).toBe(true); + }); + + it('a synced object keeps tenant and audit, and gets no ownership anchor', () => { + expect(resolveInjectedSystemColumns(synced)).toMatchObject({ + tenant: true, audit: true, owner: false, owningBusinessUnit: false, queue: false, sync: true, + }); + }); + + it('CONTROL: no other bucket, and no unmanaged object, plans them', () => { + for (const managedBy of [undefined, 'platform', 'config', 'system-data', 'engine-owned', 'append-only']) { + const plan = resolveInjectedSystemColumns({ name: 'erp_customer', ...(managedBy ? { managedBy } : {}) }); + expect(plan.sync).toBe(false); + for (const column of SYNC_PROVENANCE_COLUMNS) expect(plan.names.has(column)).toBe(false); + } + }); + + it('the hard opt-out withholds them too (systemFields: false)', () => { + const plan = resolveInjectedSystemColumns({ ...synced, systemFields: false }); + expect(plan.sync).toBe(false); + expect([...plan.names]).toEqual(['id']); + }); + + it('the definitions table answers each planned column, read-only and system-owned', () => { + const defs = injectedSystemColumnDefs(synced); + for (const column of SYNC_PROVENANCE_COLUMNS) { + expect(defs[column]).toBe(SYNC_PROVENANCE_FIELD_DEFS[column]); + expect(defs[column]).toMatchObject({ readonly: true, system: true, hidden: true, required: false }); + } + expect(SYNC_PROVENANCE_FIELD_DEFS._sync_pulled_at.type).toBe('datetime'); + expect(SYNC_PROVENANCE_FIELD_DEFS._sync_deleted_at.type).toBe('datetime'); + expect(SYNC_PROVENANCE_FIELD_DEFS._sync_run_id.type).toBe('text'); + }); + + it('every definition parses as a field, so the served columns describe themselves validly', () => { + for (const column of SYNC_PROVENANCE_COLUMNS) { + expect(FieldSchema.safeParse(SYNC_PROVENANCE_FIELD_DEFS[column]).success).toBe(true); + } + }); +}); From 88c39bd672582e543115e1172ff1b21d2070e359 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:10:30 +0000 Subject: [PATCH 3/6] fix(objectql): keep the registry facade at its ceiling and answer the gates Move the sync column additions beside their index helper so registry.ts does not grow, add the provenance index's reader row, bound the test double's find, and pay the lint load at collection in the diagnostics test. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- ...iagnostics.sync-provenance-columns.test.ts | 3 ++ .../federated-injected-column-readers.test.ts | 5 +++ packages/objectql/src/registry.ts | 33 ++++--------------- .../objectql/src/sync-provenance-index.ts | 22 ++++++++++++- packages/objectql/src/sync-provenance.test.ts | 3 +- 5 files changed, 38 insertions(+), 28 deletions(-) diff --git a/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts b/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts index ce74d8efcfc..67cb4a926a9 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.sync-provenance-columns.test.ts @@ -12,6 +12,9 @@ * differs from the platform's in any key, is still judged and refused. */ import { describe, expect, it } from 'vitest'; +// Pays the first load of the lint package the diagnostics import lazily during collection, not inside a +// clocked case (check:test-source-alias). +import '@objectstack/lint'; import { SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 34dca84cd16..14655b2c3ba 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -500,6 +500,11 @@ const READERS: Record = { disposition: 'not-a-read', why: 'the tenant index the registry declares on a provisioned tenant column', }, + // [ADR-0153 D4] The provenance index's leading column. + 'sync-provenance-index.ts# :: organization_id': { + disposition: 'not-a-read', + why: 'leads the provenance index the registry declares on a synced object, a local copy whose columns the platform provisions; it reads no row', + }, 'registry-top-level.ts# :: owning_business_unit_id': { disposition: 'not-a-read', why: 'the name the injection writes the ADR-0117 D1 anchor under', diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index b36b46743a4..c47897800b3 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { ServiceObject, ObjectOwnership, type RelatedListsArrangement, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, AUDIT_PROVENANCE_FIELDS, SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; +import { ServiceObject, ObjectOwnership, type RelatedListsArrangement, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, AUDIT_PROVENANCE_FIELDS } from '@objectstack/spec/data'; // [#4513] The audit-family governance table, and [#6562] the injected-column // DEFINITION tables it governs — see the re-exports below for why both live in a // package `objectql` and `metadata-protocol` both depend on. @@ -35,7 +35,7 @@ import { import { resolveTenancyPosture, resolveSearchPinyinEnabled } from '@objectstack/types'; import { postureEnforcesWall } from '@objectstack/spec/security'; import { provisionSearchCompanion } from './search-companion.js'; -import { provisionSyncProvenanceIndex } from './sync-provenance-index.js'; +import { provisionSyncProvenanceIndex, syncProvenanceColumnAdditions } from './sync-provenance-index.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; import { ObjectStackManifest, InstalledPackage, type InstalledPackageSource, customizationBasePackageId, type NamespaceObjectNameClash } from '@objectstack/spec/kernel'; import { applyProtection } from '@objectstack/spec/shared'; @@ -568,8 +568,6 @@ export function applySystemFields( // [ADR-0142 D3] The queue column rides with the owner anchor (the plan's // `queue` is its `owner`): "sits in Q" is `queue == Q AND owner_id IS NULL`. const wantQueue = plan.queue; - // [ADR-0153 D4] The five `_sync_` provenance columns of a `synced` object. - const wantSync = plan.sync; // Nothing to INJECT — the two opt-out rows (`systemFields: false`, // `managedBy: 'better-auth'`) and objects whose every column is already @@ -583,7 +581,7 @@ export function applySystemFields( // `systemFields.tenant` only, so `systemFields: false` leaves the wall live). // Returning `schema` here was the last exit that decided the index by NOT // asking, which is how the withholding survived #8375's convergence. - if (!wantTenant && !wantAudit && !wantOwner && !wantOwningBusinessUnit && !wantQueue && !wantSync) { + if (!wantTenant && !wantAudit && !wantOwner && !wantOwningBusinessUnit && !wantQueue && !plan.sync) { return provisionTenantScopeIndex(schema, opts); } @@ -714,28 +712,11 @@ export function applySystemFields( if (wantQueue && !schema.fields?.[QUEUE_FIELD]) { additions[QUEUE_FIELD] = { ...QUEUE_FIELD_DEF }; } + if (plan.sync) Object.assign(additions, syncProvenanceColumnAdditions(schema)); // [ADR-0153 D4] the `_sync_` columns - // [ADR-0153 D4] The sync-in provenance columns, on a `synced` object only: - // the mapping that wrote the row, its key in the source, when and by which - // run it was last written, and D3's mark (planned with the rest, written by - // nothing until the delete marking lands). `readonly`, `system`, `hidden`: - // the pull, writing as the system, is their one writer, and the engine - // refuses any other write that names one (`refuseSyncProvenanceWrite`). No - // author field can take a `_sync_` name, so the guard below only ever admits - // the platform's own definition coming back through a re-registration. Their - // index is {@link provisionSyncProvenanceIndex}, stamped after the tenant - // index on the merged result. - if (wantSync) { - for (const name of SYNC_PROVENANCE_COLUMNS) { - if (!schema.fields?.[name]) additions[name] = { ...SYNC_PROVENANCE_FIELD_DEFS[name] }; - } - } - - // [#8375] The tenant INDEX is decided over the MERGED result, never over the - // input — so this function and the read-exit seam ask the same question of the - // same document shape. Both cases below route through it, including the one - // that adds no field at all (an object whose every system column is already - // declared still owes the index decision). + // [#8375] The tenant INDEX is decided over the MERGED result, never over the input, so this function and the + // read-exit seam ask one question of one document shape; the ADR-0153 D4 provenance index is stamped after it. + // Both cases below route through them, the one adding no field included (it still owes the index decision). if (Object.keys(additions).length === 0 && Object.keys(overrides).length === 0) { return provisionSyncProvenanceIndex(provisionTenantScopeIndex(schema, opts)); } diff --git a/packages/objectql/src/sync-provenance-index.ts b/packages/objectql/src/sync-provenance-index.ts index e8ada1b9acb..79d38a55095 100644 --- a/packages/objectql/src/sync-provenance-index.ts +++ b/packages/objectql/src/sync-provenance-index.ts @@ -27,7 +27,7 @@ * duplicated. */ -import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS } from '@objectstack/spec/data'; +import { resolveInjectedSystemColumns, SYNC_PROVENANCE_COLUMNS, SYNC_PROVENANCE_FIELD_DEFS } from '@objectstack/spec/data'; type Rec = Record; @@ -54,6 +54,26 @@ export function syncProvenanceIndexFor(schema: unknown): { fields: string[] } | }; } +/** + * The provenance columns `applySystemFields` adds to a `synced` object (the + * caller asks the plan's `sync` first): the mapping that wrote the row, its + * key in the source, when and by which run it was last written, and D3's mark + * (planned with the rest, written by nothing until the delete marking lands). + * `readonly`, `system`, `hidden`: the pull, writing as the system, is their one + * writer, and the engine refuses any other write that names one + * (`refuseSyncProvenanceWrite`). No author field can take a `_sync_` name, so + * skipping a column the schema already carries only ever keeps the platform's + * own definition coming back through a re-registration. + */ +export function syncProvenanceColumnAdditions(schema: unknown): Rec { + const present = fieldsRecord(schema) ?? {}; + const additions: Rec = {}; + for (const name of SYNC_PROVENANCE_COLUMNS) { + if (!present[name]) additions[name] = { ...SYNC_PROVENANCE_FIELD_DEFS[name] }; + } + return additions; +} + function sameColumns(entry: unknown, columns: readonly string[]): boolean { const fields = entry && typeof entry === 'object' ? (entry as Rec).fields : undefined; return Array.isArray(fields) && fields.length === columns.length && fields.every((f, i) => f === columns[i]); diff --git a/packages/objectql/src/sync-provenance.test.ts b/packages/objectql/src/sync-provenance.test.ts index 8dc4c8e03f6..4222559cb63 100644 --- a/packages/objectql/src/sync-provenance.test.ts +++ b/packages/objectql/src/sync-provenance.test.ts @@ -67,7 +67,8 @@ function makeStubDriver() { async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, async find(object: string, ast: any) { - return Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; }, async findOne(object: string, ast: any) { for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; From f1e8455c4f819c074619eafd1d03f65ca2cf7b7e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:17:21 +0000 Subject: [PATCH 4/6] chore(spec): regenerate api-surface and export-origins on the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- packages/spec/api-surface/data.json | 6 ++++++ packages/spec/export-origins/data.json | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index eb42223ac27..2a583c17d00 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -580,6 +580,9 @@ "NumericColumnRepresentation (type)", "NumericStringGrammarCase (type)", "NumericStringReading (type)", + "OBJECT_ACTION_LAYOUT_BUILTINS (const)", + "OBJECT_ACTION_LAYOUT_PINNED_LIMIT (const)", + "OBJECT_ACTION_LAYOUT_SCOPES (const)", "OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE (const)", "ORACLE_DEFAULT_PORT (const)", @@ -589,6 +592,9 @@ "ObjectAccessConfig (type)", "ObjectAccessConfigParsed (type)", "ObjectAccessConfigSchema (const)", + "ObjectActionLayout (type)", + "ObjectActionLayoutArm (type)", + "ObjectActionLayoutScope (type)", "ObjectCapabilities (const)", "ObjectCapabilities (type)", "ObjectCapabilitiesParsed (type)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 50cc0607808..5bb09ebc0ef 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -570,6 +570,9 @@ "NumericColumnRepresentation": "src/data/numeric-column-representation.ts#NumericColumnRepresentation (type)", "NumericStringGrammarCase": "src/data/filter-number-comparand-declared-type.ts#NumericStringGrammarCase (type)", "NumericStringReading": "src/data/filter-number-comparand-declared-type.ts#NumericStringReading (type)", + "OBJECT_ACTION_LAYOUT_BUILTINS": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_BUILTINS (const)", + "OBJECT_ACTION_LAYOUT_PINNED_LIMIT": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_PINNED_LIMIT (const)", + "OBJECT_ACTION_LAYOUT_SCOPES": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_SCOPES (const)", "OBJECT_COLORS": "src/data/object-icon.ts#OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#OBJECT_KEY_GUIDANCE (const)", "ORACLE_DEFAULT_PORT": "src/data/driver/oracle.zod.ts#ORACLE_DEFAULT_PORT (const)", @@ -579,6 +582,9 @@ "ObjectAccessConfig": "src/data/object.zod.ts#ObjectAccessConfig (type)", "ObjectAccessConfigParsed": "src/data/object.zod.ts#ObjectAccessConfigParsed (type)", "ObjectAccessConfigSchema": "src/data/object.zod.ts#ObjectAccessConfigSchema (const)", + "ObjectActionLayout": "src/data/object-action-layout.ts#ObjectActionLayout (type)", + "ObjectActionLayoutArm": "src/data/object-action-layout.ts#ObjectActionLayoutArm (type)", + "ObjectActionLayoutScope": "src/data/object-action-layout.ts#ObjectActionLayoutScope (type)", "ObjectCapabilities": "src/data/object.zod.ts#ObjectCapabilities (type)", "ObjectCapabilitiesParsed": "src/data/object.zod.ts#ObjectCapabilitiesParsed (type)", "ObjectColor": "src/data/object-icon.ts#ObjectColor (type)", From 805d6199124e63712dfc8e107cae8c50ed94206f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:21:29 +0000 Subject: [PATCH 5/6] docs(automation): the null-guard note names a synced object's _sync_ columns Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- content/docs/automation/flows.mdx | 5 +++-- content/docs/automation/hooks.mdx | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 8b24cc5fff7..5ed502fbf7d 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2702,8 +2702,9 @@ and is read as `vars["current_user"]` / `vars["vars"]`. it `record.budget != null`, which both doors accept, and `has()` is no guard. The columns the platform adds count too: `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id`, `queue` and `organization_id` are - `null` on a row a system write, a seed or a guest left them empty in, so they - need the same guard; `created_at` and `updated_at` are stamped on every + `null` on a row a system write, a seed or a guest left them empty in, and a + `synced` object's `_sync_` columns can be `null` too, so they need the same + guard; `created_at` and `updated_at` are stamped on every stored row and need none. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index b18e975b6ac..46c19f618ad 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -150,7 +150,8 @@ rest** — CEL has no ordering or arithmetic over `null`, so the condition fault the write fails. `os build` and the publish gate refuse the unguarded form. That holds for the columns the platform adds as well: `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id`, `queue` and `organization_id` are `null` on -a row a system write, a seed or a guest left them empty in, so write +a row a system write, a seed or a guest left them empty in, and a `synced` object's +`_sync_` columns can be `null` too (`_sync_deleted_at` always is, for now), so write `record.owner_id != null && record.owner_id > 'a'`. `created_at` and `updated_at` are stamped on every stored row and need no guard, except in a `beforeInsert` hook: one with a `priority` below 10 runs before the stamp and reads them as `null`, so From b501462548d911695306ab278fbe7cca1d3b6e3e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:43:41 +0000 Subject: [PATCH 6/6] fix(objectql): judge the hooks' writes to the _sync_ columns, and refuse a connector pull with an unreadable target A _sync_ key a beforeInsert or beforeUpdate hook assigns, changes or removes is refused before the driver, on any write, the pull's own included. A connector pull whose target definition cannot be read is refused before the call instead of writing unstamped rows. The _sync_external_id description names the mapped value. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzeX8NmUPt5KSzQar4X --- .changeset/32062-sync-provenance-columns.md | 4 +- content/docs/automation/jobs.mdx | 7 +- packages/objectql/src/engine-insert.ts | 10 ++- packages/objectql/src/engine-update.ts | 7 +- .../objectql/src/sync-provenance-write.ts | 66 ++++++++++++++++-- packages/objectql/src/sync-provenance.test.ts | 69 ++++++++++++++++++- .../src/connector-pull.test.ts | 13 +++- .../service-automation/src/connector-pull.ts | 9 +++ .../spec/src/api/error-code-ledger.zod.ts | 14 ++-- .../data/injected-system-column-provenance.ts | 5 +- 10 files changed, 180 insertions(+), 24 deletions(-) diff --git a/.changeset/32062-sync-provenance-columns.md b/.changeset/32062-sync-provenance-columns.md index 332bd7a1c58..278b645ebb5 100644 --- a/.changeset/32062-sync-provenance-columns.md +++ b/.changeset/32062-sync-provenance-columns.md @@ -16,6 +16,6 @@ Skills-docs: none (no skills/ page names the `_sync_` columns or the synced buck ADR-0153 D4, the provenance half (#32062, slice 5). - **Five `_sync_` columns on every `managedBy: 'synced'` object.** `resolveInjectedSystemColumns` (`@objectstack/spec/data`) now plans `_sync_source`, `_sync_external_id`, `_sync_pulled_at`, `_sync_run_id` and `_sync_deleted_at` on that bucket only (`plan.sync`), and the registry injects them as hidden, read-only system columns, with an index on (`organization_id`, `_sync_source`, `_sync_external_id`) placed after the tenant index. New exports: `SYNC_PROVENANCE_COLUMNS`, `SYNC_PROVENANCE_PREFIX`, `SyncProvenanceColumn`, `SYNC_PROVENANCE_FIELD_DEFS`. A synced object that declares `systemFields: false` gets none of them. -- **Both pulls stamp them.** A connector pull and a datasource pull write `_sync_source` (the mapping), `_sync_external_id` (the row's `upsertKey` value as text; a key of several fields is a JSON array of the values in `upsertKey` order, such as `["10","A-1"]`), `_sync_pulled_at` and `_sync_run_id` (the `sys_sync_run` row; not written when no run ledger is composed) on every row. `_sync_deleted_at` exists but stays empty until delete marking (D3) lands. A mapping whose `fieldMapping` targets a `_sync_` column is refused with `400 mapping_target_refused` when it runs (it was refused before as an unknown target). -- **BREAKING: a `_sync_` column in any other write is refused.** The engine refuses an insert or update naming a `_sync_` key with `400 ERR_SYNC_PROVENANCE_WRITE_REFUSED`, before middleware, defaults and hooks run, whatever the caller's context, `isSystem` included. Only the pull's own write is admitted (`markSyncPullWrite`, exported from `@objectstack/objectql` with `SYNC_PULL_WRITE`, `SyncProvenanceWriteRefusedError` and `SYNC_PROVENANCE_WRITE_REFUSED_CODE`). The mark is consumed by that write, so a hook or flow it triggers writes as any other system caller and is refused the same way. Fix: leave the `_sync_` columns out of the write; the next pull of the mapping stamps them. +- **Both pulls stamp them.** A connector pull and a datasource pull write `_sync_source` (the mapping), `_sync_external_id` (the row's `upsertKey` value as text; a key of several fields is a JSON array of the values in `upsertKey` order, such as `["10","A-1"]`), `_sync_pulled_at` and `_sync_run_id` (the `sys_sync_run` row; not written when no run ledger is composed) on every row. `_sync_deleted_at` exists but stays empty until delete marking (D3) lands. A mapping whose `fieldMapping` targets a `_sync_` column is refused with `400 mapping_target_refused` when it runs (it was refused before as an unknown target). A connector pull whose target object's definition cannot be read is now refused the same way before it calls the connector, instead of writing rows it cannot stamp; the datasource pull already refused it. +- **BREAKING: a `_sync_` column in any other write is refused.** The engine refuses an insert or update naming a `_sync_` key with `400 ERR_SYNC_PROVENANCE_WRITE_REFUSED`, before middleware, defaults and hooks run, whatever the caller's context, `isSystem` included. A `_sync_` key a `beforeInsert` or `beforeUpdate` hook assigns, changes or removes is refused the same way before the driver is called, on any write, the pull's own included, so the pull's stamps are stored exactly as it wrote them. Only the pull's own write is admitted (`markSyncPullWrite`, exported from `@objectstack/objectql` with `SYNC_PULL_WRITE`, `SyncProvenanceWriteRefusedError` and `SYNC_PROVENANCE_WRITE_REFUSED_CODE`). The mark is consumed by that write, so a hook or flow it triggers writes as any other system caller and is refused the same way. Fix: leave the `_sync_` columns out of the write and out of your hooks; the next pull of the mapping stamps them. - Load-time diagnostics leave the injected `_sync_` columns out when they judge a served synced object, so it is not flagged for the reserved prefix; an author field under a `_sync_` name is still refused. diff --git a/content/docs/automation/jobs.mdx b/content/docs/automation/jobs.mdx index 322ffcf87b4..75d4d55beba 100644 --- a/content/docs/automation/jobs.mdx +++ b/content/docs/automation/jobs.mdx @@ -326,8 +326,11 @@ export const OrdersPullJob = defineJob({ record is kept). `_sync_deleted_at` is there but empty on every row: delete marking has not landed yet. Nothing else writes these columns: a write that names a `_sync_` column is refused with `400 - ERR_SYNC_PROVENANCE_WRITE_REFUSED`, a system-context one included, and a - mapping whose `fieldMapping` targets one is refused when it runs. A `synced` + ERR_SYNC_PROVENANCE_WRITE_REFUSED`, a system-context one included, and so is + a write whose `beforeInsert` or `beforeUpdate` hook assigns, changes or + removes one, the pull's own write included. A mapping whose `fieldMapping` + targets one is refused when it runs, and so is a connector pull whose target + object's definition cannot be read. A `synced` target that declares `systemFields: false` has none of these columns, and its rows are written without them. - **How a run is recorded.** A pull the platform refuses — the mapping is gone, diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 9691265b7e0..6efa829d3a5 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -47,7 +47,7 @@ import { SummaryRecomputeError } from './summary-errors.js'; import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js'; import { DuplicateRecordError } from './duplicate-record-error.js'; import { NotNullRefusalError, envelopeDriverWriteRefusal } from './not-null-refusal-error.js'; -import { refuseSyncProvenanceWrite } from './sync-provenance-write.js'; +import { refuseHookSyncProvenanceWrite, refuseSyncProvenanceWrite, snapshotSyncKeys } from './sync-provenance-write.js'; import { ASSIGNMENT_RULE_TYPE, AssignmentRuleEvaluator, OWNERSHIP_QUEUE_SOURCE_SLOT } from './assignment-rules.js'; import type { AssignmentQueueService } from './assignment-rules.js'; import { redactBoundStatement } from '@objectstack/types'; @@ -647,6 +647,8 @@ export class InsertFacet { // land on the SAME row object, so a hook mutating `ctx.input.data.x` in // place is mutating the engine's row exactly as it always has. const rowHookWrites: Array = []; + // [ADR-0153 D4] Each row's `_sync_` keys before the hooks, judged after the seal below. + const rowSyncBefore = (isBatch ? (defaultedData as any[]) : [defaultedData]).map((row) => snapshotSyncKeys(row)); const rowHookContexts: HookContext[] = (isBatch ? (defaultedData as any[]) : [defaultedData]).map( (row, rowIndex) => { const recording = @@ -706,6 +708,12 @@ export class InsertFacet { if (sealed) rowHookContexts[i]!.input.data = sealed.data as any; rowHookWrittenKeys[i] = sealed?.hookWrittenKeys; } + // [ADR-0153 D4] A `_sync_` key a hook assigned, changed or removed is refused, + // the pull's own write included (sync-provenance-write.ts, "The hooks' own writes"). + for (let i = 0; i < rowHookContexts.length; i++) { + if (undeclaredPerRow[i] !== undefined) continue; + refuseHookSyncProvenanceWrite(object, rowSyncBefore[i]!, rowHookContexts[i]!.input.data, 'insert'); + } // ── [#22306] HAND BACK what was withheld from beforeInsert ───────────── // diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 3a771dbdd99..e965e37cf93 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -35,7 +35,7 @@ import type { DroppedFieldsEvent, EngineUpdateOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { collectComposableReadableIds } from './filter-comparand-shape.js'; -import { refuseSyncProvenanceWrite } from './sync-provenance-write.js'; +import { refuseHookSyncProvenanceWrite, refuseSyncProvenanceWrite, snapshotSyncKeys } from './sync-provenance-write.js'; // [ADR-0155 D4] The fixed-read leaf seam reads the engine through the security // resolvers' host, built once per engine, which carries every member it reads. import { securityResolversHost } from './engine-facet-hosts.js'; @@ -724,6 +724,8 @@ export class UpdateFacet { opCtx.data !== null && typeof opCtx.data === 'object' ? recordHookPayloadWrites(opCtx.data as Record) : undefined; + // [ADR-0153 D4] The payload's `_sync_` keys before the hooks, judged after the seal. + const syncBeforeHooks = snapshotSyncKeys(opCtx.data); const hookContext: HookContext = { object, @@ -1103,6 +1105,9 @@ export class UpdateFacet { const sealedHookWrites = hookWrites?.seal(hookContext.input.data); if (sealedHookWrites) hookContext.input.data = sealedHookWrites.data as any; let hookWrittenKeys = sealedHookWrites?.hookWrittenKeys; + // [ADR-0153 D4] A `_sync_` key a hook assigned, changed or removed is refused, + // the pull's own write included (sync-provenance-write.ts, "The hooks' own writes"). + refuseHookSyncProvenanceWrite(object, syncBeforeHooks, hookContext.input.data, 'update'); // ── [#16344] HAND BACK what was hidden from the hooks ──────────────── // diff --git a/packages/objectql/src/sync-provenance-write.ts b/packages/objectql/src/sync-provenance-write.ts index 6318485e96c..7e0a77aec2e 100644 --- a/packages/objectql/src/sync-provenance-write.ts +++ b/packages/objectql/src/sync-provenance-write.ts @@ -30,6 +30,17 @@ * CONSUMES the mark — the engine continues with a copy of the context without * it — so a hook or flow the pull's write triggers writes as any other system * caller, and is refused like one. + * + * ## The hooks' own writes + * + * The caller's payload is judged before anything runs; the `before*` hooks run + * after, as server code, and may assign to the write's data. A `_sync_` key a + * hook assigns, changes or removes is refused too, the pull's write included + * (there a hook would overwrite the stamps D3 marks by): the engine snapshots + * the write's `_sync_` keys before the hooks ({@link snapshotSyncKeys}) and + * compares after them ({@link refuseHookSyncProvenanceWrite}), so the pull's + * stamps reach the driver exactly as the pull wrote them, and no other write + * carries one at all. */ import { SYNC_PROVENANCE_PREFIX } from '@objectstack/spec/data'; @@ -52,9 +63,11 @@ export function markSyncPullWrite(context: C): C & { [SYNC_PUL export const SYNC_PROVENANCE_WRITE_REFUSED_CODE = 'ERR_SYNC_PROVENANCE_WRITE_REFUSED' as const; /** - * A write named a `_sync_` provenance column and is not the pull's. Nothing was - * written: the refusal runs before the middleware, the defaults and the hooks. - * 400, since the payload itself is what is refused, whoever sent it. + * A write named a `_sync_` provenance column and is not the pull's, or a + * `before*` hook of a write assigned, changed or removed one (`by: 'hook'`). + * Nothing was written: the caller's payload is refused before the middleware, + * the defaults and the hooks, a hook's write before the driver. 400, since the + * payload itself is what is refused, whoever sent it. * * Identified by `code` rather than `instanceof`, the convention every engine * error here follows. @@ -69,12 +82,15 @@ export class SyncProvenanceWriteRefusedError extends Error { public readonly object: string, public readonly fields: string[], public readonly operation: 'insert' | 'update', + /** Who named the columns: the caller's payload, or a `before*` hook of the write. */ + public readonly by: 'caller' | 'hook' = 'caller', ) { super( - `Cannot ${operation} '${object}': ${fields.map((f) => `'${f}'`).join(', ')} ${fields.length === 1 ? 'is a' : 'are'} ` + `Cannot ${operation} '${object}': ${by === 'hook' ? `a before${operation === 'insert' ? 'Insert' : 'Update'} hook wrote ` : ''}` + + `${fields.map((f) => `'${f}'`).join(', ')}, ${fields.length === 1 ? 'a ' : ''}` + `sync-in provenance column${fields.length === 1 ? '' : 's'}, which only the sync-in pull writes (ADR-0153 D4), ` - + 'whatever the caller\'s context. Leave the _sync_ columns out of the write: the next pull of the mapping ' - + 'stamps them.', + + 'whatever the caller\'s context. Leave the _sync_ columns out of the write' + + (by === 'hook' ? ' and out of the hook' : '') + ': the next pull of the mapping stamps them.', ); this.name = 'SyncProvenanceWriteRefusedError'; } @@ -117,3 +133,41 @@ export function refuseSyncProvenanceWrite( const { [SYNC_PULL_WRITE]: _consumed, ...rest } = context as Record; return rest as C; } + +/** + * The write's `_sync_` keys and values before the `before*` hooks run, per row. + * A non-object row has none. + */ +export function snapshotSyncKeys(row: unknown): ReadonlyMap { + const snap = new Map(); + if (row === null || typeof row !== 'object' || Array.isArray(row)) return snap; + for (const [key, value] of Object.entries(row)) { + if (key.startsWith(SYNC_PROVENANCE_PREFIX)) snap.set(key, value); + } + return snap; +} + +/** + * Judge what the `before*` hooks did to one row's `_sync_` keys: any key they + * assigned, changed or removed relative to {@link snapshotSyncKeys} is refused + * with {@link SyncProvenanceWriteRefusedError} (`by: 'hook'`). On a write the + * caller judged clean the snapshot is empty, so any `_sync_` key is a hook's; + * on the pull's write it holds the pull's stamps, which must reach the driver + * as written. + */ +export function refuseHookSyncProvenanceWrite( + object: string, + before: ReadonlyMap, + after: unknown, + operation: 'insert' | 'update', +): void { + const now = snapshotSyncKeys(after); + const touched: string[] = []; + for (const [key, value] of now) { + if (!before.has(key) || !Object.is(before.get(key), value)) touched.push(key); + } + for (const key of before.keys()) { + if (!now.has(key)) touched.push(key); + } + if (touched.length > 0) throw new SyncProvenanceWriteRefusedError(object, touched, operation, 'hook'); +} diff --git a/packages/objectql/src/sync-provenance.test.ts b/packages/objectql/src/sync-provenance.test.ts index 4222559cb63..0583245237b 100644 --- a/packages/objectql/src/sync-provenance.test.ts +++ b/packages/objectql/src/sync-provenance.test.ts @@ -10,7 +10,9 @@ * again so a served document round-trips; * - the engine refuses a `_sync_` column in any write but the pull's, * `isSystem` included, and the pull's mark reaches exactly the one write it - * is put on — a hook's `ctx.api` write inside it is refused like any other. + * is put on — a hook's `ctx.api` write inside it is refused like any other, + * and so is a `_sync_` key a `before*` hook assigns, changes or removes, + * on any write, the pull's own included. * * A REAL {@link ObjectQL} over a minimal stub driver, the shape * `engine-audit-anchor-write.test.ts` uses. @@ -249,6 +251,71 @@ describe('[ADR-0153 D4] the engine refuses a _sync_ column in any write but the expect(SYNC_PULL_WRITE in hookContext).toBe(false); }); + it('a beforeInsert hook that assigns a _sync_ key on a system write is refused before the driver', async () => { + engine.registerHook('beforeInsert', async (ctx: any) => { + ctx.input.data._sync_deleted_at = new Date().toISOString(); + }, { object: 'erp_customer' }); + const err: any = await engine.insert('erp_customer', { code: 'C1' }, { context: system } as any).catch((e) => e); + expect(err?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.status).toBe(400); + expect(err?.by).toBe('hook'); + expect(err?.fields).toEqual(['_sync_deleted_at']); + expect(rig.calls.create).toBe(0); + }); + + it('a beforeInsert hook that rewrites the pull\'s own stamp is refused, by in-place write or by replacing the payload', async () => { + engine.registerHook('beforeInsert', async (ctx: any) => { + if (ctx.input.data.code === 'C1') ctx.input.data._sync_source = 'forged'; + else ctx.input.data = { ...ctx.input.data, _sync_source: undefined }; + }, { object: 'erp_customer' }); + for (const code of ['C1', 'C2']) { + const err: any = await engine + .insert('erp_customer', { code, _sync_source: 'erp_customers' }, { context: markSyncPullWrite(system) } as any) + .catch((e) => e); + expect(err?.code, code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.fields, code).toEqual(['_sync_source']); + } + expect(rig.calls.create).toBe(0); + }); + + it('a beforeUpdate hook that assigns a _sync_ key on a system update is refused before the driver', async () => { + const row: any = await engine.insert('erp_customer', { code: 'C1' }, { context: system } as any); + engine.registerHook('beforeUpdate', async (ctx: any) => { + ctx.input.data._sync_source = 'forged'; + }, { object: 'erp_customer' }); + const err: any = await engine + .update('erp_customer', { id: row.id, title: 'x' }, { context: system } as any) + .catch((e) => e); + expect(err?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.by).toBe('hook'); + expect(rig.calls.update).toBe(0); + }); + + it('a beforeUpdate hook that rewrites the pull\'s stamp on its update is refused', async () => { + const row: any = await engine.insert('erp_customer', { code: 'C1', _sync_run_id: 'run_1' }, { context: markSyncPullWrite(system) } as any); + engine.registerHook('beforeUpdate', async (ctx: any) => { + ctx.input.data._sync_run_id = 'run_x'; + }, { object: 'erp_customer' }); + const err: any = await engine + .update('erp_customer', { id: row.id, _sync_run_id: 'run_2' }, { context: markSyncPullWrite(system) } as any) + .catch((e) => e); + expect(err?.code).toBe(SYNC_PROVENANCE_WRITE_REFUSED_CODE); + expect(err?.fields).toEqual(['_sync_run_id']); + expect(rig.calls.update).toBe(0); + }); + + it('CONTROL: a hook that writes a mapped field of the pull\'s write lets the stamps through untouched', async () => { + engine.registerHook('beforeInsert', async (ctx: any) => { + ctx.input.data.title = 'from hook'; + }, { object: 'erp_customer' }); + const row: any = await engine.insert( + 'erp_customer', + { code: 'C1', _sync_source: 'erp_customers', _sync_external_id: 'C1' }, + { context: markSyncPullWrite(system) } as any, + ); + expect(row).toMatchObject({ title: 'from hook', _sync_source: 'erp_customers', _sync_external_id: 'C1' }); + }); + it('a hook\'s ctx.api write inside the pull\'s write is refused like any other', async () => { let nested: any; engine.registerHook('beforeInsert', async (ctx: any) => { diff --git a/packages/services/service-automation/src/connector-pull.test.ts b/packages/services/service-automation/src/connector-pull.test.ts index 329a990a697..68c4f7a9894 100644 --- a/packages/services/service-automation/src/connector-pull.test.ts +++ b/packages/services/service-automation/src/connector-pull.test.ts @@ -68,8 +68,8 @@ function harness(opts: { stored?: Array>; /** The `inputSchema` the action declares on `GET /connectors`; absent ⇒ none declared. */ inputSchema?: Record; - /** The target `contact` as the protocol serves it; absent ⇒ {@link contactObject}. */ - object?: Record; + /** The target `contact` as the protocol serves it; absent ⇒ {@link contactObject}; `null` ⇒ not served. */ + object?: Record | null; } = {}): Harness { const writes: unknown[] = []; const handler = vi.fn(async () => (opts.result ?? { status: 200, ok: true, body: [] }) as Record); @@ -80,7 +80,7 @@ function harness(opts: { if (type === 'mapping' && mapping && name === (mapping as { name: string }).name) { return { type, name, item: mapping }; } - if (type === 'object' && name === 'contact') return { type, name, item: opts.object ?? contactObject }; + if (type === 'object' && name === 'contact') return { type, name, item: opts.object === undefined ? contactObject : opts.object ?? undefined }; return undefined; }, async findData() { return { records: opts.stored ?? [] }; }, @@ -956,6 +956,13 @@ describe('[ADR-0153 D4] a connector pull stamps provenance on a synced target', expect(h.writes).toEqual([]); }); + it('a target whose definition cannot be read is refused mapping_target_refused (400) before the action is called', async () => { + const h = harness({ object: null }); + expectRefused(await refusal(h), { code: 'VALIDATION_ERROR', status: 400, reason: 'mapping_target_refused' }); + expect(h.handler).not.toHaveBeenCalled(); + expect(h.writes).toEqual([]); + }); + it('a synced target that withholds every injected column (systemFields: false) is written unstamped, unmarked', async () => { const h = harness({ object: { ...syncedContact, systemFields: false }, result: { status: 200, ok: true, body: body.slice(0, 1) } }); await pullConnectorSource(h.deps, { mapping: 'crm_contacts', context: { isSystem: true } }); diff --git a/packages/services/service-automation/src/connector-pull.ts b/packages/services/service-automation/src/connector-pull.ts index 22fb2941df5..fc33150b5a4 100644 --- a/packages/services/service-automation/src/connector-pull.ts +++ b/packages/services/service-automation/src/connector-pull.ts @@ -788,6 +788,15 @@ async function pullOnce( `Mapping "${mappingName}": fieldMapping writes '${mappedSync}', a sync-in provenance column the pull stamps ` + 'itself (ADR-0153 D4); remove that entry.'); } + // A target whose definition this run cannot read is refused before the + // call: whether its rows owe the provenance stamps is a question of its + // definition, and a row written without them could never be marked or + // repaired by a later run. (The datasource pull refuses the same way.) + if (!isPlainObject(schema)) { + return refuse('VALIDATION_ERROR', 400, 'mapping_target_refused', + `Mapping "${mappingName}": the definition of targetObject '${objectName}' could not be read, so the pull ` + + 'cannot tell which provenance columns its rows carry (ADR-0153 D4). Register the object, then run the pull again.'); + } const stampsProvenance = carriesSyncProvenanceColumns(schema); const refusedTarget = refuseUnknownMappingTargets(artifact, objectName, schema); if (refusedTarget) return refuseWith(refusedTarget, 'mapping_target_refused'); diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index fc392d810c2..cd89cad13f9 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -950,12 +950,14 @@ export const ERROR_CODE_LEDGER = { // any standard member: it is neither the client's bad input (the caller is // server-side automation) nor a missing precondition on a request. 'ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED', - // [ADR-0153 D4] A write named a `_sync_` provenance column of a `synced` - // object and is not the sync-in pull's. 400, judged on the caller's - // payload before the middleware, the defaults or a hook run, so nothing is - // written (`SyncProvenanceWriteRefusedError`, `sync-provenance-write.ts`). - // Refused whatever the caller's context, `isSystem` included: the pull is - // the columns' only writer. + // [ADR-0153 D4] A write named a `_sync_` provenance column and is not the + // sync-in pull's, or a `before*` hook of any write (the pull's included) + // assigned, changed or removed one. 400, judged on the caller's payload + // before the middleware, the defaults or a hook run, and on the hooks' + // writes before the driver, so nothing is written + // (`SyncProvenanceWriteRefusedError`, `sync-provenance-write.ts`). Refused + // whatever the caller's context, `isSystem` included: the pull is the + // columns' only writer. 'ERR_SYNC_PROVENANCE_WRITE_REFUSED', // [#8846] `transaction({ require: true })` on a driver with no // `beginTransaction` — thrown BEFORE the callback runs, so nothing has diff --git a/packages/spec/src/data/injected-system-column-provenance.ts b/packages/spec/src/data/injected-system-column-provenance.ts index 5e468a39b84..5656086303b 100644 --- a/packages/spec/src/data/injected-system-column-provenance.ts +++ b/packages/spec/src/data/injected-system-column-provenance.ts @@ -218,8 +218,9 @@ export const SYNC_PROVENANCE_FIELD_DEFS = { readonly: true, system: true, description: - "The row's key in the source, as text: the source value of the mapping's upsertKey, or for a key of several " - + 'fields a JSON array of their values in upsertKey order (ADR-0153 D4). Written by the pull only.', + "The row's key in the source, as text: the value the mapping writes to its upsertKey field (the source value " + + 'for a plain copy), or for a key of several fields a JSON array of those values in upsertKey order ' + + '(ADR-0153 D4). Written by the pull only.', }, _sync_pulled_at: { type: 'datetime',