Repository navigation
(feat) Implement metrics rest api - #4115
Conversation
1d37c50 to
ac66c27
Compare
dimas-b
left a comment
There was a problem hiding this comment.
LGTM with one minor remaining comment 😅
@sungwy , @sneethiraj : FYI about the new AuthZ operation.
flyingImer
left a comment
There was a problem hiding this comment.
The direction looks right to me
Two structural observations:
-
With this PR, MetricsPersistence grows from 2 write methods to 4 (read + write). It's marked @beta and the javadoc calls it a "Service Provider Interface." But it lives on BasePersistence, which only local DB backends implement. NoSqlMetaStoreManager and RemotePolarisMetaStoreManager go through empty BasePersistence implementations, so these methods are permanently no-op for them. Meanwhile, the actual SPI interfaces (PolarisMetricsReporter, PolarisMetricsManager) have no annotation at all. The @beta signal is on the wrong layer IIUC
-
The write path enters through PolarisMetricsManager on MetaStoreManager, but this read path bypasses that layer and goes straight to BasePersistence via callContext.getMetaStore(). If we want the metrics read API to work for non-JDBC backends, it would need a MetaStoreManager-level entry point, same as writes.
Not blocking on this. I think the question of where metrics persistence should sit architecturally is worth a discussion on dev@.
Thank you. I have added About the second point, thank you. Would this mean a read method to |
Thanks for adding @beta. Reads should go through MetaStoreManager too, same as writes. If reads stay on BasePersistence, non-JDBC backends can't implement the read API at all. I'd prefer fixing that in this PR so the read path ships with the same layering as writes. Separately, the persistence schema discussion on dev@ is still open. A follow-up issue linking to that thread would help track it. |
Pushed a commit (and rebased against updated main). For the persistence schema discussion — I'll open a follow-up issue linking to the dev@ thread once there's a message to reference. Happy to do that now if you can share the thread link (I don't have it handy). Please let me know. |
flyingImer
left a comment
There was a problem hiding this comment.
Are you planning to merge as-is now that Dmitri approved, or is there another round? Asking because the May 7 metrics sync landed on a few directional items that touch the schema and SPI shape here. Left some questions inline.
|
@obelix74 : it looks like this PR got a lot of conflicts 🤷 |
Resolved all conflicts and push. Rebased against main. |
flyingImer
left a comment
There was a problem hiding this comment.
Thanks for continuing to push this forward. The direction still looks good to me: exposing persisted metrics through a beta read API, using a stable response envelope, keeping the API in an extension module, and routing reads through table-scoped authz all make sense.
One thing I would still like to clarify before this merges is sequencing with the metrics SPI/schema work we discussed after the May 7 sync.
From the previous review thread, I think we already converged on a few points:
- the current
MetricsPersistence/PolarisMetricsManagerlayering is transitional, and #4397 is expected to move metrics persistence out of the old aggregatedBasePersistenceshape; - the current
scan_metrics_report/commit_metrics_reportsplit is also transitional, with the follow-up direction being a single metrics report model/table with a metric type discriminator; listScanMetrics/listCommitMetricsare therefore likely interim API/SPI shapes, and may collapse or be rerouted when the schema/SPI consolidation happens.
I don't think this PR has to solve all of that before it can make progress. But I do think we should avoid accidentally standardizing the transitional shape just because this PR is ready first.
Could we make the sequencing explicit before merge? For example, either rebase on #4397 if that lands first, or link a concrete follow-up that tracks:
- moving metrics persistence to the standalone SPI shape,
- consolidating the metrics schema/model,
- deciding whether the per-type list methods remain public SPI surface or collapse behind a typed query API.
| - metricTypes | ||
| - objects | ||
| properties: | ||
| metricTypes: |
There was a problem hiding this comment.
It looks like the REST spec uses lowercase, hyphenated field names, such as metric-type, rather than uppercase names like metricTypes. Can we fix all field names?
There was a problem hiding this comment.
Renamed all of them to lowercase hyphenated: metric-types, page-token, page-size, timestamp-from, timestamp-to, next-page-token, snapshot-id, metric-type and timestamp-ms. I regenerated the bundled spec too. Fixed in ebfec76.
| Defaults to `iceberg-table` when omitted. Currently, only `iceberg-table` is supported; | ||
| entries with unsupported values are ignored. | ||
| snapshotId: | ||
| type: integer |
There was a problem hiding this comment.
Could we define snapshotId as a string and treat it as an opaque, format specific identifier if we want this API to support table formats beyond Iceberg? Delta and Paimon use numeric IDs, Hudi uses instant times, and Lance uses unsigned version IDs, so int64 would not cover all of them. The service could validate and resolve the value based on the table format. Each format would still need backend support.
There was a problem hiding this comment.
Changed snapshot-id to a string and described it as an opaque, format-specific identifier. For iceberg-table the service parses it as a long and returns a 400 if it isn't numeric, and responses return it as a string. Other table formats would need their own validation and backend support. Fixed in ebfec76.
| Maximum number of results to return per page. When omitted, the server selects the page | ||
| size (`METRICS_QUERY_DEFAULT_PAGE_SIZE`, 100 by default). Values above the server maximum | ||
| (`METRICS_QUERY_MAX_PAGE_SIZE`, 1000 by default) are reduced to it. |
There was a problem hiding this comment.
We shouldn't tie the REST spec to a server config. I think we can remove the description first, and adopt the pagination schema in #6028 after it's merged in a followup PR.
| Overlapping entries do not duplicate reports. The server limits the number of entries | ||
| per request (`METRICS_QUERY_MAX_OBJECTS`, 100 by default) and rejects larger requests |
There was a problem hiding this comment.
There was a problem hiding this comment.
Same here. I removed METRICS_QUERY_MAX_OBJECTS from the objects description, it now just says the server limits the number of entries and rejects larger requests with a 400. Fixed in ebfec76.
| items: | ||
| $ref: '#/components/schemas/CatalogObject' | ||
| page-token: | ||
| $ref: '../iceberg-rest-catalog-open-api.yaml#/components/schemas/PageToken' |
There was a problem hiding this comment.
I am very much against reusing and promoting the IRC paginations definitions.
polaris/spec/iceberg-rest-catalog-open-api.yaml
Lines 2403 to 2405 in 5fafc67
I do believe that the requirement for servers to return all data is generally unreasonable and with metrics queries it specifically makes servers vulnerable to DoS via OOM attacks.
This has been discussed at length on dev.
https://lists.apache.org/thread/k81ptyktdbdf8gynncgk3o04mqt85zyk
https://lists.apache.org/thread/mmqllcbt2lfsrq571cfwbymgfwoxqdf0
@flyrain : If you proposed this reference (apologies, but I am lost in the multitude of comments on this PR), let's open a dedicated dev discussion to settle this matter.
I believe, the option for servers to fail on overly long result sets is not a replacement for a specification that instructs clients how to properly process large results.
Cf. #5927 (comment)
There was a problem hiding this comment.
I do not see a reason for adding a new API with a pagination spec that has known usability concerns. If we do that we'll be in the same situation as with the IRC API, which we had to deal with in the two dev discussions I linked above.
My proposal is using local pagination parameter definitions similar to #5927
After #6028 lands we can refactor YAML files to share some elements.
The critical point from my POV is NOT allowing clients to force servers into returning all data.
I might have missed that in my earlier reviews. Apologies about that.
There was a problem hiding this comment.
Makes sense, I switched to local definitions following #5927. page-token in the request is now a plain string instead of a ref to the IRC PageToken, page-size is documented as a hint, and the operation description says any response may be paginated and clients can't ask for all results in one response. The server already paginated every request and capped the page size at METRICS_QUERY_MAX_PAGE_SIZE, so only the spec changed. I'll move this to the shared definitions once #6028 lands.
|
@obelix74 : Unfortunately, it looks like there are merge conflicts now 🤷 |
|
Rebased onto main to clear the merge conflicts. There were two: main added the |
adnanhemani
left a comment
There was a problem hiding this comment.
One comment left for me; I think there's a potential bug in MetricsReportService.java.
| Map<Long, TableIdentifier> tableIdToIdentifier = resolved.tableIdToIdentifier(); | ||
| if (tableIdToIdentifier.isEmpty()) { | ||
| // Missing and denied tables are indistinguishable, so this does not reveal which exist. | ||
| throw new ForbiddenException( |
There was a problem hiding this comment.
This 403 fires whenever the authorized set is empty, including on a follow-up page if every previously readable table is gone or lost TABLE_READ_METRICS. A client walking next-page-token would see a 403 mid-listing.
Could later pages return 200 with empty reports and a null token instead, so a pager can treat this as end-of-results rather than an auth failure? Fine to keep 403 on the first page when nothing is readable.
There was a problem hiding this comment.
Agreed, done in c066b0d. When a request carries a page-token and none of the tables is readable anymore, the server now returns 200 with empty reports and a null next-page-token, so a pager treats it as the end of the results. The first page still returns 403. I added a test for the later-page case and described the behavior in the operation description.
| 403: | ||
| $ref: '../iceberg-rest-catalog-open-api.yaml#/components/responses/ForbiddenResponse' | ||
| 404: | ||
| description: Not Found - The catalog does not exist |
There was a problem hiding this comment.
Is "catalog does not exist" correct - or can it also be table?
There was a problem hiding this comment.
Catalog is correct. The tables are resolved as optional paths, so a missing table is left out of the result (or leads to the 403 when nothing is readable), and only a missing catalog produces a 404. The NoSuchTableError example under the 404 was wrong though, it made it look like a missing table returns 404. I dropped it in c066b0d and spelled out in the 404 description that missing tables never produce one.
adnanhemani
left a comment
There was a problem hiding this comment.
Thanks for addressing all the back-and-forth, @obelix74. Happy to see this finally getting over the line!
| only to a request without a `page-token`: when none of the tables is readable on a later | ||
| page, for example because they were dropped or the privilege was revoked during the | ||
| listing, the server returns an empty `reports` list with no `next-page-token`. A 404 is | ||
| returned only when the catalog itself does not exist. |
There was a problem hiding this comment.
Do we return a 404 if a catalog exists, but the caller doesn't have any privileges on it? That should be the default behavior
There was a problem hiding this comment.
My reading is that this sentence indicates that 404 is returned for non-existent catalogs, but not for non-existent entities. The latter receive 200 responses with no data.
There was a problem hiding this comment.
I meant specifically for a catalog that does exist, but that the user doesn't have any privileges on - not whether it had any underlying entities. I realize this isn't consistent behavior with the other apis. I'm ok to keep the behavior as is, though a future improvement would be to update entity access apis to return 404 if the user has no privileges on the underlying entity.
|
Heads-up: #5967 has been merged, so Could you rebase onto |
|
Thanks for the heads-up. I rebased onto main and reverted my change to The rebase had one real conflict, in I couldn't run the full Gradle build locally (the Spotless plugin won't resolve on my machine because of a certificate error), so I'm leaning on CI to confirm formatting and compilation. |
|
@obelix74 : Some of the commits reference Claude as a formal co-author. Per Polaris contribution guidelines only humans can be "authors". Would you mind converting the co-author tags to something like |
Squashed all commits and removed the Claude reference. |
| PolarisEntityType.TABLE_LIKE, | ||
| true)); | ||
| } | ||
| ResolverStatus status = manifest.resolveAll(); |
There was a problem hiding this comment.
I believe that both PolarisAuthorizerImpl and RangerPolarisAuthorizer/OpaPolarisAuthorizer call authzState.resolve() inside authorizer.resolveAuthorizationInputs(...), which invokes Resolver.resolveWithPlan(...).
Because manifest.resolveAll() was already called here on this line, Resolver.resolveWithPlan trips diagnostics.check(resolverStatus == null, "resolver_called") and throws an IllegalStateException (HTTP 500) whenever at least one requested table resolves (existing is not empty). MetricsReportsServiceTest masks this because manifest and authorizer are mocked.
We can resolve once by:
- Dropping the upfront
manifest.resolveAll()call (and the unusedPolarisEntityType.NAMESPACEpassthrough paths,AuthorizationIntentResolveronly looks up toTABLE_LIKEpath). - Building intents for all
identifiersand callingauthorizer.resolveAuthorizationInputs(authorizationState, new AuthorizationRequest(polarisPrincipal, allIntents))once. - Checking
manifest.getPrimaryResolverStatusOrThrow()forENTITY_COULD_NOT_BE_RESOLVED, collectingexistingtables, and callingauthorizer.authorize(...)only for thoseexistingtables (sinceAuthorizationIntentResolver.resolverequires a resolved securable).
There was a problem hiding this comment.
Good catch, you're right. I called manifest.resolveAll() and then the authorizer resolved the same manifest again, which trips the resolver_called check and turns into a 500 as soon as one requested table exists. The test didn't show it because the manifest and the authorizer were both mocks.
I took your suggestion. The upfront resolveAll() and the namespace passthrough paths are gone, the service builds an intent for every requested table, and resolveAuthorizationInputs runs once. After that I check the primary resolver status for a missing catalog, collect the tables that exist, and call authorize only for those, one table at a time so a denial on one doesn't affect the others.
The test now uses a manifest mock that throws on a second resolveAll(), and there's a test that checks the manifest is resolved once with an intent for each table (including a missing one). Against the old code 23 of the 32 tests in that class fail, so it does catch this. Pushed in 167f5f5.
There was a problem hiding this comment.
Good catch! I missed that in my review 🤦 Thanks for the fix, @obelix74 !
| request.getTimestampTo() != null ? request.getTimestampTo() : clock.millis(); | ||
| timestampFrom = upperBound - Duration.ofDays(windowDays).toMillis(); | ||
| } | ||
| MetricsQuerySpi provider = queryProvider.get(); |
There was a problem hiding this comment.
NoOpMetricsQuery lives in extensions/metrics-reports/base (polaris-extensions-metrics-reports), which is only a runtimeOnly dependency in runtime/server, not in runtime/service. In runtime/service own @QuarkusIntegrationTest apps or stripped-down downstream builds that omit the extension (see ServiceProducers.metricReporter), queryProvider.get() will fail with UnsatisfiedResolutionException (HTTP 500).
We should either check queryProvider.isResolvable() here or move NoOpMetricsQuery into runtime/service alongside MetricsReportsService.
There was a problem hiding this comment.
You're right, NoOpMetricsQuery only comes in through the extension module, so a build without it would fail on queryProvider.get().
I went with isResolvable() rather than moving the class. When no MetricsQuerySpi bean is available the service returns an empty page, which is what the no-op default returns anyway, and the module layout stays as it is. The authorization checks still run first. Added a test for the no-backend case. Pushed in 167f5f5.
There was a problem hiding this comment.
isResolvable() SGTM. We might want to refactor module deps later. I do not think that is critical for current PR :)
|
@dimas-b Fixed a merge conflict. |
|
@obelix74 : sadly, there are new merge conflicts... Could you fix them? |
Done. |
What / Why
Part of the 3-PR split of the Iceberg metrics work (agreed with EJ, Dmitri, Anand):
Changes
extensions/metrics-reports/api(polaris-extensions-metrics-reports-api) — the metrics API ships as an optional, extension-scoped feature.MetricsQuerySpiinextensions/metrics-reports/spi; a no-op default (NoOpMetricsQuery,@DefaultBean) inextensions/metrics-reports/baseso the read path returns an empty page (HTTP 200) until a durable backend is installed.MetricsReportsServiceinruntime/service(resolves names→ids, authorizes, delegates toMetricsQuerySpi).polaris-core:TABLE_READ_METRICSprivilege +LIST_TABLE_METRICSoperation, wired through the authorizer/RBAC and mirrored in the Ranger extension.Testing
./gradlew buildand:polaris-runtime-service:intTest(Quarkus) pass.