lnd icon indicating copy to clipboard operation
lnd copied to clipboard

[1/4] - protofsm: add new package for driving generic protocol FSMs

Open Roasbeef opened this issue 1 year ago • 12 comments

In this PR, we create a new package, protofsm which is intended to abstract away from something we've done dozens of time in the daemon: create a new event-drive protocol FSM. One example of this is the co-op close state machine, and also the channel state machine itself.

This packages picks out the common themes of:

  • clear states and transitions between them
  • calling out to special daemon adapters for I/O such as transaction broadcast or sending a message to a peer
  • cleaning up after state machine execution
  • notifying relevant callers of updates to the state machine

The goal of this PR, is that devs can now implement a state machine based off of this primary interface:

// State defines an abstract state along, namely its state transition function
// that takes as input an event and an environment, and returns a state
// transition (next state, and set of events to emit). As state can also either
// be terminal, or not, a terminal event causes state execution to halt.
type State[Event any, Env Environment] interface {
	// ProcessEvent takes an event and an environment, and returns a new
	// state transition. This will be iteratively called until either a
	// terminal state is reached, or no further internal events are
	// emitted.
	ProcessEvent(event Event, env Env) (*StateTransition[Event, Env], error)

	// IsTerminal returns true if this state is terminal, and false otherwise.
	IsTerminal() bool
}

With their focus being only on each state transition, rather than all the boiler plate involved (processing new events, advancing to completion, doing I/O, etc, etc).

Instead, they just make their states, then create the state machine given the starting state and env. The only other custom component needed is something capable of mapping wire messages or other events from the "outside world" into the domain of the state machine.

The set of types is based on a pseudo sum type system wherein you declare an interface, make the sole method private, then create other instances based on that interface. This restricts call sites (must pass in that interface) type, and with some tooling, exhaustive matching can also be enforced via a linter.

The best way to get a hang of the pattern proposed here is to check out the tests. They make a mock state machine, and then use the new executor to drive it to completion. You'll also get a view of how the code will actually look, with the focus being on the: input event, current state, and output transition (can also emit events to drive itself forward).

Roasbeef avatar Jan 03 '24 01:01 Roasbeef

Pull reviewers stats

Stats of the last 30 days for lnd:

User Total reviews Time to review Total comments
yyforyongyu
🥇
6
▀▀▀
3d 19h 57m
▀▀▀▀▀
3
Roasbeef
🥈
5
▀▀▀
1d 18h 46m
▀▀
18
▀▀▀▀▀▀▀
guggero
🥉
4
▀▀
1d 7h 51m
▀▀
3
bhandras
2
3h 27m
0
calvinrzachman
1
6m
1
ziggie1984
1
20h 14m
0

github-actions[bot] avatar Jan 03 '24 02:01 github-actions[bot]

we could make StateMachine an interface,

Why do you think this should be an interface? The goal here is to provide a generic implementation that can drive any FSM, which is defined from that starting/initial state, and all the state transition functions. If you look at the test, it takes that mock state machine, and is able to drive that with the shared semantics of: terminal states, clean up functions, pure state transitions that emit any side effects as events, etc.

and leave the implementations of executeDaemonEvent to specific subsystems

The goal of those was to implement all the side effects we'd ever need in a single place. The daemon events added were just the ones I needed to implement the new co-op close state machine nearly from scratch. I think if we look at all the state machines we've written in the codebase, maybe there's ~10 daemon level adapters that are used continuously. One that's missing right now is requesting to be notified of something confirming.

Roasbeef avatar Jan 04 '24 00:01 Roasbeef

[!IMPORTANT]

Review skipped

Auto reviews are limited to specific labels.

Labels to auto review (1)
  • llm-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Jan 24 '24 02:01 coderabbitai[bot]

PTAL.

Roasbeef avatar Feb 06 '24 03:02 Roasbeef

Pushed up a new set of commits with some bug fixes and some additional functionality that came in handy when starting to hook up the new RBF coop close state machine to the peer struct.

Roasbeef avatar Feb 29 '24 22:02 Roasbeef

Updated the branch to remove DisableChannel as a syscall.

Roasbeef avatar Mar 06 '24 03:03 Roasbeef

On initial look, I'm not excited about this change.

I find the event-driven pattern less readable, with code blocks like this:

switch event.(type) {
	case *IncomingStfu:
		stfu := lnwire.Stfu{
			ChanID:    env.cid,
			Initiator: false,
		}
		send := protofsm.SendMsgEvent[Events]{
			Msgs:       []lnwire.Message{&stfu},
			TargetPeer: env.key,
			SendWhen:   fn.Some(env.canSend),
			PostSendEvent: fn.Some(
				Events(&gotoQuiescent{}), // gross
			),
		}

		return &protofsm.StateTransition[Events, *Env]{
			NextState: &Live{},
			NewEvents: fn.Some(
				protofsm.EmittedEvent[Events]{
					ExternalEvents: fn.Some(
						protofsm.DaemonEventSet{&send},
					),
				},
			),
		}, nil
	case *Initiate:
		stfu := lnwire.Stfu{
			ChanID:    env.cid,
			Initiator: true,
		}
		send := protofsm.SendMsgEvent[Events]{
			Msgs:       []lnwire.Message{&stfu},
			TargetPeer: env.key,
			SendWhen:   fn.Some(env.canSend),
			PostSendEvent: fn.Some(
				Events(&gotoAwaitingStfu{}), // gross
			),
		}

		return &protofsm.StateTransition[Events, *Env]{
			NextState: &Live{},
			NewEvents: fn.Some(
				protofsm.EmittedEvent[Events]{
					ExternalEvents: fn.Some(
						protofsm.DaemonEventSet{&send},
					),
				},
			),
		}, nil
	case *gotoAwaitingStfu:
		return &protofsm.StateTransition[Events, *Env]{
			NextState: &AwaitingStfu{},
			NewEvents: fn.None[protofsm.EmittedEvent[Events]](),
		}, nil
	case *gotoQuiescent:
		return &protofsm.StateTransition[Events, *Env]{
			NextState: &Quiescent{},
			NewEvents: fn.None[protofsm.EmittedEvent[Events]](),
		}, nil
	default:
		panic("impossible: invalid QuiescerEvent")
	}
}

instead of readable equivalent code something like this:

func (q *quiescer) sendStfu() error {
  stfu := lnwire.Stfu{
    ChanID:    env.cid,
    Initiator: q.state == Initiate,
  }
  if err := sendMsg(stfu); err != nil {
    return err
  }

  switch q.state {
    case IncomingStfu: q.state = Quiescent
    case Initiate:     q.state = AwaitingStfu
    default:           return fmt.Errorf("Invalid state change")
  }

  return nil
} 

I also find it more difficult to trace the flow of a program written with protofsm, with states and events and transitions being passed all over the place. I fear that debugging code written in this style may be much more difficult.

I find it quite confusing to think about what is executing at any given time. It seems each protofsm gets its own goroutine and daemon events also get their own goroutines. And the concurrency behavior is hidden from the protofsm user, which seems a disaster just waiting to happen.

Maybe I'm slower than others, but I've been trying to grok protofsm for a day now and I'm still not confident I fully grasp the intricacies. If I had to write or modify code in this style, I would not be confident that my code was bug-free.

morehouse avatar Mar 22 '24 21:03 morehouse

I also find it more difficult to trace the flow of a program written with protofsm, with states and events and transitions being passed all over the place. I fear that debugging code written in this style may be much more difficult.

I think the exact opposite is the case. With the framework as is, you have a standardized way of handling new state transitions, and you're forced to only maintain state within the protocol state definition, instead of a large struct with many variables that are only conditionally set if a certain state is present. You can examine a single state transition at a time, which clearly enumerates all its inputs and outputs.

You also don't need to re-write the very same executor loop (take in message, select on quit channel, apply state, loop agaon) that we've implemented several times over in the codebase. You just write your state transitions, and hand it off for handling.

Re debugging, my experience of debugging the rbf-coop state machine was pretty straight forward. The only state you need to wrangle with is the state in the protocol state. There's no concurrency within the state machine either, you're forced to implement everything with serial execution. You write unit tests for a given state transition, and can even employ property based testing to assert invariants re inputs/outputs.

I find it quite confusing to think about what is executing at any given time. It seems each protofsm gets its own goroutine and daemon events also get their own goroutines. And the concurrency behavior is hidden from the protofsm user, which seems a disaster just waiting to happen.

For a given state machine, everything is executed serially (we can also make it fully blocking, but nothing works like that today, since you don't want to block wire message ingestion). You define the transitions, then a generic executor handles mapping a wire message to a protocol state (just one example) to apply directly. The daemon events executed async are the very same ones that you'd normally spwan a goroutine to funnel a response into a channel (waiting for a spend/confirmation, etc). Transaction broadcast and wire message sending are synchronous.

Roasbeef avatar Apr 04 '24 18:04 Roasbeef

Haven't dived deep into that PR yet, but looking at the example, the top two transitions to Live don't look necessarily, and they can just go directly to AwaitingStfu. I think with that, you have a more accurate comparison:

  • s(Live, IncomingStfu) -> Quiescent.
  • s(Live, Initiate) -> AwaitingStfu.

So just two switch cases. There def is a bit more line noise going on there due to Go's lack basic type inference, but you can make some helper funcs to handle the defs.

Even with that they don't look quite equivalent, as one wants to wait on a certain state to send the message, while the other would unconditionally send it. As mentioned above, to compare directly, you'd also need to implement the executor/event loop for the second version, IIRC that hadn't yet been done.

Roasbeef avatar Apr 04 '24 18:04 Roasbeef

I think all of the comments here that @Roasbeef makes about protofsm in general are correct. I also think that the quiescence protofsm implementation exaggerates its costs and understates its benefits. I made certain choices in the quiescence implementation in order to bind the state transition itself when the message itself gets sent as opposed to when it gets staged to send. This may not be necessary -- It may not even be good!

The main benefit that is understated here is that it is often the case that a state machine is best expressed as a sum of products. Product types are very easily expressed in go via structs. Sums on the other hand are another story. The sealed interface pattern helps us model it better and makes it such that we can structurally guarantee the presence or absence of the associated state paremeters with the state itself rather than having a swiss cheese block of potentially valid or invalid pointers depending on the state selector row. It also allows us to explicitly enumerate the valid state transitions away from a particular state in a way that is very well organized and isolated. Could this be accomplished in another way? Yes. Is it better to do another way? I'm not so sure.

So while it was a very simple state machine to implement, quiescence is probably not an illustrative example of the leverage that protofsm can provide. The essential tradeoff being made is that protofsm adds a close to fixed overhead in terms of the naturality of expressing the state machine, and its benefits compound as the state machine itself gets bigger.

ProofOfKeags avatar Apr 04 '24 20:04 ProofOfKeags

@yyforyongyu: review reminder @crypt-iq: review reminder @morehouse: review reminder @roasbeef, remember to re-request review from reviewers when ready

lightninglabs-deploy avatar May 16 '24 23:05 lightninglabs-deploy

Rebased to get a fresh CI run going.

Roasbeef avatar Aug 02 '24 01:08 Roasbeef

@yyforyongyu: review reminder @crypt-iq: review reminder @morehouse: review reminder @proofofkeags: review reminder @roasbeef, remember to re-request review from reviewers when ready

lightninglabs-deploy avatar Aug 09 '24 02:08 lightninglabs-deploy