Spaces:
Running
Running
add chmod
Browse files- infrastructure/database.py +42 -37
infrastructure/database.py
CHANGED
|
@@ -25,7 +25,7 @@ def _setup_cache_dir():
|
|
| 25 |
"""Set up a writable cache directory for ChromaDB with fallbacks."""
|
| 26 |
cache_candidates = [
|
| 27 |
"/data/chroma_cache",
|
| 28 |
-
"/
|
| 29 |
"/tmp/.cache/chroma"
|
| 30 |
]
|
| 31 |
|
|
@@ -70,67 +70,74 @@ def _init_chroma_client():
|
|
| 70 |
"""
|
| 71 |
import time
|
| 72 |
import chromadb # local import so we can still return memory client last
|
|
|
|
| 73 |
|
| 74 |
# Allow a force-tmp override (e.g. CHROMA_FORCE_TMP=1)
|
| 75 |
force_tmp = os.getenv("CHROMA_FORCE_TMP") in {"1", "true", "yes", "on"}
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
| 79 |
if force_tmp:
|
| 80 |
-
candidates = ["/
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def _dir_writeable(path: str) -> bool:
|
| 86 |
try:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
with open(test_file, "x", encoding="utf-8") as tf:
|
| 90 |
tf.write("ok")
|
| 91 |
-
_logger.error(f"Directory {path} is writable.")
|
| 92 |
os.remove(test_file)
|
| 93 |
return True
|
| 94 |
except Exception as e: # pragma: no cover - env specific
|
| 95 |
-
_logger.error(f"Directory {path} not writable: {e}")
|
| 96 |
tried.append((path, f"dir not writable: {e}"))
|
| 97 |
return False
|
| 98 |
|
| 99 |
for cand in candidates:
|
| 100 |
-
if cand is None:
|
| 101 |
-
_logger.error("ChromaDB falling back to in-memory client (no persistence).")
|
| 102 |
-
return chromadb.PersistentClient() # type: ignore
|
| 103 |
-
|
| 104 |
abs_path = os.path.abspath(cand)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
if not _dir_writeable(abs_path):
|
|
|
|
| 109 |
continue
|
| 110 |
|
|
|
|
|
|
|
|
|
|
| 111 |
# Attempt to (re)chmod existing sqlite/duckdb files if present but not writable
|
| 112 |
try:
|
| 113 |
for fname in os.listdir(abs_path):
|
| 114 |
if any(fname.endswith(ext) for ext in (".sqlite3", ".db", ".duckdb")):
|
| 115 |
fpath = os.path.join(abs_path, fname)
|
| 116 |
-
_logger.error(f"Found existing DB file: {fpath}")
|
| 117 |
if not os.access(fpath, os.W_OK):
|
| 118 |
try:
|
| 119 |
-
os.chmod(
|
| 120 |
-
_logger.error(f"Set DB file to 666: {fpath}")
|
| 121 |
except Exception:
|
| 122 |
-
_logger.error(f"Failed to set DB file permissions: {fpath}")
|
| 123 |
pass
|
| 124 |
except Exception:
|
| 125 |
pass
|
| 126 |
|
| 127 |
-
_logger.error(f"Initializing Chroma PersistentClient at {abs_path}")
|
| 128 |
try:
|
| 129 |
-
|
| 130 |
-
client = chromadb.PersistentClient(path=os.environ["PERSIST_DIRECTORY"])
|
| 131 |
except Exception as e: # immediate failure
|
| 132 |
tried.append((abs_path, f"create failed: {e}"))
|
| 133 |
-
_logger.error(f"Chroma path {abs_path} not
|
| 134 |
continue
|
| 135 |
|
| 136 |
# Basic list works?
|
|
@@ -144,15 +151,12 @@ def _init_chroma_client():
|
|
| 144 |
test_coll_name = f"rw_test_{int(time.time()*10)}"
|
| 145 |
try:
|
| 146 |
tc = client.get_or_create_collection(name=test_coll_name) # type: ignore
|
| 147 |
-
_logger.error(f"Successfully created test collection {test_coll_name} at {abs_path}")
|
| 148 |
tc.add(ids=["0"], metadatas=[{"t": "x"}], documents=["test"])
|
| 149 |
-
_logger.error(f"Successfully added to test collection {test_coll_name} at {abs_path}")
|
| 150 |
client.delete_collection(name=test_coll_name)
|
| 151 |
-
_logger.error(f"
|
| 152 |
return client
|
| 153 |
except Exception as e:
|
| 154 |
msg = str(e).lower()
|
| 155 |
-
_logger.error(f"DB write test failed at {abs_path}: {e}")
|
| 156 |
tried.append((abs_path, f"write test failed: {e}"))
|
| 157 |
# Clean up partial collection if it exists
|
| 158 |
try:
|
|
@@ -161,7 +165,7 @@ def _init_chroma_client():
|
|
| 161 |
pass
|
| 162 |
# Detect read-only / permission style errors; if so, try next path
|
| 163 |
if any(tok in msg for tok in ["read-only", "readonly", "permission", "attempt to write"]):
|
| 164 |
-
_logger.error(f"Chroma path {abs_path} not writable for DB operations, trying next candidate
|
| 165 |
continue
|
| 166 |
# For corruption cases attempt a reset once
|
| 167 |
if any(tok in msg for tok in ["corrupt", "corruption", "malformed", "disk image"]):
|
|
@@ -180,8 +184,9 @@ def _init_chroma_client():
|
|
| 180 |
# Otherwise just continue to next
|
| 181 |
continue
|
| 182 |
|
| 183 |
-
_logger.error("Failed to initialize persistent Chroma client; attempts=%s. Using in-memory fallback.", tried)
|
| 184 |
-
|
|
|
|
| 185 |
|
| 186 |
_client = _init_chroma_client()
|
| 187 |
|
|
@@ -193,10 +198,10 @@ def _ensure_writable_caches(): # pragma: no cover (env specific)
|
|
| 193 |
current_home = os.path.expanduser("~")
|
| 194 |
# If home resolves to root or isn't writable, pick a fallback
|
| 195 |
if current_home == "/" or not os.access(current_home, os.W_OK):
|
| 196 |
-
for cand in ["/data", "/home/user", "/
|
| 197 |
try:
|
| 198 |
os.makedirs(cand, exist_ok=True)
|
| 199 |
-
test_path = os.path.join(cand, "
|
| 200 |
with open(test_path, "a", encoding="utf-8") as f:
|
| 201 |
f.write("ok")
|
| 202 |
os.remove(test_path)
|
|
@@ -236,7 +241,7 @@ def _init_collections():
|
|
| 236 |
_chunks_collection = _client.get_or_create_collection(
|
| 237 |
name="chunks"
|
| 238 |
)
|
| 239 |
-
_logger.
|
| 240 |
except Exception as e:
|
| 241 |
_logger.error(f"Failed to initialize collections: {e}")
|
| 242 |
# Re-raise the exception to be handled by the application
|
|
|
|
| 25 |
"""Set up a writable cache directory for ChromaDB with fallbacks."""
|
| 26 |
cache_candidates = [
|
| 27 |
"/data/chroma_cache",
|
| 28 |
+
"/data/chromacache",
|
| 29 |
"/tmp/.cache/chroma"
|
| 30 |
]
|
| 31 |
|
|
|
|
| 70 |
"""
|
| 71 |
import time
|
| 72 |
import chromadb # local import so we can still return memory client last
|
| 73 |
+
from chromadb.config import Settings
|
| 74 |
|
| 75 |
# Allow a force-tmp override (e.g. CHROMA_FORCE_TMP=1)
|
| 76 |
force_tmp = os.getenv("CHROMA_FORCE_TMP") in {"1", "true", "yes", "on"}
|
| 77 |
|
| 78 |
+
env_path = os.getenv("PERSIST_DIRECTORY")
|
| 79 |
+
# Order of path attempts (most desired first)
|
| 80 |
+
candidates: list[str] = []
|
| 81 |
if force_tmp:
|
| 82 |
+
candidates = ["/tmp/chroma_db"]
|
| 83 |
+
else:
|
| 84 |
+
if env_path:
|
| 85 |
+
candidates.append(env_path)
|
| 86 |
+
# Common writable locations on HF Spaces
|
| 87 |
+
candidates.extend([
|
| 88 |
+
"/data/chroma_db",
|
| 89 |
+
"/data/chdata",
|
| 90 |
+
"/home/user/chroma_db",
|
| 91 |
+
"/data/db_chroma",
|
| 92 |
+
])
|
| 93 |
+
|
| 94 |
+
tried: list[tuple[str, str]] = []
|
| 95 |
|
| 96 |
def _dir_writeable(path: str) -> bool:
|
| 97 |
try:
|
| 98 |
+
test_file = os.path.join(path, f".write_test_{int(time.time()*1000)}")
|
| 99 |
+
with open(test_file, "w", encoding="utf-8") as tf:
|
|
|
|
| 100 |
tf.write("ok")
|
|
|
|
| 101 |
os.remove(test_file)
|
| 102 |
return True
|
| 103 |
except Exception as e: # pragma: no cover - env specific
|
|
|
|
| 104 |
tried.append((path, f"dir not writable: {e}"))
|
| 105 |
return False
|
| 106 |
|
| 107 |
for cand in candidates:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
abs_path = os.path.abspath(cand)
|
| 109 |
+
try:
|
| 110 |
+
os.makedirs(abs_path, exist_ok=True)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
tried.append((abs_path, f"makedirs failed: {e}"))
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
_logger.info(f"Attempting Chroma PersistentClient at {abs_path}")
|
| 116 |
if not _dir_writeable(abs_path):
|
| 117 |
+
_logger.error(f"Directory not writable: {abs_path}")
|
| 118 |
continue
|
| 119 |
|
| 120 |
+
# Keep env var in sync for downstream components that might read it
|
| 121 |
+
os.environ["PERSIST_DIRECTORY"] = abs_path
|
| 122 |
+
|
| 123 |
# Attempt to (re)chmod existing sqlite/duckdb files if present but not writable
|
| 124 |
try:
|
| 125 |
for fname in os.listdir(abs_path):
|
| 126 |
if any(fname.endswith(ext) for ext in (".sqlite3", ".db", ".duckdb")):
|
| 127 |
fpath = os.path.join(abs_path, fname)
|
|
|
|
| 128 |
if not os.access(fpath, os.W_OK):
|
| 129 |
try:
|
| 130 |
+
os.chmod(fpath, 0o666)
|
|
|
|
| 131 |
except Exception:
|
|
|
|
| 132 |
pass
|
| 133 |
except Exception:
|
| 134 |
pass
|
| 135 |
|
|
|
|
| 136 |
try:
|
| 137 |
+
client = chromadb.PersistentClient(path=abs_path)
|
|
|
|
| 138 |
except Exception as e: # immediate failure
|
| 139 |
tried.append((abs_path, f"create failed: {e}"))
|
| 140 |
+
_logger.error(f"Chroma path {abs_path} not usable, trying next candidate…")
|
| 141 |
continue
|
| 142 |
|
| 143 |
# Basic list works?
|
|
|
|
| 151 |
test_coll_name = f"rw_test_{int(time.time()*10)}"
|
| 152 |
try:
|
| 153 |
tc = client.get_or_create_collection(name=test_coll_name) # type: ignore
|
|
|
|
| 154 |
tc.add(ids=["0"], metadatas=[{"t": "x"}], documents=["test"])
|
|
|
|
| 155 |
client.delete_collection(name=test_coll_name)
|
| 156 |
+
_logger.error(f"Chroma connected with write access at {abs_path}")
|
| 157 |
return client
|
| 158 |
except Exception as e:
|
| 159 |
msg = str(e).lower()
|
|
|
|
| 160 |
tried.append((abs_path, f"write test failed: {e}"))
|
| 161 |
# Clean up partial collection if it exists
|
| 162 |
try:
|
|
|
|
| 165 |
pass
|
| 166 |
# Detect read-only / permission style errors; if so, try next path
|
| 167 |
if any(tok in msg for tok in ["read-only", "readonly", "permission", "attempt to write"]):
|
| 168 |
+
_logger.error(f"Chroma path {abs_path} not writable for DB operations, trying next candidate…")
|
| 169 |
continue
|
| 170 |
# For corruption cases attempt a reset once
|
| 171 |
if any(tok in msg for tok in ["corrupt", "corruption", "malformed", "disk image"]):
|
|
|
|
| 184 |
# Otherwise just continue to next
|
| 185 |
continue
|
| 186 |
|
| 187 |
+
_logger.error("Failed to initialize persistent Chroma client; attempts=%s. Using ephemeral in-memory fallback.", tried)
|
| 188 |
+
# Final fallback: non-persistent in-memory client so the app can still run
|
| 189 |
+
return chromadb.Client(Settings(is_persistent=False, anonymized_telemetry=False)) # type: ignore
|
| 190 |
|
| 191 |
_client = _init_chroma_client()
|
| 192 |
|
|
|
|
| 198 |
current_home = os.path.expanduser("~")
|
| 199 |
# If home resolves to root or isn't writable, pick a fallback
|
| 200 |
if current_home == "/" or not os.access(current_home, os.W_OK):
|
| 201 |
+
for cand in ["/data", "/home/user", "/data/home"]:
|
| 202 |
try:
|
| 203 |
os.makedirs(cand, exist_ok=True)
|
| 204 |
+
test_path = os.path.join(cand, "home_write_test")
|
| 205 |
with open(test_path, "a", encoding="utf-8") as f:
|
| 206 |
f.write("ok")
|
| 207 |
os.remove(test_path)
|
|
|
|
| 241 |
_chunks_collection = _client.get_or_create_collection(
|
| 242 |
name="chunks"
|
| 243 |
)
|
| 244 |
+
_logger.error("Successfully initialized ChromaDB collections.")
|
| 245 |
except Exception as e:
|
| 246 |
_logger.error(f"Failed to initialize collections: {e}")
|
| 247 |
# Re-raise the exception to be handled by the application
|