Paginated reads lose headers and metadata and refetch the first page

Open
#172 1 comment 0 reactions 1 assignee View on GitHub

@QixiaLu is already working on this.

Since Nov 6, 2026.

  • #176 by @benhaspalace — open

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
go
Domain
api

Research direction

Start with internal/clients/msgraph_client.go and the existing tests in internal/clients/msgraph_client_test.go; run the supplied regression test command to confirm the pagination failures. Trace how Read and List fetch and aggregate pages, then cover headers, metadata, request counts, retries, cancellation, and single object reads. Done when the acceptance cases pass while the existing Read and List interfaces remain unchanged.

Written by the indexing model from the issue text.

Description

Summary

The shared Graph client has three observable pagination problems: continuation requests lose caller headers, collection metadata is omitted from the returned result, and Read fetches the first page twice before completing a paginated response. All three can be reproduced using a two-page scripted transport.

Tested against current main at 1551ea433b5c92652b527f11eee7bf988133d836 using Go 1.26.5 on Linux/amd64. The affected provider implementation is also present in v0.6.0; the executable checks below used main's vendored dependencies. These are deterministic local reproductions with synthetic values: no Graph tenant, Azure credentials or live acceptance run was used.

Actual versus expected

Behavior Current main Expected
ConsistencyLevel / Prefer headers Present on the first page, absent on the continuation Retained on each continuation request
@odata.count, @odata.context, final @odata.deltaLink Dropped when the page contains a value array Retained with the combined collection
Requests for a two-page Read Three GETs Two GETs

This can break paginated advanced queries that require ConsistencyLevel: eventual, lose count/delta information requested by callers, and consume unnecessary request budget. No universal Graph throttle limit is assumed.

Reproduction without a tenant
  1. Clone this repository and check out 1551ea433b5c92652b527f11eee7bf988133d836.
  2. Save the following file as internal/clients/msgraph_pagination_test.go.
  3. Run go test -mod=vendor ./internal/clients -run 'TestMSGraphClientPagination|TestMSGraphClientReadSingleObject' -count=1 from the repository root with Go 1.26.5. No TF_ACC or ARM credentials are required.
Complete regression test
package clients

import (
	"context"
	"io"
	"net/http"
	"reflect"
	"strings"
	"testing"
	"testing/synctest"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
)

type paginationTransport func(*http.Request) (*http.Response, error)

func (f paginationTransport) Do(req *http.Request) (*http.Response, error) { return f(req) }

func TestMSGraphClientPagination(t *testing.T) {
	for _, method := range []string{"Read", "List"} {
		for _, emptyFirst := range []bool{false, true} {
			t.Run(method+"/emptyFirst="+map[bool]string{false: "false", true: "true"}[emptyFirst], func(t *testing.T) {
				calls := 0
				client, err := NewMSGraphClient(&testCredential{}, cloud.Configuration{}, &policy.ClientOptions{Transport: paginationTransport(func(req *http.Request) (*http.Response, error) {
					calls++
					if got := req.Header.Get("ConsistencyLevel"); got != "eventual" {
						t.Errorf("request %d ConsistencyLevel = %q", calls, got)
					}
					if got := req.Header.Get("Prefer"); got != "odata.maxpagesize=1" {
						t.Errorf("request %d Prefer = %q", calls, got)
					}
					if got := req.Header.Get("Accept"); got != "application/json" {
						t.Errorf("request %d Accept = %q", calls, got)
					}
					body := `{"value":[{"id":"second"}],"@odata.deltaLink":"https://graph.microsoft.com/v1.0/groups/delta?$deltatoken=opaque"}`
					if req.URL.Query().Get("$skiptoken") == "" {
						if req.URL.Query().Get("$count") != "true" {
							t.Error("initial query parameters missing")
						}
						values := `[{"id":"first"}]`
						if emptyFirst {
							values = `[]`
						}
						body = `{"@odata.context":"collection-context","@odata.count":2,"value":` + values + `,"@odata.nextLink":"https://graph.microsoft.com/v1.0/groups?$skiptoken=opaque%2Btoken"}`
					} else if req.URL.RawQuery != "$skiptoken=opaque%2Btoken" {
						t.Errorf("continuation query was modified: %s", req.URL.RawQuery)
					}
					return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
				})})
				if err != nil {
					t.Fatal(err)
				}
				opts := RequestOptions{Headers: map[string]string{"ConsistencyLevel": "eventual", "Prefer": "odata.maxpagesize=1"}, QueryParameters: map[string]string{"$count": "true"}}
				var result interface{}
				if method == "Read" {
					result, err = client.Read(context.Background(), "groups", "v1.0", opts)
				} else {
					result, err = client.List(context.Background(), "groups", "v1.0", opts)
				}
				if err != nil {
					t.Fatal(err)
				}
				wantValues := []interface{}{map[string]interface{}{"id": "second"}}
				if !emptyFirst {
					wantValues = append([]interface{}{map[string]interface{}{"id": "first"}}, wantValues...)
				}
				want := map[string]interface{}{"value": wantValues, "@odata.context": "collection-context", "@odata.count": float64(2), "@odata.deltaLink": "https://graph.microsoft.com/v1.0/groups/delta?$deltatoken=opaque"}
				if !reflect.DeepEqual(result, want) {
					t.Errorf("result = %#v, want %#v", result, want)
				}
				if calls != 2 {
					t.Errorf("requests = %d, want 2", calls)
				}
			})
		}
	}
}

func TestMSGraphClientPaginationRetryAndCancellation(t *testing.T) {
	for _, cancelAfterFirst := range []bool{false, true} {
		t.Run(map[bool]string{false: "retry", true: "cancel"}[cancelAfterFirst], func(t *testing.T) {
			synctest.Test(t, func(t *testing.T) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()
				calls := 0
				client, err := NewMSGraphClient(&testCredential{}, cloud.Configuration{}, &policy.ClientOptions{Transport: paginationTransport(func(req *http.Request) (*http.Response, error) {
					calls++
					status, body := http.StatusOK, `{"value":[],"@odata.nextLink":"https://graph.microsoft.com/v1.0/groups?$skiptoken=next"}`
					switch {
					case cancelAfterFirst:
						cancel()
					case calls == 1:
						status = http.StatusServiceUnavailable
					case calls == 3:
						body = `{"value":[{"id":"last"}]}`
					}
					return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
				})})
				if err != nil {
					t.Fatal(err)
				}
				_, err = client.List(ctx, "groups", "v1.0", RequestOptions{RetryOptions: &policy.RetryOptions{MaxRetries: 1, RetryDelay: time.Millisecond, MaxRetryDelay: time.Millisecond}})
				if cancelAfterFirst {
					if err == nil || calls != 1 {
						t.Fatalf("cancel: calls=%d, error=%v", calls, err)
					}
				} else if err != nil || calls != 3 {
					t.Fatalf("retry: calls=%d, error=%v", calls, err)
				}
			})
		})
	}
}

func TestMSGraphClientReadSingleObject(t *testing.T) {
	client, err := NewMSGraphClient(&testCredential{}, cloud.Configuration{}, &policy.ClientOptions{Transport: &testTransport{}})
	if err != nil {
		t.Fatal(err)
	}
	got, err := client.Read(context.Background(), "groups/1", "v1.0", RequestOptions{})
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(got, map[string]interface{}{"id": "1"}) {
		t.Fatalf("object read = %#v", got)
	}
}

The file uses testCredential and testTransport already present in internal/clients/msgraph_client_test.go on the pinned checkout. On unchanged main, the four pagination cases report missing continuation headers and metadata; both Read cases also report requests = 3, want 2. Retry, cancellation and single-object-read controls are included.

Cause

  • Read calls List from the original URL after seeing a next link, discarding its already-fetched first page.
  • List's fetcher applies options.Headers only to the initial request.
  • Aggregation continues after appending value, bypassing the metadata-copying block.

Proposed correction and acceptance

Let the internal paging implementation accept the decoded first page from Read; apply caller headers to every page; and retain non-value, non-@odata.nextLink collection metadata. Preserve first-seen metadata on repeated keys and accept a delta link supplied only on the final page. Keep opaque continuation query strings verbatim rather than reapplying the initial query parameters.

Cover ordinary and empty first pages, request counts, response metadata, header propagation, cancellation, transient retry, and unchanged single-object reads. The proposed change preserves the existing Read/List interfaces and adds no shared cache.

Related: #20 introduced pagination. #101 proposes a much broader list cache; these fixes are independently useful and do not assume list/item equivalence or change state-removal semantics.

Dominant language
Go
Stars
65
Forks
27
Avg merge
5d 10h
Merged PRs (30d)
2

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from microsoft/terraform-provider-msgraph

All issues in microsoft/terraform-provider-msgraph

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.