{"record":{"id":"99de922e37331615","repo":"gohugoio/hugo","slug":"sequence-length-must-be-non-negative","errorCode":null,"errorMessage":"sequence length must be non-negative","messagePattern":"sequence length must be non-negative","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tpl/collections/collections.go","lineNumber":208,"sourceCode":"\t\tdict[key] = values[i+1]\n\t}\n\n\treturn root, nil\n}\n\n// First returns the first limit items in list l.\nfunc (ns *Namespace) First(limit any, l any) (any, error) {\n\tif limit == nil || l == nil {\n\t\treturn nil, errors.New(\"both limit and seq must be provided\")\n\t}\n\n\tlimitv, err := cast.ToIntE(limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif limitv < 0 {\n\t\treturn nil, errors.New(\"sequence length must be non-negative\")\n\t}\n\n\tlv := reflect.ValueOf(l)\n\tlv, isNil := hreflect.Indirect(lv)\n\tif isNil {\n\t\treturn nil, errors.New(\"can't iterate over a nil value\")\n\t}\n\n\tswitch lv.Kind() {\n\tcase reflect.Array, reflect.Slice, reflect.String:\n\t\t// okay\n\tdefault:\n\t\treturn nil, errors.New(\"can't iterate over \" + reflect.ValueOf(l).Type().String())\n\t}\n\n\tif limitv > lv.Len() {\n\t\tlimitv = lv.Len()\n\t}","sourceCodeStart":190,"sourceCodeEnd":226,"githubUrl":"https://github.com/gohugoio/hugo/blob/52c9bd7908b4d02d4d0ff8f82a888834d6ee10d2/tpl/collections/collections.go#L190-L226","documentation":"First (collections.go:207-209) rejects a negative limit because you cannot take a negative count of items. The guard runs after the cast to int succeeds.","triggerScenarios":"{{ first -1 .Pages }} or a computed negative count (e.g. {{ first (sub $a $b) .Pages }} with b > a).","commonSituations":"Subtraction going below zero when deriving a count; user-supplied param not clamped; off-by-one in pagination.","solutions":["Clamp to zero: {{ first (math.Max 0 $n) .Pages }}","Guard: {{ if ge $n 0 }}{{ first $n .Pages }}{{ end }}"],"exampleFix":"// before\n{{ first (sub $a $b) .Pages }}\n// after\n{{ first (math.Max 0 (sub $a $b)) .Pages }}","handlingStrategy":"validation","validationCode":"{{ $n := math.Max 0 $n }}\n{{ first $n .Pages }}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Clamp computed counts to >= 0 with math.Max 0","Validate user-supplied counts","Guard subtraction results that can go negative"],"tags":["hugo","go-template","collections","validation","bounds-check"],"backgroundTag":null,"analyzedSha":"52c9bd7908b4d02d4d0ff8f82a888834d6ee10d2","analyzedAt":"2026-08-09T21:49:36.660Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}