Architecture Readiness for Five Engineering Problems: Touch Input, Model Releases, Agents, Legacy Modernization, and End-to-End Driving

    This article groups recurring engineering pressures—adaptive input, model releases, agent state management, legacy modernization, and end-to-end driving models—into five architecture problems. Each section covers applicable boundaries, design steps, code examples or checklists, and rollback considerations so teams can prepare architecture before these issues become production incidents.

    1. Background: Five Engineering Problems Recur Across Scenarios

    Recent technical developments span desktop interaction forms, large-model version iterations, agent automation, enterprise legacy system modernization, and end-to-end models for autonomous driving and robotics. These areas appear disconnected, but they repeatedly surface several pressures: increasingly diverse input methods, faster model release cadence, rising risk from irreversible actions in autonomous systems, and high evolution costs for long-lived systems.

    This article groups these pressures into five engineering problems, with one section for each:

    Area Core risk Section
    Adaptive interaction forms Maintaining multiple UIs doubles cost and creates feature inconsistency 2
    Model version releases Scheduling based on rumors leads to uncontrolled post-release quality 3
    Agent state management Interrupted or retried operations cause duplicate execution or lack traceability 4
    Legacy system modernization Full rewrites are high-risk and create behavior gaps between old and new 5
    End-to-end autonomous driving models Model outputs lack independent constraints, making failures hard to localize 6

    Each section includes applicable boundaries, design steps, sample code or checklists, and risks and rollback. Sample code illustrates the approach; thresholds and parameters must be determined with the team’s actual data.

    2. Adaptive Interaction Forms: Supporting Touch and Pointer in One UI

    A single device often receives both touch and mouse input. The two input types impose different UI requirements: touch needs larger hit areas and wider spacing, while pointer input can tolerate higher information density. Writing a separate UI for each mode doubles maintenance cost and easily leads to feature inconsistency.

    Applicable boundary: This suits desktop or tablet applications where the same feature must work with both input types. Dedicated pointer-only or touch-only devices do not need this mechanism.

    The design steps are as follows. First, maintain only one semantic structure for the UI. Second, let the input mode determine layout density and control size. Third, map gestures uniformly to semantic actions. Fourth, keep a separate accessibility check.

    2.1 Input Mode Detection

    The system needs to determine the input source the user is currently using. The approach is to record the most recent input type and set a switching cooldown to prevent the UI from jumping back and forth when the user operates across two devices.

    PointerEvent.pointerType in the browser takes values such as mouse, pen, or touch. The integration layer can classify pen as pointer and touch as touch, ignoring other values. The example requires Python 3.10 or later.

    1. import time
    2. from dataclasses import dataclass, field
    3. VALID_SOURCES = frozenset({"touch", "pointer"})
    4. @dataclass
    5. class InputModeTracker:
    6. mode: str = "pointer"
    7. cooldown: float = 2.0 # Cooldown in seconds
    8. # Initialize to negative infinity so the first switch is not blocked by cooldown
    9. last_switch: float = field(default_factory=lambda: float("-inf"))
    10. def __post_init__(self) -> None:
    11. if self.mode not in VALID_SOURCES:
    12. raise ValueError(f"Invalid initial mode: {self.mode!r}")
    13. if self.cooldown < 0:
    14. raise ValueError("cooldown cannot be negative")
    15. def on_event(self, source: str, now: float | None = None) -> str:
    16. """Handle one input event and return the currently active input mode."""
    17. if source not in VALID_SOURCES:
    18. return self.mode # Ignore unknown sources without changing the mode
    19. if source == self.mode:
    20. return self.mode
    21. now = time.monotonic() if now is None else now
    22. if now - self.last_switch < self.cooldown:
    23. return self.mode
    24. self.mode = source
    25. self.last_switch = now
    26. return self.mode

    Note the initial value of last_switch. If it were 0.0 and time.monotonic() returns seconds since boot, the first switch shortly after boot would be incorrectly blocked.

    Test cases are below and can be run with pytest:

    1. import pytest
    2. def test_first_switch_not_blocked():
    3. t = InputModeTracker(cooldown=2.0)
    4. assert t.on_event("touch", now=0.5) == "touch"
    5. def test_switch_blocked_inside_cooldown():
    6. t = InputModeTracker(cooldown=2.0)
    7. t.on_event("touch", now=10.0)
    8. assert t.on_event("pointer", now=11.9) == "touch"
    9. def test_switch_allowed_at_cooldown_boundary():
    10. t = InputModeTracker(cooldown=2.0)
    11. t.on_event("touch", now=10.0)
    12. assert t.on_event("pointer", now=12.0) == "pointer"
    13. def test_unknown_source_ignored():
    14. t = InputModeTracker()
    15. assert t.on_event("keyboard", now=100.0) == "pointer"
    16. def test_invalid_initial_mode_rejected():
    17. with pytest.raises(ValueError):
    18. InputModeTracker(mode="voice")

    Cooldown should be tuned with real user interaction data. Too short causes jitter; too long makes the UI feel sluggish.

    2.2 Unifying Gesture Semantics

    Operations such as scroll, zoom, and activate should map to unified semantic actions instead of device-specific branches. Business logic should care only about the action itself, with device differences encapsulated in an adaptation layer.

    Input source Raw gesture Semantic action
    touch drag scroll
    pointer wheel scroll
    touch pinch zoom
    pointer ctrl_wheel zoom
    touch tap activate
    pointer click activate
    1. GESTURE_MAP: dict[tuple[str, str], str] = {
    2. ("touch", "drag"): "scroll",
    3. ("pointer", "wheel"): "scroll",
    4. ("touch", "pinch"): "zoom",
    5. ("pointer", "ctrl_wheel"): "zoom",
    6. ("touch", "tap"): "activate",
    7. ("pointer", "click"): "activate",
    8. }
    9. def to_semantic(source: str, gesture: str) -> str | None:
    10. return GESTURE_MAP.get((source, gesture))

    Combinations outside the map return None; the business layer logs and ignores them. When adding a device such as a stylus, only the mapping entry or an adapter needs to be added; business code does not change.

    2.3 Accessibility and Keyboard Reachability

    When switching to a touch layout, keyboard navigation and screen-reader support must not regress. The checklist is:

    • Every interactive element has the correct focus order.
    • Every control has a clear semantic role and a readable label.
    • Touch target sizes meet the team’s documented minimum, with the source noted in the documentation.
    • The keyboard can reach all functionality and does not depend on mouse hover.
    • After a layout switch, focus is not lost to the top of the page.

    Risks and rollback: Cooldown parameters and layout switching should sit behind configuration flags. If problems occur, automatic switching can be disabled and the default layout fixed.

    3. Model Version Releases: Use Evaluations and Canary Rollouts Instead of Rumor-Based Scheduling

    Industry media often report expected model release dates. These reports can inform planning but should not be the basis for launch. Launch should be decided by evaluation results and canary data.

    Applicable boundary: This suits online services that update models or prompts frequently. One-off offline jobs or services whose versions remain unchanged for long periods can simplify the process.

    The design steps are as follows.

    1. Build a fixed-version evaluation set, record data sources and update dates, and set admission thresholds for each metric.
    2. Run new versions on shadow traffic first, recording results only without affecting users.
    3. Roll out gradually by percentage and observe metrics at each stage. Example percentages are 1%, 5%, 20%, 50%, and 100%; specific ratios should be determined by traffic volume and monitoring capability.
    4. Keep the previous stable version available. Switching is done through configuration, and rollback requires no redeployment.
    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class Gate:
    4. min_success_rate: float # Thresholds must be determined from baseline data
    5. max_p95_ms: float
    6. max_error_rate: float
    7. def decide(metrics: dict, gate: Gate) -> str:
    8. if metrics["error_rate"] > gate.max_error_rate:
    9. return "rollback"
    10. if metrics["success_rate"] < gate.min_success_rate or metrics["p95_ms"] > gate.max_p95_ms:
    11. return "hold"
    12. return "promote"

    The decision function only reads metrics for the current stage. If the error rate exceeds the threshold, it rolls back directly; other anomalies pause expansion and wait for human judgment.

    Checklist:

    • Does the evaluation set match the online traffic distribution, and is there leakage?
    • Do success rate, P95 latency, and error rate all have comparison baselines?
    • Is the sample size for A/B comparison sufficient to avoid treating random fluctuation as a conclusion?
    • Has the rollback configuration been exercised?

    Risk note: Evaluation sets can be overfitted through repeated tuning. Teams should keep a blind test set used only before launch. A single metric improvement does not mean overall improvement; release decisions should consider multiple metrics.

    4. Agent State Management: Make Irreversible Actions Pausable and Auditable

    Agents call tools to perform actions such as sending messages, modifying data, and making payments. Once executed, these actions may be impossible to undo. If the process crashes mid-execution, the system needs to determine whether the action took effect.

    Applicable boundary: This applies to any action with external side effects, including sending, writing, deleting, and financial operations. Pure query actions can use simplified state.

    The design steps are as follows.

    1. Assign each action a unique action_id as an idempotency key.
    2. Manage actions with an explicit state machine, recording all state transitions.
    3. Irreversible actions must pass human or rule-based confirmation before entering the executing state.
    4. Persist state before execution. On recovery after a crash, query the external system for the result first instead of rerunning directly.
    1. from enum import Enum
    2. class State(str, Enum):
    3. PLANNED = "planned"
    4. WAITING_CONFIRM = "waiting_confirm"
    5. EXECUTING = "executing"
    6. DONE = "done"
    7. FAILED = "failed"
    8. CANCELLED = "cancelled"
    9. ALLOWED = {
    10. State.PLANNED: {State.WAITING_CONFIRM, State.CANCELLED},
    11. State.WAITING_CONFIRM: {State.EXECUTING, State.CANCELLED},
    12. State.EXECUTING: {State.DONE, State.FAILED},
    13. State.FAILED: {State.WAITING_CONFIRM, State.CANCELLED},
    14. }
    15. class ActionRecord:
    16. def __init__(self, action_id: str):
    17. self.action_id = action_id
    18. self.state = State.PLANNED
    19. self.history: list[State] = [State.PLANNED]
    20. def move(self, target: State) -> None:
    21. if target not in ALLOWED.get(self.state, set()):
    22. raise ValueError(f"Invalid state transition: {self.state.value} -> {target.value}")
    23. self.state = target
    24. self.history.append(target)

    Because EXECUTING can only be entered from WAITING_CONFIRM, irreversible actions cannot bypass the confirmation step. Retrying from FAILED requires confirmation again; this is intentional to avoid automatic repeated execution after failure.

    Checklist:

    • Every action has an action_id, and external calls carry this ID.
    • State persistence happens before calling the external system.
    • The recovery flow first queries the actual result of actions in EXECUTING state.
    • All transition records can be queried by auditors.

    Risks and rollback: Agent permissions should follow least privilege, and tools can be disabled individually by action type. When an anomaly occurs, switch to read-only mode first and restore only after human confirmation.

    5. Legacy System Modernization: Migrate Incrementally with the Strangler Pattern

    Legacy systems often carry many implicit business rules. Full rewrites are high-risk and often stall because the scope is too large. The strangler pattern establishes a routing layer at the entry point, migrates functionality slice by slice to the new system, and lets the old system shrink gradually.

    Applicable boundary: This suits systems that have run for years, have complex business rules, and cannot be taken offline. Very small systems, or systems that can be safely rewritten, do not necessarily need this approach.

    The design steps are as follows.

    1. Write characterization tests for existing behavior, recording current inputs and outputs as a baseline.
    2. Add a routing layer at the entry point so all requests pass through it.
    3. Migrate by business functionality slice, one slice at a time.
    4. Use shadow comparison to verify that new and old results match. Shadow calls must be read-only; otherwise they cause duplicate writes.
    5. After the new path has run stably for a period, retire the old code.
    1. import logging
    2. log = logging.getLogger("migration")
    3. def handle_order(order_id, legacy_fn, new_fn, use_new: bool, shadow: bool = True):
    4. if use_new:
    5. return new_fn(order_id)
    6. result = legacy_fn(order_id)
    7. if shadow:
    8. try:
    9. # new_fn must be a read-only implementation and must not cause write side effects
    10. if new_fn(order_id) != result:
    11. log.warning("parity mismatch order=%s", order_id)
    12. except Exception:
    13. log.exception("shadow call failed order=%s", order_id)
    14. return result

    Risks and rollback: Dual writes easily cause data inconsistency, so it should be clear which side is the source of truth during migration. The switch belongs in configuration, and rollback only requires a configuration change. The old path must remain available while the new path is verified through comparison; the specific duration should be determined by the team based on the business cycle.

    6. End-to-End Autonomous Driving Models: Add Independent Constraints Outside Model Output

    End-to-end models map sensor input directly to control output. This structure simplifies the module chain but makes failures hard to localize. The engineering focus is to set up an independent safety constraint layer outside model output and define explicit degradation paths.

    Applicable boundary: This section discusses software architecture only. Operating vehicles on public roads must comply with local regulations and go through professional functional safety processes; the code examples here are not sufficient on their own.

    The design steps are as follows.

    1. Record model version, training data version, and calibration parameters together so every output can be traced to a specific version.
    2. Add a constraint layer after the model to clamp and validate outputs. The constraint layer logic should be independent of the model and separately verified.
    3. Monitor input distribution shift and model confidence. Enter degradation mode when metrics are abnormal.
    4. Test at layers such as simulation, closed course, and controlled roads, advancing level by level.
    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class Limits:
    4. max_accel: float # Unit: m/s²; values must be determined by the safety team
    5. max_decel: float # Positive number representing maximum deceleration
    6. max_speed: float # Unit: m/s
    7. def guard(cmd_accel: float, speed: float, limits: Limits, fallback: bool) -> float:
    8. if fallback:
    9. return -limits.max_decel # Degradation: fixed deceleration
    10. accel = min(max(cmd_accel, -limits.max_decel), limits.max_accel)
    11. if speed >= limits.max_speed and accel > 0:
    12. accel = 0.0
    13. return accel

    Risks and rollback: Model versions must be quickly revertible to the previous version. Degradation-mode triggers should be covered in tests and exercised regularly. Defects in the constraint layer directly affect safety, so its code review requirements should be higher than those for ordinary business code.

    7. Implementation Order and Checklist

    Early in a project, prepare the architecture in the following order:

    1. First design state records and idempotency keys for all operations with side effects.
    2. Establish evaluation sets, canary percentages, and rollback switches for model or rule releases.
    3. Build input adaptation and accessibility checklists for the interaction layer.
    4. For legacy systems, add characterization tests first, then add a routing layer.
    5. For systems involving physical execution, define the constraint layer and degradation paths before integrating models.

    Each item should have a rollback switch and complete at least one rollback drill before launch.