phaethon-order commited on
Commit
ca2ea72
·
unverified ·
1 Parent(s): c6a9250
Files changed (2) hide show
  1. app.py +34 -3
  2. infrastructure/database.py +101 -21
app.py CHANGED
@@ -2,7 +2,7 @@ from flask import Flask
2
  from flask_cors import CORS
3
  import os
4
  import pathlib
5
- from infrastructure.logger import setup_logger
6
  from routes.web import web_bp
7
  from routes.api import api_bp
8
  import infrastructure.database as db
@@ -24,13 +24,44 @@ def create_app():
24
  "HOME": "/data",
25
  }.items():
26
  os.environ.setdefault(k, v)
27
- pathlib.Path(v).mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  app.register_blueprint(web_bp)
30
  app.register_blueprint(api_bp)
31
 
32
  with app.app_context():
33
- db.init_db()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  return app
36
 
 
2
  from flask_cors import CORS
3
  import os
4
  import pathlib
5
+ from infrastructure.logger import setup_logger, get_logger
6
  from routes.web import web_bp
7
  from routes.api import api_bp
8
  import infrastructure.database as db
 
24
  "HOME": "/data",
25
  }.items():
26
  os.environ.setdefault(k, v)
27
+ try:
28
+ pathlib.Path(v).mkdir(parents=True, exist_ok=True)
29
+ except (OSError, PermissionError) as e:
30
+ # If we can't create the directory (read-only filesystem),
31
+ # try fallback locations
32
+ if "/data" in v:
33
+ fallback = v.replace("/data", "/tmp")
34
+ try:
35
+ pathlib.Path(fallback).mkdir(parents=True, exist_ok=True)
36
+ os.environ[k] = fallback
37
+ logger = get_logger() if 'get_logger' in globals() else None
38
+ if logger:
39
+ logger.warning(f"Fallback: {k} set to {fallback} due to: {e}")
40
+ else:
41
+ print(f"Warning: {k} set to {fallback} due to: {e}")
42
+ except Exception:
43
+ # If fallback also fails, just continue without creating the directory
44
+ pass
45
 
46
  app.register_blueprint(web_bp)
47
  app.register_blueprint(api_bp)
48
 
49
  with app.app_context():
50
+ logger = get_logger()
51
+ try:
52
+ db.init_db()
53
+ except Exception as e:
54
+ # Log the error but try to continue with a database reset
55
+ logger.error(f"Database initialization failed: {e}")
56
+ logger.info("Attempting to reset database...")
57
+ try:
58
+ if db.reset_database():
59
+ logger.info("Database reset successful")
60
+ else:
61
+ logger.error("Database reset failed - app may not function properly")
62
+ except Exception as reset_e:
63
+ logger.error(f"Database reset failed: {reset_e}")
64
+ logger.warning("App will continue but database functionality may be limited")
65
 
66
  return app
67
 
infrastructure/database.py CHANGED
@@ -27,11 +27,34 @@ SEG_VER = int(os.getenv("SEG_VER", "1"))
27
  # ---------------------------------------------------------------------------
28
  # ChromaDB client setup (with HuggingFace / read-only filesystem resilience)
29
  # ---------------------------------------------------------------------------
30
- # Set a writable cache directory for ChromaDB
31
- CACHE_DIR = "/data/chroma_cache"
32
- os.environ["CHROMA_CACHE_DIR"] = CACHE_DIR
33
- if not os.path.exists(CACHE_DIR):
34
- os.makedirs(CACHE_DIR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  CHROMA_PATH = os.getenv("CHROMA_PATH", "/data/chroma_db")
37
 
@@ -40,10 +63,11 @@ def _init_chroma_client():
40
 
41
  Order of attempts:
42
  1. Provided/ default CHROMA_PATH (relative or absolute)
43
- 2. /tmp/chroma_db (writable in most containerized envs incl. HF Spaces)
44
- 3. In-memory (non-persistent) client as last resort
 
45
  """
46
- candidates: list[Optional[str]] = [CHROMA_PATH, "/data/chroma_db"]
47
  tried: list[tuple[Optional[str], str]] = []
48
 
49
  for cand in candidates:
@@ -61,7 +85,31 @@ def _init_chroma_client():
61
  os.remove(test_file)
62
  _logger.info(f"Initializing Chroma PersistentClient at {abs_path}")
63
  import chromadb
64
- return chromadb.PersistentClient(path=os.environ["PERSIST_DIRECTORY"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  except Exception as e: # pragma: no cover - environment specific
66
  tried.append((cand, str(e)))
67
  # Continue to next candidate
@@ -115,14 +163,26 @@ _ensure_writable_caches()
115
  # Using type: ignore to suppress the error.
116
  default_ef = embedding_functions.DefaultEmbeddingFunction()
117
 
118
- _documents_collection = _client.get_or_create_collection(
119
- name="documents",
120
- embedding_function=default_ef # type: ignore
121
- )
122
- _chunks_collection = _client.get_or_create_collection(
123
- name="chunks",
124
- embedding_function=default_ef # type: ignore
125
- )
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  # ---------------------------------------------------------------------------
128
  # Data classes (replacing ORM)
@@ -193,10 +253,12 @@ class Embedding:
193
  # ---------------------------------------------------------------------------
194
  def init_db():
195
  """Initializes ChromaDB collections."""
196
- global _documents_collection, _chunks_collection
197
- _documents_collection = _client.get_or_create_collection(name="documents", embedding_function=default_ef) # type: ignore
198
- _chunks_collection = _client.get_or_create_collection(name="chunks", embedding_function=default_ef) # type: ignore
199
- _logger.info("ChromaDB collections ensured.")
 
 
200
 
201
 
202
  def reset_chroma_collections() -> bool:
@@ -218,6 +280,24 @@ def reset_chroma_collections() -> bool:
218
  return False
219
 
220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  def rebuild_chroma_client() -> None:
222
  """Rebuild the underlying Chroma client (e.g., after filesystem wipe)."""
223
  global _client
 
27
  # ---------------------------------------------------------------------------
28
  # ChromaDB client setup (with HuggingFace / read-only filesystem resilience)
29
  # ---------------------------------------------------------------------------
30
+ # Set a writable cache directory for ChromaDB with fallbacks
31
+ def _setup_cache_dir():
32
+ """Set up a writable cache directory for ChromaDB with fallbacks."""
33
+ cache_candidates = [
34
+ "/data/chroma_cache",
35
+ "/tmp/chroma_cache",
36
+ "/tmp/.cache/chroma"
37
+ ]
38
+
39
+ for cache_dir in cache_candidates:
40
+ try:
41
+ os.makedirs(cache_dir, exist_ok=True)
42
+ # Test if writable
43
+ test_file = os.path.join(cache_dir, ".write_test")
44
+ with open(test_file, "w") as f:
45
+ f.write("test")
46
+ os.remove(test_file)
47
+ os.environ["CHROMA_CACHE_DIR"] = cache_dir
48
+ _logger.info(f"Using ChromaDB cache directory: {cache_dir}")
49
+ return cache_dir
50
+ except Exception:
51
+ continue
52
+
53
+ # If all fail, don't set the cache dir and let ChromaDB handle it
54
+ _logger.warning("Could not set up ChromaDB cache directory, using default")
55
+ return None
56
+
57
+ _setup_cache_dir()
58
 
59
  CHROMA_PATH = os.getenv("CHROMA_PATH", "/data/chroma_db")
60
 
 
63
 
64
  Order of attempts:
65
  1. Provided/ default CHROMA_PATH (relative or absolute)
66
+ 2. /data/chroma_db (writable in most containerized envs incl. HF Spaces)
67
+ 3. /tmp/chroma_db (fallback for read-only filesystems)
68
+ 4. In-memory (non-persistent) client as last resort
69
  """
70
+ candidates: list[Optional[str]] = [CHROMA_PATH, "/data/chroma_db", "/tmp/chroma_db"]
71
  tried: list[tuple[Optional[str], str]] = []
72
 
73
  for cand in candidates:
 
85
  os.remove(test_file)
86
  _logger.info(f"Initializing Chroma PersistentClient at {abs_path}")
87
  import chromadb
88
+
89
+ # Try to create the client
90
+ try:
91
+ client = chromadb.PersistentClient(path=abs_path)
92
+ # Test the client by attempting a simple operation
93
+ # This helps catch database corruption or "table already exists" errors
94
+ collections = client.list_collections()
95
+ _logger.info(f"Successfully connected to ChromaDB at {abs_path}, found {len(collections)} collections")
96
+ return client
97
+ except Exception as client_e:
98
+ _logger.warning(f"Client initialization failed for {abs_path}: {client_e}")
99
+ # If it's a table exists error or similar corruption, try to reset
100
+ if any(phrase in str(client_e).lower() for phrase in ["already exists", "table", "corruption"]):
101
+ _logger.info(f"Attempting to reset/clean ChromaDB at {abs_path}")
102
+ try:
103
+ # Try to reset the database
104
+ temp_client = chromadb.PersistentClient(path=abs_path)
105
+ temp_client.reset()
106
+ return chromadb.PersistentClient(path=abs_path)
107
+ except Exception as reset_e:
108
+ _logger.warning(f"Reset failed for {abs_path}: {reset_e}")
109
+ # If reset fails, this path is unusable, continue to next candidate
110
+ raise client_e
111
+ else:
112
+ raise client_e
113
  except Exception as e: # pragma: no cover - environment specific
114
  tried.append((cand, str(e)))
115
  # Continue to next candidate
 
163
  # Using type: ignore to suppress the error.
164
  default_ef = embedding_functions.DefaultEmbeddingFunction()
165
 
166
+ def _init_collections():
167
+ """Initialize ChromaDB collections with error handling."""
168
+ global _documents_collection, _chunks_collection
169
+ try:
170
+ _documents_collection = _client.get_or_create_collection(
171
+ name="documents",
172
+ embedding_function=default_ef # type: ignore
173
+ )
174
+ _chunks_collection = _client.get_or_create_collection(
175
+ name="chunks",
176
+ embedding_function=default_ef # type: ignore
177
+ )
178
+ _logger.info("Successfully initialized ChromaDB collections.")
179
+ except Exception as e:
180
+ _logger.error(f"Failed to initialize collections: {e}")
181
+ # Re-raise the exception to be handled by the application
182
+ raise
183
+
184
+ # Initialize collections
185
+ _init_collections()
186
 
187
  # ---------------------------------------------------------------------------
188
  # Data classes (replacing ORM)
 
253
  # ---------------------------------------------------------------------------
254
  def init_db():
255
  """Initializes ChromaDB collections."""
256
+ try:
257
+ _init_collections()
258
+ _logger.info("ChromaDB collections ensured.")
259
+ except Exception as e:
260
+ _logger.error(f"Failed to initialize database collections: {e}")
261
+ raise
262
 
263
 
264
  def reset_chroma_collections() -> bool:
 
280
  return False
281
 
282
 
283
+ def reset_database() -> bool:
284
+ """Reset the entire ChromaDB database.
285
+
286
+ This is useful for recovering from database corruption issues.
287
+ Returns True if successful.
288
+ """
289
+ try:
290
+ _logger.info("Resetting entire ChromaDB database...")
291
+ _client.reset()
292
+ # Re-initialize collections after reset
293
+ _init_collections()
294
+ _logger.info("Database reset and collections re-initialized successfully.")
295
+ return True
296
+ except Exception as e:
297
+ _logger.error(f"Failed to reset database: {e}")
298
+ return False
299
+
300
+
301
  def rebuild_chroma_client() -> None:
302
  """Rebuild the underlying Chroma client (e.g., after filesystem wipe)."""
303
  global _client