Optimize coordinator API to retrieve segments with overshadowed status
Coordinator API /druid/coordinator/v1/metadata/segments?includeOvershadowedStatus builds VersionedIntervalTimeline which can be memory intensive and expensive if this API is called multiple times but multiple brokers in a cluster.
The comment here suggests :
isOvershadowedbecomes a non-final field ofDataSegmentobject itself, not participating inequals()andhashCode().- Add
interface SegmentsAccess { ImmutableDruidDataSource prepare(String dataSource); Iterable<DataSegment> iterateAll(); }(strawman naming) - Add
DataSourceAccess computeOvershadowed()method toSQLSegmentMetadataManager, which performs this computation for every snapshot ofSQLSegmentMetadataManager.dataSources(which is updated inpoll()) at most once, lazily. - Both endpoints in
MetadataResourceand Coordination balancing logic (which currently computes isOvershadowed status on its own, too) use this API. - On the side of
MetadataSegmentView, maintain something like aMap<DataSegment, DataSegment>and update overshadowed status likemap.get(segmentFromCoordinator).setOvershadowed(segmentFromCoordinator.isOvershadowed())
@leventov I have some follow-up question on the suggested design.
isOvershadowed becomes a non-final field of DataSegment
So are we saying make DataSegment mutable and add a setter for overshadowed field ?
Add interface SegmentsAccess { ImmutableDruidDataSource prepare(String dataSource); Iterable
iterateAll(); } (strawman naming)
What is the purpose of this interface, who would implement this ? Are you thinking SQLMetadataSegmentManager implements this ?
Add DataSourceAccess computeOvershadowed() method to SQLSegmentMetadataManager,
What is DataSourceAccess here ? Did you mean SQLMetadataSegmentManager ?
Both endpoints in MetadataResource and Coordination balancing logic (which currently computes isOvershadowed status on its own, too) use this API.
which API ? MetadataSegmentManager already has Iterable<DataSegment> iterateAllSegments();, what if this returns DataSegment with isOvershadowed field set, which can be set in SQLMetadataSegmentManager poll method.
On the side of MetadataSegmentView, maintain something like a Map<DataSegment, DataSegment> and update overshadowed status like map.get(segmentFromCoordinator).setOvershadowed(segmentFromCoordinator.isOvershadowed())
I think this will not be required, if coordinator API already returns DataSegment which has overshadowed status.
The general idea of computing overshadowedness as few times as possible sounds good to me, and in particular computing it on poll sounds good. I think we might as well do it eagerly, though, since it's always going to be needed (DruidCoordinatorRuleRunner, for example, always computes the list of overshadowed segments so it can avoid loading them on historicals).
I am skeptical of making DataSegment mutable, though. The alternative is a wrapper object: something like DataSegmentWithTimelineContext or DataSegmentWithOvershadowedState. The main motivation I could see for adding fields to DataSegment, vs. doing a wrapper object, is memory savings. (Is there some other reason I am missing?)
It is nice, I think, that DataSegment objects are self-contained -- they don't depend on other context. 'isOvershadowed' by its nature depends on other context (namely, what other DataSegments exist). It won't be possible to set the field correctly unless all DataSegment objects for a particular datasource are considered. This won't be possible in all cases, which will make it unclear when the field is valid and when it's not, opening up new possible bugs. A wrapper encodes into the type system whether or not the contextual overshadowedness information has been computed or not.
Furthermore, I am not convinced this tactic will be effective at minimizing memory use. As an example, the proposed Map<DataSegment, DataSegment> in MetadataSegmentView would need to keep two copies of each DataSegment, since the key and value are different objects. A wrapper would be cheaper, since the DataSegment object contained by different wrappers could be shared.
@surekhasaharan
So are we saying make DataSegment mutable and add a setter for overshadowed field ?
Yes
What is the purpose of this interface, who would implement this ? Are you thinking SQLMetadataSegmentManager implements this ?
The purpose is type-level and concurrency safety, however, since I agree with @gianm that it's easier to just compute overshadowed status eagerly on each poll(), this part of the suggestion is irrelevant. SQLMetadataSegmentManager's interface will be intact.
I think this will not be required, if coordinator API already returns DataSegment which has overshadowed status.
The idea is to keep using a segment object which resides the Broker's memory for longer, the same idea as here: https://github.com/apache/incubator-druid/blob/15d19f3059a990f022b1cb98bdd4e6a82cdf9a06/server/src/main/java/org/apache/druid/metadata/SQLMetadataSegmentManager.java#L750-L756
@gianm
I think we might as well do it eagerly
Yes. I now also think that instead of rebuilding VersionedIntervalTimeline every time from scratch, one can be kept in memory of SQLMetadataSegmentManager. (It would also allow to skip computations if no segments were added or removed in a particular data source during some poll(), compared to the previous.) The second part is optional.
I am skeptical of making DataSegment mutable, though. The alternative is a wrapper object: something like DataSegmentWithTimelineContext or DataSegmentWithOvershadowedState. The main motivation I could see for adding fields to DataSegment, vs. doing a wrapper object, is memory savings. (Is there some other reason I am missing?)
It is nice, I think, that DataSegment objects are self-contained -- they don't depend on other context. 'isOvershadowed' by its nature depends on other context (namely, what other DataSegments exist). It won't be possible to set the field correctly unless all DataSegment objects for a particular datasource are considered. This won't be possible in all cases, which will make it unclear when the field is valid and when it's not, opening up new possible bugs. A wrapper encodes into the type system whether or not the contextual overshadowedness information has been computed or not.
Looking at the existing code at #7425, I think wrapper approach would be worse.
Regarding DataSegment's immutability, it might need to go away anyway, as #6358 should be fixed (note @surekhasaharan: you can fix that problem, incl. across Coordinator -> Broker segment streaming, in the same PR). DataSegment is immutable and used in HashSets and HashMaps as a key, while it's identity is actually based only on segmentId, is not right. We should probably move to Map<SegmentId, DataSegment> across the board and make DataSegment a mutable object without equals() and hashCode() implementations to avoid defects like #6358 consistently.
As an example, the proposed Map<DataSegment, DataSegment> in MetadataSegmentView would need to keep two copies of each DataSegment, since the key and value are different objects.
The idea was that key and value is the same object in that case, but anyway, it should rather be Map<SegmentId, DataSegment>, see above.
Probably all fields of DataSegment (except overshadowed) should remain final to avoid problematic concurrency updates when actually discovering an instance of #6358 problem (which should be very rare), but the general idea is the same: we should "attach less" to DataSegment's immutability, therefore, I don't see that having a single mutable field in it would be a problem.
I feel the mutability of DataSegment is still being debated, and the major concern is recomputation of overshadowed status and building VersionedIntervalTimeline on each coordinator API call. So I am addressing the latter with #7595
Added to 0.15 milestone because If SegmentWithOvershadowedStatus will leak into Druid 0.15 API, it will be much harder to remove it from later (it will require transition PRs through several consecutive Druid versions, and temporary glue code). So I would really like to see it go away before Druid 0.15 if other people agree that needs to be done. Please provide arguments if you disagree.
Added to 0.15 milestone because If SegmentWithOvershadowedStatus will leak into Druid 0.15 API, it will be much harder to remove it from later
This sounds like going back to feature-based release instead of time-based one. Per the discussion you started, we are trying to freeze code every 3 months. After code freeze, we are backporting only regression bug fixes, security bug fixes, and doc changes if necessary. If you want to talk about a better release policy, please start a discussion on dev mailing list.
Since this issue is not any of bug fix or doc change, I don't think this issue should be necessarily a blocker for 0.15.0 release. IMO, if it's not done yet before code freeze, it simply should wait for the next release. This is the least controversial way to choose features to add to each release I think. Especially for this issue, even the discussion on the proper solution is still ongoing.
Regarding DataSegment's immutability, it might need to go away anyway, as #6358 should be fixed (note @surekhasaharan: you can fix that problem, incl. across Coordinator -> Broker segment streaming, in the same PR).
I agree the current way that DataSegment is updated and maintained is somewhat unintuitive. However, still I think it's not a good idea to make it immutable. Currently the variables can be updated in DataSegment are loadSpec and size, and the update happens only one time after the segment created by stream ingestion tasks is published. So, it's not the update of state, but update of metadata.
overshadowedStatus is different. It represents a state of a dataSegment which can have different values depending on the context. This means, the overshadowedStatus must be computed correctly before it's used. If it's added to DataSegment as a mutable variable, I guess it would be very confusing unless there is a way to figure out under what context that state was computed.
So, I'm also curious about the benefit we can when DataSegment becomes mutable. Is there anything else except memory savings?
Finally, I don't think it's a good idea to recommend to fix several problems in a single PR. It makes the PR complicated which in turn making review harder. I would say, if the author wants to fix several problems in a single PR, I'm ok with that if the PR is not much complicated and large. But, I think simple PRs more likely get reviewed because they are easy to review.
For the metadata of segment, perhaps it's better to have different data structures for segments which are actively generated by stream ingestion tasks and others. For example, the former might not have loadSpec and size fields to reduce confusion. For interning properly, we might need two maps (segmentId -> segment metadata) for each data structure which their keys are never overlapped.
Added to 0.15 milestone because If SegmentWithOvershadowedStatus will leak into Druid 0.15 API, it will be much harder to remove it from later (it will require transition PRs through several consecutive Druid versions, and temporary glue code). So I would really like to see it go away before Druid 0.15 if other people agree that needs to be done. Please provide arguments if you disagree.
@leventov - which API leak are you concerned about? From context I'm guessing it's the HTTP API. I suggest we address that by not documenting it and treating it as an internal API. The info is still exposed through system tables (the original motivation for creating this HTTP API), and that won't change even if we end up wanting to alter the underlying API.
By the way, I'm still not really sure that a mutable DataSegment is the way to go. It just feels wrong. It's a class that is meant to represent the 'payload' in the druid_segments table and the announcement in ZK of an available segment. In my experience these sorts of widely used modeling classes work best when they are immutable. Also, if we added mutable fields like 'isOvershadowed', it would often be invalid (for example: in code that is reading or writing an individual segment announcement in ZK, where the overshadowedness concept does not have meaning).
Besides, I don't think that having mutable DataSegments would really do too much to reduce churn. DataSegments aren't updated very often. Most are either never updated, or are just updated once (during realtime-to-historical handoff). If someone is doing a deep storage migration they might update all their segments, but this would be quite infrequent. If we use wrappers in situations that want to track extra state, like overshadowedness, then those wrappers could be mutable to avoid churn in the wrappers. (Meaning: we could make SegmentWithOvershadowedStatus mutable.)
@jihoonson
This sounds like going back to feature-based release instead of time-based one. Per the discussion you started, we are trying to freeze code every 3 months.
Note that I unblocked #7425 only on the condition that people agree with the proposed approach and it's being implemented immediately: https://github.com/apache/incubator-druid/pull/7425#discussion_r279823676. If I knew that new round of debate will start, I wouldn't unblock that PR and insisted on completely resolving that question before merging.
@gianm
From context I'm guessing it's the HTTP API. I suggest we address that by not documenting it and treating it as an internal API.
Internal API cannot be broken either to ensure there is a safe rolling upgrade/downgrade plan. So version 0.16 would need to add alternative implementation while fully supporting the old SegmentWithOvershadowedStatus, and only 0.17 can remove SegmentWithOvershadowedStatus.
I think the main reason why I proposed mutable isOvershadowed field was that I initially proposed to compute it lazily, on demand in SQLMetadataSegmentManager. However, later I agreed (in this thread, actually) that it can also be eager. So I think immutable would work fine.
I'm also curious about the benefit we can when DataSegment becomes mutable. Is there anything else except memory savings?
Memory and concurrency (see #7595).
So what about the following:
- Immutable, but extensible
DataSegment. - Immutable
SegmentWithOvershadowedStatuswhich extendsDataSegment(note: they also have different JSON representations). - Although immutable, both are decidedly containers, not "data classes". They both prohibit
equals()andhashCode()as described here.
Note that I unblocked #7425 only on the condition that people agree with the proposed approach and it's being implemented immediately: #7425 (comment). If I knew that new round of debate will start, I wouldn't unblock that PR and insisted on completely resolving that question before merging.
@leventov thank you for additional context. I didn't notice this before. This sounds like Both https://github.com/apache/incubator-druid/pull/7425 and https://github.com/apache/incubator-druid/pull/7595 are supposed to be done in a single PR, but they are separate for the sake of convenience of the author and reviewers. And I like to avoid two potential problems in https://github.com/apache/incubator-druid/pull/7425, i.e., slow API performance and internal API mismatch between versions. So, I think it makes sense to add this to 0.15.0 as long as https://github.com/apache/incubator-druid/pull/7595 won't take long time.
So what about the following:
- Immutable, but extensible DataSegment.
- Immutable SegmentWithOvershadowedStatus which extends DataSegment (note: they also have different JSON representations).
- Although immutable, both are decidedly containers, not "data classes". They both prohibit equals() and hashCode() as described here.
Your suggestion sounds good to me.
Memory and concurrency (see #7595).
https://github.com/apache/incubator-druid/pull/7595 looks about eager computation of overshadowed segments rather than mutable segments. Would you tell me more how the mutable segment helps concurrency?
@leventov @jihoonson @gianm thanks for the discussion, I will work on this PR tomorrow and hopefully we can get it closed before 0.15.
@jihoonson the concurrency discussion started here: https://github.com/apache/incubator-druid/pull/7595#discussion_r282159218. @jon-wei argued that type of concurrent inconsistency is OK, but I'm not sure and don't want to verify that. That issue can be worked around relatively easily by creating an object DataSourcesAndOvershadowedSegments inside SQLSegmentMetadataManager and update a field with it atomically, rather than having two separate fields dataSources and overshadowedSegments, but this problem naturally goes away itself when SQLSegmentMetadataManager will store SegmentWithOvershadowedStatus objects in dataSources in the first place.
Immutable SegmentWithOvershadowedStatus which extends DataSegment (note: they also have different JSON representations).
I guess this means we need to get rid of DataSegmentInterner (DataSegment objects cannot be interned effectively if they are being subclassed and have overshadowed fields that need to be changed). So we would want to add some other way of sharing objects between the broker's timeline (ServerSelector) and the metadata segment cache (MetadataSegmentView). We could perhaps have those two things store SegmentId objects rather than DataSegment objects, and have them use a shared registry object that stores the actual DataSegments.
However, there are some wrinkles here:
- The 'shared registry object' would probably be some kind of wrapper around
Map<SegmentId, SegmentWithOvershadowedStatus>. But when ServerSelector needs to register a DataSegment, it doesn't have a valid overshadowed status. (It's just coming from a segment announcement, not a timeline, and 'overshadowed status' only makes sense in the context of a timeline.) - There are not one, but two timelines: the timeline of published segments, and the timeline of available segments. They don't always match up 100%. So in the single SegmentWithOvershadowedStatus object, which timeline is being referred to?
One way to answer these questions is:
- The 'shared registry' should wrap a
Map<SegmentId, DataSegment>, where the DataSegments may be SegmentWithOvershadowedStatus or they may be the base class DataSegment. If they are the base class, it means we lack information about overshadowed status (maybe, so far, we've only seen it in a segment announcement). If they are the class SegmentWithOvershadowedStatus, it means we do have that information. We'll need to differentiate withinstanceofchecks. - It should refer to the timeline of published segments. (That was the original motivation for introducing all this stuff in the first place.)
What do you all think - @leventov, @surekhasaharan, @jihoonson, @jon-wei?
By the way, the JSON representations would just be different in that SegmentWithOvershadowedStatus has some extra fields, right?
Although immutable, both are decidedly containers, not "data classes". They both prohibit equals() and hashCode() as described here (https://github.com/apache/incubator-druid/issues/6358#issuecomment-489102183).
What do you mean by 'prohibit' @leventov? I followed the link, and I don't see a suggestion about prohibiting equals and hashCode. (Just about prohibiting using DataSegments as keys in a map, which seems reasonable, given that usually people probably meant to use SegmentId.)
Regarding interning - we have to get rid of them anyway: #7395 explains how. If a segment first appears in BrokerServerView, it can be created as SegmentWithOvershadowedStatus(isOvershadowed=false). Then if it later appears in MetadataSegmentView and it is not actually overshadowed, we reuse the existing object by probing BrokerServerView. If the arrived object has isOvershadowed=true, we just lose the opportunity to deduplicate this segment, but we expect it for the minority of segments, so that's fine.
Regarding SegmentWithOvershadowedStatus(isOvershadowed=false) objects in BrokerServerView while the actual status is unknown: it seems weird at first glance but it's actually fine. The rule is that to probe isOvershadowed status we should always go through MetadataSegmentView. To guard against misuse, we can prohibit casting to SegmentWithOvershadowedStatus in the codebase on the Checkstyle or IntelliJ level.
What do you mean by 'prohibit' @leventov? I followed the link, and I don't see a suggestion about prohibiting equals and hashCode. (Just about prohibiting using DataSegments as keys in a map, which seems reasonable, given that usually people probably meant to use SegmentId.)
Sorry, I didn't re-check what did I propose there. No, I don't suggest to prohibit. I suggest exactly what is written in https://github.com/apache/incubator-druid/issues/6358#issuecomment-489102183.
@leventov, I think I understand what you are suggesting: that BrokerServerView and MetadataSegmentView might both create their own DataSegment objects (well, really, they'd create a subclass: SegmentWithOvershadowedStatus) and, for such objects where (a) isOvershadowed=false and (b) they were first created by BrokerServerView, the objects will be shared because MetadataSegmentView will check with BrokerServerView to see if it has any reusable objects. (Or, perhaps, [b] might not be a requirement, if the checking is bidirectional: BrokerServerView could also check with MetadataSegmentView.)
It sounds fine, but I think keeping SegmentWithOvershadowedStatus as a wrapper object makes more sense. There's some additional pointer overhead, but it should be low. And there are benefits:
- The wrapper object approach allows DataSegment objects to always be shared (not just when
overshadowed=false). - The wrapper object approach avoids the "weird at first glance but actually fine" characteristic in BrokerServerView or the need to protect against misuse.
- Senses of equality (or deep equality, as the case may be) can be murky when inheritance is involved. Is a SegmentWithOvershadowedStatus equal to a DataSegment if every field is equal other than
overshadowed? Which behavior is best probably depends on where you are in the code. Composition through wrappers makes it very clear how the comparison works.
I think these benefits outweigh the memory savings of removing one layer of wrapping in MetadataSegmentView.
What do you all think?
Side notes:
By the way, I do think the idea to switch from interners to probing-based reuse is good and we should do that (although it doesn't need to be a 0.15.0 blocker).
And on the topic of https://github.com/apache/incubator-druid/issues/6358#issuecomment-489102183, it sounds like a good idea to me (DataSegment's equals behavior is a perennial source of confusion; it generally makes more sense to use SegmentId) but it should be doable separately, and also doesn't need to be a 0.15.0 blocker. Maybe some piece of it might be implemented as part of these changes (the deeplyEquals / allDataEquals could be useful) but the structural inspection stuff is better suited for another day.
The wrapper object approach allows
DataSegmentobjects to always be shared
I realized that they can always be shared in my approach as well: MetadataSegmentView can "inject" the new version of a SegmentWithOvershadowedStatus (with overshadowed=true) inside BrokerServerView.
Senses of equality (or deep equality, as the case may be) can be murky when inheritance is involved. Is a SegmentWithOvershadowedStatus equal to a DataSegment if every field is equal other than overshadowed? Which behavior is best probably depends on where you are in the code. Composition through wrappers makes it very clear how the comparison works.
DataSegment already checks just the id field. Again, please stop thinking about DataSegment as a "data class" with well-defined equality. It's not. Keeping equals() implemented in it (as suggested here: https://github.com/apache/incubator-druid/issues/6358#issuecomment-489102183) itself needed only to enable some other memory-saving hacks (see the link). We should also prohibit explicit calls to segment.equals(otherSegment) - it's never reasonable. Either do segment.getId().equals(otherSegment.getId()), or segment.allDataEquals(otherSegment), where allDataEquals has firm semantics (e. g. of not comparing overshadowed).
Another problem with wrapper SegmentWithOvershadowedStatus is network overhead: even in compressed formats it will be higher than for a flat object.
For me, getting rid of wrapping SegmentWithOvershadowedStatus is the only blocker for 0.15 - I don't want wrapper SegmentWithOvershadowedStatus to slip into internal network API.
For me, getting rid of wrapping SegmentWithOvershadowedStatus is the only blocker for 0.15 - I don't want wrapper SegmentWithOvershadowedStatus to slip into internal network API.
For 0.15 scope, in the interest of unblocking the release I think the cleanest way to deal with this concern is to keep SegmentWithOvershadowedStatus as a wrapper, but add a custom Jackson serde such that it's serialized as if it were a subclass: all fields on the same level. This is pretty nice, since it means callers that expect a DataSegment can still get one (they'll just ignore the overshadowed field). Then we have flexibility to do whatever we want post-0.15 as far as subclass vs. wrapper, since the network API won't need to change.
DataSegment already checks just the id field. Again, please stop thinking about DataSegment as a "data class" with well-defined equality.
I was thinking of allDataEquals too -- the question being, should it consider a DataSegment instance and a SegmentWithOvershadowedStatus instance as equal or not? It's not clear to me right now which answer (yes or no) would be more useful to most callers. I guess it should be "yes" though since overshadowed isn't really "data".
should it consider a DataSegment instance and a SegmentWithOvershadowedStatus instance as equal or not? It's not clear to me right now which answer (yes or no) would be more useful to most callers. I guess it should be "yes" though since overshadowed isn't really "data".
"Yes" for several reasons: 1) Liskov substitution principle 2) overshadowed is not "metadata" because it's not stored in the DB which is the principle of allDataEquals - after all, we introduce allDataEquals to fix #6358 which is about the data stored in the DB.