Retroactive Data Structures
Persistence lets you look at the past, and with full persistence even branch off from it, but a branch is a new timeline: the present does not change. Retroactivity (Demaine, Iacono and Langerman, 2004; journal version 2007) asks for more: change the past and let the change propagate to the present. "That deposit was really made last Tuesday", "this packet arrived before that one", "this event should have happened earlier": the structure must update every later state as if the history had always been the new one.
The model
A retroactive structure stores a timeline of operations, each tagged with a time . It supports
- INSERT: insert an update operation into the history at time ;
- DELETE: remove the update operation at time from the history;
- QUERY: run query on the state at time .
| Kind | Queries | Updates |
|---|---|---|
| partially retroactive | only on the present (the end of the timeline) | anywhere in the past |
| fully retroactive | at any time | anywhere in the past |
Write for the number of operations in the history and for the number of operations after the time of a retroactive change. The cost of a change is naturally measured against : that is how much of the history it can affect.
The baseline and when it is free
Rollback. Keep the history and an ordinary structure for the present. To change something at time , undo the later operations, apply the change, and redo them. That costs times the cost of an operation, and it works for every structure.
Commutative, invertible operations are free. If the updates commute (their order does not matter) and each has an inverse, partial retroactivity is trivial: inserting an operation in the past is the same as applying it now, and deleting one is applying its inverse now. A counter with "add ", or a set of integers with insert/delete of distinct keys, is retroactive at no cost. Searching (dictionary) structures fall in this class, so partial retroactivity for them is as cheap as the ephemeral structure.
A lower bound: sometimes rollback is the best
Retroactivity is not always cheap. Demaine, Iacono and Langerman show that there are structures for which any retroactive implementation needs time per retroactive operation, in a natural model. The idea of their example: a structure with two registers and and operations "" for constants , and "". A history of the form
time 0: x <- c
time 1..r: y <- y * x + a_r, y <- y * x + a_(r-1), ..., y <- y * x + a_0
query: ycomputes the polynomial by Horner's rule. Retroactively changing the operation at time 0 to "" and querying asks for the same polynomial evaluated at a new point . In the algebraic model (arithmetic operations on the stored values), evaluating a general degree- polynomial at a new point needs operations, even with preprocessing of the coefficients (a classical result of algebraic complexity), so no retroactive implementation does better than rollback. The lower bound is only sketched here.
A fully retroactive queue
Some structures have far better retroactive versions. For a FIFO queue, observe that if the history is valid (never dequeues from an empty queue), the -th dequeue in time order always removes the -th enqueue in time order. So the front of the queue at time is
Keep the enqueues in one order-statistic structure by time and the dequeues in another (here two Fenwick trees over integer time slots; a balanced order-statistic tree works for arbitrary times). Every retroactive insertion or deletion of an enqueue or dequeue, and every query, is . The program builds a valid history of 1200 operations, inserts them in a random order of their times, as if each were a retroactive change, and checks 300 queries against replaying the history from the start.
import random
class Fenwick: # prefix counts over time slots 1..T
def __init__(self, T): self.t = [0] * (T + 1)
def add(self, i, d):
while i < len(self.t): self.t[i] += d; i += i & -i
def prefix(self, i): # count in slots 1..i
s = 0
while i > 0: s += self.t[i]; i -= i & -i
return s
def kth(self, k): # smallest slot with prefix >= k (k >= 1)
pos, step = 0, 1 << (len(self.t).bit_length())
while step:
if pos + step < len(self.t) and self.t[pos + step] < k:
pos += step; k -= self.t[pos]
step >>= 1
return pos + 1
class RetroQueue:
"""Fully retroactive FIFO queue over integer times 1..T (one operation per time)."""
def __init__(self, T):
self.enq, self.deq, self.value = Fenwick(T), Fenwick(T), {}
def insert_enqueue(self, t, x): self.enq.add(t, 1); self.value[t] = x
def insert_dequeue(self, t): self.deq.add(t, 1)
def remove_enqueue(self, t): self.enq.add(t, -1); del self.value[t]
def remove_dequeue(self, t): self.deq.add(t, -1)
def front(self, t): # front of the queue just after time t
d = self.deq.prefix(t) # dequeues so far removed the d earliest enqueues
if self.enq.prefix(t) <= d: return None
return self.value[self.enq.kth(d + 1)]
def replay(ops, t): # the rollback method, for checking: O(r) per query
q, work = [], 0
for time in sorted(ops):
if time > t: break
kind, x = ops[time]
work += 1
if kind == "enq": q.append(x)
elif q: q.pop(0)
return (q[0] if q else None), work
T = 2000
rng = random.Random(2004)
ops, size = {}, 0 # a valid history: never dequeue from an empty queue
for t in sorted(rng.sample(range(1, T + 1), 1200)):
if size == 0 or rng.random() < 0.6:
ops[t] = ("enq", t); size += 1
else:
ops[t] = ("deq", None); size -= 1
rq = RetroQueue(T)
order = sorted(ops)
rng.shuffle(order) # the operations arrive in a random order of their times
for t in order:
if ops[t][0] == "enq": rq.insert_enqueue(t, ops[t][1])
else: rq.insert_dequeue(t)
work = 0
for t in rng.sample(range(1, T + 1), 300):
expect, w = replay(ops, t)
work += w
assert rq.front(t) == expect
print("300 queries of front(t) agree with replaying the history")
print(f"replay did {work / 300:.0f} operations per query; the Fenwick trees about 2 lg T = {2 * T.bit_length()}")
print("front at times 100, 1000, 2000:", rq.front(100), rq.front(1000), rq.front(2000))300 queries of front(t) agree with replaying the history
replay did 610 operations per query; the Fenwick trees about 2 lg T = 22
front at times 100, 1000, 2000: 66 586 1213
Replaying costs about 600 operations per query here, the structure a few dozen steps. Demaine, Iacono and Langerman give these bounds:
| Structure | Partially retroactive | Fully retroactive |
|---|---|---|
| queue | ||
| deque | ||
| union-find (unions only) | ||
| priority queue | via the general transformation (improved later, see below) | |
| any structure | by rollback; in the worst case |
The general transformation turns a partially retroactive structure into a fully retroactive one with an factor of overhead, by keeping partially retroactive copies at checkpoints in time. For priority queues, Demaine, Kaler, Liu, Sidford and Yedidia (2015) later reached polylogarithmic time for full retroactivity, amortized per operation with space, by hierarchical checkpointing.
In C++
The same fully retroactive queue with Fenwick trees, on a small history where each step is a change in the past. The rows show the front of the queue at five times after each change.
#include <cstdio>
#include <optional>
#include <vector>
// Fully retroactive FIFO queue over integer times 1..T, with two Fenwick trees.
class Fenwick {
std::vector<int> t;
public:
explicit Fenwick(int n) : t(n + 1, 0) {}
void add(int i, int d) { for (; i < static_cast<int>(t.size()); i += i & -i) t[i] += d; }
int prefix(int i) const { int s = 0; for (; i > 0; i -= i & -i) s += t[i]; return s; }
int kth(int k) const { // smallest i with prefix(i) >= k
int pos = 0, step = 1;
while (step * 2 < static_cast<int>(t.size())) step *= 2;
for (; step; step /= 2)
if (pos + step < static_cast<int>(t.size()) && t[pos + step] < k) { pos += step; k -= t[pos]; }
return pos + 1;
}
};
class RetroQueue {
Fenwick enq, deq;
std::vector<int> value;
public:
explicit RetroQueue(int T) : enq(T), deq(T), value(T + 1) {}
void enqueue_at(int t, int x) { enq.add(t, 1); value[t] = x; }
void dequeue_at(int t) { deq.add(t, 1); }
void undo_dequeue_at(int t) { deq.add(t, -1); }
std::optional<int> front(int t) const {
int d = deq.prefix(t);
if (enq.prefix(t) <= d) return std::nullopt;
return value[enq.kth(d + 1)];
}
};
void show(const RetroQueue& q, const char* label) {
std::printf("%-34s", label);
for (int t : {10, 20, 30, 40, 50}) {
auto f = q.front(t);
if (f) std::printf(" t=%d:%c", t, static_cast<char>(*f)); else std::printf(" t=%d:-", t);
}
std::printf("\n");
}
int main() {
RetroQueue q(60);
q.enqueue_at(5, 'a'); q.enqueue_at(15, 'b'); q.enqueue_at(25, 'c');
q.dequeue_at(35);
show(q, "enqueue a@5 b@15 c@25, dequeue@35");
q.enqueue_at(2, 'z'); // retroactively: something arrived first
show(q, "insert enqueue z@2 in the past");
q.dequeue_at(12);
show(q, "insert dequeue@12 in the past");
q.undo_dequeue_at(35);
show(q, "remove the dequeue@35");
}enqueue a@5 b@15 c@25, dequeue@35 t=10:a t=20:a t=30:a t=40:b t=50:b
insert enqueue z@2 in the past t=10:z t=20:z t=30:z t=40:a t=50:a
insert dequeue@12 in the past t=10:z t=20:a t=30:a t=40:b t=50:b
remove the dequeue@35 t=10:z t=20:a t=30:a t=40:a t=50:a
Priority queues: a change cascades, but only a little
Why is a priority queue harder? Retroactively inserting a small key early on changes what an early DELETE-MIN returns; the key that DELETE-MIN used to return now stays in the queue and may be returned by a later DELETE-MIN instead of something else, and so on: one change can ripple through many later deletions. Yet the final contents change by exactly one element. The program replays a random history after inserting one key at time 0 and compares.
import heapq, random
from collections import Counter
def run(history):
"""Replay a priority-queue history; return the final contents and what each delete-min returned."""
h, outs = [], []
for op, x in history:
if op == "ins": heapq.heappush(h, x)
else: outs.append(heapq.heappop(h))
return sorted(h), outs
rng = random.Random(7)
history, size = [], 0
for _ in range(60):
if size == 0 or rng.random() < 0.55:
history.append(("ins", rng.randrange(100))); size += 1
else:
history.append(("del", None)); size -= 1
final, outs = run(history)
for x in [0, 30, 99]: # retroactively insert x at time 0
final2, outs2 = run([("ins", x)] + history)
changed = sum(a != b for a, b in zip(outs, outs2))
gained = sorted((Counter(final2) - Counter(final)).elements())
lost = sorted((Counter(final) - Counter(final2)).elements())
print(f"insert {x:2} at time 0: {changed:2} of {len(outs)} delete-mins return something else; "
f"final contents gain {gained}, lose {lost}")insert 0 at time 0: 5 of 22 delete-mins return something else; final contents gain [62], lose []
insert 30 at time 0: 5 of 22 delete-mins return something else; final contents gain [62], lose []
insert 99 at time 0: 0 of 22 delete-mins return something else; final contents gain [99], lose []
That "only one element of the present changes" lemma is the heart of the partially retroactive priority queue: the element that joins the present can be found with a balanced search tree over the timeline that stores, for "bridges" (times when the current queue contains exactly the elements inserted before), the right minima and maxima, giving per retroactive operation.
Retroactivity and persistence
| Persistence | Retroactivity | |
|---|---|---|
| a change to the past | creates a new branch | rewrites every later state |
| the present | unaffected by old versions | reflects every retroactive change |
| typical cost | amortized overhead (node copying) | from (queue) to (in general) |
Test yourself
Which operations make partial retroactivity trivial?
- Any operations on a balanced tree
- Updates that commute and are invertible: a past insertion or deletion can then be applied at the present instead
- Only queries
- Operations on a priority queue
In the fully retroactive queue, what is the front at time ?
- The latest enqueue before
- The -th enqueue in time order, where is the number of dequeues up to time
- The enqueue closest to
- It requires replaying the history
What does the lower bound say?
- Every structure needs time per retroactive operation
- Some structures (e.g. one that evaluates a polynomial by Horner's rule) need time per retroactive operation in the algebraic model, so rollback cannot be beaten in general
- Queues need
- Retroactivity is impossible