Exercise 2: Submit, Leak, Submit More, Verify FIFO Order Throughout — Possible Solution ==================================================================== THE SEQUENCE ------------------------------ lb = LeakyBucket(capacity=10) first_10 = [lb.add_request(f'req-{i}') for i in range(10)] # fills the bucket exactly leaked_3 = [lb.leak() for _ in range(3)] # frees 3 slots next_8 = [lb.add_request(f'req-{i}') for i in range(10, 18)] # only 3 slots free RESULTS ------------------------------ first 10 submitted, all accepted: True | queue size: 10 leaked 3: ['req-0', 'req-1', 'req-2'] | queue size now: 7 next 8 submission results: [True, True, True, False, False, False, False, False] accepted: 3 | rejected: 5 queue size after: 10 (capped at capacity) VERIFYING THE CAPACITY LIMIT IS RESPECTED AT THE MOMENT OF SUBMISSION ------------------------------ After leaking 3, the queue had exactly 3 free slots (7 used out of a capacity of 10). Of the 8 newly-submitted requests, exactly the first 3 were accepted (filling the queue back to capacity 10), and the remaining 5 were correctly rejected - add_request() checks len(self.queue) >= self.capacity at the moment each individual request arrives, not against some earlier snapshot. VERIFYING FULL FIFO ORDER ACROSS BOTH SUBMISSION BATCHES ------------------------------ remaining leaked out, in order: ['req-3', 'req-4', 'req-5', 'req-6', 'req-7', 'req-8', 'req-9', 'req-10', 'req-11', 'req-12'] full leak order: ['req-0', 'req-1', 'req-2', 'req-3', ..., 'req-12'] matches expected FIFO order: True Leaking out everything remaining produced req-3 through req-9 (the rest of the FIRST batch, still queued in their original order) BEFORE req-10 through req-12 (the accepted portion of the SECOND batch) - exactly matching pure first-in-first-out order across the entire sequence, even though the two batches were submitted at genuinely different points with a leak() call in between. WHY THIS WORKS AS AN ANSWER ------------------------------ The sequence directly interleaves submission and leaking using this chapter's own LeakyBucket unmodified, the capacity check is verified firing correctly against the queue's actual current occupancy rather than a stale count, and the full leak order is checked end to end against the expected FIFO sequence rather than only spot-checked.