LittlePlyResearch notebook

mate_cpu_pool.py

python · 30 lines · Exact bytes

Line 1 ↗
Version & provenance · evaluation-cm7

Recorded SHA-256 32acb7c61301bd0d3b714d63bf9739dd76531359ab45a7773f726561f6e1858cRendered SHA-256 32acb7c61301bd0d3b714d63bf9739dd76531359ab45a7773f726561f6e1858c

Apache-2.0 original project code; dependencies retain their own licenses. License notes. Line links are stable within this snapshot. CM-7 completed implementation source; original and public rendered hashes recorded. Host-specific paths use /work placeholders; inspect reproduction instructions before running. Separate Rust helper retains its GPL license.

1"""Eight advisory CPU slots shared by all same-user helper calls on this host."""
2import os,fcntl,stat,tempfile
3from pathlib import Path
4POOL_SIZE=8
5
6def acquire(requested):
7    root=Path('/dev/shm')/('littleply-mate-cpu-v1-'+str(os.getuid()))
8    try:root.mkdir(mode=0o700)
9    except FileExistsError:pass
10    info=root.lstat()
11    if not stat.S_ISDIR(info.st_mode) or info.st_uid!=os.getuid() or info.st_mode&0o077:raise OSError('unsafe helper slot directory')
12    directory=os.open(root,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW);fds=[]
13    try:
14        for index in range(POOL_SIZE):
15            fd=os.open(str(index),os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=directory)
16            try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
17            except BlockingIOError:os.close(fd);continue
18            except BaseException:os.close(fd);raise
19            fds.append(fd)
20            if len(fds)==requested:break
21        return fds
22    except BaseException:
23        release(fds);raise
24    finally:os.close(directory)
25
26def release(fds):
27    # No explicit LOCK_UN: inherited descriptors keep the slot locked if the
28    # Python parent dies while its bounded native child is still exiting.
29    for fd in fds:os.close(fd)
30