https://slatedb.io logo
Handling resuming partially completed SR compactio...
# general
s
@Rohan @criccomini Now that we are aligned on the state management protocol, I will update the RFC. Now, as the next step on discussing handling the logic for resuming the partial SRs: I wanted to ask if it would be fine with having partially completed SRs in manifest or only the completed ones. With the compactionStatus field, we could support both the possibilities. cc: @almog
a
my preference is to only have completed ones in the manfiest - partial completeness seems like a compactor implementation detail
c
> my preference is to only have completed ones in the manfiest Strong +1
s
Ack. I will add a low level design based on this preference.
r
+1 to the above from me
s
I was looking at the code. I think we should persist the compaction in the submit_compaction() with empty job_attempts in the compactorEventHandler after validation completion and before starting the compaction.
Copy code
rust
    async fn submit_compaction(&mut self, compaction: Compaction) -> Result<(), SlateDBError> {
        let id = self.rand.rng().gen_uuid();
        tracing::Span::current().record("id", tracing::field::display(&id));
        // Compaction validation
        let result = self.state.submit_compaction(id, compaction.clone());
        // Persist compaction here
        match result {
            Ok(_) => {
                self.start_compaction(id, compaction).await?;
            }
            Err(err) => {
                warn!("invalid compaction: {:?}", err);
            }
        }
        Ok(())
    }
However, I think we should the active running compaction check should happen before starting the compaction.
Copy code
rust
async fn maybe_schedule_compactions(&mut self) -> Result<(), SlateDBError> {
        let compactions = self.scheduler.maybe_schedule_compaction(&self.state);
        for compaction in compactions.iter() {
            if self.state.num_compactions() >= self.options.max_concurrent_compactions {
                info!(
                    "already running {} compactions, which is at the max {}. Won't run compaction {:?}",
                    self.state.num_compactions(),
                    self.options.max_concurrent_compactions,
                    compaction
                );
                break;
            }
            self.submit_compaction(compaction.clone()).await?;
        }
        Ok(())
    }
r
not sure I follow, but I think we should just do all validation before writing the compaction to the state, and then write it if all the validation checks pass
s
> we should just do all validation before writing the compaction to the state Yes, that is my thought as well. As mentioned above in the code snippet, I think the compaction should be first persisted before calling the
start_compaction(id, compaction)
What if the compaction scheduled exceeds the threshold of active compactions? Should we persist it or drop it?
r
lets keep it simple and just drop it
c
We also need to validate compactions from external writers, which will need to happen before job execution.
s
Yes, I plan to persist all the compactions in the
submit_compaction()
method in the Compaction Event Handler. EXternal requests would be validated using the same ConflictChecker and compaction state validations before persisting.
c
I don't follow: are the third party clients going to run validation on the client side? Or is the compactor going to take the scheduled compaction from the external client (that's been persisted) and run conflict resolution again before submitting?
I might be missing something in how third parties interact with this protocol. LMK if what I'm saying makes sense.
s
Approach 1: I think the persistence of the compaction ( both for internal and external) should be owned by the Compaction Event Handler to avoid race conditions like compactions with same sources being persisted. In case we go ahead with external client persisting the compaction, we would need to have a conflict resolution logic between persisted compactions based on some criteria. Approach 2: I can think of is to do validations on every fileExists error by fetching the latest .compactor file while trying to persist the current compaction. This would ensure that if there were any external/internal compactions persisted, we would validate against them. In this approach SlateDb would run validations against both the internal/external compaction requests before persisting them. Does this make sense?
c
> Approach 1: I think the persistence of the compaction ( both for internal and external) should be owned by the Compaction Event Handler to avoid race conditions like compactions with same sources being persisted. In this approach, where and what would the external client write?
s
Client calls a function say
submit_external_compaction()
with the
CompactionRequest
that would have parameters like source L0 SSTs and source SRs.
submit_external_compaction()
validates the request and transforms it into a
Compaction
struct object. This object is then passed to a channel that is listened by the eventLoop. EventLoop would take care of persisting the request.
I will document this in a protocol and share in sometime as this is intertwined with persistence of internal and external compaction.
Added a low level design comprising of handling internal compaction persistence, external compaction request persistence and resuming compactions by compaction job during compaction execution.
c
But what if the client is on a separate machine from the event loop?
> - If latest .compactor compactor_epoch == current compactor epoch, reconcile the compactor_state and pass
new_compactions
object to Step(3). What if the step(3) execution discovers that there are invalid commpactions? Are they dropped? > - Writes the updated compacted_state to a blocking channel that would be listened and executed by the Compaction Event Handler. +1 for this approach > ### Persisting External Compactions This section seems to depend on sending external compaction requests through an in-memory channel. We want to support triggering compactions from the CLI, though, which will likely be running on a separate machine. I don't see how that can work if we depend on in-memory channels to pass external requests. Are you suggesting the CLI spin up a
Db
instance itself to write the compaction request? That would fence both the writer and compactor processes.
s
> What if the step(3) execution discovers that there are invalid commpactions? Are they dropped? yes. The invalid compactions in the
new_compactions
list would be dropped.
> But what if the client is on a separate machine from the event loop? Yes. That would be a problem because all the validations are done by the event loop. Either we would need a public API( which has it's own problems) or we would need to have the compaction validation logic available to all the clients so that the clients requests can be safely persisted.
c
My suggestion: clients write to .compactor file (or some request directory as @almog ) suggested. The compactor loop refreshes the .compactor on conflict and merges in requests (dropping invalid ones). (or polls the dir and drops invalid requests).
S3 is the API.
s
> This section seems to depend on sending external compaction requests through an in-memory channel. We want to support triggering compactions from the CLI, though, which will likely be running on a separate machine. I don't see how that can work if we depend on in-memory channels to pass external requests. Are you suggesting the CLI spin up a Db instance itself to write the compaction request? That would fence both the writer and compactor processes. No, it won't need a channel. It will write in sync to the .compactor after validating the compactor request. Compaction Event Loop is not involved.
c
I'm coming around to almog's idea that we have a dir...
Aghh I misread that sectionl.
Ok this makes sense to me
s
Copy code
rust
// API method signature uses the public struct directly
pub async fn submit_manual_compaction(
    &self, 
    source_ssts: Vec<String>,
    source_srs: Vec<String>                         
) -> Result<CompactionInfo, Error>
The submit_manual_compaction would look something like this. Any client(reader, writer, compactor) invokes this method. The validations would be made within this method and after sucessful validation it would write to the .compactor file active_compactions.
c
gotcha!
Ok I follow what you're saying now.
So the only trick is making sure the external client doesn't fence anyway (similar to how DbReader behaves)
I think we can probably avoid this by having the
admin.rs
instantiate what it needs directly rather than creating a full
Db
.
s
> So the only trick is making sure the external client doesn't fence anyway (similar to how DbReader behaves) Yes. Exactly!
c
This seems pretty straight forward. to KISS, let's keep hte requests in the .compaction file for now (instead of a separate dir on object storage).
We should probably have the compactor poll the .compactor file periodically to pick up newly scheduled compactions from external clients.
s
> I think we can probably avoid this by having the admin.rs instantiate what it needs directly rather than creating a full Db. I was thinking of using admin.rs for exposing cli commands and client interfaces. This method would serve as an internal interface that return a future. Upto the admin api whether to await or return the future.
c
Yep we've extablished this pattern for GC--we have a run_gc_once concept.
take a look at admin.rs and garbage_collector.rs to see how it's set up
we need a schedule_compaction_once or similar call in compactor and hten admin.rs can call it
s
> We should probably have the compactor poll the .compactor file periodically to pick up newly scheduled compactions from external clients. During the compactor initialisation phase(when manifest is polled), we will fetch both manifest and compaction_state. So, I don't think we will need a separate poller.
c
But if an external client adds a new compaction, the compactor won't see it until there's a conflict on its next compaction (which could be quite a while)
Aside: " Update "Protocol for State Management of Manifest and CompactionState" and "Summarised protocol" to reflect protocol based on design goals (Compaction persistence rfc #695 (comment))." this is done, right?
s
> Aside: " Update "Protocol for State Management of Manifest and CompactionState" and "Summarised protocol" to reflect protocol based on design goals (Compaction persistence rfc #695 (comment))." Yes. This is done. Updated the RFC.
c
(updating todo list on the rfc GH PR)
s
> (updating todo list on the rfc GH PR) I will create a todo list in the PR description and update the status. > But if an external client adds a new compaction, the compactor won't see it until there's a conflict on its next compaction (which could be quite a while) The conflict would happen quickly given that there would be multiple .compactor file write touch points.
c
🤔 doesn't the compactor only write to the manifest when it complets SR/SST writes?
s
Yes. But, we need a conflict on .compactor file because a compaction is added to .compactor file, right?
c
Yes. But what I'm saying is: 1. 1am today, external client writes new compaction to .compactor (it's trying to trigger a compaction) 2. <> 3. 1am tomorrow, writes happen and compaction triggers, which causes it to have a write conflict, refresh, and run the requested compaction. This is extreme, but the point is that the external client shouldn't need to wait for an unbounded perioid of time before it sees its compaction get executed.
IIRC, the compactor will reach a steady state if there are no further writes. Once that happens, no conflict will be triggered until writes occur and the scheduler in the compactor asks for a new compaction.
The current compactor loop only refreshes the manifest: _ = manifest_poll_ticker.tick() => { handler.handle_ticker().await; }
s
Ah..got it. Then it makes sense to have a periodic poller within the event loop that can also trigger the above protocol.
c
Awesome. Consider me +1 on your current external client proposal outline.
I think if @Rohan and @almog are ✅ on this, we can move forward with the RFC update
s
Nice! I have also added the flow for resuming the partially completed compactions. Can you also take a look over it?
c
Sure
> - Once on the relevant SST, go to the last block by iterating the indexes. Iterate to the lastKey of the last block of the SST. I'm partial to this since resumes are fairly infrequent and modifying metadata structures is pretty permanent. Not strongly opposed to the other approach, though.
a
+1 makes sense to me. to summarize remote requests we're basically just writing a new
.compactor
file by spinning up a non-fencing instance of the DB and calling the same methods that request a compaction from the compaction loop? that's pretty clean, I assume we'll have the compactor loop request compactions this way as well to keep it consistent?
c
Yup!
> Ignore completed L0 SSTs Won't we have to check all L0 SSTs since they are not range partitioned? So we'd have to open each L0, seek to key, and go from there?
s
> Won't we have to check all L0 SSTs since they are not range partitioned? So we'd have to open each L0, seek to key, and go from there? Each CompactionJob would persist the ids of the completed L0 SSTs during it's run. This would avoid open each L0 SST and seek the key.
c
> 3. This is done by doing a binary search on a SR to find the right SST partition and then iterating the blocks of the SST till we find the Entry. > [Note: A corner case: With monotonically overlapping SST ranges(specifically the last key), a key might be present across a contiguous range of SST in a SR] Can we always seek to the first entry for the key (the oldest seqnum for each key in each SR) and just let the merge iterator take care of deduping/dropping by calling .next() once to advance to the next key?
s
> Can we always seek to the first entry for the key (the oldest seqnum for each key in each SR) and just let the merge iterator take care of deduping/dropping by calling .next() once to advance to the next key? The entries in a SST of a SR would like this right after allowing versioning (key1, seq1), (key1, seq2), (key1, seq3) where seq1 > seq2, right?
c
I thought they were reverse sorted? (seq2, seq1, ..)
I could be wrong. I always get this confused.
s
Ah..I am confused as well. Let me check
Copy code
rust

impl Ord for MergeIteratorHeapEntry<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        // we'll wrap a Reverse in the BinaryHeap, so the cmp here is in increasing order.
        // after Reverse is wrapped, it will return the entries with higher seqnum first.
        (&self.next_kv.key, self.next_kv.seq).cmp(&(&other.next_kv.key, other.next_kv.seq))
    }
}
I think it return higher seqNum first for a given key.
c
That matches my recollection
But I'm not sure how it's stored in SST if there are multiple entries for the same key (this is the seqnum stuff @flaneur233 is working on)
s
Copy code
rust
   async fn load_manifest(&mut self) -> Result<(), SlateDBError> {
        self.manifest.refresh().await?;
        self.refresh_db_state().await?;
        Ok(())
    }

    async fn refresh_db_state(&mut self) -> Result<(), SlateDBError> {
        self.state
            .merge_remote_manifest(self.manifest.prepare_dirty()?);
        self.maybe_schedule_compactions().await?;
        Ok(())
    }
With reference to the earlier conversation on having a separate poller, The manifest poller refreshes the db_state that triggers a call to check if compactions need to be scheduled. So, I think we might not need a new poller.
c
Yea, but the maybe_schedule_compactions is only looking at DB state's SRs and SSTs. Those won't change if therea are no new writes. This is how the scheduler reaches a steady state.
The refresh needs to look at the .compactor file as well
r
At a high level the design makes sense to me. I'm not sure that using the .compactor file for requests will work though. My concern is around how the protocol will work in the presence of divergence of the schema version between the db and clients. It's pretty typical for CLIs to be on a different version from the db they're interacting with. Since the CLI will need to read-modify-write the compactor file, this means that it will write it with a different version of the schema. So, for example lets say the CLI is on some old version that doesn't know about field X which was added to the .compactor. We can take care to keep schemas backwards/forwards compatible, so the CLI would be able to read the .compactor file and add its request. But when it goes to write the update it will drop field X which corrupts the compactor state.
I think to mitigate this we'd want to go to the dir approach @almog suggested. Clients can write their requests to their own file. To get status they should be able to just read the .compactor file
Come to think of it this is a general problem with our approach to CLI/DB interaction 😬
c
Ohh, this is a great point..
I wonder if this is an issue tho? 🤔
either the CLI can read the .fbs or it can't
writes are trickier
It could lose some newer fields that were in the original file
r
yeah it's writes that are the problem. For example there's a CLI cmd to create a checkpoint, which mutates the manifest
One option for now is we can stamp the manifest with the version and forbid writes that move it backwards
c
Hmm.. maybe for now we just say CLI must use exact version of the files it's mutating...
Yep.. I was thinking of being even more draconian
r
yeah that'sa better actually
c
but I'm comfortable with forward only
r
you wouldn't want to brick the db because someone upgraded the CLI
c
IMO it's not horrible.. these are admin ops after all
yea exactly
r
I'll file a ticket
c
@Rohan where does that leave us on the .compactor mutation vs. change request dir?
r
I think with this model we can KISS and use the same file
c
That was my inclination
I'm very nervous about overcomplicating the object store protocols
(and schemas)
kewl
@Sujeet I think we can move forward then
r
I think we'll have to solve this problem at some point though. One of the nice things with slatedb is that you can run subsystems (readers, the writer, compactor) on isolated compute. With this change you're forced to upgrade them in lockstep
we can discuss on the ticket
c
Yea.. this is a tricky thing. Agree we can discuss in ticket. I think if we're pragmatic about it, it won't be too horrible to deal with.
c
Thanks!
So many important issues lol
r
seems to be scaling with the community 🙂
c
indeed
s
@criccomini I plan to refresh compaction_state as part of the
refresh_db_state
method. Then, do we need a separate poller?
@criccomini are we also good to move forward with the compaction resuming flow and the persistence flow?
c
Yep, I think that would work since that gets called through the manifest ticker periodically. If we refresh the compactor_state as well, we will see newly inserted compactions that way.
Yep, I think so. For those two, I'd suggest documenting the protocol in the RFC then getting feedback, just to be sure.
s
I have updated the RFC with the protocol.
@criccomini @Rohan can we close on the compaction state persistence RFC?
c
Yep, on my list to do one final pass. 🙂
r
there's a couple more items to hash out in the rfc, but I think we're close
s
Responded to the comments.