Debian Codegraph @

tests/integration/multithread_read.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Multithreaded file reader for cache system integration testing.
3
4 Reads a file from multiple threads simultaneously, each thread reading
5 different byte ranges. Verifies each range against expected SHA-256 checksums
6 computed from the original file content.
7
8 Usage:
9 python3 multithread_read.py <filepath> <expected_sha256> <num_threads>
10
11 Exit code 0 on success, 1 on verification failure.
12 """
13
14 import hashlib
15 import os
16 import sys
17 import threading
18
19
20 def read_range(filepath, start, length, results, index):
21 """Read a byte range from the file and store it in results."""
22 try:
23 with open(filepath, "rb") as f:
24 f.seek(start)
25 data = f.read(length)
26 results[index] = data
27 except Exception as e:
28 results[index] = e
29
30
31 def main():
32 if len(sys.argv) != 4:
33 print(f"Usage: {sys.argv[0]} <filepath> <expected_sha256>"
34 f" <num_threads>",
35 file=sys.stderr)
36 sys.exit(1)
37
38 filepath = sys.argv[1]
39 expected_sha256 = sys.argv[2]
40 num_threads = int(sys.argv[3])
41
42 file_size = os.path.getsize(filepath)
43 chunk_size = file_size // num_threads
44 remainder = file_size % num_threads
45
46 print(f" File: {os.path.basename(filepath)}")
47 print(f" Size: {file_size} bytes ({file_size / (1024*1024):.1f} MB)")
48 print(f" Threads: {num_threads}")
49 print(f" Chunk size: {chunk_size} bytes")
50
51 # Launch threads to read different ranges
52 threads = []
53 results = [None] * num_threads
54
55 offset = 0
56 for i in range(num_threads):
57 # Last thread gets any remainder bytes
58 length = chunk_size + (remainder if i == num_threads - 1 else 0)
59 t = threading.Thread(
60 target=read_range,
61 args=(filepath, offset, length, results, i),
62 )
63 threads.append(t)
64 offset += length
65
66 # Start all threads simultaneously
67 for t in threads:
68 t.start()
69
70 # Wait for all to complete
71 for t in threads:
72 t.join()
73
74 # Check for errors
75 for i, result in enumerate(results):
76 if isinstance(result, Exception):
77 print(f" ERROR: Thread {i} failed: {result}", file=sys.stderr)
78 sys.exit(1)
79 if result is None:
80 print(f" ERROR: Thread {i} returned no data", file=sys.stderr)
81 sys.exit(1)
82
83 # Reassemble and verify
84 hasher = hashlib.sha256()
85 for chunk in results:
86 hasher.update(chunk)
87 actual_sha256 = hasher.hexdigest()
88
89 if actual_sha256 == expected_sha256:
90 print(f" SHA-256 OK: {actual_sha256}")
91 sys.exit(0)
92 else:
93 print(f" SHA-256 MISMATCH!", file=sys.stderr)
94 print(f" Expected: {expected_sha256}", file=sys.stderr)
95 print(f" Actual: {actual_sha256}", file=sys.stderr)
96 sys.exit(1)
97
98
99 if __name__ == "__main__":
100 main()