Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jonmmease opened this issue Aug 11, 2022 · 6 comments · Fixed by #4488
Closed
Assignees
Labels
bug Something isn't working

Comments

@jonmmease
Copy link
Contributor

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

@jonmmease jonmmease added the bug Something isn't working label Aug 11, 2022
@andygrove
Copy link
Member

Thanks @jonmmease I will take a look

@andygrove andygrove self-assigned this Aug 12, 2022
@andygrove andygrove modified the milestone: 14.0.0 Oct 30, 2022
@wolffcm
Copy link
Contributor

wolffcm commented Nov 29, 2022

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")))

@alamb
Copy link
Contributor

alamb commented Dec 1, 2022

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

@alamb alamb changed the title Median aggregation using DataFrame panics Median aggregation using DataFrame panics: "AggregateState is not a scalar aggregate" Dec 2, 2022
@alamb
Copy link
Contributor

alamb commented Dec 2, 2022

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), ...)))))

@alamb
Copy link
Contributor

alamb commented Dec 2, 2022

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

@alamb
Copy link
Contributor

alamb commented Dec 2, 2022

Proposed fix in #4488

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants