Skip to content

Typehint Batch results - #928

Open
Strift wants to merge 8 commits into
mainfrom
php-181-typehint-batches-results
Open

Typehint Batch results#928
Strift wants to merge 8 commits into
mainfrom
php-181-typehint-batches-results

Conversation

@Strift

@Strift Strift commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Pull Request

Related issue

Fixes #743

What does this PR do?

  • Map /batches responses to a Batch contract so getBatch/getBatches return typed objects instead of raw arrays.

PR checklist

Please check if your PR fulfills the following requirements:

  • Did you use any AI tool while implementing this PR (code, tests, docs, etc.)? If yes, disclose it in the PR description and describe what it was used for. AI usage is allowed when it is disclosed.
  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Thank you so much for contributing to Meilisearch!

Summary by CodeRabbit

  • New Features
    • Batch endpoints now expose typed batch objects (including task details, stats, progress, timestamps, and an optional stopping strategy) instead of raw arrays.
    • Batch listings now return typed batch objects within pagination metadata.
    • Added new typed contracts for batch progress, progress steps, batch statistics (including optional embedder request info).
  • Bug Fixes
    • Improved handling of optional/missing fields to return consistent values (e.g., null when absent).
  • Tests
    • Updated batch endpoint tests to use object accessors, and added new unit tests for the new batch contracts and response mappings.

Summary by CodeRabbit

  • New Features
    • Added structured batch results with accessible details, statistics, progress, timestamps, strategies, and task information.
    • Batch listings now provide typed batch data while preserving pagination metadata.
    • Added access to progress steps, completion percentages, embedder request counts, and diagnostic information.
    • Batch data can be converted back into its original array format for compatibility.
  • Bug Fixes
    • Improved handling of optional batch fields and nullable diagnostic values.
  • Tests
    • Expanded coverage for batch retrieval, ordering, pagination, statistics, progress, and serialization.

Summary by CodeRabbit

  • New Features

    • Added structured batch result objects with access to task details, statistics, progress, timestamps, and strategy information.
    • Batch statistics now include status, task types, index usage, progress tracking, and optional embedder request details.
    • Batch listing supports typed results while preserving pagination information.
    • Added convenient accessors for batch progress steps, completion percentages, totals, and errors.
  • Bug Fixes

    • Improved consistency when converting batch responses between API data and application objects.

@Strift Strift added enhancement New feature or request breaking-change The related changes are breaking for the users labels Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b344aa88-bdbb-492b-8d77-696f043a41c7

📥 Commits

Reviewing files that changed from the base of the PR and between 41004c8 and f90f474.

📒 Files selected for processing (1)
  • src/Contracts/Batch.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Contracts/Batch.php

📝 Walkthrough

Walkthrough

Batch endpoints now return immutable, typed Batch objects. New contracts model batch details, statistics, progress, and embedder requests. Pagination preserves raw serialization. Delegates and tests use typed accessors.

Changes

Batch response typing

Layer / File(s) Summary
Batch contracts and conversion
src/Contracts/Batch.php, src/Contracts/BatchStats.php, src/Contracts/BatchProgress.php, src/Contracts/BatchProgressStep.php, src/Contracts/BatchEmbedderRequests.php, tests/Contracts/*
Adds immutable typed objects, factories, getters, optional-field handling, raw payload preservation, and contract tests.
Endpoint mapping and pagination contracts
src/Endpoints/Batches.php, src/Contracts/BatchesResults.php, tests/Contracts/BatchesResultsTest.php
Maps raw responses to Batch objects and serializes typed results back to raw arrays.
Delegate wiring and response validation
src/Endpoints/Delegates/HandlesBatches.php, tests/Endpoints/BatchesTest.php
Updates delegate return types and validates typed details, statistics, ordering, identifiers, and strategies.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HandlesBatches
  participant Batches
  participant Batch
  participant BatchesResults
  Client->>HandlesBatches: Request batch or batch list
  HandlesBatches->>Batches: Fetch batch response
  Batches->>Batch: Convert raw payload with Batch::fromArray()
  Batch-->>Batches: Return typed Batch objects
  Batches->>BatchesResults: Build paginated response
  BatchesResults-->>Client: Return typed results and pagination
Loading

Possibly related PRs

Suggested reviewers: norkunas

Poem

A rabbit checks each typed batch,
With stats and progress on its path.
Details, dates, and strategies align,
Raw arrays return in proper time.
Getters keep the data neat!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.83% 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 clearly and concisely describes the primary change: adding typed Batch results.
Linked Issues check ✅ Passed The changes satisfy issue #743 by returning typed Batch objects and adding the supporting typed batch contracts.
Out of Scope Changes check ✅ Passed All code and test changes support typed batch results, related nested contracts, serialization, and endpoint behavior.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch php-181-typehint-batches-results

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/Contracts/Batch.php (1)

170-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify the finishedAt presence check.

You can use isset() to concisely check if a key exists and its value is not null, which simplifies the conditional logic.

♻️ Proposed refactor
-            \array_key_exists('finishedAt', $data) && null !== $data['finishedAt']
-                ? new \DateTimeImmutable($data['finishedAt']) : null,
+            isset($data['finishedAt']) ? new \DateTimeImmutable($data['finishedAt']) : null,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Contracts/Batch.php` around lines 170 - 171, Update the finishedAt
initialization in the Batch construction logic to replace the
array_key_exists-and-null comparison with an isset($data['finishedAt']) check,
while preserving creation of DateTimeImmutable for non-null values and null
otherwise.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Contracts/Batch.php`:
- Around line 131-137: Update the PHPDoc for the toArray() method in Batch to
return the existing RawBatch type alias instead of array<mixed>,
preserving the method signature and implementation.

---

Nitpick comments:
In `@src/Contracts/Batch.php`:
- Around line 170-171: Update the finishedAt initialization in the Batch
construction logic to replace the array_key_exists-and-null comparison with an
isset($data['finishedAt']) check, while preserving creation of DateTimeImmutable
for non-null values and null otherwise.
🪄 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: 7954aad5-95cc-41c3-9863-b58e1889f39d

📥 Commits

Reviewing files that changed from the base of the PR and between cfb6932 and 4eaa842.

📒 Files selected for processing (5)
  • src/Contracts/Batch.php
  • src/Contracts/BatchesResults.php
  • src/Endpoints/Batches.php
  • src/Endpoints/Delegates/HandlesBatches.php
  • tests/Endpoints/BatchesTest.php

Comment thread src/Contracts/Batch.php
@Strift
Strift force-pushed the php-181-typehint-batches-results branch from 472ba25 to 7f37146 Compare July 17, 2026 08:10
@Strift
Strift marked this pull request as ready for review July 17, 2026 08:10
@Strift
Strift requested a review from norkunas July 17, 2026 08:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Contracts/BatchesResults.php (1)

88-106: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Ensure toArray() returns a fully scalar array instead of objects.

The toArray() method currently assigns $this->data directly to the results key, which contains Batch objects. Because Batch properties are private and it does not implement JsonSerializable, calling json_encode($batchesResults->toArray()) will serialize the objects as empty {} structures, resulting in data loss.

You should map the Batch objects to their raw array representations to ensure toArray() consistently returns a deeply primitive array.

♻️ Proposed fix
     /**
      * `@return` array{
-     *     results: list<Batch>,
+     *     results: list<RawBatch>,
      *     from: non-negative-int,
      *     limit: non-negative-int,
      *     next: non-negative-int,
      *     total: non-negative-int
      * }
      */
     public function toArray(): array
     {
         return [
-            'results' => $this->data,
+            'results' => array_map(fn (Batch $batch) => $batch->toArray(), $this->data),
             'next' => $this->next,
             'limit' => $this->limit,
             'from' => $this->from,
             'total' => $this->total,
         ];
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Contracts/BatchesResults.php` around lines 88 - 106, Update
BatchesResults::toArray() so the results value maps each Batch object to its raw
array representation before returning the array. Preserve the existing
pagination fields and ensure the return type documentation reflects a list of
scalar array data rather than list<Batch>, allowing json_encode() to retain each
batch’s contents.
🧹 Nitpick comments (1)
src/Contracts/Batch.php (1)

16-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using precise array shapes for nested stats.

If the keys for progressTrace, writeChannelCongestion, and internalDatabaseSizes are known or bounded, define their specific shapes instead of using array<string, mixed>. As per coding guidelines, src/Contracts/**/*.php should use precise PHPStan array shapes. If they are intentionally arbitrary or open-ended by the Meilisearch API, you can leave them as is.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Contracts/Batch.php` around lines 16 - 18, Update the PHPStan annotations
in the Batch contract for progressTrace, writeChannelCongestion, and
internalDatabaseSizes to use precise nested array shapes when their supported
keys are known or bounded; retain array<string, mixed> only for fields
intentionally open-ended by the Meilisearch API.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/Contracts/BatchesResults.php`:
- Around line 88-106: Update BatchesResults::toArray() so the results value maps
each Batch object to its raw array representation before returning the array.
Preserve the existing pagination fields and ensure the return type documentation
reflects a list of scalar array data rather than list<Batch>, allowing
json_encode() to retain each batch’s contents.

---

Nitpick comments:
In `@src/Contracts/Batch.php`:
- Around line 16-18: Update the PHPStan annotations in the Batch contract for
progressTrace, writeChannelCongestion, and internalDatabaseSizes to use precise
nested array shapes when their supported keys are known or bounded; retain
array<string, mixed> only for fields intentionally open-ended by the Meilisearch
API.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6d563b0b-bbd9-41d9-814d-aa918230a2d1

📥 Commits

Reviewing files that changed from the base of the PR and between 472ba25 and 7f37146.

📒 Files selected for processing (5)
  • src/Contracts/Batch.php
  • src/Contracts/BatchesResults.php
  • src/Endpoints/Batches.php
  • src/Endpoints/Delegates/HandlesBatches.php
  • tests/Endpoints/BatchesTest.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/Endpoints/BatchesTest.php
  • src/Endpoints/Batches.php

Comment thread src/Contracts/Batch.php Outdated
@Strift
Strift requested a review from norkunas July 18, 2026 01:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Contracts/BatchStats.php`:
- Around line 10-20: The RawBatchStats definition at
src/Contracts/BatchStats.php lines 10-20 and the corresponding constructor
parameter PHPDocs at src/Contracts/BatchStats.php lines 23-31 use array<string,
mixed> for progressTrace, writeChannelCongestion, and internalDatabaseSizes.
Replace each with precise PHPStan array shapes or constrained value types
matching the Meilisearch API specification, and keep the type definitions
consistent between the alias and constructor documentation.
🪄 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: cf451bb9-69ef-4513-ad8f-9860bcb09131

📥 Commits

Reviewing files that changed from the base of the PR and between 7f37146 and 8d6a077.

📒 Files selected for processing (10)
  • src/Contracts/Batch.php
  • src/Contracts/BatchEmbedderRequests.php
  • src/Contracts/BatchProgress.php
  • src/Contracts/BatchProgressStep.php
  • src/Contracts/BatchStats.php
  • src/Contracts/BatchesResults.php
  • tests/Contracts/BatchProgressTest.php
  • tests/Contracts/BatchStatsTest.php
  • tests/Contracts/BatchesResultsTest.php
  • tests/Endpoints/BatchesTest.php
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/Contracts/Batch.php
  • tests/Endpoints/BatchesTest.php
  • src/Contracts/BatchesResults.php

Comment thread src/Contracts/BatchStats.php
Strift and others added 7 commits August 4, 2026 14:59
Map /batches responses to a Batch contract so getBatch/getBatches return typed objects instead of raw arrays.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Strift
Strift force-pushed the php-181-typehint-batches-results branch from 326e076 to 41004c8 Compare August 4, 2026 06:59

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Contracts/Batch.php`:
- Around line 138-142: Update Batch::fromArray to access the required nullable
duration and progress keys directly, matching the declared RawBatch shape.
Remove optional coalescing for progress while preserving its nullable
BatchProgress::fromArray conversion, and keep optional coalescing only for
batchStrategy.
🪄 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 Plus

Run ID: 8d4eccb4-8320-4d45-906e-7a6081614d45

📥 Commits

Reviewing files that changed from the base of the PR and between 8d6a077 and 41004c8.

📒 Files selected for processing (12)
  • src/Contracts/Batch.php
  • src/Contracts/BatchEmbedderRequests.php
  • src/Contracts/BatchProgress.php
  • src/Contracts/BatchProgressStep.php
  • src/Contracts/BatchStats.php
  • src/Contracts/BatchesResults.php
  • src/Endpoints/Batches.php
  • src/Endpoints/Delegates/HandlesBatches.php
  • tests/Contracts/BatchProgressTest.php
  • tests/Contracts/BatchStatsTest.php
  • tests/Contracts/BatchesResultsTest.php
  • tests/Endpoints/BatchesTest.php
🚧 Files skipped from review as they are similar to previous changes (10)
  • tests/Contracts/BatchProgressTest.php
  • src/Contracts/BatchEmbedderRequests.php
  • src/Contracts/BatchProgress.php
  • tests/Contracts/BatchesResultsTest.php
  • src/Endpoints/Delegates/HandlesBatches.php
  • src/Contracts/BatchStats.php
  • tests/Contracts/BatchStatsTest.php
  • src/Endpoints/Batches.php
  • src/Contracts/BatchesResults.php
  • tests/Endpoints/BatchesTest.php

Comment thread src/Contracts/Batch.php Outdated
Align duration and progress reads with the RawBatch shape, keeping optional coalescing only for batchStrategy.

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking-change The related changes are breaking for the users enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Typehint batches results

2 participants