Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flock() Cache Construction - Prevent NFS/SQLite Errors #87

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions outlines/caching.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import contextlib
import fcntl
import functools
import os
from typing import Callable, Optional
Expand All @@ -11,6 +12,21 @@
_caching_enabled = True


class FileLock:
def __init__(self, lock_path):
lock_dir = os.path.dirname(lock_path)
os.makedirs(lock_dir, exist_ok=True)
self.lock_file = open(lock_path, "a+")

def __enter__(self):
fcntl.flock(self.lock_file, fcntl.LOCK_EX)
return self.lock_file

def __exit__(self, *args):
fcntl.flock(self.lock_file, fcntl.LOCK_UN)
self.lock_file.close()


class CloudpickleDisk(Disk):
def __init__(self, directory, compress_level=1, **kwargs):
self.compress_level = compress_level
Expand Down Expand Up @@ -52,12 +68,13 @@ def get_cache():

home_dir = os.path.expanduser("~")
cache_dir = os.environ.get("OUTLINES_CACHE_DIR", f"{home_dir}/.cache/outlines")
memory = Cache(
cache_dir,
eviction_policy="none",
cull_limit=0,
disk=CloudpickleDisk,
)
with FileLock(os.path.join(cache_dir, "outlines_cache.lock")):
memory = Cache(
cache_dir,
eviction_policy="none",
cull_limit=0,
disk=CloudpickleDisk,
)

# ensure if version upgrade occurs, old cache is pruned
if outlines_version != memory.get("__version__"):
Expand Down
Loading