dennis zhuang 4969bca60e feat(promql): add native histogram arithmetic and sum/avg aggregation (#9686)
I hereby agree to the terms of the [GreptimeDB
CLA](https://github.com/GreptimeTeam/.github/blob/main/CLA.md).

## Refer to a related PR or issue link (optional)

Targets `narthex`. Stacked on #9685 for the native histogram bucket
bounds and the golden fixture helpers; review only `feat(promql): add
native histogram arithmetic and sum/avg aggregation`.

## What's changed and what's your intention?

### Problem

Native histogram range functions, aggregations and binary operators all
need histogram arithmetic. The ordinary
`common_query::native_histogram::NativeHistogram` adds without Kahan
compensation and compacts with its own algorithm, so its results differ
from Prometheus in value bits and bucket layout. The native path has no
`sum`/`avg` over native histograms either.

### Change

- `histogram_eval::float_histogram::FloatHistogram` ports Prometheus
`FloatHistogram` (`model/histogram/float_histogram.go`): `Add`,
`KahanAdd`, `Sub`, `Mul`, `Div`, `Compact(0)`, `CopyToSchema`,
`DetectReset`, `Equals` and `HasOverflow`. The port covers:
- zero bucket reconciliation (`zeroCountForLargerThreshold`,
`trimBucketsInZeroBucket`), including the compensation Go keeps across
abandoned passes;
  - resolution reduction, plain and Kahan;
- the intersection of mismatched custom bounds and the matching reset
detection;
  - counter reset hint merging.

Each side is kept as `(bucket index, count)` sorted by index. The bucket
set and the order of additions match Go's span splicing. A histogram
read from a view keeps its spans until its buckets change, because
`Equals` compares span layouts; afterwards consecutive indices form one
span, the layout `Compact` produces.
- `histogram_eval::aggregate_histograms` follows the histogram paths of
Prometheus `aggregation` for `sum` and `avg` within one group.
Histograms are added in group order with `KahanAdd`. `avg` switches to
an incremental mean once the plain sum overflows. A point yields nothing
when the group also has a float there or mixes exponential and custom
buckets; any other addition error fails the aggregation. Grouping stays
with AGG-BASIC.
- `native::bound` takes exponential bounds from Go's `exponentialBounds`
table with `Ldexp`, as `getBoundExponential` does. Widened zero
thresholds are set to these bounds and compared exactly in `DetectReset`
and when adding buckets, and some table entries are one ulp off `2^(idx
/ 2^schema)`.
- `sub`, `copy_to_schema`, `detect_reset` and `equals` have no caller on
this branch yet. They are for the native histogram range functions and
binary operators, which build on other branches, so the module allows
dead code outside tests.

Review focus:

- `add_buckets`: `other` buckets whose upper bound is within the zero
threshold are skipped only while they lead; subtraction inserts negated
counts, including `-0`.
- `zero_count_for_larger_threshold` and `reconcile_zero_buckets`: the
widened threshold, the Kahan compensation of the zero count, and the
compaction after trimming, which drops only buckets whose count and
compensation are both zero.
- `kahan_add`: which side is reduced to the lower schema, and the
alignment of the compensation buckets with the receiving ones.
- `detect_reset`: both sides start from the current zero threshold;
merged buckets of a higher-resolution predecessor sum from zero.
- `aggregate_point`: the overflow switch to the incremental mean reuses
the compensation from before the failed addition.
- The aggregation writes its histograms from the first point with a
result instead of holding one slot per point of the whole input span.

### Non-goals

- Native histogram range functions (EVAL-HIST) and binary operators
(MATCH-HIST).
- Grouping and float aggregation (AGG-BASIC).
- `Equals` after an uncompacted `Add`/`Sub` compares the compacted
layout. PromQL compacts every such result before using it.

### Constraints

- Sums of floats and histograms depend on the order of the series.
Prometheus adds them in the order the head index returns them (creation
order). The kernel adds them in the order of `group`, which the caller
decides.
- Prometheus panics in `addBuckets` on histograms with zero-length
spans; the port does not. The aggregation fixtures compact their inputs
for that reason.

### Verification

- `cargo nextest run -p promql`: 319 passed.
- `cargo clippy -p promql --all-targets --all-features -- -D warnings`,
`cargo fmt --check`, `hawkeye check`: clean.
- `histogram_arithmetic_matches_prometheus`: 723 operations from Go's
`FloatHistogram` methods on random histograms
(`histogram_eval/arithmetic_cases.txt`). Inputs include:
- schemas -4 to 8 and custom buckets with matching and mismatched
bounds;
- zero thresholds from 0 to 0.5, mixed exponential and custom operands,
and all reset hints;
- reset candidates with missing buckets, lower zero counts, lower
resolution, wider zero buckets and bounds that underflow to zero;
  - three fixed cases random inputs do not reach.

Results compare every field, the bucket indices and count bits of both
the sum and the Kahan compensation, and the collision and reconciliation
flags.
- `native_histograms_match_prometheus` now also covers 240 `sum`/`avg`
cases with and without `by (job)`, from the Prometheus engine with
inputs in creation order, plus a fixed `avg` case whose overflow switch
carries a nonzero compensation. Aggregated histograms compare bit for
bit.
- Mutation check, each of these fails a test:
  - Arithmetic, 21 faults:
- no zero bucket reconciliation in `Add`, plain addition inside
`KahanAdd`, a target index without the `- 1`;
    - no zero-threshold skip, no hint collision;
    - `>` instead of `>=` when mapping custom bounds;
- resetting the zero count compensation per pass, no compaction after
trimming, a compaction that ignores the compensation;
- reset detection that ignores the zero count, missing buckets or schema
merging, or skips at a zero threshold;
    - `Equals` by value or without the layout;
- division by zero keeping buckets, `CopyToSchema` keeping the hint, a
negative factor not setting the gauge hint;
- restarting the custom-bound roll-up, dropping the custom-bucket
compensation, plain resolution reduction in `KahanAdd`.
- Aggregation, 8 faults: plain `Add` for `sum`, dropping the final
compensation, never switching to the incremental mean, discarding the
compensation at the switch, output despite floats or incompatible
schemas, no final compaction, adding the compensation before dividing.

## PR Checklist
Please convert it to a draft if some of the following conditions are not
met.

- [x] I have written the necessary rustdoc comments.
- [x] I have added the necessary unit tests and integration tests.
- [ ] This PR requires documentation updates.
- [x] API changes are backward compatible.
- [x] Schema or data changes are backward compatible.
- [ ] This PR needs to be backported to release branches, and I have
added the `backport-<target>` labels (e.g. `backport-v1.3` targets
`release/v1.3`).
2026-10-18 01:04:56 +08:00
2023-08-10 08:08:37 +00:00
2023-06-25 11:05:46 +08:00
2023-11-09 10:38:12 +00:00

GreptimeDB Logo

Metrics, logs, and traces.
One engine, on your infrastructure.

A columnar database for metrics, logs, and traces on object storage. Apache-2.0 licensed core.

User Guide  ·  API Docs  ·  Roadmap 2026  ·  Slack

Stable Canary Nightly Docker Pulls License

stable for production  ·  canary includes pre-releases  ·  nightly is a weekly snapshot of main

Introduction

GreptimeDB is an open-source observability database. Metrics, logs, and traces run on one columnar engine over object storage and share one table model: tags, timestamp, and fields. When signals carry common identifiers such as service, host, or trace ID, you can correlate them in SQL without moving data between databases.

Ingest through OpenTelemetry, Prometheus Remote Write, Loki Push, or Elasticsearch Bulk. Use SQL across observability data and PromQL for metrics. Migrate ingestion one signal at a time without rebuilding your collectors.

One Query Across Signals

OpenTelemetry ingestion writes spans to opentelemetry_traces and log records to opentelemetry_logs. Both tables carry trace_id, so correlating them is a join:

-- The slowest failed spans in the last hour,
-- with the log lines emitted inside those same traces.
SELECT
    t.service_name,
    t.span_name,
    t.duration_nano / 1000000 AS duration_ms,
    l.timestamp AS log_time,
    l.severity_text,
    l.body
FROM opentelemetry_traces t
JOIN opentelemetry_logs l ON l.trace_id = t.trace_id
WHERE t.timestamp > now() - INTERVAL '1' HOUR
  AND t.span_status_code = 'STATUS_CODE_ERROR'
ORDER BY t.duration_nano DESC
LIMIT 20;

Metrics join the same way, on any tag the tables share, such as service, host, or pod.

Why You Might Use It

  • You run Prometheus plus Loki or Elasticsearch and want one backend instead of three
  • You have outgrown Prometheus on cardinality or retention and don't want the Thanos/Mimir operational surface
  • You are hitting Loki's query performance limits as log volume grows
  • You need long retention on object storage without a separate analytics stack
  • You want to query telemetry with SQL, not only a domain query language
  • You are storing GenAI or agent telemetry (OTel GenAI conventions) alongside infrastructure signals

Learn more in Why GreptimeDB.

What's Supported

Ingest OpenTelemetry (OTLP), Prometheus Remote Write, Loki Push, Elasticsearch Bulk, InfluxDB line protocol, gRPC
Query SQL, PromQL, Jaeger-compatible trace queries, MySQL and PostgreSQL wire protocols
Storage S3, GCS, Azure Blob and S3-compatible endpoints as primary storage, with memory and local-disk caches
Built in Retention policies, downsampling, continuous aggregation, explicit table partitioning, and inverted / skipping / fulltext indexes

Compute and storage are disaggregated: object storage holds the data, while memory and local-disk caches keep recent and frequently queried data close to compute.

GreptimeDB Overview

Benchmarks

Compatibility and Migration

Compatibility is per protocol, and query-side coverage is narrower than ingestion.

Compatible Not compatible
Prometheus Remote Write ingestion; PromQL queries Gaps are listed in PromQL compatibility
Loki Push ingestion; dual-write through Grafana Alloy makes the cutover gradual LogQL and the rest of the Loki query API
Elasticsearch _bulk ingestion in the open-source core; QueryDSL partially, in Enterprise Most other Elasticsearch APIs

Limitations and Edition Boundary

Cluster deployment, object storage, the Flow engine, and every ingestion protocol listed above are in the Apache-2.0 build. Repartitioning, region migration, and index creation are manual operations there.

Read replicas, workload isolation, and automated repartitioning are GreptimeDB Enterprise features, along with enterprise security and governance. The Enterprise overview has the current list, and pricing has the edition comparison.

Architecture

GreptimeDB can run in two modes:

  • Standalone — single binary for development and small deployments.
  • Distributed — four components, each independently scalable:
    • Frontend — protocol entry (OTel, Prometheus, MySQL/PostgreSQL, gRPC, ingestion APIs for Elasticsearch/InfluxDB/Loki) and the distributed query engine. Stateless, scales horizontally.
    • Datanode — region engine with WAL, memtable, SST, cache, compaction, and indexes. Persists data to object storage. Elastic.
    • Metasrv — metadata, routing, repartitioning, and security. Backed by a pluggable KV layer (etcd or RDS).
    • Flownode (optional) — continuous flow computation (streaming and materialized views).

For deeper coverage, see the architecture doc or DeepWiki.

GreptimeDB System Overview

Try GreptimeDB

For AI agents — paste this prompt into your agent:

Read https://docs.greptime.com/SKILL.md and follow the instructions
to deploy, configure, ingest, and query GreptimeDB.
docker run -p 127.0.0.1:4000-4003:4000-4003 \
  -v "$(pwd)/greptimedb_data:/greptimedb_data" \
  --name greptime --rm \
  greptime/greptimedb:latest standalone start \
  --http-addr 0.0.0.0:4000 \
  --grpc-bind-addr 0.0.0.0:4001 \
  --mysql-addr 0.0.0.0:4002 \
  --postgres-addr 0.0.0.0:4003

Dashboard: http://localhost:4000/dashboard

Read more in the full Install Guide.

Troubleshooting:

  • Cannot connect to the database? Ensure that ports 4000, 4001, 4002, and 4003 are not blocked by a firewall or used by other services.
  • Failed to start? Check the container logs with docker logs greptime for further details.

Getting Started

Build From Source

Prerequisites:

  • Rust toolchain — stable, pinned by rust-toolchain.toml
  • Protobuf compiler (>= 3.15)
  • C/C++ building essentials: gcc / g++ / autoconf and the glibc dev package (libc6-dev on Ubuntu, glibc-devel on Fedora)
  • Python toolchain (optional, only for some test scripts)

Build and run:

make                          # build greptime binary
cargo run -- standalone start # start in standalone mode

Common dev commands:

make fmt            # format Rust code
make clippy         # lint (fails on warnings)
make test           # unit + integration tests (uses cargo-nextest)
make sqlness-test   # SQL regression tests

See the Contribution Guidelines for the full developer workflow.

Tools & Extensions

Project Status

GreptimeDB is generally available, with stable APIs and regular releases. It runs in production at scale — OceanBase Cloud operates 80+ GreptimeDB clusters managing 300 TB of logs, cutting log storage cost by 60%+ after migrating from Grafana Loki. See more in case studies.

Release lines and support windows are in the version reference. For where the project is going, read the v1.0 highlights and the 2026 roadmap.

Community

We invite you to engage and contribute!

If GreptimeDB is useful to you, please star the repo.

Known Users

License

GreptimeDB is an open-core project. Its core is licensed under the Apache License 2.0.

A small set of peripheral, enterprise-only features are gated behind the enterprise Cargo feature (not built by default) and are governed by the separate GreptimeDB Enterprise License. Source files under that license carry an explicit Enterprise License header.

Commercial Support

Scaling observability on your infrastructure? GreptimeDB Enterprise adds the operational, security, and support layer for production deployments. Contact us for details.

Contributing

Integration CI Codecov

Acknowledgement

Special thanks to all contributors! See AUTHOR.md.


All trademarks, logos, and brand names referenced in this README and in the Overview diagram are the property of their respective owners. Their use is for identification purposes only and does not imply endorsement or affiliation.

S
Description
Open-source, cloud-native, unified observability database for metrics, logs and traces, supporting SQL/PromQL/Streaming.
Readme Apache-2.0
1.9 GiB
Languages
Rust 97.4%
Python 1.9%
Shell 0.4%
JavaScript 0.2%