Skip to content
21 changes: 21 additions & 0 deletions .changeset/32062-sync-provenance-columns.md
Original file line number Diff line number Diff line change
@@ -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-0087: not-required (no-migration-prescription) No authorable key is added, removed, renamed or re-shaped, and every metadata document that parsed before parses the same. What changes is the registered shape of a `managedBy: 'synced'` object (five platform columns and one index the platform adds) and the answer a data write gets when it names a `_sync_` column: no authored value has to be rewritten, so there is nothing for a migration to prescribe and no tombstone. -->

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). 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.
5 changes: 3 additions & 2 deletions content/docs/automation/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
</Callout>

Expand Down
3 changes: 2 additions & 1 deletion content/docs/automation/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions content/docs/automation/jobs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,24 @@ 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 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,
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
Expand Down
2 changes: 1 addition & 1 deletion content/docs/data-modeling/objects.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion content/docs/references/api/automation-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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`
Expand Down
3 changes: 2 additions & 1 deletion content/docs/references/api/contract.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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`
Expand Down
1 change: 1 addition & 0 deletions content/docs/references/api/error-code-ledger.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// 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';
// 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';

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<string, any>;
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<typeof computeMetadataDiagnostics>) =>
(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<string, any>;
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);
});
});
35 changes: 34 additions & 1 deletion packages/metadata-protocol/src/metadata-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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<string, unknown> | undefined;
for (const name of SYNC_PROVENANCE_COLUMNS) {
const field = (fields as Record<string, unknown>)[name];
if (field === undefined || !isInjectedColumnDefinition(field, SYNC_PROVENANCE_FIELD_DEFS[name])) continue;
next ??= { ...(fields as Record<string, unknown>) };
delete next[name];
}
return next ? { ...(document as object), fields: next } : document;
}

/**
* Compute spec diagnostics for a single metadata document.
*
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading