Skip to content

Commit e45abbf

Browse files
Andrey Cheptsovclaude
andcommitted
Drop redundant pool lock in JobServerConnectionsPool
_get_lock and remove_all only run await-free expressions, so the extra lock adds nothing under the single-threaded event loop. Make _get_lock synchronous and drop the lock. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 93d455d commit e45abbf

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

src/dstack/_internal/server/services/jobs/server_connection.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,13 @@ def __init__(self) -> None:
157157
self._connections: dict[uuid.UUID, JobServerConnection] = {}
158158
self._failure_started_at: dict[uuid.UUID, float] = {}
159159
self._locks: WeakValueDictionary[uuid.UUID, asyncio.Lock] = WeakValueDictionary()
160-
self._pool_lock = asyncio.Lock()
161160

162161
async def ensure(
163162
self,
164163
job: JobModel,
165164
job_runtime_data: Optional[JobRuntimeData],
166165
) -> bool:
167-
lock = await self._get_lock(job.id)
166+
lock = self._get_lock(job.id)
168167
async with lock:
169168
connection = self._connections.get(job.id)
170169
if connection is not None and await connection.is_alive():
@@ -193,7 +192,7 @@ def retry_timed_out(self, job_id: uuid.UUID, timeout: float) -> bool:
193192
return time.monotonic() - failure_started_at > timeout
194193

195194
async def remove(self, job_id: uuid.UUID) -> None:
196-
lock = await self._get_lock(job_id)
195+
lock = self._get_lock(job_id)
197196
async with lock:
198197
connection = self._connections.pop(job_id, None)
199198
if connection is not None:
@@ -202,13 +201,12 @@ async def remove(self, job_id: uuid.UUID) -> None:
202201
shutil.rmtree(CONNECTIONS_DIR / str(job_id), ignore_errors=True)
203202

204203
async def remove_all(self) -> None:
205-
async with self._pool_lock:
206-
job_ids = set(self._connections).union(self._failure_started_at)
204+
job_ids = set(self._connections).union(self._failure_started_at)
207205
await asyncio.gather(*(self.remove(job_id) for job_id in job_ids))
208206

209-
async def _get_lock(self, job_id: uuid.UUID) -> asyncio.Lock:
210-
async with self._pool_lock:
211-
return self._locks.setdefault(job_id, asyncio.Lock())
207+
def _get_lock(self, job_id: uuid.UUID) -> asyncio.Lock:
208+
# setdefault is atomic under the single-threaded event loop, so no extra lock is needed
209+
return self._locks.setdefault(job_id, asyncio.Lock())
212210

213211
@staticmethod
214212
async def _close(connection: JobServerConnection) -> None:

0 commit comments

Comments
 (0)