gohugoio/hugo · error

the number of requested values (%v) must be a non-negative i

Error message

the number of requested values (%v) must be a non-negative integer <= %d

What it means

The second argument to `collections.D` is `n`, the number of random values requested. It must cast to an int in [0, 1,000,000] (`maxSeqSize`); negative values, values over the cap, or non-numeric inputs fail this check, preventing oversized allocations.

Source

Thrown at tpl/collections/collections.go:563

// Method D for sequential random sampling.
//
// If n > hi, it returns the full, sorted range [0, hi) of size hi.
//
// If n == 0 or hi == 0, it returns an empty slice.
//
// Reference:
//
//	J. S. Vitter, "An efficient algorithm for sequential random sampling," ACM Trans. Math. Softw., vol. 11, no. 1, pp. 37–57, 1985.
//	See also: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/
func (ns *Namespace) D(seed, n, hi any) ([]int, error) {
	seedInt, err := cast.ToInt64E(seed)
	if err != nil || seedInt < 0 {
		return nil, fmt.Errorf("the seed value (%v) must be a non-negative integer", seed)
	}

	nInt, err := cast.ToIntE(n)
	if err != nil || nInt < 0 || nInt > maxSeqSize {
		return nil, fmt.Errorf("the number of requested values (%v) must be a non-negative integer <= %d", n, maxSeqSize)
	}

	hiInt, err := cast.ToIntE(hi)
	if err != nil || hiInt < 0 || hiInt > maxSeqSize {
		return nil, fmt.Errorf("the maximum requested value (%v) must be a non-negative integer <= %d", hi, maxSeqSize)
	}

	if nInt == 0 || hiInt == 0 {
		return []int{}, nil
	}

	key := dKey{seed: uint64(seedInt), n: nInt, hi: hiInt}

	v, err := ns.dCache.GetOrCreate(key, func() ([]int, error) {
		if key.n > key.hi {
			result := make([]int, key.hi)
			for i := 0; i < key.hi; i++ {
				result[i] = i

View on GitHub ↗ (pinned to 8a468df065)

Solutions

  1. Pass `n` in range 0–1,000,000: `{{ collections.D 42 5 100 }}`.
  2. Clamp computed values: `{{ $n := math.Max 0 (sub (len $items) 1) }}`.
  3. Note n > hi is fine (returns the full range) — only negatives and > 1,000,000 fail.

Example fix

<!-- before -->
{{ collections.D 42 (sub (len $s) 10) 100 }}
<!-- after -->
{{ collections.D 42 (math.Max 0 (sub (len $s) 10)) 100 }}
Defensive patterns

Strategy: validation

Validate before calling

{{ $want := int .Params.count }}
{{ $max := len $items }}
{{ if or (lt $want 0) (gt $want $max) }}
  {{ $want = math.Min (math.Max 0 $want) $max }}
{{ end }}

Prevention

When it happens

Trigger: `{{ collections.D 42 -1 100 }}`, `{{ collections.D 42 2000000 100 }}`, or a non-numeric `n` such as a string param.

Common situations: Computing `n` from `sub` expressions that go negative when a collection is empty; using a large byte count or ID as the sample size by mistake.

Related errors


AI-assisted analysis of gohugoio/hugo@8a468df065 (2026-07-31). Data as JSON: /data/errors/bc319088e6d99852.json. Report an issue: GitHub ↗.