Skip to content

[Prism] Aggregate bounded trie and histogram metrics in job metrics - #41708

Open
prodriguezdefino wants to merge 1 commit into
apache:masterfrom
prodriguezdefino:prism/metrics-trie-histogram
Open

prodriguezdefino wants to merge 1 commit into
apache:masterfrom
prodriguezdefino:prism/metrics-trie-histogram

Conversation

@prodriguezdefino

Copy link
Copy Markdown
Contributor

Problem:
In buildUrnToOpsMap (sdks/go/pkg/beam/runners/prism/internal/jobservices/metrics.go), typ2accumFac registers accumulators for counters, distributions, gauges, top-N, bottom-N, string sets, and progress metrics, but omits MonitoringInfoTypeUrns_BOUNDED_TRIE_TYPE (beam:metrics:bounded_trie:v1) and MonitoringInfoTypeUrns_HISTOGRAM (beam:metrics:histogram_int64:v1).

When AddShortIDs resolves a metric with either type URN, metricsStore logs an unknown short-ID debug message, creates no accumulator, drops every update in contributeMetrics, and omits the metric from GetJobMetrics. Python's PrismRunnerTest disables bounded trie checks with check_bounded_trie=False, and Java's Prism build excludes UsesBoundedTrieMetrics.

Fix:
Add metricAccumulator implementations for BoundedTrie (merging singleton and trie nodes with bound trimming) and HistogramValue (summing bucket counts and total count across matching BucketOptions), and register both type URNs in typ2accumFac. Enable bounded trie metric checks in prism_runner_test.py and runners/prism/java/build.gradle, and add unit tests in metrics_test.go.

Reproduction (Python SDK on PrismRunner):
Build Prism (cd sdks && go build -o /tmp/prism ./go/cmd/prism) and run python repro.py --prism_location=/tmp/prism. Python's HistogramCell.to_runner_api_monitoring_info is a stub returning None, so this script wires it to monitoring_infos.user_histogram to report USER_HISTOGRAM payloads from the LOOPBACK worker.

import sys

import apache_beam as beam
from apache_beam.metrics import cells
from apache_beam.metrics import monitoring_infos
from apache_beam.metrics.metric import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.portability.api import beam_job_api_pb2
from apache_beam.portability.api import metrics_pb2
from apache_beam.utils.histogram import LinearBucket

cells.HistogramCell.to_runner_api_monitoring_info = (
    lambda self, name, transform_id: monitoring_infos.user_histogram(
        name.namespace, name.name, self.data, ptransform=transform_id))


class RecordMetricsDoFn(beam.DoFn):
    def __init__(self):
        self.trie = Metrics.bounded_trie("ns", "paths")
        self.hist = Metrics.histogram("ns", "latency", LinearBucket(0, 10, 5))

    def process(self, element):
        seg, val = element
        self.trie.add(("root", seg))
        self.hist.update(val)
        yield element


if __name__ == "__main__":
    options = PipelineOptions(
        ["--runner=PrismRunner", "--environment_type=LOOPBACK"] + sys.argv[1:]
    )
    p = beam.Pipeline(options=options)
    _ = (
        p
        | beam.Create([("a", 5), ("b", 15), ("b", 25)])
        | beam.ParDo(RecordMetricsDoFn())
    )
    res = p.run()
    res.wait_until_finish()

    tries = res.metrics().query(
        MetricsFilter().with_namespace("ns").with_name("paths")
    )["bounded_tries"]
    resp = res._job_service.GetJobMetrics(
        beam_job_api_pb2.GetJobMetricsRequest(job_id=res._job_id)
    )
    hists = [
        metrics_pb2.HistogramValue.FromString(mi.payload)
        for mi in resp.metrics.committed
        if monitoring_infos.is_histogram(mi)
        and mi.labels.get("NAMESPACE") == "ns"
        and mi.labels.get("NAME") == "latency"
    ]
    trie_paths = [set(t.committed.flattened()) for t in tries]
    hist_counts = [(h.count, list(h.bucket_counts)) for h in hists]
    print("bounded_tries:", trie_paths)
    print("histograms:", hist_counts)
    assert trie_paths == [{("root", "a", False), ("root", "b", False)}]
    assert hist_counts == [(3, [1, 1, 1, 0, 0])]

Before the fix (master): bounded_tries: [] and histograms: [], and the first assertion fails.
After the fix: bounded_tries: [{('root', 'a', False), ('root', 'b', False)}] and histograms: [(3, [1, 1, 1, 0, 0])].

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 Review Summary

This PR adds support for aggregating BoundedTrie (beam:metrics:bounded_trie:v1) and HistogramValue (beam:metrics:histogram_int64:v1) metrics in the Prism runner's job service, and enables the corresponding BoundedTrie validation tests in the Python and Java test suites. The implementation of trie merging, bound trimming, and histogram bucket accumulation aligns well with existing Beam SDK implementations and includes thorough unit test coverage.

🔍 General Feedback

  • The BoundedTrie accumulator accurately mirrors the singleton-to-trie transition, merging, and deterministic subtree trimming semantics found in the Java and Python SDKs.
  • The HistogramValue accumulator properly handles bucket option validation, count summation, and variable-length bucket_counts slices.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @lostluck for label go.
Backup reviewer: jrmccluskey (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Problem:
In buildUrnToOpsMap (sdks/go/pkg/beam/runners/prism/internal/jobservices/metrics.go),
typ2accumFac registers accumulators for counters, distributions, gauges, top-N, bottom-N,
string sets, and progress metrics, but omits MonitoringInfoTypeUrns_BOUNDED_TRIE_TYPE
(beam:metrics:bounded_trie:v1) and MonitoringInfoTypeUrns_HISTOGRAM
(beam:metrics:histogram_int64:v1).

When AddShortIDs resolves a metric with either type URN, metricsStore logs an unknown
short-ID debug message, creates no accumulator, drops every update in contributeMetrics,
and omits the metric from GetJobMetrics. Python's PrismRunnerTest disables bounded trie
checks with check_bounded_trie=False, and Java's Prism build excludes
UsesBoundedTrieMetrics.

Fix:
Add metricAccumulator implementations for BoundedTrie (merging singleton and trie nodes
with bound trimming) and HistogramValue (summing bucket counts and total count across
matching BucketOptions), and register both type URNs in typ2accumFac. Enable bounded trie
metric checks in prism_runner_test.py and runners/prism/java/build.gradle, and add unit
tests in metrics_test.go.

Reproduction (Python SDK on PrismRunner):
Python's HistogramCell.to_runner_api_monitoring_info is a stub returning None, so this
script wires it to monitoring_infos.user_histogram to report USER_HISTOGRAM payloads from
the LOOPBACK worker.
```python
import sys

import apache_beam as beam
from apache_beam.metrics import cells
from apache_beam.metrics import monitoring_infos
from apache_beam.metrics.metric import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.portability.api import beam_job_api_pb2
from apache_beam.portability.api import metrics_pb2
from apache_beam.utils.histogram import LinearBucket

cells.HistogramCell.to_runner_api_monitoring_info = (
    lambda self, name, transform_id: monitoring_infos.user_histogram(
        name.namespace, name.name, self.data, ptransform=transform_id))

class RecordMetricsDoFn(beam.DoFn):
    def __init__(self):
        self.trie = Metrics.bounded_trie("ns", "paths")
        self.hist = Metrics.histogram("ns", "latency", LinearBucket(0, 10, 5))

    def process(self, element):
        seg, val = element
        self.trie.add(("root", seg))
        self.hist.update(val)
        yield element

if __name__ == "__main__":
    options = PipelineOptions(
        ["--runner=PrismRunner", "--environment_type=LOOPBACK"] + sys.argv[1:]
    )
    p = beam.Pipeline(options=options)
    _ = (
        p
        | beam.Create([("a", 5), ("b", 15), ("b", 25)])
        | beam.ParDo(RecordMetricsDoFn())
    )
    res = p.run()
    res.wait_until_finish()

    tries = res.metrics().query(
        MetricsFilter().with_namespace("ns").with_name("paths")
    )["bounded_tries"]
    resp = res._job_service.GetJobMetrics(
        beam_job_api_pb2.GetJobMetricsRequest(job_id=res._job_id)
    )
    hists = [
        metrics_pb2.HistogramValue.FromString(mi.payload)
        for mi in resp.metrics.committed
        if monitoring_infos.is_histogram(mi)
        and mi.labels.get("NAMESPACE") == "ns"
        and mi.labels.get("NAME") == "latency"
    ]
    trie_paths = [set(t.committed.flattened()) for t in tries]
    hist_counts = [(h.count, list(h.bucket_counts)) for h in hists]
    print("bounded_tries:", trie_paths)
    print("histograms:", hist_counts)
    assert trie_paths == [{("root", "a", False), ("root", "b", False)}]
    assert hist_counts == [(3, [1, 1, 1, 0, 0])]
```

Before the fix (`master`): `bounded_tries: []` and `histograms: []`, and the first assertion fails.
After the fix: `bounded_tries: [{('root', 'a', False), ('root', 'b', False)}]` and `histograms: [(3, [1, 1, 1, 0, 0])]`.
@prodriguezdefino
prodriguezdefino force-pushed the prism/metrics-trie-histogram branch from bdb2196 to 1c60804 Compare December 2, 2026 09:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant