Transactional Device Feature CLI Processor

Easy · Software Engineering Fundamentals · Machine Learning Engineer · Technical Screen

Problem Statement

Build the command processor for a batch device-configuration CLI that updates software feature sets across a fleet of laptops with all-or-nothing semantics.

Each entry in devices is a dictionary with three fields:

  • 'id' (str): unique identifier for that laptop.
  • 'model' (str): hardware model string.
  • 'features' (set[str]): set of feature strings currently active on that laptop.

Implement

def process_laptop_updates(
    devices: List[dict],
    commands: List[str],
) -> Tuple[bool, List[dict]]:

which processes commands strictly in order according to the following rules:

  1. SELECT <device_id> — Sets <device_id> as the active target device. Fails if <device_id> does not match any record in devices. Switching to another device leaves uncommitted pending edits on earlier devices intact without applying them or leaking them onto the new target.
  2. ENABLE <feature> — Records a pending addition of <feature> on the active device. Fails if no device has been selected yet.
  3. DISABLE <feature> — Records a pending removal of <feature> on the active device. Fails if no device has been selected yet.
  4. COMMIT — Validates and applies all pending edits for the active device, then clears that device's pending buffer. Fails if no device is active, if any feature pending ENABLE is already present in that device's committed features, or if any feature pending DISABLE is absent from its committed features. (If multiple pending commands targeted the same feature on the same device before COMMIT, the latest command determines its pending action; committing with zero pending edits succeeds as a no-op.)
  5. RESET — Clears uncommitted pending edits for the active device only. Fails if no device is active.

Any malformed command line (unknown or lowercase verb, missing or extra whitespace-separated tokens, or empty/blank text) also fails immediately. Uncommitted pending edits left over when commands ends are simply ignored and do not trigger an error.

  • On full success: return (True, updated_devices) preserving the exact list order of devices, without mutating the caller's input list, dictionaries, or feature sets.
  • On any failure: immediately abort, discard every pending and previously committed change from the entire batch, and return (False, devices) with the original input untouched.

Examples

Example 1

devices = [
    {"id": "dev-10", "model": "Pro14", "features": {"sso", "firewall"}},
    {"id": "dev-20", "model": "Air13", "features": {"sso"}},
]
commands = [
    "SELECT dev-10",
    "DISABLE firewall",
    "SELECT dev-20",
    "ENABLE telemetry",
    "COMMIT",
    "SELECT dev-10",
    "COMMIT",
]
# Output:
# (True, [
#     {"id": "dev-10", "model": "Pro14", "features": {"sso"}},
#     {"id": "dev-20", "model": "Air13", "features": {"sso", "telemetry"}},
# ])

Staging DISABLE firewall on dev-10 and then switching to dev-20 isolates each device's pending edits: committing dev-20 adds "telemetry" only to dev-20, and re-selecting dev-10 to COMMIT removes "firewall" from dev-10.

Example 2

devices = [
    {"id": "dev-10", "model": "Pro14", "features": {"sso"}},
    {"id": "dev-20", "model": "Air13", "features": {"diskcrypt"}},
]
commands = [
    "SELECT dev-10",
    "ENABLE edr",
    "COMMIT",
    "SELECT dev-20",
    "DISABLE vpn",
    "COMMIT",
]
# Output:
# (False, [
#     {"id": "dev-10", "model": "Pro14", "features": {"sso"}},
#     {"id": "dev-20", "model": "Air13", "features": {"diskcrypt"}},
# ])

Even though "edr" committed cleanly on dev-10 first, attempting to DISABLE vpn on dev-20 fails validation at the second COMMIT because "vpn" is not active on dev-20, rolling back the entire batch including dev-10's earlier commit.

Example 3

devices = [
    {"id": "dev-30", "model": "Max16", "features": {"sso", "backup"}},
]
commands = [
    "SELECT dev-30",
    "ENABLE sso",
    "RESET",
    "DISABLE backup",
    "COMMIT",
    "ENABLE audit",
]
# Output:
# (True, [
#     {"id": "dev-30", "model": "Max16", "features": {"sso"}},
# ])

RESET discards the conflicting pending ENABLE sso before COMMIT, DISABLE backup commits cleanly, and the trailing uncommitted ENABLE audit stays unapplied when the batch finishes.

Constraints

  • 1 <= len(devices) <= 500
  • 1 <= len(commands) <= 2,000
  • Device IDs, model names, and feature names are non-empty alphanumeric/identifier strings of length 1 to 64.
  • Every 'id' in devices is distinct.

Step-by-step walkthrough

  1. Restate the command contract and batch semantics

    We receive an inventory list devices (each dict holding 'id', 'model', and 'features' as a set of strings) plus a sequential list of CLI commands. We must execute the entire batch atomically (an atomic operation succeeds completely or has zero effect at all):

    • If every command succeeds, return (True, updated_devices) in the exact original device order without mutating the caller's input.
    • If any command fails—even after earlier COMMIT commands already succeeded—immediately abort and return (False, devices) with the original inventory untouched.

    Pin down every state-machine rule up front so no edge case is ambiguous:

    • Command syntax: SELECT <device_id>, ENABLE <feature>, and DISABLE <feature> take exactly one whitespace-delimited argument; COMMIT and RESET take zero arguments. Unknown verbs, lowercase verbs, empty/whitespace strings, or extra tokens fail immediately.
    • Selection requirement: Running ENABLE, DISABLE, COMMIT, or RESET before any laptop has been selected fails immediately.
    • Per-device staging: Staging DISABLE firewall while dev-10 is selected attaches that pending edit only to dev-10. Running SELECT dev-20 neither deletes dev-10's staged edits nor leaks them onto dev-20.
    • Repeated staging on one feature: Staging two commands for the same feature on the same laptop before COMMIT keeps the latest intent (ENABLE sso followed by DISABLE sso leaves sso: "DISABLE"), and only that final intent is validated against committed features at COMMIT.
    • COMMIT validation and cleanup: Checks all staged edits for the selected laptop against its currently committed features (ENABLE fails if already enabled; DISABLE fails if not currently enabled), applies them, and clears that laptop's staging buffer. An empty COMMIT is a valid no-op.
    • RESET and uncommitted leftovers: RESET clears uncommitted staged edits for the selected laptop only; any edits still staged when the command list ends remain uncommitted and the batch returns True.
  2. Understand the four classic state-management bugs

    Because this problem centers on building a bug-free CLI update engine, notice the four traps that break naive implementations:

    1. The shallow-copy trap: Calling list(devices) or [dict(d) for d in devices] creates a shallow copy—a new outer list and new dicts whose 'features' keys still point to the exact same set objects in memory as the caller's input! Mutating copy[0]["features"].add("telemetry") silently corrupts devices[0]["features"], making rollback impossible:
    Shallow copy ([dict(d) for d in devices]) — BROKEN:
      devices[0]["features"]  ----\
                                   +--->  {"sso", "telemetry"}   (mutating working corrupts input!)
      working[0]["features"]  ----/
    
    Deep copy (copy.deepcopy(devices)) — SAFE:
      devices[0]["features"]  --------->  {"sso"}                (caller's set is never touched)
      working[0]["features"]  --------->  {"sso", "telemetry"}   (all commits happen on isolated copy)
    
    1. A single shared staging buffer: Keeping one global staged_to_add set instead of per-device staging causes SELECT dev-10 -> DISABLE firewall -> SELECT dev-20 -> COMMIT to leak dev-10's pending edits onto dev-20, while clearing the buffer on SELECT silently drops dev-10's pending edits.
    2. Mutating during validation: If COMMIT loops through staged edits and adds "telemetry" before checking "DISABLE missing_flag", a mid-commit failure leaves the working device half-updated.
    3. Fragile manual undo logs: Mutating devices in place and trying to reverse earlier commits upon failure is error-prone whenever multiple commits touch the same laptop.

    Demonstrating the shallow-copy bug in four lines of Python shows why copy.deepcopy is essential:

    original = [{"id": "dev-10", "model": "Pro14", "features": {"sso"}}]
    shallow_copy = [dict(d) for d in original]
    shallow_copy[0]["features"].add("telemetry")
    print("telemetry" in original[0]["features"])  # True! Original input was mutated.
    
  3. Design the per-device state and deep-copy strategy

    Two clean design choices eliminate all four bugs at once:

    • Deep-copy devices once at the start (working = copy.deepcopy(devices)). Every commit mutates working only. If any command on line 1 or line 1,999 fails, we simply execute return False, devices—zero undo logic needed, and working is garbage-collected.
    • Store pending changes in a nested dictionary staged[device_id][feature] = action. Keying the outer dictionary by device_id isolates each laptop's staging area across SELECT switches; keying the inner dictionary by feature ("ENABLE" or "DISABLE") automatically overwrites an older staged action on the same feature with the newer one!
    Engine state in memory during Example 1:
      working   = [{"id": "dev-10", "model": "Pro14", "features": {"sso", "firewall"}}, ...]
      by_id     = {"dev-10": working[0], "dev-20": working[1]}                      <- O(1) lookup by ID
      staged    = {"dev-10": {"firewall": "DISABLE"}, "dev-20": {"telemetry": "ENABLE"}}
      selected  = "dev-20"                                                          <- active target
    
  4. Parse commands and validate commits in two passes

    Isolate syntax checking and single-device commit logic into two small, single-purpose helper functions:

    • parse_command(line) splits on whitespace and enforces exact token counts (2 tokens for SELECT/ENABLE/DISABLE, 1 token for COMMIT/RESET), returning (verb, arg) (with "" for bare verbs) or None for any invalid syntax.
    • commit_changes(device, changes) runs Pass 1 (read-only validation) across every staged feature before Pass 2 (set mutation) touches device["features"]:
    from typing import Dict, List, Optional, Tuple
    import copy
    
    # Commands that require one argument (<id> or <feature>) vs commands that take zero arguments
    ARG_VERBS = ("SELECT", "ENABLE", "DISABLE")
    BARE_VERBS = ("COMMIT", "RESET")
    
    
    def parse_command(line: str) -> Optional[Tuple[str, str]]:
        """Parse a raw CLI string into (verb, argument), or return None if malformed."""
        parts = line.split()
        if len(parts) == 2 and parts[0] in ARG_VERBS:
            return parts[0], parts[1]
        if len(parts) == 1 and parts[0] in BARE_VERBS:
            return parts[0], ""
        return None
    
    
    def commit_changes(device: dict, changes: Dict[str, str]) -> bool:
        """Validate all staged changes for one device, then apply them. Return False on invalid state."""
        features = device["features"]
    
        # Pass 1 (Validation only): verify every staged action BEFORE mutating the feature set
        # so a partial failure never leaves a device half-updated.
        for feature, action in changes.items():
            if action == "ENABLE" and feature in features:
                return False
            if action == "DISABLE" and feature not in features:
                return False
    
        # Pass 2 (Mutation): every check succeeded, so safely update the device's features.
        for feature, action in changes.items():
            if action == "ENABLE":
                features.add(feature)
            else:
                features.remove(feature)
        return True
    
  5. Assemble the command execution loop

    With parse_command and commit_changes handling the details, process_laptop_updates reads top-to-bottom like the specification itself. Pay special attention to clearing device_changes right after a successful COMMIT: if you forget device_changes.clear(), a second COMMIT on the same laptop would re-validate ENABLE telemetry against a set that now already contains "telemetry" and falsely fail!

    def process_laptop_updates(devices: List[dict], commands: List[str]) -> Tuple[bool, List[dict]]:
        """Execute batch CLI commands atomically: return (True, updated_copy) or (False, original_devices)."""
        # Deep-copy all device dicts AND their inner feature sets up front so the caller's
        # original_devices input is never touched and any failure rolls back in O(1) time.
        working = copy.deepcopy(devices)
    
        # by_id: {"dev-10": device_dict_in_working, ...} for O(1) lookup while working keeps list order.
        by_id: Dict[str, dict] = {}
        for device in working:
            by_id[device["id"]] = device
    
        # staged: {"dev-10": {"telemetry": "ENABLE", "firewall": "DISABLE"}, ...}
        # Keying by device_id isolates pending edits per laptop; keying by feature lets later edits overwrite earlier ones.
        staged: Dict[str, Dict[str, str]] = {}
        selected: Optional[str] = None
    
        for line in commands:
            parsed = parse_command(line)
            if parsed is None:
                return False, devices
            verb, arg = parsed
    
            # Phase 1: Target switching — keep other devices' staged edits intact when switching.
            if verb == "SELECT":
                if arg not in by_id:
                    return False, devices
                selected = arg
                continue
    
            # Every non-SELECT command requires an active selected device.
            if selected is None:
                return False, devices
            if selected not in staged:
                staged[selected] = {}
            device_changes = staged[selected]
    
            # Phase 2: Stage, reset, or validate-and-commit on the currently selected laptop.
            if verb == "ENABLE" or verb == "DISABLE":
                device_changes[arg] = verb
            elif verb == "RESET":
                device_changes.clear()
            else:  # verb == "COMMIT"
                if not commit_changes(by_id[selected], device_changes):
                    return False, devices
                # Clear staged edits after COMMIT so a second COMMIT does not re-apply them and fail.
                device_changes.clear()
    
        # Uncommitted staged edits at the end of the batch remain unapplied without causing an error.
        return True, working
    
  6. Trace Example 1 and Example 2 step by step

    First trace Example 1 across dev-10 ({"sso", "firewall"}) and dev-20 ({"sso"}) to see how per-device staging prevents both leakage and lost edits:

    Step  Command             selected   staged dictionary                                   working features
    ----  -----------------   --------   -------------------------------------------------   -----------------------------------------
      0   (initial)           None       {}                                                  dev-10: {sso,firewall}, dev-20: {sso}
      1   SELECT dev-10       "dev-10"   {}                                                  dev-10: {sso,firewall}, dev-20: {sso}
      2   DISABLE firewall    "dev-10"   {"dev-10": {"firewall": "DISABLE"}}                 dev-10: {sso,firewall}, dev-20: {sso}
      3   SELECT dev-20       "dev-20"   {"dev-10": {"firewall": "DISABLE"}}                 dev-10: {sso,firewall}, dev-20: {sso}
      4   ENABLE telemetry    "dev-20"   {"dev-10": {...}, "dev-20": {"telemetry":"ENABLE"}} dev-10: {sso,firewall}, dev-20: {sso}
      5   COMMIT              "dev-20"   {"dev-10": {"firewall": "DISABLE"}, "dev-20": {}}   dev-10: {sso,firewall}, dev-20: {sso,telemetry}
      6   SELECT dev-10       "dev-10"   {"dev-10": {"firewall": "DISABLE"}, "dev-20": {}}   dev-10: {sso,firewall}, dev-20: {sso,telemetry}
      7   COMMIT              "dev-10"   {"dev-10": {}, "dev-20": {}}                        dev-10: {sso},          dev-20: {sso,telemetry}
    

    Now trace Example 2's multi-commit rollback: SELECT dev-10 -> ENABLE edr -> COMMIT updates working[0]["features"] to {"sso", "edr"}. Next, SELECT dev-20 -> DISABLE vpn -> COMMIT checks "vpn" in {"diskcrypt"}, sees False, and immediately executes return False, devices—discarding working (including dev-10's committed "edr") and returning the untouched original devices (dev-10: {"sso"}, dev-20: {"diskcrypt"}).

  7. Complete solution

    from typing import Dict, List, Optional, Tuple
    import copy
    
    # Commands that require one argument (<id> or <feature>) vs commands that take zero arguments
    ARG_VERBS = ("SELECT", "ENABLE", "DISABLE")
    BARE_VERBS = ("COMMIT", "RESET")
    
    
    def parse_command(line: str) -> Optional[Tuple[str, str]]:
        """Parse a raw CLI string into (verb, argument), or return None if malformed."""
        parts = line.split()
        if len(parts) == 2 and parts[0] in ARG_VERBS:
            return parts[0], parts[1]
        if len(parts) == 1 and parts[0] in BARE_VERBS:
            return parts[0], ""
        return None
    
    
    def commit_changes(device: dict, changes: Dict[str, str]) -> bool:
        """Validate all staged changes for one device, then apply them. Return False on invalid state."""
        features = device["features"]
    
        # Pass 1 (Validation only): verify every staged action BEFORE mutating the feature set
        # so a partial failure never leaves a device half-updated.
        for feature, action in changes.items():
            if action == "ENABLE" and feature in features:
                return False
            if action == "DISABLE" and feature not in features:
                return False
    
        # Pass 2 (Mutation): every check succeeded, so safely update the device's features.
        for feature, action in changes.items():
            if action == "ENABLE":
                features.add(feature)
            else:
                features.remove(feature)
        return True
    
    
    def process_laptop_updates(devices: List[dict], commands: List[str]) -> Tuple[bool, List[dict]]:
        """Execute batch CLI commands atomically: return (True, updated_copy) or (False, original_devices)."""
        # Deep-copy all device dicts AND their inner feature sets up front so the caller's
        # original_devices input is never touched and any failure rolls back in O(1) time.
        working = copy.deepcopy(devices)
    
        # by_id: {"dev-10": device_dict_in_working, ...} for O(1) lookup while working keeps list order.
        by_id: Dict[str, dict] = {}
        for device in working:
            by_id[device["id"]] = device
    
        # staged: {"dev-10": {"telemetry": "ENABLE", "firewall": "DISABLE"}, ...}
        # Keying by device_id isolates pending edits per laptop; keying by feature lets later edits overwrite earlier ones.
        staged: Dict[str, Dict[str, str]] = {}
        selected: Optional[str] = None
    
        for line in commands:
            parsed = parse_command(line)
            if parsed is None:
                return False, devices
            verb, arg = parsed
    
            # Phase 1: Target switching — keep other devices' staged edits intact when switching.
            if verb == "SELECT":
                if arg not in by_id:
                    return False, devices
                selected = arg
                continue
    
            # Every non-SELECT command requires an active selected device.
            if selected is None:
                return False, devices
            if selected not in staged:
                staged[selected] = {}
            device_changes = staged[selected]
    
            # Phase 2: Stage, reset, or validate-and-commit on the currently selected laptop.
            if verb == "ENABLE" or verb == "DISABLE":
                device_changes[arg] = verb
            elif verb == "RESET":
                device_changes.clear()
            else:  # verb == "COMMIT"
                if not commit_changes(by_id[selected], device_changes):
                    return False, devices
                # Clear staged edits after COMMIT so a second COMMIT does not re-apply them and fail.
                device_changes.clear()
    
        # Uncommitted staged edits at the end of the batch remain unapplied without causing an error.
        return True, working
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of processing this CLI batch like editing a master binder of laptop inventories using a photocopy and one sticky-note pad per laptop. Before reading the first command, you photocopy the entire binder (working = copy.deepcopy(devices)). Whenever an administrator selects a laptop and stages ENABLE or DISABLE, you jot that note onto that specific laptop's sticky note (staged[device_id]). Only when COMMIT arrives do you check every line on that laptop's sticky note against its page in the photocopy, copy the changes onto the photocopy page, and throw away that sticky note. If every command in the batch succeeds, you hand back the finished photocopy; if anything fails—even on command #1,999 after ten earlier COMMITs—you toss the photocopy in the recycling bin and hand back the untouched original binder, making the whole batch atomic (all-or-nothing).

Two naive shortcuts break this workflow. Mutating devices in place or using a shallow copy—copying the outer list or dict while still sharing the inner features set objects in memory—permanently corrupts the caller's original sets before a later command aborts. Keeping a single global staged dictionary instead of keying by device_id either leaks Laptop A's uncommitted edits onto Laptop B after SELECT B or loses Laptop A's edits if cleared on switch.

Trace Example 2 on [dev-10 {"sso"}, dev-20 {"diskcrypt"}] to watch the state machine roll back cleanly across devices:

  1. SELECT dev-10 -> ENABLE edr: Looks up "dev-10" in by_id in O(1) time and records staged["dev-10"]["edr"] = "ENABLE" without touching working yet.
  2. COMMIT: Checks "edr" not in working[0]["features"] ({"sso"}), adds "edr" to produce {"sso", "edr"} inside working, and clears staged["dev-10"].
  3. SELECT dev-20 -> DISABLE vpn -> COMMIT: Checks whether "vpn" is present in working[1]["features"] ({"diskcrypt"}). Because "vpn" is absent, validation fails—so we immediately execute return False, devices, discarding Step 2's committed "edr" because devices was never touched!

Complexity

  • Time: O(S + C * L), where S is the total number of device records and initial feature strings across devices, C is len(commands), and L <= 64 is the maximum string length of an ID or feature flag. copy.deepcopy(devices) and building by_id scan all initial records and feature strings once in O(S * L) time (O(S) dictionary/set inserts). Each SELECT, ENABLE, DISABLE, and RESET command splits one short line and performs O(1) hash-table work (O(L) string hashing). Although a single COMMIT loops over k staged features twice, it immediately clears those k entries afterward—so across the entire batch, every staged ENABLE/DISABLE is validated and applied at most once, giving O(1) amortized time (average work per command over the whole sequence).
  • Space: O(S + C * L), because working duplicates the initial inventory (O(S * L)) and staged stores at most one pending entry per ENABLE/DISABLE command (O(C * L)).

Edge cases

  • Failure after earlier valid COMMITs (Example 2): Committing valid updates on dev-10 and then failing a command on dev-20 (or hitting an unknown ID) rolls back dev-10's committed changes too, returning the original devices unchanged.
  • Commands before any SELECT: Starting with ENABLE, DISABLE, COMMIT, or RESET when selected is None immediately returns (False, devices).
  • Interleaved SELECT across devices (Example 1): Uncommitted staged edits on dev-10 survive SELECT dev-20 -> COMMIT -> SELECT dev-10 -> COMMIT without leaking to dev-20 or disappearing.
  • RESET scoping and trailing uncommitted edits (Example 3): RESET clears uncommitted edits only on selected, and ending with ENABLE audit (no COMMIT) succeeds (True) while leaving "audit" unapplied.
  • Empty or back-to-back COMMITs: Running COMMIT with nothing staged (or running COMMIT twice in a row after clearing device_changes) is a valid no-op and returns True.
  • Overwriting a staged action on the same feature: ENABLE sso followed by DISABLE sso before COMMIT overwrites staged[selected]["sso"] = "DISABLE", so only the final net intent for "sso" is validated against committed features at COMMIT (succeeding if "sso" is enabled, failing if "sso" is absent).
  • Malformed syntax: Empty or whitespace-only strings ("", " "), missing arguments "ENABLE", extra tokens "ENABLE a b", lowercase "commit", or unknown verbs "REBOOT dev-10" return None from parse_command and abort cleanly.

Common mistakes

  • Using shallow copies (devices[:] or [dict(d) for d in devices]). Both share the inner set references with devices, silently mutating the caller's input on features.add(...) and failing rollback assertions.
  • Sharing one staging structure across all laptops. Storing to_enable = set() at top level instead of per device_id applies Laptop A's staged flags to Laptop B when SELECT switches targets before COMMIT.
  • Keeping two separate sets (to_enable and to_disable) without cross-cleanup. If an operator runs ENABLE sso then DISABLE sso, keeping "sso" in both sets makes COMMIT impossible to validate unless DISABLE explicitly removes "sso" from to_enable (a single feature -> action dict handles this automatically).
  • Forgetting device_changes.clear() after COMMIT. Leaving committed actions inside staged[selected] causes a later COMMIT on the same laptop to check "telemetry" in features, see it is now present, and falsely fail validation!
  • Using features.discard(feature) without checking membership first. set.discard silently ignores missing elements, violating the specification that DISABLE of a non-existent feature must fail validation at COMMIT.
  • Mutating features inside the validation loop. When switching to an in-place undo architecture (without full deepcopy), mutating before checking every staged item leaves a device partially modified when a later staged item fails.

Alternative approaches

  • Copy-on-write per device: Instead of deep-copying all 500 laptops up front, keep a shallow copy of the outer list and deep-copy an individual laptop dict (working[idx] = copy.deepcopy(devices[idx])) only the first time COMMIT actually modifies that laptop. Copy-on-write—deferring duplication until a write actually happens—saves memory when a 10-line batch touches 2 laptops out of 100,000, though at len(devices) <= 500 upfront deepcopy is simpler and tiny.
  • Transactional undo log: Mutate working in place and append (device_id, feature, inverse_action) to an undo stack on every COMMIT, replaying the stack in reverse upon error. Useful for gigabyte-scale in-memory databases, unnecessary overhead for 500 records.

Follow-up questions

  • How would you enforce prerequisite rules between flags—for example, requiring flag Y to be active whenever flag X is active? Store prerequisite rules as an adjacency map requires: Dict[str, Set[str]] (for instance, {"telemetry": {"sso", "edr"}}). Inside commit_changes, after checking the individual ENABLE/DISABLE preconditions, compute the candidate post-commit set next_features on a temporary copy of device["features"] and verify that requires.get(flag, set()).issubset(next_features) holds for every flag in next_features before writing next_features back. Checking the complete post-commit snapshot allows enabling "edr" and "telemetry" together in one COMMIT, blocks DISABLE sso while "telemetry" stays active, and supports mutual prerequisites (X <-> Y) cleanly without topological sorting.
  • Suppose multiple administrators submit command batches against the same device registry at the same time; how would you prevent lost updates with optimistic locking? Optimistic concurrency control (OCC) lets sessions stage edits without acquiring upfront locks and catches write conflicts at commit time via per-device integer version counters (version: int). When a session executes SELECT dev-10, it records the snapshot expected_version = 7 alongside dev-10's features; at COMMIT, storage performs an atomic compare-and-set (CAS)—updating the row only if its version is still 7 (UPDATE devices SET features = ?, version = 8 WHERE id = 'dev-10' AND version = 7). If another administrator already bumped dev-10 to version 8, zero rows update, prompting the session to reload version 8 and re-validate its pending flags before retrying. For multi-device atomic batches, verify and bump all touched devices inside a single transaction ordered by device_id to avoid deadlocks.
  • How would you extend the return contract to report machine-readable diagnostics pinpointing which command index and staged flag caused a failure? Introduce an immutable CommandError(command_index: int, raw_command: str, code: str, detail: str) record with an explicit enum of error codes (MALFORMED_COMMAND, UNKNOWN_DEVICE, NO_DEVICE_SELECTED, ALREADY_ACTIVE, NOT_ACTIVE). Store (action, staged_at_index) inside staged[selected][feature] while iterating for idx, line in enumerate(commands): so that when COMMIT at index 11 fails because "sso" staged at index 7 was already active on "dev-10", the error surfaces both the failing COMMIT index (11) and the offending staged command (7). Expose process_laptop_updates_detailed(...) -> Tuple[bool, List[dict], Optional[CommandError]] and implement the original 2-tuple process_laptop_updates as a thin wrapper around it to preserve backward compatibility.

Follow-up questions

Similar questions

More Ziprecruiter interview questions

All 3 Ziprecruiter questions →