Skip to content

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

BOT-319 Sem search dead letter queue (DLQ) (#62070)

Dan Stone2c8296bf5353
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
index 78629fd8b27..63e6f56cbd0 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
@@ -7,7 +7,7 @@
(def schema-version
"Version to compare the [[metabase-enterprise.semantic-search.db.migration/db-version]] with. If this is higher,
schema migration will be performed."
- 1)
+ 2)
(defn- drop-all-but-migration-table
[tx]
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/dlq.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/dlq.clj
new file mode 100644
index 00000000000..0ec0f9bcdf1
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/dlq.clj
@@ -0,0 +1,512 @@
+(ns metabase-enterprise.semantic-search.dlq
+ "Dead Letter Queue (DLQ) implementation for semantic search indexing.
+
+ This namespace provides a dead letter queue system that handles failed semantic search
+ indexing operations with configurable retry policies. The DLQ is used when the main indexer
+ becomes stalled due to repeated failures, allowing the system to:
+
+ - Isolate problematic documents that cause indexing to fail (batch poisoning)
+ - Apply exponential backoff retry policies for transient vs permanent errors
+ - Allow the main indexer watermark to progress when only a subset of documents fail to be indexed
+
+ Initial write to the dead letter queue happen inside the indexer
+ when stall conditions are detected (see indexer.clj stall handling).
+
+ The queue is continuously drained (entries retried, and removed on success) by the indexer as part of normal index maintenance - there is no additional job
+ and writes & reads remain coordinated, ordering is preserved.
+
+ Documents will be rescheduled for retries on failure - there is a transient-policy (for temporary errors)
+ and a permanent-policy (that is likely only resolved with manual intervention, a patch to the code).
+ Even 'permanent' errors are retried however - due to inherent ambiguity - it just effects the backoff climb."
+ (:require
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.util :as semantic.util]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import
+ (java.net SocketException)
+ (java.time Clock Duration Instant InstantSource)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private dlq-table-schema
+ "The database schema definition for a DLQ table.
+ The schema includes:
+ - gate_id: PK & reference to the gate table entry that failed (NOTE: no FK, the DLQ is index specific and does not impose any change to the behaviour of the gate table)
+ - retry_count: Number of retry attempts made for this entry
+ - attempt_at: Next scheduled retry timestamp (based on backoff policy)
+ - last_attempted_at: Timestamp of the most recent retry attempt
+ - error_gated_at: Original timestamp when the gate entry was marked as failed"
+ [[:gate_id :text [:primary-key] :not-null]
+ [:retry_count :int :not-null]
+ [:attempt_at :timestamp-with-time-zone :not-null]
+ [:last_attempted_at :timestamp-with-time-zone :not-null]
+ [:error_gated_at :timestamp-with-time-zone :not-null]])
+
+(defn dlq-table-name-kw
+ "Generates the DLQ table name keyword for a specific index (metadata record).
+
+ Uses the index-table-qualifier format string from index-metadata to construct
+ a table name like 'index_table_dlq_{index-id}'."
+ [index-metadata index-id]
+ (let [{:keys [index-table-qualifier]} index-metadata]
+ (keyword (format index-table-qualifier (str "dlq_" index-id)))))
+
+(defn create-dlq-table-if-not-exists!
+ "Creates the DLQ table for the specified index if it doesn't already exist."
+ [pgvector index-metadata index-id]
+ (let [dlq-table (dlq-table-name-kw index-metadata index-id)]
+ (log/debugf "Creating DLQ table %s for index %s" dlq-table index-id)
+ ;; create table
+ (let [ddl {:create-table [dlq-table :if-not-exists]
+ :with-columns dlq-table-schema}
+ sql (sql/format ddl :quoted true)]
+ (jdbc/execute-one! pgvector sql))
+ ;; create attempt_at index
+ (let [ddl {:create-index [[(keyword (str (name dlq-table) "_attempt_at_idx")) :if-not-exists] [dlq-table :attempt_at]]}
+ sql (sql/format ddl :quoted true)]
+ (jdbc/execute-one! pgvector sql))
+ nil))
+
+(defn drop-dlq-table-if-exists!
+ "Drops the DLQ table for the specified index if it exists."
+ [pgvector index-metadata index-id]
+ (let [ddl {:drop-table [:if-exists (dlq-table-name-kw index-metadata index-id)]}
+ sql (sql/format ddl :quoted true)]
+ (jdbc/execute-one! pgvector sql)
+ nil))
+
+(defn dlq-table-exists?
+ "Returns true if the dead letter queue table exists for the given index."
+ [pgvector index-metadata index-id]
+ (semantic.util/table-exists? pgvector (name (dlq-table-name-kw index-metadata index-id))))
+
+(defn categorize-error
+ "Categorizes an error as :transient, :permanent, or defaults to :transient.
+
+ Error categorization examples:
+ - HTTP 4xx status codes -> :permanent (client errors, won't be fixed by retry)
+ - HTTP 5xx status codes -> :transient (server errors, may recover)
+ - SocketException -> :transient (network issues, may recover)
+ - AssertionError -> :permanent (logic errors, won't be fixed by retry)
+ - NullPointerException -> :permanent (programming errors, won't be fixed by retry)
+ - Everything else -> :transient (safer to retry unknown errors)
+
+ This categorization determines which retry policy is applied - 'permanent' errors
+ get much longer delays between retries than transient ones."
+ [^Throwable t]
+ (or (when-some [{:keys [status]} (ex-data t)]
+ (cond
+ (not (int? status)) nil
+ (<= 400 status 499) :permanent
+ (<= 500 status 599) :transient))
+ (condp instance? t
+ SocketException :transient
+ AssertionError :permanent
+ NullPointerException :permanent
+ nil)
+ :transient))
+
+(def transient-policy
+ "Retry policy for transient errors that are more likely to recover quickly."
+ {:cap (Duration/ofMinutes 10)
+ :base (Duration/ofMillis 500)
+ :exp 2.0})
+
+(def permanent-policy
+ "Retry policy for permanent errors that are unlikely to recover without intervention.
+
+ This policy is designed for errors like malformed documents or configuration
+ issues that typically require human intervention to resolve."
+ {:cap (Duration/ofHours 24)
+ :base (Duration/ofMinutes 10)
+ :exp 2.0})
+
+(defn linear-policy
+ "Creates a linear retry policy (no exponential backoff).
+
+ Useful for testing."
+ [base]
+ {:cap base
+ :base base
+ :exp 1.0})
+
+(defn max-delay-ms
+ "Calculates the maximum delay in milliseconds for a given retry count and policy.
+
+ Uses an exponential backoff formula: base-delay * (retry-count ^ exponential-factor)
+ The result is capped at the policy's maximum (:cap) delay and floored at 0.
+
+ This is used internally by next-delay (which introduces random jitter). It is sometimes useful
+ to predict the maximum delay regardless of any jitter."
+ ^double [^long retry-count policy]
+ (let [{:keys [^Duration base ^Duration cap ^Double exp]} policy
+ base-ms (.toMillis base)
+ cap-ms (.toMillis cap)
+ exp-factor (Math/pow retry-count exp)
+ raw-delay (* base-ms exp-factor)
+ delay (min raw-delay cap-ms)]
+ (max 0.0 (long delay))))
+
+(defn next-delay
+ "Calculates the next retry delay as a Duration for the given retry count and policy.
+
+ Applies the policy's exponential backoff formula with the cap constraint.
+ Returns a Duration object suitable for scheduling the next retry attempt (presumably against now/last-attempt).
+
+ Initially DLQ entries have a retry count of zero - it is not 'try' count, it is 'retry' count.
+ The initial retry is scheduled using the standard 'initial-backoff' variable, this function is only used
+ when we have retried at least once."
+ ^Duration [^long retry-count policy]
+ (let [{:keys [^Duration cap]} policy
+ cap-ms (.toMillis cap)
+ delay-ms (max-delay-ms retry-count policy)
+ jitter (+ 0.9 (* (rand) 0.2))
+ jittered-ms (* delay-ms jitter)]
+ (Duration/ofMillis (min cap-ms (max 0 (long jittered-ms))))))
+
+(comment
+ (next-delay 0 transient-policy)
+ (next-delay 1 transient-policy)
+ (next-delay 2 transient-policy)
+ (next-delay 10 transient-policy)
+ (next-delay 0 permanent-policy)
+ (next-delay 1 permanent-policy)
+ (next-delay 5 permanent-policy)
+ (next-delay 10 permanent-policy))
+
+(defn add-entries!
+ "Adds or updates DLQ entries in the database.
+
+ When there's a conflict on gate_id:
+ Updates the entry only if the new error_gated_at is >= the existing one (sanity check, should not happen in practice
+ if called in an order consistent with gating).
+ This ensures more recent failures take precedence over older DLQ entries
+
+ Returns the number of entries that were inserted or updated."
+ [pgvector index-metadata index-id dlq-entries]
+ (if (empty? dlq-entries)
+ 0
+ (let [dml {:insert-into (dlq-table-name-kw index-metadata index-id)
+ :values (sort-by :gate_id dlq-entries)
+ :on-conflict [:gate_id]
+ :do-update-set {:fields {:attempt_at :excluded.attempt_at
+ :retry_count :excluded.retry_count
+ :error_gated_at :excluded.error_gated_at
+ :last_attempted_at :excluded.last_attempted_at}
+ ;; condition: if exiting dlq entry reflects a more recent gate failure
+ ;; prefer the new attempt_at / retry_count from the gate to the prior DLQ entry.
+ :where [:<= [:. (dlq-table-name-kw index-metadata index-id) :error_gated_at]
+ :excluded.error_gated_at]}}
+ sql (sql/format dml :quoted true)
+ {upsert-count ::jdbc/update-count} (jdbc/execute-one! pgvector sql)]
+ (log/debugf "Added/updated %d DLQ entries for index %s" upsert-count index-id)
+ upsert-count)))
+
+(defn delete-entries!
+ "Removes DLQ entries that correspond to successfully processed gate documents.
+
+ Deletes entries matching both gate_id and error_gated_at to ensure we only
+ remove DLQ entries that correspond to the specific gate failure that was just
+ successfully reprocessed. This composite key approach prevents accidentally
+ removing newer DLQ entries for the same document.
+
+ We also use this to delete entries that have been orphaned due to an independent gate table change. This
+ race is unlikely - but nonetheless we ignore these entries and drop them from the gate table.
+ (We might race with GC'ing old tombstones, or if we change the way DLQ writes are ordered in respect to gate writes).
+
+ Returns the number of entries deleted."
+ [pgvector index-metadata index-id gate-docs]
+ (if (empty? gate-docs)
+ 0
+ (let [dml {:delete-from (dlq-table-name-kw index-metadata index-id)
+ :where [:in [:composite :gate_id :error_gated_at]
+ (for [{:keys [id gated_at]} gate-docs]
+ [id gated_at])]}
+ sql (sql/format dml :quoted true)
+ {delete-count ::jdbc/update-count} (jdbc/execute-one! pgvector sql)]
+ (when (pos? delete-count)
+ (log/debugf "Deleted %d DLQ entries for index %s" delete-count index-id))
+ delete-count)))
+
+(def ^InstantSource clock
+ "The system clock, but indirect so you can override it in tests."
+ (Clock/systemUTC))
+
+(def default-max-run-duration
+ "The default amount of time for which the DLQ retry loop will run for before exiting. The loop will
+ still exit if there is nothing left to do. We only expect to hit this max run if there are lots of scheduled retries
+ within a short time window.
+
+ By yielding the loop the indexer thread regains control and can decide how best to balance DLQ draining demands vs
+ regular watermarked indexing."
+ (Duration/ofSeconds 5))
+
+(def default-max-batch-size
+ "The default batch size, will shrink if failures continue to be encountered during a loop.
+ - In case the size of the batch is causing the error (e.g. large documents).
+ - To isolate any poisoned documents sooner than might otherwise be the case."
+ 100)
+
+(def default-poll-limit
+ "The maximum number of retry records to fetch in a single poll"
+ 1000)
+
+(defn poll
+ "Polls the indexer DLQ table for up to poll-limit entries ready to be retried.
+
+ Considers the state of both the DLQ table and the gate table to:
+ - Find DLQ entries where attempt_at <= current time (ready for retry)
+ - Include corresponding gate document data needed for reindexing
+ - Detect orphaned DLQ entries (where gate entry was deleted or has since been modified)
+
+ The entries are projected as 'gate-docs' compatible with the retry functions defined elsewhere in this namespace.
+ In addition to the gate keys: :id, :gated_at, :model, :model_id, :document, they will include some information from the
+ DLQ entry:
+ - A :retry_count to determine the next back off it fails again
+ - Both a :gated_at (from DLQ) and :new_gated_at (from gate).
+ So a caller can identify stale DLQ entries that no longer match the current gate state.
+
+ Returns up to poll-limit records, sort is undefined."
+ [pgvector index-metadata index-id poll-limit]
+ (let [q {:select [[:d.gate_id :id]
+ [:d.error_gated_at :gated_at]
+ :d.retry_count
+ :g.model
+ :g.model_id
+ :g.document
+ [:g.gated_at :new_gated_at]]
+ :from [[(dlq-table-name-kw index-metadata index-id) :d]]
+ ;; idea: we will allow gate entries to be deleted independently of the dead letter queue
+ ;; avoid cascading fks or any kind of explicit relationship
+ :left-join [[(keyword (:gate-table-name index-metadata)) :g] [:= :d.gate_id :g.id]]
+ :where [:<= :d.attempt_at (.instant clock)]
+ :limit poll-limit}
+ sql (sql/format q :quoted true)
+ results (jdbc/execute! pgvector sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ (when (seq results)
+ (log/debugf "Polled %d DLQ entries ready for retry from index %s" (count results) index-id))
+ results))
+
+(def ^Duration initial-backoff
+ "Used to schedule the initial retry attempt - no jitter, will assume the whole batch of failures
+ can be retried again at around the same time (optimistic).
+
+ From then on jitter and batch shrinking will split retries apart
+ in time and avoid situations where the same documents are tried in the same batch.
+
+ NOTE: this backoff duration only applies when the indexer is considered stalled. Before this (stall grace period)
+ the indexer retries according to its quartz schedule - this value (and the dead letter queue in general) is not used."
+ (Duration/ofSeconds 10))
+
+(defn initial-dlq-entry
+ "Returns the initial DLQ entry for a gate document that failed for the first time.
+
+ Sets retry_count to 0 and schedules the first retry after initial-backoff."
+ [{:keys [id gated_at]} ^Instant attempted-at]
+ {:gate_id id
+ :error_gated_at gated_at
+ :retry_count 0
+ :attempt_at (.plus attempted-at initial-backoff)
+ :last_attempted_at attempted-at})
+
+(defn- next-dlq-entry
+ "Returns the next DLQ entry for a gate document that has failed again.
+
+ Increments the retry_count and calculates the next attempt_at timestamp using
+ the provided retry-policy's backoff schedule. Preserves the original error_gated_at
+ timestamp to maintain consistency."
+ [{:keys [id gated_at retry_count]} retry-policy ^Instant attempted-at]
+ (let [new-retry-count (inc retry_count)]
+ {:gate_id id
+ :error_gated_at gated_at
+ :retry_count new-retry-count
+ :attempt_at (.plus attempted-at ^Duration (next-delay new-retry-count retry-policy))
+ :last_attempted_at attempted-at}))
+
+(defn- failure-outcome [ex gate-docs]
+ (let [now (.instant clock)
+ ex-category (categorize-error ex)
+ ex-policy ({:transient transient-policy, :permanent permanent-policy} ex-category transient-policy)]
+ {:failures (mapv (fn [gate-doc]
+ {:gate-doc gate-doc
+ :dlq-entry
+ (if (:retry_count gate-doc)
+ (next-dlq-entry gate-doc ex-policy now)
+ (initial-dlq-entry gate-doc now))})
+ gate-docs)}))
+
+(defn- success-outcome [gate-docs] {:successes (vec gate-docs)})
+
+(def ^:private merge-outcomes (partial merge-with into))
+
+(defn- retry! [f gate-docs]
+ (try
+ (f gate-docs)
+ (success-outcome gate-docs)
+ (catch InterruptedException ie (throw ie))
+ (catch Throwable t
+ (failure-outcome t gate-docs))))
+
+(defn- retry-upserts! [pgvector index gate-docs]
+ (retry!
+ #(semantic.index/upsert-index! pgvector index (map semantic.gate/gate-doc->search-doc %))
+ gate-docs))
+
+(defn- retry-deletes! [pgvector index gate-docs]
+ (->> gate-docs
+ (group-by :model)
+ (sort-by key)
+ (transduce
+ (map (fn [[model gate-docs]]
+ (retry!
+ #(semantic.index/delete-from-index! pgvector index model (map :model_id %))
+ gate-docs)))
+ merge-outcomes
+ {})))
+
+(defn try-batch!
+ "Attempts to index a batch of gate documents, separating upserts from deletes
+ processing them independently and then returning information on what failed and what succeeded.
+
+ Each discrete indexing operation swallows any error thrown, other than interrupts.
+
+ Upserts / Deletes can fail independently, even if both batched.
+ For deletes, currently deletes are processed in model groups, so one operation is issued for each search model
+ in the delete set - so again, multiple operations that can fail/succeed independently.
+
+ Returns an outcome map with :successes and :failures vectors,
+
+ - The :successes vector contains the input gate-docs that were successfully indexed.
+ - Maps in the :failures vector include both the original :gate-doc and a :dlq-entry that represents a new retry
+ using the gate-docs prior :retry_count and the policy associated with the caught error."
+ [pgvector index gate-docs]
+ (let [[upserts deletes] ((juxt filter remove) :document gate-docs)
+ upsert-outcome (some->> (seq upserts) (retry-upserts! pgvector index))
+ delete-outcome (some->> (seq deletes) (retry-deletes! pgvector index))]
+ (merge-outcomes {} upsert-outcome delete-outcome)))
+
+(defn- update-dlq-with-retry-outcome! [pgvector index-metadata index-id outcome]
+ (let [{:keys [successes
+ failures]} outcome]
+ (when (seq successes)
+ (->> successes
+ (sort-by (juxt :id :gated_at))
+ (delete-entries! pgvector index-metadata index-id)))
+ (when (seq failures)
+ (add-entries! pgvector index-metadata index-id (map :dlq-entry failures)))))
+
+(defn dlq-retry-loop!
+ "Runs the DLQ retry loop to attempt reindexing of failed documents.
+
+ This is the main entry point for DLQ processing, typically called by the indexer
+ when it detects that DLQ should be drained. The loop operates until one of
+ several exit conditions is met.
+
+ Loop behavior:
+ 1. Polls the DLQ for entries ready to retry (attempt_at <= current time)
+ 2. Filters out orphaned entries (where gate record no longer exists)
+ 3. Attempts to reindex valid entries in batches
+ 4. Updates DLQ based on success/failure outcomes:
+ - Successful entries are removed from the DLQ
+ - Failed entries get new retry schedules with an incremented retry_count
+ 5. Dynamically adjusts batch size:
+ - Shrinks to 1 on failures (helps isolate poisoned documents)
+ - Grows up to max-batch-size on success (optimizes throughput)
+
+ Exit conditions
+ - :interrupted - Thread was interrupted (graceful shutdown) NOTE: can ALSO still throw InterruptedException!
+ - :ran-out-of-time - Exceeded max-run-duration (used by the indexer to ensure it regains control if there are a lot of DLQ entries to retry, or retries take a long time).
+ IMPORTANT: DOES NOT terminate any blocking operations, so we should still set indexer/embedder timeout policies to reasonable numbers.
+ - :no-more-data - No more DLQ entries ready to retry (caught up)
+
+ Parameters:
+ - max-run-duration: Maximum time to run before exiting
+ - max-batch-size: Starting and maximum batch size
+ - poll-limit: Maximum entries to fetch per poll
+
+ Returns a map with:
+ - :exit-reason - One of the exit conditions above
+ - :run-time - Actual duration the loop ran (could be useful to determine the best next schedule)
+ - :success-count - Number of documents successfully re-indexed
+ - :failure-count - Number of documents that failed - counts failed _operations_, not unique documents.
+
+ The loop is designed run for a short-ish time, and to be interruptible and to yield control back to the
+ calling indexer, allowing for cooperative multitasking in the indexer job.
+ It is possible the indexer might choose to run longer DLQ loops if the main watermark is caught up and there are
+ lots of entries to retry in the DLQ.
+ The converse policy could apply if the indexer is busy at its watermark, and the DLQ demands are small."
+ [pgvector
+ index-metadata
+ index
+ index-id
+ & {:keys [^Duration max-run-duration
+ max-batch-size
+ poll-limit]
+ :or {max-run-duration default-max-run-duration
+ max-batch-size default-max-batch-size
+ poll-limit default-poll-limit}}]
+ (let [loop-start (u/start-timer)
+ max-run-ms (.toMillis max-run-duration)]
+ (log/debugf "Starting DLQ retry loop for index %s with max-run-duration %s, max-batch-size %d" index-id max-run-duration max-batch-size)
+ (loop [poll-results []
+ batch-size max-batch-size ;; assumes success is more likely that not.
+ success-count 0
+ failure-count 0]
+ (cond
+ (.isInterrupted (Thread/currentThread))
+ {:exit-reason :interrupted
+ :run-time (Duration/ofMillis (u/since-ms loop-start))
+ :success-count success-count
+ :failure-count failure-count}
+
+ ;; ran out of time
+ (< max-run-ms (u/since-ms loop-start))
+ (do
+ (log/debugf "DLQ retry loop for index %s exceeded max run time (took %s)" index-id (Duration/ofMillis (u/since-ms loop-start)))
+ {:exit-reason :ran-out-of-time
+ :run-time (Duration/ofMillis (u/since-ms loop-start))
+ :success-count success-count
+ :failure-count failure-count})
+
+ ;; ran out of data
+ (empty? poll-results)
+ (let [new-results (poll pgvector index-metadata index-id poll-limit)]
+ (if (empty? new-results)
+ (do
+ (log/debugf "DLQ retry loop completed - no more data ready for retry in index %s" index-id)
+ {:exit-reason :no-more-data
+ :run-time (Duration/ofMillis (u/since-ms loop-start))
+ :success-count success-count
+ :failure-count failure-count})
+ (recur new-results
+ ; you would think you might be able to reset to initial, but at the edge when you have lots of retries together it will slow down isolating poisoned docs
+ ; so if the batch size has shrunk - keep it to start with (it will soon grow)
+ batch-size
+ success-count
+ failure-count)))
+
+ :else
+ (let [[dlq-batch remaining-results] (split-at batch-size poll-results)
+ ;; filter out (and delete from the dlq) orphaned batch entries (that no longer reflect the latest gate record)
+ [orphaned valid-batch] ((juxt filter remove) #(not= (:gated_at %) (:new_gated_at %)) dlq-batch)
+ _ (some->> orphaned seq (delete-entries! pgvector index-metadata index-id))
+ _ (when (seq orphaned)
+ (log/debugf "Removed %d orphaned DLQ entries from index %s" (count orphaned) index-id))
+ _ (when (seq valid-batch)
+ (log/debugf "Retrying DLQ batch of %d documents for index %s" (count valid-batch) index-id))
+ outcome (try-batch! pgvector index valid-batch)
+ ;; outcome applies only to the valid batch entries
+ _ (update-dlq-with-retry-outcome! pgvector index-metadata index-id outcome)
+ {:keys [successes failures]} outcome
+ ; re-shrink batch in case data is poisoned, or we are hitting timeouts
+ new-batch-size (if (seq failures) 1 (min max-batch-size (* 2 batch-size)))]
+ (recur
+ remaining-results
+ new-batch-size
+ (+ success-count (count successes))
+ (+ failure-count (count failures))))))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index 7f9760dc55f..c3a0c235b9b 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -1,5 +1,7 @@
(ns metabase-enterprise.semantic-search.index
(:require
+ [buddy.core.codecs :as buddy-codecs]
+ [buddy.core.hash :as buddy-hash]
[clojure.string :as str]
[com.climate.claypoole :as cp]
[honey.sql :as sql]
@@ -213,13 +215,18 @@
excluded-kw (fn [column] (keyword (str "excluded." (name column))))]
(zipmap update-keys (map excluded-kw update-keys))))
-(defn- throw-if-max-pg-len
- [resource-name msg]
- (when (> (count resource-name) 63)
- (throw (ex-info msg
- {:table-name resource-name
- :length (count resource-name)
- :limit 63}))))
+(defn hash-identifier-if-exceeds-pg-limit
+ "Sometimes we need to generate new table/index names, such as when forcing a new index despite no change in index parameters.
+ When we do so we need to be sure any index names do not exceed the postgres limit for names. This function will hash the identifier
+ if it exceeds the length, and will get a name like index_${sha1} instead.
+
+ Note: The index parameters will still be available in index_metadata"
+ [identifier]
+ (if (<= (count identifier) 63)
+ identifier
+ (let [hashed-name (str "index_" (buddy-codecs/bytes->hex (buddy-hash/sha1 identifier)))]
+ (log/warnf "Using hashed name for index table %s as original table name %s exceeded the maximum table name length" hashed-name identifier)
+ hashed-name)))
(defn model-table-suffix
"Returns a new suffix for a table name, based on current timestamp"
@@ -227,19 +234,18 @@
(mod (.toEpochSecond (t/offset-date-time)) 10000000))
(defn model-table-name
- "Returns the table name for a model."
+ "Returns a default table name for a model. If the table name would exceed the 63 byte postgres limit, a hashed name is preferred."
[embedding-model]
(let [{:keys [model-name provider vector-dimensions]} embedding-model
provider-name (embedding/abbrev-provider-name provider)
abbrev-model-name (embedding/abbrev-model-name model-name)
- result (str "index_" provider-name "_" abbrev-model-name "_" vector-dimensions "_" (model-table-suffix))]
- (throw-if-max-pg-len result "Table name exceeds PostgreSQL limit")
- result))
+ ideal-table-name (str "index_" provider-name "_" abbrev-model-name "_" vector-dimensions)]
+ (hash-identifier-if-exceeds-pg-limit ideal-table-name)))
(defn default-index
"Returns the default index spec for a model."
- [embedding-model]
- (let [table-name (model-table-name embedding-model)]
+ [embedding-model & {:keys [table-name]}]
+ (let [table-name (or table-name (model-table-name embedding-model))]
{:embedding-model embedding-model
:table-name table-name
:version 1}))
@@ -383,9 +389,8 @@
(defn- index-name
"Returns the name for an index for the given index configuration, column, and index type."
[index suffix]
- (let [result (str (:table-name index) suffix)]
- (throw-if-max-pg-len result "Index name exceeds PostgreSQL limit")
- result))
+ (let [index-name (str (:table-name index) suffix)]
+ (hash-identifier-if-exceeds-pg-limit index-name)))
(defn hnsw-index-name
"Returns the name for a HNSW database index for the given semantic search index configuration."
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
index 9ce9f7d94d9..032f5631088 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
@@ -9,6 +9,7 @@
[honey.sql.helpers :as sql.helpers]
;; TODO: extract schema code to go under db.migration
[metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.util :as semantic.util]
[metabase.util :as u]
[metabase.util.log :as log]
[next.jdbc :as jdbc]
@@ -35,7 +36,8 @@
[:indexer_last_poll :timestamp-with-time-zone :null]
[:indexer_last_seen :timestamp-with-time-zone :null]
[:indexer_last_seen_id :text :null]
- [:indexer_last_seen_hash :text :null]]
+ [:indexer_last_seen_hash :text :null]
+ [:indexer_stalled_at :timestamp-with-time-zone :null]]
:control
[[:id :bigint [:primary-key]] ;; not auto-inc, only one row - still useful to ensure only one row when inserting.
@@ -72,7 +74,7 @@
(def default-index-metadata
"The default index metadata configuration that will be used for the search engine integration."
- {:version "1"
+ {:version "2"
:metadata-table-name "index_metadata"
:control-table-name "index_control"
:gate-table-name "index_gate"
@@ -199,20 +201,13 @@
:table-name table_name
:version index_version})
-(defn- table-exists? [pgvector table-name]
- (-> (jdbc/execute-one! pgvector
- ["SELECT exists (select 1 FROM information_schema.tables WHERE table_name = ?) table_exists"
- table-name]
- {:builder-fn jdbc.rs/as-unqualified-lower-maps})
- (:table_exists false)))
-
(defn- index-table-exists? [pgvector index]
- (table-exists? pgvector (:table-name index)))
+ (semantic.util/table-exists? pgvector (:table-name index)))
(defn- control-and-metadata-tables-exist?
[pgvector index-metadata]
- (and (table-exists? pgvector (:metadata-table-name index-metadata))
- (table-exists? pgvector (:control-table-name index-metadata))))
+ (and (semantic.util/table-exists? pgvector (:metadata-table-name index-metadata))
+ (semantic.util/table-exists? pgvector (:control-table-name index-metadata))))
(defn get-active-index-state
"Returns the currently active index configuration, or nil if none active.
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj
index c32a8f03892..0b76b5ff8dd 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj
@@ -2,21 +2,26 @@
"Companion to the gate lib defining an indexing loop to be invoked as a singleton Quartz job.
- A (cluster singleton) interruptible quartz job should invoke (quartz-job-run!) (see task/indexer.clj).
- - The job will poll the gate table in a loop and index anything new it finds (inserts, updates & deletes)
+ - The job will poll the gate table in a loop and index anything new it finds (inserts, updates & deletes).
+ - Occasionally (scheduled according to demand) will drain some records from the dead letter queue and try attempt to reindex them (see dlq.clj).
- Saves watermark state back to index metadata for each batch of documents indexed
(if interrupted / crashes / process dies, polling can continue from its watermark position).
- - The job can run the indexing-loop for a time, eventually yielding back to quartz
+ - The job can run the indexing-loop for a time, eventually yielding back to quartz.
- we do not poll once per job invocation, indexing-loop can poll and index data many, many times before yielding.
- it will exit if it has run for default-max-run-duration
- it will exit if it has not seen any new data in default-exit-early-cold-duration
- - it will exit if it is interrupted (e.g. node shutdown)
- - Polling behaviour respects the limitations of gate.clj (there is a 2x gate-write-timeout lag tolerance)
+ - it will exit if it is interrupted (e.g. node shutdown).
+ - Polling behaviour respects the limitations of gate.clj (there is a 2x gate-write-timeout lag tolerance).
- if there is a lot of new write activity you might see the indexer stall for a short time
to wait for commit-races to become very unlikely.
- - when reindexing cold gate entries the loop is free to index using straightforward key-set pagination, no stalls.
- - Any kind of exception will immediately exit the loop (quartz is free to reschedule)."
+ - when reindexing cold gate entries the loop is free to index using straightforward key-set pagination, without waiting.
+ - By default, any kind of exception will immediately exit the loop (quartz is free to reschedule).
+ - If the indexer is deemed to have stalled due to repeated errors:
+ - The loop will instead start adding failed gate docs to the dead-letter-queue (see dlq.clj).
+ - Progress its watermark regardless (to avoid indexer stalls if e.g. documents are poisoned)."
(:require
[honey.sql :as sql]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
[metabase-enterprise.semantic-search.gate :as semantic.gate]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
@@ -24,13 +29,65 @@
[metabase.util.log :as log]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as jdbc.rs])
- (:import (java.time Duration Instant)))
+ (:import (java.sql Timestamp)
+ (java.time Clock Duration Instant InstantSource)))
(set! *warn-on-reflection* true)
-(def ^:private lag-tolerance
- (.multipliedBy semantic.gate/gate-write-timeout
- (semantic.settings/ee-search-indexer-lag-tolerance-multiplier)))
+(def ^InstantSource clock "Handy var for test indirection" (Clock/systemUTC))
+
+(def ^:private lag-tolerance (.multipliedBy semantic.gate/gate-write-timeout (semantic.settings/ee-search-indexer-lag-tolerance-multiplier)))
+
+(def ^Duration stall-grace-period
+ "Time to wait after marking an indexer as stalled before switching to DLQ mode.
+
+ This grace period allows for transient issues to resolve naturally before
+ falling back to the more aggressive DLQ processing mode. During this period,
+ the indexer continues to attempt normal processing and throw exceptions on failure."
+ (Duration/ofSeconds 10))
+
+(defn- clear-stall!
+ "Clears the stall marker from the index metadata table.
+
+ Called when the indexer successfully processes documents after being stalled,
+ indicating that normal processing can resume. This resets the indexer to its
+ normal error handling mode where exceptions cause the indexer to exit.
+
+ Returns true if a stall marker was actually cleared, false if none existed."
+ [pgvector index-metadata index]
+ (let [dml {:update [(keyword (:metadata-table-name index-metadata))]
+ :set {:indexer_stalled_at nil}
+ :where [:and [:= :table_name (:table-name index)] [:!= nil :indexer_stalled_at]]}
+ sql (sql/format dml :quoted true)
+ {update-count ::jdbc/update-count} (jdbc/execute-one! pgvector sql)
+ cleared (pos? update-count)]
+ (when cleared
+ (log/debugf "Cleared stall marker for index %s" (:table-name index)))
+ cleared))
+
+(defn- mark-stalled!
+ "Marks the indexer as stalled in the index metadata table.
+
+ This is called when an indexing operation fails, indicating that the indexer
+ should switch to DLQ mode after the grace period elapses. The stall marker timestamp
+ is used to determine when the grace period has passed.
+
+ Only sets the timestamp if one isn't already present (preserves the original
+ stall time). Returns the timestamp that was set, or nil if already stalled."
+ [pgvector index-metadata index]
+ (let [now (Timestamp/from (.instant clock))
+ dml {:update [(keyword (:metadata-table-name index-metadata))]
+ :set {:indexer_stalled_at now}
+ :where [:and
+ [:= :table_name (:table-name index)]
+ ;; do not overwrite existing (earlier) timestamps
+ [:= nil :indexer_stalled_at]]}
+ sql (sql/format dml :quoted true)
+ {update-count ::jdbc/update-count} (jdbc/execute-one! pgvector sql)
+ timestamp (when (pos? update-count) now)]
+ (when timestamp
+ (log/debugf "Marked indexer as stalled for index %s at %s" (:table-name index) timestamp))
+ timestamp))
(defn indexing-step
"Runs a single blocking step of the indexing loop."
@@ -45,45 +102,118 @@
;; We keep a :last-seen-candidates set so if we saw them last time we can filter them out
(remove-redundant-candidates [update-candidates]
(let [{:keys [last-seen-candidates]} @indexing-state]
- (not-empty (if (seq last-seen-candidates)
- (into [] (remove last-seen-candidates) update-candidates)
- update-candidates))))
+ (if (seq last-seen-candidates)
+ (into [] (remove last-seen-candidates) update-candidates)
+ update-candidates)))
;; currently we expect to flush the watermark each time we poll
(move-to-next-watermark [poll-result]
(let [{:keys [watermark]} @indexing-state
next-watermark (semantic.gate/next-watermark watermark poll-result)]
(vswap! indexing-state assoc :watermark next-watermark)
- (semantic.gate/flush-watermark! pgvector index-metadata index next-watermark)))]
- (let [{:keys [update-candidates] :as poll-result} (poll)]
- (if-some [novel-candidates (remove-redundant-candidates update-candidates)]
- (let [documents-query {:select [:model :model_id :document]
+ (semantic.gate/flush-watermark! pgvector index-metadata index next-watermark)))
+
+ (clear-stall-if-needed []
+ (when (:stalled-at @indexing-state)
+ (clear-stall! pgvector index-metadata index)
+ (vswap! indexing-state assoc :stalled-at nil)))]
+ (let [poll-result (poll)
+ {:keys [update-candidates]} poll-result
+ novel-candidates (remove-redundant-candidates update-candidates)
+ documents-query {:select [:id :gated_at :model :model_id :document]
:from [(keyword (:gate-table-name index-metadata))]
:where [:in :id (sort (map :id novel-candidates))]}
- documents-sql (sql/format documents-query :quoted true)
- gate-docs (jdbc/execute! pgvector documents-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
- updates (filter :document gate-docs)
- deletes (remove :document gate-docs)
- updated-documents (map semantic.gate/gate-doc->search-doc updates)]
- (log/infof "Found gate updates: %d updates, %d deletes" (count updates) (count deletes))
- (when (seq updated-documents)
- (semantic.index/upsert-index! pgvector index updated-documents))
+ documents-sql (sql/format documents-query :quoted true)
+ gate-docs (when (seq novel-candidates) (jdbc/execute! pgvector documents-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+ updates (filter :document gate-docs)
+ deletes (remove :document gate-docs)
+ ^Timestamp stalled-at (:stalled-at @indexing-state)]
+
+ (when (seq gate-docs)
+ (log/infof "Found gate updates: %d updates, %d deletes" (count updates) (count deletes)))
+
+ (cond
+ ;; nothing to do
+ (empty? gate-docs)
+ (do
+ (clear-stall-if-needed)
+ (move-to-next-watermark poll-result)
+ (log/tracef "No gate documents to process for index %s" (:table-name index)))
+
+ ;; NORMAL MODE: Not stalled, or still within grace period
+ ;; This is the default behavior when the indexer is healthy. Any failures
+ ;; will cause exceptions to be thrown, causing the indexer loop to exit
+ ;; and Quartz to reschedule (typically within 10 seconds).
+ (or
+ ;; not stalled - indexer has not encountered repeated failures
+ (nil? stalled-at)
+ ;; within grace period - recently stalled but still allowing normal retry behavior
+ (.isBefore (.instant clock) (.plus (.toInstant stalled-at) stall-grace-period))
+ ;; DLQ processing hasn't been initialized (keeping this while in flux, ensures DLQ is 'optional').
+ (nil? (:next-dlq-run @indexing-state)))
+ (try
+ (when (seq updates)
+ (log/debugf "Processing %d index updates in normal mode for index %s" (count updates) (:table-name index))
+ (semantic.index/upsert-index! pgvector index (map semantic.gate/gate-doc->search-doc updates)))
(doseq [[model deletes] (group-by :model deletes)]
+ (when (seq deletes)
+ (log/debugf "Processing %d index deletes for model %s in normal mode for index %s" (count deletes) model (:table-name index)))
(semantic.index/delete-from-index! pgvector index model (map :model_id deletes)))
- (vswap! indexing-state assoc
- :last-seen-change (Instant/now)
- :last-indexed-count (count novel-candidates)
- :last-poll-count (count update-candidates))
- (move-to-next-watermark poll-result))
+ (clear-stall-if-needed)
+ (move-to-next-watermark poll-result)
+ (log/debugf "Processed %d gate documents successfully in normal mode for index %s" (count gate-docs) (:table-name index))
+ (catch InterruptedException ie (throw ie))
+ (catch Throwable t
+ (log/debug t "Indexing failure caught in normal mode")
+ (log/warnf "Indexing failed in normal mode for index %s, marking as stalled: %s" (:table-name index) (.getMessage t))
+ (mark-stalled! pgvector index-metadata index)
+ (throw t)))
+
+ ;; STALLED MODE: Grace period elapsed, switch to DLQ-based processing
+ ;; This mode is activated when the indexer has been stalled and the grace period
+ ;; has elapsed. The goal is to make progress at any cost while isolating problematic
+ ;; documents that prevent normal processing.
+ ;;
+ ;; DLQ Processing Strategy:
+ ;; - Any indexing failures are added to the dead letter queue to be retried after the dlq/initial-backoff.
+ ;; - The watermark progresses regardless of success/failure (prevents infinite stalls)
+ ;; - DLQ lib implements exponential backoff policies appropriate to error types
+ ;; - DLQ lib can isolate poisoned documents from good ones through batch size reduction
+ ;; - When all documents in a batch succeed, the indexer recovers to normal mode
+ ;;
+ ;; This ensures that even if some documents are permanently broken, the indexer
+ ;; continues to make progress on processable documents while retrying failures
+ ;; according to appropriate policies.
+ :else
(do
- (vswap! indexing-state assoc
- :last-indexed-count 0
- :last-poll-count (count update-candidates))
- (move-to-next-watermark poll-result)))
+ (log/debugf "Processing %d documents in stalled mode (using DLQ) for index %s" (count gate-docs) (:table-name index))
+ (let [{:keys [failures]} (semantic.dlq/try-batch! pgvector index gate-docs)]
+ (when (seq failures)
+ (log/warnf "Adding %d indexing failures to the dead letter queue" (count failures))
+ (semantic.dlq/add-entries! pgvector index-metadata (:index-id @indexing-state) (map :dlq-entry failures)))
- ;; we use this to filter redundant entries from the last poll (duplicate delivery is expected and intended when
+ ;; once no longer failing, clear any stall from index_metadata
+ ;; this will cause the 'healthy' branch to be used again.
+ (when (empty? failures)
+ (let [stalled-at (.toInstant ^Timestamp (:stalled-at @indexing-state))
+ stall-duration (Duration/between stalled-at (.instant clock))]
+ (log/info "Indexer recovered from stall in" stall-duration))
+ (clear-stall-if-needed))
+
+ ;; we progress the watermark regardless of success when stalled
+ (move-to-next-watermark poll-result)
+ (log/debugf "Processed %d gate documents in stalled mode for index %s, %d failed and moved to DLQ" (count gate-docs) (:table-name index) (count failures)))))
+
+ ;; we set :last-seen-candidates
+ ;; to filter redundant entries from the last poll (duplicate delivery is expected and intended when
;; at the tail of the gate index).
- (vswap! indexing-state assoc :last-seen-candidates (set update-candidates)))))
+ (vswap! indexing-state assoc
+ :last-seen-candidates (set update-candidates)
+ :last-novel-count (count novel-candidates)
+ :last-poll-count (count update-candidates)
+ :last-seen-change (if (seq novel-candidates)
+ (.instant clock)
+ (:last-seen-change @indexing-state))))))
;; having a var is handy for tests
(defn- sleep [ms]
@@ -92,9 +222,16 @@
(defn on-indexing-idle
"Runs any loop idle behaviour (such as waiting), called after each step."
[indexing-state]
- (let [{:keys [last-poll-count last-indexed-count]} @indexing-state
- novelty-ratio (if (zero? last-poll-count) 0 (/ last-indexed-count last-poll-count))]
+ (let [{:keys [last-poll-count
+ last-novel-count
+ ^Instant next-dlq-run]} @indexing-state
+ novelty-ratio (if (zero? last-poll-count) 0 (/ last-novel-count last-poll-count))]
+
(cond
+ ;; if the next DLQ run should happen on the next iteration, we should not idle
+ (and next-dlq-run (.isAfter (.instant clock) next-dlq-run))
+ nil
+
;; more than 25% the results are new, immediately get more
(< 0.25 novelty-ratio)
nil
@@ -128,9 +265,94 @@
^Instant last-seen-change
^Duration exit-early-cold-duration]}
^Instant now]
- (and start-time
- last-seen-change
- (.isAfter now (.plus last-seen-change exit-early-cold-duration))))
+ (or (and last-seen-change
+ (.isAfter now (.plus last-seen-change exit-early-cold-duration)))
+ (and (nil? last-seen-change)
+ start-time
+ (.isAfter now (.plus start-time exit-early-cold-duration)))))
+
+(def ^Duration dlq-max-run-duration
+ "Maximum time the DLQ retry loop will run before yielding back to the main indexer.
+
+ This prevents DLQ processing from monopolizing the indexer thread while still
+ allowing meaningful progress on retries.
+
+ Constant for now, Later this may vary based on demand of DLQ vs watermark progress."
+ (Duration/ofSeconds 10))
+
+(def dlq-max-batch-size
+ "Starting batch size for DLQ processing.
+
+ The DLQ will adaptively shrink this on failures to isolate poisoned
+ documents, and grow it back up to this maximum on success."
+ 100)
+
+(def dlq-poll-limit
+ "Maximum number of DLQ entries to fetch in a single poll operation.
+
+ This limits memory usage and ensures responsive behavior even when the
+ DLQ contains many entries ready for retry.
+
+ We do need to balance this for throughput during periods of prolonged (but transient) failure.
+ It is important that DLQ draining throughput is high when there are lots of pending retries.
+
+ NOTE: The DLQ loop does issue multiple poll requests until it runs out of scheduled retries or its max time -
+ so this limit does not need to be _that_ high."
+ 1000)
+
+(def ^Duration dlq-frequency
+ "How often to run DLQ processing when there's no immediate work to do.
+
+ When the DLQ run completes because it ran out of ready entries (rather than
+ time), the next DLQ run is scheduled this far in the future.
+ (i.e. we backoff and focus on watermark indexing If the DLQ run completes there is nothing left to do)."
+ (Duration/ofSeconds 15))
+
+(defn dlq-step
+ "Runs the dead letter queue retry loop for up to dlq-max-run-duration.
+ NOTE: is free to change the :last-seen-change marker timestamp, to avoid cold exits if the
+ DLQ runs are processing data. (Otherwise we would _also_ require new gate writes to avoid a cold exit.)"
+ [pgvector index-metadata index indexing-state]
+ (let [{:keys [index-id]} @indexing-state
+ {:keys [exit-reason
+ ^Duration run-time
+ success-count
+ failure-count]}
+ (semantic.dlq/dlq-retry-loop!
+ pgvector
+ index-metadata
+ index
+ index-id
+ :max-run-duration dlq-max-run-duration
+ :max-batch-size dlq-max-batch-size
+ :poll-limit dlq-poll-limit)
+
+ now (.instant clock)]
+
+ (log/debugf "DLQ step completed for index %s: exit-reason=%s, run-time=%s, successes=%d, failures=%d"
+ (:table-name index) exit-reason run-time success-count failure-count)
+
+ (when (or (pos? success-count) (pos? failure-count))
+ (log/infof "Dead letter queue loop completed in %.2f seconds, %d successes, %d failures."
+ (/ (.toMillis run-time) 1e3)
+ success-count
+ failure-count))
+
+ ;; if we succeed we mark a DLQ success to hold off an early exit due to the exit-early-cold-duration elapsing
+ ;; otherwise the indexing-loop will exit despite us having more to do in the DLQ.
+ (when (pos? success-count)
+ (vswap! indexing-state assoc :last-seen-change now))
+
+ ;; schedule the next run, immediately on the next iteration if there is a lot to do.
+ (let [next-run (if (and (pos? success-count) (= :ran-out-of-time exit-reason))
+ now
+ (.plus now dlq-frequency))]
+ (if (= now next-run)
+ (log/debugf "Scheduling next DLQ run for index %s immediately as there is more to retry" (:table-name index))
+ (log/debugf "Scheduling next DLQ run for index %s at %s" (:table-name index) next-run))
+ (vswap! indexing-state assoc :next-dlq-run next-run))
+
+ nil))
(defn indexing-loop
"Runs the indexing loop on the current thread, blocks until exit or interrupted.
@@ -140,31 +362,44 @@
index-metadata
index
indexing-state]
- (vswap! indexing-state assoc :start-time (Instant/now))
+ (vswap! indexing-state assoc :start-time (.instant clock))
(loop []
(cond
(.isInterrupted (Thread/currentThread))
(on-indexing-interrupted)
- (max-run-time-elapsed? @indexing-state (Instant/now))
- (log/debug "Indexer run time elapsed. Indexer exiting, quartz will reschedule.")
+ (max-run-time-elapsed? @indexing-state (.instant clock))
+ (log/debugf "Indexer run time elapsed for index %s. Indexer exiting, quartz will reschedule." (:table-name index))
- (exit-early-due-to-cold-data? @indexing-state (Instant/now))
- (log/debug "Indexer not seen any recent change, Indexer exiting, quartz will reschedule.")
+ (exit-early-due-to-cold-data? @indexing-state (.instant clock))
+ (log/debugf "Indexer not seen any recent change for index %s, Indexer exiting, quartz will reschedule." (:table-name index))
:else
- (let [interrupted (or (try
- (indexing-step pgvector index-metadata index indexing-state)
- false
- (catch InterruptedException _
- (log/info "Indexing thread interrupted while processing")
- true))
- (try
- (on-indexing-idle indexing-state)
- false
- (catch InterruptedException _
- (log/info "Indexing thread interrupted while idling")
- true)))]
+ (let [interrupted (or
+ ;; normal indexing
+ (try
+ (indexing-step pgvector index-metadata index indexing-state)
+ false
+ (catch InterruptedException _
+ (log/info "Indexing thread interrupted while indexing")
+ true))
+ ;; run dead letter queue processing if it is time to do so
+ (when-some [^Instant next-dlq-run (:next-dlq-run @indexing-state)]
+ (when (.isAfter (.instant clock) next-dlq-run)
+ (log/debugf "Starting DLQ processing for index %s" (:table-name index))
+ (try
+ (dlq-step pgvector index-metadata index indexing-state)
+ false
+ (catch InterruptedException _
+ (log/info "Indexing thread interrupted while processing the dead letter queue")
+ true))))
+ ;; idling
+ (try
+ (on-indexing-idle indexing-state)
+ false
+ (catch InterruptedException _
+ (log/info "Indexing thread interrupted while idling")
+ true)))]
(if interrupted
(on-indexing-interrupted)
(recur))))))
@@ -189,10 +424,13 @@
;; Seeding this value with the watermark solves a problem where the very last document
;; will be re-indexed every time the indexer is rescheduled
:last-seen-candidates (if last-seen #{last-seen} #{})
- :last-indexed-count 0
+ :last-novel-count 0
:last-poll-count 0
:max-run-duration max-run-duration
- :exit-early-cold-duration exit-early-cold-duration})))
+ :exit-early-cold-duration exit-early-cold-duration
+ :index-id (:id metadata-row)
+ ;; nil if healthy, a timestamp of when we first stalled if unhealthy
+ :stalled-at (:indexer_stalled_at metadata-row)})))
(defn quartz-job-run!
"Quartz job (execute) implementation. Determines the active index before running
@@ -204,14 +442,25 @@
(let [{:keys [index metadata-row]} (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
(when-not index (log/debug "No active semantic search index"))
(when index
+ (log/debugf "Starting indexer loop for index %s (ID: %s)" (:table_name metadata-row) (:id metadata-row))
(let [indexing-state (init-indexing-state metadata-row)]
+
+ ;; if the DLQ table exists, schedule runs to happen during indexing
+ ;; note: we might remove the table-exists? condition once schema solidifies
+ (if (semantic.dlq/dlq-table-exists? pgvector index-metadata (:id metadata-row))
+ (do
+ (log/debugf "DLQ table exists for index %s, scheduling DLQ processing" (:table-name index))
+ (vswap! indexing-state assoc :next-dlq-run (.plus (.instant clock) dlq-frequency)))
+ (log/warnf "DLQ table does not exist for index %s" (:table-name index)))
+
(try
(indexing-loop
pgvector
index-metadata
index
indexing-state)
+
(catch InterruptedException ie (throw ie))
(catch Throwable t
- (log/error t "An exception was caught during the indexing loop")
+ (log/errorf t "An exception was caught during the indexing loop for index %s" (:table-name metadata-row))
(throw t)))))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
index 6996d244d46..c8dc872fad7 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
@@ -10,6 +10,7 @@
(:require
[metabase-enterprise.semantic-search.db.connection :as semantic.db.connection]
[metabase-enterprise.semantic-search.db.migration :as semantic.db.migration]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
[metabase-enterprise.semantic-search.gate :as semantic.gate]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
@@ -29,50 +30,38 @@
(require '[metabase-enterprise.semantic-search.embedding :as semantic.embedding])
(def embedding-model (semantic.embedding/get-configured-model)))
-(defn determine-target-index
- "Determines which index should be active for the given embedding model.
+(defn- fresh-index [index-metadata embedding-model & {:keys [force-reset?]}]
+ (let [default-table-name (semantic.index/model-table-name embedding-model)
+ generated-table-name (if force-reset?
+ (str default-table-name "_" (semantic.index/model-table-suffix))
+ default-table-name)
+ table-name (semantic.index/hash-identifier-if-exceeds-pg-limit generated-table-name)]
+ (-> (semantic.index/default-index embedding-model :table-name table-name)
+ (semantic.index-metadata/qualify-index index-metadata))))
- Returns the index specification that should be activated."
- [tx index-metadata embedding-model {:keys [force-reset?]}]
- (let [active-index-state (semantic.index-metadata/get-active-index-state tx index-metadata)
- active-index (:index active-index-state)
- active-model (:embedding-model active-index)
- model-changed (not= embedding-model active-model)]
- (cond
- force-reset?
- (semantic.index-metadata/create-new-index-spec tx index-metadata embedding-model)
+(defn initialize-index!
+ "Creates an index for the provided embedding model (if it does not exist or if we're asking to force reset).
- model-changed
- (or (semantic.index-metadata/find-compatible-index! tx index-metadata embedding-model)
- (semantic.index-metadata/create-new-index-spec tx index-metadata embedding-model))
+ Returns the index that you can use with semantic.search.index functions to operate on the index."
+ [tx index-metadata embedding-model opts]
+ (let [force-new-index (:force-reset? opts)
- :else
- {:index active-index})))
+ {:keys [index metadata-row active]}
+ (if force-new-index
+ {:index (fresh-index index-metadata embedding-model opts)}
+ (or (semantic.index-metadata/find-compatible-index! tx index-metadata embedding-model)
+ {:index (fresh-index index-metadata embedding-model opts)}))
-(defn switch-to-index!
- "Switches to the specified index, creating it if necessary and activating it.
+ index-id (or (:id metadata-row) (semantic.index-metadata/record-new-index-table! tx index-metadata index))]
- Returns the id of the activated index."
- [tx index-metadata {:keys [index metadata-row]}]
- (let [id (or (:id metadata-row) (semantic.index-metadata/record-new-index-table! tx index-metadata index))]
- (semantic.index-metadata/activate-index! tx index-metadata id)
- id))
+ (semantic.index/create-index-table-if-not-exists! tx index)
+ (semantic.dlq/create-dlq-table-if-not-exists! tx index-metadata index-id)
-(defn initialize-index!
- "Creates an index for the provided embedding model (if it does not exist or if we're asking to force reset).
+ (when-not active
+ (log/infof "Configured model does not match active index, switching to new index %s" (u/pprint-to-str index))
+ (semantic.index-metadata/activate-index! tx index-metadata index-id))
- Returns the index that you can use with semantic.search.index functions to operate on the index."
- [tx index-metadata embedding-model opts]
- (let [target-index-spec (determine-target-index tx index-metadata embedding-model opts)
- current-active (:index (semantic.index-metadata/get-active-index-state tx index-metadata))
- needs-switch? (not= (:index target-index-spec) current-active)]
- (semantic.index/create-index-table-if-not-exists! tx (:index target-index-spec))
- (when needs-switch?
- (when current-active
- (log/infof "Configured model does not match active index, switching. Previous active: %s"
- (u/pprint-to-str current-active)))
- (switch-to-index! tx index-metadata target-index-spec))
- (:index target-index-spec)))
+ index))
(defn init-semantic-search!
"Initialises a pgvector database for semantic search if it does not exist and creates an index for the provided
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj
index 4bca5d6d90f..87136820e0d 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj
@@ -53,7 +53,7 @@
(.interrupt execution-thread)))))
(def ^:private ^Duration startup-delay (Duration/parse "PT10S"))
-(def ^:private ^Duration run-frequency (Duration/parse "PT10S"))
+(def ^:private ^Duration run-frequency (Duration/parse "PT20S"))
(defmethod task/init! ::SemanticSearchIndexer [_]
(when (premium-features/has-feature? :semantic-search)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/util.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/util.clj
new file mode 100644
index 00000000000..11e563b0685
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/util.clj
@@ -0,0 +1,13 @@
+(ns metabase-enterprise.semantic-search.util
+ (:require
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs]))
+
+(defn table-exists?
+ "Does the table-name exist in pgvector DB's information_schema.tables?"
+ [pgvector table-name]
+ (-> (jdbc/execute-one! pgvector
+ ["SELECT exists (select 1 FROM information_schema.tables WHERE table_name = ?) table_exists"
+ table-name]
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (:table_exists false)))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
index 1282c2451a3..ffc6deea13a 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
@@ -7,6 +7,7 @@
[metabase-enterprise.semantic-search.env :as semantic.env]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
[metabase.search.ingestion :as search.ingestion]
[metabase.test :as mt]
@@ -71,13 +72,11 @@
(testing "POST /api/search/re-init with semantic search support"
(mt/with-premium-features #{:semantic-search}
(semantic.tu/with-index!
- (let [original-index semantic.tu/mock-index
+ (let [original-index semantic.tu/mock-index
original-table-name (:table-name original-index)
- new-index (with-redefs [semantic.index/model-table-suffix (fn [] 345)]
- (-> (semantic.index/default-index semantic.tu/mock-embedding-model)
- (semantic.index-metadata/qualify-index
- semantic.tu/mock-index-metadata)))
- new-table-name (:table-name new-index)]
+ new-index (with-redefs [semantic.index/model-table-suffix (constantly 345)]
+ (#'semantic.pgvector-api/fresh-index semantic.tu/mock-index-metadata semantic.tu/mock-embedding-model :force-reset? true))
+ new-table-name (:table-name new-index)]
(is (semantic.tu/table-exists-in-db? original-table-name))
(is (not (semantic.tu/table-exists-in-db? new-table-name)))
@@ -87,8 +86,7 @@
(is (:active best-index)))
(testing "re-init creates the new index"
- (with-redefs [semantic.index/default-index (fn [_] new-index)
- semantic.env/get-index-metadata (fn [] (assoc semantic.tu/mock-index-metadata :index-table-qualifier "%s"))]
+ (with-redefs [semantic.index/model-table-suffix (constantly 345)]
(let [response (mt/user-http-request :crowberto :post 200 "search/re-init")]
(is (contains? response :message))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj
new file mode 100644
index 00000000000..70a30802ec1
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj
@@ -0,0 +1,354 @@
+(ns metabase-enterprise.semantic-search.dlq-test
+ (:require
+ [clojure.test :refer :all]
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.util.json :as json]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.io Closeable)
+ (java.net SocketException)
+ (java.sql Timestamp)
+ (java.time Duration Instant InstantSource)
+ (org.postgresql.util PGobject)))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(defn- open-dlq! ^Closeable [pgvector index-metadata index-id]
+ (semantic.tu/closeable
+ (semantic.dlq/create-dlq-table-if-not-exists! pgvector index-metadata index-id)
+ (fn [_] (semantic.dlq/drop-dlq-table-if-exists! pgvector index-metadata index-id))))
+
+(defn- ts ^Timestamp [s]
+ (Timestamp/from (Instant/parse s)))
+
+(deftest error-categorization-test
+ (testing "HTTP status codes"
+ (is (= :permanent (semantic.dlq/categorize-error (ex-info "Client error" {:status 404}))))
+ (is (= :permanent (semantic.dlq/categorize-error (ex-info "Validation error" {:status 422}))))
+ (is (= :transient (semantic.dlq/categorize-error (ex-info "Server error" {:status 500}))))
+ (is (= :transient (semantic.dlq/categorize-error (ex-info "Gateway timeout" {:status 504})))))
+
+ (testing "Exception types"
+ (is (= :transient (semantic.dlq/categorize-error (SocketException. "Connection reset"))))
+ (is (= :permanent (semantic.dlq/categorize-error (AssertionError. "Invalid assertion"))))
+ (is (= :permanent (semantic.dlq/categorize-error (NullPointerException. "NPE")))))
+
+ (testing "Default to transient"
+ (is (= :transient (semantic.dlq/categorize-error (RuntimeException. "Unknown error"))))
+ (is (= :transient (semantic.dlq/categorize-error (Exception. "Generic exception"))))))
+
+(deftest dlq-table-creation-test
+ (testing "DLQ table creation and existence checks"
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ index-id 42]
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)]
+ (is (false? (semantic.dlq/dlq-table-exists? pgvector index-metadata index-id)))
+ (semantic.dlq/create-dlq-table-if-not-exists! pgvector index-metadata index-id)
+ (is (true? (semantic.dlq/dlq-table-exists? pgvector index-metadata index-id)))
+ (semantic.dlq/drop-dlq-table-if-exists! pgvector index-metadata index-id)
+ (is (false? (semantic.dlq/dlq-table-exists? pgvector index-metadata index-id)))))))
+
+(deftest dlq-entry-management-test
+ (testing "DLQ entry add, query, and delete operations"
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ index-id 42]
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (open-dlq! pgvector index-metadata index-id)]
+ (let [t1 (ts "2025-01-01T10:00:00Z")
+ t2 (ts "2025-01-01T11:00:00Z")
+ entries [{:gate_id "gate1"
+ :retry_count 0
+ :attempt_at t1
+ :last_attempted_at t2
+ :error_gated_at t1}
+ {:gate_id "gate2"
+ :retry_count 1
+ :attempt_at t2
+ :last_attempted_at t1
+ :error_gated_at t1}]]
+
+ (is (= 2 (semantic.dlq/add-entries! pgvector index-metadata index-id entries)))
+
+ (let [table-name (semantic.dlq/dlq-table-name-kw index-metadata index-id)
+ results (jdbc/execute! pgvector
+ (sql/format {:select [:*] :from [table-name] :order-by [:gate_id]} :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ (is (= 2 (count results)))
+ (is (= "gate1" (:gate_id (first results))))
+ (is (= 0 (:retry_count (first results)))))
+
+ (let [table-name (semantic.dlq/dlq-table-name-kw index-metadata index-id)
+ all-results (jdbc/execute! pgvector
+ (sql/format {:select [[:gate_id :id] [:error_gated_at :gated_at]] :from [table-name]} :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ (is (= 2 (semantic.dlq/delete-entries! pgvector index-metadata index-id all-results)))
+ (let [remaining (jdbc/execute! pgvector
+ (sql/format {:select [:*] :from [table-name]} :quoted true))]
+ (is (empty? remaining)))))))))
+
+(deftest dlq-entry-upsert-test
+ (testing "DLQ entry upsert behavior on conflict"
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ index-id 42]
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (open-dlq! pgvector index-metadata index-id)]
+ (let [t1 (ts "2025-01-01T10:00:00Z")
+ t2 (ts "2025-01-01T11:00:00Z")
+ initial-entry [{:gate_id "gate1"
+ :retry_count 0
+ :attempt_at t1
+ :last_attempted_at t2
+ :error_gated_at t1}]]
+
+ (is (= 1 (semantic.dlq/add-entries! pgvector index-metadata index-id initial-entry)))
+
+ (let [updated-entry [{:gate_id "gate1"
+ :retry_count 2
+ :attempt_at t2
+ :last_attempted_at t2
+ :error_gated_at t2}]]
+ (is (= 1 (semantic.dlq/add-entries! pgvector index-metadata index-id updated-entry))))
+
+ (let [table-name (semantic.dlq/dlq-table-name-kw index-metadata index-id)
+ results (jdbc/execute! pgvector
+ (sql/format {:select [:*] :from [table-name] :order-by [:gate_id]} :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ (is (= 1 (count results)))
+ (is (= "gate1" (:gate_id (first results))))
+ (is (= 2 (:retry_count (first results))))
+ (is (= t2 (:error_gated_at (first results))))))))))
+
+(deftest dlq-poll-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ t1 (ts "2025-01-01T10:00:00Z")
+ t2 (ts "2025-01-01T11:00:00Z")
+ t3 (ts "2025-01-01T12:00:00Z")
+ c1 {:model "card" :id "1" :name "Test" :searchable_text "Content"}
+ c2 {:model "card" :id "2" :name "Test" :searchable_text "Content"}
+ version semantic.gate/search-doc->gate-doc
+ delete (fn [doc t] (semantic.gate/deleted-search-doc->gate-doc (:model doc) (:id doc) t))]
+
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)
+ index-id-ref (semantic.tu/closeable
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+ (constantly nil))
+ _ (open-dlq! pgvector index-metadata @index-id-ref)]
+
+ ;; Set up test data: gate entry and DLQ entry
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1) (delete c2 t2)])
+
+ ;; Add some DLQ entries that should be retried
+ (let [dlq-entries [;; upsert
+ {:gate_id "card_1"
+ :retry_count 1
+ :attempt_at t2
+ :last_attempted_at t2
+ :error_gated_at t1}
+ ;; delete
+ {:gate_id "card_2"
+ :retry_count 1
+ :attempt_at t3
+ :last_attempted_at t2
+ :error_gated_at t1}
+ ;; orphan
+ {:gate_id "card_3"
+ :retry_count 1
+ :attempt_at t1
+ :last_attempted_at t2
+ :error_gated_at t1}]]
+ (semantic.dlq/add-entries! pgvector index-metadata @index-id-ref dlq-entries))
+
+ (testing "poll at different times finds records to be retried as-of that clock value"
+ (testing "t1"
+ (with-redefs [semantic.dlq/clock (reify InstantSource (instant [_] (.toInstant t1)))]
+ (let [poll-results (semantic.dlq/poll pgvector index-metadata @index-id-ref 100)]
+ (is (= {"card_3" 1} (frequencies (map :id poll-results)))))))
+
+ (testing "t2"
+ (with-redefs [semantic.dlq/clock (reify InstantSource (instant [_] (.toInstant t2)))]
+ (let [poll-results (semantic.dlq/poll pgvector index-metadata @index-id-ref 100)]
+ (is (= {"card_1" 1 "card_3" 1} (frequencies (map :id poll-results)))))))
+
+ (testing "t3"
+ (with-redefs [semantic.dlq/clock (reify InstantSource (instant [_] (.toInstant t3)))]
+ (let [poll-results (semantic.dlq/poll pgvector index-metadata @index-id-ref 100)]
+ (is (= {"card_1" 1 "card_2" 1 "card_3" 1} (frequencies (map :id poll-results))))))))
+
+ (testing "limit parameter"
+ (with-redefs [semantic.dlq/clock (reify InstantSource (instant [_] (.toInstant t3)))]
+ (is (= 1 (count (semantic.dlq/poll pgvector index-metadata @index-id-ref 1))))
+ (is (= 3 (count (semantic.dlq/poll pgvector index-metadata @index-id-ref 10)))))))))
+
+(deftest dlq-retry-loop-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ clock-ref (volatile! (Instant/parse "2025-01-04T00:00:00Z"))
+ clock (reify InstantSource (instant [_] @clock-ref))
+ t1 (ts "2025-01-01T10:00:00Z")
+ c1 {:model "card" :id "1" :name "Test" :searchable_text "Content"}
+ c2 {:model "card" :id "2" :name "Test" :searchable_text "Content"}
+ version semantic.gate/search-doc->gate-doc
+ add-gate-to-dlq! (fn [pgvector index-metadata index-id]
+ (->> (semantic.gate/poll pgvector index-metadata {})
+ :update-candidates
+ (map #(semantic.dlq/initial-dlq-entry % (.instant clock)))
+ (semantic.dlq/add-entries! pgvector index-metadata index-id)))]
+
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)
+ index-id-ref (semantic.tu/closeable
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+ (constantly nil))
+ _ (open-dlq! pgvector index-metadata @index-id-ref)]
+
+ (with-redefs [semantic.dlq/clock clock]
+
+ (testing "exits with no data"
+ (let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
+ :max-run-duration (Duration/ofSeconds 1))]
+ (is (= :no-more-data (:exit-reason result)))
+ (is (zero? (:success-count result)))
+ (is (zero? (:failure-count result)))))
+
+ (testing "processes successful retries"
+ ;; Set up gate data and DLQ entries for retry
+ (is (pos? (semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1)])))
+
+ (add-gate-to-dlq! pgvector index-metadata @index-id-ref)
+
+ (testing "clock has not advanced beyond initial backoff"
+ (is (= 0 (count (semantic.dlq/poll pgvector index-metadata @index-id-ref 10)))))
+
+ (testing "advance clock beyond initial backoff"
+ ;; move clock passed the expected back off time
+ (vreset! clock-ref (.plus (.instant clock) semantic.dlq/initial-backoff))
+ (is (= 1 (count (semantic.dlq/poll pgvector index-metadata @index-id-ref 10)))))
+
+ (let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
+ :max-run-duration (Duration/ofMinutes 5)
+ :max-batch-size 10)]
+ (is (= :no-more-data (:exit-reason result)))
+ (is (= 1 (:success-count result)))))
+
+ (testing "handles failures and adjusts batch size"
+ ;; ensure there are two documents in the gate
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1) (version c2 t1)])
+ ;; add everything to dlq
+ (add-gate-to-dlq! pgvector index-metadata @index-id-ref)
+
+ (vreset! clock-ref (.plus (.instant clock) semantic.dlq/initial-backoff))
+
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Forced failure")))]
+ (let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
+ :max-run-duration (Duration/ofSeconds 1)
+ :max-batch-size 10)]
+ (is (#{:no-more-data :ran-out-of-time} (:exit-reason result)))
+ (is (= 2 (:failure-count result)))))
+
+ (testing "batch shrinking to minimum size of 1, causing passes"
+ (add-gate-to-dlq! pgvector index-metadata @index-id-ref)
+ (vreset! clock-ref (.plus (.instant clock) semantic.dlq/initial-backoff))
+ (let [observed-batches (atom [])]
+ (with-redefs [semantic.dlq/transient-policy (semantic.dlq/linear-policy Duration/ZERO)
+ semantic.index/upsert-index! (fn [_ _ docs]
+ ;; important: simulate time passing
+ (vreset! clock-ref (.plus (.instant clock) (Duration/ofMillis 1)))
+ (swap! observed-batches conj (count docs))
+ (when (> (count docs) 1)
+ (throw (RuntimeException. "Batch too large"))))]
+ (let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
+ :max-run-duration (Duration/ofSeconds 1)
+ :max-batch-size 10)]
+ (is (= :no-more-data (:exit-reason result)))
+ (is (= 2 (:success-count result))) ; both writes eventually succeed
+ (is (= 2 (:failure-count result))) ; first batch
+ (is (= [2 1 1] @observed-batches))))))
+
+ (testing "exits once max-run time elapses, even if dlq is full"
+ (add-gate-to-dlq! pgvector index-metadata @index-id-ref)
+ (vreset! clock-ref (.plus (.instant clock) semantic.dlq/initial-backoff))
+ (with-redefs [semantic.dlq/transient-policy (semantic.dlq/linear-policy Duration/ZERO)
+ semantic.index/upsert-index! (fn [& _]
+ ;; important: simulate time passing on each attempt
+ (vreset! clock-ref (.plus (.instant clock) (Duration/ofMillis 1)))
+ (throw (RuntimeException. "Boom")))]
+ (let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
+ :max-run-duration (Duration/ofMillis 10)
+ :max-batch-size 10)]
+ (is (= :ran-out-of-time (:exit-reason result)))
+ (is (= 0 (:success-count result)))
+ (is (pos? (:failure-count result)))))))))))
+
+(deftest try-batch-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ gate-docs [{:id "card_1"
+ :model "card"
+ :model_id "1"
+ :document (doto (PGobject.)
+ (.setType "jsonb")
+ (.setValue (json/encode {:model "card"
+ :name "hey"
+ :id "1"
+ :searchable_text "foo"})))
+ :gated_at (ts "2025-01-04T09:00:00Z")
+ :error_gated_at (ts "2025-01-04T09:00:00Z")}
+ {:id "card_2"
+ :model "card"
+ :model_id "2"
+ :document nil ; deletion
+ :gated_at (ts "2025-01-04T09:00:00Z")
+ :error_gated_at (ts "2025-01-04T09:00:00Z")}]]
+
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)]
+
+ (testing "batch processing singles out orphans (dlq entry with no associated gate record)"
+ (let [outcome (semantic.dlq/try-batch! pgvector index gate-docs)]
+ (is (= {"card_1" 1 "card_2" 1} (frequencies (map :id (:successes outcome)))))
+ (is (= {} (frequencies (map :gate_id (:failures outcome)))))))
+
+ (testing "failures across upsert/delete are aggregated"
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))
+ semantic.index/delete-from-index! (fn [& _] (throw (RuntimeException. "Delete failed")))]
+ (let [outcome (semantic.dlq/try-batch! pgvector index gate-docs)]
+ (is (= {"card_1" 1 "card_2" 1} (frequencies (map (comp :gate_id :dlq-entry) (:failures outcome)))))
+ (is (= {} (frequencies (map :id (:successes outcome))))))))
+
+ (testing "partial failure is representable"
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))]
+ (let [outcome (semantic.dlq/try-batch! pgvector index gate-docs)]
+ (is (= {"card_1" 1} (frequencies (map (comp :gate_id :dlq-entry) (:failures outcome)))))
+ (is (= {"card_2" 1} (frequencies (map :id (:successes outcome))))))))
+
+ (testing "failure increments retry count"
+ (let [now (Instant/parse "2025-01-01T13:14:33Z")]
+ (doseq [[ex policy] [[(RuntimeException. "Upsert failed") semantic.dlq/transient-policy]
+ [(AssertionError. "Assert") semantic.dlq/permanent-policy]]]
+ (with-redefs [rand (constantly 1.0)
+ semantic.index/upsert-index! (fn [& _] (throw ex))
+ semantic.dlq/clock (reify InstantSource (instant [_] now))]
+ (let [outcome (semantic.dlq/try-batch! pgvector index (map #(assoc % :retry_count 42) gate-docs))
+ [dlq-entry :as dlq-docs] (map :dlq-entry (:failures outcome))]
+ (is (= 1 (count dlq-docs)))
+ (is (= 43 (:retry_count dlq-entry)))
+ (is (= now (:last_attempted_at dlq-entry)))
+ (is (= (.plus now ^Duration (semantic.dlq/next-delay 43 policy)) (:attempt_at dlq-entry)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj
index 32c0ce34e1d..e0cdb8c2766 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj
@@ -9,47 +9,28 @@
(def ^:private test-short-model-name "short-model")
(def ^:private test-long-model-name "some-really-really-really-really-really-long-model-name-that-will-exceed-the-limit")
(def ^:private test-vector-dimensions 1024)
-(def ^:private pg-limit-error-pattern #"exceeds PostgreSQL limit")
-;; Postgres truncates indentifier names to 63 bytes (+ 1 byte for a terminating NULL). Ensure that errors are thrown
-;; if a resource name would exceed the limit for any embedding provider + model combination.
+;; Postgres truncates indentifier names to 63 bytes (+ 1 byte for a terminating NULL). Ensure that names do not exceed the limit
(deftest ^:parallel index-embedding-name-length-test
(mt/with-premium-features #{:semantic-search}
- (testing "Throws if index name would be longer than the 63 byte Postgres limit"
+ (testing "Truncates if name would be longer than the 63 byte Postgres limit"
(doseq [name-func [#'semantic.index/hnsw-index-name
#'semantic.index/fts-index-name
- #'semantic.index/fts-native-index-name]]
+ #'semantic.index/fts-native-index-name
+ :table-name]]
(testing (str name-func)
- (is (thrown-with-msg? clojure.lang.ExceptionInfo
- pg-limit-error-pattern
- (-> {:provider test-provider
- :model-name test-long-model-name
- :vector-dimensions test-vector-dimensions}
- semantic.index/default-index))))))
- (testing "Succeeds if index name would be less than the 63 byte Postgres limit"
- (let [index (-> {:provider test-provider
- :model-name test-short-model-name
- :vector-dimensions test-vector-dimensions}
- semantic.index/default-index)]
- (doseq [name-func [#'semantic.index/hnsw-index-name
- #'semantic.index/fts-index-name
- #'semantic.index/fts-native-index-name]]
- (testing (str name-func)
- (is (string? (name-func index)))
- (is (< (count (name-func index)) 64))))))))
-
-(deftest ^:parallel table-name-length-test
- (mt/with-premium-features #{:semantic-search}
- (testing "Throws if table name exceeds 63 byte Postgres limit"
- (let [embedding-model {:provider test-provider
- :model-name test-long-model-name
- :vector-dimensions test-vector-dimensions}]
- (is (thrown-with-msg? clojure.lang.ExceptionInfo
- #"Table name exceeds PostgreSQL limit"
- (semantic.index/model-table-name embedding-model)))))
- (testing "Succeeds if table name would be less than the 63 byte Postgres limit"
- (let [embedding-model {:provider test-provider
- :model-name test-short-model-name
- :vector-dimensions test-vector-dimensions}]
- (is (string? (semantic.index/model-table-name embedding-model)))
- (is (< (count (semantic.index/model-table-name embedding-model)) 64))))))
+ (testing "long"
+ (is (>= 63 (count (name-func (semantic.index/default-index {:provider test-provider
+ :model-name test-long-model-name
+ :vector-dimensions test-vector-dimensions})))))
+ (testing "remains unique"
+ (not= (name-func (semantic.index/default-index {:provider test-provider
+ :model-name (str test-long-model-name "a")
+ :vector-dimensions test-vector-dimensions}))
+ (name-func (semantic.index/default-index {:provider test-provider
+ :model-name (str test-long-model-name "aa")
+ :vector-dimensions test-vector-dimensions})))))
+ (testing "short"
+ (is (>= 63 (count (name-func (semantic.index/default-index {:provider test-provider
+ :model-name test-short-model-name
+ :vector-dimensions test-vector-dimensions})))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
index 3f048bd148c..d6a238214c4 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer :all]
[honey.sql :as sql]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
[metabase-enterprise.semantic-search.gate :as semantic.gate]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
@@ -13,7 +14,7 @@
[next.jdbc.result-set :as jdbc.rs])
(:import (java.io Closeable)
(java.sql Timestamp)
- (java.time Duration Instant)))
+ (java.time Duration Instant InstantSource)))
(set! *warn-on-reflection* true)
@@ -68,7 +69,7 @@
(is (= [] @delete-calls))
(is (= 1 (count @poll-calls)))
(is (= 0 (:last-poll-count @indexing-state)))
- (is (= 0 (:last-indexed-count @indexing-state)))
+ (is (= 0 (:last-novel-count @indexing-state)))
(testing "watermark has been updated"
(let [[{poll-result :ret}] @poll-calls]
@@ -88,7 +89,7 @@
(is (= 1 (count @delete-calls)))
(is (= 1 (count @poll-calls)))
(is (= 2 (:last-poll-count @indexing-state)))
- (is (= 2 (:last-indexed-count @indexing-state)))
+ (is (= 2 (:last-novel-count @indexing-state)))
(testing "watermark has been updated"
(let [[{poll-result :ret}] @poll-calls]
@@ -107,7 +108,7 @@
(is (= 0 (count @delete-calls)))
(is (= 1 (count @poll-calls)))
(is (= 2 (:last-poll-count @indexing-state)))
- (is (= 0 (:last-indexed-count @indexing-state)))))
+ (is (= 0 (:last-novel-count @indexing-state)))))
(testing "add some more data, picked up"
(clear-spies)
@@ -119,7 +120,7 @@
(is (= 1 (count @upsert-calls)))
(is (= 0 (count @delete-calls)))
(is (= 1 (count @poll-calls)))
- (is (= 1 (:last-indexed-count @indexing-state)))))
+ (is (= 1 (:last-novel-count @indexing-state)))))
(testing "exceptions during indexing are bubbled, and the watermark position is preserved"
(clear-spies)
@@ -147,28 +148,28 @@
;; todo not sure I like this cuteness
(deftest on-indexing-idle-test
(testing "idle behavior based on novelty ratio"
- (let [indexing-state (volatile! {:last-poll-count 100 :last-indexed-count 30})]
+ (let [indexing-state (volatile! {:last-poll-count 100 :last-novel-count 30})]
(testing "high novelty ratio (>25%) - no sleep"
(with-redefs [semantic.indexer/sleep (fn [ms] (throw (ex-info "Should not sleep" {:ms ms})))]
(is (nil? (semantic.indexer/on-indexing-idle indexing-state)))))
(testing "medium novelty ratio (10-25%) - small backoff"
- (vswap! indexing-state assoc :last-indexed-count 15) ; 15% novelty
+ (vswap! indexing-state assoc :last-novel-count 15) ; 15% novelty
(let [sleep-called (atom nil)]
(with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
(is (= 250 @sleep-called)))))
(testing "low novelty ratio (1-10%) - medium backoff"
- (vswap! indexing-state assoc :last-indexed-count 5) ; 5% novelty
+ (vswap! indexing-state assoc :last-novel-count 5) ; 5% novelty
(let [sleep-called (atom nil)]
(with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
(is (= 1500 @sleep-called)))))
(testing "very low novelty ratio (<1%) - big backoff"
- (vswap! indexing-state assoc :last-indexed-count 0) ; 0% novelty
+ (vswap! indexing-state assoc :last-novel-count 0) ; 0% novelty
(let [sleep-called (atom nil)]
(with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
@@ -344,9 +345,14 @@
(is (= (ts "2025-01-01T12:00:00Z") (get-in state-value [:watermark :last-poll])))
(is (= expected-last-seen (get-in state-value [:watermark :last-seen])))
(is (= #{expected-last-seen} (:last-seen-candidates state-value)))
- (is (zero? (:last-indexed-count state-value)))
+ (is (zero? (:last-novel-count state-value)))
(is (zero? (:last-poll-count state-value))))))
+(defn- open-dlq! ^Closeable [pgvector index-metadata index-id]
+ (semantic.tu/closeable
+ (semantic.dlq/create-dlq-table-if-not-exists! pgvector index-metadata index-id)
+ (fn [_] (semantic.dlq/drop-dlq-table-if-exists! pgvector index-metadata index-id))))
+
(deftest quartz-job-run!-test
(let [pgvector semantic.tu/db
index-metadata (semantic.tu/unique-index-metadata)
@@ -404,9 +410,306 @@
(testing "exit on exception/error during loop"
(with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index {} :metadata-row {}})
semantic.indexer/indexing-loop (fn [& _] (throw ex))]
- (with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
(let [{:keys [caught-ex ^Thread thread]} @job-thread]
(testing "thread exited"
(is (.join thread (Duration/ofSeconds 5))))
(testing "crashed with expected msg"
- (is (= (ex-message ex) (ex-message @caught-ex)))))))))))
+ (is (= (ex-message ex) (ex-message @caught-ex)))))))))
+
+ (testing "initial dlq run is scheduled if table exists"
+ (let [loop-args (atom [])
+ metadata-row {:id 42
+ :indexer_last_poll (ts "2025-01-01T12:00:00Z")
+ :indexer_last_seen (ts "2025-01-01T11:30:00Z")}
+ index {:table-name "foo"}
+ t (Instant/parse "2025-01-01T23:14:43Z")]
+ (with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index index :metadata-row metadata-row})
+ semantic.indexer/indexing-loop (fn [& args] (swap! loop-args conj args) nil)
+ semantic.indexer/clock (reify InstantSource (instant [_] t))]
+ (with-open [_ (open-dlq! pgvector index-metadata (:id metadata-row)) ; right now index id only matters for the table name, use anything
+ job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (let [{:keys [caught-ex ^Thread thread]} @job-thread]
+ (testing "thread exited (loop returned)"
+ (is (.join thread (Duration/ofSeconds 5))))
+ (testing "args as expected"
+ (is (= 1 (count @loop-args)))
+ (let [[[_ _ _ indexing-state]] @loop-args]
+ (is (= (.plus t semantic.indexer/dlq-frequency) (:next-dlq-run @indexing-state)))))
+ (testing "did not crash"
+ (is (nil? @caught-ex))))))))))
+
+(deftest dlq-step-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ sut semantic.indexer/dlq-step
+ clock-ref (volatile! (Instant/parse "2025-01-04T00:00:00Z"))
+ clock (reify InstantSource (instant [_] @clock-ref))
+ dlq-loop-impl (volatile! (constantly nil))
+ run-scenario (fn [{:keys [indexing-state dlq-loop-return]}]
+ (vreset! dlq-loop-impl (constantly dlq-loop-return))
+ (let [indexing-state-ref (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))]
+ (vswap! indexing-state-ref merge indexing-state)
+ (sut pgvector index-metadata index indexing-state-ref)
+ @indexing-state-ref))]
+ (with-redefs [semantic.dlq/dlq-retry-loop! (fn [& args] (apply @dlq-loop-impl args))
+ semantic.indexer/clock clock
+ semantic.dlq/clock clock]
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)
+ index-id-ref (semantic.tu/closeable
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+ (constantly nil))
+ _ (open-dlq! pgvector index-metadata @index-id-ref)]
+
+ (testing "dlq rescheduled after no change"
+ (let [original-last-seen-change (Instant/parse "2025-01-12T03:22:45Z")
+ {:keys [last-seen-change next-dlq-run]}
+ (run-scenario {:indexing-state {:last-seen-change original-last-seen-change}
+ :dlq-loop-return {:exit-reason :no-more-data,
+ :run-time (Duration/parse "PT42S")
+ :success-count 0
+ :failure-count 0}})
+ expected-next-dlq-run (.plus (.instant clock) semantic.indexer/dlq-frequency)]
+ (testing ":last-seen-change not modified - would allow cold exit"
+ (is (= original-last-seen-change last-seen-change)))
+ (is (= expected-next-dlq-run next-dlq-run))))
+
+ (testing "dlq rescheduled after change (no more data, should back off)"
+ (let [{:keys [last-seen-change next-dlq-run]}
+ (run-scenario {:dlq-loop-return {:exit-reason :no-more-data,
+ :run-time (Duration/parse "PT12S")
+ :success-count 1
+ :failure-count 0}})
+ expected-next-dlq-run (.plus (.instant clock) semantic.indexer/dlq-frequency)]
+ (is (= (.instant clock) last-seen-change))
+ (is (= expected-next-dlq-run next-dlq-run))))
+
+ (testing "dlq rescheduled immediately after change (ran out of time, more to do)"
+ (let [{:keys [last-seen-change next-dlq-run]}
+ (run-scenario {:dlq-loop-return {:exit-reason :ran-out-of-time
+ :run-time (Duration/parse "PT15S")
+ :success-count 1
+ :failure-count 0}})]
+ (is (= (.instant clock) last-seen-change))
+ (is (= (.instant clock) next-dlq-run))))
+
+ ;; for now policy for this branch is the same as the above - but may change
+ (testing "dlq rescheduled immediately after change (ran out of time, more to do - failures)"
+ (let [{:keys [last-seen-change next-dlq-run]}
+ (run-scenario {:dlq-loop-return {:exit-reason :ran-out-of-time
+ :run-time (Duration/parse "PT12S")
+ :success-count 2
+ :failure-count 3}})]
+ (is (= (.instant clock) last-seen-change))
+ (is (= (.instant clock) next-dlq-run))))))))
+
+(defn- get-dlq-rows! [pgvector index-metadata index-id]
+ (let [q {:select [:*] :from [(semantic.dlq/dlq-table-name-kw index-metadata index-id)]}]
+ (jdbc/execute! pgvector (sql/format q :quoted true) {:builder-fn jdbc.rs/as-unqualified-lower-maps})))
+
+(deftest indexer-stall-and-recovery-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ clock-ref (volatile! (Instant/parse "2025-01-04T10:00:00Z"))
+ clock (reify InstantSource (instant [_] @clock-ref))
+ t1 (ts "2025-01-01T00:01:00Z")
+ card (fn [id] {:model "card" :id (str id) :name "Test" :searchable_text "Content"})
+ version semantic.gate/search-doc->gate-doc
+ fresh-indexing-state (fn []
+ (let [state (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))]
+ (vswap! state assoc :next-dlq-run (.instant clock)) ; ensure DLQ is scheduled
+ state))]
+
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)
+ index-id-ref (semantic.tu/closeable
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+ (constantly nil))
+ _ (open-dlq! pgvector index-metadata @index-id-ref)]
+
+ (with-redefs [semantic.indexer/clock clock
+ semantic.dlq/clock clock
+ ;; assume during this test that we are on the 'confident' gate poll branch.
+ semantic.indexer/lag-tolerance Duration/ZERO]
+
+ (testing "normal indexing without stalls"
+ (let [indexing-state (fresh-indexing-state)]
+ (semantic.gate/gate-documents! pgvector index-metadata [(version (card 1) t1)])
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+
+ (is (nil? (:stalled-at @indexing-state)))
+ (is (nil? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))))))
+
+ (testing "indexing failure marks as stalled"
+ (let [indexing-state (fresh-indexing-state)]
+ (semantic.gate/gate-documents! pgvector index-metadata [(version (card 2) t1)])
+
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Index failure")))]
+ (is (thrown? RuntimeException (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)))
+ (is (some? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))))))
+
+ (testing "stalled indexing before grace period continues to throw"
+ (let [indexing-state (fresh-indexing-state)
+ stall-time (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))
+ initial-clock (.instant clock)]
+ (is (some? stall-time))
+ (is (= stall-time (:stalled-at @indexing-state)))
+
+ ;; Advance clock but (just about) stay within grace period
+ (vreset! clock-ref (.plus initial-clock (.minus semantic.indexer/stall-grace-period (Duration/ofSeconds 1))))
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing during grace period")))]
+ (is (thrown? RuntimeException (semantic.indexer/indexing-step pgvector index-metadata index indexing-state))))
+
+ ;; Stall time should not be overwritten (retains original lower value)
+ (let [current-stall-time (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))]
+ (is (= stall-time current-stall-time))))))
+
+ (testing "recovery from stall clears stall status"
+ (let [indexing-state (fresh-indexing-state)
+ stall-time (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))]
+ (is (some? stall-time))
+ (semantic.gate/gate-documents! pgvector index-metadata [(version (card 3) t1)])
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (nil? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))))))
+
+ (testing "stalled indexing uses DLQ after grace period"
+ (let [indexing-state (fresh-indexing-state)
+ initial-watermark (:watermark @indexing-state)]
+ (vswap! indexing-state assoc :stalled-at (Timestamp/from (.instant clock)))
+ (vreset! clock-ref (-> (.instant clock)
+ (.plus semantic.indexer/stall-grace-period)
+ (.plus (Duration/ofSeconds 1))))
+ (semantic.gate/gate-documents! pgvector index-metadata [(version (card 4) t1)])
+
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing")))]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+
+ (testing "DLQ entries created"
+ (let [dlq-rows (get-dlq-rows! pgvector index-metadata @index-id-ref)]
+ (is (seq dlq-rows))
+ (is (= ["card_4"] (map :gate_id dlq-rows)))))
+
+ (testing "watermark progresses despite failures"
+ (let [new-watermark (:watermark @indexing-state)]
+ (is (not= initial-watermark new-watermark))
+ (is (= -1 (compare (:last-poll initial-watermark) (:last-poll new-watermark)))))))))))))
+
+(deftest dlq-integration-with-indexer-loop-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ clock-ref (volatile! (Instant/parse "2025-01-04T10:00:00Z"))
+ clock (reify InstantSource (instant [_] @clock-ref))
+ t1 (ts "2025-01-01T00:01:00Z")
+ card (fn [id content] {:model "card" :id (str id) :name content :searchable_text content})
+ version semantic.gate/search-doc->gate-doc
+ poisoned-doc-id (volatile! nil)
+ get-indexed-docs (fn []
+ (jdbc/execute! pgvector
+ (sql/format {:select [:model_id] :from [(keyword (:table-name index))]} :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+ upsert-index! semantic.index/upsert-index!]
+
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)
+ _ (semantic.tu/open-index! pgvector index)
+ index-id-ref (semantic.tu/closeable
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+ (constantly nil))
+ _ (open-dlq! pgvector index-metadata @index-id-ref)]
+
+ (with-redefs [semantic.indexer/lag-tolerance Duration/ZERO
+ semantic.indexer/dlq-frequency Duration/ZERO ; every loop iteration
+ semantic.indexer/dlq-max-run-duration (Duration/ofSeconds 2)
+ semantic.indexer/stall-grace-period Duration/ZERO
+ semantic.indexer/sleep (fn [_])
+ semantic.dlq/initial-backoff Duration/ZERO
+ semantic.dlq/transient-policy (semantic.dlq/linear-policy (Duration/ofMillis 1))
+ ;; upsert to track indexed docs and poison specific documents
+ semantic.index/upsert-index! (fn [pgvector index docs]
+ (run! (fn [doc]
+ (when (= (:id doc) @poisoned-doc-id)
+ (throw (RuntimeException. "Poisoned document"))))
+ docs)
+ (when (seq docs)
+ ;; Insert into actual index
+ (upsert-index! pgvector index docs)))]
+
+ (testing "indexer loop with poisoned document uses DLQ correctly"
+ (let [good-docs [(card 1 "Good Doc 1") (card 2 "Good Doc 2") (card 3 "Good Doc 3")]
+ bad-doc (card 4 "Poisoned Doc")
+ all-docs (conj good-docs bad-doc)]
+
+ ;; Set up poisoned document
+ (vreset! poisoned-doc-id (str (:id bad-doc)))
+
+ ;; Add all documents to gate
+ (semantic.gate/gate-documents! pgvector index-metadata (map #(version % t1) all-docs))
+
+ ;; Create indexing state with short durations and DLQ scheduling
+ (let [fresh-indexing-state (fn []
+ (doto (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))
+ (vswap! assoc
+ :max-run-duration (Duration/ofSeconds 3)
+ :exit-early-cold-duration (Duration/ofSeconds 3)
+ :next-dlq-run (.instant clock))))]
+
+ (testing "Initial loop will exit with the expected exception"
+ (with-open [loop-thread (open-loop-thread! pgvector index-metadata index (fresh-indexing-state))]
+ (let [{:keys [^Thread thread caught-ex]} @loop-thread]
+ (is (.join thread (Duration/ofSeconds 5)) "dies in a reasonable amount of time")
+ (is (= "Poisoned document" (ex-message @caught-ex)))
+ (is (some? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index)))))))
+
+ (testing "dead letter queue is drained, everything can eventually be indexed"
+ (with-open [loop-thread (open-loop-thread! pgvector index-metadata index (fresh-indexing-state))]
+ (let [{:keys [^Thread thread]} @loop-thread
+ start-time (u/start-timer)]
+ (testing "stall is cleared (dlq allowed us to seek to the gate tail)"
+ (is
+ (loop []
+ (cond
+ (< 1000 (u/since-ms start-time)) false
+ (nil? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))) true
+ :else (recur)))))
+
+ (testing "good docs get indexed right away, despite the poison"
+ (is
+ (= (frequencies (map :id good-docs))
+ (frequencies (map :model_id
+ (loop [indexed-docs (get-indexed-docs)]
+ (cond
+ (< 1000 (u/since-ms start-time)) indexed-docs
+ (= (count good-docs) (count indexed-docs)) indexed-docs
+ :else (recur (get-indexed-docs)))))))))
+
+ (testing "only 1 dlq entry left"
+ (is (= 1 (count (get-dlq-rows! pgvector index-metadata @index-id-ref)))))
+
+ (testing "clear the poison"
+ (vreset! poisoned-doc-id nil)
+ (testing "all docs get indexed"
+ (is
+ (= (frequencies (map :id all-docs))
+ (frequencies (map :model_id
+ (loop [indexed-docs (get-indexed-docs)]
+ (cond
+ (< 1000 (u/since-ms start-time)) indexed-docs
+ (= (count all-docs) (count indexed-docs)) indexed-docs
+ :else (recur (get-indexed-docs))))))))))
+
+ (testing "dlq drained (allow for a bit of time)"
+ (is (= []
+ (loop [rows (get-dlq-rows! pgvector index-metadata @index-id-ref)]
+ (cond
+ (< 1000 (u/since-ms start-time)) rows
+ (empty? rows) rows
+ :else (recur (get-dlq-rows! pgvector index-metadata @index-id-ref)))))))
+
+ (.interrupt thread)
+ (is (.join thread (Duration/ofSeconds 1)) "dies in a reasonable amount of time")))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
index 6621848137d..48f0603ab18 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer :all]
[honey.sql :as sql]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
[metabase-enterprise.semantic-search.indexer :as semantic.indexer]
@@ -38,6 +39,8 @@
(is (= @index-ref (:index active-state)))
(is (= model1 (:embedding-model (:index active-state))))
(is (= (:model-name model1) (:model_name (:metadata-row active-state))))
+ (testing "dlq is created"
+ (is (semantic.tu/table-exists-in-db? (semantic.dlq/dlq-table-name-kw index-metadata (:id (:metadata-row active-state))))))
(testing "idempotent"
(let [new-index @(sut pgvector index-metadata model1)]
(is (= @index-ref new-index))
@@ -46,7 +49,9 @@
(let [new-index @(sut pgvector index-metadata model2)
active-state (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
(is (= model2 (:embedding-model new-index)))
- (is (= new-index (:index active-state))))
+ (is (= new-index (:index active-state)))
+ (testing "new dlq is created"
+ (is (semantic.tu/table-exists-in-db? (semantic.dlq/dlq-table-name-kw index-metadata (:id (:metadata-row active-state)))))))
(testing "model1 index still exists"
(is (=? {:index {:embedding-model model1}
:active false
@@ -237,10 +242,10 @@
(.interrupt thread)
(when-not (.join thread (Duration/ofSeconds 30))
(log/fatal "Indexing loop thread not exiting during test!")))))))]
- (with-redefs [semantic.indexer/sleep (fn [_]) ; do not slow down
+ (with-redefs [semantic.indexer/sleep (fn [_]) ; do not slow down
; important to test poll / paging (not many docs in test-data)
- semantic.settings/ee-search-indexer-poll-limit (constantly 4)
- semantic.indexer/lag-tolerance Duration/ZERO] ; if too high will slow the test down significantly
+ semantic.settings/ee-search-indexer-poll-limit (constantly 4)
+ semantic.indexer/lag-tolerance Duration/ZERO] ; if too high will slow the test down significantly
(with-open [index-ref (open-semantic-search! pgvector index-metadata embedding-model)
job-thread ^Closeable (open-job-thread pgvector index-metadata)]
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj
index 0a5159e7d0e..660bcaf5e58 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj
@@ -8,11 +8,13 @@
[metabase-enterprise.semantic-search.core]
[metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
[metabase-enterprise.semantic-search.db.migration :as semantic.db.migration]
+ [metabase-enterprise.semantic-search.dlq :as semantic.dlq]
[metabase-enterprise.semantic-search.embedding :as semantic.embedding]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
[metabase-enterprise.semantic-search.indexer :as semantic.indexer]
[metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
+ [metabase-enterprise.semantic-search.util :as semantic.util]
[metabase.search.engine :as search.engine]
[metabase.search.ingestion :as search.ingestion]
[metabase.test :as mt]
@@ -225,7 +227,7 @@
[results]
(filter #(contains? mock-embeddings (:name %)) results))
-(defn closeable [o close-fn]
+(defn closeable ^Closeable [o close-fn]
(reify
IDeref
(deref [_] o)
@@ -310,7 +312,7 @@
:indexer_last_seen Instant/EPOCH}
indexing-state (semantic.indexer/init-indexing-state metadata-row)
step (fn [] (semantic.indexer/indexing-step db mock-index-metadata mock-index indexing-state))]
- (while (do (step) (pos? (:last-indexed-count @indexing-state))))))
+ (while (do (step) (pos? (:last-novel-count @indexing-state))))))
(defmacro blocking-index!
"Execute body ensuring [[index-all!]] is invoked at the end"
@@ -325,7 +327,7 @@
`(with-indexable-documents!
(with-redefs [semantic.embedding/get-configured-model (fn [] mock-embedding-model)
semantic.index-metadata/default-index-metadata mock-index-metadata
- semantic.index/model-table-suffix mock-table-suffix]
+ semantic.index/model-table-suffix mock-table-suffix]
(with-open [_# (open-temp-index-and-metadata!)]
(binding [search.ingestion/*force-sync* true]
(blocking-index!
@@ -337,10 +339,7 @@
[table-name]
(when table-name
(try
- (let [result (jdbc/execute! db
- ["SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = ?)"
- (name table-name)])]
- (-> result first vals first))
+ (semantic.util/table-exists? db (name table-name))
(catch Exception _ false))))
(defn table-has-index?
@@ -371,10 +370,11 @@
(defn cleanup-index-metadata!
"A-la-carte drop everything related to the index-metdata root (including index tables themselves)"
[pgvector index-metadata]
- (doseq [{:keys [table_name]}
+ (doseq [{index-id :id, :keys [table_name]}
(when (table-exists-in-db? (:metadata-table-name index-metadata))
(get-metadata-rows pgvector index-metadata))]
- (semantic.index/drop-index-table! pgvector {:table-name table_name}))
+ (semantic.index/drop-index-table! pgvector {:table-name table_name})
+ (semantic.dlq/drop-dlq-table-if-exists! pgvector index-metadata index-id))
(semantic.index-metadata/drop-tables-if-exists! pgvector index-metadata)
(semantic.db.migration/drop-migration-table! pgvector))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj
index 64766ab8ee2..c049c7097df 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj
@@ -18,10 +18,10 @@
(mt/with-premium-features #{:semantic-search}
(try
(semantic.tu/cleanup-index-metadata! semantic.tu/db semantic.tu/mock-index-metadata)
- (with-redefs [semantic.db.datasource/data-source (atom nil)
- semantic.env/get-index-metadata (constantly semantic.tu/mock-index-metadata)
+ (with-redefs [semantic.db.datasource/data-source (atom nil)
+ semantic.env/get-index-metadata (constantly semantic.tu/mock-index-metadata)
semantic.env/get-configured-embedding-model (constantly semantic.tu/mock-embedding-model)
- semantic.index/model-table-suffix semantic.tu/mock-table-suffix]
+ semantic.index/model-table-suffix semantic.tu/mock-table-suffix]
(test-func))
(finally
(semantic.tu/cleanup-index-metadata! semantic.tu/db semantic.tu/mock-index-metadata)))))