Hardware Device Registry: Validation, Active Tallies, and Bulk Transitions

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

You are maintaining an in-memory hardware inventory service built around ALLOWED_STATUSES, Device, RegistrationError, and DeviceRegistry:

ALLOWED_STATUSES = {
    "sensor": {"ACTIVE", "INACTIVE", "MAINTENANCE"},
    "camera": {"ACTIVE", "INACTIVE", "FAULTY"},
    "gateway": {"ACTIVE", "MAINTENANCE", "FAULTY"},
}

Each Device(device_id, device_type, status, registered_at) instance records those four attributes and initializes last_maintenance_at = registered_at and failure_count = 0. External monitoring code may subsequently update last_maintenance_at, failure_count, or status directly on stored Device objects. DeviceRegistry stores registered hardware in self.devices (dict mapping device_id -> Device).

Complete the following four tasks in DeviceRegistry:

  1. Fix is_valid_status(self, device_type, status) -> bool (used by add_device):

    • The starter implementation mistakenly scans every set in ALLOWED_STATUSES.values() while ignoring device_type, causing add_device to accept statuses belonging to other hardware categories as well as unrecognized device_type strings.
    • Update is_valid_status so it returns True if and only if both device_type and status are str instances, device_type is an exact key in ALLOWED_STATUSES, and status belongs to ALLOWED_STATUSES[device_type]. Non-string or unhashable arguments (such as None, lists, or sets) must return False cleanly without raising TypeError.
    • add_device(self, device) -> bool must continue returning False (leaving self.devices unchanged) when is_valid_status rejects the pair, and storing self.devices[device.device_id] = device while returning True otherwise.
  2. Implement register_device(self, device_id, device_type, status, registered_at) -> Device:

    • Validate arguments in the exact order below, raising RegistrationError(reason, message) (a ValueError subclass whose .reason attribute holds the machine-readable code) on the first failing check without mutating self.devices:
      1. "INVALID_ID" — device_id is not a str or equals "".
      2. "UNKNOWN_TYPE" — device_type is not a str or is absent from ALLOWED_STATUSES.
      3. "STATUS_NOT_ALLOWED" — status is not a str or is disallowed for device_type by ALLOWED_STATUSES.
      4. "INVALID_TIME" — registered_at is not an int (bool values such as True/False and float values must be rejected).
      5. "NEGATIVE_TIME" — registered_at < 0 (0 and positive integers are permitted).
      6. "DUPLICATE_ID" — device_id already exists in self.devices (even when every field matches the stored record).
    • When all six checks succeed, construct Device(device_id, device_type, status, registered_at), insert it under self.devices[device_id], and return the new Device.
  3. Implement count_active_by_type(self) -> Dict[str, int]:

    • Return a dictionary mapping each device_type to the count of currently stored devices whose status == "ACTIVE".
    • Omit any device_type whose active count is 0, and insert dictionary keys in ascending alphabetical order.
  4. Implement bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int:

    • First validate parameters: now, maintenance_interval, and failure_threshold must each be numeric (int or float, rejecting bool and non-numbers), with maintenance_interval > 0 and failure_threshold > 0; otherwise raise ValueError before modifying any device.
    • Only devices currently in status "ACTIVE" are eligible ("INACTIVE", "MAINTENANCE", and "FAULTY" devices remain untouched).
    • For each "ACTIVE" device, evaluate candidate target statuses in strict priority order:
      1. "FAULTY" if device.failure_count >= failure_threshold.
      2. "MAINTENANCE" if now - device.last_maintenance_at >= maintenance_interval.
    • Transition the device to the first triggered target status permitted for its device_type in ALLOWED_STATUSES (falling through to rule 2 if rule 1 triggers a disallowed status, or leaving the device "ACTIVE" if no triggered target is allowed). Return the integer count of devices whose status changed.

Examples

Example 1

registry = DeviceRegistry()
rejected = registry.add_device(Device("gw-04", "gateway", "INACTIVE", 250))
# rejected -> False ("gateway" permits {"ACTIVE", "MAINTENANCE", "FAULTY"}, not "INACTIVE")

dev = registry.register_device("gw-04", "gateway", "ACTIVE", 250)
# dev.registered_at == 250, dev.last_maintenance_at == 250, dev.failure_count == 0

# Raises RegistrationError with reason == "STATUS_NOT_ALLOWED" (checked before negative time & duplicate ID)
registry.register_device("gw-04", "sensor", "FAULTY", -10)

Walk-through: "INACTIVE" exists on sensors and cameras, not gateways, so the fixed is_valid_status returns False and add_device leaves registry.devices empty. Registering "gw-04" as an "ACTIVE" "gateway" at timestamp 250 succeeds. A subsequent malformed call ("gw-04", "sensor", "FAULTY", -10) fails check 3 ("STATUS_NOT_ALLOWED") before reaching "NEGATIVE_TIME" or "DUPLICATE_ID", leaving "gw-04" unchanged.

Example 2

registry = DeviceRegistry()
registry.register_device("sen-10", "sensor", "ACTIVE", 50)
registry.register_device("sen-20", "sensor", "MAINTENANCE", 60)
registry.register_device("gw-10", "gateway", "ACTIVE", 70)
registry.register_device("gw-20", "gateway", "ACTIVE", 80)
registry.register_device("cam-10", "camera", "INACTIVE", 90)

counts = registry.count_active_by_type()
# counts -> {"gateway": 2, "sensor": 1}

Walk-through: Two gateways and one sensor currently hold status "ACTIVE". Because "cam-10" is "INACTIVE", "camera" has zero active units and is omitted entirely; the remaining keys are inserted in sorted order ["gateway", "sensor"].

Example 3

registry = DeviceRegistry()
# Helper setup: register each device at t=0, then set (last_maintenance_at, failure_count):
#   "gw-10":  ("gateway", "ACTIVE",  last_maintenance_at=300, failure_count=3) -> FAULTY
#   "sen-10": ("sensor",  "ACTIVE",  last_maintenance_at=350, failure_count=4) -> MAINTENANCE
#   "sen-20": ("sensor",  "ACTIVE",  last_maintenance_at=500, failure_count=5) -> ACTIVE (unchanged)
#   "cam-10": ("camera",  "ACTIVE",  last_maintenance_at=100, failure_count=0) -> ACTIVE (unchanged)
#   "cam-20": ("camera",  "ACTIVE",  last_maintenance_at=550, failure_count=2) -> FAULTY
#   "gw-20":  ("gateway", "FAULTY",  last_maintenance_at=0,   failure_count=8) -> FAULTY (ineligible)

changed = registry.bulk_update_status(now=600, maintenance_interval=200, failure_threshold=2)
# changed -> 3

Walk-through: At now = 600 with maintenance_interval = 200 and failure_threshold = 2, "gw-10" triggers both rules and picks higher-priority "FAULTY". "sen-10" triggers "FAULTY" first, sees "sensor" disallows "FAULTY", and falls through to "MAINTENANCE" (600 - 350 = 250 >= 200). "sen-20" disallows "FAULTY" and is not yet overdue (100 < 200), "cam-10" disallows "MAINTENANCE", "cam-20" hits 2 >= 2 ("FAULTY"), and "gw-20" is skipped because it is not "ACTIVE"—giving 3 transitions in total.

Constraints

  • All string comparisons for device_type and status are strictly case-sensitive.
  • Any failed register_device or bulk_update_status call must leave self.devices and all stored Device objects completely unmodified.
  • registered_at must be an exact int (>= 0), rejecting bool and float.
  • now, maintenance_interval, and failure_threshold accept int or float (rejecting bool), with maintenance_interval > 0 and failure_threshold > 0.

Step-by-step walkthrough

  1. Settle requirements and API contracts before coding

    This exercise builds four incremental changes on a single DeviceRegistry module:

    1. Find and fix a validation bug exposed by a failing test.
    2. Add register_device with full input validation.
    3. Add count_active_by_type excluding zero-count types.
    4. Add bulk_update_status driven by failure count and maintenance age.

    Because progressive business-logic interviews intentionally leave edge behavior open, lock down explicit, testable contracts first:

    • Error reporting: Keep add_device returning True / False so existing callers and tests do not break. Have the new register_device raise RegistrationError(reason, message) (a ValueError subclass with a machine-readable reason attribute like "DUPLICATE_ID") so callers know which rule failed without fragile string matching.
    • Exact case matching: "Sensor" and "active" are rejected rather than silently upper/lowercased, surfacing bad upstream data immediately.
    • Timestamps and duplicates: registered_at must be a non-negative int (bool and float are rejected; future timestamps are allowed because the registry holds no wall clock). Re-registering an existing device_id always raises "DUPLICATE_ID", even with identical fields.
    • Single-threaded core, deterministic output: Assume single-threaded calls for the base class (multi-thread safety is handled via a lock in follow-ups), and insert keys in sorted order in count_active_by_type.
  2. Part 1: Trace the status-validation bug to the root cause

    Start from Example 1's rejected call and trace backwards line by line:

    call:       gateway = Device("gw-04", "gateway", "INACTIVE", 250)
                registry.add_device(gateway)  --> returned True in starter (expected False!)
                          |
                          v
    add_device: calls self.is_valid_status("gateway", "INACTIVE")
                          |
                          v
    buggy code: for statuses in ALLOWED_STATUSES.values():
                    if status in statuses:    --> "INACTIVE" is in sensor's set -> returns True!
    

    Look at the method signature def is_valid_status(self, device_type, status):—the parameter device_type is never used! Instead of checking whether status is valid for this specific device_type, the loop checks whether any device type in the entire configuration map allows status.

    Because device_type is ignored, the exact same bug lets two whole classes of invalid devices slip into self.devices:

    • Cross-type statuses: "gateway" with "INACTIVE" (from "sensor"/"camera"), "sensor" with "FAULTY" (from "camera"/"gateway"), and "camera" with "MAINTENANCE" (from "sensor"/"gateway").
    • Completely unknown device types: Device("prt-1", "printer", "ACTIVE", 0) is accepted because "ACTIVE" exists in "sensor", and "printer" is never looked up!
  3. Part 1: Fix is_valid_status with a minimal, safe lookup

    Instead of scanning ALLOWED_STATUSES.values(), look up ALLOWED_STATUSES.get(device_type) directly. Checking isinstance(..., str) first also prevents unhashable inputs (like ["camera"]) from crashing dictionary or set lookups with TypeError:

        def is_valid_status(self, device_type, status):
            # Reject non-strings first so unhashable values (like lists or sets) return False
            # cleanly instead of crashing dict/set lookups with TypeError.
            if not isinstance(device_type, str) or not isinstance(status, str):
                return False
            allowed_for_type = ALLOWED_STATUSES.get(device_type)
            if allowed_for_type is None:
                return False
            return status in allowed_for_type
    

    Leave add_device untouched so we do not break existing callers that rely on its boolean return value or overwrite behavior. Pin the fix with regression tests covering cross-type statuses (sensor/FAULTY, gateway/INACTIVE, camera/MAINTENANCE), unknown types (printer/ACTIVE), unknown statuses (camera/BROKEN), unhashable types, and valid pairs (camera/FAULTY, sensor/MAINTENANCE).

  4. Part 2: Order checks for atomic, predictable registration

    Atomicity means an operation either succeeds completely or leaves zero changes behind. In register_device, atomicity is guaranteed by running every validation check before constructing Device or writing to self.devices.

    The order of those six checks also matters for two subtle reasons:

    1. Validate types before hash lookups: If a caller passes device_id = ["s-9"] and we check device_id in self.devices first, Python raises TypeError: unhashable type: 'list' instead of our clean RegistrationError("INVALID_ID", ...).
    2. Reject bool before int, and check state last: In Python, bool subclasses int (isinstance(True, int) evaluates to True!), so isinstance(registered_at, bool) must be checked first. Running the DUPLICATE_ID lookup last guarantees malformed arguments always report the same input error regardless of what is currently stored.
    Check order in _validate_registration:
      1. not isinstance(device_id, str) or device_id == ""   --> RegistrationError("INVALID_ID")
      2. not isinstance(device_type, str) or not in map      --> RegistrationError("UNKNOWN_TYPE")
      3. not isinstance(status, str) or not valid for type   --> RegistrationError("STATUS_NOT_ALLOWED")
      4. isinstance(registered_at, bool) or not int          --> RegistrationError("INVALID_TIME")
      5. registered_at < 0                                   --> RegistrationError("NEGATIVE_TIME")
      6. device_id in self.devices                           --> RegistrationError("DUPLICATE_ID")
      --> All passed: create Device, store in self.devices[device_id], return Device
    
  5. Part 2: Implement RegistrationError and register_device

    Putting validation in _validate_registration keeps register_device four lines long and crystal clear:

    class RegistrationError(ValueError):
        """Raised by register_device; `reason` names the check that failed."""
    
        def __init__(self, reason: str, message: str) -> None:
            super().__init__(message)
            self.reason = reason
    
        def register_device(self, device_id, device_type, status, registered_at) -> Device:
            # Validate every field and uniqueness check BEFORE creating or storing anything
            # so any failed call leaves self.devices completely untouched (atomic rejection).
            self._validate_registration(device_id, device_type, status, registered_at)
            device = Device(device_id, device_type, status, registered_at)
            self.devices[device_id] = device
            return device
    
        def _validate_registration(self, device_id, device_type, status, registered_at):
            # 1-3: Validate string types and allowed-map membership before any hash lookup
            # on self.devices so malformed inputs raise RegistrationError, never TypeError.
            if not isinstance(device_id, str) or device_id == "":
                raise RegistrationError("INVALID_ID", f"device_id must be a non-empty string, got {device_id!r}")
            if not isinstance(device_type, str) or device_type not in ALLOWED_STATUSES:
                raise RegistrationError("UNKNOWN_TYPE", f"unknown device type {device_type!r}")
            if not isinstance(status, str) or not self.is_valid_status(device_type, status):
                raise RegistrationError("STATUS_NOT_ALLOWED", f"status {status!r} is not allowed for {device_type!r}")
    
            # 4-5: In Python, bool is a subclass of int (isinstance(True, int) is True),
            # so explicitly reject bool before checking isinstance(..., int).
            if isinstance(registered_at, bool) or not isinstance(registered_at, int):
                raise RegistrationError("INVALID_TIME", f"registered_at must be an int, got {registered_at!r}")
            if registered_at < 0:
                raise RegistrationError("NEGATIVE_TIME", f"registered_at must be >= 0, got {registered_at}")
    
            # 6: Check duplicate ID last so malformed inputs always fail with the same
            # input-validation reason regardless of current registry state.
            if device_id in self.devices:
                raise RegistrationError("DUPLICATE_ID", f"device {device_id!r} is already registered")
    
  6. Part 3: Count active devices per type while omitting zeros

    To omit device types with zero active devices naturally, iterate over self.devices.values() rather than starting from ALLOWED_STATUSES.keys(). A device type only enters active_counts when we actually encounter an "ACTIVE" device of that type—so zero-count types are never created in the first place.

    Why scan on demand (O(n) over n devices) instead of maintaining a cached active_counts dictionary on every write? Because Device.status is a plain public attribute (device.status = "ACTIVE"). Just as external code mutates last_maintenance_at and failure_count directly on Device instances, direct assignments to device.status would bypass the registry and silently desynchronize cached counters. Scanning self.devices is always accurate and fast.

        def count_active_by_type(self) -> Dict[str, int]:
            # active_counts: {device_type: count of ACTIVE devices}, accumulated from stored
            # devices so types with zero active devices are omitted automatically.
            active_counts = {}
            for device in self.devices.values():
                if device.status == "ACTIVE":
                    device_type = device.device_type
                    active_counts[device_type] = active_counts.get(device_type, 0) + 1
    
            # Insert keys in sorted order so iteration and string output are deterministic.
            sorted_counts = {}
            for device_type in sorted(active_counts):
                sorted_counts[device_type] = active_counts[device_type]
            return sorted_counts
    
  7. Part 4: Bulk status update with priority and per-type fallback

    Pin down clear, conflict-free rules for bulk_update_status(now, maintenance_interval, failure_threshold):

    • Parameter guard: Reject non-numeric/boolean arguments or maintenance_interval <= 0 or failure_threshold <= 0 with ValueError before touching any device.
    • Eligibility: Only devices currently in "ACTIVE" are eligible ("INACTIVE", "MAINTENANCE", and "FAULTY" devices are already out of normal service).
    • Priority and per-type fallback:
      1. Check failures first (device.failure_count >= failure_threshold -> "FAULTY"), because hardware failure is more urgent than routine service.
      2. Crucial interaction with ALLOWED_STATUSES: "sensor" does not allow "FAULTY", and "camera" does not allow "MAINTENANCE". If a rule triggers a target status that is_valid_status rejects for that device's type, fall through to the next triggered rule instead of writing an illegal status! For example, an "ACTIVE" sensor that is both failing and overdue cannot become "FAULTY", so it falls through and becomes "MAINTENANCE".
    device_type   failing (>= T)?   overdue (>= I)?   allowed statuses              chosen target
    gateway       yes               yes               ACTIVE, MAINTENANCE, FAULTY   "FAULTY"      (priority 1 wins)
    sensor        yes               yes               ACTIVE, INACTIVE, MAINTENANCE "MAINTENANCE" ("FAULTY" disallowed -> falls through)
    sensor        yes               no                ACTIVE, INACTIVE, MAINTENANCE None          ("FAULTY" disallowed, not overdue)
    camera        no                yes               ACTIVE, INACTIVE, FAULTY      None          ("MAINTENANCE" disallowed)
    
        def bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int:
            # Validate threshold parameters up front so an invalid call mutates zero devices.
            if (
                isinstance(now, bool)
                or not isinstance(now, (int, float))
                or isinstance(maintenance_interval, bool)
                or not isinstance(maintenance_interval, (int, float))
                or isinstance(failure_threshold, bool)
                or not isinstance(failure_threshold, (int, float))
            ):
                raise ValueError("now, maintenance_interval, and failure_threshold must be numbers")
            if maintenance_interval <= 0 or failure_threshold <= 0:
                raise ValueError("maintenance_interval and failure_threshold must be positive")
    
            updated_count = 0
            for device in self.devices.values():
                new_status = self._choose_bulk_target(device, now, maintenance_interval, failure_threshold)
                # Count only genuine transitions where a valid target status differs from current status.
                if new_status is not None and new_status != device.status:
                    device.status = new_status
                    updated_count += 1
            return updated_count
    
        def _choose_bulk_target(self, device, now, maintenance_interval, failure_threshold):
            """Return the highest-priority triggered status permitted for this device's type, or None."""
            # Only currently ACTIVE devices are eligible; INACTIVE/MAINTENANCE/FAULTY stay untouched.
            if device.status != "ACTIVE":
                return None
    
            # Priority 1: failures reaching failure_threshold prefer "FAULTY".
            # If "FAULTY" is disallowed for this type (e.g., "sensor"), fall through to check maintenance.
            if device.failure_count >= failure_threshold:
                if self.is_valid_status(device.device_type, "FAULTY"):
                    return "FAULTY"
    
            # Priority 2: elapsed time since last maintenance reaching maintenance_interval tries "MAINTENANCE".
            elapsed_since_maintenance = now - device.last_maintenance_at
            if elapsed_since_maintenance >= maintenance_interval:
                if self.is_valid_status(device.device_type, "MAINTENANCE"):
                    return "MAINTENANCE"
    
            return None
    
  8. Walk through Example 3 and assemble the full solution

    Trace bulk_update_status(now=600, maintenance_interval=200, failure_threshold=2) across the six devices from Example 3:

    id       type      before   last_maint  elapsed  failures  outcome
    gw-10    gateway   ACTIVE   300         300      3         -> FAULTY       (both trigger; FAULTY wins)
    sen-10   sensor    ACTIVE   350         250      4         -> MAINTENANCE  (sensor disallows FAULTY; falls through)
    sen-20   sensor    ACTIVE   500         100      5         unchanged       (sensor disallows FAULTY; not overdue)
    cam-10   camera    ACTIVE   100         500      0         unchanged       (camera disallows MAINTENANCE)
    cam-20   camera    ACTIVE   550         50       2         -> FAULTY       (failures == 2 hits boundary)
    gw-20    gateway   FAULTY   0           600      8         unchanged       (not ACTIVE -> ineligible)
    

    Exactly 3 devices (gw-10, sen-10, cam-20) change status, so the call returns 3. Calling it a second time immediately returns 0 because those 3 devices are no longer "ACTIVE".

    from typing import Dict
    
    # Configuration map: each known device_type -> set of valid status strings for that type.
    ALLOWED_STATUSES = {
        "sensor": {"ACTIVE", "INACTIVE", "MAINTENANCE"},
        "camera": {"ACTIVE", "INACTIVE", "FAULTY"},
        "gateway": {"ACTIVE", "MAINTENANCE", "FAULTY"},
    }
    
    
    class RegistrationError(ValueError):
        """Raised by register_device; `reason` names the check that failed."""
    
        def __init__(self, reason: str, message: str) -> None:
            super().__init__(message)
            self.reason = reason
    
    
    class Device:
        def __init__(self, device_id, device_type, status, registered_at):
            self.device_id = device_id
            self.device_type = device_type
            self.status = status
            self.registered_at = registered_at
            # New devices start with last maintenance at registration time and zero failures.
            self.last_maintenance_at = registered_at
            self.failure_count = 0
    
    
    class DeviceRegistry:
        def __init__(self):
            # Primary store: maps device_id (str) -> Device instance.
            self.devices = {}
    
        def is_valid_status(self, device_type, status):
            # Reject non-strings first so unhashable values (like lists or sets) return False
            # cleanly instead of crashing dict/set lookups with TypeError.
            if not isinstance(device_type, str) or not isinstance(status, str):
                return False
            allowed_for_type = ALLOWED_STATUSES.get(device_type)
            if allowed_for_type is None:
                return False
            return status in allowed_for_type
    
        def add_device(self, device):
            if not self.is_valid_status(device.device_type, device.status):
                return False
            self.devices[device.device_id] = device
            return True
    
        def register_device(self, device_id, device_type, status, registered_at) -> Device:
            # Validate every field and uniqueness check BEFORE creating or storing anything
            # so any failed call leaves self.devices completely untouched (atomic rejection).
            self._validate_registration(device_id, device_type, status, registered_at)
            device = Device(device_id, device_type, status, registered_at)
            self.devices[device_id] = device
            return device
    
        def _validate_registration(self, device_id, device_type, status, registered_at):
            # 1-3: Validate string types and allowed-map membership before any hash lookup
            # on self.devices so malformed inputs raise RegistrationError, never TypeError.
            if not isinstance(device_id, str) or device_id == "":
                raise RegistrationError("INVALID_ID", f"device_id must be a non-empty string, got {device_id!r}")
            if not isinstance(device_type, str) or device_type not in ALLOWED_STATUSES:
                raise RegistrationError("UNKNOWN_TYPE", f"unknown device type {device_type!r}")
            if not isinstance(status, str) or not self.is_valid_status(device_type, status):
                raise RegistrationError("STATUS_NOT_ALLOWED", f"status {status!r} is not allowed for {device_type!r}")
    
            # 4-5: In Python, bool is a subclass of int (isinstance(True, int) is True),
            # so explicitly reject bool before checking isinstance(..., int).
            if isinstance(registered_at, bool) or not isinstance(registered_at, int):
                raise RegistrationError("INVALID_TIME", f"registered_at must be an int, got {registered_at!r}")
            if registered_at < 0:
                raise RegistrationError("NEGATIVE_TIME", f"registered_at must be >= 0, got {registered_at}")
    
            # 6: Check duplicate ID last so malformed inputs always fail with the same
            # input-validation reason regardless of current registry state.
            if device_id in self.devices:
                raise RegistrationError("DUPLICATE_ID", f"device {device_id!r} is already registered")
    
        def count_active_by_type(self) -> Dict[str, int]:
            # active_counts: {device_type: count of ACTIVE devices}, accumulated from stored
            # devices so types with zero active devices are omitted automatically.
            active_counts = {}
            for device in self.devices.values():
                if device.status == "ACTIVE":
                    device_type = device.device_type
                    active_counts[device_type] = active_counts.get(device_type, 0) + 1
    
            # Insert keys in sorted order so iteration and string output are deterministic.
            sorted_counts = {}
            for device_type in sorted(active_counts):
                sorted_counts[device_type] = active_counts[device_type]
            return sorted_counts
    
        def bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int:
            # Validate threshold parameters up front so an invalid call mutates zero devices.
            if (
                isinstance(now, bool)
                or not isinstance(now, (int, float))
                or isinstance(maintenance_interval, bool)
                or not isinstance(maintenance_interval, (int, float))
                or isinstance(failure_threshold, bool)
                or not isinstance(failure_threshold, (int, float))
            ):
                raise ValueError("now, maintenance_interval, and failure_threshold must be numbers")
            if maintenance_interval <= 0 or failure_threshold <= 0:
                raise ValueError("maintenance_interval and failure_threshold must be positive")
    
            updated_count = 0
            for device in self.devices.values():
                new_status = self._choose_bulk_target(device, now, maintenance_interval, failure_threshold)
                # Count only genuine transitions where a valid target status differs from current status.
                if new_status is not None and new_status != device.status:
                    device.status = new_status
                    updated_count += 1
            return updated_count
    
        def _choose_bulk_target(self, device, now, maintenance_interval, failure_threshold):
            """Return the highest-priority triggered status permitted for this device's type, or None."""
            # Only currently ACTIVE devices are eligible; INACTIVE/MAINTENANCE/FAULTY stay untouched.
            if device.status != "ACTIVE":
                return None
    
            # Priority 1: failures reaching failure_threshold prefer "FAULTY".
            # If "FAULTY" is disallowed for this type (e.g., "sensor"), fall through to check maintenance.
            if device.failure_count >= failure_threshold:
                if self.is_valid_status(device.device_type, "FAULTY"):
                    return "FAULTY"
    
            # Priority 2: elapsed time since last maintenance reaching maintenance_interval tries "MAINTENANCE".
            elapsed_since_maintenance = now - device.last_maintenance_at
            if elapsed_since_maintenance >= maintenance_interval:
                if self.is_valid_status(device.device_type, "MAINTENANCE"):
                    return "MAINTENANCE"
    
            return None
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of DeviceRegistry as an equipment check-in desk with a separate rulebook page for each hardware type: sensors, cameras, and gateways each permit their own subset of statuses, and every check-in or automated sweep must consult that specific device type's page before recording any state change. By validating every rule up front before touching self.devices, a rejected registration is atomic (meaning it either succeeds completely or leaves zero trace behind).

Naive implementations break down in subtle ways across all four parts. In Part 1, looping over ALLOWED_STATUSES.values() checks whether a status exists on any page of the rulebook rather than this device's page—letting gateways enter "INACTIVE" and even accepting unknown types like "printer". In Part 2, checking device_id in self.devices before verifying isinstance(device_id, str) crashes with TypeError on unhashable inputs like ["gw-04"]. And in Part 4, blindly setting "FAULTY" on every failing device puts a failing "sensor" into an illegal status that Part 1 just banned.

Walk through three concrete calls from the examples to see how the pieces fit together:

  1. add_device(Device("gw-04", "gateway", "INACTIVE", 250)) looks up ALLOWED_STATUSES.get("gateway") ({"ACTIVE", "MAINTENANCE", "FAULTY"}), sees "INACTIVE" is missing, returns False, and leaves self.devices empty.
  2. register_device("sen-10", "sensor", "ACTIVE", 50) passes all six ordered checks (INVALID_ID, UNKNOWN_TYPE, STATUS_NOT_ALLOWED, INVALID_TIME, NEGATIVE_TIME, DUPLICATE_ID) and stores "sen-10", so count_active_by_type() includes "sensor" while omitting zero-count categories like "camera".
  3. Suppose "sen-10" later has last_maintenance_at = 350 and failure_count = 4. Calling bulk_update_status(now=600, maintenance_interval=200, failure_threshold=2) checks failures first (4 >= 2), sees "FAULTY" is disallowed for "sensor", falls through to maintenance (600 - 350 = 250 >= 200), confirms "MAINTENANCE" is allowed for "sensor", updates "sen-10" to "MAINTENANCE", and counts 1 real transition.

Complexity

  • Time:
    • is_valid_status and add_device run in O(1) average time because we do a single dictionary lookup by device_type followed by a single hash-set membership check for status (faster than the buggy version, which looped across every type's set).
    • register_device runs in O(1) average time because it performs six constant-time type/value/hash checks and one dictionary insertion into self.devices.
    • count_active_by_type runs in O(n + k log k) time for n registered devices and k device types that have at least one "ACTIVE" device: we scan all n devices once in O(n) to tally active counts, then sort the k distinct active type names (k <= n, typically k <= 3).
    • bulk_update_status runs in O(n) time because we visit each of the n stored devices once and run at most two O(1) is_valid_status checks per device.
  • Space:
    • The registry stores n Device objects in O(n) space.
    • count_active_by_type allocates O(k) auxiliary dictionary space for the k active types, while is_valid_status, register_device, and bulk_update_status use O(1) extra space.

Edge cases

  • Unhashable or non-string arguments (["gw-04"], {"ACTIVE"}, None): Checking isinstance(..., str) before any dict or set lookup ensures is_valid_status returns False and register_device raises RegistrationError rather than crashing with TypeError: unhashable type.
  • Boolean timestamps (registered_at = True or False): Because bool is a subclass of int in Python (isinstance(True, int) is True), we explicitly reject isinstance(registered_at, bool) before accepting int. Timestamp 0 is valid; -1 raises "NEGATIVE_TIME".
  • Empty registry or zero active devices: count_active_by_type() returns {} cleanly, and bulk_update_status(...) returns 0.
  • Exact threshold boundaries and clock skew in bulk updates: failure_count == failure_threshold and now - last_maintenance_at == maintenance_interval trigger updates (>=), whereas 1 unit below does not. If last_maintenance_at > now (clock skew), now - last_maintenance_at is negative and safely treated as not overdue.
  • Failing sensor that is not yet overdue for maintenance: Because "sensor" disallows "FAULTY" and maintenance is not overdue ("sen-20" in Example 3), _choose_bulk_target returns None and leaves the sensor "ACTIVE" rather than corrupting its state.

Common mistakes

  • Patching only one specific type/status pair (if device_type == "gateway" and status == "INACTIVE": return False): Fixes one symptom while still accepting "sensor"/"FAULTY", "camera"/"MAINTENANCE", and unknown types like "printer".
  • Indexing ALLOWED_STATUSES[device_type] directly: Raises an unhandled KeyError on unknown device types like "printer" instead of returning False in is_valid_status.
  • Mutating self.devices before all checks pass (or inserting first and rolling back on error): Breaks atomicity if an exception interrupts validation halfway through.
  • Initializing count_active_by_type with {t: 0 for t in ALLOWED_STATUSES}: Leaves forbidden 0-count entries in the output unless manually stripped, and misses any legacy device whose type was later removed from ALLOWED_STATUSES.
  • Returning a collections.defaultdict(int) from count_active_by_type: If a caller later accesses counts["camera"] when no cameras are active, defaultdict silently inserts "camera": 0, violating the zero-omission contract after the fact.
  • Stopping after the first triggered rule in bulk_update_status when its target status is disallowed: If a failing, overdue sensor checks "FAULTY", sees "FAULTY" is invalid for sensors, and immediately gives up without checking "MAINTENANCE", an overdue sensor never gets sent to maintenance.

Follow-up questions

  • How can you protect register_device against race conditions when concurrent threads attempt to claim the same device_id? Without synchronization, two threads can suffer a race condition (where correctness depends on unpredictable thread scheduling): both pass device_id in self.devices before either executes self.devices[device_id] = device, so the second silently overwrites the first—Python's GIL (Global Interpreter Lock, which serializes bytecode instructions) can switch threads right between the check and the write. Add a self._lock = threading.Lock() on DeviceRegistry and wrap register_device, add_device, bulk_update_status, and count_active_by_type in with self._lock: so check-and-insert executes as one indivisible critical section (or enforce a UNIQUE primary key constraint if backed by SQL).
  • Suppose ALLOWED_STATUSES is reloaded dynamically and drops a status currently assigned to live devices—how should the service handle those records? Never silently mutate or delete live devices during a config reload, because the registry cannot guess the safe physical replacement state. Instead, validate the candidate config against self.devices first to list any devices holding newly removed statuses, then either reject the reload until an operator migrates those devices or run an explicit, logged migration mapping (such as "MAINTENANCE" -> "INACTIVE"), swapping the ALLOWED_STATUSES reference in a single atomic pointer assignment once ready.
  • How would you design a tamper-evident audit trail that records both manual status edits and automated bulk transitions? Funnel every state transition through a single internal helper _set_status(device, new_status, actor, reason, timestamp) that appends an immutable event (device_id, old_status, new_status, actor, reason, timestamp) to an append-only audit log (a list or database table where records are only added, never overwritten). For bulk_update_status, attach a shared batch_id and rule reason (such as "bulk:failure_count>=2"), and turn Device.status into a read-only @property backed by Device._status so external callers cannot mutate statuses behind the audit log's back.

Follow-up questions

Similar questions

More Onepay interview questions

All 3 Onepay questions →