Coverage for src/python/ensembl/vep/runner/run/output_transaction.py: 83%
97 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Atomic output transactions for the default annotation runner."""
16from __future__ import annotations
18import logging
19import os
20import secrets
21import stat
22from pathlib import Path
24from attrs import define, field
26__all__ = ["OutputTransaction"]
28logger = logging.getLogger(__name__)
31def _temporary_sibling(destination: Path, suffix: str) -> Path:
32 """Create a unique sibling with normal output permissions."""
33 try:
34 destination_mode = stat.S_IMODE(destination.stat().st_mode)
35 except FileNotFoundError:
36 destination_mode = None
38 for _attempt in range(100): 38 ↛ 56line 38 didn't jump to line 56 because the loop on line 38 didn't complete
39 temporary = destination.with_name(f".{destination.name}.{secrets.token_hex(8)}.{suffix}")
40 try:
41 descriptor = os.open(
42 temporary,
43 os.O_WRONLY | os.O_CREAT | os.O_EXCL,
44 0o666,
45 )
46 except FileExistsError:
47 continue
48 os.close(descriptor)
49 if destination_mode is not None:
50 try:
51 temporary.chmod(destination_mode)
52 except BaseException:
53 temporary.unlink(missing_ok=True)
54 raise
55 return temporary
56 raise FileExistsError(f"could not create a temporary file beside {destination}")
59@define(kw_only=True, auto_attribs=True)
60class OutputTransaction:
61 """Atomic transaction for files produced by one run.
63 Attributes:
64 replace_existing (bool): Whether commit may replace existing destinations.
65 """
67 replace_existing: bool
68 _staged_files: list[tuple[Path, Path]] = field(factory=list, init=False)
70 def stage(self, destination: Path) -> Path:
71 """Create and track a temporary file beside ``destination``."""
72 temporary = _temporary_sibling(destination, "tmp")
73 self._staged_files.append((temporary, destination))
74 return temporary
76 def commit(self) -> None:
77 """Commit every staged file or restore the previous generation."""
78 if not self.replace_existing:
79 self._commit_new_files()
80 return
81 self._replace_files()
83 def cleanup(self) -> None:
84 """Remove temporary files that were not consumed by commit."""
85 for temporary, _destination in self._staged_files:
86 temporary.unlink(missing_ok=True)
88 def _commit_new_files(self) -> None:
89 """Commit files without replacing destinations created during the run."""
90 committed: list[Path] = []
91 try:
92 for temporary, destination in self._staged_files:
93 os.link(temporary, destination)
94 committed.append(destination)
95 except BaseException:
96 for destination in reversed(committed):
97 destination.unlink(missing_ok=True)
98 raise
100 def _replace_files(self) -> None:
101 """Replace destinations and restore all predecessors if any replacement fails."""
102 backups: dict[Path, Path] = {}
103 committed: set[Path] = set()
104 try:
105 for temporary, destination in self._staged_files:
106 if destination.exists():
107 backup = _temporary_sibling(destination, "backup")
108 try:
109 destination.replace(backup)
110 except BaseException:
111 backup.unlink(missing_ok=True)
112 raise
113 backups[destination] = backup
114 temporary.replace(destination)
115 committed.add(destination)
116 except BaseException as commit_failure:
117 try:
118 self._rollback(backups, committed)
119 except OSError as rollback_failure:
120 raise rollback_failure from commit_failure
121 raise
123 for backup in backups.values():
124 try:
125 backup.unlink(missing_ok=True)
126 except OSError as failure:
127 logger.warning("could not remove output transaction backup %s: %s", backup, failure)
129 def _rollback(self, backups: dict[Path, Path], committed: set[Path]) -> None:
130 """Restore destinations changed by an incomplete commit."""
131 failures: list[OSError] = []
132 for _temporary, destination in reversed(self._staged_files):
133 if destination in committed:
134 try:
135 destination.unlink(missing_ok=True)
136 except OSError as failure:
137 failures.append(failure)
138 backup = backups.get(destination)
139 if backup is not None: 139 ↛ 132line 139 didn't jump to line 132 because the condition on line 139 was always true
140 try:
141 backup.replace(destination)
142 except OSError as failure:
143 failures.append(failure)
144 if failures: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true
145 raise OSError(f"could not restore output transaction: {failures[0]}")