Skip to content

Median aggregation using DataFrame panics: "AggregateState is not a scalar aggregate" #3105

Closed

Description

@jonmmease

Describe the bug
I am trying to use the new exact median aggregation function introduced by @andygrove in #3009, but when I try it using the DataFrame API the operation panics. Apologies that I didn't get around to testing this while the PR was open!

To Reproduce
Here is a test case that can be run inside the src/core/tests/dataframe.rs file:

#[tokio::test]
async fn exact_median() -> Result<()> {
    let schema = Schema::new(vec![
        Field::new("a", DataType::Int32, true),
        Field::new("b", DataType::Float64, true),
    ]);

    let batch = RecordBatch::try_new(
        Arc::new(schema.clone()),
        vec![
            Arc::new(Int32Array::from_slice(&[1, 1, 1, 1])),
            Arc::new(Float64Array::from_slice(&[10.0, 0.0, 20.0, 100.0])),
        ],
    )
    .unwrap();

    let ctx = SessionContext::new();
    let provider = MemTable::try_new(Arc::new(schema), vec![vec![batch]]).unwrap();
    ctx.register_table("t", Arc::new(provider)).unwrap();

    let df = ctx
        .table("t")
        .unwrap()
        .aggregate(
            vec![col("a")],
            vec![Expr::AggregateFunction {
                fun: AggregateFunction::Median,
                args: vec![col("b")],
                distinct: false,
            }
            .alias("agg")],
        )
        .unwrap();

    let results = df.collect().await.unwrap();

    #[rustfmt::skip]
        let expected = vec![
        "+---+------+",
        "| a | agg  |",
        "+---+------+",
        "| 1 | 15.0 |",
        "+---+------+",
    ];
    assert_batches_eq!(expected, &results);

    Ok(())
}
thread 'exact_median' panicked at 'unexpected accumulator state in hash aggregate: Internal("AggregateState is not a scalar aggregate")', datafusion/core/src/physical_plan/aggregates/hash.rs:434:34
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'exact_median' panicked at 'called `Result::unwrap()` on an `Err` value: ArrowError(ExternalError(Execution("Join Error: task 29 panicked")))', datafusion/core/tests/dataframe.rs:459:38

Expected behavior
I expect the test above to pass

Activity

  1. andygrove commented on Aug 12, 2022

    @andygrove
    Member

    Thanks @jonmmease I will take a look

  2. self-assigned this
    on Aug 12, 2022
  3. modified the milestone: 14.0.0 on Oct 30, 2022
  4. wolffcm commented on Nov 29, 2022

    @wolffcm
    Contributor

    I can also reproduce this with datafusion-cli, which I would guess is the same issue?

    ❯ create table cpu (host string, usage float) as select * from (values ('host0', 90.1), ('host1', 90.2));
    0 rows in set. Query took 0.011 seconds.
    ❯ select host, median(usage) from cpu group by host;
    thread 'tokio-runtime-worker' panicked at 'unexpected accumulator state in hash aggregate: Internal("AggregateState is not a scalar aggregate")', /Users/cwolff/workspace/github.com/apache/arrow-datafusion/datafusion/core/src/physical_plan/aggregates/hash.rs:517:34
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    ArrowError(ExternalError(Execution("Join Error: task 17 panicked")))
  5. alamb commented on Dec 1, 2022

    @alamb
    Contributor

    We are hitting this with IOx so I plan to fix it

  6. changed the title [-]Median aggregation using DataFrame panics[/-] [+]Median aggregation using DataFrame panics: "AggregateState is not a scalar aggregate"[/+] on Dec 2, 2022
  7. alamb commented on Dec 2, 2022

    @alamb
    Contributor

    Strangely, if I run the function directly on values without first making a table it works fine.

    DataFusion CLI v14.0.0
    ❯ select median(column2) from (values ('host0', 90.1), ('host1', 90.2));
    +-----------------+
    | MEDIAN(column2) |
    +-----------------+
    | 90.15           |
    +-----------------+
    1 row in set. Query took 0.053 seconds.
    ❯ create table cpu (host string, usage float) as select * from (values ('host0', 90.1), ('host1', 90.2));
    0 rows in set. Query took 0.005 seconds.
    ❯ select host, median(usage) from cpu group by host;
    thread 'tokio-runtime-worker' panicked at 'unexpected accumulator state in hash aggregate: Internal("AggregateState is not a scalar aggregate")', /Users/alamb/Software/arrow-datafusion2/datafusion/core/src/physical_plan/aggregates/hash.rs:517:34
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    ArrowError(ExternalError(Context("Join Error", External(JoinError::Panic(Id(51), ...)))))
    
  8. alamb commented on Dec 2, 2022

    @alamb
    Contributor

    I think this code will basically happen any time median is used in a query that has more than one partition

  9. alamb commented on Dec 2, 2022

    @alamb
    Contributor

    Proposed fix in #4488

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions