Skip to content

Implement database abstraction, error checking (ref #5907) - #6107

Merged
calmh merged 20 commits into
syncthing:masterfrom
calmh:dbastr3
Nov 29, 2019
Merged

calmh merged 20 commits into
syncthing:masterfrom
calmh:dbastr3

Conversation

@calmh

@calmh calmh commented Oct 25, 2019 •

Copy link
Copy Markdown
Member

So here's a slog of a PR ...

Purpose

This PR does two things, because one lead to the other:

  • Move the leveldb specific stuff into a small "backend" package that
    defines a backend interface and the leveldb implementation. This allows,
    potentially, in the future, switching the db implementation so another
    KV store should we wish to do so.

  • Add proper error handling all along the way. The db and backend
    packages are now errcheck clean. However, I drew the line at modifying
    the FileSet API in order to keep this manageable and not continue
    refactoring all of the rest of Syncthing. As such, the FileSet methods
    still panic on database errors, except for the "database is closed"
    error which is instead handled by silently returning as quickly as
    possible, with the assumption that we're anyway "on the way out".

Testing

I've been running with this for a few days and it passes at least some integration testing. That doesn't constitute heavy testing exactly and database changes are always scary. That said I think this already improves things as there was potential for, for example, silently failing to save a new folder ID and yet continuing on with life... That won't happen now.

"Pluggable backend"

That's not only a fantasy. Part of the purpose of this PR was to test another KV implementation, and I'm in fact running this by just dropping in a badger implementation in backend with no other changes and this seems fine so far. Whether we want to go with that or not is absolutely not decided but I like the ability to experiment.

calmh added 2 commits October 25, 2019 09:41
This PR does two things, because one lead to the other:

- Move the leveldb specific stuff into a small "backend" package that
defines a backend interface and the leveldb implementation. This allows,
potentially, in the future, switching the db implementation so another
KV store should we wish to do so.

- Add proper error handling all along the way. The db and backend
packages are now errcheck clean. However, I drew the line at modifying
the FileSet API in order to keep this manageable and not continue
refactoring all of the rest of Syncthing. As such, the FileSet methods
still panic on database errors, except for the "database is closed"
error which is instead handled by silently returning as quickly as
possible, with the assumption that we're anyway "on the way out".
Comment thread cmd/stindex/idxck.go Resolved
Comment thread lib/db/schemaupdater.go Resolved
Comment thread cmd/stindex/dumpsize.go Resolved
Comment thread lib/db/backend/leveldb_open.go Resolved
Comment thread cmd/stindex/dump.go Resolved
Comment thread lib/db/instance.go Resolved
Comment thread lib/db/instance.go Resolved
Comment thread lib/db/instance.go Resolved
Comment thread lib/db/transactions.go Resolved
Comment thread lib/db/transactions.go Resolved

@imsodin imsodin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I only had a quick look at the interfaces, no other review yet.

To me it's unexpected to have leveldb specific parts (e.g. Tuning) in the same place/package as the "generic interfaces". I would consider the interfaces part of the db, i.e. the db prescribes what a backend needs to implement, and then a db backend implements that separately.

Comment thread lib/db/backend/backend.go Resolved
Comment thread lib/db/backend/backend.go Resolved
Comment thread lib/db/backend/leveldb_backend.go Resolved
Comment thread lib/db/backend/leveldb_backend.go Resolved
Comment thread lib/db/backend/leveldb_backend.go Resolved
Comment thread lib/db/backend/leveldb_backend.go Resolved
Comment thread lib/db/backend/leveldb_test.go Resolved
Comment thread lib/db/instance.go Resolved
Comment thread lib/db/transactions.go Resolved
Comment thread lib/db/transactions.go Resolved
Comment thread lib/db/transactions.go Resolved
Comment thread lib/fs/mtimefs.go
Bytes(key string) (data []byte, ok bool)
PutBytes(key string, data []byte)
Delete(key string)
PutBytes(key string, data []byte) error

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Bytes() above could also return an error, oppose to "it's not there".

@AudriusButkevicius

Copy link
Copy Markdown
Member

What are we doing with this? Do you plan to finish this, or are you abandoning it?

@calmh

calmh commented Nov 5, 2019

Copy link
Copy Markdown
Member Author

Dude. Chill. I'm finishing it.

calmh added 3 commits November 6, 2019 08:31
* master:
  gui: New folder state "Local Additions" for receive-only (fixes syncthing#5968) (syncthing#6117)
  lib/model: Fix removal of a marker when there are still folders referencing it (syncthing#6114)
  build: I like long, complicated things, ok?
Comment thread lib/db/backend/leveldb_test.go Resolved
Comment thread lib/db/backend/leveldb_test.go Resolved
@calmh

calmh commented Nov 6, 2019

Copy link
Copy Markdown
Member Author

I adressed some of the review comments. Two things I deliberately haven't: panic()ing in the top level methods, and returning errors from NamespacedKV. The reason for that is that both of those result in cascading changes everywhere else -- refactoring the pulling loop to be able to shut down on database error, etc. etc. I think this is large enough as-is, and the behavior w.r.t. when we panic or not is the same as it was previously. We should do that refactor, but I'm afraid that if I do it as part of this PR we'll never get there.

@AudriusButkevicius AudriusButkevicius left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Too big to review in detail but clearly is heading in the right direction

Comment thread lib/db/set.go Outdated
if err := db.folderIdx.Delete([]byte(folder)); backend.IsClosed(err) {
return
} else if err != nil {
panic(err)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In theory all of this should be in a "transaction"?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

In principle... In practice that looks very infections once I start pulling the threads, almost the same as removing the top-level write operations completely. Let me see what I can do.

@AudriusButkevicius

Copy link
Copy Markdown
Member

Also unresolved the namespacedkv Bytes() comments as it seems they are not addressed, nor commented on.

In general, I think the reviewer should be resolving the comments once the discussion concludes or he agrees with the code changes provided. If you address a comment just drop a note as addressed so the reviewer knows its done.

Now I have to go double check every resolved comment to see if you left any feedback, if you did anything about it or not, as it's resolves with no message of what was done, did you ignore it, change code, or what.

@imsodin imsodin left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It's "Request changes" due to the checkFlush issue (#6107 (comment)), the rest is small stuff (I still didn't read everything in such detail).

And just rehashing because it wasn't addressed, feel free to address by dismissing ;) :

To me it's unexpected to have leveldb specific parts (e.g. Tuning) in the same place/package as the "generic interfaces". I would consider the interfaces part of the db, i.e. the db prescribes what a backend needs to implement, and then a db backend implements that separately.

Comment thread lib/db/backend/leveldb_backend.go Resolved
Comment thread lib/db/backend/leveldb_backend.go Outdated

func (t *leveldbTransaction) Delete(key []byte) error {
t.batch.Delete(key)
return wrapLeveldbErr(t.checkFlush())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

That reintroduces the problem with non-atomic db updates: Previously checkFlush was only called when all db operations that need to go through (or not) together were added to the batch. The only options I see are to either expose checkFlush, guaranteeing that the db is only written in those cases, or add a batch-like part to the interface.

@calmh calmh Nov 7, 2019 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is somewhat of an issue. Frankly one of the motivations behind this work is to move to something that provides real transactions (whether that's still goleveldb or something else) and I'm not convinced the current guarantees are what you think. Having multiple writes go out as a batch doesn't make it atomic, it just means there are multiple non-atomic writes happening in close temporal succession... I agree though that this change makes it strictly less atomic, whatever the state before.

For what it's worth the Badger interface is the same. Badger can at any point in a transaction return ErrTransactionTooBig at which point the thing to do is to commit it, create a new one, and continue onwards...

We don't create large transactions though, except in certain "internal" loops like when deleting a folder, as all other updates from the outside come in as small batches anyway.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok, maybe I shouldn't have brought up "atomic". However this clearly makes it worse, as before we were vulnerable to an inconsistent db while "there are multiple non-atomic writes happening in close temporal succession", now we are vulnerable during the entire time an implementation thinks it doesn't yet need to flush a transaction.

We don't create large transactions though, except in certain "internal" loops like when deleting a folder, as all other updates from the outside come in as small batches anyway.

Possibly, but that means we depend on implementation details, namely that model-side batching creates batches small enough that the backend implementation commits it as a whole.

And I don't know what the properties of a "real transactions" are - could you quickly explain what exactly you want there?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

What I want is for things to be atomically committed once we call commit, all or nothing. Currently there's no guarantee -- in fact, when there is a problem it would probably be quite unlikely for it to happen precisely between two batches. I mean, if there's an I/O error or the disk becomes full it will probably happen when we are in fact writing, like in the middle of a batch, not when we are not writing. :)

But I'm still thinking of the best way to handle this. We could add some sort of Checkpoint() method which is advisory that if a transaction / batch needs to be broken, this would be a good time to do it... (I.e., that current checkFlush)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What I want is for things to be atomically committed once we call commit, all or nothing. [...]

Cool, I very much want that too - that was my only theory, but I dismissed it as too unrealistic :D

Well, OOM, power-out, ... are still possibilities.

And how to do it: I was thinking about adding a simple *Batch type that contains keys to put/delete and a Apply(b *Batch) to the writer interface with the requirement that the writer must flush either before or after all the operations in batch.

@calmh calmh Nov 17, 2019 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I don't want more types, as Batch on top of Transaction on top of DB doesn't make sense on its own, imho. But I added the Checkpoint thing to be roughly equivalent with the already existing checkFlush. The behavior is sort of unspecified ("maybe it commits, maybe it doesn't, it might affect your reads") but that's what we already had and what we get from leveldb... With the limits in place you're pretty much guaranteed that if you call Checkpoint then the next write won't cause the flush, at least. A bit more guaranteed than it was before when it just used the same 4M limit for all calls.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

With leveldb I don't understand why the read ambiguity is needed. A leveldb snapshot is just the state of a the db at a specific point in time - we can't modify or don't release/resnapshot when flushing the buffer associated with the snapshot making up a read-write-transaction. The only unspecified behaviour I get is that we can't require "checkpointing" to only happen on calling Checkpoint, but just tell the implementation should checkpoint then if Checkpoint is called regularly. If we do require this ambiguity about future reads on Checkpoint, if anyway possible Checkpoint should get an additional return value that signifies whether the transaction has been broken thus (further reads can change) or not.

Another thing that should be stated explicitly: I assume Commit is final (i.e. no more writes can/should happen after calling it)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're right, I was mixing up things. There is a snapshot so there is no ambiguity. There is also no need for such an ambiguity in the future either as we can always have a read-snap + write-tran.

Comment thread lib/db/backend/leveldb_open.go Resolved
Comment thread lib/syncthing/utils.go
if err != nil {
return nil, err
}
return db.NewLowlevel(ldb), nil

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd like to use this change to make the interface of lib/syncthing deal with backend.Backend instead of *db.Lowlevel. Or do you want to defer that to a separate PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'm not sure we want to expose backend outside the db package. Can we explore later?

Comment thread lib/db/util_test.go Resolved
Comment thread lib/db/transactions.go Resolved
Comment thread lib/db/transactions.go Outdated
return keyBuf, nil, false, nil
}
if err != nil {
return nil, nil, false, err

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can still return keyBuf and thus also merge the two ifs. Sure we're probably panicking thus making reuse not really an issue, but it also doesn't hurt.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I really think that in this error case there is no continuation possible and it's cleaner to return all the nils to indicate that all bets are off at this point. Returning the keybuf, so far as it indicates anything at all, indicates that just this little thing didn't work out quite right but please continue calling more db functions, which isn't really the thing...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

My point is that I believe the distinction (whether returning nil or keyBuf) really doesn't matter at all when err != nil and I consider a second, separate if branche noise that reduces readability. I don't think anyone would even look at keyBuf when encountering an error, even less go like "lets do something drastic if err != nil, unless keyBuf != nil, then try to recover somehow, because apparently they want me to keep using that buffer".

@calmh calmh Nov 7, 2019 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

OK, fair. To me this looks a little less clear because we're doing if err != nil || ! ok { return ... err } and err might in fact be nil but 🤷‍♂

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good point too - might have asked Audrius for a third opinion before going through, but maybe it's just as well to stop bikeshedding at this point (sorry about that ;) ).

Comment thread lib/db/transactions.go Resolved
Comment thread lib/db/set.go Resolved
Comment thread lib/db/set.go Resolved
@calmh

calmh commented Nov 7, 2019

Copy link
Copy Markdown
Member Author

@AudriusButkevicius yeah sorry about the resolvingness, that was the wrong thing to do.

As for namedspacedkv I've tried to answer that a couple of times. :) I'm deliberately avoiding to change the external API of the db package to return errors where we currently don't, as that rabbit whole goes deep...

@AudriusButkevicius

Copy link
Copy Markdown
Member

I think the namespaced change should be a very shallow rabbit hole, but we can always fix it later.

* master:
  docker: Add stdiscosrv and strelaysrv Dockerfiles (syncthing#6143)
  lib/protocol: Buffer allocation when compressing (fixes syncthing#6146) (syncthing#6147)
  golang-ci: Upgrade, skipping the white space complainer
  all: Cleanups enabled by Go 1.12
  lib/tlsutil: Remove Go 1.12 TLS 1.3 beta opt-in
  lib/api: Make theme paths relative (syncthing#6142)
  gui, lib/api: Adds support for prefers-color-scheme (fixes syncthing#6115)
  lib/api: Reset mtime after theme change (fixes syncthing#5810) (syncthing#6140)
  lib/model: Remove some testing deadlocks (syncthing#6138)
  lib/model: Add test for previous commit
  lib/model: Add initial deviceStatRefs on model creation (fixes syncthing#6136) (syncthing#6137)
  lib/model: Add folders on start in model (syncthing#6135)
  cmd/stbench: rm -r cmd/stbench (syncthing#6131)
  lib/api: Slightly unflake TestCSRFRequired by allowing longer timeout
  Fix bufferpool puts (ref syncthing#4976) (syncthing#6125)
  all: Remove dead code, fix lost msgLen checks (syncthing#6129)
  lib/upnp: Fix outdated comment (syncthing#6110)
* master:
  golang-ci: Skip "cognitive complexity" check for now
  lib/model: Prevent cleanup-race in testing (ref syncthing#6152) (syncthing#6155)
  gui: Decrease padding on the panel and modal bodies (syncthing#6153)
  lib/model: In tests prevent goroutine leaks and increase timeouts (syncthing#6152)
  lib/model: Simplify pull error/retry logic (fixes syncthing#6139) (syncthing#6141)
@calmh

calmh commented Nov 18, 2019

Copy link
Copy Markdown
Member Author

@imsodin About Tuning, I'm not sure how to handle that. At the moment I pretended it was a general thing that other potential databases could support. But if the leveldb comes from the backend package, that's where the type needs to live... Having it at the db level would be an import cycle. I guess the leveldb backend could be a package of its own? That would leave the backend package pretty much just a couple of interfaces and make it harder to do things like reuse tests.

@imsodin

imsodin commented Nov 18, 2019

Copy link
Copy Markdown
Member

My proposal may be more skirting than solving the issue, but I'd still like it better than the current state: Remove the "pseude-backend-agnostic" backend.Open and backend.OpenMemory and readd db.Open and db.OpenMemory that directly call the specific db.OpenLevelDB/db.OpenLevelMemory.

@calmh

calmh commented Nov 18, 2019

Copy link
Copy Markdown
Member Author

My point in having the backend package to begin with is to make sure that there is no dependency from the larger db package directly to an implementation -- it can only come via the Backend interface, and the backend package itself is quite light as it's just the low level wrapper types. I don't think removing the backend package and moving all the types up one level improves the situation really, or I'm not understanding what you're suggesting.

imsodin
imsodin previously approved these changes Nov 19, 2019

@imsodin imsodin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I have clearly gone confused in my last comment, that proposal doesn't make sense. I am fine with the current state, as my Tuning comments are entirely cosmetic/matter of taste.

Is it correct that the purpose of db.Open is that if we exchange the backend, any calls opening the backend don't need to be changed?

@calmh

calmh commented Nov 24, 2019

Copy link
Copy Markdown
Member Author

That was my intention... I think from a user perspective we should only have kind of database at any given point. We might need to have an internal migration step if we do change the backend, but that should be essentially invisible from the outside...

@AudriusButkevicius
AudriusButkevicius dismissed stale reviews from imsodin and themself via 912253e November 26, 2019 07:42
@calmh
calmh merged commit c71116e into syncthing:master Nov 29, 2019
@calmh
calmh deleted the dbastr3 branch November 29, 2019 08:11
@calmh calmh added this to the v1.3.3 milestone Dec 5, 2019
@st-review st-review added the frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion label Nov 29, 2020
@syncthing syncthing locked and limited conversation to collaborators Nov 29, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants