Coverage for fastblocks / actions / sync / strategies.py: 35%

181 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Sync strategies for handling synchronization operations with conflict resolution.""" 

2 

3import asyncio 

4import typing as t 

5from enum import Enum 

6from pathlib import Path 

7 

8from oneiric.core.resolution import Resolver 

9 

10# Migration from ACB to Oneiric 

11depends = Resolver() 

12 

13# ACB compatibility imports - these will be migrated in future phases 

14try: 

15 # MIGRATED: Removed ACB import - debug import debug 

16 pass 

17except ImportError: 

18 # Fallback for Oneiric-only mode 

19 def debug(msg: str) -> None: 

20 """Debug function fallback.""" 

21 print(f"[DEBUG] {msg}") 

22 

23 

24class SyncDirection(Enum): 

25 PULL = "pull" 

26 PUSH = "push" 

27 BIDIRECTIONAL = "bidirectional" 

28 

29 

30class ConflictStrategy(Enum): 

31 REMOTE_WINS = "remote_wins" 

32 LOCAL_WINS = "local_wins" 

33 NEWEST_WINS = "newest_wins" 

34 MANUAL = "manual" 

35 BACKUP_BOTH = "backup_both" 

36 

37 

38class SyncStrategy: 

39 def __init__( 

40 self, 

41 *, 

42 direction: SyncDirection = SyncDirection.BIDIRECTIONAL, 

43 conflict_strategy: ConflictStrategy = ConflictStrategy.NEWEST_WINS, 

44 dry_run: bool = False, 

45 backup_on_conflict: bool = True, 

46 parallel: bool = True, 

47 max_concurrent: int = 5, 

48 timeout: float = 30.0, 

49 retry_attempts: int = 2, 

50 retry_delay: float = 0.5, 

51 ) -> None: 

52 self.direction = direction 

53 self.conflict_strategy = conflict_strategy 

54 self.dry_run = dry_run 

55 self.backup_on_conflict = backup_on_conflict 

56 self.parallel = parallel 

57 self.max_concurrent = max_concurrent 

58 self.timeout = timeout 

59 self.retry_attempts = retry_attempts 

60 self.retry_delay = retry_delay 

61 

62 

63class SyncResult: 

64 def __init__( 

65 self, 

66 *, 

67 synced_items: list[str] | None = None, 

68 conflicts: list[dict[str, t.Any]] | None = None, 

69 errors: list[Exception] | None = None, 

70 skipped: list[str] | None = None, 

71 backed_up: list[str] | None = None, 

72 ) -> None: 

73 self.synced_items = synced_items if synced_items is not None else [] 

74 self.conflicts = conflicts if conflicts is not None else [] 

75 self.errors = errors if errors is not None else [] 

76 self.skipped = skipped if skipped is not None else [] 

77 self.backed_up = backed_up if backed_up is not None else [] 

78 

79 @property 

80 def total_processed(self) -> int: 

81 return ( 

82 len(self.synced_items) 

83 + len(self.conflicts) 

84 + len(self.errors) 

85 + len(self.skipped) 

86 ) 

87 

88 @property 

89 def success_count(self) -> int: 

90 return len(self.synced_items) 

91 

92 @property 

93 def has_conflicts(self) -> bool: 

94 return len(self.conflicts) > 0 

95 

96 @property 

97 def has_errors(self) -> bool: 

98 return len(self.errors) > 0 

99 

100 @property 

101 def is_success(self) -> bool: 

102 return not self.has_errors and not self.has_conflicts 

103 

104 

105async def sync_with_strategy( 

106 sync_tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

107 strategy: SyncStrategy, 

108) -> SyncResult: 

109 result = SyncResult() 

110 

111 if strategy.parallel and len(sync_tasks) > 1: 

112 await _execute_parallel_sync(sync_tasks, strategy, result) 

113 else: 

114 await _execute_sequential_sync(sync_tasks, strategy, result) 

115 

116 debug( 

117 f"Sync completed: {result.success_count} synced, {len(result.conflicts)} conflicts, {len(result.errors)} errors", 

118 ) 

119 

120 return result 

121 

122 

123async def _execute_parallel_sync( 

124 sync_tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

125 strategy: SyncStrategy, 

126 result: SyncResult, 

127) -> None: 

128 semaphore = asyncio.Semaphore(strategy.max_concurrent) 

129 

130 async def execute_with_semaphore( 

131 task: t.Coroutine[t.Any, t.Any, t.Any], 

132 ) -> t.Any: 

133 async with semaphore: 

134 return await _execute_with_retry(task, strategy) 

135 

136 try: 

137 results = await asyncio.wait_for( 

138 asyncio.gather( 

139 *[execute_with_semaphore(task) for task in sync_tasks], 

140 return_exceptions=True, 

141 ), 

142 timeout=strategy.timeout, 

143 ) 

144 

145 _process_parallel_results(results, result) 

146 

147 except TimeoutError as e: 

148 result.errors.append(e) 

149 debug(f"Sync timeout after {strategy.timeout}s") 

150 

151 

152def _process_parallel_results(results: list[t.Any], result: SyncResult) -> None: 

153 for task_result in results: 

154 if isinstance(task_result, Exception): 

155 result.errors.append(task_result) 

156 elif isinstance(task_result, dict): 

157 _merge_sync_result(result, task_result) 

158 

159 

160async def _execute_sequential_sync( 

161 sync_tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

162 strategy: SyncStrategy, 

163 result: SyncResult, 

164) -> None: 

165 for task in sync_tasks: 

166 try: 

167 task_result = await asyncio.wait_for( 

168 _execute_with_retry(task, strategy), 

169 timeout=strategy.timeout, 

170 ) 

171 

172 if isinstance(task_result, dict): 

173 _merge_sync_result(result, task_result) 

174 

175 except Exception as e: 

176 result.errors.append(e) 

177 debug(f"Sync task failed: {e}") 

178 

179 

180async def _execute_with_retry( 

181 task: t.Coroutine[t.Any, t.Any, t.Any], 

182 strategy: SyncStrategy, 

183) -> t.Any: 

184 for attempt in range(strategy.retry_attempts + 1): 

185 try: 

186 return await task 

187 except Exception as e: 

188 if attempt == strategy.retry_attempts: 

189 raise 

190 

191 debug(f"Sync retry attempt {attempt + 1} after error: {e}") 

192 await asyncio.sleep(strategy.retry_delay * (attempt + 1)) 

193 

194 msg = "Should not reach here" 

195 raise RuntimeError(msg) 

196 

197 

198def _merge_sync_result(main_result: SyncResult, task_result: dict[str, t.Any]) -> None: 

199 main_result.synced_items.extend(task_result.get("synced", [])) 

200 main_result.conflicts.extend(task_result.get("conflicts", [])) 

201 main_result.errors.extend(task_result.get("errors", [])) 

202 main_result.skipped.extend(task_result.get("skipped", [])) 

203 main_result.backed_up.extend(task_result.get("backed_up", [])) 

204 

205 

206async def resolve_conflict( 

207 local_path: Path, 

208 remote_content: bytes, 

209 local_content: bytes, 

210 strategy: ConflictStrategy, 

211 local_mtime: float | None = None, 

212 remote_mtime: float | None = None, 

213) -> tuple[bytes, str]: 

214 if strategy == ConflictStrategy.REMOTE_WINS: 

215 return remote_content, "remote_wins" 

216 

217 if strategy == ConflictStrategy.LOCAL_WINS: 

218 return local_content, "local_wins" 

219 

220 if strategy == ConflictStrategy.NEWEST_WINS: 

221 if local_mtime and remote_mtime: 

222 if remote_mtime > local_mtime: 

223 return remote_content, f"remote_newer({remote_mtime} > {local_mtime})" 

224 return local_content, f"local_newer({local_mtime} >= {remote_mtime})" 

225 return remote_content, "newest_wins_fallback_remote" 

226 

227 if strategy == ConflictStrategy.BACKUP_BOTH: 

228 return remote_content, "backup_both" 

229 

230 if strategy == ConflictStrategy.MANUAL: 

231 msg = f"Manual conflict resolution required for {local_path}" 

232 raise ValueError(msg) 

233 

234 msg = f"Unknown conflict strategy: {strategy}" 

235 raise ValueError(msg) 

236 

237 

238async def create_backup(file_path: Path, suffix: str | None = None) -> Path: 

239 if suffix is None: 

240 import time 

241 

242 timestamp = int(time.time()) 

243 suffix = f"backup_{timestamp}" 

244 backup_path = file_path.with_suffix(f"{file_path.suffix}.{suffix}") 

245 try: 

246 if file_path.exists(): 

247 import shutil 

248 

249 shutil.copy2(file_path, backup_path) 

250 debug(f"Created backup: {backup_path}") 

251 

252 return backup_path 

253 except Exception as e: 

254 debug(f"Error creating backup for {file_path}: {e}") 

255 raise 

256 

257 

258def compare_content( 

259 content1: bytes, 

260 content2: bytes, 

261 use_hash: bool = True, 

262) -> bool: 

263 if len(content1) != len(content2): 

264 return False 

265 

266 if use_hash and len(content1) > 1024: 

267 import hashlib 

268 

269 hash1 = hashlib.blake2b(content1).hexdigest() 

270 hash2 = hashlib.blake2b(content2).hexdigest() 

271 return hash1 == hash2 

272 

273 return content1 == content2 

274 

275 

276async def get_file_info(file_path: Path) -> dict[str, t.Any]: 

277 try: 

278 if not file_path.exists(): 

279 return { 

280 "exists": False, 

281 "size": 0, 

282 "mtime": 0, 

283 "content_hash": None, 

284 } 

285 stat = file_path.stat() 

286 content = file_path.read_bytes() 

287 import hashlib 

288 

289 content_hash = hashlib.blake2b(content).hexdigest() 

290 

291 return { 

292 "exists": True, 

293 "size": stat.st_size, 

294 "mtime": stat.st_mtime, 

295 "content_hash": content_hash, 

296 "content": content, 

297 } 

298 except Exception as e: 

299 debug(f"Error getting file info for {file_path}: {e}") 

300 return { 

301 "exists": False, 

302 "size": 0, 

303 "mtime": 0, 

304 "content_hash": None, 

305 "error": str(e), 

306 } 

307 

308 

309def should_sync( 

310 local_info: dict[str, t.Any], 

311 remote_info: dict[str, t.Any], 

312 direction: SyncDirection, 

313) -> tuple[bool, str]: 

314 local_exists = local_info["exists"] 

315 remote_exists = remote_info["exists"] 

316 

317 if missing_result := _check_missing_files(local_exists, remote_exists, direction): 

318 return missing_result 

319 

320 if local_exists and remote_exists: 

321 return _check_content_differences(local_info, remote_info, direction) 

322 

323 return False, "content_identical" 

324 

325 

326def _check_missing_files( 

327 local_exists: bool, 

328 remote_exists: bool, 

329 direction: SyncDirection, 

330) -> tuple[bool, str] | None: 

331 if not local_exists and remote_exists: 

332 if direction in (SyncDirection.PULL, SyncDirection.BIDIRECTIONAL): 

333 return True, "local_missing" 

334 

335 if local_exists and not remote_exists: 

336 if direction in (SyncDirection.PUSH, SyncDirection.BIDIRECTIONAL): 

337 return True, "remote_missing" 

338 

339 if not local_exists and not remote_exists: 

340 return False, "both_missing" 

341 

342 return None 

343 

344 

345def _check_content_differences( 

346 local_info: dict[str, t.Any], 

347 remote_info: dict[str, t.Any], 

348 direction: SyncDirection, 

349) -> tuple[bool, str]: 

350 if local_info["content_hash"] == remote_info["content_hash"]: 

351 return False, "content_identical" 

352 

353 direction_reasons = { 

354 SyncDirection.PULL: "content_differs_pull", 

355 SyncDirection.PUSH: "content_differs_push", 

356 SyncDirection.BIDIRECTIONAL: "content_differs_bidirectional", 

357 } 

358 

359 return True, direction_reasons.get(direction, "content_differs") 

360 

361 

362def get_sync_summary(result: SyncResult) -> dict[str, t.Any]: 

363 return { 

364 "total_processed": result.total_processed, 

365 "synced": result.success_count, 

366 "conflicts": len(result.conflicts), 

367 "errors": len(result.errors), 

368 "skipped": len(result.skipped), 

369 "backed_up": len(result.backed_up), 

370 "success_rate": result.success_count / max(result.total_processed, 1), 

371 "has_conflicts": result.has_conflicts, 

372 "has_errors": result.has_errors, 

373 "is_success": result.is_success, 

374 } 

375 

376 

377# Migration status indicator 

378# Note: Partial migration - ACB debug system still in use 

379_using_oneiric = True # Oneiric resolver available 

380_requires_further_migration = True # ACB debug system needs migration