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

Better head object coupling for chain service #4869

Merged
merged 16 commits into from Feb 15, 2020
Merged

Conversation

terencechain
Copy link
Member

@terencechain terencechain commented Feb 14, 2020

Problem statement: There's too many variables that defines head for chain service.
Example in initial chain info:

s.headState, _ = s.beaconDB.State(ctx, bytesutil.ToBytes32(finalized.Root))
s.headBlock, _ = s.beaconDB.Block(ctx, bytesutil.ToBytes32(finalized.Root))
if s.headBlock != nil && s.headBlock.Block != nil {
	s.headSlot = s.headBlock.Block.Slot
}
s.canonicalRoots[s.headSlot] = finalized.Root

A problem could be, if headSlot changes itself, then it changes head root while head state and head block remain its own version 😢

To make it better, we define a head object:

// This defines the current chain service's view of head.
type head struct {
	slot  uint64 // current head slot.
	root  [32]byte // current head root.
	block *ethpb.SignedBeaconBlock // current head block.
	state *state.BeaconState // current head state.
}

To update the head object:

// This sets head view object which is used to track the head slot, root, block and state.
func (s *Service) setHead(slot uint64, root [32]byte, block *ethpb.SignedBeaconBlock, state *state.BeaconState) {
	s.headLock.Lock()
	defer s.headLock.Unlock()

	s.head = &head{
		slot:  slot,
		root:  root,
		block: block,
		state: state,
	}
}

To retrieve from the head object, it's copy by default:

// This returns the head block.
// It does a full copy on head block for immutability.
func (s *Service) headBlock() *ethpb.SignedBeaconBlock {
	s.headLock.RLock()
	defer s.headLock.RUnlock()

	return stateTrie.CopySignedBeaconBlock(s.head.block)
}

And now to initialize chain info:

s.setHead(finalizedState.Slot(), bytesutil.ToBytes32(finalized.Root), finalizedBlock, finalizedState)

This PR also cleaned up general head code by moving function to its proper location. Will list out those changes via inline comments

@terencechain terencechain self-assigned this Feb 14, 2020
@terencechain terencechain added the Enhancement New feature or request label Feb 14, 2020
// This gets called to update canonical root mapping. It does not save head block
// root in DB. With the inception of inital-sync-cache-state flag, it uses finalized
// check point as anchors to resume sync therefore head is no longer needed to be saved on per slot basis.
func (s *Service) saveHeadNoDB(ctx context.Context, b *ethpb.SignedBeaconBlock, r [32]byte) error {
Copy link
Member Author

Choose a reason for hiding this comment

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

this is an old function, I moved it from service.go to here, it makes more sense here

}

// This sets head view object which is used to track the head slot, root, block and state.
func (s *Service) setHead(slot uint64, root [32]byte, block *ethpb.SignedBeaconBlock, state *state.BeaconState) {
Copy link
Member Author

Choose a reason for hiding this comment

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

start review here lines 145 to 205

const latestSlotCount = 10

// HeadsHandler is a handler to serve /heads page in metrics.
func (s *Service) HeadsHandler(w http.ResponseWriter, _ *http.Request) {
Copy link
Member Author

Choose a reason for hiding this comment

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

This was not used at all. Removing it because it was too much work to maintain

s.headLock.RLock()
defer s.headLock.RUnlock()

return !(s.head == nil) && !(s.head.state == nil)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
return !(s.head == nil) && !(s.head.state == nil)
return s.head != nil && s.head.state != nil

Copy link
Member Author

Choose a reason for hiding this comment

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

Nice :)

@codecov
Copy link

codecov bot commented Feb 14, 2020

Codecov Report

❗ No coverage uploaded for pull request base (master@a26da31). Click here to learn what that means.
The diff coverage is 0%.

@@            Coverage Diff            @@
##             master    #4869   +/-   ##
=========================================
  Coverage          ?   44.34%           
=========================================
  Files             ?      203           
  Lines             ?    15205           
  Branches          ?        0           
=========================================
  Hits              ?     6742           
  Misses            ?     7382           
  Partials          ?     1081

}

// This sets head view object which is used to track the head slot, root, block and state.
func (s *Service) setHead(slot uint64, root [32]byte, block *ethpb.SignedBeaconBlock, state *state.BeaconState) {
Copy link
Member

Choose a reason for hiding this comment

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

we dont need a slot param, cant we just get it from the block ?

slot: slot,
root: root,
block: block,
state: state,
Copy link
Member

Choose a reason for hiding this comment

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

please copy the state

Copy link
Member Author

Choose a reason for hiding this comment

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

I also copied the block as well

root := make([]byte, 32)
copy(root, s.head.root[:])

return bytesutil.ToBytes32(root)
Copy link
Member

Choose a reason for hiding this comment

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

roots are 32 byte arrays, so they are passed by value. You can just do

return s.head.root

@terencechain terencechain added the Ready For Review A pull request ready for code review label Feb 15, 2020
@@ -29,8 +29,7 @@ var validatorBalancesGaugeVec = promauto.NewGaugeVec(
// and penalties over time, percentage gain/loss, and gives the end user a better idea
// of how the validator performs with respect to the rest.
func (v *validator) LogValidatorGainsAndLosses(ctx context.Context, slot uint64) error {

if slot%params.BeaconConfig().SlotsPerEpoch != 0 || slot < params.BeaconConfig().SlotsPerEpoch {
if slot%params.BeaconConfig().SlotsPerEpoch != 0 || slot <= params.BeaconConfig().SlotsPerEpoch {
Copy link
Member Author

Choose a reason for hiding this comment

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

This was a bug, caught it via new test here

return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}
cpt := s.headState.FinalizedCheckpoint()

cpt := state.CopyCheckpoint(s.finalizedCheckpt)
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you move this beneath the equality check and just compare s.finalizedCheckpt.Root in bytes.Equal? Might save some copies

Copy link
Member Author

Choose a reason for hiding this comment

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

Good suggestion. Done

return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}

cpt := s.headState.CurrentJustifiedCheckpoint()
cpt := state.CopyCheckpoint(s.justifiedCheckpt)
Copy link
Contributor

Choose a reason for hiding this comment

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

Same here

return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}

cpt := s.headState.PreviousJustifiedCheckpoint()
cpt := state.CopyCheckpoint(s.prevJustifiedCheckpt)
Copy link
Contributor

Choose a reason for hiding this comment

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

Same here

}

return s.headState.Copy(), nil
headState, err := s.beaconDB.HeadState(ctx)
Copy link
Contributor

Choose a reason for hiding this comment

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

Update cache if we have a cache miss?

Copy link
Member Author

Choose a reason for hiding this comment

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

Not here. That's what the PR aim to avoid. Update individual head field. If there's a miss setHead will be used during init

@prylabs-bulldozer prylabs-bulldozer bot merged commit 456ac5f into master Feb 15, 2020
@delete-merged-branch delete-merged-branch bot deleted the better-head-obj branch February 15, 2020 18:57
cryptomental pushed a commit to cryptomental/prysm that referenced this pull request Feb 24, 2020
* Done
* Fixed lock
* Fixed all the tests
* Comments
* Fixed more tests
* Merge branch 'master' into better-head-obj
* Fixed more tests
* Merge branch 'better-head-obj' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
* Prestons feedback & fixed test
* Nishant's feedback
* Participation edge case
* Gaz
* Merge branch 'master' into better-head-obj
* Merge branch 'master' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
* Raul's feedback
* Merge branch 'better-head-obj' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
cryptomental pushed a commit to cryptomental/prysm that referenced this pull request Feb 28, 2020
* Done
* Fixed lock
* Fixed all the tests
* Comments
* Fixed more tests
* Merge branch 'master' into better-head-obj
* Fixed more tests
* Merge branch 'better-head-obj' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
* Prestons feedback & fixed test
* Nishant's feedback
* Participation edge case
* Gaz
* Merge branch 'master' into better-head-obj
* Merge branch 'master' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
* Raul's feedback
* Merge branch 'better-head-obj' of git+ssh://github.com/prysmaticlabs/prysm into better-head-obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement New feature or request Ready For Review A pull request ready for code review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants