The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Name module cycles and fail when they merge (#82386)
Chris Trutere902d2623c7b
diff --git a/.claude/skills/name-module-cycle/SKILL.md b/.claude/skills/name-module-cycle/SKILL.mdnew file mode 100644index 00000000000..2cd5669d907--- /dev/null+++ b/.claude/skills/name-module-cycle/SKILL.md@@ -0,0 +1,79 @@+---+name: name-module-cycle+description: Suggest a space-themed name for a cyclic cluster of backend modules when metabase.core.module-cycles-test reports a cluster without a name, usually after a split. Use when someone needs to name a module cycle or add a line to .clj-kondo/config/modules/cycle-clusters.edn.+allowed-tools: Read, Grep, Glob, Bash+---++# Name a module cycle++`.clj-kondo/config/modules/cycle-clusters.edn` maps each cyclic cluster of the module require graph to an anchor+module. When a change splits a cluster, the new half has no name, and the person who split it gets to choose one.+Help them choose; do not pick for them.++## 1. See the cluster++The test failure lists the cluster's modules and, for a small cluster, the requires between them that make it a+cycle. For the full picture, including teams, run:++```bash+clojure -X:dev dev.module-cycles/print-clusters+```++Unnamed clusters print first.++## 2. Split, or a new cycle?++Look at everything the branch changes, committed or not: `git diff $(git merge-base origin/master HEAD)`, plus new+files from `git ls-files --others --exclude-standard`.+If it removed requires and these modules were part of a named cluster on master, the cluster split: name the new+half. If it added a require between these modules, it created a new cycle: help break it instead, and stop here.++## 3. Learn what the cluster does++A module's namespaces are `metabase.<module>.*`, with dashes as underscores in the path, so `cloud-migration` lives+in `src/metabase/cloud_migration/`, and `enterprise/foo` in `enterprise/backend/src/metabase_enterprise/foo/`. Some+modules declare an `:ns-prefix` in `.clj-kondo/config/modules/config.edn` instead: `core.cmd` lives in+`src/metabase/cmd/`, and `mcp.oauth-server` in `src/metabase/oauth_server/`.++`core.clj` is often a bare facade. The `ns` docstrings of `api.clj`, `models/` and any `README.md` usually say more,+and so do the requires that close the cycle: they show what each module needs from the others.++## 4. Suggest names++Offer three to five names, each with one line on why it fits. A good name:++- comes from space: astronomy, spaceflight, or science fiction about space;+- has some link to what the cluster does, its role in the codebase, or how it came to be;+- is a lowercase kebab-case simple symbol, not already in the file;+- stays true as the cluster changes, so avoid sizes and counts (`binary-star` stops fitting when a third module joins).++The current names show the range:++| Name | Anchor | Why it fits |+|---|---|---|+| `galactic-center` | `query-processor` | The dense core everything orbits |+| `foundation` | `app-db` | The base layer, and Asimov's Foundation |+| `tardis` | `lib` | A plain box from the outside; internally complex, and it can take you places |+| `stargate` | `api-routes` | The gateway every request comes through |+| `first-contact` | `mcp` | The protocol outside agents use to talk to Metabase |+| `deep-thought` | `metabot` | The computer built to answer the big question |++The `<anchor>-knot` placeholder from the test failure is a valid fallback when nothing better comes up.++## 5. Pick the anchor++The anchor can be any module in the cluster, and the name follows it. Prefer one that is central and unlikely to+leave the cluster or be renamed. The test proposes the member with the most requires to and from the rest of the+cluster, ties broken alphabetically; in a small cluster everything often ties, and then the proposal carries no+signal.++## 6. Record it++Add `<name> <anchor>` to the map in `.clj-kondo/config/modules/cycle-clusters.edn`, keeping the entries sorted and+the anchors aligned one space past the longest name, then run:++```bash+./bin/test-agent :only '[metabase.core.module-cycles-test]'+```++Mention the new name in the PR, so reviewers see the split.diff --git a/.clj-kondo/config/modules/cycle-clusters.edn b/.clj-kondo/config/modules/cycle-clusters.ednnew file mode 100644index 00000000000..8cf33eddc4d--- /dev/null+++ b/.clj-kondo/config/modules/cycle-clusters.edn@@ -0,0 +1,11 @@+;; Named cyclic clusters of the module require graph: cluster name => anchor module.+;; The cluster holding the anchor carries the name; its members are computed, so it can grow and shrink freely.+;; The test metabase.core.module-cycles-test fails until every cluster holds exactly one anchor.+;; When a cluster splits, whoever split it names the new half.+;; Names follow a space theme with some link to what the cluster does; the name-module-cycle skill helps pick one.+{deep-thought metabot+ first-contact mcp+ foundation app-db+ galactic-center query-processor+ stargate api-routes+ tardis lib}diff --git a/.github/file-paths.yaml b/.github/file-paths.yamlindex 3e34bc3d704..3925f62f890 100644--- a/.github/file-paths.yaml+++ b/.github/file-paths.yaml@@ -197,6 +197,7 @@ project_backend_checks:- "{resources,test_resources,test_config}/**/*.{clj,cljc,cljs}"- ".clj-kondo/config.edn"- ".clj-kondo/config/modules/config.edn"+ - ".clj-kondo/config/modules/cycle-clusters.edn"- ".github/team.json"- "dev/resources/dev/modules_config_test/**"diff --git a/.github/scripts/file-paths.unit.spec.ts b/.github/scripts/file-paths.unit.spec.tsindex 7e88bab7e08..62db9f746ce 100644--- a/.github/scripts/file-paths.unit.spec.ts+++ b/.github/scripts/file-paths.unit.spec.ts@@ -182,4 +182,13 @@ describe("file-paths.yaml", () => {])("runs CI-script tests when %s changes", (file) => {expect(matches("ci_scripts", file)).toBe(true);});++ it("runs the module cycles test when a cluster is named", () => {+ expect(+ matches(+ "project_backend_checks",+ ".clj-kondo/config/modules/cycle-clusters.edn",+ ),+ ).toBe(true);+ });});diff --git a/CLAUDE.md b/CLAUDE.mdindex c51a5f70bd3..7f78f02e807 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -115,6 +115,16 @@ Explain budget increases in the PR. Do not record reductions in feature PRs: posa `Tighten ratchets` PR for them. Use `./bin/mage kondo-ratchets-shrink --seed :linter` only when adding aninline-ignore budget. If any ratchet file conflicts, run `./bin/merge-kondo-ratchets`.+`.clj-kondo/config/modules/cycle-clusters.edn` names each cyclic cluster (strongly connected component) of the module+require graph by an anchor module: the cluster holding the anchor carries the name, and its members are computed,+so a named cluster can grow and shrink without an edit. The big one is `galactic-center`. Names follow a space+theme; the `name-module-cycle` skill helps pick one.++The test `metabase.core.module-cycles-test` fails until every cluster holds exactly one anchor. When you split a+cluster, name the new half: the failure proposes a name and anchor to add. When two named clusters merge, find+another way; the failure shows the requires joining them. When an anchor leaves every cycle, anchor its name on+another member if the cluster survives, or remove the line.+## Tool PreferencesIf `clojure-mcp` tools are available, prefer them over shell-based alternatives for Clojure development.diff --git a/dev/src/dev/module_cycles.clj b/dev/src/dev/module_cycles.cljnew file mode 100644index 00000000000..07a247e5d8b--- /dev/null+++ b/dev/src/dev/module_cycles.clj@@ -0,0 +1,296 @@+(ns dev.module-cycles+ "Named cyclic clusters of the module require graph.++ The file at [[clusters-file]] names each cluster by an anchor module: the cluster holding it carries the name.+ Membership is computed, never recorded, so a cluster can grow or shrink without an edit.+ Every cluster must hold exactly one anchor.+ Two anchors in one cluster mean two named clusters merged.+ A cluster without one is a new cycle or the unnamed half of a split.+ An anchor in no cluster names a cycle that is gone."+ (:require+ [clojure.edn :as edn]+ [clojure.java.io :as io]+ [clojure.string :as str]+ [dev.deps-graph :as deps-graph]+ [hooks.common.modules :as modules]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(def clusters-file+ "The file of cluster names, relative to the repo root."+ ".clj-kondo/config/modules/cycle-clusters.edn")++;;;; =============================================================================+;;;; Reading the names+;;;; =============================================================================++(defn- read-form+ "The one EDN form in the file at `path`. Throws when the file is empty or holds a second form."+ [path]+ (with-open [reader (java.io.PushbackReader. (io/reader path))]+ (let [eof (Object.)+ form (edn/read {:eof eof} reader)]+ (when (identical? eof form)+ (throw (ex-info (str path " is empty; expected a map of cluster name to anchor module")+ {:file path})))+ (when-not (identical? eof (edn/read {:eof eof} reader))+ (throw (ex-info (str path " holds more than one form; expected one map")+ {:file path})))+ form)))++(defn validate-anchors+ "Return `anchors` if it maps simple-symbol names to module symbols, no module anchoring two; throw otherwise."+ [anchors]+ (when-not (map? anchors)+ (throw (ex-info (str clusters-file " must hold a map of cluster name to anchor module, not " (pr-str anchors))+ {:anchors anchors})))+ (doseq [[cluster-name anchor] anchors]+ (when-not (simple-symbol? cluster-name)+ (throw (ex-info (format "%s is not a cluster name; names are simple symbols" (pr-str cluster-name))+ {:cluster cluster-name})))+ (when-not (symbol? anchor)+ (throw (ex-info (format "%s must be anchored by a module symbol, not %s" cluster-name (pr-str anchor))+ {:cluster cluster-name, :anchor anchor}))))+ (doseq [[anchor names] (group-by val anchors)+ :when (< 1 (count names))]+ (throw (ex-info (format "%s anchors more than one cluster: %s" anchor (str/join ", " (sort (map key names))))+ {:anchor anchor, :clusters (sort (map key names))})))+ anchors)++(defn read-anchors+ "Parsed and validated contents of the file at `path`, [[clusters-file]] by default."+ ([]+ (read-anchors clusters-file))+ ([path]+ (when-not (.exists (io/file path))+ (throw (ex-info (str path " is missing") {:file path})))+ (validate-anchors (read-form path))))++;;;; =============================================================================+;;;; Finding problems+;;;; =============================================================================++(defn- degree+ "How many edges of `graph` inside `cluster` touch `module`."+ [graph cluster module]+ (+ (count (filter cluster (get graph module)))+ (count (filter #(contains? (get graph %) module) cluster))))++(defn propose+ "A placeholder `{:name :anchor}` for an unnamed `cluster` of `graph`, avoiding the names in `taken`.+ Nil when no member of the cluster is among `modules`.+ The anchor is the member among `modules` with the most requires inside the cluster, ties broken alphabetically.+ The name comes from the anchor, so `enterprise/transforms.python` gives `enterprise-transforms-python-knot`."+ [graph modules cluster taken]+ (when-let [members (seq (filter modules cluster))]+ (let [anchor (first (sort-by (juxt #(- (degree graph cluster %)) str) members))+ stem (str (str/replace (str anchor) #"[/.]" "-") "-knot")+ names (cons stem (map #(str stem "-" %) (iterate inc 2)))]+ {:name (symbol (first (remove (comp (set taken) symbol) names)))+ :anchor anchor})))++(defn- proposals+ "Map each of the `unnamed` clusters to its [[propose]] result, no two placeholders sharing a name."+ [graph modules anchors unnamed]+ (first (reduce (fn [[acc taken] cluster]+ (let [p (propose graph modules cluster taken)]+ [(assoc acc cluster p) (cond-> taken p (conj (:name p)))]))+ [{} (set (keys anchors))]+ unnamed)))++(defn- shortest-path+ "The shortest chain of requires from `from` to `to` that stays inside `cluster`, as a vector of modules."+ [graph cluster from to]+ (loop [frontier (conj clojure.lang.PersistentQueue/EMPTY [from])+ seen #{from}]+ (when-let [path (peek frontier)]+ (if (= (peek path) to)+ path+ (let [nexts (remove seen (filter cluster (sort (get graph (peek path)))))]+ (recur (into (pop frontier) (map #(conj path %)) nexts)+ (into seen nexts)))))))++(defn- requires-within+ "The requires between members of `cluster`, as sorted `[from to]` pairs."+ [graph cluster]+ (vec (for [from (sort cluster)+ to (sort (filter cluster (get graph from)))]+ [from to])))++(defn- names-in+ "A function of a cluster returning the `[name anchor]` pairs inside it, sorted by name.+ Only anchors among `modules` count."+ [modules anchors]+ (let [anchor->name (u/for-map [[cluster-name anchor] anchors+ :when (modules anchor)]+ [anchor cluster-name])]+ (fn [cluster]+ (sort (for [module cluster+ :let [cluster-name (anchor->name module)]+ :when cluster-name]+ [cluster-name module])))))++(defn- merge-problem+ "The `:merge` problem for `cluster`, which holds the `named` `[name anchor]` pairs."+ [graph cluster named]+ (let [[[name-a anchor-a] & others] named]+ {:type :merge+ :cluster cluster+ :names (mapv first named)+ :chains (vec (for [[name-b anchor-b] others+ [from to from-anchor to-anchor] [[name-a name-b anchor-a anchor-b]+ [name-b name-a anchor-b anchor-a]]]+ {:from from, :to to, :path (shortest-path graph cluster from-anchor to-anchor)}))}))++(defn problems+ "Every way the cyclic clusters of `graph` disagree with the cluster names in `anchors`, as maps keyed by `:type`.+ Empty when each cluster holds exactly one anchor, and each anchor is among `modules` and in a cluster.++ - `:merge`, two or more named clusters in one cycle: `:cluster`, `:names`, and `:chains` of `{:from :to :path}`+ linking the first name's anchor to each other's, both ways+ - `:unnamed`, a cluster with no name: `:cluster`, its `:requires` as `[from to]` pairs, and a [[propose]]+ `:proposal`, nil when none of its modules is among `modules`+ - `:anchor-left`, a name whose anchor is in no cycle: `:name`, `:anchor`+ - `:undeclared-anchor`, a name anchored on a module not among `modules`: `:name`, `:anchor`"+ [graph modules anchors]+ (let [components (deps-graph/cyclic-components graph)+ clusters (map (juxt identity (names-in modules anchors)) components)+ in-any (into #{} cat components)+ undeclared (into #{} (remove modules) (vals anchors))+ ;; A cluster holding an undeclared anchor already has a name waiting on it, so it gets only that problem.+ unnamed (keep (fn [[cluster named]]+ (when (and (empty? named) (not-any? undeclared cluster))+ cluster))+ clusters)+ placeholders (proposals graph modules anchors unnamed)]+ (vec (concat+ (for [[cluster named] clusters+ :when (< 1 (count named))]+ (merge-problem graph cluster named))+ (for [cluster unnamed]+ {:type :unnamed+ :cluster cluster+ :requires (requires-within graph cluster)+ :proposal (placeholders cluster)})+ (keep (fn [[cluster-name anchor]]+ (cond+ (not (modules anchor)) {:type :undeclared-anchor, :name cluster-name, :anchor anchor}+ (not (in-any anchor)) {:type :anchor-left, :name cluster-name, :anchor anchor}))+ (sort-by key anchors))))))++;;;; =============================================================================+;;;; Messages+;;;; =============================================================================++(defn- module-list+ "The sorted `modules` on one line, cut off after eight."+ [modules]+ (let [sorted (sort modules)+ shown (take 8 sorted)]+ (str (str/join ", " shown)+ (when (< (count shown) (count sorted))+ (format " (and %d more)" (- (count sorted) (count shown)))))))++(defn- requires-lines+ "The `requires` of `cluster` as indented `from -> to` lines, or nil for a cluster of more than ten modules."+ [cluster requires]+ (when (<= (count cluster) 10)+ (for [[from to] requires]+ (str " " from " -> " to))))++(defn- merge-lines [{:keys [cluster names chains]}]+ (concat+ [(format "%s merged into one cycle of %d modules." (str/join " and " names) (count cluster))+ (str " This undoes the work that kept them apart, and the merged tangle is hard to cut apart again."+ " Please find another way.")]+ (for [{:keys [from to path]} chains]+ (format " %s reaches %s through %s" from to (str/join " -> " path)))+ [(str " The require that joined them is most likely on one of these chains, probably one your change added."+ " Cut it, for example by moving the code that needs it, or by inverting the dependency with an event or"+ " a multimethod.")+ (str " If instead only an anchor moved, and the cluster it left is still a cycle, anchor that name on a module"+ " still in it.")+ (str " Only if there is truly no way around it: remove all but one of the names from "+ clusters-file " and explain why in the PR.")]))++(defn- unnamed-lines [{:keys [cluster requires proposal]}]+ (concat+ [(format "A cluster without a name: %d modules, %s." (count cluster) (module-list cluster))]+ (when-let [lines (seq (requires-lines cluster requires))]+ (cons " It is a cycle through these requires:" lines))+ [(str " If your change split a cluster in two, that is a real improvement: thank you."+ " You get to name the new one.")+ (str " Names follow a space theme, with some link to what the cluster does. For ideas, ask your agent to use"+ " the name-module-cycle skill in .claude/skills/name-module-cycle.")+ (if-let [{:keys [name anchor]} proposal]+ (format " Then add a line like `%s %s` to %s. Any declared member can be the anchor." name anchor+ clusters-file)+ (str " None of its modules is declared in .clj-kondo/config/modules/config.edn yet. Add an entry with a :team"+ " for each, run `./bin/mage fix-modules-config` to fill in the rest, then anchor the name on one of them."))+ " If this is a brand new cycle instead, break it rather than naming it."]))++(defn- anchor-left-lines [{cluster-name :name, :keys [anchor]}]+ [(format "%s is anchored on %s, which is no longer in any cycle." cluster-name anchor)+ (str " If the rest of the cluster is still a cycle, reported above without a name, keep the name and anchor it"+ " on one of its modules instead.")+ (format " Otherwise the cycle is gone. Nice work. Remove its line from %s to retire the name." clusters-file)])++(defn- undeclared-anchor-lines [{cluster-name :name, :keys [anchor]}]+ [(format (str "%s is anchored on %s, which is not a declared module. Declare it in"+ " .clj-kondo/config/modules/config.edn, or anchor the name on a declared module in %s.")+ cluster-name anchor clusters-file)])++(defn message+ "The failure message for one of the [[problems]]."+ [problem]+ (str/join "\n" ((case (:type problem)+ :merge merge-lines+ :unnamed unnamed-lines+ :anchor-left anchor-left-lines+ :undeclared-anchor undeclared-anchor-lines)+ problem)))++;;;; =============================================================================+;;;; The repository+;;;; =============================================================================++(defn- repository+ "The module config, require graph, configured modules and cluster names of the current tree."+ []+ (let [config (deps-graph/kondo-config)]+ {:config config+ :graph (deps-graph/module-dependencies (deps-graph/dependencies (modules/build-prefix->module config)))+ :modules (set (keys config))+ :anchors (read-anchors)}))++(defn report+ "The failure messages for the [[problems]] between the current tree's module require graph and [[clusters-file]]."+ []+ (let [{:keys [graph modules anchors]} (repository)]+ (mapv message (problems graph modules anchors))))++(defn print-clusters+ "Print every cyclic cluster of the module require graph with its name, anchor, teams and members, unnamed first.+ Run it with `clojure -X:dev dev.module-cycles/print-clusters`."+ [_]+ (let [{:keys [config graph modules anchors]} (repository)+ named-in (names-in modules anchors)+ ;; Unnamed clusters first: they are the ones someone is here to name.+ clusters (sort-by #(boolean (seq (named-in %))) (deps-graph/cyclic-components graph))+ placeholders (proposals graph modules anchors (remove (comp seq named-in) clusters))]+ (doseq [cluster clusters+ :let [named (named-in cluster)]]+ (println (if (seq named)+ (str/join " + " (map (fn [[n m]] (format "%s (anchor %s)" n m)) named))+ (if-let [{:keys [name anchor]} (placeholders cluster)]+ (format "unnamed (placeholder %s, anchor %s)" name anchor)+ "unnamed (no declared module to anchor on)")))+ (println (format " %d modules, teams: %s" (count cluster)+ (str/join ", " (sort (distinct (keep #(get-in config [% :team]) cluster))))))+ (doseq [module (sort cluster)]+ (println (str " " module)))+ (when-let [lines (and (empty? named) (seq (requires-lines cluster (requires-within graph cluster))))]+ (println " requires:")+ (run! println lines))+ (println))))diff --git a/dev/test/metabase/core/module_cycles_test.clj b/dev/test/metabase/core/module_cycles_test.cljnew file mode 100644index 00000000000..070aef27186--- /dev/null+++ b/dev/test/metabase/core/module_cycles_test.clj@@ -0,0 +1,172 @@+(ns metabase.core.module-cycles-test+ (:require+ [clojure.java.io :as io]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [dev.kondo-ratchet :as kondo-ratchet]+ [dev.module-cycles :as module-cycles]))++(set! *warn-on-reflection* true)++(def ^:private graph+ "Two cycles, `qp <-> sync` and `app-db <-> settings`, joined one way by `sync -> settings`."+ {'app-db #{'settings}+ 'qp #{'sync}+ 'settings #{'app-db}+ 'sync #{'qp 'settings}})++(def ^:private modules+ (set (keys graph)))++(def ^:private anchors+ '{foundation app-db, galactic-center qp})++(defn- ring+ "A graph in which `modules` require each other in a single loop."+ [modules]+ (zipmap modules (map hash-set (rest (cycle modules)))))++(defn- lines [problem]+ (str/split-lines (module-cycles/message problem)))++(deftest ^:parallel passing-structures-test+ (testing "each cluster holding one anchor passes"+ (is (= [] (module-cycles/problems graph modules anchors))))+ (testing "a named cluster can gain a module"+ (is (= [] (module-cycles/problems (assoc graph 'qp #{'sync 'lib}, 'lib #{'qp}) (conj modules 'lib) anchors)))))++(deftest ^:parallel merges-fail-test+ (testing "a merge shows the requires linking the two anchors, both ways"+ (is (=? [{:type :merge+ :names '[foundation galactic-center]+ :chains [{:from 'foundation, :to 'galactic-center, :path '[app-db settings qp]}+ {:from 'galactic-center, :to 'foundation, :path '[qp sync settings app-db]}]}]+ (module-cycles/problems (assoc graph 'settings #{'app-db 'qp}) modules anchors))))+ (testing "a three-way merge links the first name to each of the others"+ (let [graph (assoc graph 'settings #{'app-db 'qp}, 'lib #{'qp}, 'qp #{'sync 'lib})+ anchors (assoc anchors 'tardis 'lib)+ [merge] (module-cycles/problems graph (conj modules 'lib) anchors)]+ (is (= '[[foundation galactic-center] [galactic-center foundation] [foundation tardis] [tardis foundation]]+ (map (juxt :from :to) (:chains merge)))))))++(deftest ^:parallel unnamed-clusters-fail-test+ (testing "a tie for the most requires inside the cluster proposes the alphabetically first member"+ (is (= [{:type :unnamed+ :cluster '#{qp sync}+ :requires '[[qp sync] [sync qp]]+ :proposal '{:name qp-knot, :anchor qp}}]+ (module-cycles/problems graph modules '{foundation app-db}))))+ (testing "a proposal avoids the names already taken"+ (is (=? [{:type :unnamed, :proposal '{:name qp-knot-2}}+ {:type :anchor-left, :name 'qp-knot}]+ (module-cycles/problems graph (conj modules 'lib) '{foundation app-db, qp-knot lib}))))+ (testing "two proposals never share a name"+ (let [graph (merge (ring '[foo.bar x]) (ring '[foo-bar y]))]+ (is (= '#{foo-bar-knot foo-bar-knot-2}+ (set (map (comp :name :proposal) (module-cycles/problems graph (set (keys graph)) {})))))))+ (testing "dots and slashes in a module name become dashes"+ (is (= 'enterprise-transforms-python-knot+ (:name (module-cycles/propose (ring '[enterprise/transforms.python x])+ '#{enterprise/transforms.python x}+ '#{enterprise/transforms.python x}+ #{})))))+ (testing "a proposal only anchors on a declared module"+ (is (=? [{:type :unnamed, :proposal '{:anchor sync}}]+ (module-cycles/problems graph (disj modules 'qp) '{foundation app-db}))))+ (testing "a cycle of undeclared modules gets no proposal"+ (is (=? [{:type :unnamed, :proposal nil}]+ (module-cycles/problems graph (disj modules 'qp 'sync) '{foundation app-db})))))++(deftest ^:parallel anchors-leaving-every-cycle-test+ (testing "a cycle that is gone leaves its anchor behind"+ (is (= [{:type :anchor-left, :name 'galactic-center, :anchor 'qp}]+ (module-cycles/problems (assoc graph 'sync #{'settings}) modules anchors))))+ (testing "an anchor that left a surviving cycle is reported alongside the cycle it left"+ (is (=? [{:type :unnamed, :cluster '#{lib sync}}+ {:type :anchor-left, :anchor 'qp}]+ (module-cycles/problems (assoc graph 'qp #{}, 'sync #{'lib}, 'lib #{'sync}) (conj modules 'lib) anchors)))))++(deftest ^:parallel undeclared-anchors-test+ (testing "an undeclared anchor outside every cycle leaves its cluster unnamed"+ (is (=? [{:type :unnamed, :cluster '#{qp sync}}+ {:type :undeclared-anchor, :name 'galactic-center, :anchor 'query-processor}]+ (module-cycles/problems graph modules '{foundation app-db, galactic-center query-processor}))))+ (testing "an undeclared anchor inside a cycle is the only problem for that cycle"+ (is (= [{:type :undeclared-anchor, :name 'galactic-center, :anchor 'qp}]+ (module-cycles/problems graph (disj modules 'qp) anchors)))))++(deftest ^:parallel names-file-test+ (testing "malformed names throw"+ (are [anchors msg] (thrown-with-msg? clojure.lang.ExceptionInfo msg (module-cycles/validate-anchors anchors))+ '[foundation app-db] #"must hold a map"+ '{:foundation app-db} #"not a cluster name"+ '{foundation "app-db"} #"must be anchored by a module symbol"+ '{foundation app-db, other app-db} #"app-db anchors more than one cluster: foundation, other"))+ (testing "a file must hold exactly one form"+ (let [file (io/file (System/getProperty "java.io.tmpdir") (str "cycle-clusters-" (System/nanoTime) ".edn"))]+ (try+ (are [contents msg] (thrown-with-msg? clojure.lang.ExceptionInfo msg+ (do (spit file contents)+ (module-cycles/read-anchors (.getPath file))))+ ";; nothing\n" #"is empty"+ "{a app-db}\n{b qp}\n" #"more than one form")+ (finally+ (io/delete-file file true)))))+ (testing "a missing file throws"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"is missing"+ (module-cycles/read-anchors "no/such/cycle-clusters.edn")))))++(deftest ^:parallel messages-test+ (testing "a merge names the clusters, shows the chains, and keeps removing a name as the last resort"+ (let [msg (lines {:type :merge+ :cluster '#{app-db qp settings sync}+ :names '[foundation galactic-center]+ :chains [{:from 'foundation, :to 'galactic-center, :path '[app-db settings qp]}]})]+ (is (= "foundation and galactic-center merged into one cycle of 4 modules." (first msg)))+ (is (some #{" foundation reaches galactic-center through app-db -> settings -> qp"} msg))+ (is (re-find #"remove all but one of the names" (last msg)))))+ (testing "an unnamed cluster lists its requires and the line to add"+ (let [msg (lines {:type :unnamed+ :cluster '#{qp sync}+ :requires '[[qp sync] [sync qp]]+ :proposal '{:name qp-knot, :anchor qp}})]+ (is (=? ["A cluster without a name: 2 modules, qp, sync."+ " It is a cycle through these requires:"+ " qp -> sync"+ " sync -> qp"]+ (take 4 msg)))+ (is (some #(str/includes? % "You get to name the new one") msg))+ (is (some #(str/includes? % "add a line like `qp-knot qp`") msg))))+ (testing "an unnamed cluster without a proposal asks for its modules to be declared"+ (is (some #(str/includes? % "None of its modules is declared")+ (lines {:type :unnamed, :cluster '#{qp sync}, :requires [], :proposal nil}))))+ (testing "a large cluster is cut off after eight modules, and its requires are not listed"+ (let [members (mapv #(symbol (format "m%02d" %)) (range 11))+ msg (lines {:type :unnamed+ :cluster (set members)+ :requires (mapv vector members (rest (cycle members)))+ :proposal '{:name m00-knot, :anchor m00}})]+ (is (re-find #"11 modules, m00, .*, m07 \(and 3 more\)\.$" (first msg)))+ (is (not-any? #(str/includes? % "It is a cycle through") msg))))+ (testing "a small cluster lists its requires however many there are"+ (let [members '[a b c d e]+ msg (lines {:type :unnamed+ :cluster (set members)+ :requires (vec (for [from members, to members :when (not= from to)] [from to]))+ :proposal '{:name a-knot, :anchor a}})]+ (is (= 20 (count (filter #(str/includes? % " -> ") msg))))))+ (testing "an anchor that left every cycle asks for the name to move or retire"+ (let [msg (lines {:type :anchor-left, :name 'galactic-center, :anchor 'qp})]+ (is (= "galactic-center is anchored on qp, which is no longer in any cycle." (first msg)))+ (is (re-find #"Remove its line" (last msg)))))+ (testing "an undeclared anchor asks for the module to be declared or the name moved"+ (is (re-find #"^galactic-center is anchored on qp, which is not a declared module\. Declare it"+ (module-cycles/message {:type :undeclared-anchor, :name 'galactic-center, :anchor 'qp})))))++(deftest module-cycles-test+ ;; Release branches disable the ratchets, and their structure is frozen with them.+ (when-not (kondo-ratchet/disabled?)+ (let [problems (module-cycles/report)]+ (is (empty? problems)+ (str "Every cyclic cluster of the module require graph holds exactly one anchor from "+ module-cycles/clusters-file ".\n\n" (str/join "\n\n" problems))))))diff --git a/mage/src/mage/project_tests.clj b/mage/src/mage/project_tests.cljindex 02c5bc89700..10292f91a6e 100644--- a/mage/src/mage/project_tests.clj+++ b/mage/src/mage/project_tests.clj@@ -9,6 +9,7 @@(def ^:private module-check-namespaces'[dev.modules-config-test+ metabase.core.module-cycles-testmetabase.core.modules-test])(def ^:private honey-sql-check-namespacesdiff --git a/mage/test/mage/project_tests_test.clj b/mage/test/mage/project_tests_test.cljindex 202b94c3474..dc55f7f9c9a 100644--- a/mage/test/mage/project_tests_test.clj+++ b/mage/test/mage/project_tests_test.clj@@ -44,6 +44,7 @@(is (= [["clojure" "-M:test"]["clojure" "-X:dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:ci" ":only"(str '[dev.modules-config-test+ metabase.core.module-cycles-testmetabase.core.modules-testmetabase.core.kondo-ratchet-testmetabase.core.kondo-ratchet-check-test@@ -92,7 +93,7 @@(deftest targeted-suites-test(testing "modules runs only its own namespaces"(is (= [["clojure" "-X:dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:ci" ":only"- "[dev.modules-config-test metabase.core.modules-test]"]]+ "[dev.modules-config-test metabase.core.module-cycles-test metabase.core.modules-test]"]](:calls (run-suites! [] ["modules"])))))(testing "ratchets checks the repository's policy file"(is (= [["./bin/mage" "kondo-ratchets"]]