"""Mechanism tests complement the real HTTP + measured SQL experiment.""" import sys, time, unittest from concurrent.futures import ThreadPoolExecutor from pathlib import Path from threading import Barrier, Event, Lock from unittest.mock import patch sys.path.insert(0, '/app') from src import cache class SingleFlightTests(unittest.TestCase): def tearDown(self): self.assertEqual(cache.flights, {}) def test_same_user_one_load(self): barrier=Barrier(16); calls=[] def load(): calls.append(1); time.sleep(.1); return {'public':'data'} def call(_): barrier.wait(); return cache.profile('same',load) with patch.object(cache,'_profile',side_effect=lambda uid,load:load()): with ThreadPoolExecutor(16) as pool: results=list(pool.map(call,range(16))) self.assertEqual(len(calls),1);self.assertEqual(results,[{'public':'data'}]*16) def test_different_users_do_not_serialize(self): barrier=Barrier(2) def load(): barrier.wait(timeout=1);return 'public' with patch.object(cache,'_profile',side_effect=lambda uid,load:load()): with ThreadPoolExecutor(2) as pool: results=list(pool.map(lambda uid:cache.profile(uid,load),['a','b'])) self.assertEqual(results,['public','public']) def test_leader_exception_wakes_waiters_and_retry(self): started=Event();release=Event() def load(): started.set();release.wait(2);raise ValueError('synthetic') with patch.object(cache,'_profile',side_effect=lambda uid,load:load()): with ThreadPoolExecutor(8) as pool: leader=pool.submit(cache.profile,'a',load);self.assertTrue(started.wait(1)) followers=[pool.submit(cache.profile,'a',load) for _ in range(7)] time.sleep(.05);release.set() for f in [leader,*followers]: with self.assertRaises(ValueError):f.result(timeout=1) self.assertEqual(cache.profile('a',lambda:'recovered'),'recovered') def test_wait_timeout_fallback_does_not_replace_leader(self): started=Event();release=Event() def leader_load():started.set();release.wait(2);return 'leader' with patch.object(cache,'_profile',side_effect=lambda uid,load:load()),patch.object(cache,'FLIGHT_WAIT',.05): with ThreadPoolExecutor(2) as pool: leader=pool.submit(cache.profile,'a',leader_load);self.assertTrue(started.wait(1)) t=time.monotonic();self.assertEqual(cache.profile('a',lambda:'fallback'),'fallback') self.assertLess(time.monotonic()-t,.5);self.assertIn('a',cache.flights) release.set();self.assertEqual(leader.result(timeout=1),'leader') def test_registry_limit_direct_fallback(self): with patch.object(cache,'FLIGHT_LIMIT',0),patch.object(cache,'_profile',side_effect=AssertionError): self.assertEqual(cache.profile('a',lambda:'direct'),'direct') if __name__=='__main__':unittest.main(verbosity=2)