dabla commented on code in PR #76533:
URL: https://github.com/apache/airflow/pull/76533#discussion_r4648254707


##########
providers/http/src/airflow/providers/http/operators/pagination.py:
##########
@@ -0,0 +1,328 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Stateless ``pagination_function`` factories for ``HttpOperator``.
+
+Each factory returns a callback ``(response) -> dict | None`` compatible with
+``airflow.providers.http.operators.http.HttpOperator``. The next page is
+derived only from that response (JSON body and the query string of
+``response.url``). Deferrable runs rebuild the task between pages, so a counter
+closed over by the callback would reset and request the same page again.
+
+The factories do not apply a page cap. Pass ``max_pages`` to ``HttpOperator``
+so the limit also covers a hand-written callback.
+
+Offset, page, and cursor values are read from the URL query. ``HttpHook`` sends
+``data`` as query parameters for GET and as a body otherwise, so these helpers
+target GET listings. A cursor that exists only in a POST body needs a custom
+callback.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from typing import Any
+from urllib.parse import parse_qsl, urljoin, urlparse
+
+from requests import Response
+
+log = logging.getLogger(__name__)
+
+PaginationCallback = Callable[[Response], dict[str, Any] | None]
+
+__all__ = [
+    "cursor_pagination",
+    "next_link_pagination",
+    "offset_pagination",
+    "page_number_pagination",
+]
+
+
+def offset_pagination(
+    *,
+    offset_param: str = "offset",
+    limit_param: str = "limit",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+) -> PaginationCallback:
+    """
+    Return a callback that advances an offset query parameter.
+
+    The next offset is the offset on ``response.url`` plus ``page_size``.
+    The callback returns ``None`` when the page has fewer than ``page_size``
+    records, or when ``has_more_key`` is present on the JSON object and false.
+
+    :param offset_param: Query parameter that carries the offset.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page. The offset 
advances by this amount.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    """
+    offset_param = _require_name("offset_param", offset_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, offset_param, default=0)
+        return {"data": {offset_param: current + page_size, limit_param: 
page_size}}
+
+    return next_page
+
+
+def page_number_pagination(
+    *,
+    page_param: str = "page",
+    limit_param: str = "page_size",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+    first_page: int = 1,
+) -> PaginationCallback:
+    """
+    Return a callback that advances a page-number query parameter.
+
+    When ``page_param`` is absent from ``response.url``, the current page is
+    ``first_page``. The callback returns ``None`` on a short page or when
+    ``has_more_key`` is present and false.
+
+    :param page_param: Query parameter that carries the page number.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    :param first_page: Page number used when the request URL has no page 
parameter.
+    """
+    page_param = _require_name("page_param", page_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+    first_page = _require_int("first_page", first_page)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, page_param, default=first_page)
+        return {"data": {page_param: current + 1, limit_param: page_size}}
+
+    return next_page
+
+
+def cursor_pagination(

Review Comment:
   **[warning]** `cursor_pagination` is keyset pagination on the highest record 
field, not what most APIs (and the docs example right above the new section) 
call a cursor, and it ends the walk silently when its assumptions do not hold.
   
   Checked against this head:
   
   - A cursor returned in the body (`{"items": [...], "next_cursor": "abc"}`), 
the shape of the existing `howto_operator_http_pagination_function` example, 
cannot be expressed: `field` is looked up on the records only, so the callback 
returns `None` after the first page.
   - A listing sorted newest first (`[{"id": 10}, {"id": 9}]`): page 1 sends 
`after=10`, page 2 has the same maximum, the "cursor does not advance" guard 
returns `None`. Two pages, no warning, the task succeeds with a partial result.
   - `numeric=False` is the default and the tests themselves pin that it loses 
`1001` and `1002` (`test_walk_string_cursor_stops_before_1001`).
   
   For a helper whose purpose is to spare users the hand-written callback, a 
partial result that looks like a success is the worst outcome. Suggestions: 
name it after what it does (keyset / "max field") and add the common variant 
that reads the next cursor from a dotted path in the body, as 
`next_link_pagination` already does for URLs; and log a warning when the walk 
ends because the cursor did not advance on a full page. The name is public API 
from the first release on, so it is worth settling now.



##########
providers/http/src/airflow/providers/http/operators/pagination.py:
##########
@@ -0,0 +1,328 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Stateless ``pagination_function`` factories for ``HttpOperator``.

Review Comment:
   **[blocker]** A module under `operators/` must be listed in `provider.yaml`, 
and this one is not.
   
   The provider-yaml check globs every `**/operators/*.py` of the provider and 
compares the set with `operators.python-modules` in `provider.yaml` 
([`parse_module_data`](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/scripts/in_container/run_provider_yaml_files_check.py#L337-L353),
 [the 
comparison](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/scripts/in_container/run_provider_yaml_files_check.py#L425-L453)).
 `providers/http/provider.yaml` still lists only 
`airflow.providers.http.operators.http`, so the static check will fail once the 
workflow is approved (CI has not run yet on this PR).
   
   Listing the module would make it pass, but it would also publish a module 
without any operator in the operators reference. These are plain callback 
factories, so a module outside `operators/` (for example 
`airflow/providers/http/pagination.py`) fits better and needs no 
`provider.yaml` entry.



##########
providers/http/src/airflow/providers/http/operators/pagination.py:
##########
@@ -0,0 +1,328 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Stateless ``pagination_function`` factories for ``HttpOperator``.
+
+Each factory returns a callback ``(response) -> dict | None`` compatible with
+``airflow.providers.http.operators.http.HttpOperator``. The next page is
+derived only from that response (JSON body and the query string of
+``response.url``). Deferrable runs rebuild the task between pages, so a counter
+closed over by the callback would reset and request the same page again.
+
+The factories do not apply a page cap. Pass ``max_pages`` to ``HttpOperator``
+so the limit also covers a hand-written callback.
+
+Offset, page, and cursor values are read from the URL query. ``HttpHook`` sends
+``data`` as query parameters for GET and as a body otherwise, so these helpers
+target GET listings. A cursor that exists only in a POST body needs a custom
+callback.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from typing import Any
+from urllib.parse import parse_qsl, urljoin, urlparse
+
+from requests import Response
+
+log = logging.getLogger(__name__)
+
+PaginationCallback = Callable[[Response], dict[str, Any] | None]
+
+__all__ = [
+    "cursor_pagination",
+    "next_link_pagination",
+    "offset_pagination",
+    "page_number_pagination",
+]
+
+
+def offset_pagination(
+    *,
+    offset_param: str = "offset",
+    limit_param: str = "limit",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+) -> PaginationCallback:
+    """
+    Return a callback that advances an offset query parameter.
+
+    The next offset is the offset on ``response.url`` plus ``page_size``.
+    The callback returns ``None`` when the page has fewer than ``page_size``
+    records, or when ``has_more_key`` is present on the JSON object and false.
+
+    :param offset_param: Query parameter that carries the offset.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page. The offset 
advances by this amount.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    """
+    offset_param = _require_name("offset_param", offset_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, offset_param, default=0)
+        return {"data": {offset_param: current + page_size, limit_param: 
page_size}}
+
+    return next_page
+
+
+def page_number_pagination(
+    *,
+    page_param: str = "page",
+    limit_param: str = "page_size",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+    first_page: int = 1,
+) -> PaginationCallback:
+    """
+    Return a callback that advances a page-number query parameter.
+
+    When ``page_param`` is absent from ``response.url``, the current page is
+    ``first_page``. The callback returns ``None`` on a short page or when
+    ``has_more_key`` is present and false.
+
+    :param page_param: Query parameter that carries the page number.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    :param first_page: Page number used when the request URL has no page 
parameter.
+    """
+    page_param = _require_name("page_param", page_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+    first_page = _require_int("first_page", first_page)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, page_param, default=first_page)
+        return {"data": {page_param: current + 1, limit_param: page_size}}
+
+    return next_page
+
+
+def cursor_pagination(
+    *,
+    param: str,
+    field: str,
+    limit_param: str = "limit",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+    numeric: bool = False,
+) -> PaginationCallback:
+    """
+    Return a callback that sets a cursor query parameter to the max record 
field.
+
+    The walk stops when the cursor does not advance, the page is short, or
+    ``has_more_key`` is present and false. An empty cursor is never sent:
+    ``?after=`` is how some APIs mean "no filter" and would repeat the listing.
+
+    ``numeric=False`` compares values with ``max()`` on their original type.
+    Decimal strings do not sort numerically, so ``"999"`` is greater than
+    ``"1000"`` and the cursor stops moving. Set ``numeric=True`` to compare
+    them as integers.
+
+    :param param: Query parameter that carries the cursor.
+    :param field: Record field the cursor is taken from.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    :param numeric: Compare cursor values as integers instead of as strings.
+    """
+    param = _require_name("param", param)
+    field = _require_name("field", field)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+    if not isinstance(numeric, bool):
+        raise ValueError("numeric must be a bool")
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        nxt = _max_field(records, field, numeric=numeric)
+        if nxt is None or str(nxt) == "":
+            return None
+        if _query_value(response.url, param) == str(nxt):
+            return None
+        return {"data": {param: nxt, limit_param: page_size}}
+
+    return next_page
+
+
+def next_link_pagination(
+    *,
+    path: str,
+    base_path: str = "",
+    allow_other_hosts: bool = False,
+) -> PaginationCallback:
+    """
+    Return a callback that follows a next-page URL stored in the JSON body.
+
+    ``path`` is a dotted path (``page.next``). The callback returns
+    ``{"endpoint": "<path>?<query>"}`` because ``HttpHook`` joins ``endpoint``
+    onto the connection's base URL. An absolute next URL is reduced to that
+    path and query. The request stays on the connection host either way, so
+    connection credentials are not sent to another host.
+
+    A next URL whose host differs from ``response.url`` is ignored unless
+    ``allow_other_hosts`` is true. When it is true, only the path and query are
+    used, still on the connection host. This matches the guard added for
+    Microsoft Graph next links: a payload must not redirect a credentialed
+    client at an arbitrary host.
+
+    If the connection host already includes a path 
(``https://api.example.com/v2``)
+    and the next URL repeats it (``/v2/feeds``), pass ``base_path="/v2"``.
+    Otherwise the hook appends ``/v2`` again and calls ``/v2/v2/feeds``.
+
+    :param path: Dotted path of the next-page URL in the JSON body.
+    :param base_path: Path prefix already present on the connection host, 
stripped
+        from the next URL so the endpoint is not doubled.
+    :param allow_other_hosts: Accept a next URL on a different host and use its
+        path on the connection host. The default refuses that URL.
+    """
+    path = _require_name("path", path)
+    if not isinstance(base_path, str):
+        raise ValueError("base_path must be a string")
+    if not isinstance(allow_other_hosts, bool):
+        raise ValueError("allow_other_hosts must be a bool")
+    stripped = base_path.strip().strip("/")
+    prefix = f"/{stripped}" if stripped else ""
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        nxt = _dig(response.json(), path)
+        if not isinstance(nxt, str) or not nxt.strip():
+            return None
+        current = urlparse(response.url)
+        resolved = urljoin(response.url, nxt.strip())
+        if resolved == response.url:
+            return None
+        target = urlparse(resolved)
+        if _netloc(target.netloc) != _netloc(current.netloc) and not 
allow_other_hosts:
+            log.warning(
+                "Ignoring next-page URL on a different host (%s). The response 
host is %s. "
+                "Set allow_other_hosts=True to use that link's path on the 
connection host.",
+                target.netloc,
+                current.netloc,
+            )
+            return None
+        endpoint = target.path or "/"
+        if prefix and (endpoint == prefix or 
endpoint.startswith(f"{prefix}/")):
+            endpoint = endpoint[len(prefix) :] or "/"
+        if not endpoint.startswith("/"):
+            endpoint = f"/{endpoint}"
+        if target.query:
+            endpoint = f"{endpoint}?{target.query}"
+        return {"endpoint": endpoint}

Review Comment:
   **[warning]** `next_link_pagination` returns only `endpoint`, so the 
operator's own `data` is sent again on every page, appended to the next link's 
query.
   
   `_merge_next_page_parameters` keeps `self.data` when the callback returns no 
`data` ([http.py 
L399-L404](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/providers/http/src/airflow/providers/http/operators/http.py#L399-L404)),
 and `HttpHook.run` passes it as `params` for GET ([hooks/http.py 
L406-L408](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/providers/http/src/airflow/providers/http/hooks/http.py#L406-L408)).
 With `data={"offset": 0, "limit": 100, "status": "open"}` and a next link 
`/orders?offset=100&limit=100&status=open`, the second request is:
   
   ```
   /orders?offset=100&limit=100&status=open&offset=0&limit=100&status=open
   ```
   
   Which of the two `offset` values the server takes is up to the server; one 
that takes the last returns page 1 forever (until `max_pages`, when set). The 
callback cannot clear `data` either, because an empty dict falls back to 
`self.data`. None of the next-link tests passes `data` to the operator, so this 
path is not covered. Either the docs must say the initial query belongs in 
`endpoint` when this helper is used, or the merge needs a way for a callback to 
replace `data` instead of merging it; a test with `data=` on the operator 
should pin whichever is chosen.
   
   Smaller point on the same function: with `allow_other_hosts=True` the link's 
path is requested on the connection host, not on the other host. The name 
promises the opposite of what happens; something like 
`use_path_of_other_hosts`, or dropping the option until someone needs it, would 
avoid a surprised user.



##########
providers/http/src/airflow/providers/http/operators/pagination.py:
##########
@@ -0,0 +1,328 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Stateless ``pagination_function`` factories for ``HttpOperator``.
+
+Each factory returns a callback ``(response) -> dict | None`` compatible with
+``airflow.providers.http.operators.http.HttpOperator``. The next page is
+derived only from that response (JSON body and the query string of
+``response.url``). Deferrable runs rebuild the task between pages, so a counter
+closed over by the callback would reset and request the same page again.
+
+The factories do not apply a page cap. Pass ``max_pages`` to ``HttpOperator``
+so the limit also covers a hand-written callback.
+
+Offset, page, and cursor values are read from the URL query. ``HttpHook`` sends
+``data`` as query parameters for GET and as a body otherwise, so these helpers
+target GET listings. A cursor that exists only in a POST body needs a custom
+callback.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from typing import Any
+from urllib.parse import parse_qsl, urljoin, urlparse
+
+from requests import Response
+
+log = logging.getLogger(__name__)
+
+PaginationCallback = Callable[[Response], dict[str, Any] | None]
+
+__all__ = [
+    "cursor_pagination",
+    "next_link_pagination",
+    "offset_pagination",
+    "page_number_pagination",
+]
+
+
+def offset_pagination(
+    *,
+    offset_param: str = "offset",
+    limit_param: str = "limit",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+) -> PaginationCallback:
+    """
+    Return a callback that advances an offset query parameter.
+
+    The next offset is the offset on ``response.url`` plus ``page_size``.
+    The callback returns ``None`` when the page has fewer than ``page_size``
+    records, or when ``has_more_key`` is present on the JSON object and false.
+
+    :param offset_param: Query parameter that carries the offset.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page. The offset 
advances by this amount.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    """
+    offset_param = _require_name("offset_param", offset_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, offset_param, default=0)
+        return {"data": {offset_param: current + page_size, limit_param: 
page_size}}
+
+    return next_page
+
+
+def page_number_pagination(
+    *,
+    page_param: str = "page",
+    limit_param: str = "page_size",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+    first_page: int = 1,
+) -> PaginationCallback:
+    """
+    Return a callback that advances a page-number query parameter.
+
+    When ``page_param`` is absent from ``response.url``, the current page is
+    ``first_page``. The callback returns ``None`` on a short page or when
+    ``has_more_key`` is present and false.
+
+    :param page_param: Query parameter that carries the page number.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    :param first_page: Page number used when the request URL has no page 
parameter.
+    """
+    page_param = _require_name("page_param", page_param)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+    first_page = _require_int("first_page", first_page)
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        current = _int_query(response.url, page_param, default=first_page)
+        return {"data": {page_param: current + 1, limit_param: page_size}}
+
+    return next_page
+
+
+def cursor_pagination(
+    *,
+    param: str,
+    field: str,
+    limit_param: str = "limit",
+    page_size: int = 100,
+    records_key: str = "",
+    has_more_key: str = "",
+    numeric: bool = False,
+) -> PaginationCallback:
+    """
+    Return a callback that sets a cursor query parameter to the max record 
field.
+
+    The walk stops when the cursor does not advance, the page is short, or
+    ``has_more_key`` is present and false. An empty cursor is never sent:
+    ``?after=`` is how some APIs mean "no filter" and would repeat the listing.
+
+    ``numeric=False`` compares values with ``max()`` on their original type.
+    Decimal strings do not sort numerically, so ``"999"`` is greater than
+    ``"1000"`` and the cursor stops moving. Set ``numeric=True`` to compare
+    them as integers.
+
+    :param param: Query parameter that carries the cursor.
+    :param field: Record field the cursor is taken from.
+    :param limit_param: Query parameter that carries the page size.
+    :param page_size: Number of records requested per page.
+    :param records_key: Key of the record list when the body is an object.
+        Empty when the body itself is the list.
+    :param has_more_key: Optional boolean field that is false on the last page.
+    :param numeric: Compare cursor values as integers instead of as strings.
+    """
+    param = _require_name("param", param)
+    field = _require_name("field", field)
+    limit_param = _require_name("limit_param", limit_param)
+    page_size = _require_page_size(page_size)
+    if not isinstance(numeric, bool):
+        raise ValueError("numeric must be a bool")
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        payload = response.json()
+        records = _records(payload, records_key)
+        if _short_page(payload, records, page_size=page_size, 
has_more_key=has_more_key):
+            return None
+        nxt = _max_field(records, field, numeric=numeric)
+        if nxt is None or str(nxt) == "":
+            return None
+        if _query_value(response.url, param) == str(nxt):
+            return None
+        return {"data": {param: nxt, limit_param: page_size}}
+
+    return next_page
+
+
+def next_link_pagination(
+    *,
+    path: str,
+    base_path: str = "",
+    allow_other_hosts: bool = False,
+) -> PaginationCallback:
+    """
+    Return a callback that follows a next-page URL stored in the JSON body.
+
+    ``path`` is a dotted path (``page.next``). The callback returns
+    ``{"endpoint": "<path>?<query>"}`` because ``HttpHook`` joins ``endpoint``
+    onto the connection's base URL. An absolute next URL is reduced to that
+    path and query. The request stays on the connection host either way, so
+    connection credentials are not sent to another host.
+
+    A next URL whose host differs from ``response.url`` is ignored unless
+    ``allow_other_hosts`` is true. When it is true, only the path and query are
+    used, still on the connection host. This matches the guard added for
+    Microsoft Graph next links: a payload must not redirect a credentialed
+    client at an arbitrary host.
+
+    If the connection host already includes a path 
(``https://api.example.com/v2``)
+    and the next URL repeats it (``/v2/feeds``), pass ``base_path="/v2"``.
+    Otherwise the hook appends ``/v2`` again and calls ``/v2/v2/feeds``.
+
+    :param path: Dotted path of the next-page URL in the JSON body.
+    :param base_path: Path prefix already present on the connection host, 
stripped
+        from the next URL so the endpoint is not doubled.
+    :param allow_other_hosts: Accept a next URL on a different host and use its
+        path on the connection host. The default refuses that URL.
+    """
+    path = _require_name("path", path)
+    if not isinstance(base_path, str):
+        raise ValueError("base_path must be a string")
+    if not isinstance(allow_other_hosts, bool):
+        raise ValueError("allow_other_hosts must be a bool")
+    stripped = base_path.strip().strip("/")
+    prefix = f"/{stripped}" if stripped else ""
+
+    def next_page(response: Response) -> dict[str, Any] | None:
+        nxt = _dig(response.json(), path)
+        if not isinstance(nxt, str) or not nxt.strip():
+            return None
+        current = urlparse(response.url)
+        resolved = urljoin(response.url, nxt.strip())
+        if resolved == response.url:
+            return None
+        target = urlparse(resolved)
+        if _netloc(target.netloc) != _netloc(current.netloc) and not 
allow_other_hosts:
+            log.warning(
+                "Ignoring next-page URL on a different host (%s). The response 
host is %s. "
+                "Set allow_other_hosts=True to use that link's path on the 
connection host.",
+                target.netloc,
+                current.netloc,
+            )
+            return None
+        endpoint = target.path or "/"
+        if prefix and (endpoint == prefix or 
endpoint.startswith(f"{prefix}/")):
+            endpoint = endpoint[len(prefix) :] or "/"
+        if not endpoint.startswith("/"):
+            endpoint = f"/{endpoint}"
+        if target.query:
+            endpoint = f"{endpoint}?{target.query}"
+        return {"endpoint": endpoint}
+
+    return next_page
+
+
+def _require_name(name: str, value: str) -> str:
+    if not isinstance(value, str) or not value:
+        raise ValueError(f"{name} must be a non-empty string")
+    return value
+
+
+def _require_page_size(page_size: int) -> int:
+    if isinstance(page_size, bool) or not isinstance(page_size, int) or 
page_size < 1:
+        raise ValueError("page_size must be a positive integer")
+    return page_size
+
+
+def _require_int(name: str, value: int) -> int:
+    if isinstance(value, bool) or not isinstance(value, int):
+        raise ValueError(f"{name} must be an integer")
+    return value
+
+
+def _netloc(netloc: str) -> str:
+    return netloc.casefold()
+
+
+def _records(payload: Any, records_key: str) -> list[Any]:
+    if records_key:
+        rows = payload.get(records_key, []) if isinstance(payload, dict) else 
[]
+        return rows if isinstance(rows, list) else []
+    return payload if isinstance(payload, list) else []
+
+
+def _short_page(payload: Any, records: list[Any], *, page_size: int, 
has_more_key: str) -> bool:
+    if has_more_key and isinstance(payload, dict) and not 
bool(payload.get(has_more_key, True)):
+        return True
+    return len(records) < page_size

Review Comment:
   **[warning]** A short page ends the walk even when the API says `has_more` 
is true.
   
   `_short_page` uses `has_more_key` only to stop earlier; when the field is 
present and true, `len(records) < page_size` still wins. An API that caps the 
page size below the requested one (asked 100, serves 50, `has_more: true`) 
stops after the first page: `offset_pagination(page_size=100, 
records_key="orders", has_more_key="has_more")` returns `None` for a 50-record 
page with `has_more: true`. Again a silent partial result.
   
   When `has_more_key` is configured and present in the body, it should decide 
alone; the length heuristic is the fallback for APIs without such a field. In 
that case the offset should also advance by `len(records)` rather than 
`page_size`, or the walk skips records.



##########
providers/http/tests/unit/http/operators/test_pagination.py:
##########
@@ -0,0 +1,566 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import json
+import logging
+import re
+from collections.abc import Callable
+from typing import Any
+from unittest import mock
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+import requests
+import tenacity
+from requests import Response
+
+from airflow.models import Connection
+from airflow.providers.common.compat.sdk import TaskDeferred
+from airflow.providers.http.hooks.http import HttpHook
+from airflow.providers.http.operators.http import HttpOperator
+from airflow.providers.http.operators.pagination import (
+    cursor_pagination,
+    next_link_pagination,
+    offset_pagination,
+    page_number_pagination,
+)
+from airflow.providers.http.triggers.http import HttpResponseSerializer
+
+BASE = "https://api.example.com";
+EVENTS = ("997", "998", "999", "1000", "1001", "1002")
+ORDERS = list(range(1, 8))
+
+
+def _query(request) -> dict[str, list[str]]:
+    return parse_qs(urlparse(request.url).query, keep_blank_values=True)
+
+
+def _query_int(request, name: str, default: int) -> int:
+    raw = _query(request).get(name)
+    if not raw or raw[0] == "":
+        return default
+    return int(raw[0])
+
+
+def _json_body(payload_for: Callable[..., Any]) -> Callable[..., str]:
+    def _respond(request, context):
+        context.status_code = 200
+        context.headers["Content-Type"] = "application/json"
+        return json.dumps(payload_for(request))
+
+    return _respond
+
+
+def _orders_payload(request) -> dict[str, Any]:
+    offset = _query_int(request, "offset", 0)
+    limit = _query_int(request, "limit", 3)
+    if offset > 30:
+        raise AssertionError(f"offset pagination did not advance 
(offset={offset})")
+    window = ORDERS[offset : offset + limit]
+    return {"orders": window, "has_more": offset + limit < len(ORDERS)}
+
+
+def _events_payload(request) -> dict[str, Any]:
+    limit = _query_int(request, "limit", 2)
+    after = _query(request).get("after")
+    calls = getattr(_events_payload, "calls", 0) + 1
+    _events_payload.calls = calls
+    if calls > 12:
+        raise AssertionError("cursor pagination did not stop")
+    if after is not None and after[0] == "":
+        matched = list(EVENTS)
+        unfiltered = True
+    elif after is not None:
+        cursor = int(after[0])
+        matched = [event_id for event_id in EVENTS if int(event_id) >= cursor]
+        unfiltered = False
+    else:
+        matched = list(EVENTS)
+        unfiltered = False
+    return {"events": [{"id": event_id} for event_id in matched[:limit]], 
"unfiltered": unfiltered}
+
+
+def _walk(first_url: str, pager, *, limit: int = 10) -> list[Response]:
+    """Follow a pagination callback the way HttpOperator merges ``data`` or 
``endpoint``."""
+    url = first_url
+    responses: list[Response] = []
+    for _ in range(limit):
+        response = requests.get(url, timeout=5)
+        responses.append(response)
+        nxt = pager(response)
+        if not nxt:
+            return responses
+        if "endpoint" in nxt:
+            parsed = urlparse(url)
+            url = f"{parsed.scheme}://{parsed.netloc}{nxt['endpoint']}"
+        else:
+            url = requests.Request("GET", url.split("?")[0], 
params=nxt["data"]).prepare().url
+    raise AssertionError(f"pagination did not stop after {limit} requests")
+
+
+def _distinct_ids(responses: list[Response], key: str) -> list[Any]:
+    seen: list[Any] = []
+    for response in responses:
+        for row in response.json()[key]:
+            row_id = row["id"] if isinstance(row, dict) else row
+            if row_id not in seen:
+                seen.append(row_id)
+    return seen
+
+
+def _serialized_page(url: str, payload: dict[str, Any]) -> dict[str, Any]:
+    response = Response()
+    response.status_code = 200
+    response.url = url
+    response.encoding = "utf-8"
+    response.headers["Content-Type"] = "application/json"
+    response._content = json.dumps(payload).encode()
+    return {
+        "context": {},
+        "event": {"status": "success", "response": 
HttpResponseSerializer.serialize(response)},
+    }
+
+
+class TestOffsetPagination:
+    def test_walks_until_has_more_is_false(self, requests_mock):
+        requests_mock.get(re.compile(rf"{BASE}/orders"), 
text=_json_body(_orders_payload))
+        pager = offset_pagination(page_size=3, records_key="orders", 
has_more_key="has_more")
+        responses = _walk(f"{BASE}/orders?offset=0&limit=3", pager)
+        assert _distinct_ids(responses, "orders") == ORDERS
+        assert len(responses) == 3
+
+    def test_same_response_yields_the_same_next_page(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders?offset=4&limit=2", json={"orders": 
[5, 6]})
+        response = requests.get(f"{BASE}/orders?offset=4&limit=2", timeout=5)
+        first = offset_pagination(page_size=2, records_key="orders")
+        second = offset_pagination(page_size=2, records_key="orders")
+        assert first(response) == {"data": {"offset": 6, "limit": 2}}
+        assert second(response) == first(response)
+
+    def test_short_page_stops(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders?offset=0&limit=3", json={"orders": 
[1]})
+        response = requests.get(f"{BASE}/orders?offset=0&limit=3", timeout=5)
+        assert offset_pagination(page_size=3, records_key="orders")(response) 
is None
+
+    def test_missing_offset_starts_at_zero(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders", json=[1, 2])
+        response = requests.get(f"{BASE}/orders", timeout=5)
+        assert offset_pagination(page_size=2)(response) == {"data": {"offset": 
2, "limit": 2}}
+
+    def test_page_size_must_be_positive(self):
+        with pytest.raises(ValueError, match="page_size"):
+            offset_pagination(page_size=0)
+
+
+class TestPageNumberPagination:
+    def test_reads_the_page_from_the_response_url(self, requests_mock):
+        requests_mock.get(f"{BASE}/customers?page=3&page_size=2", 
json={"customers": [1, 2]})
+        response = requests.get(f"{BASE}/customers?page=3&page_size=2", 
timeout=5)
+        nxt = page_number_pagination(page_size=2, 
records_key="customers")(response)
+        assert nxt == {"data": {"page": 4, "page_size": 2}}
+
+    def test_missing_page_param_uses_first_page(self, requests_mock):
+        requests_mock.get(f"{BASE}/customers", json=[1, 2])
+        response = requests.get(f"{BASE}/customers", timeout=5)
+        assert page_number_pagination(page_size=2)(response)["data"]["page"] 
== 2
+
+    def test_walks_a_short_last_page(self, requests_mock):
+        customers = list(range(1, 6))
+
+        def payload(request):
+            page = _query_int(request, "page", 1)
+            page_size = _query_int(request, "page_size", 2)
+            start = (page - 1) * page_size
+            return {"customers": customers[start : start + page_size]}
+
+        requests_mock.get(re.compile(rf"{BASE}/customers"), 
text=_json_body(payload))
+        pager = page_number_pagination(page_size=2, records_key="customers")
+        responses = _walk(f"{BASE}/customers?page=1&page_size=2", pager)
+        assert _distinct_ids(responses, "customers") == customers
+        assert len(responses) == 3
+
+
+class TestCursorPagination:
+    @pytest.mark.parametrize(("numeric", "expected"), [(True, 1000), (False, 
"999")])
+    def test_numeric_comparison_does_not_stop_on_string_order(self, 
requests_mock, numeric, expected):
+        # "999" > "1000" as text, so a string max never moves past the page 
that contains both.
+        requests_mock.get(
+            f"{BASE}/events",
+            json={"events": [{"id": "999"}, {"id": "1000"}]},
+        )
+        response = requests.get(f"{BASE}/events", timeout=5)
+        pager = cursor_pagination(
+            param="after", field="id", page_size=2, records_key="events", 
numeric=numeric
+        )
+        assert pager(response)["data"]["after"] == expected
+
+    def test_stops_when_the_cursor_does_not_advance(self, requests_mock):
+        requests_mock.get(
+            f"{BASE}/events?after=1000",
+            json={"events": [{"id": "999"}, {"id": "1000"}]},
+        )
+        response = requests.get(f"{BASE}/events?after=1000", timeout=5)
+        pager = cursor_pagination(param="after", field="id", page_size=2, 
records_key="events", numeric=True)
+        assert pager(response) is None
+
+    def test_never_sends_an_empty_cursor(self, requests_mock):
+        requests_mock.get(f"{BASE}/events", json={"events": [{"id": ""}, 
{"id": ""}]})
+        response = requests.get(f"{BASE}/events", timeout=5)
+        pager = cursor_pagination(param="after", field="id", page_size=2, 
records_key="events")
+        assert pager(response) is None
+
+    @pytest.mark.parametrize(
+        ("numeric", "expected_ids"),
+        [
+            (False, ["997", "998", "999", "1000"]),
+            (True, ["997", "998", "999", "1000", "1001", "1002"]),
+        ],
+    )
+    def test_walk_string_cursor_stops_before_1001(self, requests_mock, 
numeric, expected_ids):
+        _events_payload.calls = 0
+        requests_mock.get(re.compile(rf"{BASE}/events"), 
text=_json_body(_events_payload))
+        pager = cursor_pagination(
+            param="after", field="id", page_size=2, records_key="events", 
numeric=numeric
+        )
+        responses = _walk(f"{BASE}/events?limit=2", pager)
+        assert _distinct_ids(responses, "events") == expected_ids
+        if not numeric:
+            assert all("1001" not in response.url and "1002" not in 
response.url for response in responses)
+
+
+class TestNextLinkPagination:
+    def test_relative_link_becomes_an_endpoint(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"/feeds?cursor=2"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        assert next_link_pagination(path="page.next")(response) == 
{"endpoint": "/feeds?cursor=2"}
+
+    def test_other_host_is_refused(self, requests_mock, caplog):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"https://evil.invalid/steal"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        with caplog.at_level(logging.WARNING):
+            assert next_link_pagination(path="page.next")(response) is None
+        assert "different host" in caplog.text

Review Comment:
   **[nit]** Assertions on `caplog.text` (here and on lines 259, 333, 352, 417, 
504).
   
   
[`AGENTS.md`](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/AGENTS.md?plain=1#L172):
 "Do not assert on raw log text (`caplog.text` for example)". The structured 
form (`"..." in caplog`, or a dict with the event and its fields) is the one to 
use.



##########
providers/http/tests/unit/http/operators/test_pagination.py:
##########
@@ -0,0 +1,566 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import json
+import logging
+import re
+from collections.abc import Callable
+from typing import Any
+from unittest import mock
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+import requests
+import tenacity
+from requests import Response
+
+from airflow.models import Connection
+from airflow.providers.common.compat.sdk import TaskDeferred
+from airflow.providers.http.hooks.http import HttpHook
+from airflow.providers.http.operators.http import HttpOperator
+from airflow.providers.http.operators.pagination import (
+    cursor_pagination,
+    next_link_pagination,
+    offset_pagination,
+    page_number_pagination,
+)
+from airflow.providers.http.triggers.http import HttpResponseSerializer
+
+BASE = "https://api.example.com";
+EVENTS = ("997", "998", "999", "1000", "1001", "1002")
+ORDERS = list(range(1, 8))
+
+
+def _query(request) -> dict[str, list[str]]:
+    return parse_qs(urlparse(request.url).query, keep_blank_values=True)
+
+
+def _query_int(request, name: str, default: int) -> int:
+    raw = _query(request).get(name)
+    if not raw or raw[0] == "":
+        return default
+    return int(raw[0])
+
+
+def _json_body(payload_for: Callable[..., Any]) -> Callable[..., str]:
+    def _respond(request, context):
+        context.status_code = 200
+        context.headers["Content-Type"] = "application/json"
+        return json.dumps(payload_for(request))
+
+    return _respond
+
+
+def _orders_payload(request) -> dict[str, Any]:
+    offset = _query_int(request, "offset", 0)
+    limit = _query_int(request, "limit", 3)
+    if offset > 30:
+        raise AssertionError(f"offset pagination did not advance 
(offset={offset})")
+    window = ORDERS[offset : offset + limit]
+    return {"orders": window, "has_more": offset + limit < len(ORDERS)}
+
+
+def _events_payload(request) -> dict[str, Any]:
+    limit = _query_int(request, "limit", 2)
+    after = _query(request).get("after")
+    calls = getattr(_events_payload, "calls", 0) + 1
+    _events_payload.calls = calls
+    if calls > 12:
+        raise AssertionError("cursor pagination did not stop")
+    if after is not None and after[0] == "":
+        matched = list(EVENTS)
+        unfiltered = True
+    elif after is not None:
+        cursor = int(after[0])
+        matched = [event_id for event_id in EVENTS if int(event_id) >= cursor]
+        unfiltered = False
+    else:
+        matched = list(EVENTS)
+        unfiltered = False
+    return {"events": [{"id": event_id} for event_id in matched[:limit]], 
"unfiltered": unfiltered}
+
+
+def _walk(first_url: str, pager, *, limit: int = 10) -> list[Response]:
+    """Follow a pagination callback the way HttpOperator merges ``data`` or 
``endpoint``."""
+    url = first_url
+    responses: list[Response] = []
+    for _ in range(limit):
+        response = requests.get(url, timeout=5)
+        responses.append(response)
+        nxt = pager(response)
+        if not nxt:
+            return responses
+        if "endpoint" in nxt:
+            parsed = urlparse(url)
+            url = f"{parsed.scheme}://{parsed.netloc}{nxt['endpoint']}"
+        else:
+            url = requests.Request("GET", url.split("?")[0], 
params=nxt["data"]).prepare().url
+    raise AssertionError(f"pagination did not stop after {limit} requests")
+
+
+def _distinct_ids(responses: list[Response], key: str) -> list[Any]:
+    seen: list[Any] = []
+    for response in responses:
+        for row in response.json()[key]:
+            row_id = row["id"] if isinstance(row, dict) else row
+            if row_id not in seen:
+                seen.append(row_id)
+    return seen
+
+
+def _serialized_page(url: str, payload: dict[str, Any]) -> dict[str, Any]:
+    response = Response()
+    response.status_code = 200
+    response.url = url
+    response.encoding = "utf-8"
+    response.headers["Content-Type"] = "application/json"
+    response._content = json.dumps(payload).encode()
+    return {
+        "context": {},
+        "event": {"status": "success", "response": 
HttpResponseSerializer.serialize(response)},
+    }
+
+
+class TestOffsetPagination:
+    def test_walks_until_has_more_is_false(self, requests_mock):
+        requests_mock.get(re.compile(rf"{BASE}/orders"), 
text=_json_body(_orders_payload))
+        pager = offset_pagination(page_size=3, records_key="orders", 
has_more_key="has_more")
+        responses = _walk(f"{BASE}/orders?offset=0&limit=3", pager)
+        assert _distinct_ids(responses, "orders") == ORDERS
+        assert len(responses) == 3
+
+    def test_same_response_yields_the_same_next_page(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders?offset=4&limit=2", json={"orders": 
[5, 6]})
+        response = requests.get(f"{BASE}/orders?offset=4&limit=2", timeout=5)
+        first = offset_pagination(page_size=2, records_key="orders")
+        second = offset_pagination(page_size=2, records_key="orders")
+        assert first(response) == {"data": {"offset": 6, "limit": 2}}
+        assert second(response) == first(response)
+
+    def test_short_page_stops(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders?offset=0&limit=3", json={"orders": 
[1]})
+        response = requests.get(f"{BASE}/orders?offset=0&limit=3", timeout=5)
+        assert offset_pagination(page_size=3, records_key="orders")(response) 
is None
+
+    def test_missing_offset_starts_at_zero(self, requests_mock):
+        requests_mock.get(f"{BASE}/orders", json=[1, 2])
+        response = requests.get(f"{BASE}/orders", timeout=5)
+        assert offset_pagination(page_size=2)(response) == {"data": {"offset": 
2, "limit": 2}}
+
+    def test_page_size_must_be_positive(self):
+        with pytest.raises(ValueError, match="page_size"):
+            offset_pagination(page_size=0)
+
+
+class TestPageNumberPagination:
+    def test_reads_the_page_from_the_response_url(self, requests_mock):
+        requests_mock.get(f"{BASE}/customers?page=3&page_size=2", 
json={"customers": [1, 2]})
+        response = requests.get(f"{BASE}/customers?page=3&page_size=2", 
timeout=5)
+        nxt = page_number_pagination(page_size=2, 
records_key="customers")(response)
+        assert nxt == {"data": {"page": 4, "page_size": 2}}
+
+    def test_missing_page_param_uses_first_page(self, requests_mock):
+        requests_mock.get(f"{BASE}/customers", json=[1, 2])
+        response = requests.get(f"{BASE}/customers", timeout=5)
+        assert page_number_pagination(page_size=2)(response)["data"]["page"] 
== 2
+
+    def test_walks_a_short_last_page(self, requests_mock):
+        customers = list(range(1, 6))
+
+        def payload(request):
+            page = _query_int(request, "page", 1)
+            page_size = _query_int(request, "page_size", 2)
+            start = (page - 1) * page_size
+            return {"customers": customers[start : start + page_size]}
+
+        requests_mock.get(re.compile(rf"{BASE}/customers"), 
text=_json_body(payload))
+        pager = page_number_pagination(page_size=2, records_key="customers")
+        responses = _walk(f"{BASE}/customers?page=1&page_size=2", pager)
+        assert _distinct_ids(responses, "customers") == customers
+        assert len(responses) == 3
+
+
+class TestCursorPagination:
+    @pytest.mark.parametrize(("numeric", "expected"), [(True, 1000), (False, 
"999")])
+    def test_numeric_comparison_does_not_stop_on_string_order(self, 
requests_mock, numeric, expected):
+        # "999" > "1000" as text, so a string max never moves past the page 
that contains both.
+        requests_mock.get(
+            f"{BASE}/events",
+            json={"events": [{"id": "999"}, {"id": "1000"}]},
+        )
+        response = requests.get(f"{BASE}/events", timeout=5)
+        pager = cursor_pagination(
+            param="after", field="id", page_size=2, records_key="events", 
numeric=numeric
+        )
+        assert pager(response)["data"]["after"] == expected
+
+    def test_stops_when_the_cursor_does_not_advance(self, requests_mock):
+        requests_mock.get(
+            f"{BASE}/events?after=1000",
+            json={"events": [{"id": "999"}, {"id": "1000"}]},
+        )
+        response = requests.get(f"{BASE}/events?after=1000", timeout=5)
+        pager = cursor_pagination(param="after", field="id", page_size=2, 
records_key="events", numeric=True)
+        assert pager(response) is None
+
+    def test_never_sends_an_empty_cursor(self, requests_mock):
+        requests_mock.get(f"{BASE}/events", json={"events": [{"id": ""}, 
{"id": ""}]})
+        response = requests.get(f"{BASE}/events", timeout=5)
+        pager = cursor_pagination(param="after", field="id", page_size=2, 
records_key="events")
+        assert pager(response) is None
+
+    @pytest.mark.parametrize(
+        ("numeric", "expected_ids"),
+        [
+            (False, ["997", "998", "999", "1000"]),
+            (True, ["997", "998", "999", "1000", "1001", "1002"]),
+        ],
+    )
+    def test_walk_string_cursor_stops_before_1001(self, requests_mock, 
numeric, expected_ids):
+        _events_payload.calls = 0
+        requests_mock.get(re.compile(rf"{BASE}/events"), 
text=_json_body(_events_payload))
+        pager = cursor_pagination(
+            param="after", field="id", page_size=2, records_key="events", 
numeric=numeric
+        )
+        responses = _walk(f"{BASE}/events?limit=2", pager)
+        assert _distinct_ids(responses, "events") == expected_ids
+        if not numeric:
+            assert all("1001" not in response.url and "1002" not in 
response.url for response in responses)
+
+
+class TestNextLinkPagination:
+    def test_relative_link_becomes_an_endpoint(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"/feeds?cursor=2"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        assert next_link_pagination(path="page.next")(response) == 
{"endpoint": "/feeds?cursor=2"}
+
+    def test_other_host_is_refused(self, requests_mock, caplog):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"https://evil.invalid/steal"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        with caplog.at_level(logging.WARNING):
+            assert next_link_pagination(path="page.next")(response) is None
+        assert "different host" in caplog.text
+        assert "evil.invalid" in caplog.text
+
+    def test_protocol_relative_other_host_is_refused(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"//evil.invalid/steal"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        assert next_link_pagination(path="page.next")(response) is None
+
+    def test_other_host_path_is_used_when_opted_in(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": 
"https://cdn.example.com/feeds?c=2"}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        pager = next_link_pagination(path="page.next", allow_other_hosts=True)
+        assert pager(response) == {"endpoint": "/feeds?c=2"}
+
+    def test_base_path_is_not_doubled(self, requests_mock):
+        requests_mock.get(f"{BASE}/v2/feeds", json={"page": {"next": 
"/v2/feeds?cursor=2"}})
+        response = requests.get(f"{BASE}/v2/feeds", timeout=5)
+        pager = next_link_pagination(path="page.next", base_path="/v2")
+        assert pager(response) == {"endpoint": "/feeds?cursor=2"}
+
+    def test_base_path_does_not_strip_a_longer_segment(self, requests_mock):
+        requests_mock.get(f"{BASE}/v20/feeds", json={"page": {"next": 
"/v20/feeds?cursor=2"}})
+        response = requests.get(f"{BASE}/v20/feeds", timeout=5)
+        pager = next_link_pagination(path="page.next", base_path="/v2")
+        assert pager(response) == {"endpoint": "/v20/feeds?cursor=2"}
+
+    def test_self_link_stops(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds?cursor=2", json={"page": {"next": 
"/feeds?cursor=2"}})
+        response = requests.get(f"{BASE}/feeds?cursor=2", timeout=5)
+        assert next_link_pagination(path="page.next")(response) is None
+
+    def test_null_next_link_stops(self, requests_mock):
+        requests_mock.get(f"{BASE}/feeds", json={"page": {"next": None}})
+        response = requests.get(f"{BASE}/feeds", timeout=5)
+        assert next_link_pagination(path="page.next")(response) is None
+
+
[email protected]("os.environ", 
AIRFLOW_CONN_HTTP_EXAMPLE="http://www.example.com";)
+class TestHttpOperatorMaxPages:
+    @pytest.fixture(autouse=True)
+    def _connections(self, create_connection_without_db):
+        create_connection_without_db(
+            Connection(
+                conn_id="http_default", conn_type="http", host="test:8080/", 
extra='{"bearer": "test"}'
+            )
+        )
+        create_connection_without_db(
+            Connection(conn_id="http_with_base_path", conn_type="http", 
host="http://api.example.com/v2";)
+        )
+
+    def test_sync_max_pages_stops_and_warns(self, requests_mock, caplog):
+        def payload(request):
+            offset = _query_int(request, "offset", 0)
+            if offset > 20:
+                raise AssertionError("max_pages did not stop the sync loop")
+            return {"rows": [offset, offset + 1], "has_more": True}
+
+        requests_mock.get(re.compile(r"http://www\.example\.com/rows";), 
text=_json_body(payload))
+        operator = HttpOperator(
+            task_id="capped",
+            method="GET",
+            endpoint="/rows",
+            data={"offset": 0, "limit": 2},
+            http_conn_id="HTTP_EXAMPLE",
+            pagination_function=offset_pagination(page_size=2, 
records_key="rows", has_more_key="has_more"),
+            max_pages=2,
+            response_filter=lambda responses: [
+                row for response in responses for row in 
response.json()["rows"]
+            ],
+        )
+        with caplog.at_level(logging.WARNING):
+            result = operator.execute({})
+
+        assert result == [0, 1, 2, 3]
+        assert len(requests_mock.request_history) == 2
+        assert "max_pages=2" in caplog.text
+
+    def test_sync_does_not_warn_when_the_listing_ends_on_the_cap(self, 
requests_mock, caplog):
+        requests_mock.get(
+            re.compile(r"http://www\.example\.com/rows";),
+            text=_json_body(lambda request: {"rows": [1], "has_more": False}),
+        )
+        operator = HttpOperator(
+            task_id="exact_cap",
+            method="GET",
+            endpoint="/rows",
+            data={"offset": 0, "limit": 2},
+            http_conn_id="HTTP_EXAMPLE",
+            pagination_function=offset_pagination(page_size=2, 
records_key="rows", has_more_key="has_more"),
+            max_pages=1,
+        )
+        with caplog.at_level(logging.WARNING):
+            result = operator.execute({})
+        assert json.loads(result[0]) == {"rows": [1], "has_more": False}
+        assert "max_pages=" not in caplog.text
+
+    def test_fresh_callback_each_page_keeps_advancing(self, requests_mock):
+        """A new factory per page must read the offset from the response, not 
from a counter."""
+        requests_mock.get(re.compile(r"http://www\.example\.com/orders";), 
text=_json_body(_orders_payload))
+
+        def pagination_function(response):
+            return offset_pagination(page_size=3, records_key="orders", 
has_more_key="has_more")(response)
+
+        operator = HttpOperator(
+            task_id="fresh",
+            method="GET",
+            endpoint="/orders",
+            data={"offset": 0, "limit": 3},
+            http_conn_id="HTTP_EXAMPLE",
+            pagination_function=pagination_function,
+            response_filter=lambda responses: _distinct_ids(responses, 
"orders"),
+        )
+        assert operator.execute({}) == ORDERS
+        offsets = [_query_int(request, "offset", 0) for request in 
requests_mock.request_history]
+        assert offsets == [0, 3, 6]
+
+    @pytest.mark.parametrize(
+        ("numeric", "expected_ids"),
+        [
+            (False, ["997", "998", "999", "1000"]),
+            (True, ["997", "998", "999", "1000", "1001", "1002"]),
+        ],
+    )
+    def test_string_cursor_stops_early_and_numeric_cursor_does_not(
+        self, requests_mock, numeric, expected_ids
+    ):
+        _events_payload.calls = 0
+        requests_mock.get(re.compile(r"http://www\.example\.com/events";), 
text=_json_body(_events_payload))
+        operator = HttpOperator(
+            task_id="events",
+            method="GET",
+            endpoint="/events",
+            data={"limit": 2},
+            http_conn_id="HTTP_EXAMPLE",
+            pagination_function=cursor_pagination(
+                param="after", field="id", page_size=2, records_key="events", 
numeric=numeric
+            ),
+            response_filter=lambda responses: _distinct_ids(responses, 
"events"),
+        )
+        assert operator.execute({}) == expected_ids
+
+    def test_other_host_next_link_does_not_leave_the_connection(self, 
requests_mock, caplog):
+        requests_mock.get(
+            re.compile(r"http://www\.example\.com/feeds";),
+            text=_json_body(
+                lambda request: {"items": [{"id": "t1"}], "page": {"next": 
"http://evil.invalid/steal"}}
+            ),
+        )
+        operator = HttpOperator(
+            task_id="trap",
+            method="GET",
+            endpoint="/feeds",
+            http_conn_id="HTTP_EXAMPLE",
+            pagination_function=next_link_pagination(path="page.next"),
+            response_filter=lambda responses: _distinct_ids(responses, 
"items"),
+        )
+        with caplog.at_level(logging.WARNING):
+            assert operator.execute({}) == ["t1"]
+        assert len(requests_mock.request_history) == 1
+        assert "different host" in caplog.text
+
+    def test_connection_base_path_is_not_doubled(self, requests_mock):
+        def payload(request):
+            if urlparse(request.url).path != "/v2/feeds":
+                raise AssertionError(f"endpoint was doubled: {request.url}")
+            if _query(request).get("cursor") == ["2"]:
+                return {"items": [{"id": "f3"}], "page": {"next": None}}
+            return {"items": [{"id": "f1"}, {"id": "f2"}], "page": {"next": 
"/v2/feeds?cursor=2"}}
+
+        requests_mock.get(re.compile(r"http://api\.example\.com/";), 
text=_json_body(payload))
+        operator = HttpOperator(
+            task_id="base_path",
+            method="GET",
+            endpoint="/feeds",
+            http_conn_id="http_with_base_path",
+            pagination_function=next_link_pagination(path="page.next", 
base_path="/v2"),
+            response_filter=lambda responses: _distinct_ids(responses, 
"items"),
+        )
+        assert operator.execute({}) == ["f1", "f2", "f3"]
+        assert [urlparse(request.url).path for request in 
requests_mock.request_history] == [
+            "/v2/feeds",
+            "/v2/feeds",
+        ]
+
+    @pytest.mark.parametrize("max_pages", [0, -1, True, 1.5, "2"])
+    def test_max_pages_rejects_non_positive_integers(self, max_pages):
+        with pytest.raises(ValueError, match="max_pages"):
+            HttpOperator(task_id="bad_cap", max_pages=max_pages)
+
+    @mock.patch.object(HttpHook, "run_with_advanced_retry")

Review Comment:
   **[nit]** `mock.patch.object(HttpHook, "run_with_advanced_retry")` without 
`autospec=True`.
   
   
[`AGENTS.md`](https://github.com/apache/airflow/blob/1c1db41100b8223a3cf23231d8300c4f07869efa/AGENTS.md?plain=1#L165):
 "Use `spec`/`autospec` when mocking". With `autospec=True` the test would also 
fail if the operator called the hook with arguments its signature does not 
accept.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to