{"record":{"id":"ca339da3e0af7cf7","repo":"dgraph-io/dgraph","slug":"invalid-variable-aggregation-check-the-levels","errorCode":null,"errorMessage":"Invalid variable aggregation. Check the levels.","messagePattern":"Invalid variable aggregation\\. Check the levels\\.","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"query/query.go","lineNumber":1099,"sourceCode":"\tvar relSG *SubGraph\n\tfor _, ch := range parent.Children {\n\t\tif sg == ch {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range ch.Params.FacetVar {\n\t\t\tif v == needsVar {\n\t\t\t\trelSG = ch\n\t\t\t}\n\t\t}\n\t\tfor _, cch := range ch.Children {\n\t\t\t// Find the sibling node whose child has the required variable.\n\t\t\tif cch.Params.Var == needsVar {\n\t\t\t\trelSG = ch\n\t\t\t}\n\t\t}\n\t}\n\tif relSG == nil {\n\t\treturn nil, errors.Errorf(\"Invalid variable aggregation. Check the levels.\")\n\t}\n\n\tvals := doneVars[needsVar].Vals\n\tmp = types.NewShardedMap()\n\t// Go over the sibling node and aggregate.\n\tfor i, list := range relSG.uidMatrix {\n\t\tag := aggregator{\n\t\t\tname: sg.SrcFunc.Name,\n\t\t}\n\t\tfor _, uid := range list.Uids {\n\t\t\tif val, ok := vals.Get(uid); ok {\n\t\t\t\tif err := ag.Apply(val); err != nil {\n\t\t\t\t\treturn nil, errors.Errorf(\"Error in applying aggregation %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tv, err := ag.Value()\n\t\tif err != nil && err != ErrEmptyVal {","sourceCodeStart":1081,"sourceCodeEnd":1117,"githubUrl":"https://github.com/dgraph-io/dgraph/blob/759e242be62c91f8d084da06ad0c8d21256d9c07/query/query.go#L1081-L1117","documentation":"During variable aggregation (math/aggregation over value variables), Dgraph must find the sibling subgraph that carries the variable needed for aggregation. If no sibling subgraph matching the needed variable exists, the aggregation level is invalid and this error is thrown. It indicates the variable referenced in an aggregation was not produced at a compatible level of the query graph.","triggerScenarios":"Using sum/min/max/avg over a variable whose name does not match any sibling node's Var (e.g. 'sum(val(x))' where x was never emitted as a variable at the right level); mismatched variable scoping inside nested filters or math blocks.","commonSituations":"Typo in variable name between emitter (as x) and consumer (val(x)); aggregating a variable defined only in a nested branch; copying a query fragment without the sibling node that defines the variable.","solutions":["Verify the variable is defined with 'as var' or 'as val' at the same level the aggregation consumes it","Check for typos in the variable name","Restructure the query so the aggregation's sibling node emits the needed variable","Run the query without aggregation first to confirm the variable is populated"],"exampleFix":"// before\n{\n  me(func: eq(name, \"a\")) {\n    friend { u as count(uid) }\n    total as sum(val(friend))  # no such val(friend) at this level\n  }\n}\n// after\n{\n  me(func: eq(name, \"a\")) {\n    friend as friend_of { c as count(uid) }\n    total as sum(val(c))\n  }\n}","handlingStrategy":"validation","validationCode":"// Ensure every val(x) consumer has a matching 'as x' emitter in the query text\nfor _, agg := range []string{\"val(a)\", \"val(t)\"} {\n    name := strings.TrimSuffix(strings.TrimPrefix(agg, \"val(\"), \")\")\n    if !strings.Contains(query, \"as \"+name) && !strings.Contains(query, \"var(\"+name+\" as\") {\n        return fmt.Errorf(\"variable %s used in aggregation but never defined\", name)\n    }\n}","typeGuard":null,"tryCatchPattern":"if err != nil && strings.Contains(err.Error(), \"Invalid variable aggregation\") {\n    return fmt.Errorf(\"query uses a variable that is not defined at the right level: %w\", err)\n}","preventionTips":["Define variables with 'as' in the same block/level where they are aggregated","Lint query strings for val(x) usage without a matching emitter","Test complex aggregation queries in Ratel before deploying","Avoid copying query fragments without their variable-defining siblings"],"tags":["dgraph","query","variables","aggregation"],"backgroundTag":"dgraph-variable-scope-mismatch","analyzedSha":"759e242be62c91f8d084da06ad0c8d21256d9c07","analyzedAt":"2026-09-01T14:42:12.034Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}