haystack icon indicating copy to clipboard operation
haystack copied to clipboard

Run typing checks on our test files

Open sjrl opened this issue 10 months ago • 22 comments

While working on changes to haystack-experimental (https://github.com/deepset-ai/haystack-experimental/pull/430) I wanted to ensure that the protocol I was developing was working as expected with the respective implementations.

I realized though that we never actually test whether our implementations satisfy our protocols since we don't do any type checks on actual test-like code.

Therefore, I think it would be a good idea if we add type checking to our test code in our repos so we can better catch these issues. This will be quite a bit work to get our tests fully compliant but perhaps we could do it in a piece-meal approach where we only turn on type checking in a small part of tests and grow from there.

Components

  • [x] test/components/audio/
  • [x] test/components/builders/
  • [x] test/components/caching/
  • [ ] test/components/classifiers/
  • [ ] test/components/connectors/
  • [x] test/components/converters/
  • [x] test/components/embedders/
  • [ ] test/components/evaluators/
  • [x] test/components/extractors/
  • [x] test/components/fetchers/
  • [x] test/components/generators/
  • [x] test/components/joiners/
  • [ ] test/components/preprocessors/
  • [x] test/components/query/
  • [x] test/components/rankers/
  • [ ] test/components/readers/
  • [x] test/components/retrievers/
  • [ ] test/components/routers/
  • [x] test/components/samplers/
  • [ ] test/components/tools/
  • [x] test/components/validators/
  • [ ] test/components/websearch/
  • [x] test/components/writers/

Document Stores

  • [x] test/document_stores/

Agents

  • [ ] test/components/agents/

Other

  • [x] test/core/
  • [x] test/dataclasses/
  • [x] test/evaluation/
  • [x] test/fuzz/
  • [ ] test/hooks/
  • [x] test/human_in_the_loop/
  • [x] test/marshal/
  • [x] test/skill_stores/
  • [x] test/testing/
  • [ ] test/token_counters/
  • [x] test/tools/ (top-level, distinct from test/components/tools/)
  • [x] test/tracing/
  • [x] test/utils/

sjrl avatar Jan 16 '26 13:01 sjrl

Hi, is this still relevant? Should I take it?

Jventajas avatar Jul 01 '26 10:07 Jventajas

I took the next piece of this, test/components/embedders/. Most of the errors there were tests passing a wrong type on purpose to check the raised TypeError, plus a few missing annotations. Opening a PR now.

omborda2002 avatar Jul 03 '26 10:07 omborda2002

I can take the next small increment for this issue: add test/components/caching/ to the existing mypy target, fix only the type errors needed in its two CacheChecker test modules, and run the focused mypy/pytest checks before opening a PR. I checked that the existing recent contribution covered test/components/embedders/; I will keep this scope disjoint.

yaodong-shen avatar Aug 02 '26 15:08 yaodong-shen

Working on adding typing checks for \ est/components/writers/!

Aryan-Pardeshi avatar Aug 07 '26 21:08 Aryan-Pardeshi

#12318 covers test/components/joiners/.

The checklist above has drifted from the types allowlist in pyproject.toml, which makes it easy to pick something that is already done:

Already in the allowlist on main, but unchecked here: test/core/, test/dataclasses/, test/document_stores/, test/evaluation/, test/marshal/, test/testing/, test/tools/, test/tracing/, test/utils/, test/components/caching/, test/components/generators/.

Listed here but no longer in the repo: test/components/audio/, classifiers/, connectors/, readers/, tools/, websearch/, and test/human_in_the_loop/ (now test/hooks/human_in_the_loop, already in the allowlist).

That leaves 19 directories actually open: agents, builders, converters, evaluators, extractors, fetchers, joiners (this PR), preprocessors, query, rankers, retrievers, routers, samplers and validators under test/components/, plus test/fuzz/, test/skill_stores/, test/token_counters/, test/hooks/compaction/ and test/hooks/tool_result_offloading/.

atikulmunna avatar Aug 12 '26 10:08 atikulmunna

I can take the next disjoint increment: est/components/agents/. I verified that it is not yet in the current ypes allowlist and found no open or closed PR claiming that directory. I will first run the directory through the repository's mypy configuration, keep changes limited to test typing fixes plus the allowlist entry, and run the focused agent tests and formatting before opening a PR.

KXHXK avatar Aug 12 '26 20:08 KXHXK

Baseline result: type-checking the full est/components/agents/ directory currently reports 136 errors across six files, so treating it as one increment would be too broad and review-heavy. I am narrowing this contribution to est/components/agents/test_state_class.py, which has three related generic-inference errors in one test. I will add that file to the mypy target, make the minimal type annotation needed, and validate the file plus the focused tests. The remaining agent test files stay unclaimed.

KXHXK avatar Aug 12 '26 20:08 KXHXK

I can take the next disjoint increment: test/components/extractors/.

It's not in the types allowlist in pyproject.toml on main, and I found no open or closed PR claiming it... the increments currently in flight are test/components/rankers/ (#12319) and test/components/agents/test_state_class.py (#12327), both disjoint from this.

Baseline is 6 errors across 3 files, so it works as a single reviewable increment rather than needing to be narrowed further:

  • test_regex_text_extractor.py: a missing annotation, and a deliberate wrong-type call under pytest.raises(TypeError)
  • test_llm_metadata_extractor.py: a deliberate missing-argument call, plus "ChatGenerator" has no attribute "to_dict" in test_from_dict_openai
  • image/test_llm_document_content_extractor.py: a deliberate missing-argument call, and len() on a str | None

The to_dict one is the protocol-vs-implementation gap this issue was opened for, so I narrowed it with isinstance rather than an ignore, that also pins that from_dict rebuilt an OpenAIChatGenerator.

Changes stay limited to test typing fixes plus the allowlist entry. Opening the PR shortly.

-Anmol :)

abhati27 avatar Aug 13 '26 22:08 abhati27

I can take test/components/routers/ next. It is not in the types allowlist on main, and there is no open or closed PR covering it.

Baseline: 63 errors across 4 test files, 43 of them in test_conditional_router.py.

The bulk are arg-type, from route lists being inferred as list[dict[str, object]] where list[Route] is expected. Since Route is a TypedDict, annotating those literals is worth more than silencing the error: mypy then checks each route against the actual schema (condition, output, output_name, output_type) instead of accepting any dict.

The rest are union-attr where the metadata router tests reach for .data or .content on a Document | ByteStream, plus a few attr-defined on the __haystack_input__ / __haystack_output__ attributes the @component decorator adds at runtime.

Planning to keep it to one PR, same shape as #12318 and #12319.

atikulmunna avatar Aug 14 '26 18:08 atikulmunna

I can take the next disjoint increment: test/components/converters/test_utils.py. It is not in the current types allowlist, and I found no open or closed PR or issue comment claiming this file. The repository mypy baseline reports two deliberate invalid-input calls in this file; I will keep the change to the allowlist entry plus minimal typing annotations for those calls, then run the focused mypy/pytest checks and formatting before opening a PR.

Gout999 avatar Aug 18 '26 10:08 Gout999

Opened #12433 covering test/components/samplers/, picking a directory that doesn't overlap the increments already in flight (#12343 has extractors/).

Baseline there was 2 errors, both the same one:

test/components/samplers/test_top_p.py:68: error: Value of type variable "SupportsRichComparisonT" of "sorted" cannot be "float | None"  [type-var]
test/components/samplers/test_top_p.py:87: error: same

The directory only holds __init__.py and test_top_p.py, so it's fully covered.

Still unclaimed as far as I can tell, if anyone is looking for a next increment: evaluators/, fetchers/ (4 errors), preprocessors/, retrievers/, hooks/budget/, and hooks/tool_result_offloading/ (4 errors). builders/ has 25 and is probably worth splitting.

[!NOTE] AI-assisted (Claude Code); verified before posting.

sainikhiljuluri avatar Aug 22 '26 07:08 sainikhiljuluri

I can take the next disjoint increment: test/components/fetchers/.

Current main still omits it from the types target, and the directory contains one test module with four current mypy errors. I’ll keep this scoped to the minimal typing fixes in test/components/fetchers/test_link_content_fetcher.py plus the pyproject.toml target entry, then run the focused mypy check, focused unit tests, and formatting before opening a PR.

I’ll also disclose the AI-assisted implementation and review in the PR.

samrusani avatar Aug 22 '26 17:08 samrusani

I can take the next disjoint increment: test/components/evaluators/.

It is not in the current types target, and it doesn't overlap the increments already in flight: #12435 has fetchers/, #12343 has extractors/, #12433 has samplers/, and @Gout999 claimed converters/test_utils.py.

Current baseline there is 19 mypy errors across 5 of the 10 test modules:

  • 6 var-annotated on empty list literals in test_document_recall.py and test_document_ndcg.py, which just need an annotation.
  • 11 in test_llm_evaluator.py and test_sas_evaluator.py that come from deliberate invalid-input calls inside pytest.raises blocks, so those get narrow # type: ignore[...] comments in the same style as #12394.
  • 3 attr-defined on __haystack_output__, which the @component decorator adds at runtime.

I'll keep this scoped to the minimal typing fixes plus the types target entry in pyproject.toml, with no change to what any test asserts.

ShousenZHANG avatar Aug 23 '26 12:08 ShousenZHANG

I can take the next disjoint increment: test/components/builders/.

It is not in the current types target on main, and no open or closed PR or comment covers it. The increments in flight are extractors/ (#12343), samplers/ (#12433) and fetchers/ (#12435), so this doesn't overlap any of them.

Baseline is 25 errors across 2 of the 3 test modules:

  • 12 attr-defined on __haystack_input__ / __haystack_output__, which the @component decorator attaches at runtime.
  • 8 index / union-attr from reading builder.template[0].text, where template is typed list[ChatMessage] | str | None. Those get narrowed with an assert rather than silenced.
  • 1 list-item on a deliberate mixed-type template inside a validation test, so that one gets a narrow # type: ignore[list-item].
  • 2 no-untyped-def for missing return annotations.

Scoped to the minimal typing fixes plus the types target entry, with no change to what any test asserts.

Note for whoever picks the next one: every increment edits the same single types = "..." line in pyproject.toml, so whichever lands first leaves the others conflicting. #12433 and #12435 are both showing conflicts right now and just need a rebase of that one line.

ShousenZHANG avatar Aug 25 '26 00:08 ShousenZHANG

I can take the next disjoint increment: test/components/retrievers/.

It is not in the current types target on main, and no open or closed PR or comment covers it. It also doesn't overlap fetchers/ (#12435), the only increment still in flight.

Baseline is 78 errors across 11 of the 16 test modules, concentrated in three files:

  • test_auto_merging_retriever.py / _async.py (20 each) — mostly call-overload from a docs variable that is first the dict returned by HierarchicalDocumentSplitter.run and then reassigned to a retriever result, so mypy can't keep one type for it. Fixed by giving the two values separate names.
  • test_multi_retriever.py (18) — no-untyped-def and assignment.
  • The remaining 8 files have 1-7 errors each: type-var on sorted over float | None, method-assign on monkeypatched to_dict, and a no-redef on a re-annotated local.

Scoped to the minimal typing fixes plus the types target entry, with no change to what any test asserts.

ShousenZHANG avatar Aug 27 '26 01:08 ShousenZHANG

I can take test/components/extractors/ next. It doesn't overlap fetchers/ (#12435), the only other increment in flight.

One thing worth flagging: this directory is already clean. mypy test/components/extractors/ reports Success: no issues found in 5 source files against current main, but the path was never added to the types target, so CI isn't actually checking it — any typing regression introduced there today would go unnoticed.

So this increment is a one-line change to pyproject.toml, with no source edits needed. Happy to fold it into someone else's PR instead if that's tidier; it seemed worth closing the gap either way.

ShousenZHANG avatar Aug 27 '26 04:08 ShousenZHANG

I can take the next disjoint increment: test/components/preprocessors/.

It is not in the current types target on main, and no open or closed PR or comment covers it — fetchers/ (#12435) and retrievers/ (#12481) are the only increments in flight, and neither overlaps.

Baseline is 265 errors across 9 of the 13 files, but that number is misleading. 206 of them are in test_recursive_splitter.py alone, and they all cascade from one pattern repeated seven times, where the dict returned by run() is rebound to the list it holds:

doc_chunks = splitter.run([doc])
doc_chunks = doc_chunks["documents"]

Giving the two values separate names drops that file to 26 and the directory to 85 — in line with the recent increments.

Nine open PRs add tests to these files, but all of them are pure additions; a three-way merge against each produces zero conflicts, so this shouldn't step on any of them.

Opened #12504.

ShousenZHANG avatar Aug 29 '26 07:08 ShousenZHANG

Taking test/hooks/budget/ — the smallest of the test/hooks/ gaps. The types target currently covers only test/hooks/human_in_the_loop, so budget/, compaction/, tool_result_offloading/ and the three test/hooks/*.py root files are all still unchecked.

Baseline is 3 errors in test_hooks.py, and neither group is a blanket-annotation case:

  • KeepIterating, the inline stub passed as an on_exit hook, is missing the to_dict / from_dict members the Hook protocol requires (list-item at L106). Implementing them via default_to_dict / default_from_dict matches the LifecycleHook stubs #12681 just added in test/components/agents/test_agent_hooks.py.
  • the two agent.chat_generator.run = MagicMock(...) lines are method-assign. Replacing a bound method on a mock generator is the intended pattern here, so those get a narrow # type: ignore[method-assign] rather than a restructure.

No overlap with compaction/, tool_result_offloading/ or the agents/ / converters/ remainders — happy to take another of those next if nobody else has.

ShousenZHANG avatar Sep 11 '26 11:09 ShousenZHANG

Taking the three test/hooks/ root modules next — test_from_function.py, test_invocation.py, test_utils.py — as a follow-up to #12710 (test/hooks/budget/).

Baseline is 56 errors, but 44 of them come from a single cause: six inline stub hooks (RecordingHook, ThreadRecordingHook, AsyncRecordingHook, LifecycleSpy, WarmOnlyHook, PlainHook) are missing the to_dict / from_dict members the Hook protocol requires, so every list they appear in fails list-item. Implementing the pair via default_to_dict / default_from_dict — the shape #12681 used for LifecycleHook — clears all 44.

The rest: a handful of hook dictionaries inferred as dict[str, ...] where the callee wants HookPoint keys, fixed with an explicit annotation; and one .function read off a Hook, narrowed with isinstance rather than suppressed.

Five suppressions remain, all in TestFunctionHookConstruction, where the test deliberately passes a wrong callable to assert FunctionHook rejects it — there the type error is the thing under test.

Still not touching compaction/ or tool_result_offloading/; those are the larger remaining test/hooks/ gaps and I'd rather land these two first.

ShousenZHANG avatar Sep 11 '26 12:09 ShousenZHANG

Taking test/hooks/tool_result_offloading/.

Opened #12720 with the minimal typing fixes plus the types target entry in pyproject.toml:

  • Added test/hooks/tool_result_offloading/ to the types script line in pyproject.toml.
  • In test/hooks/tool_result_offloading/test_policies.py: added isinstance(restored, OffloadOverChars) assertion to narrow the restored policy before accessing .threshold.
  • In test/hooks/tool_result_offloading/test_hooks.py:
    • Updated TextOnlyToolResultStore.write parameter content to str | bytes to satisfy ToolResultStore protocol under LSP.
    • Added explicit type annotation for content: list[TextContent | ImageContent | FileContent] in test cases.
    • Added narrow # type: ignore[method-assign] and # type: ignore[attr-defined] for mock generator setup.

Passed all 40 unit tests, hatch run test:types (508 source files), and hatch run fmt-check locally.

Anurag-M1 avatar Sep 12 '26 17:09 Anurag-M1