Re-sorted items in the AI Search Backend lose their search API entity ID keys
>>> [!note] Migrated issue <!-- Drupal.org comment --> <!-- Migrated from issue #3579657. --> Reported by: [meanderix](https://www.drupal.org/user/2648149) Related to !36 !34 >>> <p>I was using Codex for an unrelated issue, when the following was detected (comments by Codex).</p> <p>I ran into what looks like a small key-preservation bug in <code>modules/ai_search/src/Plugin/search_api/backend/SearchApiAiSearchBackend.php</code>.</p> <p>The backend builds the result set with item IDs as array keys, but when <code>search_api_relevance</code> sorting is applied it uses <code>usort()</code> on <code>$results-&gt;getResultItems()</code>. That reindexes the array numerically and drops the original Search API item IDs.</p> <p>Later, when Search API preloads original objects from the result set, it uses the array keys as item IDs. Because the keys have been rewritten to <code>0, 1, 2, ...</code>, Search API ends up trying to resolve items with an empty datasource ID and logs:</p> <p><code>Drupal\search_api\SearchApiException: The datasource with ID '' could not be retrieved for index 'AI content'.</code></p> <p>In my case this was easy to trigger from application code that iterates AI Search results and calls <code>$item-&gt;getOriginalObject()</code> / accesses the entity. A local eval command reproduced it consistently for a relevance-sorted AI Search query.</p> <p>The fix seems to be to use <code>uasort()</code> instead of <code>usort()</code> so the existing item-ID keys are preserved while still sorting by score.</p> <p>Patch attached.</p>
issue