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:
SELECT <device_id>— Sets<device_id>as the active target device. Fails if<device_id>does not match any record indevices. Switching to another device leaves uncommitted pending edits on earlier devices intact without applying them or leaking them onto the new target.ENABLE <feature>— Records a pending addition of<feature>on the active device. Fails if no device has been selected yet.DISABLE <feature>— Records a pending removal of<feature>on the active device. Fails if no device has been selected yet.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 pendingENABLEis already present in that device's committedfeatures, or if any feature pendingDISABLEis absent from its committedfeatures. (If multiple pending commands targeted the same feature on the same device beforeCOMMIT, the latest command determines its pending action; committing with zero pending edits succeeds as a no-op.)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 ofdevices, 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) <= 5001 <= len(commands) <= 2,000- Device IDs, model names, and feature names are non-empty alphanumeric/identifier strings of length
1to64. - Every
'id'indevicesis distinct.
Step-by-step walkthrough
Restate the command contract and batch semantics
We receive an inventory list
devices(each dict holding'id','model', and'features'as asetof strings) plus a sequential list of CLIcommands. 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
COMMITcommands 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>, andDISABLE <feature>take exactly one whitespace-delimited argument;COMMITandRESETtake zero arguments. Unknown verbs, lowercase verbs, empty/whitespace strings, or extra tokens fail immediately. - Selection requirement: Running
ENABLE,DISABLE,COMMIT, orRESETbefore any laptop has been selected fails immediately. - Per-device staging: Staging
DISABLE firewallwhiledev-10is selected attaches that pending edit only todev-10. RunningSELECT dev-20neither deletesdev-10's staged edits nor leaks them ontodev-20. - Repeated staging on one feature: Staging two commands for the same feature on the same laptop before
COMMITkeeps the latest intent (ENABLE ssofollowed byDISABLE ssoleavessso: "DISABLE"), and only that final intent is validated against committedfeaturesatCOMMIT. COMMITvalidation and cleanup: Checks all staged edits for the selected laptop against its currently committedfeatures(ENABLEfails if already enabled;DISABLEfails if not currently enabled), applies them, and clears that laptop's staging buffer. An emptyCOMMITis a valid no-op.RESETand uncommitted leftovers:RESETclears uncommitted staged edits for the selected laptop only; any edits still staged when the command list ends remain uncommitted and the batch returnsTrue.
- If every command succeeds, return
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:
- 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 samesetobjects in memory as the caller's input! Mutatingcopy[0]["features"].add("telemetry")silently corruptsdevices[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)- A single shared staging buffer: Keeping one global
staged_to_addset instead of per-device staging causesSELECT dev-10 -> DISABLE firewall -> SELECT dev-20 -> COMMITto leakdev-10's pending edits ontodev-20, while clearing the buffer onSELECTsilently dropsdev-10's pending edits. - Mutating during validation: If
COMMITloops through staged edits and adds"telemetry"before checking"DISABLE missing_flag", a mid-commit failure leaves the working device half-updated. - Fragile manual undo logs: Mutating
devicesin 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.deepcopyis 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.- The shallow-copy trap: Calling
Design the per-device state and deep-copy strategy
Two clean design choices eliminate all four bugs at once:
- Deep-copy
devicesonce at the start (working = copy.deepcopy(devices)). Every commit mutatesworkingonly. If any command on line 1 or line 1,999 fails, we simply executereturn False, devices—zero undo logic needed, andworkingis garbage-collected. - Store pending changes in a nested dictionary
staged[device_id][feature] = action. Keying the outer dictionary bydevice_idisolates each laptop's staging area acrossSELECTswitches; keying the inner dictionary byfeature("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- Deep-copy
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 (2tokens forSELECT/ENABLE/DISABLE,1token forCOMMIT/RESET), returning(verb, arg)(with""for bare verbs) orNonefor any invalid syntax.commit_changes(device, changes)runs Pass 1 (read-only validation) across every staged feature before Pass 2 (set mutation) touchesdevice["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 TrueAssemble the command execution loop
With
parse_commandandcommit_changeshandling the details,process_laptop_updatesreads top-to-bottom like the specification itself. Pay special attention to clearingdevice_changesright after a successfulCOMMIT: if you forgetdevice_changes.clear(), a secondCOMMITon the same laptop would re-validateENABLE telemetryagainst 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, workingTrace Example 1 and Example 2 step by step
First trace Example 1 across
dev-10({"sso", "firewall"}) anddev-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 -> COMMITupdatesworking[0]["features"]to{"sso", "edr"}. Next,SELECT dev-20 -> DISABLE vpn -> COMMITchecks"vpn" in {"diskcrypt"}, seesFalse, and immediately executesreturn False, devices—discardingworking(includingdev-10's committed"edr") and returning the untouched originaldevices(dev-10: {"sso"}, dev-20: {"diskcrypt"}).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:
SELECT dev-10->ENABLE edr: Looks up"dev-10"inby_idinO(1)time and recordsstaged["dev-10"]["edr"] = "ENABLE"without touchingworkingyet.COMMIT: Checks"edr" not in working[0]["features"]({"sso"}), adds"edr"to produce{"sso", "edr"}insideworking, and clearsstaged["dev-10"].SELECT dev-20->DISABLE vpn->COMMIT: Checks whether"vpn"is present inworking[1]["features"]({"diskcrypt"}). Because"vpn"is absent, validation fails—so we immediately executereturn False, devices, discarding Step 2's committed"edr"becausedeviceswas never touched!
Complexity
- Time:
O(S + C * L), whereSis the total number of device records and initial feature strings acrossdevices,Cislen(commands), andL <= 64is the maximum string length of an ID or feature flag.copy.deepcopy(devices)and buildingby_idscan all initial records and feature strings once inO(S * L)time (O(S)dictionary/set inserts). EachSELECT,ENABLE,DISABLE, andRESETcommand splits one short line and performsO(1)hash-table work (O(L)string hashing). Although a singleCOMMITloops overkstaged features twice, it immediately clears thosekentries afterward—so across the entire batch, every stagedENABLE/DISABLEis validated and applied at most once, givingO(1)amortized time (average work per command over the whole sequence). - Space:
O(S + C * L), becauseworkingduplicates the initial inventory (O(S * L)) andstagedstores at most one pending entry perENABLE/DISABLEcommand (O(C * L)).
Edge cases
- Failure after earlier valid
COMMITs (Example 2): Committing valid updates ondev-10and then failing a command ondev-20(or hitting an unknown ID) rolls backdev-10's committed changes too, returning the originaldevicesunchanged. - Commands before any
SELECT: Starting withENABLE,DISABLE,COMMIT, orRESETwhenselected is Noneimmediately returns(False, devices). - Interleaved
SELECTacross devices (Example 1): Uncommitted staged edits ondev-10surviveSELECT dev-20 -> COMMIT -> SELECT dev-10 -> COMMITwithout leaking todev-20or disappearing. RESETscoping and trailing uncommitted edits (Example 3):RESETclears uncommitted edits only onselected, and ending withENABLE audit(noCOMMIT) succeeds (True) while leaving"audit"unapplied.- Empty or back-to-back
COMMITs: RunningCOMMITwith nothing staged (or runningCOMMITtwice in a row after clearingdevice_changes) is a valid no-op and returnsTrue. - Overwriting a staged action on the same feature:
ENABLE ssofollowed byDISABLE ssobeforeCOMMIToverwritesstaged[selected]["sso"] = "DISABLE", so only the final net intent for"sso"is validated against committedfeaturesatCOMMIT(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"returnNonefromparse_commandand abort cleanly.
Common mistakes
- Using shallow copies (
devices[:]or[dict(d) for d in devices]). Both share the innersetreferences withdevices, silently mutating the caller's input onfeatures.add(...)and failing rollback assertions. - Sharing one staging structure across all laptops. Storing
to_enable = set()at top level instead of perdevice_idapplies Laptop A's staged flags to Laptop B whenSELECTswitches targets beforeCOMMIT. - Keeping two separate sets (
to_enableandto_disable) without cross-cleanup. If an operator runsENABLE ssothenDISABLE sso, keeping"sso"in both sets makesCOMMITimpossible to validate unlessDISABLEexplicitly removes"sso"fromto_enable(a singlefeature -> actiondict handles this automatically). - Forgetting
device_changes.clear()afterCOMMIT. Leaving committed actions insidestaged[selected]causes a laterCOMMITon 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.discardsilently ignores missing elements, violating the specification thatDISABLEof a non-existent feature must fail validation atCOMMIT. - Mutating
featuresinside the validation loop. When switching to an in-place undo architecture (without fulldeepcopy), 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
500laptops 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 timeCOMMITactually 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 atlen(devices) <= 500upfrontdeepcopyis simpler and tiny. - Transactional undo log: Mutate
workingin place and append(device_id, feature, inverse_action)to an undo stack on everyCOMMIT, 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"}}). Insidecommit_changes, after checking the individualENABLE/DISABLEpreconditions, compute the candidate post-commit setnext_featureson a temporary copy ofdevice["features"]and verify thatrequires.get(flag, set()).issubset(next_features)holds for everyflaginnext_featuresbefore writingnext_featuresback. Checking the complete post-commit snapshot allows enabling"edr"and"telemetry"together in oneCOMMIT, blocksDISABLE ssowhile"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 executesSELECT dev-10, it records the snapshotexpected_version = 7alongsidedev-10's features; atCOMMIT, storage performs an atomic compare-and-set (CAS)—updating the row only if its version is still7(UPDATE devices SET features = ?, version = 8 WHERE id = 'dev-10' AND version = 7). If another administrator already bumpeddev-10to version8, zero rows update, prompting the session to reload version8and re-validate its pending flags before retrying. For multi-device atomic batches, verify and bump all touched devices inside a single transaction ordered bydevice_idto 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)insidestaged[selected][feature]while iteratingfor idx, line in enumerate(commands):so that whenCOMMITat index11fails because"sso"staged at index7was already active on"dev-10", the error surfaces both the failingCOMMITindex (11) and the offending staged command (7). Exposeprocess_laptop_updates_detailed(...) -> Tuple[bool, List[dict], Optional[CommandError]]and implement the original 2-tupleprocess_laptop_updatesas a thin wrapper around it to preserve backward compatibility.
Follow-up questions
- How would you enforce prerequisite rules between flags—for example, requiring flag Y to be active whenever flag X is active?
- Suppose multiple administrators submit command batches against the same device registry at the same time; how would you prevent lost updates with optimistic locking?
- How would you extend the return contract to report machine-readable diagnostics pinpointing which command index and staged flag caused a failure?
Similar questions
- Real-Time Restaurant Vote Leaderboard
- Predecessor and Successor in Sorted IDs
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging