Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(dictation): stop orphaning recoverable audio and losing concurrent writes

Ruben Lütke4a03083f7b94
diff --git a/jarvis/dictation/_locks.py b/jarvis/dictation/_locks.py
new file mode 100644
index 0000000000..9702a2787b
--- /dev/null
+++ b/jarvis/dictation/_locks.py
@@ -0,0 +1,86 @@
+"""One writer lock per store path, shared by every instance pointing at it.
+
+Why this exists
+---------------
+The dictation sidecars (:mod:`jarvis.dictation.history`,
+:mod:`jarvis.dictation.stats`) are read-modify-write stores: load the whole
+JSON file, change one thing, write it back atomically. That is only safe if
+the load and the write are one indivisible step.
+
+A lock held on the *instance* cannot provide that here, because nothing keeps
+an instance around: the REST routes and the speech pipeline each construct a
+fresh ``DictationHistory()`` / ``DictationStats()`` per operation. Two of them
+serialise against nothing at all, so the last :func:`os.replace` silently
+wins — a Restore can be erased by a dictation that happened to finish a
+moment later. The file was never torn, just quietly reverted, which is the
+kind of loss nobody reports because it looks like it never happened.
+
+So the lock belongs to the PATH, not to the object holding it. This registry
+hands out one lock per resolved store path; two instances built from two
+spellings of the same file get the same lock.
+
+Deadlock, and why there is none
+-------------------------------
+``DictationHistory.add`` holds the history lock while it feeds the statistics
+sidecar, so the only nesting that exists runs history -> stats, never the
+reverse (nothing in the statistics module knows the history exists). Those are
+two different files and therefore two different locks. The one way to make
+them the same lock is to point both stores at one path, which is why these are
+re-entrant: that configuration then blocks nothing instead of deadlocking a
+dictation.
+
+Scope: this serialises threads inside ONE process, which is what the app is.
+Two separate processes writing the same sidecar still race — the atomic
+tempfile + ``os.replace`` keeps the file readable, it just does not keep both
+updates.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+from pathlib import Path
+
+#: Guards the registry itself. Held only long enough to look up or insert.
+_REGISTRY_GUARD = threading.Lock()
+#: Resolved store path -> its lock. Never evicted: a real install has a
+#: handful of distinct sidecar paths, and a lock cannot be weak-referenced
+#: (``_thread.RLock`` does not support it), so an eviction scheme would have
+#: to guess when a writer is done. A few dozen bytes per path is the cheaper
+#: side of that trade.
+_LOCKS: dict[str, threading.RLock] = {}
+
+
+def lock_key(path: Path | str) -> str:
+ """The registry key for ``path`` — resolved and case-normalised.
+
+ ``resolve`` collapses ``..`` segments and symlinks so two spellings of one
+ file share a lock; ``normcase`` finishes the job on Windows, where paths
+ are case-insensitive and ``History.json`` is the same file as
+ ``history.json``. On POSIX ``normcase`` is the identity function, so the
+ case-sensitive filesystem keeps its semantics.
+
+ A path that cannot be resolved (a vanished parent, a permission error)
+ falls back to its literal form rather than raising: a lock key is never
+ worth failing a write over.
+ """
+ candidate = Path(path)
+ try:
+ resolved = candidate.resolve()
+ except (OSError, ValueError, RuntimeError):
+ resolved = candidate
+ return os.path.normcase(str(resolved))
+
+
+def store_lock(path: Path | str) -> threading.RLock:
+ """The one lock for ``path``. Same file in, same lock object out."""
+ key = lock_key(path)
+ with _REGISTRY_GUARD:
+ lock = _LOCKS.get(key)
+ if lock is None:
+ lock = threading.RLock()
+ _LOCKS[key] = lock
+ return lock
+
+
+__all__ = ["lock_key", "store_lock"]
diff --git a/jarvis/dictation/history.py b/jarvis/dictation/history.py
index 5d2f6aeee5..004e17a150 100644
--- a/jarvis/dictation/history.py
+++ b/jarvis/dictation/history.py
@@ -38,7 +38,6 @@ import json
import logging
import os
import tempfile
-import threading
import uuid
from dataclasses import asdict, dataclass, field, replace
from dataclasses import fields as fields_of
@@ -46,6 +45,8 @@ from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from jarvis.dictation._locks import store_lock
+
if TYPE_CHECKING: # import-time cost stays zero on the dictation hot path
from jarvis.dictation.stats import DictationStats
@@ -163,7 +164,12 @@ class DictationHistory:
if stats_path is not None
else self._path.parent / "dictation_stats.json"
)
- self._lock = threading.Lock()
+ # Keyed by the PATH, not owned by this object: every call site builds a
+ # fresh DictationHistory per operation (the REST routes, the speech
+ # pipeline), so a per-instance lock would serialise nothing and two
+ # overlapping read-modify-write cycles would end with the later
+ # os.replace quietly erasing the earlier one. See jarvis.dictation._locks.
+ self._lock = store_lock(self._path)
@property
def path(self) -> Path:
@@ -448,14 +454,20 @@ def _holds_pending_recovery(entry: DictationEntry) -> bool:
An entry the user can still recover from — one that ended badly or was
discarded, and whose audio is still on disk — is the ONLY thing that makes
- the Restore button do anything. Letting the ordinary count cap evict it
- would delete the row while leaving the audio file behind: the user sees the
- entry vanish, the disk keeps the recording, and nobody can get either back.
- So these are exempt from the count cap.
-
- They are NOT exempt from the retention window: the audio itself ages out on
- its own schedule, and an entry whose sidecar is already gone is not a
- pending recovery any more.
+ the Restore button do anything. Dropping the row while leaving the audio
+ file behind is the worst of both worlds: the user sees the entry vanish,
+ the disk keeps the recording, and nobody can reach either again. The
+ history row IS the only handle on that file, so it survives BOTH caps —
+ the count cap and the retention window.
+
+ Surviving the retention window is not an exception to the retention
+ promise, it is how the promise is kept: the row stops being exempt the
+ moment the audio ages out on its own schedule
+ (``[dictation].audio_retention_days``, enforced by
+ :func:`jarvis.dictation.audio.prune_audio`), and the next prune drops it.
+ The two retention keys are independently settable, so the alternative —
+ trusting the audio window to be the shorter one — leaves an orphaned WAV
+ behind on every configuration where it is not.
"""
from jarvis.dictation.outcomes import is_recoverable
@@ -468,6 +480,21 @@ def _holds_pending_recovery(entry: DictationEntry) -> bool:
return audio_exists(entry.audio_path)
+def _is_expired(entry: DictationEntry, cutoff: datetime) -> bool:
+ """``True`` when this entry is older than the retention cutoff.
+
+ An unparseable timestamp reads as "not expired": a row whose age cannot be
+ established is kept rather than silently discarded.
+ """
+ try:
+ created = datetime.fromisoformat(entry.created_at)
+ except (TypeError, ValueError):
+ return False
+ if created.tzinfo is None:
+ created = created.replace(tzinfo=UTC)
+ return created < cutoff
+
+
def _prune(
entries: list[DictationEntry],
*,
@@ -479,32 +506,26 @@ def _prune(
``retention_days = 0`` means "keep until the count cap"; an unparseable
timestamp is kept rather than silently discarded. ``max_entries = 0`` is an
explicit "keep nothing" and overrides every exemption.
+
+ Both caps are checked in one pass, because the pending-recovery exemption
+ costs a filesystem probe per entry and applies to both of them.
"""
cap = max(0, min(int(max_entries or 0), MAX_ENTRIES_CEILING))
if not cap:
return []
- kept = entries
+ cutoff: datetime | None = None
if retention_days and retention_days > 0:
cutoff = datetime.now(UTC) - timedelta(days=int(retention_days))
- fresh: list[DictationEntry] = []
- for entry in kept:
- try:
- created = datetime.fromisoformat(entry.created_at)
- except (TypeError, ValueError):
- fresh.append(entry)
- continue
- if created.tzinfo is None:
- created = created.replace(tzinfo=UTC)
- if created >= cutoff:
- fresh.append(entry)
- kept = fresh
result: list[DictationEntry] = []
budget = cap
- for entry in kept: # newest first — the survivors of the cap are recent
+ for entry in entries: # newest first — the survivors of the cap are recent
if _holds_pending_recovery(entry):
+ # Exempt from both caps, and it does not spend the count budget.
result.append(entry)
continue
+ if cutoff is not None and _is_expired(entry, cutoff):
+ continue
if budget > 0:
result.append(entry)
budget -= 1
diff --git a/jarvis/dictation/stats.py b/jarvis/dictation/stats.py
index f19c6de410..df9a4e711b 100644
--- a/jarvis/dictation/stats.py
+++ b/jarvis/dictation/stats.py
@@ -39,7 +39,6 @@ import json
import logging
import os
import tempfile
-import threading
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from datetime import date as _date
@@ -47,6 +46,8 @@ from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
+from jarvis.dictation._locks import store_lock
+
log = logging.getLogger(__name__)
#: How many days the API hands to the UI. Enough for a year-ish of sparkline
@@ -208,7 +209,11 @@ class DictationStats:
def __init__(self, path: Path | str | None = None) -> None:
self._path = Path(path) if path is not None else default_stats_path()
- self._lock = threading.Lock()
+ # Shared per path rather than per instance: DictationHistory builds a
+ # fresh DictationStats for every entry it records, so a per-object lock
+ # would leave the counters' read-modify-write cycle unguarded against
+ # any other writer (jarvis.dictation._locks).
+ self._lock = store_lock(self._path)
@property
def path(self) -> Path:
diff --git a/tests/unit/dictation/test_dictation_stats.py b/tests/unit/dictation/test_dictation_stats.py
index 59df9ae27f..a518b4d69d 100644
--- a/tests/unit/dictation/test_dictation_stats.py
+++ b/tests/unit/dictation/test_dictation_stats.py
@@ -236,3 +236,47 @@ def test_summarize_entries_skips_wordless_rows() -> None:
def test_summarize_entries_tolerates_an_empty_sequence() -> None:
assert summarize_entries([])["totals"]["words"] == 0
+
+
+# --------------------------------------------------------------------------
+# Concurrency
+# --------------------------------------------------------------------------
+
+
+def test_two_stats_at_one_path_share_one_lock(tmp_path: Path) -> None:
+ """The counters are constructed per entry recorded, never held onto."""
+ nested = tmp_path / "sub"
+ nested.mkdir()
+ direct = DictationStats(tmp_path / "dictation_stats.json")
+ roundabout = DictationStats(nested / ".." / "dictation_stats.json")
+ assert direct._lock is roundabout._lock
+
+
+def test_concurrent_recording_loses_no_count(tmp_path: Path) -> None:
+ """Read-modify-write on one file from two threads must not drop a count."""
+ import threading
+
+ path = tmp_path / "dictation_stats.json"
+ workers, rounds = 2, 40
+ start = threading.Barrier(workers, timeout=15)
+ errors: list[Exception] = []
+
+ def record() -> None:
+ try:
+ start.wait()
+ for _ in range(rounds):
+ assert DictationStats(path).record(word_count=3, duration_s=1.0)
+ except Exception as exc:
+ errors.append(exc)
+
+ threads = [threading.Thread(target=record) for _ in range(workers)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=60)
+ assert not thread.is_alive()
+ assert not errors, errors
+
+ totals = DictationStats(path).summary()["totals"]
+ assert totals["dictations"] == workers * rounds
+ assert totals["words"] == workers * rounds * 3
diff --git a/tests/unit/dictation/test_segment_and_history.py b/tests/unit/dictation/test_segment_and_history.py
index 84aa7a54dc..192abcddf0 100644
--- a/tests/unit/dictation/test_segment_and_history.py
+++ b/tests/unit/dictation/test_segment_and_history.py
@@ -7,6 +7,7 @@ on it.
"""
from __future__ import annotations
+import threading
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -455,8 +456,17 @@ def test_a_successful_entry_with_audio_is_not_exempt(tmp_path: Path) -> None:
assert fine not in kept
-def test_the_exemption_does_not_survive_the_retention_window(tmp_path: Path) -> None:
- """Audio ages out on its own schedule; a stale row is not held open."""
+def test_the_retention_window_does_not_orphan_a_recoverable_recording(
+ tmp_path: Path,
+) -> None:
+ """The two retention keys are independent, so the row follows the audio.
+
+ ``history_retention_days`` and ``audio_retention_days`` are separate
+ settings with no cross-field validation, so "1 day of history, a year of
+ audio" is a legal configuration. If the time cutoff dropped the row anyway,
+ the WAV would still be on disk with nothing left pointing at it: audio the
+ user can neither restore from nor find.
+ """
from jarvis.dictation.audio import save_dictation_audio
from jarvis.dictation.history import DictationEntry
@@ -470,4 +480,150 @@ def test_the_exemption_does_not_survive_the_retention_window(tmp_path: Path) ->
outcome="failed",
audio_path=str(path),
)
+ # history_retention_days = 1 against an audio window measured in months.
+ assert _prune([stale], max_entries=100, retention_days=1) == [stale]
+ assert path.is_file()
+
+
+def test_the_row_ages_out_once_the_audio_window_has_taken_the_file(
+ tmp_path: Path,
+) -> None:
+ """The exemption ends with the recording, which is what bounds it."""
+ from jarvis.dictation.audio import prune_audio, save_dictation_audio
+ from jarvis.dictation.history import DictationEntry
+
+ path = save_dictation_audio("old", b"\x00\x01" * 800, directory=tmp_path)
+ assert path is not None
+ stale = DictationEntry(
+ id="old",
+ created_at=(datetime.now(UTC) - timedelta(days=40)).isoformat(),
+ raw_text="",
+ text="",
+ outcome="failed",
+ audio_path=str(path),
+ )
+ assert prune_audio(max_files=0, retention_days=0, directory=tmp_path) == 0
+ path.unlink() # what the audio retention would have done on its schedule
+ assert _prune([stale], max_entries=100, retention_days=30) == []
+
+
+def test_an_expired_entry_without_audio_still_ages_out(tmp_path: Path) -> None:
+ """The exemption is about a stranded recording, not about failing at all."""
+ from jarvis.dictation.history import DictationEntry
+
+ stale = DictationEntry(
+ id="old",
+ created_at=(datetime.now(UTC) - timedelta(days=40)).isoformat(),
+ raw_text="",
+ text="",
+ outcome="failed",
+ )
assert _prune([stale], max_entries=100, retention_days=30) == []
+
+
+def test_add_keeps_a_recoverable_row_a_short_history_window_would_drop(
+ tmp_path: Path,
+) -> None:
+ """The same configuration, driven through the real write path."""
+ from jarvis.dictation.audio import save_dictation_audio
+
+ store = DictationHistory(tmp_path / "dictation_history.json")
+ entry = store.add(raw_text="", text="", outcome="failed", retention_days=1)
+ assert entry is not None
+ wav = save_dictation_audio(entry.id, b"\x00\x01" * 800, directory=store.audio_dir)
+ assert wav is not None
+ assert store.update(entry.id, audio_path=str(wav)) is not None
+
+ # Backdate it well past the one-day history window, then write again so the
+ # prune runs over it.
+ _backdate(store, entry.id, days=30)
+ store.add(raw_text="later", text="later", retention_days=1)
+
+ kept = {e.id for e in store.list_all()}
+ assert entry.id in kept
+ assert wav.is_file()
+
+
+def _backdate(store: DictationHistory, entry_id: str, *, days: float) -> None:
+ """Rewrite one entry's timestamp on disk. ``created_at`` is immutable."""
+ import json
+
+ payload = json.loads(store.path.read_text(encoding="utf-8"))
+ when = (datetime.now(UTC) - timedelta(days=days)).isoformat()
+ for item in payload["entries"]:
+ if item.get("id") == entry_id:
+ item["created_at"] = when
+ store.path.write_text(json.dumps(payload), encoding="utf-8")
+
+
+# --------------------------------------------------------------------------
+# The write lock belongs to the path, not to the instance
+# --------------------------------------------------------------------------
+
+
+def test_two_stores_at_one_path_share_one_lock(tmp_path: Path) -> None:
+ """Nothing keeps an instance alive, so a per-object lock guards nothing.
+
+ Every caller builds a fresh store per operation, and two spellings of the
+ same file have to end up on the same lock or the read-modify-write cycle
+ is unguarded.
+ """
+ nested = tmp_path / "sub"
+ nested.mkdir()
+ direct = DictationHistory(tmp_path / "dictation_history.json")
+ roundabout = DictationHistory(nested / ".." / "dictation_history.json")
+ assert direct._lock is roundabout._lock
+ assert direct.stats()._lock is roundabout.stats()._lock
+
+
+def test_two_stores_at_different_paths_do_not_share_a_lock(tmp_path: Path) -> None:
+ """Two profiles must not serialise against each other for no reason."""
+ one = DictationHistory(tmp_path / "one.json")
+ two = DictationHistory(tmp_path / "two.json")
+ assert one._lock is not two._lock
+
+
+def test_a_restore_is_not_clobbered_by_a_dictation_finishing(tmp_path: Path) -> None:
+ """The race the REST endpoints introduced: two writers, one file.
+
+ A restore (read, change one row, write it all back) overlapping a
+ dictation being recorded used to end with whichever ``os.replace`` landed
+ last: the file stayed readable, one of the two updates just quietly
+ vanished. Both must survive.
+ """
+ path = tmp_path / "dictation_history.json"
+ seed = DictationHistory(path).add(raw_text="", text="", outcome="failed")
+ assert seed is not None
+
+ rounds = 30
+ start = threading.Barrier(2, timeout=15)
+ errors: list[Exception] = []
+
+ def restoring() -> None:
+ try:
+ start.wait()
+ for i in range(rounds):
+ assert DictationHistory(path).update(seed.id, text=f"restored-{i}")
+ except Exception as exc:
+ errors.append(exc)
+
+ def dictating() -> None:
+ try:
+ start.wait()
+ for i in range(rounds):
+ assert DictationHistory(path).add(raw_text=f"n{i}", text=f"n{i}")
+ except Exception as exc:
+ errors.append(exc)
+
+ workers = [threading.Thread(target=restoring), threading.Thread(target=dictating)]
+ for worker in workers:
+ worker.start()
+ for worker in workers:
+ worker.join(timeout=60)
+ assert not worker.is_alive()
+ assert not errors, errors
+
+ entries = DictationHistory(path).list_all()
+ assert len([e for e in entries if e.text.startswith("n")]) == rounds
+ restored = [e for e in entries if e.id == seed.id]
+ assert [e.text for e in restored] == [f"restored-{rounds - 1}"]