AI System DesignAI System Design FundamentalsModule 11 — Architecture contracts and integration

Designing Reversible Proposal-and-Commit Workflows for AI Bulk Catalog Edits

Question 23 of 47 · Updated

On this page

Let AI propose changes, not perform them. Build a product-owned change-set service that freezes the selected catalog records and their base revisions, validates structured suggestions, renders a trustworthy before/after preview, binds approval to an immutable proposal, and commits only authorized edits against current authoritative revisions. Record the exact committed changes and make undo a new, separately validated revision rather than a blind restoration of an old snapshot. This preserves concurrent human work, makes retry safe, and gives the merchant control over the scope and consequences of bulk AI editing.

Original curriculum question: How would you design a reversible proposal-and-commit workflow for AI-generated bulk catalog edits?

ASD-082 | Module 11 — Architecture contracts and integration | Progressive learning order 10. ASD-081 defines how model outputs become versioned domain artifacts. ASD-006 established prediction versus decision authority and transactional invariants; this lesson takes that boundary into a concrete editing product, including frozen selections, semantic field diffs, batch manifests, preview and acceptance, per-record revision preconditions, historical inverses and conflict resolution. Existing agent approval lessons cover pausing/resuming a workflow, not this catalog edit lifecycle. ASD-018 covers cross-system compensation and uncertain external effects; here the primary commitment boundary is one authoritative catalog. Downstream indexes are derived projections, not independent business transactions. Later catalog enrichment lessons cover obtaining high-quality attributes from multimodal inputs; the pending data-cleaning agent lesson addresses general data-quality transformations. We focus on safe application of already proposed changes. Cross-system approval queues, policy exceptions, downstream correction and evidence infrastructure receive separate treatment.

All workload counts, product fields, timings, cost and acceptance thresholds in the worked examples are hypothetical. The executable example was tested in a local in-memory SQLite database; no real product catalog, model, network or production deployment was used.

1. Requirements: the editor's contract#

Imagine a merchant with 80,000 SKUs wants to standardize titles, rewrite descriptions and normalize approved category attributes. An AI tool can suggest changes for a filtered selection of 12,000 items. It must not silently publish thousands of generated claims, modify price or inventory, overwrite a merchandiser's intervening corrections, or treat a successful model response as a committed catalog update.

The product should let an authorized user choose the affected records and allowed fields, obtain a preview, inspect and revise suggestions, approve an exact subset, commit according to a declared atomicity policy, inspect receipts, and request undo for eligible committed changes.

Functional requirementExample acceptance contract
ScopeOnly explicitly selected authorized SKUs and allowed fields may be proposed or committed
PreviewDisplay current/base value, proposed value, semantic impact, validation and evidence
ApprovalExact approved manifest and revision; new approval after material change
CommitRecheck current permission, constraints, revision and expiry; record actual result
RetryOne committed effect per logical plan or chunk; distinguish duplicate from changed payload
UndoRestore prior values only under valid current preconditions; append a new revision
ConflictsPreserve human or newer edits; show actionable resolution rather than silent overwrite
AuditLink proposal, approvals, original and resulting revisions, receipts and inverse operations

Nonfunctional requirements include bounded generation and preview time, durable job progress, preview rendering performance, accessibility, current authorization, recoverability, bounded write contention, retention of revision history and measurable downstream publication lag. Define success per logical approved edit and per bulk operation, not merely the percentage of model calls returning valid JSON. A merchant may accept partial success for unrelated title edits while requiring all-or-nothing treatment for a group of variants whose attributes must remain consistent.

2. Architecture: separate generation, review and the authoritative write path#

Loading diagram…

The model worker gets only authorized source data and a restricted proposal schema. It has no credential capable of directly changing a catalog. The authoritative service owns identities, editable fields, allowed transformations, constraints, revisions and writes. The preview is constructed from a validated patch and the trusted base record, not from a model-generated explanation of what it changed.

A durable proposal store contains drafts and immutable proposal versions; approval records and receipts bind exact versions. An asynchronous worker pool may generate and validate many proposals, while the commit executor remains narrowly scoped and uses bounded database transactions. A modular monolith can implement these roles; separate services are optional when resource isolation or ownership warrants them.

Separate three kinds of state: what the model suggested, what the reviewer authorized, and what the catalog actually committed. Never use a single ambiguous status such as "AI updated" to represent all three.

3. Freeze the selection: a filter is not a manifest#

Suppose the user asks "fix the titles of all blue shirts with missing brand prefixes." That filter may match 600 items now and 800 later. Re-evaluating it at commit time silently expands authorization beyond what was previewed. Resolve the selection on a consistent authorized view and persist an immutable manifest of canonical product or variant IDs, selected fields, base revisions, scope and source evidence references.

For large selections, a content-addressed manifest can reference immutable pages or partitions. Record the expected count and manifest digest. The page list, ordering or canonical order, schema version, snapshot position, tenant and operation scope must be covered by the digest. A digest of one page does not prove completeness of the other pages. An approval of a dynamic predicate is a different product contract with explicitly governed future membership; it must never be substituted for approval of a frozen set.

Capture consistent per-record base state. A long-running scan may not provide one globally consistent snapshot: record that limitation, use a database-supported consistent snapshot or defined cutoff where required, and validate all affected records at commit. Use opaque IDs, not human-visible SKU codes that can be reused or changed, where the production catalog supports them. Model-supplied identifiers must resolve within the selected allowlist; do not create records or cross tenants because the model invented a plausible identifier.

Handle duplicates, variants, deleted products and stale source fields. Resolve the operation's target to a specific authoritative aggregate, e.g. product-level description versus variant-level color, rather than interpreting both as freely editable rows. A preview must not disclose data from a product that the requester can no longer access.

4. Structured proposals and safe operations#

Use a small, domain-specific schema rather than allowing the model to produce executable SQL or an arbitrary JSON Patch over the complete product object. JSON Patch (RFC 6902) is useful as a standardized patch language, but its paths, operations and array semantics need restrictive validation. Prefer named catalog operations when they express business meaning better than unrestricted structural paths.

Illustrative *server-normalized* proposal entry:

JSON
{ "schema_version": "catalog-edit/v1", "proposal_id": "plan-42", "proposal_revision": 3, "product_id": "prod-170", "base_revision": 17, "changes": [ { "op": "replace_title", "before": "cotton shirt blue m", "after": "Blue Cotton Shirt — M", "evidence_refs": ["supplier-spec-19"] }, { "op": "set_color", "before": null, "after": "blue", "evidence_refs": ["variant-spec-31"] } ], "policy_version": "catalog-content/v4" }

The trusted service fills identifiers, old values, revision and policy context from its snapshot; it does not trust model-authored before values. An LLM may return a constrained suggestion such as {op, proposed value, evidence candidate}. Treat it as untrusted input. Distinguish a missing field from an explicit null, an empty string, an unset operation and deletion. Require stable units, locale and enum mappings. For ordered media and option lists, use stable element identities or versioned list operations rather than stale array positions.

Define an allowlist for operation types and fields. Title normalization may be permitted, but prices, quantities, tax classes, shipping restrictions, safety warnings, published inventory and ownership need separate authority and domain checks. Do not allow model-generated text to remove legally or operationally required disclosures. A model cannot change the allowed-field list, reviewer identity or approval status.

Validate schema, length and encoding, supported locale, allowed categories, units, referential integrity, required attributes and cross-field rules. Validate HTML or rich text according to safe rendering policy; never render arbitrary generated scripts. Check claims against authorized source facts. For example, adding "organic", "waterproof" or "certified" to a title requires evidence, not a confidence score. Unsupported content should be flagged or rejected, not rewritten into a plausible false claim.

The output schema constrains structure, not truth. An approved catalog policy or evidence check must verify that the content is appropriate to publish.

5. Dry runs and semantic diffs#

A dry run computes the proposed effects without changing authoritative catalog state. Use the same operation interpreter and domain constraints as the real executor wherever feasible. A validation-only path cannot reserve future success; data and permissions may change afterward.

A robust preview contains:

ItemBeforeProposedResult
A-100 titlecotton shirt blue mBlue Cotton Shirt — MEligible
A-101 materialcottonorganic cottonBlocked: unsupported claim
A-102 sizeM38Blocked: incompatible size convention
A-103 descriptionExisting descriptionShorter source-grounded descriptionReview required
A-104 price1,299 INR999 INRBlocked: forbidden operation

This is a semantic diff, not merely a character diff. A title's whitespace change is different from a new product property or a price mutation. Highlight changed claims, categories, units, data loss, required warnings, published visibility and variant consistency. Use normalized comparison only where equivalence is explicitly defined; normalizing strings can remove meaningful case, symbols or locale differences. Preserve original bytes or a canonical representation sufficient for the actual inverse.

Show exact counts for proposed, no-op, blocked, review-required and eligible entries, with drill-down by reason and affected field. Precompute paginated diffs, keep the source revision visible and let reviewers select a subset. If a reviewer edits a suggestion or removes an entry, issue a new immutable manifest revision/digest and invalidate earlier approval of the changed manifest. Do not approve hidden filtered-out rows accidentally.

A dry run may need to simulate aggregate constraints, such as a product's variant option uniqueness. Compute cross-record validation over the same declared atomic group. If a constraint depends on live external state, record that check as preliminary and perform an authoritative check at commitment. Never claim a preview guarantees future success.

6. State machine and approval contract#

Loading diagram…

This is an operation lifecycle diagram, not a database state transition implementation. A new proposal after conflict or an inverse has a new identity/version and links to its predecessor; it does not mutate the old approved artifact. Committed historical records remain committed even if later undone. A job-level status can represent partial completion only when the operation contract explicitly allows it; per-item/chunk receipts carry the actual truth.

Approval binds tenant, exact manifest digest, schema and policy versions, approved fields/records, operation type, authorized actor or role constraints, reviewer identity, reason and expiry. Use server-issued approval records; the model cannot author them. Canonicalize the manifest using a specified algorithm (RFC 8785 is one option for suitable JSON data), and include the ordering and all material fields. A digest detects payload mismatch but is not authorization or a signature. Authentication, protected storage and role checks remain mandatory.

For high-impact changes, enforce separation of duties or multiple approvals as required. The UI should provide adequate review evidence, not a blind "approve all" button that conceals risks. Allow reviewers to reject, exclude entries or request revisions. Silence is not consent. Current actor, object and field permissions must be checked again before the write. If approval expires or a relevant policy or reviewed base revision changes, hold or replan. Human approval does not override mandatory business invariants.

Review effort is a practical bottleneck. For illustration, 12,000 proposed items at six seconds of individual review each require 72,000 seconds, or 20 reviewer-hours, excluding exceptions and coordination. Grouping equivalent low-risk transformations with clear counts and representative samples may reduce effort if the policy permits it. Do not treat sample approval as approval of every semantically different item unless the governing procedure explicitly allows and bounds that scope. Assess unsupported-claim risk and high-impact exceptions separately.

7. Optimistic concurrency control and the commit boundary#

Use a monotonic revision or strong version token for each authoritative aggregate. Optimistic concurrency control assumes conflicts are uncommon and verifies the expected revision at write time. An HTTP If-Match precondition can express a strong ETag requirement on a single resource, but an application-level bulk manifest still needs per-record or per-group preconditions.

An illustrative PostgreSQL operation (schema names are hypothetical; this is not executed):

SQL
UPDATE catalog_product SET title = $1, revision = revision + 1 WHERE tenant_id = $2 AND product_id = $3 AND revision = $4 AND title IS NOT DISTINCT FROM $5 RETURNING product_id, title, revision;

A zero-row result means the operation did not commit that change. Do not fetch the new revision and retry automatically with the stale approved payload. The predicate and transaction semantics must be compatible with the actual database. Tenant and object identity are obtained from trusted authorized scope. Production SQL should use parameter binding, appropriately restricted write privileges and database constraints.

An all-or-nothing change set has one bounded transaction:

  1. Obtain the immutable approved manifest and current actor context, and claim or resolve the logical operation key.
  2. Recheck current grants, policy compatibility, approval binding, expiry and allowed field scope.
  3. Check or lock relevant authoritative records and any aggregate invariants in deterministic order.
  4. Perform conditional updates; require the expected number of affected rows and validate new state.
  5. Store before/after changes, new revisions, one committed receipt and any outbox entries in the same transaction.
  6. Commit. Return success only after authoritative commitment; otherwise resolve the ambiguous state or return a typed failure.

Read and write isolation must actually protect cross-row invariants. A row-local version predicate does not prevent two transactions independently violating a catalog-wide uniqueness or quota rule. Use unique/check constraints, an explicitly locked aggregate, or a suitable serializable transaction with bounded retries. Lock acquisition order reduces some deadlock risk but cannot eliminate all concurrency anomalies. Never hold locks while calling an LLM or waiting for reviewer approval.

Loading diagram…

If approval/identity reside outside the database, a remote check is not made atomic by opening a database transaction. Define the actual consistency and revocation contract or keep critical checks at the resource owner; the diagram assumes appropriate current checks can be enforced. If a caller is no longer authorized, do not disclose the receipt merely because its ID is known.

8. Idempotency and ambiguous outcomes#

Networks can fail after a catalog transaction commits but before the response arrives. The caller cannot conclude failure from a timeout. Associate every intent with a stable tenant-scoped operation ID and canonical payload digest. Persist the receipt and resulting revisions transactionally with the updates. A repeat with matching digest returns the original outcome; a reuse with different digest returns a conflict. Scope receipt access to the currently authorized principal and resource. Decide whether and which failed attempts reserve the key; record transient failures differently from committed receipts.

Idempotency does not mean repeatedly setting a value is always safe. An old edit replay can overwrite a later edit, increment a revision twice, emit duplicate events or create duplicate audit records. Deduplicate the logical effect, not just the final text. Expiration of a proposal prevents a new commitment, but an authorized retry of an already committed intent should be able to recover its receipt according to the retention contract without executing again.

A conditional update with a version check alone is insufficient to resolve an ambiguous response: a subsequent zero-row result may mean the previous attempt succeeded or another writer won. The receipt tells the difference. If receipt retention expires, do not accept an ancient retry as a new operation silently. Preserve appropriate tombstones or explicitly bound the supported replay interval.

Example API surfaces:

APIConsumer contract
POST /catalog-edit-plansCreate a durable scoped proposal-generation job or plan
GET /catalog-edit-plans/{id}/previewAuthorized immutable manifest, summary and paged diffs
POST /catalog-edit-plans/{id}/approvalsBind reviewer decision to exact digest and version
POST /catalog-edit-plans/{id}/commitRequest commit of approved immutable intent
GET /catalog-edit-receipts/{id}Resolve actual committed/partial state and revisions
POST /catalog-edit-receipts/{id}/undo-plansCreate a new inverse draft from committed history

Return documented HTTP semantics: a 202 for durable acceptance is not a completed mutation, a conflict such as 409 or a failed HTTP precondition such as 412 should be meaningful, and a timeout requires status lookup if outcome is uncertain. Use safe structured error types and correlation IDs. Do not expose protected record existence or details to unauthorized callers. For bulk jobs, include the chosen consistency mode and per-chunk progress.

9. Bulk execution, partial failures and scaling#

A single all-or-nothing transaction is attractive for a bounded set with coupled constraints. A huge transaction across tens of thousands of records can hold locks, grow logs, delay replication, exhaust memory and create expensive retries. Decide semantics explicitly:

ModeAppropriate useUser-visible contract
Atomic small planRelated variants or small reviewed batchAll changes commit or none
Atomic bounded groupsIndependent product/variant aggregatesEach group atomic; plan may be partial
Staged catalog generationPublication requires a coherent full snapshot and storage architecture supports itValidate staged generation then atomically promote manifest/pointer
Independent per-item updatesUnrelated attributes where partial success is acceptableExact per-item committed/conflicted/skipped receipts

If the merchant selects independent-title mode for 12,000 products, group into chunks according to tested lock duration and workload. Suppose chunks contain up to 200 edits, so 60 chunks are needed. If 55 commit fully, three conflict entirely and two are not yet attempted, actual state is 11,000 committed, 600 conflicted and 400 pending assuming every chunk contains exactly 200 entries. Do not report all 12,000 completed just because suggestion generation finished. A cancellation after chunk 55 stops unstarted chunks, but does not revert already committed chunks. Undo is a separate approved operation against the actual committed subset.

Give chunks stable identities derived from the frozen manifest and grouping plan. Bind each to its digest and policy, and store durable receipts plus retry attempts. A worker claim requires ownership or a lease/fencing protocol appropriate to the architecture. Persist progress using authoritative receipts; do not use an incrementing counter that can be double-counted on retry. Jobs that fail with a known conflict are not automatically retried with new base revisions.

Partition by the true invariant boundary: product and variants, not an arbitrary item count that splits mandatory groups. Lock in consistent key order within a transaction and bound the work. Set per-tenant admission limits, queue size/age limits and retry budgets; isolate generation workloads from interactive catalog browsing and writes. Batch LLM calls where supported but preserve item-level association and validate each entry independently. Never allow one misassociated response to edit another product.

For a coherent staged generation, write validated immutable snapshots or versioned overlays into staging, reconcile all required data, and atomically change the catalog's published generation reference under a write-ownership protocol. Readers must honor the generation, and concurrent live writes need explicit capture/merge rules. A pointer flip is not inherently sufficient for a mutable catalog; assess whether the data model supports it. Retaining two entire generations may be costly and undo of a later live edit still needs conflict handling.

10. History: record the changes that actually committed#

Keep authoritative revision history with a stable relationship between a committed plan, record changes and the resulting revision. History is not the model's proposed diff or the approval alone.

Ledger fieldPurpose
Tenant, entity ID and operation IDScope and correlation
Base and committed revisionIdentify actual pre/post states
Field operation, before and afterConstruct inverse and explain effect
Manifest digest and policy/approval refsEstablish reviewed content and authority
Actor, trusted commit timeAccountability
Parent receipt or reverses IDLineage for corrections and undo
Event/receipt statusDistinguish committed state from downstream projection
Retention classificationLimit exposure and support compliant deletion

Use append-only logical revision records or equivalent governed version history. An immutable snapshot of the actual change may be more robust than regenerating the old state from an LLM. Store sufficient type information for exact inversion, including missing versus null, units, array identities and relationships. No-op edits should be identified during planning; do not manufacture meaningless revisions unless the domain explicitly requires them.

Retention must balance reversibility and privacy. Product descriptions may contain inadvertently uploaded personal information or copyrighted source material. Historical access is itself protected; do not expose deleted content via an undo preview. Record limited evidence references instead of duplicating raw source documents and prompts. If approved deletion or legal obligations require removal of a historical value, the operation may no longer be reversible; show this explicitly. Cryptographic hashes support integrity checks but do not prove truth, authorization or completeness alone.

11. Conflict-aware undo is a new change, not a rewind#

A reversible operation captures the inverse of each committed field change. If the forward edit replaced title A with B at revision 17, commitment produces revision 18. A safe strict inverse expects revision 18 and value B, proposes restoring A, and if approved and committed produces revision 19. Revision numbers must not decrease.

Worked example:

StepTitleRevision
Originalcotton shirt blue m17
Approved AI commitBlue Cotton Shirt — M18
Human correctionNavy Cotton Shirt — M19
Requested undocotton shirt blue mNot committed

The old inverse expects 18, but the record is now at 19. Restoring the entire original value would discard the human correction. Under strict whole-record version semantics, conflict; preserve revision 19. Show the user the original A, AI-applied B, and current C and the exact overlapping fields.

For a more permissive field-level merge, consider a product whose AI operation changed title while a human changed only the description. A field-level version or tracked last-writer lineage might establish that the title still carries the AI change. Generate a new inverse against the current record that preserves description and checks all cross-field invariants. A simple equality test (current title equals B) is not always sufficient: an intervening writer may have changed it and then restored B (the ABA problem). Use actual field revisions/lineage or conservative whole-record checks. Never automatically merge conflicting changes without a documented semantic policy.

Loading diagram…

Undo can fail for reasons beyond revision conflict: revoked access, removed field, newly mandatory value, deleted entity, unavailable historical content, changed taxonomy, dependent product state or expired approval. Do not recreate a removed product silently or restore a now-prohibited claim. Build a new validated correction where allowed. Treat redo as another operation, not changing history flags. A second attempt to undo the same original receipt should return the matching inverse receipt if it is the same logical operation; a new distinct inverse request must still verify actual post-state and lineage.

Reversibility has a scope. A catalog title revision can be reversed in the catalog, but a customer who already saw the old title cannot unsee it. An external advertisement, sale, notification or financial effect requires separate reconciliation and potentially compensation. ASD-018 covers that problem. Do not market local field undo as a universal reversal of real-world consequences.

12. Practical tested implementation: atomic title edits and strict undo#

The example below uses standard-library Python and SQLite to illustrate a deliberately narrow authoritative catalog: tenant-scoped title edits, one atomic plan of up to 100 items, digest-bound approval, optimistic revision checks, before/after history and receipt-derived strict undo. No inference or external effects occur. The local fixture represents already normalized trusted server context, and the reviewer grant and editor grant are controlled database rows.

PYTHON
from dataclasses import dataclass, asdict, replace from hashlib import sha256 import json import sqlite3 @dataclass(frozen=True) class Edit: sku: str revision: int before: str after: str @dataclass(frozen=True) class Plan: tenant: str plan_id: str expires: int edits: tuple[Edit, ...] reverses: str | None = None def digest(plan): body = json.dumps(asdict(plan), sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False) return sha256(body.encode('utf-8')).hexdigest() def grant(db, tenant, actor, role): return db.execute('SELECT 1 FROM grants WHERE tenant=? AND actor=? AND role=?', (tenant, actor, role)).fetchone() is not None def inverse(db, tenant, receipt_id, undo_id, expires): # Internal helper: caller must authorize history access first. rows = db.execute('SELECT sku, revision, before, after FROM history ' 'WHERE tenant=? AND plan_id=? ORDER BY sku', (tenant, receipt_id)).fetchall() if not rows: raise ValueError('unknown receipt') return Plan(tenant, undo_id, expires, tuple(Edit(s, rev, after, before) for s, rev, before, after in rows), receipt_id) def commit(db, plan, actor, now): # Actor, plan and time come from trusted server context in this example. db.execute('BEGIN IMMEDIATE') try: def done(result): db.commit() return result if not grant(db, plan.tenant, actor, 'editor'): return done('DENIED') if (not plan.plan_id or type(plan.expires) is not int or not plan.edits or len(plan.edits) > 100 or len({e.sku for e in plan.edits}) != len(plan.edits) or any(not e.sku or type(e.revision) is not int or e.revision < 1 or type(e.before) is not str or type(e.after) is not str or not e.after.strip() or len(e.after) > 120 or e.before == e.after for e in plan.edits)): return done('INVALID') d = digest(plan) old = db.execute('SELECT digest FROM receipts WHERE tenant=? AND plan_id=?', (plan.tenant, plan.plan_id)).fetchone() if old: return done('COMMITTED' if old[0] == d else 'KEY_CONFLICT') if now >= plan.expires: return done('EXPIRED') approval = db.execute('SELECT reviewer, expires FROM approvals ' 'WHERE tenant=? AND plan_id=? AND digest=?', (plan.tenant, plan.plan_id, d)).fetchone() if (not approval or approval[0] == actor or now >= approval[1] or not grant(db, plan.tenant, approval[0], 'reviewer')): return done('NOT_APPROVED') if plan.reverses is not None: try: expected = inverse(db, plan.tenant, plan.reverses, plan.plan_id, plan.expires) except ValueError: return done('INVALID') if expected != plan: return done('INVALID') for e in sorted(plan.edits, key=lambda e: e.sku): changed = db.execute('UPDATE catalog SET title=?, revision=revision+1 ' 'WHERE tenant=? AND sku=? AND revision=? AND title=?', (e.after, plan.tenant, e.sku, e.revision, e.before)) if changed.rowcount != 1: db.rollback() return 'CONFLICT' db.execute('INSERT INTO history VALUES (?,?,?,?,?,?)', (plan.tenant, plan.plan_id, e.sku, e.revision+1, e.before, e.after)) db.execute('INSERT INTO receipts VALUES (?,?,?,?)', (plan.tenant, plan.plan_id, d, plan.reverses)) return done('COMMITTED') except BaseException: db.rollback() raise def main(): db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE catalog(tenant TEXT, sku TEXT, title TEXT, revision INTEGER, PRIMARY KEY(tenant,sku)); CREATE TABLE grants(tenant TEXT, actor TEXT, role TEXT, PRIMARY KEY(tenant,actor,role)); CREATE TABLE approvals(tenant TEXT, plan_id TEXT, digest TEXT, reviewer TEXT, expires INTEGER, PRIMARY KEY(tenant,plan_id)); CREATE TABLE receipts(tenant TEXT, plan_id TEXT, digest TEXT, reverses TEXT, PRIMARY KEY(tenant,plan_id)); CREATE TABLE history(tenant TEXT, plan_id TEXT, sku TEXT, revision INTEGER, before TEXT, after TEXT, PRIMARY KEY(tenant,plan_id,sku)); INSERT INTO catalog VALUES ('a','1','Old A',1),('a','2','Old B',1),('b','1','Private',1); INSERT INTO grants VALUES ('a','editor','editor'),('a','reviewer','reviewer');''') def approve(p, reviewer='reviewer', expiry=90): db.execute('INSERT OR REPLACE INTO approvals VALUES (?,?,?,?,?)', (p.tenant, p.plan_id, digest(p), reviewer, expiry)) def state(): return db.execute('SELECT sku,title,revision FROM catalog WHERE tenant=\'a\' ORDER BY sku').fetchall() p = Plan('a','p1',100,(Edit('1',1,'Old A','New A'),Edit('2',1,'Old B','New B'))) assert commit(db,p,'stranger',10) == 'DENIED' assert commit(db,replace(p,tenant='b'),'editor',10) == 'DENIED' assert commit(db,p,'editor',10) == 'NOT_APPROVED' assert commit(db,replace(p,edits=(p.edits[0],p.edits[0])),'editor',10) == 'INVALID' approve(p) assert commit(db,replace(p,edits=(replace(p.edits[0],after='Changed'),p.edits[1])),'editor',10) == 'NOT_APPROVED' assert commit(db,p,'editor',100) == 'EXPIRED' assert commit(db,p,'editor',90) == 'NOT_APPROVED' bad = replace(p,plan_id='bad',edits=(p.edits[0],replace(p.edits[1],revision=2))) approve(bad) assert commit(db,bad,'editor',10) == 'CONFLICT' assert state() == [('1','Old A',1),('2','Old B',1)] assert db.execute('SELECT count(*) FROM history').fetchone()[0] == 0 assert commit(db,p,'editor',10) == 'COMMITTED' assert commit(db,p,'editor',101) == 'COMMITTED' assert commit(db,replace(p,expires=200),'editor',10) == 'KEY_CONFLICT' assert state() == [('1','New A',2),('2','New B',2)] u = inverse(db,'a','p1','undo1',200) approve(u) assert commit(db,u,'editor',10) == 'COMMITTED' assert state() == [('1','Old A',3),('2','Old B',3)] assert commit(db,u,'editor',10) == 'COMMITTED' p2 = Plan('a','p2',100,(Edit('1',3,'Old A','Next A'),Edit('2',3,'Old B','Next B'))) approve(p2) assert commit(db,p2,'editor',10) == 'COMMITTED' u2 = inverse(db,'a','p2','undo2',200) approve(u2) db.execute("UPDATE catalog SET title='Human edit',revision=revision+1 WHERE tenant='a' AND sku='2'") assert commit(db,u2,'editor',10) == 'CONFLICT' assert state() == [('1','Next A',4),('2','Human edit',5)] assert db.execute("SELECT title FROM catalog WHERE tenant='b'").fetchone()[0] == 'Private' db.execute("DELETE FROM grants WHERE role='reviewer'") assert commit(db, u2, 'editor', 10) == 'NOT_APPROVED' assert db.execute('SELECT count(*) FROM receipts').fetchone()[0] == 3 print('23 checks passed') if __name__ == '__main__': main()

Observed local execution using Python 3.13.5:

23 checks passed

The 23 assertions verify denied and cross-tenant requests, missing approval, duplicate SKU validation, modified approved payload, proposal/approval expiry, rollback of the first edit when a later edit conflicts, absence of orphan history after rollback, successful commit, retry after expiry, conflicting key reuse, resulting revisions, exact approved undo, retry of undo, a second commit, all-or-nothing undo failure after a human edit, preservation of the other tenant, reviewer revocation and exact receipt count. The rollback test is important: it actually performs the earlier conditional update inside a transaction before encountering the later conflict and verifies both catalog and history stayed unchanged.

The digest includes the complete dataclass content and list order, using a deterministic Python JSON serialization. It is not a general interoperable RFC 8785 implementation: production must specify normalization, Unicode and number semantics, canonical ordering, typed validation and the exact manifest format. The example binds the reviewer to a different actor and requires a current tenant-level reviewer role at new commitment; it does not implement item/field-specific grants, distinct original requester identities, authorization of the approval-writing endpoint, actor-specific receipt access, policy-version compatibility or independent provenance verification. In a real deployment authenticate both identities, use current scoped grants and ensure receipt/history read authorization. The fixture helper that inserts approval records is not an API. The inverse helper is internal and must not be accessible without protected history authorization.

The code uses BEGIN IMMEDIATE to obtain a SQLite write transaction before checking grant, approval, receipt and catalog state. Within that one local store the guarded update and receipt/history are atomic. SQLite's locking behavior is not a simulation of production PostgreSQL isolation, distributed transactions, process death or concurrent workloads. The code checks proposal and approval deadlines using a supplied trusted integer timestamp, not a live time service. It does not validate every wire input type or all business constraints, store explicit approval IDs in the receipt, emit an outbox, persist noncommitted outcomes or support partial batches. Those are requirements of the production design discussed above. The fixture includes a direct human update solely to simulate a later revision; a real human edit must use the same authorized history-preserving path.

The rollback of a conflict leaves no successful receipt. Retrying a previously committed plan returns COMMITTED before checking old expiry/approval, but only after current editor grant and plan validation; this recovers an existing result, not permission to commit another write. A new undo has its own digest and approval and verifies the proposed inverse equals the history-derived inverse. It can only restore when current whole-record revision and title still match. The example deliberately refuses field-level merging. For n edits, digest/validation is linear in input bytes plus n; sorting is O(n log n), database cost includes n indexed updates and history inserts, and the transaction holds a write lock for the bounded unit. Actual throughput and contention require testing against the intended database and data distribution.

13. Derived publication, external visibility and reconciliation#

Catalog commitment and storefront visibility are separate. A successful database receipt may precede updates to the search index, cache, analytics feed or rendered storefront. Write a transactional outbox event with the committed revision and event ID, then relay asynchronously. A consumer validates source authority and applies a version-aware update. At-least-once delivery is compatible with idempotent derived-state updates; older events must not overwrite newer revisions. Treat an undo as a new higher revision, so a delayed old "forward" event cannot reapply the undesired value.

Expose states such as "catalog committed; storefront update pending" and "published revision observed." A failed index update does not roll back the catalog automatically. Retry or rebuild from the authoritative state, reconcile by revision and handle missing/duplicate events. If an approved policy requires atomic public visibility of a complete generation, use a suitable staged publication contract rather than falsely imply all derived stores change in the same SQL transaction.

For example, revision 20 is committed, its outbox event is delayed, then an approved undo creates revision 21. A search consumer receiving 21 before 20 must preserve 21. In a rebuild, compare indexed document revision and deleted-record handling against the current authorized catalog. Authorization and deletion obligations apply to derived indexes, caches, preview copies and history. Actual external actions such as customer notifications or advertisements may require distinct approvals and compensation; keep them out of the narrow edit commit when feasible.

14. Operational scale and a worked resource budget#

Suppose 12,000 selected products receive one generation attempt each, with mean input 500 tokens and output 120 tokens. Offered generation work is six million input tokens and 1.44 million output tokens. With an illustrative 10% additional full attempts, plan for 6.6 million and 1.584 million tokens. These are workload calculations, not actual model usage or throughput measurements. Grouped requests may alter token totals and semantic error rates; measure actual usage and item association.

Assume a validated generation pool could process 20 items/s under an approved input mix, independent of the commit path. Pure first-attempt work takes 600 seconds; 13,200 attempts at that rate take 660 seconds. Add queue delays, source reads, validation, retries, review time and any unavailable inputs. An acknowledgment can be immediate while a finished preview takes minutes. Never hold a catalog transaction for that generation duration.

For illustrative commit capacity, suppose a 200-record atomic group completes in 0.4 seconds under a measured-like but fictional test envelope, including history and outbox writes. One serial worker would take 60 × 0.4 = 24 seconds of transaction execution for 60 groups if all succeed, excluding scheduling and contention. Four workers cannot be assumed to reduce this to six seconds; shared indexes, WAL, hot products, connection pool, locks and replication can dominate. Size against measured p95 lock time and user-facing latency. Use shorter groups if necessary while preserving invariant boundaries. Bound total transaction size and retry work.

If normalized proposal and history payload average 1.5 KB and 2 KB per item respectively, 12,000 items generate 18 MB of proposals and 24 MB of history in decimal units, or 42 MB combined before indexes, snapshots, raw model logs, database overhead and copies. Ten such operations/day retained 30 days would be approximately 12.6 GB raw under these assumptions. Count audit/history copies and undo retention explicitly; never keep unnecessary sensitive raw prompts solely for debugging. Large previews need paged access and streaming export only with current authorization.

Cost per successfully committed and verified edit includes generation, retries, validation, review labor, database/history storage and downstream reconciliation. Optimizing accepted edits per token alone can reward unsafe automatic approval. Measure quality and actual user corrections alongside economics.

15. Failure handling and security#

FailureRequired behavior
Model emits arbitrary SQL or forbidden fieldReject outside allowlisted typed operation; no execution
Model invents a product ID or changes tenantReject and record safe validation reason
Prompt injection in supplier descriptionTreat source text as data; no extra tools or write authority
Evidence missing or contradictoryHold or reject affected claims
Manifest changed after approvalInvalidate approval; new reviewed digest
Approval expired or grant revokedBlock new commitment
Concurrent human editConflict or independently authorized safe merge
Deadlock/serialization failureRetry same immutable operation within limits if safe; never refresh expected revisions silently
Commit response lostResolve receipt using scoped key before retry
Worker stops mid-chunkDetermine authoritative transaction outcome and resume from receipts
Catalog committed but index staleReconcile projections and communicate publication lag
Undo conflictsPreserve current state and provide conflict-aware review
Mandatory policy violation detected after commitContain affected publication, issue authorized correction, investigate

Do not give the model unrestricted query or tool access to the catalog. Authenticate the user and worker, scope reads and writes to tenant/resource/field and purpose, enforce permissions at the catalog owner, restrict egress and protect source data and logs. Prompt instructions such as "do not change price" are insufficient; the actual schema and commit path must exclude price operations. Treat model responses and review comments as untrusted content; escape or safely render preview text. Prevent mass-assignment bugs and object reference bypasses. Require rate limits and approval for high-impact scope. Audit admin and policy changes; protect history access, backup and deletion.

The review interface must not leak another tenant's identifiers or history through conflict error details. Use an appropriate indistinguishable denied/not-found contract where needed. Avoid overly broad reviewer roles; separate request, review and execution responsibility as the risk requires. All sensitive operations, including undo, need current authority, not only the forward edit.

16. Monitoring, evaluation and release acceptance#

Track generation validity, source-grounded claim accuracy, duplicate/misassociated products, proportion of proposals with blocked fields, reviewer acceptance/revision rates, review queue age, commit conflict rate, committed item count, duplicate retries resolved, undo success and conflict rate, data integrity violations, publication lag, support incidents and cost per correctly committed edit. Distinguish proposed, approved, committed, published, corrected and undone. A high approval rate alone can indicate reviewer fatigue rather than good predictions.

Use representative catalog fixtures covering locale, variants, null/empty fields, unusual Unicode, changing permissions, taxonomy migrations and invalid claims. Evaluate with domain reviewers and deterministic checks. Test the following independently before release:

  • Proposal contract: malformed JSON, unknown fields/operations, invalid units, duplicate IDs, fabricated identifiers, unsupported claims.
  • Preview: normalized and actual before/after values, null versus missing, affected record completeness, approval subset and correct digest.
  • Concurrency: competing users, changed revisions, simultaneous approval revoke, conflicting aggregate changes, deterministic lock order and serialization retries.
  • Atomicity: injected failure after the first mutation and before receipt, rollback of history and outbox, crash after commit before response.
  • Idempotency: concurrent duplicate commit, same key/different payload, receipt retention and replay, chunk recovery.
  • Undo: exact inverse, overlapping human edit, field-level lineage, later policy change, deleted history, repeated undo and redo.
  • Authorization: cross-tenant and object/field scope, reviewer identity, revoked grant, preview/history access, protected external effects.
  • Projection: delayed, duplicate and out-of-order events, deletion/rebuild reconciliation and publication status.
  • Load: large selection, reviewer backlog, concurrent interactive editing, bounded transactions, replication lag and backpressure.

The local 23-check example establishes selected sequential state-machine invariants, not these complete production guarantees. Test actual infrastructure and release controls. Run shadow generation with read-only data and isolated outputs; do not shadow actual mutations against production. Start with a small approved field set and bounded scope, observe quality and conflict behavior, and expand only after evidence. A kill switch can disable commits while retaining safe previews; undo capability and correction ownership must remain available according to the approved policy.

17. Architecture trade-offs and interview-ready answer#

The central trade-off is between strict atomicity, scalable work and the ability to preserve later edits. Whole-record revision checks are conservative and simple but can conflict with unrelated changes. Field-level versioning improves concurrency at the cost of more complex lineage and invariant validation. Atomic small groups provide strong consistency while partial plans need precise receipts and honest status. Staged snapshot publication can provide coherent visibility but increases storage and migration complexity. Longer undo retention improves recoverability but costs storage and may conflict with data-deletion obligations. Human review improves control but can dominate latency; constrain scope and improve evidence rather than silently remove approval.

In an interview, I would start by defining the catalog owner's invariants, editable field allowlist, selection scope, atomicity and undo contract. I would freeze a manifest of authorized entity IDs and base revisions, run AI only as a suggestion producer, normalize typed patches, validate factual evidence and show a trusted semantic diff. I would bind reviewer approval to the exact immutable manifest, policy and expiry.

The commit service would independently check current authorization and constraints, apply revision-guarded updates in bounded transactions, and atomically record actual before/after history, receipts and outbox intent. Logical keys and payload digests would resolve duplicate or ambiguous requests. For large operations I would choose explicit atomic groups or a validated staged publication model and surface precise partial results. Undo would derive a fresh inverse proposal from the committed receipt, compare current revisions/lineage, preserve intervening human edits, obtain current approval and append a new revision. I would monitor correctness, review load, conflicts, downstream freshness and cost and test failure/recovery paths. The model supplies proposals; the authoritative product determines what changed, why, and which changes remain safely reversible.

References and research transparency#

The authorized offline research exception was applied. These references identify established standards, technical documentation, systems literature and risk guidance. Live link availability, current contents and the current Supabase changelog could not be verified. Four Mermaid diagrams use standard triple-backtick fences and received structural review; parser execution and live site rendering were not tested. The exact Python code was run locally using Python 3.13.5 with 23 assertions passing; the stored code is independently checked against the tested block. No production concurrency, database fault-injection, real model generation, security assessment, real downstream projection or load tests were performed. SQL and JSON snippets are illustrative, not executed integration tests. All numerical examples are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython