hashicorp/terraform · error

expected to receive state in %d bytes, actually received %d

Error message

expected to receive state in %d bytes, actually received %d bytes

What it means

Returned by WriteStateBytes (internal/grpcwrap/provider6.go:1102) after the receive loop completes when the total bytes actually written (totalReceivedBytes) do not match the TotalLength the client declared in the first chunk (expectedTotalLength). The stream ended cleanly but the byte accounting is inconsistent, so the assembled buffer is rejected rather than persisted.

Source

Thrown at internal/grpcwrap/provider6.go:1102

				stateId = chunk.Meta.StateId
			} else {
				panic("expected Meta to be set on first chunk sent to WriteStateBytes")
			}
		}

		n, err := state.Write(chunk.Bytes)
		if err != nil {
			return fmt.Errorf("error writing state: %w", err)
		}
		totalReceivedBytes += n
	}

	if grpcErr != nil {
		return grpcErr
	}

	if int64(totalReceivedBytes) != expectedTotalLength {
		return fmt.Errorf("expected to receive state in %d bytes, actually received %d bytes", expectedTotalLength, totalReceivedBytes)
	}

	if totalReceivedBytes == 0 {
		// Even an empty state file has content; no bytes is not valid
		return errors.New("No state data received from Terraform: No state data was received from Terraform. This is a bug and should be reported.")
	}

	resp := p.provider.WriteStateBytes(providers.WriteStateBytesRequest{
		StateId:  stateId,
		TypeName: typeName,
		Bytes:    state.Bytes(),
	})

	err := srv.SendAndClose(&proto6.WriteStateBytes_Response{
		Diagnostics: convert.AppendProtoDiag([]*proto6.Diagnostic{}, resp.Diagnostics),
	})

	return err

View on GitHub (pinned to c9def3e214)

Solutions

  1. Check client/core version for known chunking bugs and upgrade if applicable.
  2. Inspect for any proxy/gateway between core and the provider that could mutate or drop gRPC messages.
  3. Capture a gRPC trace to compare bytes sent vs TotalLength declared.
  4. If implementing a custom state store client, ensure TotalLength equals the sum of all chunk.Bytes lengths exactly.

Example fix

// before (custom client)
firstChunk.TotalLength = 1024
// but only 900 bytes of chunk.Bytes sent across all messages
// -> expected to receive state in 1024 bytes, actually received 900 bytes

// after
total := int64(0)
for _, c := range chunks { total += int64(len(c.Bytes)) }
chunks[0].TotalLength = total
Defensive patterns

Strategy: validation

Validate before calling

// Client side: compute TotalLength exactly from the sum of chunk sizes:
func buildChunks(full []byte, chunkSize int) []*tfplugin6.WriteStateBytes_Request {
    total := int64(len(full))
    var chunks []*tfplugin6.WriteStateBytes_Request
    for i := 0; i < len(full); i += chunkSize {
        end := i + chunkSize
        if end > len(full) { end = len(full) }
        chunks = append(chunks, &tfplugin6.WriteStateBytes_Request{
            Bytes:       full[i:end],
            TotalLength: total,
        })
    }
    return chunks
}

Type guard

func chunksConsistent(chunks []*tfplugin6.WriteStateBytes_Request) bool {
    if len(chunks) == 0 { return true }
    total := int64(0)
    for _, c := range chunks { total += int64(len(c.Bytes)) }
    return total == chunks[0].TotalLength
}

Try / catch

if err := streamUpload(chunks); err != nil {
    if strings.Contains(err.Error(), "expected to receive state in") {
        // rebuild chunks with correct TotalLength and retry
        chunks = buildChunks(full, chunkSize)
    }
}

Prevention

When it happens

Trigger: A client that sets TotalLength=N on the first chunk but sends a different number of bytes total (chunk loss, duplicated/missed sends, client bug), or a transport that silently truncated the stream before EOF.

Common situations: Client-side chunking bug in Terraform core, a middleware/proxy that alters or drops chunks, retry logic that resends partial chunks, or a buggy state store wrapper miscalculating TotalLength.

Related errors


AI-assisted analysis of hashicorp/terraform@c9def3e214 (2026-08-07). Data as JSON: /api/errors/45e2b2386cfa0799. Report an issue: GitHub.