Skip to content

fix(config): serialize config reads and writes with FileLock - #2184

Open
aloneangel45 wants to merge 4 commits into
basicmachines-co:mainfrom
aloneangel45:fix/2181-lock-config-writes
Open

aloneangel45 wants to merge 4 commits into
basicmachines-co:mainfrom
aloneangel45:fix/2181-lock-config-writes

Conversation

@aloneangel45

Copy link
Copy Markdown

Summary

Serializes read-modify-replace operations on config.json across threads and concurrent MCP/CLI processes using filelock.FileLock.

Root Cause

save_basic_memory_config() read config.json in _file_config_dict(), wrote a temporary file, and called os.replace(temp_path, file_path) without holding an inter-process lock. Concurrent processes could overwrite each other's config changes or hit PermissionError during concurrent os.replace() calls on Windows.

Additionally, _save_last_checked_timestamp() performed an unlocked load_config() -> mutate -> save_config() cycle that could overwrite concurrent changes written between load and save.

Changes

  • Added a shared _config_write_lock context manager in src/basic_memory/config.py pairing a per-path threading.RLock (plus re-entrancy guard within the same call stack) with filelock.FileLock (bounded by CONFIG_LOCK_TIMEOUT_SECONDS = 10.0) around directory creation, read/merge, temp write, and os.replace.
  • Added ConfigManager.update_config(mutate, *, persist_env_keys=...) to atomically reload, mutate, and write config.json under the same lock.
  • Updated _save_last_checked_timestamp() in src/basic_memory/cli/auto_update.py to use ConfigManager.update_config when available while keeping compatibility with lightweight test stubs (StubConfigManager).
  • Added tests/test_config_locking.py covering concurrent multi-process updates, lock-timeout error propagation, and nested initial config creation inside update_config.

Verification

  • ruff format --check src/basic_memory/config.py src/basic_memory/cli/auto_update.py tests/test_config_locking.py: passed
  • ruff check src/basic_memory/config.py src/basic_memory/cli/auto_update.py tests/test_config_locking.py: passed
  • pytest --noconftest -v tests/test_config_locking.py tests/test_config_save_reports_failure.py tests/cli/test_auto_update.py: 44 passed (--noconftest used locally because tests/conftest.py imports full DB/embeddings dependencies not installed in this isolated environment)

Fixes #2181

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T02:19:51.507991Z e3b6535 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3b6535515

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

os.replace(temp_path, file_path)
finally:
temp_path.unlink(missing_ok=True)
with _config_write_lock(file_path):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Lock before building caller snapshots

When separate processes perform read-modify-write updates such as ConfigManager.add_project(), both can load and edit the same old config before reaching this lock. It serializes the replacements, but the later writer still writes a stale full snapshot and can drop the earlier update; update_config() is not used by those mutation paths. Hold the lock across their reload, mutation, and write as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in the updated commit: ConfigManager.add_project, remove_project, and set_default_project now run reload -> check -> mutate -> save via _mutate_config_locked inside _config_write_lock so concurrent processes cannot overwrite each other's updates with stale snapshots. Added test_add_project_serializes_concurrent_processes and signed off for DCO. Verified with ruff format --check, ruff check, and pytest --noconftest -v tests/test_config_locking.py tests/test_config_save_reports_failure.py tests/cli/test_auto_update.py (45 passed).

@aloneangel45
aloneangel45 force-pushed the fix/2181-lock-config-writes branch from e3b6535 to e0f8915 Compare November 30, 2026 02:38
Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>
@Flynn-Kawolsky

Copy link
Copy Markdown

Thanks for tackling #2181 — the re-entrant _config_write_lock helper, UTF-8 encoding fix on temp_path.write_text, and multi-process tests are a great start. A few concrete edge cases I noticed on Windows and concurrent threads:

  1. Windows PermissionError (WinError 5) still occurs against unlocked load_config() readers: ConfigManager.load_config() still reads config.json without _config_write_lock, and _write_config_locked() runs a single os.replace(temp_path, file_path) with no Windows retry. Testing that exact locked write loop against 3 concurrent unlocked Path.read_text() reader subprocesses on Windows 11 still fails ~25% of writes (PermissionError: [WinError 5]). Adding a short bounded retry on PermissionError when os.name == "nt" around os.replace() (or coordinating reads) plus a concurrent reader+writer test would close the Windows failure mode described in [BUG] save_basic_memory_config() performs unlocked read-modify-write on config.json across concurrent MCP processes #2181.
  2. In-process _CONFIG_CACHE aliasing during _mutate_config_locked(): Inside _mutate_config_locked(), config = self.load_config() repopulates module-global _CONFIG_CACHE (with the pre-write _CONFIG_MTIME/_CONFIG_SIZE), and then mutate(config) mutates that cached object in place before save_config() and finally: clear _CONFIG_CACHE. Another thread calling load_config() during that window receives the uncommitted, actively mutating BasicMemoryConfig instance (and can hit dict-size-changed errors on config.projects or see partial state if mutate() raises). Clearing _CONFIG_CACHE immediately after self.load_config() (or mutating config.model_copy(deep=True)) prevents exposing uncommitted state.
  3. Remaining unlocked read-modify-write callers: bm config set / bm config unset (src/basic_memory/cli/commands/config.py:246, 272, mentioned in [BUG] save_basic_memory_config() performs unlocked read-modify-write on config.json across concurrent MCP processes #2181) and the periodic promo stamp (src/basic_memory/cli/promo.py:130) still do load_config() -> mutate -> save_config() outside update_config(), so they can still race with _save_last_checked_timestamp() (as can callers in cli/commands/project.py and services/project_service.py). Switching at least config.py and promo.py to update_config() would close the main CLI/background race.
  4. Error-contract asymmetry & CLA: add_project/remove_project/set_default_project now let filelock.Timeout raise from _mutate_config_locked(), while still discarding save_config()'s returned Exception | None — worth deciding whether lock timeouts should raise or follow the existing error-return contract. Also a friendly reminder that license/cla is still pending (maintainers require a signed CLA before merging).

…lock config CLI/promo

Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>
@aloneangel45

Copy link
Copy Markdown
Author

@Flynn-Kawolsky Thank you for the detailed review! Updated the PR in 37e4017 to address your points:

  1. Windows PermissionError (WinError 5) during os.replace: Added _replace_with_windows_retry in _write_config_locked (bounded backoff up to 8 retries on PermissionError when os.name == "nt"), plus unit + concurrent unlocked-reader stress coverage (test_replace_with_windows_retry_recovers_from_permission_error, test_locked_writes_survive_concurrent_unlocked_readers).
  2. In-process _CONFIG_CACHE aliasing during _mutate_config_locked: _mutate_config_locked now clears _CONFIG_CACHE/_CONFIG_MTIME/_CONFIG_SIZE immediately and works on self.load_config().model_copy(deep=True) before invoking mutate(config), preventing mid-mutation reads or failed writes from observing mutated cached state (test_mutate_config_locked_does_not_leak_uncommitted_cache).
  3. Remaining unlocked read-modify-write callers (cli/commands/config.py, cli/promo.py): Switched config set, config unset (resolving default_project inside the locked mutator), and maybe_show_cloud_promo stamp persistence to update_config(...) (test_cli_config_set_unset_and_promo_preserve_concurrent_projects). Note: services/project_service.py and cli/commands/project.py still perform separate unlocked load_config/save_config sequences and were left untouched here to keep this PR tightly scoped.
  4. Error contract & CLA note: Preserved _mutate_config_locked (propagating ValueError and filelock.Timeout) for add_project/remove_project/set_default_project rather than changing them to swallow errors via update_config. Note that the license/cla check still requires manual CLAassistant browser approval by the repo owner account (@aloneangel45).

Verification on Windows after final edits: ruff format --check and ruff check passed on all 4 modified files; pytest across tests/cli/test_cloud_promo.py, tests/cli/test_config_command.py, tests/test_config_locking.py, tests/test_config.py, tests/test_config_env_overrides_not_persisted.py, tests/test_config_load_side_effects.py, and tests/test_config_save_reports_failure.py ran with 202 passed, 1 skipped (running under a lightweight HOME/BASIC_MEMORY_HOME isolation shim because testcontainers is not installed in this local environment).

@Flynn-Kawolsky

Copy link
Copy Markdown

Thanks for the quick follow-up in 37e4017 — the _replace_with_windows_retry helper, deep-copy _CONFIG_CACHE isolation, and promo.py / config.py update_config wiring are much cleaner.

Two concrete edge cases I found while reviewing and testing 37e4017 on Windows 11:

  1. src/basic_memory/cli/commands/config.py (typer.Exit logging + swallowed write errors):

    • typer.Exit subclasses RuntimeError (Exception), so raising typer.Exit(1) inside _apply() hits update_config()'s except Exception as error: logger.error(f"Failed to update config: {error}") and emits a spurious Failed to update config: 1 error log on normal validation failures (invalid value or unknown default_project).
    • Conversely, if update_config() returns a real failure (e.g. filelock.Timeout or PermissionError after retries), config_set skips if isinstance(result_err, typer.Exit), falls back to saved_value[0] (unpersisted) or getattr(config_manager.config, key) (stale/env value), and prints [green]<key> = ...[/green] with exit code 0. config_unset similarly discards update_config()'s return value and prints green success on failure.
    • Checking if result_err is not None: and exiting nonzero (matching cli/commands/project.py's set_serve_skills pattern), while keeping validation exits out of update_config()'s logger.error, would keep both logs and exit codes accurate.
  2. Unlocked ConfigManager.load_config() readers on Windows (src/basic_memory/config.py):

    • _replace_with_windows_retry protects the writer from concurrent unlocked readers, but the reverse side still fails on Windows: running the exact same 3-reader × 15-write stress pattern from test_locked_writes_survive_concurrent_unlocked_readers on Windows 11 produced transient PermissionError ([Errno 13] Permission denied) inside Path.read_text() in 4 of 5 trials (the test reader loop masks this via except OSError: pass).
    • In production, ConfigManager.load_config() reads self.config_file.read_text(encoding="utf-8") with no retry, so a transient PermissionError falls into except Exception and terminates the process with SystemExit("Error: failed to load config ... Fix or delete the file and re-run.").
    • Adding a matching brief Windows PermissionError retry helper around config_file.read_text(...) in load_config() (and tightening the reader stress test to assert zero unhandled load_config() failures) would close the reader half of the Windows race too.

Once those two are addressed and the account owner completes license/cla, this will be in great shape for maintainer CI and review.

@aloneangel45

Copy link
Copy Markdown
Author

Updated in 181bc4d (addressing review feedback from @Flynn-Kawolsky):

  1. Windows concurrent read retry (load_config): Extracted a shared _retry_windows_permission_error helper and wrapped config_file.read_text() in _read_text_with_windows_retry so concurrent unlocked readers tolerate transient Win32 PermissionError (winerror == 5) while an atomic os.replace swaps config.json; added est_read_text_with_windows_retry_recovers_from_permission_error and tightened est_locked_writes_survive_concurrent_unlocked_readers so concurrent reader subprocesses fail directly without swallowing OSError.
  2. CLI validation & save error propagation (config_set / config_unset): Moved validation failure exit out of the update_config callback via a �ool | None mutate return (skipping save_config cleanly without hitting the generic Failed to update config exception log) and checked the returned error from update_config in both config_set and config_unset so lock/save failures print an error and exit 1 instead of reporting success.

Verification run locally on Windows (Python 3.14.3; optional modules estcontainers, dateparser,
edis, and
edis_fastapi stubbed only for importing ests/conftest.py / ests/cli/conftest.py):

uff format --check &
uff check on all 4 modified files: passed (All checks passed!).

  • pytest -q tests/test_config_locking.py tests/cli/test_config_command.py tests/cli/test_cloud_promo.py tests/test_config.py tests/test_config_env_overrides_not_persisted.py tests/test_config_load_side_effects.py tests/test_config_save_reports_failure.py: 205 passed, 1 skipped.

@aloneangel45
aloneangel45 force-pushed the fix/2181-lock-config-writes branch from 181bc4d to 5edd898 Compare November 30, 2026 21:53
… in CLI

Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>
@Flynn-Kawolsky

Copy link
Copy Markdown

Thanks for turning around both fixes so quickly in 5edd898 — the shared _retry_windows_permission_error helper, tightened concurrent unlocked-reader stress test, and config_set/config_unset error-handling tests all look solid. I verified 5edd898 on Windows 11 locally: ruff check and ruff format --check are clean across all 6 files, and the 7 config test suites pass (205 passed, 1 skipped).

One quick CI blocker I caught when running just typecheck (uv run ty check src tests test-int, enforced by .github/workflows/test.yml):

  • src/basic_memory/config.py:446 (_retry_windows_permission_error): ty reports error[invalid-return-type]: Function can implicitly return None, which is not assignable to return type _T@_retry_windows_permission_error because the for attempt in range(8): loop has no trailing return/raise (the other 5 modified files have 0 diagnostics).
  • Running 7 retry iterations in the loop followed by a final return operation() keeps the exact same 8-attempt backoff schedule and makes ty check pass:
def _retry_windows_permission_error(operation: Callable[[], _T]) -> _T:
    """Retry transient Windows sharing-violation PermissionError across concurrent readers/writers."""
    if os.name != "nt":
        return operation()
    delay = 0.002
    for _ in range(7):
        try:
            return operation()
        except PermissionError:
            time.sleep(delay)
            delay = min(delay * 2, 0.05)
    return operation()

Once that one-liner is in (and the account owner completes license/cla), everything looks green for maintainer review.

Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>
@aloneangel45

Copy link
Copy Markdown
Author

Updated _retry_windows_permission_error in e5a416b to run 7 retry attempts followed by a trailing return operation() so ty no longer infers an implicit None return while keeping the exact 8-attempt backoff schedule.

@Flynn-Kawolsky

Copy link
Copy Markdown

Thanks for the quick fix in e5a416b! Re-verified locally on Windows 11:

  • ruff check, ruff format --check, and ty check all exit 0 after the _retry_windows_permission_error update (src/basic_memory/config.py:446-457).
  • pytest across the config/locking and CLI suites (test_config_locking.py, test_config_save_reports_failure.py, test_config_command.py, test_auto_update.py, test_cloud_promo.py) passes cleanly (108 passed).

Once license/cla is completed, this looks ready for maintainer review. LGTM!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] save_basic_memory_config() performs unlocked read-modify-write on config.json across concurrent MCP processes

3 participants