Skip to content

lib: Apply config changes sequentially (ref #5298) - #7188

Merged
calmh merged 21 commits into
syncthing:mainfrom
imsodin:lib/configQueue
Jan 15, 2021
Merged

calmh merged 21 commits into
syncthing:mainfrom
imsodin:lib/configQueue

Conversation

@imsodin

@imsodin imsodin commented Dec 10, 2020

Copy link
Copy Markdown
Member

This is a proposal to make config changes in the current system less prone to races. It is thus related to #5298, however clearly does not address all the issues brought up there nor is it intending to.

It was prompted by the review comment about the order of initialising folders in the model and subscribing to config changes here: #7150 (comment)
That's inherently racy as it is, regardless of the order in which order it's done.

The proposed change here is that changes to the config only go ahead once all calls to .CommitConfiguration due to the previous change returned. If multiple config changes are outstanding, they will applied in the same order as the config change method (e.g. SetFolder) was called.
In addition with .Subscribe returning the currently active config, this allows a subscriber to subscribe to config changes, use the returned config for initialisation, and then start processing config changes. Thus starting with subscribing, they get all config changes sequentially in the correct order. Which I have done for model.

The obvious potential for problems here is locking. Previously anyone changing the config was only blocked until all previous config changes were dispatched asynchronously. Now blocking happens until all previous config changes took effect. If a subscriber is changing the config while holding a lock, that the subscriber also acquires on CommitConfiguration, that can deadlock. However doing that is also problematic today (can cause concurrent CommitConfiguration calls, which is also very bad) and we are aware of it, as e.g. evident in this comment:

	// Needs to happen outside of the fmut, as can cause CommitConfiguration

I added an explicit clause to the comment on the Committer interface, which obviously doesn't guarantee anything, but might increase awareness.

@calmh calmh 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.

Hmm

Comment thread lib/config/wrapper.go Resolved
Comment thread lib/config/wrapper.go Resolved
@imsodin

imsodin commented Dec 10, 2020

Copy link
Copy Markdown
Member Author

Hmm

Actually I wanted to talk about that (the concept) mainly. I just started to explain what I had in mind without code, and thought that wouldn't be comprehensible. Thus I created an explanation plus code to compare if the explanation isn't fully comprehensible.
I guess the review (thanks) means that at the least you didn't immediately think of a catch that invalidates the concept :)

@calmh

calmh commented Dec 10, 2020

Copy link
Copy Markdown
Member

I think the concept is sound. In general I think 1) starting a subscription, 2) getting the config, 3) continuing with life, should be a working sequence of operations for a subscriber even without this, as long as you're guaranteed to get notifications of all config changes that happen after the subscribe call returns. However, sequencing all config changes so that they are actually applied in the order they were asked for still seems worthwhile.

@imsodin

imsodin commented Dec 10, 2020

Copy link
Copy Markdown
Member Author

I refactored (rewrote) as suggested with a buffered chan. There's still a bit of machinery as I didn't want to just spawn a goroutine on Wrap that's never terminated (neither do I want config to be a service). The machinery seemed sound and understandable while writing, I hope it stands the test of review (and/or a nights sleep and looking at it again) :)

@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.

So I understand what this tries to do, but I doubt it squashes a lot of bugs.

I think our bigger problem is things like

cfg = wcfg.Copy()
cfg.Fiddle = true
wcfg.Save(...)

which would not be solved by this, because someone else might have done SetFolders between Copy() and Save() which would now be lost.

The same problem applies at a smaller level too, whereby

devs := wcfg.Devices()
devs.forEach { it.Fiddle = true }
wcfg.SetDevices(devs)

Suddenly loses any devices added between Devices() and SetDevices().

The few ways I can think of solving this is turning config modification around.
All the types you read now like Devices() etc are immutable (probably return interfaces),
and the only way to mutate stuff is to do something like:

wcfg.Modify(func (cfg config.Configuration) {
    cfg.Fiddle = true
})

or

leImmutableDevice.Modify(func (mutable)  {
   mutable.Fiddle = true
})

which is obviously serialized and potentially blocking, and probably PITA to use.

The other option would be remove ability to modify collections in bulk.

So no SetDevices, just AddDevice/RemoveDevice etc, then each struct gains a version, and on each read/modify/write we check if the version being written for this device matches the version currently in the config to catch outdated data writes, and prevent those.
Sprinkle retry logging everywhere.

Or idk, switch to some sort of CRDT library, plus counters?

Comment thread lib/config/wrapper.go Outdated
// Replace swaps the current configuration object for the given one.
func (w *wrapper) Replace(cfg Configuration) (Waiter, error) {
return w.replaceQueued(func() (Waiter, error) {
return w.replaceLocked(cfg.Copy())

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 know this doesn't affect this implementation, but in all of the functions, you probably want to copy the inputs
before you create the closure, just in case there is a reference to the same variable in some other routine that is not blocked by replaceQueued and is happily fiddling with the inputs.

Comment thread lib/config/wrapper.go Outdated
select {
case e = <-w.queue:
default:
w.queueMut.Unlock()

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 don't think you need the lock for the queue, as it's only set on initialization, so the struct member is never written to, just read.

@imsodin

imsodin commented Dec 12, 2020

Copy link
Copy Markdown
Member Author

So I understand what this tries to do, but I doubt it squashes a lot of bugs.

I agree. What you explained is a much bigger source of bugs. However solving it is also hard, while this is simple, and can happen now. I do believe the issue solved here might realistically cause bugs at startup, as it's quite realistic that a user changes stuff in the UI while folders are still rebuilding metadata. That immeadiately creates a race between handling folders in serve and CommitConfiguration.

Suddenly loses any devices added between Devices() and SetDevices().

Not that it changes much, but SetDevices is more like AddOrReplaceDevices: It doesn't remove devices not in the given device-list.

@calmh

calmh commented Dec 21, 2020 •

Copy link
Copy Markdown
Member

I see the thing with avoiding a serve() method, but it's a new design that we don't have anywhere else that's less easy to see is obviously correct. I think having an actual serve loop and combining that with Audrius' API suggestion would be better. That is, something like

type Wrapper struct {
  queue chan func(*Configuration)
  ...
} // there can be only one Wrapper instance

func (w* Wrapper) Serve() {
  for fn := range funcs { // actually a select probably
    fn(&w.cfg) // mutates
    // notify subscribers
    // save
  }
}

We can then be sure that things are serialized because there is only the one loop, and it can do things like set a timer to do a save one second after a config change, so multiple changes get aggregated, etc...

We could still have methods like RemoveDevice and SetDevice. If SetDevice takes a device config it's not 100% safe against multiple mutators touching the same device at the same time, but really that's a design error regardless. If we really care then the Set... functions could of course take mutator functions like func(*DeviceConfiguration) and such to do the actual tweaking of only specific attributes...

@imsodin

imsodin commented Dec 26, 2020

Copy link
Copy Markdown
Member Author

Now config.wrapper is a service and modification happens through

type ModifyFunction func(*Configuration) bool

	Modify(ModifyFunction) (Waiter, error)

The end state is quite palatable, the diff... less so. Though a lot of it is boilerplate in tests.

@acolomb

acolomb commented Dec 28, 2020

Copy link
Copy Markdown
Member

Sorry if this is not directly related, but I read about possibly aggregating config changes before calling CommitConfiguration() above. I found one place where that might more easily trigger an existing bug:

    		// Ignored folder was removed, reconnect to retrigger the prompt.
		if !toCfg.Paused && len(fromCfg.IgnoredFolders) > len(toCfg.IgnoredFolders) {
			closeDevices = append(closeDevices, deviceID)
		}

If a folder is unignored and another one ignored in the same modification cycle, this check will not notice and neglect to replace the connection. I don't see an easy way except a deep comparison to catch this.

@imsodin

imsodin commented Jan 4, 2021

Copy link
Copy Markdown
Member Author

I briefly considered aggregating config changes, but dropped that thought quickly because of various possible problems like the one you mentioned. I am not aware of ever mentioning that though. In this issue the only mentioning of aggregating is calmh's suggestion to defer saving the config (as in saving to file), which is independent of CommitConfiguration.

@imsodin

imsodin commented Jan 4, 2021

Copy link
Copy Markdown
Member Author

The new config wrapper service saves the config every 5 seconds if there are any changes now. Thus I removed all the .Save calls that did not act on the error except for logging. Explicitly calling .Save is still possible and used in the rest api, where an error is returned if saving fails.

The PR is ready from my side.

@calmh calmh 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 like this

Comment thread lib/config/wrapper.go Outdated

w.mut.Lock()
to := w.cfg.Copy()
if e.modifyFunc(&to) {

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.

As an alternative to returning a boolean we could serialize the config before and after the function call and compare to see if they changed something relevant or not. Then perhaps the modifier could/should return an error, for cases where it starts modifying the config but then realizes something went wrong and needs to bail out... but if that is not a thing that can happen currently we could leave the modifier without return value?

@imsodin imsodin Jan 13, 2021 •

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.

It seems a bit ugly to me to serialize or reflect to see if the config changed, when the caller knows whether they changed the config or not. Not that it matters performance wise. Well that's my reasoning, I am not attached to either solution though :)

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 was thinking it a bit ugly that I had to say whether I modified the config or not, when the config is there so the caller can plainly see if I did or not. :) It also wasn't 100% certain what the bool return meant at first glance.

Since it's just for saving we could even just remember the last serialized version and when going to save check if it's the same and then skip it.

But if there are cases where we start changing the config and then return false because we change our mind then this is legitimate. (I didn't check if we ever do that, some of the auto accept and introducer stuff is convoluted.)

(I'm also not heavily invested in this, it's fine as is, really.)

@imsodin imsodin Jan 14, 2021 •

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.

There's a bit of ugliness everywhere :)

Since it's just for saving we could even just remember the last serialized version and when going to save check if it's the same and then skip it.

It's also to skip the subscriber verify and commit stages if unchanged.

But if there are cases where we start changing the config and then return false because we change our mind then this is legitimate. (I didn't check if we ever do that, some of the auto accept and introducer stuff is convoluted.)

We do. Previously it was a bunch of conditions based on reading the config to determine if we need to change something, then call some Wrapper.Set... method. Now all of this is a single call to Wrapper.Modify, the conditions check the config obtained as an argument from Wrapper.Modify. Still, we can use the same conditions to just return early without changes and let the wrapper realize that we didn't change anything on its own.

It also wasn't 100% certain what the bool return meant at first glance.

That tips it in favor of not having a bool to me: Less potential for confusion.

Comment thread lib/config/wrapper.go
Comment on lines +259 to +273
done := make(chan struct{})
go func() {
waiter.Wait()
close(done)
}()
select {
case <-done:
if !saveTimerRunning {
saveTimer.Reset(minSaveInterval)
saveTimerRunning = true
}
case <-ctx.Done():
return ctx.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.

Seems to me we could start the save timer directly when the modify returns and save some small complexity?

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.

Waiting for done happens to serialize modifications, i.e. only process a change once the previous one is fully in effect. Using that to restart the timer only afterward is just a side-effect. However regardless of complexity, starting it immediatly on the change feels like the better call: I don't see any reason to e.g. wait for a slow CommitConfiguration before saving.

Comment thread lib/syncthing/syncthing.go Outdated
a.mainService.Add(connectionsService)

// Candidate builds always run with usage reporting.
a.cfg.Modify(func(cfg *config.Configuration) bool {

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.

Are we sure mainService is running at this point? If not, this will hang, right?

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.

Yes and yes. Starting the api in this same function would already hang: It's waiting for the server to come up.

Comment thread lib/config/commit_test.go Outdated
t.Helper()
waiter, err := w.Modify(func(cfg *Configuration) bool {
waiter, err := w.Modify(func(cfg *Configuration) {
cfg = &to

@calmh calmh Jan 14, 2021 •

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.

This can't possibly work? Maybe *cfg = to but why doesn't anything fail due to this?

Comment thread lib/config/commit_test.go Outdated

_, err := w.Modify(func(cfg *Configuration) bool {
_, err := w.Modify(func(cfg *Configuration) {
cfg = &Configuration{Version: 3}

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.

Likewise

t.Helper()
waiter, err := w.Modify(func(cfg *config.Configuration) bool {
waiter, err := w.Modify(func(cfg *config.Configuration) {
*cfg = to

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.

👍

@calmh calmh 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.

LGTM apart from that which is impossible

@imsodin

imsodin commented Jan 14, 2021

Copy link
Copy Markdown
Member Author

The explanation for the impossibility: The entire test file with the "defect" is one large no-op. The only test within is skipped. I was unable to make the test fail (after fixing), so I'll unskip it to see what CI has to say.

@calmh

calmh commented Jan 14, 2021

Copy link
Copy Markdown
Member

Aah it's TestReplaceCommit! I remember that one, I think I was the one finally adding the skip. 😬

@imsodin

imsodin commented Jan 15, 2021

Copy link
Copy Markdown
Member Author

And, do you want to give it a new chance? Or is it too 😬

@calmh

calmh commented Jan 15, 2021

Copy link
Copy Markdown
Member

Who knows, this change might even fix it?! Let's see.

@calmh
calmh merged commit f63cdbf into syncthing:main Jan 15, 2021
@imsodin
imsodin deleted the lib/configQueue branch January 15, 2021 19:43
Comment thread cmd/syncthing/main.go
// environment variable is set.

if build.IsCandidate && !upgrade.DisabledByCompilation && !runtimeOptions.NoUpgrade {
l.Infoln("Automatic upgrade is always enabled for candidate releases.")

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.

This deadlocks because we're not running the service yet...

calmh added a commit to calmh/syncthing that referenced this pull request Jan 16, 2021
@calmh calmh added this to the v1.14.0 milestone Feb 4, 2021
@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 Jan 16, 2022
@syncthing syncthing locked and limited conversation to collaborators Jan 16, 2022
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