Skip to content

Commit d6a8462

Browse files
committed
fix: AnswerBuilder returned referenced documents in scrambled order
The referenced document indices were kept in a set and iterated directly, so the returned documents came out in the set's hash-table order rather than ascending source-index order (e.g. citations [3] [10] [50] yielded documents ordered 10, 3, 50). This order was deterministic but did not match the source order. Iterate the indices sorted so documents follow ascending source index.
1 parent b69e9aa commit d6a8462

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

haystack/components/builders/answer_builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def run(
222222
else set(range(len(documents)))
223223
)
224224

225-
for idx in doc_idxs:
225+
for idx in sorted(doc_idxs):
226226
try:
227227
doc = documents[idx]
228228
except IndexError:
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
fixes:
3+
- |
4+
Fixed ``AnswerBuilder`` returning referenced documents in a scrambled order
5+
instead of ascending source-index order. The referenced document indices
6+
were collected in a ``set`` and iterated directly, so documents were emitted
7+
in the set's internal hash-table order (e.g. citations [3] [10] [50]
8+
yielded documents ordered 10, 3, 50). This order was deterministic but did
9+
not match the intuitive source order. The referenced documents are now
10+
returned sorted by their source index.

test/components/builders/test_answer_builder.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,16 @@ def test_run_with_documents_with_reference_pattern(self):
146146
assert answers[0].documents[0].meta["referenced"] is True
147147
assert answers[0].documents[0].meta["source_index"] == 2
148148

149+
def test_run_returns_referenced_documents_in_source_order(self):
150+
component = AnswerBuilder(reference_pattern="\\[(\\d+)\\]", return_only_referenced_documents=True)
151+
output = component.run(
152+
query="test query",
153+
replies=["First [3], then [10], and finally [50]."],
154+
documents=[Document(content=f"doc{i}") for i in range(1, 51)],
155+
)
156+
source_indices = [doc.meta["source_index"] for doc in output["answers"][0].documents]
157+
assert source_indices == [3, 10, 50]
158+
149159
def test_run_with_documents_with_reference_pattern_return_all_documents(self):
150160
component = AnswerBuilder(reference_pattern="\\[(\\d+)\\]", return_only_referenced_documents=False)
151161
output = component.run(

0 commit comments

Comments
 (0)