hivemind-sqlite-database 0.4.1a1__tar.gz → 0.4.3a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of hivemind-sqlite-database might be problematic. Click here for more details.

Files changed (14) hide show
  1. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/PKG-INFO +1 -1
  2. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database/__init__.py +113 -20
  3. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database/version.py +1 -1
  4. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/PKG-INFO +1 -1
  5. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/tests/test_sqlitedb.py +113 -0
  6. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/LICENSE.md +0 -0
  7. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/README.md +0 -0
  8. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/SOURCES.txt +0 -0
  9. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/dependency_links.txt +0 -0
  10. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/entry_points.txt +0 -0
  11. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/requires.txt +0 -0
  12. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/hivemind_sqlite_database.egg-info/top_level.txt +0 -0
  13. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/pyproject.toml +0 -0
  14. {hivemind_sqlite_database-0.4.1a1 → hivemind_sqlite_database-0.4.3a1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hivemind-sqlite-database
3
- Version: 0.4.1a1
3
+ Version: 0.4.3a1
4
4
  Summary: sqlite database plugin for hivemind-core
5
5
  Author-email: jarbasAi <jarbasai@mailfence.com>
6
6
  License: Apache-2.0
@@ -2,7 +2,7 @@ import json
2
2
  import os.path
3
3
  import sqlite3
4
4
  import threading
5
- from typing import List, Optional, Union, Iterable
5
+ from typing import ClassVar, List, Optional, Union, Iterable
6
6
 
7
7
  from ovos_utils.log import LOG
8
8
  from ovos_utils.xdg_utils import xdg_data_home
@@ -26,6 +26,17 @@ class SQLiteDB(AbstractDB):
26
26
  name: str = "clients"
27
27
  subfolder: str = "hivemind-core"
28
28
  password: Optional[str] = None
29
+ # Overrides the computed xdg path entirely, e.g. ":memory:" for tests.
30
+ # Every thread's connection is opened against this same target, so
31
+ # nothing ever silently falls back to the real client database.
32
+ # ":memory:" becomes a named shared in-memory database, one per
33
+ # SQLiteDB instance, so worker threads see the same tables as the
34
+ # thread that created them.
35
+ db_path: Optional[str] = None
36
+
37
+ # How long SQLite waits for a file lock held by another connection
38
+ # before giving up with SQLITE_BUSY, in milliseconds.
39
+ BUSY_TIMEOUT_MS: ClassVar[int] = 10000
29
40
 
30
41
  def __post_init__(self):
31
42
  """
@@ -38,14 +49,49 @@ class SQLiteDB(AbstractDB):
38
49
 
39
50
  When *password* is ``None`` (default) the standard ``sqlite3`` module
40
51
  is used and the database file is unencrypted.
52
+
53
+ Each thread gets its own connection (see :attr:`conn`). A single
54
+ shared connection is not usable from several threads at once: the
55
+ transaction state belongs to the connection, so one thread's
56
+ ``COMMIT`` ends another thread's transaction and resets its
57
+ in-flight statements. Under a threaded network backend that shows
58
+ up as ``sqlite3.ProgrammingError: bad parameter or other API
59
+ misuse`` and as writes that land with corrupted bindings.
41
60
  """
42
- db_path = os.path.join(xdg_data_home(), self.subfolder, self.name + ".db")
43
- LOG.debug(f"sqlite database path: {db_path}")
44
- os.makedirs(os.path.dirname(db_path), exist_ok=True)
61
+ if self.db_path is not None:
62
+ self._db_path = self.db_path
63
+ if self._db_path == ":memory:":
64
+ # A plain ":memory:" database belongs to the one connection
65
+ # that opened it, so the next thread would open a second,
66
+ # empty database and find no tables. Give it a name and a
67
+ # shared cache instead. The name carries the instance id, so
68
+ # two in-memory databases in one process stay independent.
69
+ self._db_path = f"file:hivemind-{id(self):x}?mode=memory&cache=shared"
70
+ else:
71
+ self._db_path = os.path.join(xdg_data_home(), self.subfolder, self.name + ".db")
72
+ self._is_uri = self._db_path.startswith("file:")
73
+ parent = os.path.dirname(self._db_path)
74
+ if parent and not self._is_uri:
75
+ os.makedirs(parent, exist_ok=True)
76
+ LOG.debug(f"sqlite database path: {self._db_path}")
77
+
78
+ if self.password is not None and self.password == "":
79
+ raise ValueError("password must be non-empty when encryption is enabled")
80
+
81
+ self._write_lock = threading.Lock()
82
+ # opening the first connection also applies the WAL pragma
83
+ self.conn.execute("PRAGMA journal_mode=WAL")
84
+ if "mode=memory" in self._db_path:
85
+ # A shared in-memory database lives only while a connection to
86
+ # it is open. Hold one for the lifetime of this object so the
87
+ # tables survive a thread closing its own connection.
88
+ self._keepalive = self._connect()
89
+ self._initialize_database()
90
+ self._maybe_migrate()
45
91
 
92
+ def _connect(self):
93
+ """Open one new connection to the backing file."""
46
94
  if self.password is not None:
47
- if self.password == "":
48
- raise ValueError("password must be non-empty when encryption is enabled")
49
95
  try:
50
96
  import sqlcipher3 as _sqlcipher
51
97
  except ImportError:
@@ -54,18 +100,63 @@ class SQLiteDB(AbstractDB):
54
100
  "Install the system library (e.g. 'apt install libsqlcipher-dev') "
55
101
  "then: pip install hivemind-sqlite-database[cipher]"
56
102
  )
57
- self.conn = _sqlcipher.connect(db_path, check_same_thread=False)
58
- self.conn.row_factory = _sqlcipher.Row
103
+ conn = _sqlcipher.connect(self._db_path, check_same_thread=False,
104
+ uri=self._is_uri)
105
+ conn.row_factory = _sqlcipher.Row
59
106
  escaped_password = self.password.replace("'", "''")
60
- self.conn.execute(f"PRAGMA key='{escaped_password}'")
107
+ conn.execute(f"PRAGMA key='{escaped_password}'")
61
108
  else:
62
- self.conn = sqlite3.connect(db_path, check_same_thread=False)
63
- self.conn.row_factory = sqlite3.Row
64
-
65
- self.conn.execute("PRAGMA journal_mode=WAL")
66
- self._write_lock = threading.Lock()
67
- self._initialize_database()
68
- self._maybe_migrate()
109
+ conn = sqlite3.connect(self._db_path, check_same_thread=False,
110
+ uri=self._is_uri)
111
+ conn.row_factory = sqlite3.Row
112
+ conn.execute(f"PRAGMA busy_timeout={int(self.BUSY_TIMEOUT_MS)}")
113
+ return conn
114
+
115
+ @property
116
+ def conn(self):
117
+ """The calling thread's own connection, opened on first use.
118
+
119
+ Connections are cheap and WAL lets many readers run beside one
120
+ writer, so a per-thread connection costs a file handle and buys
121
+ real thread safety. ``_write_lock`` still serialises writers
122
+ in-process so they do not fight over the file lock.
123
+ """
124
+ local = self._thread_state()
125
+ conn = getattr(local, "conn", None)
126
+ if conn is None:
127
+ conn = local.conn = self._connect()
128
+ return conn
129
+
130
+ @conn.setter
131
+ def conn(self, value) -> None:
132
+ """Adopt an already-open connection for the calling thread only.
133
+
134
+ Any other thread that later touches ``.conn`` still opens its own
135
+ connection against ``self._db_path`` — if that is the real client
136
+ database, that thread silently writes to it. Pass ``db_path``
137
+ (e.g. ``":memory:"``) to the constructor instead so every thread,
138
+ present and future, agrees on the same target; this setter exists
139
+ only for single-threaded call sites that already hold a connection
140
+ they want reused.
141
+ """
142
+ self._thread_state().conn = value
143
+
144
+ def _thread_state(self) -> threading.local:
145
+ local = self.__dict__.get("_local")
146
+ if local is None:
147
+ local = self.__dict__["_local"] = threading.local()
148
+ return local
149
+
150
+ def close(self) -> None:
151
+ """Close the calling thread's connection, if it has one."""
152
+ local = self._thread_state()
153
+ conn = getattr(local, "conn", None)
154
+ if conn is not None:
155
+ local.conn = None
156
+ try:
157
+ conn.close()
158
+ except sqlite3.Error as e:
159
+ LOG.error(f"Failed to close SQLite connection: {e}")
69
160
 
70
161
  def _initialize_database(self):
71
162
  """Initialize the database schema."""
@@ -235,10 +326,12 @@ class SQLiteDB(AbstractDB):
235
326
  LOG.error(f"Invalid search key: {key!r}")
236
327
  return []
237
328
  try:
238
- with self.conn:
239
- cur = self.conn.execute(f"SELECT * FROM clients WHERE {key} = ?", (val,))
240
- rows = cur.fetchall()
241
- return [self._row_to_client(row) for row in rows]
329
+ # deliberately NOT wrapped in ``with self.conn`` — that context
330
+ # manager commits the connection's transaction on exit, which a
331
+ # read has no business doing.
332
+ cur = self.conn.execute(f"SELECT * FROM clients WHERE {key} = ?", (val,))
333
+ rows = cur.fetchall()
334
+ return [self._row_to_client(row) for row in rows]
242
335
  except sqlite3.Error as e:
243
336
  LOG.error(f"Failed to search clients in SQLite: {e}")
244
337
  return []
@@ -1,7 +1,7 @@
1
1
  # START_VERSION_BLOCK
2
2
  VERSION_MAJOR = 0
3
3
  VERSION_MINOR = 4
4
- VERSION_BUILD = 1
4
+ VERSION_BUILD = 3
5
5
  VERSION_ALPHA = 1
6
6
  # END_VERSION_BLOCK
7
7
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hivemind-sqlite-database
3
- Version: 0.4.1a1
3
+ Version: 0.4.3a1
4
4
  Summary: sqlite database plugin for hivemind-core
5
5
  Author-email: jarbasAi <jarbasai@mailfence.com>
6
6
  License: Apache-2.0
@@ -422,6 +422,56 @@ class TestSQLiteDBRoundTrip(unittest.TestCase):
422
422
  self.assertEqual(r.intent_blacklist, ["a:b"])
423
423
 
424
424
 
425
+ class TestSQLiteDBPathOverride(unittest.TestCase):
426
+ """A worker thread must never fall back to the real client database
427
+ just because the test only overrode `.conn` on the main thread."""
428
+
429
+ def test_db_path_override_keeps_worker_threads_off_disk(self):
430
+ import unittest.mock as mock
431
+ with tempfile.TemporaryDirectory() as tmpdir:
432
+ with mock.patch(
433
+ "hivemind_sqlite_database.xdg_data_home", return_value=tmpdir
434
+ ):
435
+ db = SQLiteDB(name="clients", subfolder="hivemind-core",
436
+ db_path=":memory:")
437
+
438
+ # Read a row written on this thread. "SELECT 1" would answer
439
+ # the same against a private, empty database and so would
440
+ # never notice a per-thread database.
441
+ db.add_item(Client(client_id=1, api_key="key",
442
+ name="kitchen"))
443
+
444
+ errors = []
445
+ seen = []
446
+
447
+ def worker():
448
+ try:
449
+ seen.extend(db.search_by_value("name", "kitchen"))
450
+ except Exception as e: # noqa: BLE001
451
+ errors.append(e)
452
+
453
+ t = threading.Thread(target=worker)
454
+ t.start()
455
+ t.join()
456
+
457
+ self.assertEqual(errors, [])
458
+ self.assertEqual([c.client_id for c in seen], [1])
459
+ real_db_file = os.path.join(tmpdir, "hivemind-core", "clients.db")
460
+ self.assertFalse(os.path.exists(real_db_file))
461
+
462
+ def test_two_in_memory_databases_stay_independent(self):
463
+ first = SQLiteDB(db_path=":memory:")
464
+ second = SQLiteDB(db_path=":memory:")
465
+ first.add_item(Client(client_id=1, api_key="key", name="kitchen"))
466
+ self.assertEqual(second.search_by_value("name", "kitchen"), [])
467
+
468
+ def test_explicit_db_path_creates_missing_directories(self):
469
+ with tempfile.TemporaryDirectory() as tmpdir:
470
+ path = os.path.join(tmpdir, "newdir", "clients.db")
471
+ SQLiteDB(db_path=path)
472
+ self.assertTrue(os.path.isfile(path))
473
+
474
+
425
475
  class TestSQLiteDBCommit(unittest.TestCase):
426
476
  def test_commit_returns_true(self):
427
477
  db = make_db()
@@ -883,3 +933,66 @@ class TestSQLiteDBSchemaV2RoundTrip(unittest.TestCase):
883
933
 
884
934
  if __name__ == "__main__":
885
935
  unittest.main()
936
+
937
+
938
+ class TestSQLiteDBThreadSafety(unittest.TestCase):
939
+ """A real file-backed DB hammered from many threads at once.
940
+
941
+ Reproduces the failure seen under the threaded (webrockets) network
942
+ backend: concurrent reads and writes through ONE shared connection
943
+ raise ``bad parameter or other API misuse`` and write rows with
944
+ corrupted bindings (``NOT NULL constraint failed: clients.api_key``),
945
+ because one thread's implicit COMMIT ends another thread's
946
+ transaction.
947
+ """
948
+
949
+ def test_concurrent_read_write_is_clean(self):
950
+ import tempfile
951
+ from unittest.mock import patch
952
+
953
+ with tempfile.TemporaryDirectory() as tmp:
954
+ with patch("hivemind_sqlite_database.xdg_data_home", return_value=tmp):
955
+ db = SQLiteDB()
956
+ n = 60
957
+ for i in range(n):
958
+ self.assertTrue(db.add_item(make_client(i, f"key-{i}")))
959
+
960
+ errors = []
961
+ misses = []
962
+ barrier = threading.Barrier(24)
963
+
964
+ def reader(i):
965
+ barrier.wait()
966
+ try:
967
+ for _ in range(40):
968
+ got = db.search_by_value("api_key", f"key-{i % n}")
969
+ if len(got) != 1:
970
+ misses.append((i, len(got)))
971
+ except Exception as e: # noqa: BLE001
972
+ errors.append(repr(e))
973
+
974
+ def writer(i):
975
+ barrier.wait()
976
+ try:
977
+ for k in range(40):
978
+ if not db.add_item(
979
+ make_client(i % n, f"key-{i % n}",
980
+ name=f"w{k}")):
981
+ errors.append(f"add_item returned False ({i},{k})")
982
+ except Exception as e: # noqa: BLE001
983
+ errors.append(repr(e))
984
+
985
+ threads = [threading.Thread(target=reader, args=(i,))
986
+ for i in range(16)]
987
+ threads += [threading.Thread(target=writer, args=(i,))
988
+ for i in range(8)]
989
+ for t in threads:
990
+ t.start()
991
+ for t in threads:
992
+ t.join(timeout=120)
993
+
994
+ self.assertEqual(errors, [])
995
+ self.assertEqual(misses, [])
996
+ # every api_key still resolves to exactly one live row
997
+ for i in range(n):
998
+ self.assertEqual(len(db.search_by_value("api_key", f"key-{i}")), 1)