dgraph-io/dgraph · error

Root of negative number

Error message

Root of negative number

What it means

Error returned by the DQL math evaluator (query/math.go) when computing a root (e.g. sqrt) of a negative number, which is undefined for real-valued results. Fix by ensuring the operand is non-negative or by using a function that supports negative inputs.

Source

Thrown at query/math.go:31

	"github.com/dgraph-io/dgraph/v25/types"
)

type mathTree struct {
	Fn    string
	Var   string
	Const types.Val // If its a const value node.
	Val   *types.ShardedMap
	Child []*mathTree
}

var (
	ErrorIntOverflow     = errors.New("Integer overflow")
	ErrorFloat32Overflow = errors.New("Float32 overflow")
	ErrorDivisionByZero  = errors.New("Division by zero")
	ErrorFractionalPower = errors.New("Fractional power of negative number")
	ErrorNegativeLog     = errors.New("Log of negative number")
	ErrorNegativeRoot    = errors.New("Root of negative number")
	ErrorVectorsNotMatch = errors.New("The length of vectors must match")
	ErrorArgsDisagree    = errors.New("Left and right arguments must match")
	ErrorShouldBeVector  = errors.New("Type should be []float, but is not. Cannot determine type.")
	ErrorBadVectorMult   = errors.New("Cannot multiply vector by vector")
)

// processBinary handles the binary operands like
// +, -, *, /, %, max, min, logbase, dot
func processBinary(mNode *mathTree) error {
	aggName := mNode.Fn

	mpl := mNode.Child[0].Val
	mpr := mNode.Child[1].Val
	cl := mNode.Child[0].Const
	cr := mNode.Child[1].Const

	f := func(k uint64, lshard, rshard, destMapi *map[uint64]types.Val) error {
		ag := aggregator{

View on GitHub (pinned to 759e242be6)

Solutions

  1. Guard with abs(): math(sqrt(abs(x))) if only magnitude matters
  2. Filter out negative values with @filter(ge(x, 0)) before computing sqrt
  3. Fix upstream data/normalization so the value cannot be negative

Example fix

// before
math(sqrt(delta))
// after
math(sqrt(abs(delta)))
Defensive patterns

Strategy: validation

Validate before calling

// Filter non-negative values before sqrt:
// { q(func: type(M)) @filter(ge(x, 0)) { r as math(sqrt(x)) } }
const query = `{ q(func: type(M)) @filter(ge(x, 0)) { r as math(sqrt(x)) } }`;

Try / catch

try {
  const res = await dgraph.newTxn().query(query);
} catch (e) {
  if (String(e).includes('Root of negative')) {
    // retry with math(sqrt(abs(x)))
  } else throw e;
}

Prevention

When it happens

Trigger: math(sqrt(a)) where a < 0; returned by applySqrt (TestProcessUnary covers it).

Common situations: Taking sqrt of variance/delta fields that can be negative; sign errors upstream in normalization; sqrt applied to temperature diffs or signed scores.

Related errors


AI-assisted analysis of dgraph-io/dgraph@759e242be6 (2026-09-01). Data as JSON: /api/errors/315669d2857575a1. Report an issue: GitHub.