Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DynComms [0/n]: fn package additions #8653

Open
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

ProofOfKeags
Copy link
Collaborator

@ProofOfKeags ProofOfKeags commented Apr 15, 2024

NOTE: This change is part of a series implementing Dynamic Commitments.

Change Description

This adds some useful library functions that will allow us to capture patterns we often use throughout the codebase. None of the code in this PR has any direct bearing on Dynamic Commitments but it is generally useful infrastructure that will be assumed to be available in future PRs in the series.

Steps to Test

N/A

Pull Request Checklist

Testing

  • Your PR passes all CI checks.
  • Tests covering the positive and negative (error paths) are included.
  • Bug fixes contain tests triggering the bug to prevent regressions.

Code Style and Documentation

📝 Please see our Contribution Guidelines for further guidance.

Copy link

coderabbitai bot commented Apr 15, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

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

@ProofOfKeags ProofOfKeags requested review from a team, yyforyongyu and morehouse and removed request for a team April 15, 2024 20:54
@ProofOfKeags ProofOfKeags self-assigned this Apr 16, 2024
@ProofOfKeags ProofOfKeags added fn llm-review add to a PR to have an LLM bot review it labels Apr 16, 2024
@ProofOfKeags ProofOfKeags requested review from ziggie1984 and removed request for morehouse April 17, 2024 19:04
@ProofOfKeags ProofOfKeags force-pushed the fn-prim branch 2 times, most recently from 464abe1 to 22b714d Compare April 17, 2024 20:18
@ProofOfKeags ProofOfKeags changed the title Add fn tools DynComms [0/n]: fn package additions Apr 17, 2024
Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

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

LGTM, I wonder where you get the inspiration for these library functions, these functions are almost suitable for a general golang library using generics ?

fn/fn.go Outdated Show resolved Hide resolved
@@ -136,3 +138,48 @@ func TestZipWith(t *testing.T) {
z, []bool{false, true, false, false, false},
))
}

func TestPropForEachConcMapIsomorphism(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Seems like the TestProp prefix makes sense to be generalized in our docs, as soon as we do prop testing ? So we have a consistent way throughout the codebase ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah I agree. Our prop testing is pretty sparse at the moment but it's my preferred form of testing.

Copy link
Collaborator

Choose a reason for hiding this comment

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

ok sounds good, will also create property tests next time, they seem to include also the fuzzing component by creating a whole range of input values.

Maybe we can come up with a nice doc guide in the near future what we expect in general from unit tests in the LND codebase.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah what's also nice about them is that it forces you to think more clearly about what the precise requirements of the system are, as opposed to eyeballing a few test cases and hoping that those cases are enough to make reasonable implementations likely. It's a brittle assumption.

fn/slice_test.go Show resolved Hide resolved
foundIdx := FindIdx(pred, s)

// onlyVal :: Option[T2[A, B]] -> Option[B]
onlyVal := MapOption(func(t2 T2[int, uint8]) uint8 {
Copy link
Collaborator

Choose a reason for hiding this comment

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

wondering if it makes sense to generalize it ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Generalize what?

Copy link
Collaborator

Choose a reason for hiding this comment

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

mapping a tuple to an Option Tuple to a value: [T2[A, B]] -> Option[T2[A, B]] -> Option[B], could be part of the tuple definition ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I don't think it should be. However, I do think that maybe exporting functions for Fst and Snd is a good idea.

fn/either.go Show resolved Hide resolved
@ProofOfKeags
Copy link
Collaborator Author

I wonder where you get the inspiration for these library functions, these functions are almost suitable for a general golang library using generics ?

Years of writing Haskell as my native language. Yeah this would be better suited for a golang general lib but I have no desire to do ongoing maintenance of go libraries for the whole golang ecosystem. Further, @Roasbeef doesn't want to depend on external libraries for this kind of thing due to OSS maintainer risk (either malice or just disappearing), which is why we invented the fn package in the first place.

Generally speaking, the fn package is not Bitcoin/Lightning specific in any way. We only want to put stuff in here that is genuinely generic for all sorts or problem domains.

fn/either.go Show resolved Hide resolved

func TestPropConstructorEliminatorDuality(t *testing.T) {
f := func(i int, s string, isRight bool) bool {
Len := func(s string) int { return len(s) } // smh
Copy link
Collaborator

Choose a reason for hiding this comment

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

Q: what does the comment mean smh ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

"Shake my head", means disappointment. I was making some commentary about how I couldn't just put len in the field as the type func(string) int even though it would be a sensible thing to be able to do. append has similar issues. Perhaps I should either remove the snarky comment or be more explicit about warning people not to try and refactor it away.

fn/either_test.go Show resolved Hide resolved
@@ -136,3 +138,48 @@ func TestZipWith(t *testing.T) {
z, []bool{false, true, false, false, false},
))
}

func TestPropForEachConcMapIsomorphism(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

ok sounds good, will also create property tests next time, they seem to include also the fuzzing component by creating a whole range of input values.

Maybe we can come up with a nice doc guide in the near future what we expect in general from unit tests in the LND codebase.

foundIdx := FindIdx(pred, s)

// onlyVal :: Option[T2[A, B]] -> Option[B]
onlyVal := MapOption(func(t2 T2[int, uint8]) uint8 {
Copy link
Collaborator

Choose a reason for hiding this comment

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

mapping a tuple to an Option Tuple to a value: [T2[A, B]] -> Option[T2[A, B]] -> Option[B], could be part of the tuple definition ?

fn/either.go Show resolved Hide resolved
@ProofOfKeags ProofOfKeags requested a review from guggero June 5, 2024 23:30
@ProofOfKeags ProofOfKeags force-pushed the fn-prim branch 2 times, most recently from 0398ffe to f6f92d6 Compare June 10, 2024 19:23
@saubyk saubyk removed the request for review from guggero June 11, 2024 04:51
Copy link
Collaborator

@yyforyongyu yyforyongyu left a comment

Choose a reason for hiding this comment

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

Will review the following PRs to understand the usage.

fn/t2.go Outdated Show resolved Hide resolved
fn/t2.go Outdated Show resolved Hide resolved
}

// WhenLeft executes the given function if the Either is left.
func (e Either[L, R]) WhenLeft(f func(L)) {
e.left.WhenSome(f)
if !e.isRight {
Copy link
Collaborator

Choose a reason for hiding this comment

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

So there's no feedback when calling these WhenLeft or WhenRight? How do the callers know an effect has been applied to an Either obj or not?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Correct. This function should only be used if we want to conditionally run actions using the inner value on one side. If you need to somehow introspect this value to understand whether the closure was run or not, it's probably better to use ElimEither

fn/fn.go Outdated
}
}

// Iden is the lef and right identity of Comp. It is a function that simply
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
// Iden is the lef and right identity of Comp. It is a function that simply
// Iden is the left and right identity of Comp. It is a function that simply

Copy link
Collaborator

Choose a reason for hiding this comment

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

And would be nice to just name it Identity.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

We can do so but I'd like to offer a couple of reasons I chose Iden instead.

  1. We have an 80 column limit. This space is quite scarce and Iden takes 5% of it whereas Identity would take 10%.
  2. Simplicity opts for the names iden and comp instead of identity and compose. Given that it is a well-known Bitcoin project I figured it would provide good intuition

// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
Copy link
Collaborator

Choose a reason for hiding this comment

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

Q: what is this license stuff, or why here but not in other places?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I source ripped the golang std List and the BSD License they include stipulates that we have to reproduce the license.


// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List[A any] struct {
Copy link
Collaborator

Choose a reason for hiding this comment

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

hmm there's already lru.List and lru.Cache tho, and we would prefer lru.Cache as it's memory safe.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I couldn't find "List". I did find lru.Cache[K, V any], but I fail to understand precisely how that substitutes here.

Copy link
Member

Choose a reason for hiding this comment

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

Yeah I ripped this in the LRU package for neutrino: https://github.com/lightninglabs/neutrino/blob/master/cache/lru/list.go

i, a := i, a
wait.Add(1)
go func() {
bs[i] = f(a)
Copy link
Collaborator

Choose a reason for hiding this comment

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

will this create race?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I don't understand how it would given that each thread's landing zone is preallocated and distinct.

bs := make([]B, len(as))

for i, a := range as {
i, a := i, a
Copy link
Collaborator

Choose a reason for hiding this comment

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

not sure I understand this swap

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

What swap? I think this is just the required loopvar aliasing because go is strange in this way.

Copy link
Member

Choose a reason for hiding this comment

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

We can drop this safely now (latest Go version).

@lightninglabs-deploy
Copy link

@yyforyongyu: review reminder
@ProofOfKeags, remember to re-request review from reviewers when ready

// argument. This can be a useful utility when taking functions defined in a
// typical go style and adapting them to work with higher-order functions that
// expect functions of a single argument.
func Curry[A, B, C any](f func(A, B) C) func(A) func(B) C {
Copy link
Member

Choose a reason for hiding this comment

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

Could be cut perhaps? Main thing that jumps to mind is syntax bloat, same with Uncurry.

bs := make([]B, len(as))

for i, a := range as {
i, a := i, a
Copy link
Member

Choose a reason for hiding this comment

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

We can drop this safely now (latest Go version).

// goroutine for each element in the slice and then awaits all results before
// returning them.
func ForEachConc[A, B any](f func(A) B, as []A) []B {
wait := sync.WaitGroup{}
Copy link
Member

Choose a reason for hiding this comment

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

Style nit, can just be:

var wait sync.WaitGroup 

// ForEachConc maps the argument function over the slice, spawning a new
// goroutine for each element in the slice and then awaits all results before
// returning them.
func ForEachConc[A, B any](f func(A) B, as []A) []B {
Copy link
Member

Choose a reason for hiding this comment

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

Perhaps we can lift this version? It uses an errgroup to make it easier to manage error result values: https://github.com/lightninglabs/taproot-assets/blob/main/fn/concurrency.go#L10-L34

@@ -99,6 +99,18 @@ func Find[A any](pred func(A) bool, s []A) Option[A] {
return None[A]()
}

// FindIdx returns the first value that passes the supplied predicate along with
// its index in the slice. If no satisfactory value is found, None is returned.
func FindIdx[A any](pred func(A) bool, s []A) Option[T2[int, A]] {
Copy link
Member

Choose a reason for hiding this comment

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

Stdlib has this now: https://pkg.go.dev/slices#Index

Could call it, then map the -1 to an option.


// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List[A any] struct {
Copy link
Member

Choose a reason for hiding this comment

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

Yeah I ripped this in the LRU package for neutrino: https://github.com/lightninglabs/neutrino/blob/master/cache/lru/list.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

None yet

6 participants