Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions chasm/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,10 @@ type EngineUpdateWithStartExecutionResult = UpdateWithStartExecutionResult[struc
// function as output rather than as an error.
// - Reads and PollComponent waiters see the transition while the execution is cached, so a
// waiter can see state that is later lost.
// - Immediate pure tasks run. Other tasks added by the transition are created when it is persisted.
// - Immediate pure tasks run during the transition. Scheduled pure tasks can run from memory
// when the archetype sets [SpeculativeOptions.EnableTasks].
// - Ref returns ErrSpeculativeComponentRef for a component the transition created until it is persisted.
// - Replication ignores states
//
// TODO: Add option to support all task.
// - Replication sees the transition once it is persisted.
func WithSpeculative() TransitionOption {
return func(opts *TransitionOptions) {
opts.Speculative = true
Expand Down
4 changes: 4 additions & 0 deletions chasm/registrable_component.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ type (
// SpeculativeOptions configures how executions of an archetype handle [WithSpeculative]
// transitions.
SpeculativeOptions struct {
// EnableTasks runs scheduled pure tasks from memory while the execution stays cached.
// TODO: Support side-effect tasks.
EnableTasks bool

// AutoPersist persists a pending speculative transition after a while. It is read when a
// speculative transition starts a new unpersisted window.
AutoPersist AutoPersistOptions
Expand Down
28 changes: 28 additions & 0 deletions chasm/registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,34 @@ func (s *RegistryTestSuite) TestRegistry_RegisterComponents_WithDetached() {
s.Require().False(normalRC.IsDetached())
}

func (s *RegistryTestSuite) TestRegistry_RegisterComponents_WithSpeculativeOptions() {
r := chasm.NewRegistry(s.logger)
ctrl := gomock.NewController(s.T())
lib := chasm.NewMockLibrary(ctrl)
lib.EXPECT().Name().Return("TestLibrary").AnyTimes()
lib.EXPECT().Components().Return([]*chasm.RegistrableComponent{
chasm.NewRegistrableComponent[*chasm.MockComponent](
"SpeculativeComponent",
chasm.WithSpeculativeOptions(func(*namespace.Namespace) chasm.SpeculativeOptions {
return chasm.SpeculativeOptions{EnableTasks: true}
}),
),
})
lib.EXPECT().Tasks().Return(nil)
lib.EXPECT().NexusServices().Return(nil)
lib.EXPECT().NexusServiceProcessors().Return(nil)

err := r.Register(lib)
s.Require().NoError(err)

speculativeRC, ok := r.Component("TestLibrary.SpeculativeComponent")
s.Require().True(ok)
s.Require().True(speculativeRC.SpeculativeOptions(nil).EnableTasks)

normalRC := chasm.NewRegistrableComponent[*chasm.MockComponent]("NormalComponent")
s.Require().False(normalRC.SpeculativeOptions(nil).EnableTasks)
}

func (s *RegistryTestSuite) TestRegistry_RegisterComponents_WithRetention() {
r := chasm.NewRegistry(s.logger)
ctrl := gomock.NewController(s.T())
Expand Down
217 changes: 205 additions & 12 deletions chasm/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,20 @@ type (
MemoryWakeupResult struct {
// PersistNow requires the caller to persist the pending speculative transition.
PersistNow bool
// NotifyPollers reports that pure tasks changed state that stays in memory.
NotifyPollers bool
}

taskWithAttributes struct {
task any
attributes TaskAttributes
}

speculativePureTask struct {
node *Node
taskWithAttributes
}

// NodesMutation is a set of mutations for all nodes rooted at a given node n,
// including the node n itself.
NodesMutation struct {
Expand Down Expand Up @@ -1989,6 +1996,16 @@ func (n *Node) CloseTransaction(ctx context.Context, isActive bool) (NodesMutati

// ApplySpeculativeTransition runs the in-memory part of CloseTransaction for a transition.
func (n *Node) ApplySpeculativeTransition(_ context.Context) error {
if err := n.applySpeculativeTransition(); err != nil {
return err
}
if n.autoPersistDue(n.backend.Now()) {
return nil
}
return n.ScheduleMemoryWakeup()
}

func (n *Node) applySpeculativeTransition() error {
if err := n.executeImmediatePureTasks(); err != nil {
return err
}
Expand All @@ -2004,17 +2021,88 @@ func (n *Node) ApplySpeculativeTransition(_ context.Context) error {
}
}

if len(n.newTasks) != 0 && n.speculativePureTasksEnabled() {
if err := n.pruneSpeculativePureTasks(); err != nil {
return err
}
}

if !n.speculativeTransitionPending {
if autoPersist, ok := n.autoPersistOptions(); ok {
n.autoPersistDeadline = n.backend.Now().Add(autoPersist.MaxUnpersistedDuration)
}
}
n.speculativeTransitionPending = true
n.speculativeTransitionFailoverVersion = n.backend.GetCurrentVersion()
if n.autoPersistDue(n.backend.Now()) {
return nil
return nil
}

// pruneSpeculativePureTasks drops invalid or superseded scheduled pure tasks.
func (n *Node) pruneSpeculativePureTasks() error {
validateContext := NewContext(NewContextWithOperationIntent(context.Background(), OperationIntentProgress), n)
for component, componentTasks := range n.newTasks {
node, ok := n.findAttachedNode(component)
if !ok {
delete(n.newTasks, component)
continue
}

kept, err := node.filterSpeculativePureTasks(validateContext, componentTasks)
if err != nil {
return err
}
if len(kept) == 0 {
delete(n.newTasks, component)
} else {
n.newTasks[component] = kept
}
}
return n.ScheduleMemoryWakeup()
return nil
}

func (n *Node) filterSpeculativePureTasks(validateContext Context, componentTasks []taskWithAttributes) ([]taskWithAttributes, error) {
kept := componentTasks[:0]
singletons := make(map[uint32]int)
for _, task := range componentTasks {
registeredTask, ok := n.registry.taskFor(task.task)
if !ok || !registeredTask.isPureTask {
kept = append(kept, task)
continue
}

valid, err := n.validateTask(validateContext, TaskInvocation{TaskAttributes: task.attributes}, task.task)
if err != nil {
return nil, err
}
if !valid {
continue
}
if registeredTask.singletonMode != 0 {
if index, exists := singletons[registeredTask.taskTypeID]; exists {
if registeredTask.singletonMode == SingletonTaskModeReplace {
kept[index] = task
}
continue
}
singletons[registeredTask.taskTypeID] = len(kept)
}
kept = append(kept, task)
}
clear(componentTasks[len(kept):])
return kept, nil
}

// findAttachedNode looks up a component that is still in the tree.
// Replacing a component in place leaves the old value in valueToNode.
func (n *Node) findAttachedNode(component any) (*Node, bool) {
node, ok := n.valueToNode[component]
if !ok {
return nil, false
}
if found, ok := n.findNode(node.path()); !ok || found != node {
return nil, false
}
return node, true
}

// autoPersistOptions returns the [SpeculativeOptions.AutoPersist] of the execution's archetype for its
Expand Down Expand Up @@ -2045,6 +2133,61 @@ func (n *Node) SpeculativeTransitionFailoverVersion() (int64, bool) {
return n.speculativeTransitionFailoverVersion, n.speculativeTransitionPending
}

// takeDueSpeculativePureTasks removes scheduled pure tasks that are ready to run.
func (n *Node) takeDueSpeculativePureTasks(now time.Time) ([]speculativePureTask, error) {
if len(n.newTasks) == 0 || !n.speculativePureTasksEnabled() {
return nil, nil
}
if err := n.syncSubComponents(); err != nil {
return nil, err
}
var due []speculativePureTask
for component, componentTasks := range n.newTasks {
node, ok := n.findAttachedNode(component)
if !ok {
delete(n.newTasks, component)
continue
}
remaining := slices.DeleteFunc(componentTasks, func(task taskWithAttributes) bool {
if task.attributes.ScheduledTime.After(now) || !n.isPureTask(task) {
return false
}
due = append(due, speculativePureTask{node: node, taskWithAttributes: task})
return true
})
if len(remaining) == 0 {
delete(n.newTasks, component)
} else {
n.newTasks[component] = remaining
}
}
slices.SortStableFunc(due, func(a, b speculativePureTask) int {
return a.attributes.ScheduledTime.Compare(b.attributes.ScheduledTime)
})
return due, nil
}

// nextSpeculativePureTaskTime returns the earliest time a scheduled pure task is due.
func (n *Node) nextSpeculativePureTaskTime() (time.Time, bool) {
var next time.Time
if len(n.newTasks) == 0 || !n.speculativePureTasksEnabled() {
return next, false
}
for _, componentTasks := range n.newTasks {
for _, task := range componentTasks {
if n.isPureTask(task) && (next.IsZero() || task.attributes.ScheduledTime.Before(next)) {
next = task.attributes.ScheduledTime
}
}
}
return next, !next.IsZero()
}

func (n *Node) isPureTask(task taskWithAttributes) bool {
registeredTask, ok := n.registry.taskFor(task.task)
return ok && registeredTask.isPureTask
}

// ScheduleMemoryWakeup asks the backend for an in-memory timer at the execution's next in-memory work.
func (n *Node) ScheduleMemoryWakeup() error {
fireTime, ok := n.nextMemoryWakeupTime()
Expand All @@ -2054,19 +2197,69 @@ func (n *Node) ScheduleMemoryWakeup() error {
return n.backend.ScheduleChasmMemoryTimer(fireTime)
}

// RunMemoryWakeup runs the in-memory work due by now. The caller does what the result asks. When it
// doesn't persist, the caller then calls [Node.ScheduleMemoryWakeup].
func (n *Node) RunMemoryWakeup(_ context.Context, now time.Time) (MemoryWakeupResult, error) {
return MemoryWakeupResult{PersistNow: n.autoPersistDue(now)}, nil
// RunMemoryWakeup runs due scheduled pure tasks and returns the persistence decision.
func (n *Node) RunMemoryWakeup(ctx context.Context, now time.Time) (MemoryWakeupResult, error) {
if n.autoPersistDue(now) {
return MemoryWakeupResult{PersistNow: true}, nil
}

due, err := n.takeDueSpeculativePureTasks(now)
if err != nil {
return MemoryWakeupResult{}, err
}

var result MemoryWakeupResult
pureTasksRan := false
// Sync the tree again after a task changes it.
needsSync := false
for _, task := range due {
// An earlier pure task may have removed this task's component.
if needsSync {
if err := n.syncSubComponents(); err != nil {
return MemoryWakeupResult{}, err
}
}
// Skip tasks whose component was removed or replaced.
if node, ok := n.findAttachedNode(task.node.value); !ok || node != task.node {
continue
}
executed, err := task.node.ExecutePureTask(ctx, task.attributes, task.task)
if err != nil {
return MemoryWakeupResult{}, err
}
needsSync = executed
pureTasksRan = pureTasksRan || executed
}

if pureTasksRan {
if err := n.applySpeculativeTransition(); err != nil {
return MemoryWakeupResult{}, err
}
decision, err := n.SpeculativeTransitionDecision(ctx)
if err != nil {
return MemoryWakeupResult{}, err
}
result.PersistNow = decision.PersistNow
result.NotifyPollers = decision.NotifyPollers
}
return result, nil
}

// nextMemoryWakeupTime returns when the execution next has in-memory work. The bool is false when
// it has none.
// nextMemoryWakeupTime returns the earliest time of pending in-memory work.
func (n *Node) nextMemoryWakeupTime() (time.Time, bool) {
if !n.speculativeTransitionPending || n.autoPersistDeadline.IsZero() {
return time.Time{}, false
next, hasTask := n.nextSpeculativePureTaskTime()
if n.speculativeTransitionPending && !n.autoPersistDeadline.IsZero() {
autoPersistAt := n.autoPersistDeadline.Add(autoPersistWakeupBuffer)
if !hasTask || autoPersistAt.Before(next) {
return autoPersistAt, true
}
}
return n.autoPersistDeadline.Add(autoPersistWakeupBuffer), true
return next, hasTask
}

func (n *Node) speculativePureTasksEnabled() bool {
rc, ok := n.registry.ComponentByID(n.ArchetypeID())
return ok && rc.speculativeOptions != nil && rc.SpeculativeOptions(n.backend.GetNamespaceEntry()).EnableTasks
}

// TransitionDecision describes the engine's actions for a transition.
Expand Down
Loading
Loading