Skip to content
Coding · Medium · Reconciliation · Target O(n log n) · Senior

Reconcile desired and actual state

Diff a desired resource map against the actual one and emit creates, updates and deletes in an order that never breaks a parent-child dependency.

Statement

desired and actual each map a resource name to a dict of fields. Write reconcile(desired, actual, managed_fields) that returns the actions that turn actual into desired, as a list of (action, name) tuples: "create" for a name only in desired, "delete" for a name only in actual, and "update" for a name in both whose fields differ.

Fields named in managed_fields are set by the server, such as an id or a status. Ignore them on both sides when comparing. Every other field counts, including one that is present on one side only, and nested values are compared in full.

A resource may have a "parent" field naming another resource in the same map; a missing parent is the same as None. A parent has to exist for as long as its children do, and that fixes the order: all creates, then all updates, then all deletes. A resource is created after its parent when the parent is being created too. A resource is deleted only after every child of it that is being deleted. Updates go in name order.

Whenever more than one create, or more than one delete, could go next, take the name that sorts first. That makes the answer unique. Do not modify the maps you are given.

Examples

managed_fields = ["uid"]. vpc differs only in uid, so it needs nothing. db moves to its new parent before the old parent is deleted.

desired = {
  "vpc":      {"cidr": "10.0.0.0/16"},
  "subnet-a": {"parent": "vpc", "cidr": "10.0.1.0/24"},
  "db":       {"parent": "subnet-a", "size": "large"},
}
actual = {
  "vpc":        {"cidr": "10.0.0.0/16", "uid": "v-1"},
  "db":         {"parent": "subnet-old", "size": "small", "uid": "d-7"},
  "subnet-old": {"parent": "vpc", "cidr": "10.0.9.0/24", "uid": "s-3"},
  "cache":      {"parent": "subnet-old", "uid": "c-2"},
}
→ [("create", "subnet-a"), ("update", "db"),
   ("delete", "cache"), ("delete", "subnet-old")]

Constraints

Up to 2 × 10⁴ resources in each map. Within one map every parent that is named exists, and there are no cycles. A chain of parents can be as long as the map, so do not recurse along it.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app