Coverage for little_loops / fsm / concurrency.py: 99%

118 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""Scope-based concurrency control for FSM loops. 

2 

3Prevents concurrent loops from conflicting when operating on 

4the same files or directories through file-based locking. 

5 

6Public exports: 

7 ScopeLock: Dataclass representing a scope lock 

8 LockManager: Manager for acquiring/releasing scope locks 

9""" 

10 

11from __future__ import annotations 

12 

13import errno 

14import fcntl 

15import json 

16import os 

17import time 

18from dataclasses import dataclass 

19from datetime import UTC, datetime 

20from pathlib import Path 

21from typing import Any 

22 

23RUNNING_DIR = ".running" 

24 

25 

26def _iso_now() -> str: 

27 """Return current time as ISO8601 string.""" 

28 return datetime.now(UTC).isoformat() 

29 

30 

31@dataclass 

32class ScopeLock: 

33 """Represents a lock on a set of paths for a running loop. 

34 

35 Attributes: 

36 loop_name: Name of the loop holding the lock 

37 scope: List of paths this loop operates on 

38 pid: Process ID of the lock holder 

39 started_at: ISO timestamp when lock was acquired 

40 """ 

41 

42 loop_name: str 

43 scope: list[str] 

44 pid: int 

45 started_at: str 

46 

47 def to_dict(self) -> dict[str, Any]: 

48 """Convert to dictionary for JSON serialization.""" 

49 return { 

50 "loop_name": self.loop_name, 

51 "scope": self.scope, 

52 "pid": self.pid, 

53 "started_at": self.started_at, 

54 } 

55 

56 @classmethod 

57 def from_dict(cls, data: dict[str, Any]) -> ScopeLock: 

58 """Create from dictionary (JSON deserialization).""" 

59 return cls( 

60 loop_name=str(data["loop_name"]), 

61 scope=list(data["scope"]) if isinstance(data["scope"], list) else [str(data["scope"])], 

62 pid=int(data["pid"]), 

63 started_at=str(data["started_at"]), 

64 ) 

65 

66 

67class LockManager: 

68 """Manage scope-based locks for concurrent loop execution. 

69 

70 Lock files are stored in .loops/.running/<name>.lock 

71 and contain JSON with ScopeLock data. 

72 """ 

73 

74 def __init__(self, loops_dir: Path | None = None) -> None: 

75 """Initialize the lock manager. 

76 

77 Args: 

78 loops_dir: Base directory for loops (default: .loops) 

79 """ 

80 self.loops_dir = loops_dir or Path(".loops") 

81 self.running_dir = self.loops_dir / RUNNING_DIR 

82 

83 def acquire(self, loop_name: str, scope: list[str]) -> bool: 

84 """Attempt to acquire lock for the given scope. 

85 

86 Args: 

87 loop_name: Name of the loop to acquire lock for 

88 scope: List of paths the loop operates on 

89 

90 Returns: 

91 True if lock acquired, False if conflict exists 

92 """ 

93 # Normalize scope - empty means whole project 

94 if not scope: 

95 scope = ["."] 

96 scope = [self._normalize_path(p) for p in scope] 

97 

98 # Ensure running directory exists before opening sentinel lock 

99 self.running_dir.mkdir(parents=True, exist_ok=True) 

100 

101 # Serialize the check-and-create sequence across processes using a 

102 # sentinel file. This eliminates the TOCTOU window between 

103 # find_conflict() (read) and lock-file creation (write). 

104 # .acquire.lock is a dotfile so Path.glob("*.lock") will not match it 

105 # and stale-lock cleanup in find_conflict/list_locks ignores it. 

106 dir_lock_path = self.running_dir / ".acquire.lock" 

107 with open(dir_lock_path, "w") as dir_lock: 

108 fcntl.flock(dir_lock, fcntl.LOCK_EX) 

109 

110 # Check for conflicts (now atomic with write below) 

111 conflict = self.find_conflict(scope) 

112 if conflict: 

113 return False 

114 

115 # Create lock file 

116 lock_file = self.running_dir / f"{loop_name}.lock" 

117 lock = ScopeLock( 

118 loop_name=loop_name, 

119 scope=scope, 

120 pid=os.getpid(), 

121 started_at=_iso_now(), 

122 ) 

123 with open(lock_file, "w") as f: 

124 json.dump(lock.to_dict(), f) 

125 

126 return True 

127 

128 def release(self, loop_name: str) -> None: 

129 """Release lock for a loop. 

130 

131 Args: 

132 loop_name: Name of the loop to release lock for 

133 """ 

134 lock_file = self.running_dir / f"{loop_name}.lock" 

135 lock_file.unlink(missing_ok=True) 

136 

137 def find_conflict(self, scope: list[str]) -> ScopeLock | None: 

138 """Find any running loop with overlapping scope. 

139 

140 Also cleans up stale locks from dead processes. 

141 

142 Args: 

143 scope: Scope to check for conflicts 

144 

145 Returns: 

146 ScopeLock of conflicting loop, or None if no conflict 

147 """ 

148 if not self.running_dir.exists(): 

149 return None 

150 

151 for lock_file in self.running_dir.glob("*.lock"): 

152 try: 

153 with open(lock_file) as f: 

154 data = json.load(f) 

155 lock = ScopeLock.from_dict(data) 

156 

157 # Check if process is still alive 

158 if not self._process_alive(lock.pid): 

159 # Stale lock, remove it 

160 lock_file.unlink(missing_ok=True) 

161 continue 

162 

163 # Check for overlap 

164 if self._scopes_overlap(scope, lock.scope): 

165 return lock 

166 

167 except (json.JSONDecodeError, KeyError, FileNotFoundError): 

168 # Malformed or deleted lock file, skip 

169 continue 

170 

171 return None 

172 

173 def list_locks(self) -> list[ScopeLock]: 

174 """List all active locks. 

175 

176 Cleans up stale locks as a side effect. 

177 

178 Returns: 

179 List of active ScopeLock objects 

180 """ 

181 locks: list[ScopeLock] = [] 

182 if not self.running_dir.exists(): 

183 return locks 

184 

185 for lock_file in self.running_dir.glob("*.lock"): 

186 try: 

187 with open(lock_file) as f: 

188 data = json.load(f) 

189 lock = ScopeLock.from_dict(data) 

190 

191 if self._process_alive(lock.pid): 

192 locks.append(lock) 

193 else: 

194 # Stale lock, remove it 

195 lock_file.unlink(missing_ok=True) 

196 except (json.JSONDecodeError, KeyError, FileNotFoundError): 

197 continue 

198 

199 return locks 

200 

201 def wait_for_scope(self, scope: list[str], timeout: int = 300) -> bool: 

202 """Wait until scope is available. 

203 

204 Args: 

205 scope: Scope to wait for 

206 timeout: Maximum time to wait in seconds 

207 

208 Returns: 

209 True if scope became available, False if timeout 

210 """ 

211 start = time.time() 

212 while time.time() - start < timeout: 

213 conflict = self.find_conflict(scope) 

214 if conflict is None: 

215 return True 

216 time.sleep(1) 

217 

218 return False 

219 

220 def _scopes_overlap(self, scope1: list[str], scope2: list[str]) -> bool: 

221 """Check if two scopes have any overlapping paths.""" 

222 for p1 in scope1: 

223 for p2 in scope2: 

224 if self._paths_overlap(p1, p2): 

225 return True 

226 return False 

227 

228 def _paths_overlap(self, path1: str, path2: str) -> bool: 

229 """Check if two paths overlap (same, or one contains the other).""" 

230 p1 = Path(path1).resolve() 

231 p2 = Path(path2).resolve() 

232 

233 # Same path 

234 if p1 == p2: 

235 return True 

236 

237 # One is parent of other 

238 try: 

239 p1.relative_to(p2) 

240 return True 

241 except ValueError: 

242 pass 

243 

244 try: 

245 p2.relative_to(p1) 

246 return True 

247 except ValueError: 

248 pass 

249 

250 return False 

251 

252 def _normalize_path(self, path: str) -> str: 

253 """Normalize path for consistent comparison.""" 

254 return str(Path(path).resolve()) 

255 

256 def _process_alive(self, pid: int) -> bool: 

257 """Check if process is still running.""" 

258 try: 

259 os.kill(pid, 0) 

260 return True 

261 except OSError as e: 

262 if e.errno == errno.ESRCH: 

263 return False # No such process 

264 return True # EPERM or other: process exists, no permission