Skip to content

[track-state] Synchronize access to WeakHashMap cache #939

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2025
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## master (unreleased)

* [#939](https://github.com/clojure-emacs/cider-nrepl/pull/939): Tracker: synchronize access to WeakHashMap cache to prevent infinite loops.

## 0.55.6 (2025-04-28)

* Bump `orchard` to [0.34.3](https://github.com/clojure-emacs/orchard/blob/master/CHANGELOG.md#0343-2025-04-28).
Expand Down
36 changes: 19 additions & 17 deletions src/cider/nrepl/middleware/track_state.clj
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@
(defn- get-metadata-if-changed?
[^Var the-var, ^WeakHashMap real-metadata-ns-cache]
(let [var-name (.sym the-var)
;; WHM is not thread-safe but we should only access this from a single
;; (session) thread.
cached-meta (some-> real-metadata-ns-cache (.get var-name))
current-meta (meta the-var)]
(when-not (identical? cached-meta current-meta)
Expand Down Expand Up @@ -116,23 +114,27 @@
[the-ns]
(let [ns-sym (ns-name the-ns)
old-project-ns-map (:interns (get *old-project-state* ns-sym))
real-metadata-whm (when *real-metadata-cache*
real-metadata-whm (if *real-metadata-cache*
(or (@*real-metadata-cache* ns-sym)
((swap! *real-metadata-cache* assoc ns-sym
(WeakHashMap.)) ns-sym)))]
(reduce-kv (fn [acc sym the-var]
(if (and (var? the-var)
(not (identical? (.ns ^Var the-var)
clojure-core)))
(let [old-meta (get old-project-ns-map sym)
new-meta (compute-var-meta the-var real-metadata-whm
old-project-ns-map)]
(if (identical? old-meta new-meta)
acc
(assoc acc sym new-meta)))
acc))
old-project-ns-map
(ns-map the-ns))))
(WeakHashMap.)) ns-sym))
(WeakHashMap.))]
;; WHM is not thread-safe, so synchronize the access to it to avoid infinite
;; loops like https://github.com/clojure-emacs/cider-nrepl/issues/936.
(locking real-metadata-whm
(reduce-kv (fn [acc sym the-var]
(if (and (var? the-var)
(not (identical? (.ns ^Var the-var)
clojure-core)))
(let [old-meta (get old-project-ns-map sym)
new-meta (compute-var-meta the-var real-metadata-whm
old-project-ns-map)]
(if (identical? old-meta new-meta)
acc
(assoc acc sym new-meta)))
acc))
old-project-ns-map
(ns-map the-ns)))))

(def clojure-core-map
(when clojure-core
Expand Down