Repository navigation
[BEAM-4775] add GetJobMetrics RPC - #7934
ryan-williams wants to merge 14 commits into
Conversation
8b96599 to
11cfac0
Compare
| runtime project(path: ":beam-model-pipeline", configuration: "shadow") | ||
| } | ||
|
|
||
| configurations { |
There was a problem hiding this comment.
this will go away when I move the MonitoringInfo protos to model/pipeline: #7938
| // export the shaded variant as the actual runtime dependency. | ||
| compile project(path: ":beam-model-pipeline", configuration: "unshaded") | ||
| runtime project(path: ":beam-model-pipeline", configuration: "shadow") | ||
| compile project(path: ":beam-model-fn-execution", configuration: "unshaded") |
There was a problem hiding this comment.
this will go away when I move the MonitoringInfo protos to model/pipeline: #7938
| * Create a metric that can be incremented and decremented, and is aggregated by taking the sum. | ||
| */ | ||
| public static Counter counter(MonitoringInfoMetricName metricName) { | ||
| public static Counter counter(MetricName metricName) { |
There was a problem hiding this comment.
this is a result of introducing a MetricName constructor (MonitoringInfoMetricName.named) that can return a "system" MonitoringInfoMetricName or a "user" AutoValue_MetricName.
previous discussion: #7876 (comment)
MonitoringInfoMetricName goes away altogether in #7915; it is conceptually a MetricKey (not a MetricName), and I line everything up accordingly in that PR.
| if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { | ||
| urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); | ||
| } else { | ||
| return null; |
There was a problem hiding this comment.
previous discussion: #7868 (comment)
Getting a fully-formed user-metric name here, or sentinel null, is useful in a few call-sites.
| extractUpdates(counters), extractUpdates(distributions), extractUpdates(gauges)); | ||
| } | ||
|
|
||
| /** |
There was a problem hiding this comment.
This went to MetricUpdateProtos, with hooks to support more types
| private Map<String, String> labels = new HashMap<String, String>(); | ||
|
|
||
| private MonitoringInfoMetricName(String urn, HashMap<String, String> labels) { | ||
| checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); |
There was a problem hiding this comment.
these checkArguments are now in the polymorphic MetricName constructor below, which everything still funnels through.
Much of that kind of distinction will go away with e.g. #7915, but we probably want this PR with the new proto/RPC to go in first
| * Update this container with metrics from the passed {@link MonitoringInfo}s, and send updates | ||
| * along to Flink's internal metrics framework. | ||
| */ | ||
| public void updateMetrics(String stepName, List<MonitoringInfo> monitoringInfos) { |
There was a problem hiding this comment.
having the stepName here (and updateMetrics(stepName) below) was wrong, and came from my initially not understanding that the MonitoringInfos here come with their true ptransform names, and the stepName as Flink operators understood it was just some made-up name for the fused stage.
(tbf, MonitoringInfos didn't have a correct ptransform label on them until #7624, which this predates)
ff8a6ee to
d31f0cf
Compare
|
Run Flink ValidatesRunner |
|
Run Java Flink PortableValidatesRunner Batch |
|
Overall, I think this PR is adding way too much code and complexity. I would rather not submit this. I have spent 2 hours reading this so far and have gone through about half. I'll have to look at it some more tomorrow. But I am not yet convinced everything you've added is necessary at the moment. and much the naming and callback passing is quite confusing so its hard to understand what the various methods are doing. |
| } | ||
|
|
||
| // All metrics for a given job. Each runner may or may not support "committed" metrics. | ||
| message MetricResults { |
There was a problem hiding this comment.
Can we change the name, MetricResults represent a class structure in the languages. And this name is already used in those places.
GetMetricsResponse was the name we picked here. Is there a reason you used MetricResults?
https://s.apache.org/get-metrics-api
There was a problem hiding this comment.
This is my take on the "proto analog of the SDKs' existing MetricResults", as Alex suggested below. Sorry that wasn't clear.
Is there a reason that this isn't a good fit for that, as written?
This makes e.g. MetricResultsProtos.java perform a simple role: convert between the proto and SDK versions of this concept, which I think is more general than the specific GetJobMetrics RPC.
This currently is different than the SDKs' versions because it goes {attempted,committed} > {counter,distribution,gauge}, whereas the SDKs are the other way around (each result, with a specific type, has {attempted,committed}). I implemented protos like that in a previous draft, but protos' lack of generics made it messier, and it was decided to arrange the protos this way.
| } | ||
|
|
||
| message GetJobMetricsResponse { | ||
| org.apache.beam.model.fn_execution.v1.MetricResults metrics = 1; |
There was a problem hiding this comment.
I don't think we need the MetricResults layer. Can we just put the MonitoringInfos attempted, comitted here.
There was a problem hiding this comment.
Basically, I think that at some point we should introduce a MetricResult proto to be shared across languages. instead of having each SDK implement the same class. Are you planning at some point to make your MetricResults proto be that at some point? I think that would be a good path
There was a problem hiding this comment.
Are you planning at some point to make your MetricResults proto be that at some point? I think that would be a good path
Yes, elaborated above. The MetricResults concept is more general than the GetJobMetrics RPC, I think, and this makes it more clear what proto structures correspond to what SDK structures.
|
|
||
| public MetricResultBuilder(MetricKey key, T attempted) { | ||
| this.key = key; | ||
| this.attempted = attempted; |
There was a problem hiding this comment.
Add a setAttempted for both
I would say the default is that committed are the only ones emitted by an SDK, which come from the ProcessBundleResponse, while attempted come from the ProcessBundleProgressResponse, requiring a lot more work.
There was a problem hiding this comment.
This is only used when we know we have an "attempted", and we may or may not have a "committed". All runners today populate "attempted", but only some populate "committed".
Encoding [the knowledge that we always have "attempted" here] makes build not have to do any checking; attempted is final and non-@Nullable (unlike committed, but that's ok because MetricResult also encodes this fact).
I found it cleaner than an approach that pretended to be more general (this is a private static class with just the logic it uses), though I understand calling it a Builder may be confusing / unidiomatic.
lmk if I should rename it, or still make it a more general "builder"-pattern, or what you think.
There was a problem hiding this comment.
I don't think your assumption is correct. You could assume attempted == committed values. But the java SDK for example doesn't return the ProgressBundleResponse metrics which would be used for attempted metrics.
There was a problem hiding this comment.
There are a couple meanings of {"attempted", "committed"} floating around.
You've implied they correspond to MIs that come in via {ProcessBundleProgressResponse, ProcessBundleResponse}, resp., but there's a pre-fn-api {"physical", "logical"} meaning that most existing code uses.
I'm not trying to resolve these two meanings in this PR. I wrote things to conform to exactly what was already happening, while still supporting the changes I'm attempting to make (which require converting between [new proto] and [existing SDK] representations of metrics).
What was already happening, that I'm preserving, is:
- "attempted" ("physical") is always set
- "committed" ("logical") is sometimes set
- some runners don't support the latter, so they don't set it (by going through
MCSM.asAttemptedOnlyMetricResults): - other runners do set both:
- DataflowMetrics 1, 2: "attempted" and "committed" are set to the same value
- DirectMetrics: both values set, representing "physical" and "logical" values
- portable DirectMetrics
- most portable DirectRunner metrics code seems like copy-pasta from the legacy version. I've consolidated / deleted some of it, but haven't gotten to this yet.
- some runners don't support the latter, so they don't set it (by going through
- accordingly, "committed" is
@Nullable, and "attempted" is not.
In this private static helper, I've written the simplest conversion I can manage between [an attempted metric value] and [optional corresponding committed value that comes in via a different proto field] and a MetricResult that joins them.
lmk if that doesn't make sense!
There was a problem hiding this comment.
Is this wording backwards? Committed generally refers to something persisted to disk, so physical seemed like the appropriate word to match with it.
"attempted" ("physical")
"committed" ("logical")
There was a problem hiding this comment.
I don't think it is backwards.
"attempted" is "physical" in the sense that multiple attempts of the same work will physically do work (e.g. read bytes from disk).
OTOH, only one instance of any given piece of work should be "committed", and will correspond to the "logical" amount you expect to be processed (e.g. number of elements in a collection).
There was a problem hiding this comment.
Sorry this was onerous to review, and thanks for spending the time @ajamato and @Ardagan. I'll go make some of the code changes you suggested, but I feel like we are reasonably aligned on the big-picture here.
MetricResults proto
The MetricResults proto here is isomorphic to the Python- and Java-SDK versions of that structure. That's deliberate, and is the reason I called it "MetricResults" instead of GetJobMetricsResponse.
The GetJobMetrics RPC's response only contains a MetricResults; maybe I should skip defining a dedicated response-type for it, and just return a MetricResults?
rpc GetJobMetrics (GetJobMetricsRequest) returns (MetricResults);
There's a "transpose" between the proto and SDK MetricResults-shapes that requires a conversion step: proto is {attempted,committed} x {counter,distribution,gauge}, SDKs are vice versa. I've implemented that conversion for both languages.
I think we're all agreed that the proto version should fork on {attempted,committed} first; whether the SDKs should be made to follow later on is an open question I'm interested to discuss.
Callbacks
I understand the overloads+callbacks are hard to grok; I'll see what I can do about that. I think there's a way to make that more readable than having separate methods for each {metric type} x {attempted,committed}, especially as we'll probably add more types shortly.
Looking forward to your thoughts, thanks again.
| } | ||
|
|
||
| // All metrics for a given job. Each runner may or may not support "committed" metrics. | ||
| message MetricResults { |
There was a problem hiding this comment.
This is my take on the "proto analog of the SDKs' existing MetricResults", as Alex suggested below. Sorry that wasn't clear.
Is there a reason that this isn't a good fit for that, as written?
This makes e.g. MetricResultsProtos.java perform a simple role: convert between the proto and SDK versions of this concept, which I think is more general than the specific GetJobMetrics RPC.
This currently is different than the SDKs' versions because it goes {attempted,committed} > {counter,distribution,gauge}, whereas the SDKs are the other way around (each result, with a specific type, has {attempted,committed}). I implemented protos like that in a previous draft, but protos' lack of generics made it messier, and it was decided to arrange the protos this way.
| } | ||
|
|
||
| message GetJobMetricsResponse { | ||
| org.apache.beam.model.fn_execution.v1.MetricResults metrics = 1; |
There was a problem hiding this comment.
Are you planning at some point to make your MetricResults proto be that at some point? I think that would be a good path
Yes, elaborated above. The MetricResults concept is more general than the GetJobMetrics RPC, I think, and this makes it more clear what proto structures correspond to what SDK structures.
| /** Convert metric results from Java SDK to proto form. */ | ||
| public static BeamFnApi.MetricResults toProto(MetricResults metricResults) { | ||
| BeamFnApi.MetricResults.Builder builder = BeamFnApi.MetricResults.newBuilder(); | ||
| MetricQueryResults results = metricResults.queryMetrics(null); |
There was a problem hiding this comment.
OK, I can make another attempt at that style.
However, note that this 3-way split on types is sometimes crossed with {plural,singlular} or {attempted,committed}. Here's such a 3x2 helper-method grid I removed from MCSM recently (replaced with these calls to these helpers).
I'll also likely fast-follow this with double versions of everything, and possibly extrema, so the extra abstraction may be more important in the future.
| metricResult.getCommitted(), | ||
| set, | ||
| BeamFnApi.MetricResults.Builder::addCommitted); | ||
| } catch (UnsupportedOperationException ignored) { |
There was a problem hiding this comment.
If the runner doesn't support committed metrics, then the correct behavior for a MetricResults Proto<->SDK converter (which is what this file is) is to just skip the committed metrics.
getCommitted() throws UnsupportedOperationException is one way to identify that case.
getCommittedOrNull() == null would be another.
This is the expected path for some runners (Flink), I don't see that it's worth logging or failing anything.
I experimented with splitting MetricResults into AttemptedOnlyMetricResults and AttemptedAndCommittedMetricResults, but it wasn't worth it.
lmk if that makes sense, or if I've missed something.
|
|
||
| public MetricResultBuilder(MetricKey key, T attempted) { | ||
| this.key = key; | ||
| this.attempted = attempted; |
There was a problem hiding this comment.
This is only used when we know we have an "attempted", and we may or may not have a "committed". All runners today populate "attempted", but only some populate "committed".
Encoding [the knowledge that we always have "attempted" here] makes build not have to do any checking; attempted is final and non-@Nullable (unlike committed, but that's ok because MetricResult also encodes this fact).
I found it cleaner than an approach that pretended to be more general (this is a private static class with just the logic it uses), though I understand calling it a Builder may be confusing / unidiomatic.
lmk if I should rename it, or still make it a more general "builder"-pattern, or what you think.
| public class MetricUpdatesProtos { | ||
| public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) { | ||
| ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>(); | ||
|
|
There was a problem hiding this comment.
Slightly confused; you're pointing at MetricsContainerImpl.counterUpdateToMonitoringInfo, which converts a counter MetricUpdate to a MonitoringInfo.
In this PR I moved that logic here (a file more explicitly dedicated to MetricUpdate<->MI conversions), removed it there, and generalized it to other metric types. It is still only called from one place, but is reusable if other MetricUpdate<->MI code-paths crop up (it was previously a private method).
It also now uses MI-builder stuff for setting {name,labels} from a MetricKey (handleMetricKey below), so that code is now going through a more widely-shared path.
lmk if I'm missing something.
| * metric. | ||
| */ | ||
| public static MetricName named(String urn, Map<String, String> labels) { | ||
| checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); |
There was a problem hiding this comment.
In the MonitoringInfos-everywhere world, it's natural to have MIs that are a mix of user- and system-metrics, and want to turn them into SDK reprs (incl. MetricNames).
In this PR, I rely on [the ability to correctly make an AutoValue_MetricName for user-metrics and a MonitoringInfoMetricName for system metrics in two places]:
- Flink's bundle-progress listener converts mixed MIs here.
- The MetricResultsProtos conversion code-path uses them (
keyFromMonitoringInfocallsMIMN.createbelow, which calls this); this is how JobServicePipelineResult to convert MetricResults proto to an SDK MetricResults.
|
|
||
| public SimpleMonitoringInfoBuilder handleMetricKey(MetricKey key) { | ||
| MetricName metricName = key.metricName(); | ||
| if (metricName instanceof MonitoringInfoMetricName) { |
There was a problem hiding this comment.
Yea, as I mentioned in the MetricUpdatesProtos comment, in this PR I put that code here, and it's used in multiple places as the canonical way to go from SDK form (MetricKey/MetricName) toward MI form.
SIMB seems like the right place to handle the setting of these MI fields. Everything else now calls this.
I don't think it had a lot to do with MetricUpdates specifically, and the call-site you've linked was a private (non-static) method, inhibiting reuse.
| try { | ||
| JobInvocation invocation = getInvocation(invocationId); | ||
| LOG.info("Found job invocation for metrics: {}", invocation); | ||
| MetricResults metrics = invocation.getMetrics(); |
There was a problem hiding this comment.
PipelineResult exposes the SDK-style MetricResults; JobInvocation gets them from there.
Switching to (or adding) MetricResults proto there seemed a bit more involved, but I'll think about it, it might work.
I'd suggest we leave it for a follow-on PR though. This is a case where I tried to play nicely with what the SDK was already doing. We can push for more MI-only APIs everywhere next…
539b2d0 to
60d8bc1
Compare
Also just noting a weird possible flake in the Jenkins run prior: |
|
Run Java_Examples_Dataflow PreCommit |
| distributionData.getMax()); | ||
| } | ||
|
|
||
| public static IntDistributionData toProto(DistributionResult distributionResult) { |
There was a problem hiding this comment.
Can these static methods live on the DistributionResult object, instead of a new file?
(And for similar files as well).
There was a problem hiding this comment.
I actually decided to pull these back to this file (I'd previously made the change you suggested).
When I put them on DistributionResult, that gave sdks/java/core a public-API dependency on the IntDistributionData proto (and a bunch of gRPC- and proto-things that come along with it, transitively), which GcpCoreApiSurfaceTest complained about:
I prefer just putting these helpers in this file in runners-core as opposed to adding e.g. org.apache.beam.model.* to their public API surface (and everyone else's, they just happen to care enough to have a test…).
I ran into this on other metric-related PRs, and so far have been able to keep it out of master. We may end up needing to just "leak" a lot of proto and gRPC here anyway, so maybe it doesn't matter, but this feels like the more considerate thing to do for now.
lmk what you think
| import org.joda.time.Instant; | ||
|
|
||
| /** Convert gauges from proto to SDK representations. */ | ||
| public class GaugeProtos { |
There was a problem hiding this comment.
Ditto, move to and from methods to the GaugeResult class.
There was a problem hiding this comment.
similarly to above, I tried this, but (shaded) com.google.protobuf.Timestamp ends up in the public API surface of downstream modules, which feels icky. I've reverted this back to GaugeProtos.
I don't mind small files of static helpers doing specific things, but lmk if you think I should put this back in core or what.
|
|
||
| public MetricResultBuilder(MetricKey key, T attempted) { | ||
| this.key = key; | ||
| this.attempted = attempted; |
There was a problem hiding this comment.
I don't think your assumption is correct. You could assume attempted == committed values. But the java SDK for example doesn't return the ProgressBundleResponse metrics which would be used for attempted metrics.
| Metric metric = monitoringInfo.getMetric(); | ||
| MetricKey key = | ||
| MetricKey.create(monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL), metricName); | ||
| processMetric( |
There was a problem hiding this comment.
processMetric could become a more descriptive name
There was a problem hiding this comment.
I changed it to forEachMetricType; I don't necessarily think that's better. lmk if you have a different idea.
It's conceptually a forEach over the Metric sum-type. Ideally it would be a codegen'd method on Metric itself, but that's another story.
c558291 to
e09bb30
Compare
There was a problem hiding this comment.
I think I've responded to all the comments, thanks again.
@ajamato asked me offline to put some thoughts about the higher-level direction here in a doc, so I'll work on that next.
As an aside, I'll mention this trick for checking out PRs locally, in case you've not seen it:
git config --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/pr/*'
(Change origin if you have it named differently).
I find this invaluable for reviewing large PRs, seeing where methods are called, etc. You can run it once per repo, and then:
git checkout pr/7934
| metricResult.getCommitted(), | ||
| set, | ||
| BeamFnApi.MetricResults.Builder::addCommitted); | ||
| } catch (UnsupportedOperationException ignored) { |
There was a problem hiding this comment.
I reworked this in terms of getCommittedOrNull and a null-check, lmk if I should do something else.
| * @param add add the {@link MonitoringInfo} created from this key/value to either the "attempted" | ||
| * or "committed" list of the {@link BeamFnApi.MetricResults.Builder builder} | ||
| */ | ||
| private static <T> void process( |
There was a problem hiding this comment.
I renamed them:
addMetricResultToBuilder: for any type, add attempted (and optional committed) valuesaddMetricToBuilder: add one specific (attempted xor committed) value
lmk what you think
| add(metrics.getCommittedList(), true); | ||
| } | ||
|
|
||
| private void add(Iterable<MonitoringInfo> monitoringInfos, Boolean committed) { |
There was a problem hiding this comment.
this isn't really a builder in that sense; maybe there's another name I should give it?
all these methods are private and only called from the constructor.
I've renamed them to not be so overload-heavy.
lmk what you think
| Metric metric = monitoringInfo.getMetric(); | ||
| MetricKey key = | ||
| MetricKey.create(monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL), metricName); | ||
| processMetric( |
There was a problem hiding this comment.
I changed it to forEachMetricType; I don't necessarily think that's better. lmk if you have a different idea.
It's conceptually a forEach over the Metric sum-type. Ideally it would be a codegen'd method on Metric itself, but that's another story.
|
Run Python PreCommit |
|
Some kind of installation error that registered as |
|
Flaky cassandra test (BEAM-6722) |
|
Run Java PreCommit |
|
This is a new one, to me: |
|
Run Python PreCommit |
Some other noise (e.g. |
|
Run Python PreCommit |
|
Run Portable_Python PreCommit |
|
Seems like the job failed to boot properly: |
|
|
||
| public MetricResultBuilder(MetricKey key, T attempted) { | ||
| this.key = key; | ||
| this.attempted = attempted; |
There was a problem hiding this comment.
Is this wording backwards? Committed generally refers to something persisted to disk, so physical seemed like the appropriate word to match with it.
"attempted" ("physical")
"committed" ("logical")
| * Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, | ||
| * or gauge), and gracefully dropping / warning about unexpected and unsupported states. | ||
| */ | ||
| public static void forEachMetricType( |
There was a problem hiding this comment.
forEach methods generally loop and call the callback on every element in the collection. Rename or make this do the looping as well.
There was a problem hiding this comment.
I renamed this once already (previously: processMetric); please suggest a name that you think is better.
This is an abstraction over the Metric sum-type; for each possible metric type, it performs some action.
Call-sites that want to process a Metric should specify what to do in each possible case, avoiding (possibly incomplete) if/else-ing; this also centralizes sensible log statements in response to unsupported types.
From the Javadoc, for inspiration:
Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, or gauge), and gracefully dropping / warning about unexpected and unsupported states.
| private static <T> void addMetricResultToBuilder( | ||
| MetricsApi.MetricResults.Builder builder, | ||
| MetricResult<T> metricResult, | ||
| BiConsumer<SimpleMonitoringInfoBuilder, T> set) { |
There was a problem hiding this comment.
The use of this BiConsumer is really hard to follow especially since its using SimpleMonitoringInfoBuilder. Can you rewrite this file so that you don't need to do this callback passing.
I think most of this is unncessary since everything is the same except for the value you are setting (gauge vs distribution vs counter).
Would you mind trying this instead: I think this will reduce code length as well.
(1) call a helper method to set the labels, metric name, etc. on the SimpleMonitoringInfo
(2) then call a separate method to set the counter, gauge or distribution afterward
(3) Then call a helper method to add it to the collection structure.
There was a problem hiding this comment.
Here is what toProto is doing:
- for type in {counters, distributions, gauges}:
- for each instance of type:
- for each kind in {attempted, committed}:
- SIMB.setLabelsAndUrn
- add instance value to SIMB using type-specific SIMB helper
- SIMB.build
- null check + add result MI using kind-specific helper
- for each kind in {attempted, committed}:
- for each instance of type:
That inner logic is going to be typed 6 times (3 types * 2 kinds, and the former is likely to grow!) unless we abstract over one or both axes using callbacks.
To me, the latter is clearer and less bug-prone (that null check is tricky and likely to change, and should be funneled through as few call-sites as possible, representing the official way to transit the relevant APIs).
I think your proposal is to split bits of the innermost logic into separate passes over the 3 containing loops. I'm skeptical that's going to be cleaner; please sketch it in more detail if you think it will be.
| * <p>The proto form also holds more kinds of values, so some {@link MonitoringInfo}s may be dropped | ||
| * from converting to the Java SDK form. | ||
| */ | ||
| public class MetricResultsProtos { |
There was a problem hiding this comment.
Making the attampted/committed value just a parameter will simplify things, rather than maintaining separate collections for both
There was a problem hiding this comment.
If you mean folding it into the MI (as a label), yea, that would make this code simpler.
I don't think we have agreement on that idea yet even between you, me, and @robertwb; are you in favor of that? We'd need to go to the ML as well.
idk whether it's worth trying to merge a version that leaks {attempted,committed} at the top level of the proto, in the meantime. Something for us to discuss…
| return builder.setTimestampToNow().build(); | ||
| } | ||
|
|
||
| private static <T> void fromMetrics( |
There was a problem hiding this comment.
The return type is never used here. Remove it from the signature
There was a problem hiding this comment.
I don't understand. If you're asking me to remove the <T>, it is needed because the function fn expects type T and is applied to the MetricUpdates of the same type. lmk if I missed something.
| public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) { | ||
| ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>(); | ||
|
|
||
| fromMetrics( |
There was a problem hiding this comment.
Similarily in this code, the BiConsumer usage complicates this and makes it harder to read.
Its simple enough to
(1) make a for loop for each of these calls, iterating through the MetricUpdates
(2) call a helper to do everything else
A lot of this problem comes from the fact that MetricUpdate is just a generic class with no knowledge of what its actually storing. So you can't take advantage of any polymophism with a MetricGaugeUpdate, MetricDistributionUpdate, MetricCounterUpdate, etc. So a lot of the code surrounding this special cases or writes switches for each one. If this polymorphism existed you could tell the MetricUpdate to set itself on a MonitoringInfo/SimpleMonitoringInfoBuilder. That's an option as well, but it will require a larger change. Better to table for now.
A lot of the cases where you pass in a callback seem to be for similar reasons.
There was a problem hiding this comment.
Sketching each approach:
Abstracting over types and passing type-specific SIMB helpers as callbacks
public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) {
ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>();
addMetricUpdates(monitoringInfos, metricUpdates.counterUpdates(), SimpleMonitoringInfoBuilder::setInt64Value);
addMetricUpdates(monitoringInfos, metricUpdates.distributionUpdates(), SimpleMonitoringInfoBuilder::setIntDistributionValue);
addMetricUpdates(monitoringInfos, metricUpdates.gaugeUpdates(), SimpleMonitoringInfoBuilder::setGaugeValue);
return monitoringInfos;
}
private static <T> void addMetricUpdates(ArrayList<MonitoringInfo> monitoringInfos, Iterable<MetricUpdate<T>> metrics, BiConsumer<SimpleMonitoringInfoBuilder, T> setValue) {
for (MetricUpdate<T> metric : metrics) {
MonitoringInfo monitoringInfo = updateToProto(metric, setValue);
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
}
private static <T> MonitoringInfo updateToProto(MetricUpdate<T> metricUpdate, BiConsumer<SimpleMonitoringInfoBuilder, T> setValue) {
MetricKey metricKey = metricUpdate.getKey();
SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey);
setValue.accept(builder, metricUpdate.getUpdate());
return builder.setTimestampToNow().build();
}
Repeating for-loops for each type
public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) {
ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>();
for (MetricUpdate<Long> metricUpdate : metricUpdates.counterUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder() .setLabelsAndUrnFrom(metricKey).setInt64Value(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
for (MetricUpdate<DistributionData> metricUpdate : metricUpdates.distributionUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey).setIntDistributionValue(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
for (MetricUpdate<GaugeData> metricUpdate : metricUpdates.gaugeUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey).setGaugeValue(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
return monitoringInfos;
}
Notes:
| Type-abstracted (w/ callbacks) | Repeated for-loops per type | |
|---|---|---|
| LOC: | 21 | 25 |
| LOC (post-spotless): | 35 | 40 |
| Added lines for each new type: | 1 | 12 |
| Source of boilerplate: | method definitions | copy-pasted business logic |
Copy-pasting those SIMB-calls and null-checks is really bad, to me. If I've misrepresented what you're proposing, please write up what you have in mind.
| return builder.toString(); | ||
| public String toString(String delimiter) { | ||
| StringBuilder sb = new StringBuilder(); | ||
| if (labels.containsKey(PCOLLECTION_LABEL)) { |
There was a problem hiding this comment.
I really don't understand this decision, just make it print all the labels. Why special case PCOLLECTION_LABEL
There was a problem hiding this comment.
I tried to explain it at length in the javadoc of this method, above. If that explanation isn't clear let me know.
To paraphrase: MonitoringInfoMetricName is an awkward object that I remove in #7915, but have to deal with here to make job metrics RPC workable without depending on that refactor. If we decide to go with #7915 first then we could avoid this intermediate state.
MIMN is awkward because it stores labels, but MetricName (which it extends) normally doesn't (MetricKey does; currently just the ptransform label, but that's also expanded in #7915).
This was the simplest way to make toString work for existing call-sites that want [a ptransform xor pcollection label], without doing the larger cleanup in #7915.
ryan-williams
left a comment
There was a problem hiding this comment.
Addressed all comments.
Still want to discuss the callbacks vs [repeated for-loops] question, see comments.
Please consider "resolving" some of the older comments that I've responded to, if my response assuaged your concerns. I don't want to mark things resolved if we still need to discuss them or you've missed them. Thanks!
| return builder.toString(); | ||
| public String toString(String delimiter) { | ||
| StringBuilder sb = new StringBuilder(); | ||
| if (labels.containsKey(PCOLLECTION_LABEL)) { |
There was a problem hiding this comment.
I tried to explain it at length in the javadoc of this method, above. If that explanation isn't clear let me know.
To paraphrase: MonitoringInfoMetricName is an awkward object that I remove in #7915, but have to deal with here to make job metrics RPC workable without depending on that refactor. If we decide to go with #7915 first then we could avoid this intermediate state.
MIMN is awkward because it stores labels, but MetricName (which it extends) normally doesn't (MetricKey does; currently just the ptransform label, but that's also expanded in #7915).
This was the simplest way to make toString work for existing call-sites that want [a ptransform xor pcollection label], without doing the larger cleanup in #7915.
| * Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, | ||
| * or gauge), and gracefully dropping / warning about unexpected and unsupported states. | ||
| */ | ||
| public static void forEachMetricType( |
There was a problem hiding this comment.
I renamed this once already (previously: processMetric); please suggest a name that you think is better.
This is an abstraction over the Metric sum-type; for each possible metric type, it performs some action.
Call-sites that want to process a Metric should specify what to do in each possible case, avoiding (possibly incomplete) if/else-ing; this also centralizes sensible log statements in response to unsupported types.
From the Javadoc, for inspiration:
Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, or gauge), and gracefully dropping / warning about unexpected and unsupported states.
| return builder.setTimestampToNow().build(); | ||
| } | ||
|
|
||
| private static <T> void fromMetrics( |
There was a problem hiding this comment.
I don't understand. If you're asking me to remove the <T>, it is needed because the function fn expects type T and is applied to the MetricUpdates of the same type. lmk if I missed something.
|
|
||
| public MetricResultBuilder(MetricKey key, T attempted) { | ||
| this.key = key; | ||
| this.attempted = attempted; |
There was a problem hiding this comment.
I don't think it is backwards.
"attempted" is "physical" in the sense that multiple attempts of the same work will physically do work (e.g. read bytes from disk).
OTOH, only one instance of any given piece of work should be "committed", and will correspond to the "logical" amount you expect to be processed (e.g. number of elements in a collection).
| private static <T> void addMetricResultToBuilder( | ||
| MetricsApi.MetricResults.Builder builder, | ||
| MetricResult<T> metricResult, | ||
| BiConsumer<SimpleMonitoringInfoBuilder, T> set) { |
There was a problem hiding this comment.
Here is what toProto is doing:
- for type in {counters, distributions, gauges}:
- for each instance of type:
- for each kind in {attempted, committed}:
- SIMB.setLabelsAndUrn
- add instance value to SIMB using type-specific SIMB helper
- SIMB.build
- null check + add result MI using kind-specific helper
- for each kind in {attempted, committed}:
- for each instance of type:
That inner logic is going to be typed 6 times (3 types * 2 kinds, and the former is likely to grow!) unless we abstract over one or both axes using callbacks.
To me, the latter is clearer and less bug-prone (that null check is tricky and likely to change, and should be funneled through as few call-sites as possible, representing the official way to transit the relevant APIs).
I think your proposal is to split bits of the innermost logic into separate passes over the 3 containing loops. I'm skeptical that's going to be cleaner; please sketch it in more detail if you think it will be.
| * <p>The proto form also holds more kinds of values, so some {@link MonitoringInfo}s may be dropped | ||
| * from converting to the Java SDK form. | ||
| */ | ||
| public class MetricResultsProtos { |
There was a problem hiding this comment.
If you mean folding it into the MI (as a label), yea, that would make this code simpler.
I don't think we have agreement on that idea yet even between you, me, and @robertwb; are you in favor of that? We'd need to go to the ML as well.
idk whether it's worth trying to merge a version that leaks {attempted,committed} at the top level of the proto, in the meantime. Something for us to discuss…
| public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) { | ||
| ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>(); | ||
|
|
||
| fromMetrics( |
There was a problem hiding this comment.
Sketching each approach:
Abstracting over types and passing type-specific SIMB helpers as callbacks
public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) {
ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>();
addMetricUpdates(monitoringInfos, metricUpdates.counterUpdates(), SimpleMonitoringInfoBuilder::setInt64Value);
addMetricUpdates(monitoringInfos, metricUpdates.distributionUpdates(), SimpleMonitoringInfoBuilder::setIntDistributionValue);
addMetricUpdates(monitoringInfos, metricUpdates.gaugeUpdates(), SimpleMonitoringInfoBuilder::setGaugeValue);
return monitoringInfos;
}
private static <T> void addMetricUpdates(ArrayList<MonitoringInfo> monitoringInfos, Iterable<MetricUpdate<T>> metrics, BiConsumer<SimpleMonitoringInfoBuilder, T> setValue) {
for (MetricUpdate<T> metric : metrics) {
MonitoringInfo monitoringInfo = updateToProto(metric, setValue);
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
}
private static <T> MonitoringInfo updateToProto(MetricUpdate<T> metricUpdate, BiConsumer<SimpleMonitoringInfoBuilder, T> setValue) {
MetricKey metricKey = metricUpdate.getKey();
SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey);
setValue.accept(builder, metricUpdate.getUpdate());
return builder.setTimestampToNow().build();
}
Repeating for-loops for each type
public static List<MonitoringInfo> toProto(MetricUpdates metricUpdates) {
ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<>();
for (MetricUpdate<Long> metricUpdate : metricUpdates.counterUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder() .setLabelsAndUrnFrom(metricKey).setInt64Value(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
for (MetricUpdate<DistributionData> metricUpdate : metricUpdates.distributionUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey).setIntDistributionValue(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
for (MetricUpdate<GaugeData> metricUpdate : metricUpdates.gaugeUpdates()) {
MetricKey metricKey = metricUpdate.getKey();
MonitoringInfo monitoringInfo = new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey).setGaugeValue(metricUpdate.getUpdate()).setTimestampToNow().build();
if (monitoringInfo != null) {
monitoringInfos.add(monitoringInfo);
}
}
return monitoringInfos;
}
Notes:
| Type-abstracted (w/ callbacks) | Repeated for-loops per type | |
|---|---|---|
| LOC: | 21 | 25 |
| LOC (post-spotless): | 35 | 40 |
| Added lines for each new type: | 1 | 12 |
| Source of boilerplate: | method definitions | copy-pasted business logic |
Copy-pasting those SIMB-calls and null-checks is really bad, to me. If I've misrepresented what you're proposing, please write up what you have in mind.
|
Run Java PreCommit |

MonitoringInfoprotos from the fn apiMonitoringInfointomodel/pipeline, to avoid introducing a [job API] → [fn API] depempty_linesmetric!R: @robertwb @ajamato
CC: @mxm since I reworked the Flink metrics a bit in particular
Post-Commit Tests Status (on master branch)
See .test-infra/jenkins/README for trigger phrase, status and link of all Jenkins jobs.