Subject: Re: bug#74718: 29.4; Huge metadata with flex completion style

From: Stefan Monnier <[email-masked]>
Date: Tue, 10 Dec 2024 16:54:00 -0500

> Here the offending code in minibuffer.el (in
> completion--nth-completion):
>
> --8<---------------cut here---------------start------------->8---
>    (adjust-fn (get (cdr result-and-style) 'completion--adjust-metadata)))
>     (when (and adjust-fn metadata)
>       (setcdr metadata (cdr (funcall adjust-fn metadata))))
> --8<---------------cut here---------------end--------------->8---

Thanks Thierry.
The above code is indeed a hack we should try get rid of.
I suspect it remained unnoticed until now because most UIs get a "fresh"
new metadata before calling `completion-try/all-completions`, but we
shouldn't rely on such a property.

I think I vaguely remember when this code was added that we discussed
whether it's OK to do that (for all I know, I may even have suggested
this hack), so replacing it with a more robust solution may be
not straightforward.

In the mean time, maybe a patch like the one below can temporarily paper
over the underlying problem?

        Stefan

diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index 405ee21cdb2..d258085c778 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -1307,9 +1307,15 @@ completion--nth-completion
                                string table pred point)))
                    (and probe (cons probe style))))))
            (completion--styles md)))
-         (adjust-fn (get (cdr result-and-style) 'completion--adjust-metadata)))
-    (when (and adjust-fn metadata)
-      (setcdr metadata (cdr (funcall adjust-fn metadata))))
+         (adjust-fn (get (cdr result-and-style) 'completion--adjust-metadata))
+         (adjusted (completion-metadata-get
+                    metadata 'completion--adjusted-metadata)))
+    (when (and adjust-fn metadata
+               ;; Avoid re-applying the same adjustment (bug#74718).
+               (not (memq (cdr result-and-style) adjusted)))
+      (setcdr metadata `((completion--adjusted-metadata
+                          ,(cdr result-and-style) . ,adjusted)
+                         . ,(cdr (funcall adjust-fn metadata)))))
     (if requote
         (funcall requote (car result-and-style) n)
       (car result-and-style))))