Skip to content

Add method to get task documents#895

Open
mvanhorn wants to merge 9 commits intomeilisearch:mainfrom
mvanhorn:osc/890-get-task-documents
Open

Add method to get task documents#895
mvanhorn wants to merge 9 commits intomeilisearch:mainfrom
mvanhorn:osc/890-get-task-documents

Conversation

@mvanhorn
Copy link
Copy Markdown
Contributor

@mvanhorn mvanhorn commented Mar 25, 2026

Summary

Adds getTaskDocuments() for the GET /tasks/{task_id}/documents endpoint introduced in Meilisearch v1.13.

Changes

  • src/Endpoints/Tasks.php: Added getDocuments(int $taskUid) that calls GET /tasks/{id}/documents
  • src/Endpoints/Delegates/HandlesTasks.php: Added getTaskDocuments(int $uid) delegate method
  • .code-samples.meilisearch.yaml: Added get_task_documents_1 code sample

Testing

Fixes #890

This contribution was developed with AI assistance (Claude Code).

Summary by CodeRabbit

  • New Features

    • Retrieve documents associated with a specific task ID via a new endpoint method, returning the task’s document payload.
  • Documentation

    • Added a code sample showing how to fetch documents for a given task.
  • Tests

    • Added an integration test that enables the experimental route, seeds a completed task, and verifies fetching task documents returns a non-empty array.

Adds getTaskDocuments() for the GET /tasks/{task_id}/documents
endpoint introduced in Meilisearch v1.13.

Fixes meilisearch#890
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 25, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added a Tasks endpoint method to fetch a task's documents, a delegate method exposing it on the client surface, a unit test exercising the client call, and a documentation code-sample entry demonstrating usage.

Changes

Cohort / File(s) Summary
Tasks endpoint
src/Endpoints/Tasks.php
Added public function getDocuments(int $taskUid): array which issues GET /tasks/{taskUid}/documents and returns the response payload as an array.
Delegate / Client surface
src/Endpoints/Delegates/HandlesTasks.php
Added public function getTaskDocuments(int $uid): array delegating to tasks->getDocuments($uid).
Tests
tests/Endpoints/TasksTest.php
Added testGetTaskDocumentsClient() that seeds an index, enables the experimental route, calls the client delegate with a completed task UID, and asserts a non-empty array response.
Documentation samples
.code-samples.meilisearch.yaml
Added get_task_documents_1 example showing $client->getTaskDocuments(1) usage.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant Delegate as HandlesTasks
  participant Tasks as Tasks Endpoint
  participant HTTP as HTTP Client
  participant Server as Meilisearch Server

  Client->>Delegate: getTaskDocuments(taskUid)
  Delegate->>Tasks: getDocuments(taskUid)
  Tasks->>HTTP: GET /tasks/{taskUid}/documents
  HTTP->>Server: HTTP GET /tasks/{taskUid}/documents
  Server-->>HTTP: 200 OK + documents payload
  HTTP-->>Tasks: response payload
  Tasks-->>Delegate: return array payload
  Delegate-->>Client: return array payload
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 I hopped through code to fetch the traces,
Task documents found in distant places,
Delegate led the nimble quest,
Tests ensured the path was blessed,
Hooray for docs—now off for a rest! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add method to get task documents' directly and clearly describes the main change: adding a new method for retrieving task documents.
Linked Issues check ✅ Passed All three objectives from issue #890 are met: the SDK method for GET /tasks/{task_id}/documents is implemented in Tasks.php and delegated in HandlesTasks.php, test cases verify the new method, and code-sample entry get_task_documents_1 was added.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the task documents retrieval feature and its documentation, with no unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 25, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.14%. Comparing base (0078a8c) to head (902ee12).
⚠️ Report is 138 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #895      +/-   ##
==========================================
- Coverage   89.78%   87.14%   -2.64%     
==========================================
  Files          59       82      +23     
  Lines        1449     1821     +372     
==========================================
+ Hits         1301     1587     +286     
- Misses        148      234      +86     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@norkunas
Copy link
Copy Markdown
Collaborator

Missing tests :)

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Endpoints/Tasks.php`:
- Around line 25-28: Add integration tests for the new Tasks::getDocuments(int
$taskUid): array method by creating a test method (e.g., testGetDocuments) in
the existing TasksTest class that follows the pattern of other task tests (like
testGetOneTaskFromWaitTask): arrange a stubbed HTTP response for the GET to the
"/{taskUid}/documents" endpoint, call $tasks->getDocuments($taskUid), and assert
the returned array matches the stubbed payload and that the HTTP client was
invoked with the correct path; ensure the test covers at least one successful
response and a case for an empty document list to mirror existing test styles.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a9f3112e-ad70-4983-a276-0f019086ea6c

📥 Commits

Reviewing files that changed from the base of the PR and between 9c4ce8c and a34dc1d.

📒 Files selected for processing (3)
  • .code-samples.meilisearch.yaml
  • src/Endpoints/Delegates/HandlesTasks.php
  • src/Endpoints/Tasks.php

Verify that getTaskDocuments returns an array for a completed
document addition task.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@mvanhorn
Copy link
Copy Markdown
Contributor Author

Added test in 2173521: verifies getTaskDocuments() returns an array for a completed document addition task.


$documents = $this->client->getTaskDocuments($completedTask->getTaskUid());

self::assertIsArray($documents);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe asserting that array is not empty is better to prove that we really get something?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added assertNotEmpty in 4ac9ba2.

Addresses review feedback to verify we actually receive data.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
tests/Endpoints/TasksTest.php (1)

57-57: ⚠️ Potential issue | 🟡 Minor

Remove redundant assertIsArray call.

The getTaskDocuments() method has an explicit : array return type annotation, making the type check at line 57 redundant from a static analysis perspective. Keep assertNotEmpty() to validate that the response contains meaningful data.

Proposed fix
-    self::assertIsArray($documents);
     self::assertNotEmpty($documents);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Endpoints/TasksTest.php` at line 57, Remove the redundant type
assertion: in the TasksTest test that calls getTaskDocuments() (which already
has a : array return type), delete the self::assertIsArray($documents) assertion
and keep the self::assertNotEmpty($documents) check to ensure the response
contains meaningful data; update only the assertion call in the TasksTest test
method that invokes getTaskDocuments().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/Endpoints/TasksTest.php`:
- Line 53: The destructured assignment "[$seedTask, $completedTask] =
$this->seedIndex();" declares $seedTask which is unused; change it to ignore the
first slot and only capture the used variable by replacing $seedTask with an
unused/ignored placeholder (e.g. $_ or a blank slot) in the destructuring so
only $completedTask from seedIndex() is assigned, eliminating the PHPMD
unused-variable warning while leaving the seedIndex() call intact.
- Line 55: The test calls getTaskDocuments on $this->client before the
experimental endpoint is enabled; enable the experimental feature flag named
getTaskDocumentsRoute using the HTTP client pattern used in other tests (call
the test HTTP client on $this->client->http or the equivalent test request
helper to set the experimental flag to true) prior to invoking
getTaskDocuments($completedTask->getTaskUid()), then proceed with the existing
call; confirm the feature key matches your Meilisearch version.

---

Duplicate comments:
In `@tests/Endpoints/TasksTest.php`:
- Line 57: Remove the redundant type assertion: in the TasksTest test that calls
getTaskDocuments() (which already has a : array return type), delete the
self::assertIsArray($documents) assertion and keep the
self::assertNotEmpty($documents) check to ensure the response contains
meaningful data; update only the assertion call in the TasksTest test method
that invokes getTaskDocuments().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e39fd884-c5bc-4cef-a48e-5fdc8d6c1f97

📥 Commits

Reviewing files that changed from the base of the PR and between 2173521 and 4ac9ba2.

📒 Files selected for processing (1)
  • tests/Endpoints/TasksTest.php

Copy link
Copy Markdown
Collaborator

@norkunas norkunas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just fix CI

@mvanhorn
Copy link
Copy Markdown
Contributor Author

Fixed in 980d58b: removed the redundant assertIsArray (phpstan flagged it as alreadyNarrowedType since getTaskDocuments() already returns array) and dropped the unused $seedTask variable.

Copy link
Copy Markdown
Collaborator

@Strift Strift left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests are failing:

1) Tests\Endpoints\TasksTest::testGetTaskDocumentsClient
Meilisearch\Exceptions\ApiException: Getting the documents of an enqueued task requires enabling the `get task documents route` experimental feature. See https://github.com/orgs/meilisearch/discussions/808

/home/runner/work/meilisearch-php/meilisearch-php/src/Http/Client.php:248
/home/runner/work/meilisearch-php/meilisearch-php/src/Http/Client.php:171
/home/runner/work/meilisearch-php/meilisearch-php/src/Http/Client.php:76
/home/runner/work/meilisearch-php/meilisearch-php/src/Endpoints/Tasks.php:27
/home/runner/work/meilisearch-php/meilisearch-php/src/Endpoints/Delegates/HandlesTasks.php:25
/home/runner/work/meilisearch-php/meilisearch-php/tests/Endpoints/TasksTest.php:55

Signed-off-by: Matt Van Horn <mvanhorn@users.noreply.github.com>
@mvanhorn
Copy link
Copy Markdown
Contributor Author

Enabled the experimental feature flag before the test call in 5f38a80 -- follows the same $http->patch('/experimental-features', ...) pattern used in DocumentsTest and other experimental endpoint tests.

Comment on lines +54 to +55
$http = new Client($this->host, getenv('MEILISEARCH_API_KEY'));
$http->patch('/experimental-features', ['getTaskDocumentsRoute' => true]);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Strift as experimental features are the public/documented api, i think it should be available on $this->client like $this->client->enableExperimentaFeature(...), so the tests wouldn't need to instantiate new http client, wdyt?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that would be better. But the enableExperimentaFeature method would be unstable, because the accepted set of features would vary as versions change.

We do it in the JS package, and I personally think that's fine.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

well we could just accept any string, so would not matter if list changes

The API only returns documents for enqueued or processing tasks.
The test was calling getTaskDocuments on a completed task.
@mvanhorn
Copy link
Copy Markdown
Contributor Author

mvanhorn commented Apr 2, 2026

Fixed the test in 96d3851. The issue was calling getTaskDocuments() on a completed task -- the API only returns documents for enqueued or processing tasks. Now calls it immediately after updateDocuments() before the task completes.

Re: the experimental feature enablement discussion -- happy to switch to $this->client->enableExperimentalFeature(...) if you settle on that API. Current approach follows the same raw HTTP pattern used in DocumentsTest.

@norkunas
Copy link
Copy Markdown
Collaborator

norkunas commented Apr 2, 2026

@Strift this is somewhat unexpected that this endpoint returns ndjson 🙂

@mvanhorn
Copy link
Copy Markdown
Contributor Author

mvanhorn commented Apr 2, 2026

Saw the NDJSON discussion -- should I update getTaskDocuments() to parse the NDJSON response (split lines + json_decode each), or would you rather handle the response format separately?

@Strift
Copy link
Copy Markdown
Collaborator

Strift commented Apr 4, 2026

Hey there,

I would like to align this feature with how it's being handled in our other SDKs (specifically the JavaScript one). The /tasks/{task_id}/documents endpoint returns NDJSON (Newline Delimited JSON), and I prefer to handle it via streaming rather than parsing the entire response into a standard JSON array.

I prefer to align with what the Meilisearch team designed. Since it's an experimental method, we can still iterate if this doesn't work well.

To achieve this, I recommend the following changes:

  1. Add getStream to the HTTP Contract:
    In src/Contracts/Http.php, add the method definition:

    /**
     * @throws ApiException
     */
    public function getStream(string $path, array $query = []): StreamInterface;
  2. Implement getStream in the HTTP Client:
    In src/Http/Client.php, implement the method using the existing executeStream helper:

    public function getStream(string $path, array $query = []): StreamInterface
    {
        $request = $this->requestFactory->createRequest(
            'GET',
            $this->baseUrl.$path.$this->buildQueryString($query)
        );
    
        return $this->executeStream($request);
    }
  3. Update the Tasks endpoint:
    In src/Endpoints/Tasks.php and the HandlesTasks delegate, update the method to return a StreamInterface and use the new getStream() method. We should avoid converting the response to an array and instead return the raw NDJSON stream (similar to how streamCompletion works in HandlesChatWorkspaceSettings).

For reference, you can look at the equivalent implementation in the JavaScript SDK: meilisearch-js PR #2156.

Align with JS SDK implementation per maintainer request. The
/tasks/{task_id}/documents endpoint returns NDJSON, so streaming
via StreamInterface is the correct approach rather than parsing
into a JSON array.

- Add getStream() to Http contract and Client implementation
- Update Tasks::getDocuments() to use getStream()
- Update HandlesTasks::getTaskDocuments() return type
- Update test to assert StreamInterface and non-empty content
@mvanhorn
Copy link
Copy Markdown
Contributor Author

mvanhorn commented Apr 4, 2026

Implemented in 902ee12:

  • Added getStream() to Http contract and Client implementation
  • Tasks::getDocuments() now returns StreamInterface via getStream()
  • HandlesTasks::getTaskDocuments() return type updated to StreamInterface
  • Test updated to assert StreamInterface and non-empty content

Followed the pattern from the existing postStream/executeStream pair. Happy to adjust if the JS SDK reference calls for anything different.


self::assertInstanceOf(StreamInterface::class, $stream);
$content = (string) $stream;
self::assertNotEmpty($content);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

well i'd like that the test would show how to access documents, because now it's unclear for me

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 81d91b5 - the test now parses the NDJSON stream line by line, decodes each document, and asserts the structure. Also fixes the phpstan alreadyNarrowedType error from the removed assertInstanceOf.

Show how to access individual documents from the stream by
splitting NDJSON lines, decoding each, and asserting structure.
Fixes phpstan alreadyNarrowedType error by removing redundant
assertInstanceOf check.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The testGetTaskDocumentsClient test was calling getTaskDocuments on a
task that hadn't completed yet, causing a JsonException when trying to
parse the NDJSON response. Wait for the task to finish first.

Also removes the redundant assertNotEmpty($documents) that phpstan
flagged as alreadyNarrowedType since the array is guaranteed non-empty
by the assertNotEmpty($lines) above.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@mvanhorn
Copy link
Copy Markdown
Contributor Author

mvanhorn commented Apr 6, 2026

Fixed in f289c8c: the test was calling getTaskDocuments before the task completed, causing the JsonException. Added $task->wait() before the fetch. Also removed the redundant assertNotEmpty($documents) that phpstan flagged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Meilisearch v1.13.0] Add method to get tasks documents

3 participants