apache/flink · error · IllegalArgumentException

The key index must not be negative.

Error message

The key index must not be negative.

What it means

Thrown by Ordering.appendOrdering when the supplied field index is negative. Field indexes reference positions in a tuple/record schema and must be non-negative. A negative index is always a programming error.

Source

Thrown at flink-core/src/main/java/org/apache/flink/api/common/operators/Ordering.java:67

     * @param order
     */
    public Ordering(int index, Class<? extends Comparable<?>> type, Order order) {
        appendOrdering(index, type, order);
    }

    /**
     * Extends this ordering by appending an additional order requirement. If the index has been
     * previously appended then the unmodified Ordering is returned.
     *
     * @param index Field index of the appended order requirement.
     * @param type Type of the appended order requirement.
     * @param order Order of the appended order requirement.
     * @return This ordering with an additional appended order requirement.
     */
    public Ordering appendOrdering(
            Integer index, Class<? extends Comparable<?>> type, Order order) {
        if (index < 0) {
            throw new IllegalArgumentException("The key index must not be negative.");
        }
        if (order == null) {
            throw new NullPointerException();
        }
        if (order == Order.NONE) {
            throw new IllegalArgumentException(
                    "An ordering must not be created with a NONE order.");
        }

        if (!this.indexes.contains(index)) {
            this.indexes = this.indexes.addField(index);
            this.types.add(type);
            this.orders.add(order);
        }

        return this;
    }

View on GitHub (pinned to 2f3c205e92)

Solutions

  1. Validate that index >= 0 before calling appendOrdering.
  2. Fix the upstream calculation that produced the negative value.
  3. Use guard clauses or Preconditions.checkArgument(index >= 0, ...).

Example fix

// before
ordering.appendOrdering(pos - 1, Integer.class, Order.ASCENDING);

// after
int safePos = Math.max(0, pos - 1);
ordering.appendOrdering(safePos, Integer.class, Order.ASCENDING);
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0) {
    throw new IllegalArgumentException("Field index must be >= 0, got " + index);
}

Prevention

When it happens

Trigger: Calling new Ordering(-1, type, Order.ASCENDING) or ordering.appendOrdering(-1, ...). Computing an index from subtraction that underflows to negative.

Common situations: Arithmetic that produces a negative index (e.g. pos - 1 when pos is 0). Passing unchecked user-supplied indices into ordering construction.

Related errors


AI-assisted analysis of apache/flink@2f3c205e92 (2026-08-14). Data as JSON: /api/errors/76818ab410ca2aa6. Report an issue: GitHub.