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

Migrating Legacy Rules Engines to AI-Assisted Decision Services Safely

Question 30 of 47 · Updated

On this page

Replace the legacy decision mechanism incrementally, not its mandatory obligations. First classify existing rules by their business meaning and authority. Preserve hard constraints in a common deterministic enforcement boundary; use AI only for approved predictive or recommendation responsibilities. Introduce a stable decision contract and a routing facade, compare legacy and candidate decisions on aligned cases without duplicating effects, and progressively transfer authority for clearly defined cohorts. Fence commitments with current ownership and state versions, reconcile real outcomes, and preserve a safe rollback path until the legacy implementation is demonstrably redundant.

How would you replace a legacy rules engine with an AI-assisted decision service while both systems coexist?

ASD-089 | Module 11 — Architecture contracts and integration | Learning order 17. ASD-006 defines the prediction-policy-effect boundary. ASD-008 concerns productionizing an already-used AI prototype, including application and data continuity. ASD-087 resolves disagreement among competing model outputs. This lesson addresses a different transition: a functioning deterministic decision service already exercises authority, and a new hybrid service seeks to assume selected decisions while the original remains operational. The published MLOps shadow-deployment lesson explains safe mirroring and paired model comparison; apply that technique here without repeating its infrastructure implementation. Our distinctive focus is rule disposition, decision semantic parity, independent adjudication of changed behavior, single authority during coexistence, reversible authority transfer and evidence-based retirement. The following ASD-090 addresses governed policy exceptions, not replacing policies with predictions.

All scenarios, counts, thresholds and costs are hypothetical. No live rules engine, model or migration was executed.

1. Inventory the rules by meaning before writing a model#

Suppose a warehouse quality-control service routes manufactured lots to standard inspection, additional review or hold. The current engine uses threshold tables, exception lists and historical heuristics. It may have accumulated rules over years. A model trained on past routing outcomes could reproduce its mistakes or learn shortcuts that violate current obligations.

Begin with a decision inventory, including code, configuration, database triggers, operational overrides, downstream consumers and informal manual procedures. Trace the actual call paths: some clients may bypass the documented engine and write directly to the underlying tables. Record rule ID, version, owner, predicate, consequence, effective period, exception authority, data dependencies, observed frequency, precedence and explanation. Check compound rules and side effects, not just isolated conditionals.

Rule classWarehouse exampleMigration disposition
Mandatory prohibitionLot subject to an unresolved mandatory quality holdKeep deterministic, enforced at commitment
AuthorizationOnly authorized inspectors can release a held lotKeep at protected resource boundary
Referential or transactional invariantOne disposition per inspection intent; correct lot revisionEnforce with authoritative constraints
Policy obligationSpecific product families require additional inspectionPreserve until accountable policy owner changes it
Predictive heuristicReview when a sensor proxy exceeds an old thresholdCandidate for validated statistical replacement
Optimization heuristicPrioritize likely defects within available inspection slotsCandidate for constrained optimization
Operational fallbackRoute to manual review when measurements unavailablePreserve or explicitly redesign and test
Obsolete or redundant ruleRule for a retired production lineRemove only after owner and usage review

A rule that is rarely triggered may protect a crucial invariant. Frequency is not evidence that it is safe to remove. Conversely, a heuristic that was introduced as a temporary workaround may not deserve permanent status. Obtain owner decisions for ambiguous rules. If the classification is unresolved, preserve behavior or hold the affected migration scope.

Use an explicit decision table or equivalent policy representation, such as a suitable DMN model, to document precedence and conflict cases. Do not mechanically translate undocumented if/else behavior into model labels. Separate facts, policy predicates, estimates, recommendations and effects. If a legacy rule combines all five, split the responsibilities behind a compatibility boundary before moving authority.

2. Establish the decision contract and the unit of migration#

The migration unit is a logical decision intent, not an HTTP request or an arbitrary percentage of traffic. For example, disposition of lot L at inspection revision 17 under the current inspection policy. A retry belongs to the same intent; reinspection after a material state change may be a new explicitly linked intent. Establish canonical identity and ownership, including the scope where related decisions must remain consistent.

Specify the existing consumer contract:

Contract elementExample
InputAuthorized lot identity, immutable measurement snapshot, current lot revision
OutputHOLD, REVIEW or STANDARD; explicit reason and decision identity
Mandatory checksHolds, current policy, authorization and approved inspection pathway
Decision receiptExact authoritative disposition, owner, epoch, policy and input revision
FailureTyped unavailable, stale or manual-review disposition; no ambiguous success
CompatibilitySupported existing clients retain the meaning of each disposition
TimingA decision deadline and review queue objective
RetryOne logical commitment; receipt lookup after ambiguous response

STANDARD means the lot follows the standard inspection pathway; it does not mean the lot has passed inspection or is authorized for release. Mapping a new probability to the old disposition is a policy decision, not a serialization detail. Ensure the new explanation codes map correctly, including missing evidence and abstention. If old clients cannot safely interpret a new outcome such as REVIEW_REQUIRED, use a separately documented compatible mapping or version the contract. Never silently map unknown to approval.

Expose the same canonical decision interface for both engines. The new service may provide additional evidence fields to capable clients, while existing clients receive a faithful compatible projection. Keep contract version, policy version, model release, source revision and routing/authority epoch separate. A model version change is not a new authorization contract by itself.

3. Target coexistence architecture#

Loading diagram…

The routing facade is a strangler boundary: callers retain a stable port while selected responsibilities move to the new implementation. It may be a module, gateway or service, depending on the actual topology. A proxy alone is not an ownership boundary if either engine can bypass it and commit effects independently.

Create adapters that compute candidate dispositions without directly applying irreversible effects. The authoritative resource owner accepts only the selected authorized disposition under current policy and state. During shadow mode the candidate has no production write or notification authority. During canary mode the hybrid can own the selected intent but the same shared commitment boundary enforces mandatory constraints. If the legacy engine cannot be made pure, run a separately isolated evaluator or replay from captured inputs; do not mirror a side-effecting handler.

There is one owner per intent or defined ownership partition at a time. The logical owner can be legacy or hybrid, with a monotonically increasing fencing epoch. Both engines may execute computations, but only the authoritative owner can commit a new disposition. The commitment boundary must check the epoch against trusted current ownership. A cached feature flag or lease without a check at the sink cannot fence a paused worker.

Separate decision selection from downstream action. A durable decision receipt and, where needed, an outbox intent can be committed locally with appropriate atomicity. A review task or external action has its own effect identity and receipt. Do not claim exactly-once external delivery from a unique local decision row.

4. Establish a meaningful baseline#

Before adding AI, measure the actual legacy system and its failure modes. Capture point-in-time input facts and applicable rule versions, including overrides, missing fields, external lookup results, rule firing trace, action and outcome. Rule decisions often affect the labels later observed. For example, reviewed lots may receive more intensive testing than standard-inspection lots, so the observed defect rates are not directly comparable without accounting for inspection selection.

Construct three datasets or evidence sets with clear separation:

  1. A characterization set for discovering current behavior and edge cases, including rule boundary values, precedence collisions and historical incidents.
  2. A development set for improving candidate heuristics, model calibration and decision policy, respecting temporal and group boundaries.
  3. An untouched confirmation set and, when justified, a controlled live evaluation for the intended population.

Historical legacy decisions are useful behavioral labels, not universal ground truth. If the candidate is meant to improve a flawed rule, perfect imitation is the wrong objective. For mandatory controls, behavioral parity may also be insufficient if the legacy engine had a bypass; enforce the independently approved policy.

Use actual outcome measures defined by the domain: valid inspections, false routing, review burden, delay, quality failures and control violations. Compare with a simpler improved deterministic baseline as well as the existing engine. A rules cleanup may solve the problem without adding an AI dependency. If there is no representative outcome evidence for a high-consequence case, preserve the existing approved pathway or require qualified review rather than pretend the new model is proven.

5. Hybrid decision design: keep invariants outside the model#

For the warehouse example, the candidate estimates the risk of a defect under a precisely defined inspection/reference procedure. A deterministic policy maps the estimate and current measurement quality to an eligible inspection disposition. A mandatory unresolved hold always blocks standard routing. The model does not choose whether the hold applies.

The illustrative policy is:

  • If a mandatory prohibition applies, HOLD.
  • If the input is unsupported, required evidence is missing, or probability is unavailable or invalid, REVIEW or the approved safe alternative.
  • Otherwise request REVIEW when the risk is at or above a separately validated threshold; use STANDARD when the lower-risk path is permitted.
  • Recheck current authoritative constraints before recording the disposition and initiating inspection.

Thresholds depend on outcome and error costs, review capacity, calibration, critical slices and approved safety requirements. A score below a threshold never grants permission to release the product. A policy exception cannot be inferred from a model's confidence; the next lesson covers the exception lifecycle.

Migrate heuristic responsibilities one by one. Keep some stable rules permanently if they are interpretable, cheap and appropriate. A successful migration does not require eliminating every deterministic rule. The target may be a smaller explicit rule set plus a statistical ranking or prediction module.

Version the final mapping and evaluate the whole policy, not just classifier AUC. When changing the model, update the approved compatibility registry and confirm that the decision mapping still satisfies its requirements. Preserve reason codes for mandatory rules and distinct explanatory evidence for model-assisted proposals; generated rationales are not proof of which rule actually fired.

6. Shadow decisions and differential testing#

Use the same immutable input snapshot and applicable policy context to compare the legacy and candidate decision artifacts. A shadow candidate must be unable to commit business effects. It should be isolated from critical resource budgets and should not block the authoritative path. The dedicated MLOps shadow lesson develops mirroring capacity, side-effect isolation and coverage in detail; here focus on semantic comparisons.

Define a normalized comparison object containing intent identity, snapshot and state revisions, legacy rule release, candidate model/policy release, normalized dispositions, reasons, mandatory invariant results and missing/invalid member status.

Classify differences by their meaning:

DifferenceInterpretationRequired disposition
Same decision, same required semanticsBehavioral agreementStill sample outcome correctness
Same disposition, changed reasonPossible explanation or policy differenceReview reason compatibility
Different decision from approved heuristic changeIntended behavior changeValidate outcomes and approved cost/risk
Different because context or input differsUnpaired comparisonFix alignment or report missing evidence
Candidate bypasses a mandatory ruleControl violationStop affected migration
Legacy decision violates current approved ruleExisting defectContain and correct with policy owner
Candidate abstains or times outAvailability/degradation issueAssess fallback and coverage

Differential testing finds differences, not truth. Use independently adjudicated cases, trusted measurements, documented policy and eventual outcomes to decide whether a difference is correct. Avoid treating legacy as an oracle for the very heuristic you intend to improve. For critical cases, review both agreement and disagreement; common defects can persist when both systems agree.

Use boundary and property tests: mandatory holds cannot become STANDARD merely because risk decreases; changing the owner epoch invalidates an uncommitted stale owner's attempt; unrelated presentation changes must not alter disposition; absent or invalid scores cannot become zero risk. Include null, NaN, changed units, time-sensitive rules, contradictory facts, concurrent case revisions, historical exceptions and unknown product classes.

Worked differential comparison#

Suppose 10,000 eligible copied decisions are observed. Both engines produce comparable valid dispositions for 9,500; 500 are unpaired because candidate results are unavailable, invalid or refer to a different snapshot. Of the paired cases, 8,740 agree and 760 differ: agreement 92%, disagreement 8%, pairing coverage 95%. The agreement figure is conditional on valid pairs, not on all offered cases.

Assume reviewers inspect the 760 disagreements and classify 520 as justified candidate improvements, 180 as unjustified changes and 60 as unresolved. These hypothetical labels are not evidence of overall quality. A separate representative sample of agreement cases and outcomes is necessary. A single mandatory-hold bypass is grounds to stop the affected release even if most disagreements are beneficial.

If the sample is drawn from only one production line or excludes low-quality sensor cases, it cannot justify activation for other lines. Preserve unpaired cases as a denominator, measure coverage by critical slice, and avoid imputing correctness for missing labels.

7. Authority transfer as an explicit state transition#

Loading diagram…

These are migration phases, not a requirement to pass through every phase. Advisory mode exposes suggestions to a human, so it can affect decisions even if no automatic effect is enabled. It requires its own approval and monitoring; it is not equivalent to shadow. The legacy implementation may continue to own excluded cohorts indefinitely.

For a cohort cutover, define the source and target owners, current epoch, eligible intent classes, in-flight work treatment and exact cutover precondition. A trusted authority record might map (tenant, workflow, partition) to owner and epoch. The resource accepting commitments checks that same partition and epoch in the actual write boundary. A monotonically increasing epoch is never reset to an earlier value during rollback. A previously committed receipt remains historical even if its owner no longer owns new work.

There are several possible in-flight contracts. Drain legacy intents before handing off the partition; preserve explicitly pinned per-intent ownership until completion; or fence unfinished work and replan from current state. Pick one. Do not transfer partition ownership and allow an old worker to commit under stale assumptions. If pinned intent ownership survives the partition switch, the sink must distinguish that valid explicit exception from a stale worker. A stale lease check in an application server cannot replace resource-side fencing.

A stable deterministic cohort assignment helps avoid switching users or related entities mid-workflow. Choose the key at the actual consistency boundary. The percentage of tenants is not necessarily the percentage of decisions. Record assignment and actual owner on each receipt. If a workflow has multiple related decisions or shared state, migrate the appropriate aggregate or coordinate with its owner.

Loading diagram…

The diagram assumes the ownership change is actually enforced atomically by the commitment resource. In a distributed architecture, updating a registry asynchronously without a coordinated fence may leave a split-brain interval. Establish a linearizable or appropriately transactional ownership protocol for the write boundary, or stop admissions, drain and reconcile before cutover. Receipt access requires its own current authorization.

8. Progressive rollout and evidence gates#

Example migration stages: classify and externalize hard controls; establish compatibility facade; run offline differential characterization; mirror a bounded eligible sample; offer approved advisory suggestions where meaningful; transfer authority for a low-risk cohort; expand only when predeclared acceptance gates pass.

A hypothetical initial canary gate could require zero observed mandatory control violations, complete reconciliation of authoritative receipts, no unacceptable degradation in critical slices, and acceptable review workload, latency and outcome evidence. Zero observed failures is not proof of zero risk. If n independent representative opportunities yield zero failures, the approximate 95% upper bound on failure probability is 3/n (rule of three), subject to assumptions. With 1,000 such opportunities it is about 0.3%; rare or unrepresented conditions remain untested. Mandatory structural controls and targeted tests remain necessary.

For a system receiving 200 eligible decisions/s, a 5% live canary would offer approximately 10/s to the new owner under uniform traffic assumptions. A 20% shadow of the remaining legacy path would copy about 38/s, for 48 candidate computations/s before retries if no overlap. Distinguish authoritative exposure from shadow workload. Budget extra feature reads and isolate shadow queues; loss of shadow pairing must not compromise legacy availability.

Measure actual assignments, candidate completion, committed receipts, failures, review delay and outcomes. If canary outcomes are delayed, do not expand just because the first hour has low latency. Use mature outcome windows and predefined pause/rollback criteria. If interventions change which outcomes are observed, an approved experiment or causal evaluation may be required; shadow comparisons do not establish counterfactual outcome improvement.

9. Worked decision economics and review capacity#

Suppose an approved evaluation population has 10,000 cases. For a fictional mature and independently adjudicated evaluation, legacy routes 3,000 to additional inspection, and the candidate routes 2,200. Assume all mandatory cases are reviewed by both systems. Of the cases sent to standard inspection, legacy has 70 missed review-worthy cases and candidate has 85. These counts alone do not establish equivalence or safety.

At an illustrative incremental review cost of $5 per additional inspection and an assumed loss of $100 per missed review-worthy case:

MetricLegacyCandidate
Additional reviews3,0002,200
Review cost$15,000$11,000
Missed review-worthy cases7085
Illustrative miss loss$7,000$8,500
Total modeled cost$22,000$19,500

Modeled savings are $2,500 on that sample, but misses increase by 15. A mandatory missed-case gate or a higher severity cost may make the candidate unacceptable despite the lower sum. At miss loss $300, totals are $36,000 versus $36,500. The break-even loss for the incremental comparison is $4,000/15 ≈ $266.67 per additional miss, assuming all other costs equal. Actual risk depends on error severity, uncertainty, correlated cases, intervention effects, model cost and fairness across supported groups. A review budget cannot justify violating a mandatory hold.

Capacity matters: if live arrivals are 100 cases/min and candidate review fraction is 22%, reviews arrive at 22/min. Six reviewers completing three/min each provide nominal capacity 18/min; backlog grows four/min during sustained demand. Eight equivalent reviewers nominally provide 24/min but need practical headroom for variation and priorities. A fallback that routes all cases to review could overwhelm the system. Define a safe admission/hold plan, staffing and deadline behavior rather than silently relaxing thresholds during an outage.

10. Practical implementation: single-owner decision receipts#

The following standard-library Python example exercises a local SQLite commitment boundary. Both decision functions can compute results without writing. Only the owner with the current epoch may create a new receipt. A trusted case revision and a mandatory prohibition are checked at commitment. The owner switch uses a conditional epoch update, and rollback creates a new epoch rather than restoring an old one.

PYTHON
import sqlite3 from dataclasses import dataclass, replace from math import isfinite @dataclass(frozen=True) class Case: id: str revision: int prohibited: bool legacy_review: bool risk: float | None def candidate(c): if c.prohibited: return 'HOLD' if c.risk is None or type(c.risk) not in (int, float) or not isfinite(c.risk) or not 0 <= c.risk <= 1: return 'REVIEW' return 'REVIEW' if c.risk >= .3 else 'STANDARD' def legacy(c): return 'HOLD' if c.prohibited else 'REVIEW' if c.legacy_review else 'STANDARD' def commit(db, c, owner, epoch): # Trusted caller and canonical case ID; this is not authentication. db.execute('BEGIN IMMEDIATE') try: old = db.execute('SELECT disposition FROM receipts WHERE id=?', (c.id,)).fetchone() if old: db.commit() return old[0] current = db.execute('SELECT owner,epoch FROM authority').fetchone() if current != (owner, epoch): db.rollback() return 'FENCED' row = db.execute('SELECT revision,prohibited FROM cases WHERE id=?', (c.id,)).fetchone() if row != (c.revision, int(c.prohibited)): db.rollback() return 'STALE' disposition = legacy(c) if owner == 'legacy' else candidate(c) # The shared commitment boundary enforces the hard rule independently. if row[1]: disposition = 'HOLD' db.execute('INSERT INTO receipts VALUES (?,?,?,?)', (c.id, owner, epoch, disposition)) db.commit() return disposition except BaseException: db.rollback() raise def switch(db, expected, owner): if owner not in ('legacy', 'hybrid'): raise ValueError('unknown owner') return db.execute('UPDATE authority SET owner=?,epoch=epoch+1 WHERE epoch=?', (owner, expected)).rowcount == 1 db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE authority(owner TEXT,epoch INTEGER); INSERT INTO authority VALUES ('legacy',1); CREATE TABLE cases(id TEXT PRIMARY KEY,revision INTEGER,prohibited INTEGER); CREATE TABLE receipts(id TEXT PRIMARY KEY,owner TEXT,epoch INTEGER,disposition TEXT); INSERT INTO cases VALUES ('a',1,0),('b',1,0),('c',1,1),('d',2,0),('e',1,0),('f',1,0);''') a = Case('a',1,False,True,.1) assert candidate(a) == 'STANDARD' and legacy(a) == 'REVIEW' assert db.execute('SELECT count(*) FROM receipts').fetchone()[0] == 0 assert commit(db,a,'hybrid',1) == 'FENCED' assert commit(db,a,'legacy',1) == 'REVIEW' assert switch(db,1,'hybrid') assert not switch(db,1,'legacy') assert commit(db,a,'hybrid',2) == 'REVIEW' b = replace(a,id='b') assert commit(db,b,'legacy',1) == 'FENCED' assert commit(db,b,'hybrid',2) == 'STANDARD' assert commit(db,replace(a,id='c',prohibited=True),'hybrid',2) == 'HOLD' assert commit(db,replace(a,id='d'),'hybrid',2) == 'STALE' assert candidate(replace(a,risk=float('nan'))) == 'REVIEW' assert candidate(replace(a,risk=True)) == 'REVIEW' assert candidate(replace(a,risk=None)) == 'REVIEW' assert candidate(replace(a,risk=.3)) == 'REVIEW' assert switch(db,2,'legacy') assert commit(db,replace(a,id='e'),'hybrid',2) == 'FENCED' assert commit(db,replace(a,id='e'),'legacy',3) == 'REVIEW' assert commit(db,b,'legacy',3) == 'STANDARD' assert commit(db,replace(a,id='f'),'legacy',3) == 'REVIEW' assert db.execute('SELECT count(*) FROM receipts').fetchone()[0] == 5 assert db.execute("SELECT owner,epoch FROM receipts WHERE id='b'").fetchone() == ('hybrid',2) print('22 checks passed')

Actual local execution: Python 3.13.5, 22 assertions passed.

The checks cover differing shadow outputs without creating a receipt, rejection of the non-owner, valid legacy commitment, successful and stale ownership switches, preservation of the original receipt after cutover, rejection of delayed legacy writes, valid hybrid commitment, mandatory holds, stale case revisions, invalid and absent probability fallback, the risk threshold boundary, rollback to a new epoch, rejection of delayed hybrid writes, successful post-rollback legacy commitments, preservation of the hybrid receipt and expected receipt count and ownership.

The fixture is deliberately narrow. It assumes trusted normalized inputs, one global authority partition, a unique immutable case ID per decision intent, and one trusted SQLite connection. A repeated committed intent returns its existing disposition before checking new ownership, which models receipt recovery, not authorization to make another decision. Production needs separate authorized receipt retrieval, payload/intent digest comparison, resource-scoped ownership, server-derived actor and input provenance, current policy version checks and unique operation constraints. The toy does not verify that the supplied risk and legacy heuristic actually came from the claimed immutable snapshot; a real service must bind and validate those artifacts. Its one-row authority table is a fixture, not a robust production schema. It does not perform inference, external effects, an outbox, parallel processes or crash recovery. The mandatory hold is checked in both evaluators and again against current authoritative state; the case revision must match. A different revision requires a new explicitly defined intent or conflict disposition, not replay of the old receipt as a new decision.

SQLite BEGIN IMMEDIATE serializes write access in this example. The successful test proves selected sequential invariants, not distributed linearizability, real PostgreSQL isolation, malicious-caller resistance or production concurrency. In a real resource owner, use appropriate conditional writes, constraints and transactional ownership checks; if the registry is remote, document the synchronization protocol rather than assume its read is atomic with a write. Runtime model calls should execute outside database transactions; this fixture computes only cheap local logic inside the transaction.

Each decision uses a constant number of indexed database operations in the small schema. Scaling depends on partition contention, isolation, durable storage and external effects. There is no measured throughput claim.

11. Fallback must preserve authority and current policy#

An unavailable model need not mean "use the legacy engine" automatically. Legacy fallback is a different decision mechanism with its own eligibility, approved semantics and operational availability.

FailureSafe policy example
Candidate inference times outApproved deterministic fallback or manual review
Candidate input unsupportedLegacy only if that context is explicitly supported; otherwise hold
Hard policy cannot be obtainedDo not infer permission from cached risk or legacy output
Authority registry unavailableBlock new commitment where ownership cannot be proven
Shared source measurement invalidNeither engine is entitled to pretend valid evidence
Legacy no longer understands new stateHold or recover compatible representation; no blind fallback
Review queue fullApproved admission control or safe hold

During hybrid ownership, the hybrid decision adapter may invoke a read-only legacy heuristic as an approved fallback while retaining the hybrid owner's commitment authority. This is different from transferring ownership to legacy. If an actual ownership transfer is required, perform a fenced transition. Never let fallback and primary race to produce independent effects.

Use a bounded deadline and retry budget. A circuit breaker may remove an unhealthy predictor but cannot remove mandatory checks. Log the requested route, actual mechanism, fallback reason and authority epoch; do not disguise fallback as an AI result. A fallback rate spike is a migration quality and availability signal.

12. Rollback, reconciliation and historical obligations#

Rollback stops further exposure to an unsafe owner or implementation. It does not rewrite history or undo effects already committed.

  1. Stop new candidate authority allocation for the affected partitions and disable unsafe shadow/advisory paths if needed.
  2. Activate a verified legacy-compatible or safe-hold pathway using a new ownership epoch. Enforce the fence at the commitment boundary.
  3. Resolve in-flight intents from authoritative receipts, explicit state and outbox/effect evidence. Do not infer failure from a timeout or rerun both engines.
  4. Identify committed candidate decisions with incorrect or uncertain outcomes; isolate affected records and notify authorized owners. Apply separately approved correction, reinspection or compensation where appropriate.
  5. Check client and data compatibility, mandatory rules, review backlog, resource availability and actual user outcomes before restoring normal admissions.
  6. Document incident scope, cause, corrected artifacts and evidence required for another attempt.

If the new service introduced a decision state that legacy cannot interpret, reverting routing alone may break behavior. Keep compatible state representation during the rollback window, maintain read adapters or use a safe containment path. Do not weaken current policy to match old code. Replaying old decisions is not rollback: replay can duplicate effects or use obsolete context.

Reconciliation compares canonical intents to authoritative receipts and downstream effects: expected disposition, owner and epoch, policy and state revision, durable effect status, missing/duplicate operations, review obligations and corrections. Compare actual source-of-truth state, not simply the two engines' logs. A receipt marked committed without a downstream action receipt does not prove the action completed. ASD-018 addresses multi-system compensation in depth; this lesson's focus is restoring authority and identifying affected commitments.

13. Auditability and operational ownership#

For each decision retain governed references to:

  • Canonical intent, case and immutable input snapshot, applicable policy and time.
  • Legacy rule release and rule trace, candidate model/calibrator/feature releases and score, if generated.
  • Candidate/legacy comparison, reason classification, authority assignment and epoch.
  • Actual selected mechanism, fallback or human adjudication, final disposition and decision/effect receipts.
  • Any later correction, rollback cohort or remediation record.

Keep shadow records distinguishable from authoritative outcomes in analytics and training. A downstream training job must not use a shadow disposition as actual user behavior. Record whether labels reflect the chosen inspection intervention. Preserve privacy and current authorized access; avoid copying sensitive raw data into unrestricted comparison logs. Mirror only approved scopes and processors. Restrict shadow credentials and egress, and enforce policy even on a compromised model response.

Monitor offered and committed counts by owner, paired coverage, disagreement by rule family and slice, mandatory-control violations, stale-owner rejections, duplicate receipt attempts, fallback rates, actual outcome quality, review backlog and decision latency. Count unpaired and abstained cases. A high agreement metric is not a quality metric. Assign a migration owner, rule/policy owner, evaluation lead, resource-owner/on-call and reviewer capacity owner; document stop authority and escalation.

14. Legacy retirement: remove implementation, retain required obligations#

Retire legacy components only when the accountable owners approve evidence that:

GateEvidence
Functional coverageEvery supported intent and client has a compatible owner or approved alternative
Rule dispositionMandatory rules retained; retired heuristics explicitly approved
Actual authorityNo unexplained legacy commits or direct bypasses remain
OutcomeMature quality, risk, review capacity and critical slice gates pass
RecoveryTested safe fallback/recovery without legacy; outstanding work reconciled
Historical continuityPrior decisions and receipts remain interpretable under authorized retention
OperationsOwnership, runbooks, monitoring, dependency and access inventory updated

Retirement can happen in stages: stop legacy authority, disable unneeded evaluation traffic, retain read-only historical adapters, then remove unused code and infrastructure after the approved recovery window. Revoke old write credentials and direct endpoints; verify that scheduled jobs and downstream consumers no longer depend on them. Keep documentation of mandatory controls and policy owners. A legacy rule implementation may still be useful as a read-only regression oracle, but not an unowned hidden production fallback.

A second example is an internal support-ticket router. Hard privacy and team-access restrictions remain deterministic; a model replaces heuristic category scoring and proposes a destination. During coexistence the facade selects a single routing owner per ticket, while the ticket service enforces allowed destinations and idempotent assignment. Compare routing results with independent agent adjudication and resolution quality rather than copy historical misroutes. Rollback fences new assignments but does not automatically move already assigned tickets. This illustrates that the technique generalizes beyond factory inspection without making the domain-specific rules interchangeable.

15. Production test plan and interview answer#

Test the rule inventory against approved policy and historical characterization fixtures. Exercise each mandatory prohibition, precedence conflict and boundary case, plus stale and missing inputs. Run differential evaluations on aligned snapshots, include unpaired cases and independently adjudicate intended changes. Test unauthorized shadow attempts, direct legacy bypasses, duplicate logical intents and ambiguous acknowledgments. Inject cutover races, stale workers, ownership switch failures, case-state changes and rollback while work is in flight. Verify the real resource's conditional writes and external effect reconciliation under concurrency, crashes and network partitions. Test review overload, model/source outage and backward compatibility with existing clients. Confirm actual production outcomes through controlled exposure, not shadow disagreement alone.

In an interview I would start by classifying legacy rules into mandatory constraints, authorization, heuristics and fallbacks. I would preserve mandatory rules in the authoritative enforcement layer, establish a versioned compatible decision interface and introduce a strangler facade. I would test the candidate against aligned legacy decisions and independent outcomes in read-only shadow mode, treating disagreements as cases for adjudication rather than mistakes by definition. I would transfer ownership incrementally using a stable cohort and sink-enforced epoch, ensure a single durable decision receipt per logical intent, and validate current state at commitment. I would use approved fallback profiles, explicit rollout and stop gates, and rollback with a new fence plus reconciliation of already committed decisions. Finally, I would retire legacy only after outcome, control, compatibility, recovery and ownership evidence passes.

The migration succeeds when the new service safely owns the intended decisions and the old service no longer carries a necessary obligation—not when all rules have been replaced by AI.

References and research transparency#

The authorized offline research exception applies. The references identify established architectural guidance, specifications, research and technical documentation; live contents, link availability and the current Supabase changelog were not verified. Three meaningful standard triple-backtick Mermaid diagrams received structural review; parser execution and live frontend rendering were not tested. The exact Python block executed locally on Python 3.13.5 with 22 assertions passing. No trained model, actual legacy service, distributed migration, security evaluation, live shadow traffic, concurrency/load test or real external effect was exercised. All numerical scenarios are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython