Skip to content
Merged
Show file tree
Hide file tree
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
11 changes: 11 additions & 0 deletions client/cli/chat_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,17 @@ def resource_dir(env_var, name):
STATE_DIR = os.environ.get("SPEAR_STATE_DIR") or _TEST_STATE or APP_DIR
os.makedirs(STATE_DIR, exist_ok=True)

# An image ships its index and names it here. What a session indexes then goes
# beside its other state, where it outlives the container, and is read before
# the shipped one. The indexers are separate programs and learn the place from
# the environment.

SHIPPED_DB_PATH = os.environ.get("SPEAR_SHIPPED_DB_PATH") or ""

if SHIPPED_DB_PATH and not os.environ.get("SPEAR_DB_PATH") and not _TEST_STATE:
DB_PATH = f"{STATE_DIR}/chromadb"
os.environ["SPEAR_DB_PATH"] = DB_PATH

# All of these accumulate, so all of them live under STATE_DIR: the audit
# trail, the runtime trace, the tool results a later turn may re-read, the
# session records and the file checkpoints an undo restores from. Rooting them
Expand Down
37 changes: 35 additions & 2 deletions client/cli/corpus_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import subprocess
from retrieval import embedding
from cli import session_workspace
from cli.chat_settings import APP_DIR, DB_PATH
from cli.chat_settings import APP_DIR, DB_PATH, SHIPPED_DB_PATH
from cli.corpus_registry import corpora_below, load_projects
from cli.terminal_ui import C_DIM, C_RST, C_WARN

Expand Down Expand Up @@ -603,7 +603,40 @@ def _db():
"""
import chromadb

return chromadb.PersistentClient(path=DB_PATH)
own = chromadb.PersistentClient(path=DB_PATH)

if (SHIPPED_DB_PATH and os.path.isdir(SHIPPED_DB_PATH)
and os.path.realpath(SHIPPED_DB_PATH) != os.path.realpath(DB_PATH)):
return LayeredIndex(own, chromadb.PersistentClient(path=SHIPPED_DB_PATH))

return own


class LayeredIndex:
"""The user's index over the one an image ships.

A collection is looked up in the user's first, so a corpus indexed again
by the user answers from that; everything that writes goes to the user's.
"""

def __init__(self, own, shipped):
self._own, self._shipped = own, shipped

def get_collection(self, name, **kwargs):
try:
return self._own.get_collection(name, **kwargs)
except Exception:
return self._shipped.get_collection(name, **kwargs)

def list_collections(self):
mine = list(self._own.list_collections())
names = {collection.name for collection in mine}

return mine + [collection for collection in self._shipped.list_collections()
if collection.name not in names]

def __getattr__(self, name):
return getattr(self._own, name)


def archive_index(rec):
Expand Down
55 changes: 55 additions & 0 deletions client/tests/test_layered_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""The user's index is read before the one an image ships, and is the one
written."""

import os
import sys
import tempfile
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import chromadb

from cli import corpus_search


def vectors(count):
return [[float(i), 1.0] for i in range(count)]


class LayeredIndex(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.own = chromadb.PersistentClient(path=f"{self.tmp.name}/own")
self.shipped = chromadb.PersistentClient(path=f"{self.tmp.name}/shipped")
self.index = corpus_search.LayeredIndex(self.own, self.shipped)

baked = self.shipped.create_collection("baked")
baked.add(ids=["a", "b"], documents=["one", "two"], embeddings=vectors(2))

def test_a_shipped_collection_is_found(self):
self.assertEqual(self.index.get_collection(name="baked").count(), 2)

def test_the_user_s_collection_of_the_same_name_wins(self):
mine = self.own.create_collection("baked")
mine.add(ids=["a"], documents=["mine"], embeddings=vectors(1))

self.assertEqual(self.index.get_collection(name="baked").count(), 1)
self.assertEqual([c.name for c in self.index.list_collections()], ["baked"])

def test_what_is_created_goes_to_the_user_s(self):
self.index.get_or_create_collection("new")

self.assertEqual([c.name for c in self.own.list_collections()], ["new"])
self.assertEqual([c.name for c in self.shipped.list_collections()], ["baked"])
self.assertEqual(sorted(c.name for c in self.index.list_collections()),
["baked", "new"])

def test_an_unknown_collection_still_fails(self):
with self.assertRaises(Exception):
self.index.get_collection(name="absent")


if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions docker/Dockerfile.harness
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ RUN chmod +x /opt/spear/entrypoint.sh /opt/spear/spear-run.sh /usr/local/bin/spe
ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common
ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards
ENV SPEAR_STATE_DIR=/opt/spear/state
ENV SPEAR_SHIPPED_DB_PATH=$APP/chromadb
ENV SPEAR_CORPUS_ROOT=/corpora
ENV PATH=$APP/bin:$PATH
WORKDIR /corpora
Expand Down
3 changes: 1 addition & 2 deletions docker/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ print(f"corpora: {found} present, {miss} missing "
# is the entire reason the tool exists.
import textwrap

import chromadb
have = {c.name for c in chromadb.PersistentClient(path=chat_settings.DB_PATH).list_collections()}
have = {c.name for c in corpus_search._db().list_collections()}
absent = sorted(n for n, spec in corpus_registry.load_projects().items()
if os.path.isdir(spec["path"])
and corpus_search.collection_name_for(spec) not in have)
Expand Down
Loading