Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

CLI for Data Complexity Score (#72768)

Chris Truter25c3ea297249
diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/cli.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/cli.clj
new file mode 100644
index 00000000000..cbc028dfaa5
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/cli.clj
@@ -0,0 +1,97 @@
+(ns metabase-enterprise.data-complexity-score.cli
+ "CLI entrypoint for computing the data complexity score against on-disk representations.
+
+ Useful for offline scoring of benchmarks, CI, and exploratory analysis.
+
+ Invoke via:
+
+ clojure -M:ee:dev -m metabase-enterprise.data-complexity-score.cli \\
+ --representation-dir path/to/fixture/
+
+ Patterned after [[metabase-enterprise.checker.cli]] — same `fail!` pattern, same arg style."
+ (:require
+ [clojure.java.io :as io]
+ [clojure.pprint :as pprint]
+ [clojure.tools.cli :as cli]
+ [metabase-enterprise.data-complexity-score.complexity :as complexity]
+ [metabase-enterprise.data-complexity-score.representation :as representation]))
+
+(set! *warn-on-reflection* true)
+
+#_{:clj-kondo/ignore [:discouraged-var]}
+(def ^:private output!
+ "Alias for println so the lint suppression stays in one place."
+ println)
+
+(defn- fail!
+ "Print an error to stderr and exit 1."
+ [& messages]
+ (binding [*out* *err*]
+ (doseq [msg messages] (output! msg)))
+ (flush)
+ (System/exit 1))
+
+(defn- validate-dir! [path]
+ (let [f (io/file path)]
+ (cond
+ (not (.exists f)) (throw (ex-info (str "--representation-dir does not exist: " path)
+ {:cli-validation true :path path}))
+ (not (.isDirectory f)) (throw (ex-info (str "--representation-dir must be a directory: " path)
+ {:cli-validation true :path path})))))
+
+(def ^:private cli-options
+ [["-r" "--representation-dir PATH" "Directory of a serdes YAML export, optionally with an embeddings.json sidecar (required)."]
+ ["-e" "--embeddings PATH" "Explicit embeddings JSON file. Overrides embeddings.json in the directory."]
+ ["-o" "--output PATH" "Write EDN result to this file instead of stdout."]
+ ["-h" "--help" "Show this message."]])
+
+(defn- usage [summary]
+ (str "Usage: clojure -M:ee:dev -m metabase-enterprise.data-complexity-score.cli [options]\n\n"
+ "Options:\n" summary))
+
+(defn- pretty [result]
+ (with-out-str
+ #_{:clj-kondo/ignore [:discouraged-var]}
+ (pprint/pprint result)))
+
+(defn- write-result! [result output-path]
+ (if output-path
+ (spit output-path (pretty result))
+ (do
+ #_{:clj-kondo/ignore [:discouraged-var]}
+ (print (pretty result))
+ (flush))))
+
+(defn- run-cli
+ "Pure core of the CLI: validates options, loads representation, computes the score.
+ Returns the result map so tests can call this directly without intercepting `System/exit`.
+ Throws `ex-info` for validation failures (with `:cli-validation true` in the ex-data) and propagates
+ `load-dir`'s `ex-info` (e.g. missing `--embeddings` override). `-main` converts those into user-facing
+ `fail!`; library callers can inspect the ex-data and render errors their own way."
+ [{:keys [representation-dir embeddings]}]
+ (when-not representation-dir
+ (throw (ex-info "Missing --representation-dir option" {:cli-validation true})))
+ (validate-dir! representation-dir)
+ (let [{:keys [library universe embedder]} (representation/load-dir representation-dir :embeddings-path embeddings)]
+ (complexity/score-from-entities library universe embedder {})))
+
+;; `-main` is invoked via `clj -M:ee:dev -m …cli`, not via an AOT'd jar, so `(:gen-class)` is unnecessary.
+#_{:clj-kondo/ignore [:main-without-gen-class]}
+(defn -main
+ "Entrypoint."
+ [& args]
+ (let [{:keys [options errors summary]} (cli/parse-opts args cli-options)]
+ (cond
+ (:help options) (do (output! (usage summary)) (System/exit 0))
+ (seq errors) (apply fail! errors)
+ :else (try
+ (write-result! (run-cli options) (:output options))
+ (catch clojure.lang.ExceptionInfo e
+ ;; Handle CLI validation failures (`:cli-validation`) and missing-embeddings
+ ;; failures from representation (`:embeddings-path`) — both are user-facing
+ ;; misconfigurations rather than bugs.
+ (let [data (ex-data e)]
+ (if (or (:cli-validation data) (:embeddings-path data))
+ (fail! (ex-message e))
+ (throw e)))))))
+ (System/exit 0))
diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj
index 5eb1958f9cc..d87a08600e6 100644
--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj
@@ -420,6 +420,33 @@
true
events)))
+(defn score-from-entities
+ "Pure: compute the full complexity score from pre-built entity vectors and an embedder. No DB
+ access, no Snowplow emission — suitable for callers that have already loaded their entities
+ from another source (e.g., a representation file).
+
+ Options:
+ `:embedding-model-meta` — `{:provider ... :model-name ...}` map embedded into the response's
+ `:meta`, or nil to omit the key. Callers that know what embedding model they used should
+ pass it so benchmark consumers can pin to it.
+ `:metabot-entities` — when non-nil, scored separately as the `:metabot` catalog. When nil
+ (default), we assume this means that metabot has no additional filtering configured, and
+ reuse the `:universe` score. In the fallback case the response `:meta` includes
+ `:metabot-source :universe-fallback` so benchmark consumers recognise this scenario."
+ [library-entities universe-entities embedder {:keys [embedding-model-meta metabot-entities]}]
+ (let [universe-score (score-catalog universe-entities embedder)
+ metabot-fallback? (nil? metabot-entities)]
+ {:library (score-catalog library-entities embedder)
+ :universe universe-score
+ :metabot (if metabot-fallback?
+ universe-score
+ (score-catalog metabot-entities embedder))
+ :meta (cond-> {:formula-version formula-version
+ :synonym-threshold synonym-similarity-threshold
+ :weights weights}
+ embedding-model-meta (assoc :embedding-model embedding-model-meta)
+ metabot-fallback? (assoc :metabot-source :universe-fallback))}))
+
(defn- time-phase!
"Run `f`, record duration on the per-phase histogram labelled by `stage` and `catalog`, return its value."
[stage catalog f]
diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity_embedders.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity_embedders.clj
index c448c7eb35e..cdcaee2c4d1 100644
--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity_embedders.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity_embedders.clj
@@ -20,7 +20,6 @@
`_`, `-`, `.`, and camelCase boundaries become spaces; adjacent whitespace is collapsed and
the result is lowercased.
- Splitting happens *before* lowercasing so the camelCase boundary stays visible.
Embedding models are trained on English: `\"monthly_active_users\"` is an out-of-distribution
token while `\"monthly active users\"` hits three well-understood ones.
@@ -47,24 +46,9 @@
vectors (when (seq names) (vec (name-embed-fn names)))]
(into {} (filter val) (zipmap names vectors)))))
-(def default-text-variant
- "Which text form of each entity name gets embedded by the default synonym embedder.
-
- `:names-split` rewrites snake/kebab/dotted/camelCase names into space-separated English
- tokens before sending them to the provider — see [[split-for-embedding]].
-
- Alternatives worth considering (not implemented): `:names` (raw lowercased name),
- `:search-text` (type + name + description + schema, as the semantic-search indexer does),
- or `:typed-split` ([source|value] prefix + split name).
- The 2026-04-21 analysis shows names-split as the best default for both Arctic and MiniLM.
-
- The value rides the fingerprint so a future swap to another variant forces a re-score
- without a `formula-version` bump."
- :names-split)
-
(def ^:private ^Class floats-class
- "`float[]` class object — cached so [[ensure-floats]] can `instance?`-check without
- re-resolving on every vector."
+ "`float[]` class object — cached so callers can `instance?`-check without re-resolving on every
+ vector."
(class (float-array 0)))
(defn- ensure-floats
@@ -75,6 +59,33 @@
^floats [v]
(if (instance? floats-class v) v (float-array v)))
+(defn file-embedder
+ "Build an embedder from a pre-loaded `{name -> [float ...]}` map.
+ Keys are run through [[normalize-name]] here so callers can hand in raw display names.
+ Values may be seqs/vectors of floats or `^floats` arrays.
+ Entities whose normalized name isn't in the map get no vector — same contract as the other embedders."
+ [name->vec]
+ (let [normalized (into {}
+ (keep (fn [[k v]]
+ (when-let [n (normalize-name k)]
+ [n (ensure-floats v)])))
+ name->vec)]
+ (fn embed [_entities] normalized)))
+
+(def default-text-variant
+ "Which text form of each entity name gets embedded by the default synonym embedder.
+
+ `:names-split` rewrites snake/kebab/dotted/camelCase names into space-separated English
+ tokens before sending them to the provider — see [[split-for-embedding]].
+
+ Alternatives worth considering (not implemented):
+ - `:names` (raw lowercased name)
+ - `:search-text` (type + name + description + schema, as the semantic-search indexer does)
+ - `:typed-split` ([source|value] prefix + split name).
+
+ The 2026-04-21 analysis suggested names-split as the best default for both Arctic and MiniLM."
+ :names-split)
+
(def ^:private provider-batch-size
"Names per `get-embeddings-batch` HTTP call.
diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/representation.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/representation.clj
new file mode 100644
index 00000000000..179efd306fc
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/representation.clj
@@ -0,0 +1,246 @@
+(ns metabase-enterprise.data-complexity-score.representation
+ "Load a serdes export directory into the shape the complexity scorer expects.
+
+ Format: the official Metabase serdes/representation YAML, byte-compatible with what
+ `serdes/store` emits and what `metabase-enterprise.checker` parses.
+
+ Layout (subset that the scorer reads):
+
+ <dir>/databases/<db>/<db>.yaml (Database metadata; `is_audit: true` excludes the DB)
+ <dir>/databases/<db>/schemas/<schema>/tables/<table>/<table>.yaml
+ <dir>/databases/<db>/schemas/<schema>/tables/<table>/fields/<field>.yaml
+ <dir>/databases/<db>/schemas/<schema>/tables/<table>/measures/<measure>.yaml
+ <dir>/databases/<db>/tables/<table>/... (schema-less variant)
+ <dir>/collections/<coll>/<coll>.yaml (Collection metadata; type: library marks the root)
+ <dir>/collections/<coll>/cards/<card>.yaml
+ <dir>/embeddings.json (sidecar — not part of the serdes spec)
+
+ Library membership is derived from `Collection.type = \"library\"` plus the `parent_id` chain.
+
+ Caveats vs. the live appdb scorer in [[metabase-enterprise.data-complexity-score.complexity]]:
+ - `:metabot` catalog: requires premium-feature gates and a Metabot config row that aren't in
+ an export. The CLI flags `:metabot` as a universe fallback (see `cli/run-cli`)."
+ (:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
+ [metabase-enterprise.data-complexity-score.complexity-embedders :as embedders]
+ [metabase.collections.core :as collections]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.yaml :as yaml])
+ (:import
+ (java.io File)))
+
+(set! *warn-on-reflection* true)
+
+;;; ------------------------------------------- file walking -------------------------------------------
+
+(defn- yaml-file? [^File f]
+ (and (.isFile f) (str/ends-with? (.getName f) ".yaml")))
+
+(defn- list-dirs [^File dir]
+ (if (.isDirectory dir) (filterv #(.isDirectory ^File %) (.listFiles dir)) []))
+
+(defn- list-yamls [^File dir]
+ (if (.isDirectory dir) (filterv yaml-file? (.listFiles dir)) []))
+
+(defn- entity-model
+ "Read the serdes model name (e.g. \"Collection\", \"Card\") from a parsed YAML map.
+ Returns nil for files without a `serdes/meta` block."
+ [yaml-map]
+ (some-> yaml-map (get :serdes/meta) last :model))
+
+(defn- load-yaml [^File f]
+ (yaml/parse-string (slurp f)))
+
+;;; ------------------------------------- collections + cards -------------------------------------
+
+(defn- walk-collections-tree
+ "Walk `collections/` and bucket by serdes model.
+ Returns `{:collections [...] :cards [...]}`; everything else (Dashboard, Document, Snippet,
+ Transform, Segment, Measure) is ignored — measures live under the database tree."
+ [^File collections-dir]
+ (if (.isDirectory collections-dir)
+ (reduce
+ (fn [acc ^File f]
+ (let [parsed (load-yaml f)]
+ (case (entity-model parsed)
+ "Collection" (update acc :collections conj parsed)
+ "Card" (update acc :cards conj parsed)
+ acc)))
+ {:collections [] :cards []}
+ (filter yaml-file? (file-seq collections-dir)))
+ {:collections [] :cards []}))
+
+(defn- library-collection-ids
+ "Set of collection entity_ids in the Library subtree — root + every descendant reachable via
+ the `parent_id` chain. Empty when no library-typed collection exists."
+ [collections]
+ (if-let [root (u/seek #(= collections/library-collection-type (:type %)) collections)]
+ (let [root-eid (:entity_id root)
+ parent-of (into {} (map (juxt :entity_id :parent_id)) collections)
+ in-library? (fn [eid]
+ (loop [cur eid, seen #{}]
+ (cond
+ (= cur root-eid) true
+ (or (nil? cur) (seen cur)) false
+ :else (recur (parent-of cur) (conj seen cur)))))]
+ (into #{root-eid}
+ (keep #(when (in-library? (:entity_id %)) (:entity_id %)))
+ collections))
+ #{}))
+
+;;; ------------------------------------- tables, fields, measures -------------------------------------
+
+(defn- table-self-yaml
+ "Path to the Table's self-named `<dir>.yaml` inside `table-dir`, or nil if missing."
+ [^File table-dir]
+ (let [f (io/file table-dir (str (.getName table-dir) ".yaml"))]
+ (when (.exists f) f)))
+
+(defn- list-table-dirs
+ "All Table directories under one database — both schema-qualified and schema-less variants."
+ [^File db-dir]
+ (concat (mapcat (fn [^File schema-dir] (list-dirs (io/file schema-dir "tables")))
+ (list-dirs (io/file db-dir "schemas")))
+ (list-dirs (io/file db-dir "tables"))))
+
+(defn- database-self-yaml
+ "Path to the Database's self-named `<db-dir>/<db-dir>.yaml`, or nil if missing."
+ [^File db-dir]
+ (let [f (io/file db-dir (str (.getName db-dir) ".yaml"))]
+ (when (.exists f) f)))
+
+(defn- audit-database-names
+ "Set of database names whose self-yaml has `:is_audit true`. Mirrors the live appdb scorer's
+ `[:not= audit/audit-db-id]` filter — the v2 serdes extract path doesn't exclude the audit DB,
+ so anything in the export carrying `:is_audit true` would otherwise inflate `:universe`."
+ [^File databases-dir]
+ (if (.isDirectory databases-dir)
+ (into #{}
+ (keep (fn [^File db-dir]
+ (when-let [self (database-self-yaml db-dir)]
+ (let [parsed (load-yaml self)]
+ (when (true? (:is_audit parsed))
+ (:name parsed))))))
+ (list-dirs databases-dir))
+ #{}))
+
+(defn- load-yamls-of-model
+ "Parse YAMLs in `dir` and keep only those whose serdes model equals `model`.
+ Serdes co-locates side-car models in the same directory — e.g. FieldValues and FieldUserSettings
+ live next to Field YAMLs under `fields/` (`<field>___fieldvalues.yaml`,
+ `<field>___fieldusersettings.yaml`). The `___` separator is a serdes invariant, so we skip those
+ filenames before parsing — both to avoid inflating `:field-count` and to avoid the parse cost on
+ the 2N side-cars that would be discarded anyway."
+ [dir model]
+ (->> (list-yamls dir)
+ (remove #(str/includes? (.getName ^File %) "___"))
+ (into [] (comp (map load-yaml) (filter #(= model (entity-model %)))))))
+
+(defn- load-table
+ "Load one Table directory into `{:table :fields :measures}`, or nil if its self-yaml is missing."
+ [^File table-dir]
+ (when-let [self (table-self-yaml table-dir)]
+ {:table (load-yaml self)
+ :fields (load-yamls-of-model (io/file table-dir "fields") "Field")
+ :measures (load-yamls-of-model (io/file table-dir "measures") "Measure")}))
+
+(defn- walk-databases-tree
+ "Walk `<dir>/databases/<db>/...` and return one `{:table :fields :measures}` per Table dir."
+ [^File databases-dir]
+ (if (.isDirectory databases-dir)
+ (vec (keep load-table (mapcat list-table-dirs (list-dirs databases-dir))))
+ []))
+
+;;; ------------------------------------------- entity shaping -------------------------------------------
+
+(defn- table-path-id
+ "Stable `:id` for a Table, since serdes Table YAMLs carry no entity_id.
+ Format: `\"<db>/<schema>/<name>\"`; `<schema>` is the empty string for schema-less databases."
+ [{:keys [db_id schema name]}]
+ (str db_id "/" (or schema "") "/" name))
+
+(defn- ->table-entity [{:keys [table fields measures]}]
+ ;; Field.active defaults to true and Measure.archived defaults to false: treat both missing
+ ;; AND explicit nil as the default, so only an explicit `false`/`true` flips the predicate.
+ {:id (table-path-id table)
+ :name (:name table)
+ :kind :table
+ :field-count (count (remove #(false? (:active %)) fields))
+ :measure-names (mapv :name (remove #(true? (:archived %)) measures))})
+
+(defn- ->card-entity [{:keys [entity_id name type]}]
+ {:id entity_id
+ :name name
+ :kind (keyword type)
+ :field-count 0
+ :measure-names []})
+
+;;; ------------------------------------------- embeddings sidecar -------------------------------------------
+
+(defn- resolve-embeddings-file
+ "Resolve `embeddings-path` against `dir` (relative paths) or as-is (absolute).
+ Throws ex-info when the file is missing — silent fallback would mask a typo and produce a
+ misleadingly low score."
+ ^File [dir embeddings-path]
+ (let [given (io/file embeddings-path)
+ f (if (.isAbsolute given) given (io/file dir embeddings-path))]
+ (when-not (.exists f)
+ (throw (ex-info (str "Embeddings file not found: " (.getPath f))
+ {:embeddings-path embeddings-path
+ :resolved-path (.getPath f)
+ :dir (str dir)})))
+ f))
+
+(defn- load-embeddings
+ "Decode the embeddings sidecar — explicit override, then default `embeddings.json`, else `{}`."
+ [dir embeddings-path]
+ (if embeddings-path
+ (json/decode (slurp (resolve-embeddings-file dir embeddings-path)) false)
+ (let [default (io/file dir "embeddings.json")]
+ (if (.exists default) (json/decode (slurp default) false) {}))))
+
+;;; ------------------------------------------- public entry point -------------------------------------------
+
+(defn load-dir
+ "Load a serdes export and return `{:library :universe :embedder}` for the complexity scorer.
+
+ Filters mirror the live appdb scorer:
+ - Universe Cards : `type ∈ {metric model}`, not archived
+ - Universe Tables: `active` (defaults true)
+ - Library Cards : Universe Card whose `collection_id` is in the Library subtree
+ - Library Tables : Universe Table with `is_published true` and `collection_id` in the Library
+
+ Options:
+ `:embeddings-path` — explicit JSON embeddings file. Relative paths resolve against `dir`.
+ Throws when the resolved file is missing. Defaults to `<dir>/embeddings.json` when absent."
+ [dir & {:keys [embeddings-path]}]
+ (let [dir-file (io/file dir)
+ databases-dir (io/file dir-file "databases")
+ {:keys [collections cards]} (walk-collections-tree (io/file dir-file "collections"))
+ tables (walk-databases-tree databases-dir)
+ embeddings (load-embeddings dir embeddings-path)
+ lib-coll-ids (library-collection-ids collections)
+ audit-db-names (audit-database-names databases-dir)
+ non-audit-card? (fn [c] (not (contains? audit-db-names (:database_id c))))
+ non-audit-table? (fn [t] (not (contains? audit-db-names (:db_id t))))
+ ;; In serdes: Card.archived is in :copy without a default → absent means false.
+ ;; Field.active defaults to true; Measure.archived defaults to false (in shapers).
+ universe-card? (fn [c] (and (contains? #{"metric" "model"} (:type c))
+ (not (get c :archived false))
+ (non-audit-card? c)))
+ library-card? (fn [c] (and (universe-card? c)
+ (contains? lib-coll-ids (:collection_id c))))
+ universe-table? (fn [{t :table}]
+ (and (get t :active true)
+ (non-audit-table? t)))
+ library-table? (fn [{t :table :as bundle}]
+ (and (universe-table? bundle)
+ (:is_published t)
+ (contains? lib-coll-ids (:collection_id t))))]
+ {:library (vec (concat (mapv ->card-entity (filter library-card? cards))
+ (mapv ->table-entity (filter library-table? tables))))
+ :universe (vec (concat (mapv ->card-entity (filter universe-card? cards))
+ (mapv ->table-entity (filter universe-table? tables))))
+ :embedder (embedders/file-embedder embeddings)}))
diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/settings.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/settings.clj
index 5768a10d7b3..a784b0faf80 100644
--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/settings.clj
@@ -34,11 +34,8 @@
(defsetting data-complexity-scoring-use-search-index-embedder
(deferred-tru
(str "Source the synonym-axis embeddings from the active semantic-search pgvector index "
- "instead of calling the synonym-axis embedder configured below. The default (off) is "
- "the better-calibrated signal — see "
- "https://linear.app/metabase/document/synonym-analysis-21-april-2026-31c8ce76eddb "
- "— but the search-index path does not require ai-service to be reachable, which is "
- "useful for instances where it is not deployed."))
+ "instead of calling the synonym-axis embedder configured below. This saves us doing "
+ "additional calculations, but the results seem less reliable."))
:encryption :no
:visibility :admin
:default false
@@ -57,10 +54,7 @@
(defsetting data-complexity-scoring-synonym-embedding-model
(deferred-tru
- (str "Model name passed to the synonym-axis embedding provider. Defaults to "
- "sentence-transformers/all-MiniLM-L6-v2 — an STS-trained Sentence-Transformers model "
- "calibrated against names-split preprocessing at threshold 0.80. See the synonym "
- "calibration analysis before swapping this."))
+ "Model name passed to the synonym-axis embedding provider.")
:encryption :no
:visibility :admin
:default "sentence-transformers/all-MiniLM-L6-v2"
diff --git a/enterprise/backend/test/metabase_enterprise/data_complexity_score/cli_test.clj b/enterprise/backend/test/metabase_enterprise/data_complexity_score/cli_test.clj
new file mode 100644
index 00000000000..763505f10c7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_complexity_score/cli_test.clj
@@ -0,0 +1,275 @@
+(ns metabase-enterprise.data-complexity-score.cli-test
+ (:require
+ [clojure.edn :as edn]
+ [clojure.java.io :as io]
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-complexity-score.cli :as cli]
+ [metabase-enterprise.data-complexity-score.complexity :as complexity]
+ [metabase-enterprise.data-complexity-score.complexity-embedders :as embedders]
+ [metabase-enterprise.data-complexity-score.representation :as representation]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private representation-fixture-dir
+ "enterprise/backend/test_resources/data_complexity_score/representation_fixture")
+
+(defn- empty-tmp-dir ^java.io.File [^String prefix]
+ (doto (java.io.File/createTempFile prefix "")
+ (.delete) (.mkdirs) .deleteOnExit))
+
+;;; ------------------------------------- on-disk fixture tests -------------------------------------
+
+(deftest ^:parallel representation-fixture-scores-deterministically-test
+ (testing "loading representation_fixture/ produces the totals + sub-scores it was designed for"
+ ;; Fixture summary:
+ ;; Library — 4 published tables (orders, subscriptions, clients, customers) + 2 metric
+ ;; cards (Revenue x2).
+ ;; Universe-only — 2 unpublished tables (events, event_log) + 1 schema-less Table (widgets,
+ ;; active but not published) + 1 model card (Revenue) in the Outside collection.
+ ;; Audit DB — 1 Table (query_log) + 1 metric Card (Audit Metric) live under an
+ ;; `is_audit: true` Database. Both are valid on their own, so they would
+ ;; inflate Universe by 2 if the audit-DB filter regressed.
+ ;; Embeddings — orthogonal except clients≈customers (library synonym) and
+ ;; events≈event_log (extra universe-only synonym). The customers key is in
+ ;; raw display-name form (" Customers ") to exercise the on-disk →
+ ;; file-embedder → scorer normalization path end-to-end.
+ ;; Measures — "revenue" on orders + subscriptions (library repeat) plus a third on
+ ;; events (extra universe repeat).
+ (let [result (#'cli/run-cli {:representation-dir representation-fixture-dir})]
+ (testing "library score matches the hand-derived total"
+ (is (= {:total 215
+ :components {:entity-count {:measurement 6.0 :score 60}
+ :name-collisions {:measurement 1.0 :score 100}
+ :synonym-pairs {:measurement 1.0 :score 50}
+ :field-count {:measurement 3.0 :score 3}
+ :repeated-measures {:measurement 1.0 :score 2}}}
+ (:library result))))
+ (testing "universe score matches the hand-derived total"
+ (is (= {:total 409
+ :components {:entity-count {:measurement 10.0 :score 100}
+ :name-collisions {:measurement 2.0 :score 200}
+ :synonym-pairs {:measurement 2.0 :score 100}
+ :field-count {:measurement 5.0 :score 5}
+ :repeated-measures {:measurement 2.0 :score 4}}}
+ (:universe result))))
+ (testing "meta has formula-version + threshold + weights but no :embedding-model (offline mode)"
+ (is (= {:formula-version 1
+ :synonym-threshold 0.8
+ :weights complexity/weights
+ :metabot-source :universe-fallback}
+ (:meta result))))))
+ (testing "the schema-less widgets table (under databases/<db>/tables/, no schema dir) loads into :universe"
+ (let [{:keys [universe]} (representation/load-dir representation-fixture-dir)]
+ (is (some #(= "widgets" (:name %)) universe)
+ "schema-less Table directory should be picked up by the loader")))
+ (testing "audit-DB content (is_audit: true) is excluded from :universe — both Tables and Cards"
+ ;; Mirrors the live appdb scorer's `[:not= audit/audit-db-id]` filter. The fixture has
+ ;; `databases/audit_database/...` (`is_audit: true`) with a `query_log` Table and a
+ ;; `collections/outside/cards/audit_metric.yaml` Card whose database_id points at it. Both
+ ;; would be valid Universe entries on their own; the filter is what keeps them out.
+ (let [{:keys [universe]} (representation/load-dir representation-fixture-dir)
+ names (set (map :name universe))]
+ (is (not (contains? names "query_log"))
+ "Table in is_audit DB must not appear in :universe")
+ (is (not (contains? names "Audit Metric"))
+ "Card whose database_id is the audit DB must not appear in :universe")))
+ (testing "FieldValues side-car YAMLs (`*___fieldvalues.yaml`) under fields/ do not inflate :field-count"
+ ;; The fixture's `events/fields/event_id___fieldvalues.yaml` is a real-shape serdes side-car
+ ;; sitting next to a Field YAML. `load-yamls-of-model` must skip it; otherwise the events Table
+ ;; would jump from 2 fields to 3 and the universe :field-count would land at 6 instead of 5.
+ (let [{:keys [universe]} (representation/load-dir representation-fixture-dir)
+ events (u/seek #(= "events" (:name %)) universe)]
+ (is (= 2 (:field-count events))
+ "events Table should have exactly 2 fields — the side-car must not be counted"))))
+
+(deftest ^:sequential run-cli-writes-readable-edn-to-output-file-test
+ ;; Not ^:parallel: calls `cli/write-result!`, which kondo flags as a destructive function in
+ ;; parallel tests. The temp file we hand it is unique-per-call so the write is safe in
+ ;; principle, but the lint flag is the right default — drop it instead of whitelisting.
+ (testing "--output path gets a readable EDN dump of the same result"
+ (let [tmp (doto (java.io.File/createTempFile "complexity-cli-output-" ".edn") .deleteOnExit)]
+ ;; Call internals instead of -main, which terminates the JVM via System/exit.
+ (#'cli/write-result! (#'cli/run-cli {:representation-dir representation-fixture-dir})
+ (.getAbsolutePath tmp))
+ (is (= 215 (-> (slurp tmp) edn/read-string :library :total))))))
+
+;;; ------------------------------------- pure embedder/scoring tests -------------------------------------
+
+(deftest ^:parallel file-embedder-test
+ (testing "file-embedder converts seqs to ^floats, preserves already-typed arrays, omits absent names"
+ (let [input {"a" [1.0 0.0] "b" (float-array [0.0 1.0])}
+ embedder (embedders/file-embedder input)
+ result (embedder [{:name "Any"}])]
+ (testing "same keys as input (the embedder ignores entities — scoring does the filtering)"
+ (is (= #{"a" "b"} (set (keys result)))))
+ (testing "both values round-trip to the expected vectors"
+ (is (= [1.0 0.0] (vec (get result "a"))))
+ (is (= [0.0 1.0] (vec (get result "b")))))))
+ (testing "raw display-name keys (mixed case, surrounding whitespace) are normalized so scoring matches"
+ (let [embedder (embedders/file-embedder {"Revenue" [1.0 0.0] " Orders " [0.0 1.0]})
+ result (embedder [{:name "Revenue"} {:name "orders"}])]
+ (is (= #{"revenue" "orders"} (set (keys result))))
+ (is (= [1.0 0.0] (vec (get result "revenue"))))
+ (is (= [0.0 1.0] (vec (get result "orders")))))))
+
+(deftest ^:parallel synonym-threshold-test
+ (testing "synonym detection requires cosine ≥ 0.80 — a regression to the old 0.30 cutoff would"
+ (testing "flag mid-similarity pairs that the current formula correctly rejects."
+ (let [score-pairs (fn [embeddings]
+ (get-in (complexity/score-from-entities
+ [{:id 10 :name "Alpha" :kind :table :field-count 0 :measure-names []}
+ {:id 11 :name "Beta" :kind :table :field-count 0 :measure-names []}]
+ []
+ (embedders/file-embedder embeddings)
+ {})
+ [:library :components :synonym-pairs :measurement]))]
+ (testing "cosine ≈ 0.50 — above the old 0.30 cutoff, below 0.80: NOT a synonym"
+ (is (= 0.0 (score-pairs {"alpha" [1.0 0.0]
+ "beta" [0.5 0.866]}))))
+ (testing "cosine ≈ 0.79 — just below the threshold: NOT a synonym"
+ (is (= 0.0 (score-pairs {"alpha" [1.0 0.0]
+ "beta" [0.79 0.613]}))))
+ (testing "cosine ≈ 0.81 — just above the threshold: IS a synonym"
+ (is (= 1.0 (score-pairs {"alpha" [1.0 0.0]
+ "beta" [0.81 0.586]}))))))))
+
+;;; ----------------------------------- loader unit tests (no YAML emit) -----------------------------------
+
+(deftest ^:parallel library-collection-ids-test
+ (testing "library-collection-ids includes the root + every descendant reachable via parent_id chain"
+ (let [collections [{:entity_id "root" :type "library"}
+ {:entity_id "child" :parent_id "root"}
+ {:entity_id "grand" :parent_id "child"}
+ {:entity_id "out"} ; root-level non-library collection
+ {:entity_id "orphan" :parent_id "no-such-collection"}]]
+ (is (= #{"root" "child" "grand"}
+ (#'representation/library-collection-ids collections)))))
+ (testing "no library collection → empty set (so library scoring short-circuits to zero)"
+ (is (= #{} (#'representation/library-collection-ids
+ [{:entity_id "any" :type nil}
+ {:entity_id "kid" :parent_id "any"}])))))
+
+(deftest ^:parallel ->table-entity-default-flag-handling-test
+ (testing "->table-entity treats missing/nil :active and :archived as the documented defaults"
+ ;; Field.active defaults to true → only explicit `false` drops the field.
+ ;; Measure.archived defaults to false → only explicit `true` drops the measure.
+ (let [entity (#'representation/->table-entity
+ {:table {:db_id "db" :schema "s" :name "t"}
+ :fields [{} ; missing → counted (active default true)
+ {:active true} ; true → counted
+ {:active false} ; false → dropped
+ {:active nil}] ; nil → counted (treat as default)
+ :measures [{:name "m-missing"} ; missing → kept
+ {:name "m-true" :archived true} ; true → dropped
+ {:name "m-false" :archived false} ; false → kept
+ {:name "m-nil" :archived nil}]})] ; nil → kept (treat as default)
+ (is (=? {:field-count 3
+ :measure-names ["m-missing" "m-false" "m-nil"]}
+ entity)))))
+
+(deftest ^:parallel list-table-dirs-schema-less-branch-test
+ (testing "list-table-dirs picks up tables under <db>/tables/ (schema-less, e.g. MongoDB exports)"
+ (let [tmp-dir (empty-tmp-dir "schema-less-")
+ table-dir (io/file tmp-dir "tables/widgets")]
+ (.mkdirs table-dir)
+ (let [dirs (#'representation/list-table-dirs tmp-dir)]
+ (is (= [(.getCanonicalPath table-dir)] (mapv #(.getCanonicalPath ^java.io.File %) dirs))))))
+ (testing "list-table-dirs returns [] for an empty database dir (no schemas/, no tables/)"
+ (is (= [] (vec (#'representation/list-table-dirs (empty-tmp-dir "empty-db-")))))))
+
+(deftest ^:parallel resolve-embeddings-file-test
+ (let [tmp-dir (empty-tmp-dir "emb-resolve-")
+ present (io/file tmp-dir "embeddings/variant.json")]
+ (io/make-parents present)
+ (spit present "{}")
+ (testing "relative path resolves under the representation dir, not cwd"
+ (let [resolved (#'representation/resolve-embeddings-file (.getAbsolutePath tmp-dir)
+ "embeddings/variant.json")]
+ (is (= (.getCanonicalPath present) (.getCanonicalPath resolved)))))
+ (testing "absolute path is honored as-is, regardless of dir"
+ (let [resolved (#'representation/resolve-embeddings-file "/tmp" (.getAbsolutePath present))]
+ (is (= (.getCanonicalPath present) (.getCanonicalPath resolved)))))
+ (testing "missing file throws ex-info carrying both the request and the resolved path"
+ (let [ex (try (#'representation/resolve-embeddings-file (.getAbsolutePath tmp-dir)
+ "embeddings/does-not-exist.json")
+ nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (some? ex) "expected an exception, got a silent success")
+ (is (re-find #"does-not-exist\.json" (ex-message ex)))
+ (is (= "embeddings/does-not-exist.json" (:embeddings-path (ex-data ex))))
+ (is (re-find #"embeddings/does-not-exist\.json" (:resolved-path (ex-data ex))))))))
+
+(deftest ^:parallel run-cli-propagates-missing-embeddings-test
+ (testing "run-cli surfaces the missing-embeddings ex-info instead of silently scoring without embeddings"
+ ;; `run-cli` is the pure core — it must not call `System/exit` when --embeddings can't be
+ ;; resolved. The CLI-layer fail!/exit handling lives in `-main` (covered separately).
+ (let [ex (try (#'cli/run-cli {:representation-dir representation-fixture-dir
+ :embeddings "embeddings/does-not-exist.json"})
+ nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (some? ex) "run-cli should throw, not exit the JVM")
+ (is (re-find #"does-not-exist\.json" (ex-message ex)))
+ (is (re-find #"embeddings/does-not-exist\.json" (:resolved-path (ex-data ex)))))))
+
+(deftest ^:parallel representation-empty-dir-test
+ (testing "an empty export dir loads cleanly: missing collections/ + databases/ → empty entity vectors"
+ (let [{:keys [library universe]} (representation/load-dir
+ (.getAbsolutePath (empty-tmp-dir "empty-rep-")))]
+ (is (= [] library))
+ (is (= [] universe)))))
+
+;;; ----------------------------------- CLI validation + -main integration -----------------------------------
+
+(deftest ^:parallel run-cli-validation-errors-throw-not-exit-test
+ (testing "run-cli throws ex-info (never calls System/exit) for all validation failures"
+ (testing "missing --representation-dir throws {:cli-validation true}"
+ (let [ex (try (#'cli/run-cli {}) nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (some? ex))
+ (is (true? (:cli-validation (ex-data ex))))
+ (is (re-find #"Missing --representation-dir" (ex-message ex)))))
+ (testing "non-existent --representation-dir throws {:cli-validation true}"
+ (let [ex (try (#'cli/run-cli {:representation-dir "/nonexistent/path/abc123-not-a-dir"})
+ nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (some? ex))
+ (is (true? (:cli-validation (ex-data ex))))
+ (is (re-find #"does not exist" (ex-message ex)))))
+ (testing "--representation-dir pointing at a file (not a directory) throws {:cli-validation true}"
+ (let [tmp-file (doto (java.io.File/createTempFile "not-a-dir-" ".tmp") .deleteOnExit)
+ ex (try (#'cli/run-cli {:representation-dir (.getAbsolutePath tmp-file)}) nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (some? ex))
+ (is (true? (:cli-validation (ex-data ex))))
+ (is (re-find #"must be a directory" (ex-message ex)))))))
+
+(deftest ^:sequential main-translates-validation-errors-to-fail-test
+ (testing "-main converts ex-info {:cli-validation true} from run-cli into fail! + exit 1"
+ (let [fail-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [cli/fail! (fn [& msgs]
+ (swap! fail-calls conj (vec msgs))
+ (throw (ex-info "mocked-exit" {::mock :exit})))]
+ (try (#'cli/-main "--representation-dir" "/nonexistent/path/xyz-not-a-dir")
+ (catch clojure.lang.ExceptionInfo _ nil)))
+ (is (= 1 (count @fail-calls)) "fail! should be invoked exactly once")
+ (is (re-find #"does not exist" (ffirst @fail-calls))))))
+
+(deftest ^:sequential main-converts-missing-embeddings-to-fail-test
+ (testing "-main translates a missing --embeddings override into a one-line fail! + exit 1"
+ (let [fail-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [cli/fail! (fn [& msgs]
+ (swap! fail-calls conj (vec msgs))
+ (throw (ex-info "mocked-exit" {::mock :exit})))]
+ (let [thrown (try (#'cli/-main "--representation-dir" representation-fixture-dir
+ "--embeddings" "embeddings/does-not-exist.json")
+ nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (= {::mock :exit} (ex-data thrown))
+ "expected -main to hit the mocked fail! path, not exit cleanly or throw something else")))
+ (is (= 1 (count @fail-calls)) "fail! should be invoked exactly once")
+ (let [[msg & extra] (first @fail-calls)]
+ (is (empty? extra) "fail! should be called with a single message")
+ (is (re-find #"does-not-exist\.json" msg)
+ "the user-facing message must mention the missing file")))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj b/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
index e58a91123fe..079eff6bab5 100644
--- a/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
@@ -100,6 +100,24 @@
(is (=? {:components {:synonym-pairs {:measurement 0.0 :score 0}}}
(#'complexity/score-catalog es nil))))))
+(deftest ^:parallel score-from-entities-metabot-fallback-test
+ (testing "score-from-entities marks :metabot as a universe fallback when no metabot-entities are passed"
+ (let [library []
+ universe [(entity :name "orders") (entity :name "widgets")]]
+ (testing "nil metabot-entities → :metabot reuses the :universe score and :meta flags the fallback"
+ (let [result (complexity/score-from-entities library universe nil {})]
+ (is (= :universe-fallback (get-in result [:meta :metabot-source]))
+ "benchmark consumers need this marker to tell an approximated :metabot apart from a real one")
+ (is (= (:universe result) (:metabot result))
+ "fallback path must copy :universe verbatim — no second scoring pass")))
+ (testing "non-nil metabot-entities → :metabot is scored separately and the marker is absent"
+ (let [result (complexity/score-from-entities library universe nil
+ {:metabot-entities [(entity :name "orders")]})]
+ (is (nil? (get-in result [:meta :metabot-source]))
+ "real metabot score must not be stamped with the fallback marker")
+ (is (not= (:universe result) (:metabot result))
+ "pre-check: the metabot vector is smaller than universe so the scores should differ"))))))
+
(deftest ^:parallel synonym-scoring-test
(testing "cosine similarity above threshold flags a synonym pair"
(let [es [(entity :name "customers") (entity :name "clients")]
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/data/data.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/data/data.yaml
new file mode 100644
index 00000000000..80e4c640c57
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/data/data.yaml
@@ -0,0 +1,10 @@
+name: Data
+entity_id: LiBrArYdAtA000000001
+slug: data
+type: library-data
+parent_id: LiBrArYrOoT000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: LiBrArYdAtA000000001
+ label: data
+ model: Collection
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/library.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/library.yaml
new file mode 100644
index 00000000000..bda7159a769
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/library.yaml
@@ -0,0 +1,9 @@
+name: Library
+entity_id: LiBrArYrOoT000000001
+slug: library
+type: library
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: LiBrArYrOoT000000001
+ label: library
+ model: Collection
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_a.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_a.yaml
new file mode 100644
index 00000000000..111182015e2
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_a.yaml
@@ -0,0 +1,11 @@
+name: Revenue
+entity_id: ReVeNuEcArDmEtRiC0a1
+type: metric
+archived: false
+collection_id: LiBrArYmEtRiCs000001
+database_id: Sample Database
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: ReVeNuEcArDmEtRiC0a1
+ label: revenue
+ model: Card
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_b.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_b.yaml
new file mode 100644
index 00000000000..3a85f5755a3
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/cards/revenue_metric_b.yaml
@@ -0,0 +1,11 @@
+name: Revenue
+entity_id: ReVeNuEcArDmEtRiC0b2
+type: metric
+archived: false
+collection_id: LiBrArYmEtRiCs000001
+database_id: Sample Database
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: ReVeNuEcArDmEtRiC0b2
+ label: revenue
+ model: Card
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/metrics.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/metrics.yaml
new file mode 100644
index 00000000000..774fcd699ee
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/library/metrics/metrics.yaml
@@ -0,0 +1,10 @@
+name: Metrics
+entity_id: LiBrArYmEtRiCs000001
+slug: metrics
+type: library-metrics
+parent_id: LiBrArYrOoT000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: LiBrArYmEtRiCs000001
+ label: metrics
+ model: Collection
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/audit_metric.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/audit_metric.yaml
new file mode 100644
index 00000000000..7741db7d9c3
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/audit_metric.yaml
@@ -0,0 +1,11 @@
+name: Audit Metric
+entity_id: AuDiTmEtRiCcArD00001
+type: metric
+archived: false
+collection_id: OuTsIdEcOlL000000001
+database_id: Audit Database
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: AuDiTmEtRiCcArD00001
+ label: audit_metric
+ model: Card
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/revenue_model.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/revenue_model.yaml
new file mode 100644
index 00000000000..19783c40cec
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/cards/revenue_model.yaml
@@ -0,0 +1,11 @@
+name: Revenue
+entity_id: ReVeNuEcArDmOdEl0001
+type: model
+archived: false
+collection_id: OuTsIdEcOlL000000001
+database_id: Sample Database
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: ReVeNuEcArDmOdEl0001
+ label: revenue
+ model: Card
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/outside.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/outside.yaml
new file mode 100644
index 00000000000..cad885f4721
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/collections/outside/outside.yaml
@@ -0,0 +1,8 @@
+name: Outside
+entity_id: OuTsIdEcOlL000000001
+slug: outside
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: OuTsIdEcOlL000000001
+ label: outside
+ model: Collection
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/audit_database.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/audit_database.yaml
new file mode 100644
index 00000000000..20caeb8250b
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/audit_database.yaml
@@ -0,0 +1,8 @@
+name: Audit Database
+entity_id: aUdItDaTaBaSe0000001
+engine: h2
+is_audit: true
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Audit Database
+ model: Database
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/tables/query_log/query_log.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/tables/query_log/query_log.yaml
new file mode 100644
index 00000000000..4639a3f909e
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/audit_database/tables/query_log/query_log.yaml
@@ -0,0 +1,10 @@
+name: query_log
+db_id: Audit Database
+active: true
+is_published: true
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Audit Database
+ model: Database
+- id: query_log
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/sample_database.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/sample_database.yaml
new file mode 100644
index 00000000000..ea3eaae1ee0
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/sample_database.yaml
@@ -0,0 +1,7 @@
+name: Sample Database
+entity_id: sAmPlEdAtAbAsE0000001
+engine: h2
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/clients/clients.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/clients/clients.yaml
new file mode 100644
index 00000000000..56a4328c4d4
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/clients/clients.yaml
@@ -0,0 +1,14 @@
+name: clients
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: true
+collection_id: LiBrArYdAtA000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: clients
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/customers/customers.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/customers/customers.yaml
new file mode 100644
index 00000000000..22165de8a8a
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/customers/customers.yaml
@@ -0,0 +1,14 @@
+name: customers
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: true
+collection_id: LiBrArYdAtA000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: customers
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/event_log/event_log.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/event_log/event_log.yaml
new file mode 100644
index 00000000000..718363c0931
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/event_log/event_log.yaml
@@ -0,0 +1,13 @@
+name: event_log
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: false
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: event_log
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/events.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/events.yaml
new file mode 100644
index 00000000000..ef97d7b4a54
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/events.yaml
@@ -0,0 +1,13 @@
+name: events
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: false
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: events
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id.yaml
new file mode 100644
index 00000000000..5823168f578
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id.yaml
@@ -0,0 +1,15 @@
+name: event_id
+active: true
+table_id:
+- Sample Database
+- PUBLIC
+- events
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: events
+ model: Table
+- id: event_id
+ model: Field
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id___fieldvalues.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id___fieldvalues.yaml
new file mode 100644
index 00000000000..bbe709ed40a
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_id___fieldvalues.yaml
@@ -0,0 +1,21 @@
+field_id:
+- Sample Database
+- PUBLIC
+- events
+- event_id
+type: full
+values:
+- 'evt-1'
+- 'evt-2'
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: events
+ model: Table
+- id: event_id
+ model: Field
+- id: full
+ model: FieldValues
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_ts.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_ts.yaml
new file mode 100644
index 00000000000..f2623d28fd2
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/fields/event_ts.yaml
@@ -0,0 +1,15 @@
+name: event_ts
+active: true
+table_id:
+- Sample Database
+- PUBLIC
+- events
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: events
+ model: Table
+- id: event_ts
+ model: Field
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/measures/revenue.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/measures/revenue.yaml
new file mode 100644
index 00000000000..2ee1c9698c4
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/events/measures/revenue.yaml
@@ -0,0 +1,11 @@
+name: revenue
+entity_id: rEvEnUeEvEnTs000001
+archived: false
+table_id:
+- Sample Database
+- PUBLIC
+- events
+serdes/meta:
+- id: rEvEnUeEvEnTs000001
+ label: revenue
+ model: Measure
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/id.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/id.yaml
new file mode 100644
index 00000000000..ea3818574ab
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/id.yaml
@@ -0,0 +1,15 @@
+name: id
+active: true
+table_id:
+- Sample Database
+- PUBLIC
+- orders
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: orders
+ model: Table
+- id: id
+ model: Field
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/total.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/total.yaml
new file mode 100644
index 00000000000..eb3b52d7504
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/fields/total.yaml
@@ -0,0 +1,15 @@
+name: total
+active: true
+table_id:
+- Sample Database
+- PUBLIC
+- orders
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: orders
+ model: Table
+- id: total
+ model: Field
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/measures/revenue.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/measures/revenue.yaml
new file mode 100644
index 00000000000..9094baddebb
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/measures/revenue.yaml
@@ -0,0 +1,11 @@
+name: revenue
+entity_id: rEvEnUeOrDeRs0000001
+archived: false
+table_id:
+- Sample Database
+- PUBLIC
+- orders
+serdes/meta:
+- id: rEvEnUeOrDeRs0000001
+ label: revenue
+ model: Measure
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/orders.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/orders.yaml
new file mode 100644
index 00000000000..6dd47fa093f
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/orders/orders.yaml
@@ -0,0 +1,14 @@
+name: orders
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: true
+collection_id: LiBrArYdAtA000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: orders
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/fields/id.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/fields/id.yaml
new file mode 100644
index 00000000000..8950590485c
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/fields/id.yaml
@@ -0,0 +1,15 @@
+name: id
+active: true
+table_id:
+- Sample Database
+- PUBLIC
+- subscriptions
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: subscriptions
+ model: Table
+- id: id
+ model: Field
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/measures/revenue.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/measures/revenue.yaml
new file mode 100644
index 00000000000..00fc5173e23
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/measures/revenue.yaml
@@ -0,0 +1,11 @@
+name: revenue
+entity_id: rEvEnUeSuBs000000001
+archived: false
+table_id:
+- Sample Database
+- PUBLIC
+- subscriptions
+serdes/meta:
+- id: rEvEnUeSuBs000000001
+ label: revenue
+ model: Measure
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/subscriptions.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/subscriptions.yaml
new file mode 100644
index 00000000000..0673cfe09d7
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/schemas/PUBLIC/tables/subscriptions/subscriptions.yaml
@@ -0,0 +1,14 @@
+name: subscriptions
+db_id: Sample Database
+schema: PUBLIC
+active: true
+is_published: true
+collection_id: LiBrArYdAtA000000001
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: PUBLIC
+ model: Schema
+- id: subscriptions
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/tables/widgets/widgets.yaml b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/tables/widgets/widgets.yaml
new file mode 100644
index 00000000000..6b3c56c22ab
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/databases/sample_database/tables/widgets/widgets.yaml
@@ -0,0 +1,10 @@
+name: widgets
+db_id: Sample Database
+active: true
+is_published: false
+created_at: '2026-04-02T00:00:00Z'
+serdes/meta:
+- id: Sample Database
+ model: Database
+- id: widgets
+ model: Table
diff --git a/enterprise/backend/test_resources/data_complexity_score/representation_fixture/embeddings.json b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/embeddings.json
new file mode 100644
index 00000000000..c29c5b81194
--- /dev/null
+++ b/enterprise/backend/test_resources/data_complexity_score/representation_fixture/embeddings.json
@@ -0,0 +1,9 @@
+{
+ "orders": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ "subscriptions": [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ "clients": [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ " Customers ": [0.0, 0.0, 0.99, 0.1, 0.0, 0.0, 0.0],
+ "revenue": [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
+ "events": [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
+ "event_log": [0.0, 0.0, 0.0, 0.0, 0.0, 0.99, 0.1]
+}